nakas commited on
Commit
9c047e2
·
verified ·
1 Parent(s): 5efed82

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +155 -0
app.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import requests
3
+ import os
4
+
5
+ # Your Google Pollen API key should be set as a secret in your Hugging Face Space
6
+ # For local testing, you can uncomment the following line and add your key
7
+ # os.environ['GOOGLE_API_KEY'] = "YOUR_API_KEY_HERE"
8
+
9
+ API_KEY = os.environ.get("GOOGLE_API_KEY")
10
+
11
+ def get_pollen_data(latitude, longitude):
12
+ """
13
+ Fetches pollen data from the Google Pollen API for a given location.
14
+ """
15
+ if not API_KEY:
16
+ return "Error: GOOGLE_API_KEY not found. Please set it as a secret in your Hugging Face Space.", "", ""
17
+
18
+ if not latitude or not longitude:
19
+ return "Error: Please enter both latitude and longitude.", "", ""
20
+
21
+ try:
22
+ lat = float(latitude)
23
+ lon = float(longitude)
24
+ except ValueError:
25
+ return "Error: Invalid latitude or longitude. Please enter valid numbers.", "", ""
26
+
27
+ # The Google Pollen API endpoint for looking up pollen information
28
+ endpoint = "https://pollen.googleapis.com/v1/forecast:lookup"
29
+
30
+ params = {
31
+ "key": API_KEY,
32
+ "location.latitude": lat,
33
+ "location.longitude": lon,
34
+ "days": 5 # Get forecast for the next 5 days
35
+ }
36
+
37
+ try:
38
+ response = requests.get(endpoint, params=params)
39
+ response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx)
40
+ data = response.json()
41
+
42
+ if not data.get('dailyInfo'):
43
+ return "No pollen data found for this location.", "", ""
44
+
45
+ # Process and format the data for display
46
+ tree_pollen = ""
47
+ grass_pollen = ""
48
+ weed_pollen = ""
49
+
50
+ for day_info in data.get('dailyInfo', []):
51
+ date = day_info.get('date', {})
52
+ date_str = f"{date.get('year', 'N/A')}-{date.get('month', 'N/A'):02d}-{date.get('day', 'N/A'):02d}"
53
+
54
+ tree_pollen += f"\n**Date: {date_str}**\n"
55
+ grass_pollen += f"\n**Date: {date_str}**\n"
56
+ weed_pollen += f"\n**Date: {date_str}**\n"
57
+
58
+ pollen_types = day_info.get('pollenTypeInfo', [])
59
+
60
+ # Keep track if any data was found for each category for a given day
61
+ tree_found = False
62
+ grass_found = False
63
+ weed_found = False
64
+
65
+ for pollen in pollen_types:
66
+ display_name = pollen.get('displayName', 'N/A')
67
+ in_season = pollen.get('inSeason', False)
68
+
69
+ if not in_season:
70
+ continue
71
+
72
+ index_info = pollen.get('indexInfo', {})
73
+ index_value = index_info.get('value', 'N/A')
74
+ category = index_info.get('category', 'N/A')
75
+ health_recs = pollen.get('healthRecommendations', {})
76
+
77
+ formatted_pollen_info = f"- **{display_name}**: Index: {index_value} ({category})\n"
78
+
79
+ # Append health recommendations if available
80
+ if health_recs and health_recs.get('recommendations'):
81
+ for rec in health_recs.get('recommendations').values():
82
+ formatted_pollen_info += f" - {rec}\n"
83
+
84
+ plant_type = pollen.get('plantType', 'UNKNOWN')
85
+ if plant_type == 'TREE':
86
+ tree_pollen += formatted_pollen_info
87
+ tree_found = True
88
+ elif plant_type == 'GRASS':
89
+ grass_pollen += formatted_pollen_info
90
+ grass_found = True
91
+ elif plant_type == 'WEED':
92
+ weed_pollen += formatted_pollen_info
93
+ weed_found = True
94
+
95
+ if not tree_found:
96
+ tree_pollen += "- No significant tree pollen detected.\n"
97
+ if not grass_found:
98
+ grass_pollen += "- No significant grass pollen detected.\n"
99
+ if not weed_found:
100
+ weed_pollen += "- No significant weed pollen detected.\n"
101
+
102
+
103
+ return tree_pollen.strip(), grass_pollen.strip(), weed_pollen.strip()
104
+
105
+ except requests.exceptions.RequestException as e:
106
+ return f"Error connecting to the API: {e}", "", ""
107
+ except Exception as e:
108
+ return f"An unexpected error occurred: {e}", "", ""
109
+
110
+
111
+ # Define the Gradio Interface
112
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
113
+ gr.Markdown(
114
+ """
115
+ # 🤧 Google Pollen API Checker
116
+ Enter the latitude and longitude of a location to get the 5-day pollen forecast.
117
+ You can find the coordinates for a location using Google Maps.
118
+ """
119
+ )
120
+
121
+ with gr.Row():
122
+ lat_input = gr.Textbox(label="Latitude", placeholder="e.g., 34.0522")
123
+ lon_input = gr.Textbox(label="Longitude", placeholder="e.g., -118.2437")
124
+
125
+ submit_button = gr.Button("Get Pollen Data", variant="primary")
126
+
127
+ gr.Markdown("---")
128
+ gr.Markdown("## 🌳 Tree Pollen")
129
+ tree_output = gr.Markdown()
130
+
131
+ gr.Markdown("## 🌱 Grass Pollen")
132
+ grass_output = gr.Markdown()
133
+
134
+ gr.Markdown("## 🌿 Weed Pollen")
135
+ weed_output = gr.Markdown()
136
+
137
+ # Define the action for the submit button
138
+ submit_button.click(
139
+ fn=get_pollen_data,
140
+ inputs=[lat_input, lon_input],
141
+ outputs=[tree_output, grass_output, weed_output]
142
+ )
143
+
144
+ gr.Examples(
145
+ examples=[
146
+ ["40.7128", "-74.0060"], # New York, NY
147
+ ["34.0522", "-118.2437"], # Los Angeles, CA
148
+ ["51.5074", "-0.1278"], # London, UK
149
+ ],
150
+ inputs=[lat_input, lon_input],
151
+ )
152
+
153
+
154
+ if __name__ == "__main__":
155
+ demo.launch()