nakas commited on
Commit
cd66fc5
·
verified ·
1 Parent(s): 4116f2c

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -0
app.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import requests
3
+ from PIL import Image
4
+ from io import BytesIO
5
+ import numpy as np
6
+ import torch
7
+ from skillful_nowcasting.dgmr import DGMR
8
+ from datetime import datetime, timezone
9
+
10
+ # Load the pretrained model
11
+ model = DGMR.from_pretrained("openclimatefix/dgmr")
12
+
13
+ def get_latest_radar_image():
14
+ """Fetches the latest radar image from the Iowa State University archive."""
15
+ now = datetime.now(timezone.utc)
16
+ url = f"https://mesonet.agron.iastate.edu/archive/data/{now.year}/{now.month:02d}/{now.day:02d}/GIS/uscomp/n0r_0.png"
17
+ response = requests.get(url)
18
+ img = Image.open(BytesIO(response.content)).convert("RGB")
19
+ return img
20
+
21
+ def preprocess_image(img):
22
+ """Preprocesses the image for the model."""
23
+ img = img.resize((128, 128))
24
+ img_array = np.array(img) / 255.0
25
+ img_tensor = torch.from_numpy(img_array).permute(2, 0, 1).float()
26
+ # Add batch and sequence dimensions
27
+ return img_tensor.unsqueeze(0).unsqueeze(0)
28
+
29
+ def postprocess_output(output_tensor):
30
+ """Postprocesses the model output back to an image."""
31
+ # Take the first prediction in the sequence
32
+ output_tensor = output_tensor[0, 0, :, :, :]
33
+ output_array = output_tensor.permute(1, 2, 0).detach().numpy()
34
+ output_array = (output_array * 255).astype(np.uint8)
35
+ return Image.fromarray(output_array)
36
+
37
+ def predict_nowcast():
38
+ """Fetches the latest radar, runs the nowcasting model, and returns the images."""
39
+ input_image = get_latest_radar_image()
40
+ preprocessed_input = preprocess_image(input_image)
41
+
42
+ # The DGMR model expects a sequence of 4 input images.
43
+ # For this example, we will feed the same image 4 times.
44
+ model_input = torch.cat([preprocessed_input] * 4, dim=1)
45
+
46
+ with torch.no_grad():
47
+ output = model(model_input)
48
+
49
+ predicted_image = postprocess_output(output)
50
+
51
+ return input_image, predicted_image
52
+
53
+ # Create the Gradio interface
54
+ with gr.Blocks() as demo:
55
+ gr.Markdown("## American Radar Nowcasting with AI")
56
+ gr.Markdown(
57
+ "Click the button to fetch the latest American radar image and generate a nowcast prediction using the `skillful_nowcasting` model."
58
+ )
59
+
60
+ with gr.Row():
61
+ input_image_display = gr.Image(label="Current Radar Image")
62
+ output_image_display = gr.Image(label="Predicted Nowcast")
63
+
64
+ predict_button = gr.Button("Generate Nowcast")
65
+ predict_button.click(
66
+ fn=predict_nowcast,
67
+ inputs=[],
68
+ outputs=[input_image_display, output_image_display]
69
+ )
70
+
71
+ demo.launch()