Spaces:
Sleeping
Sleeping
import gradio as gr | |
import requests | |
import os | |
# Your Google Pollen API key should be set as a secret in your Hugging Face Space | |
# For local testing, you can uncomment the following line and add your key | |
# os.environ['GOOGLE_API_KEY'] = "YOUR_API_KEY_HERE" | |
API_KEY = os.environ.get("GOOGLE_API_KEY") | |
def get_pollen_data(latitude, longitude): | |
""" | |
Fetches pollen data from the Google Pollen API for a given location. | |
""" | |
if not API_KEY: | |
return "Error: GOOGLE_API_KEY not found. Please set it as a secret in your Hugging Face Space.", "", "" | |
if not latitude or not longitude: | |
return "Error: Please enter both latitude and longitude.", "", "" | |
try: | |
lat = float(latitude) | |
lon = float(longitude) | |
except ValueError: | |
return "Error: Invalid latitude or longitude. Please enter valid numbers.", "", "" | |
# The Google Pollen API endpoint for looking up pollen information | |
endpoint = "https://pollen.googleapis.com/v1/forecast:lookup" | |
params = { | |
"key": API_KEY, | |
"location.latitude": lat, | |
"location.longitude": lon, | |
"days": 5 # Get forecast for the next 5 days | |
} | |
try: | |
response = requests.get(endpoint, params=params) | |
response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx) | |
data = response.json() | |
if not data.get('dailyInfo'): | |
return "No pollen data found for this location.", "", "" | |
# Process and format the data for display | |
tree_pollen = "" | |
grass_pollen = "" | |
weed_pollen = "" | |
for day_info in data.get('dailyInfo', []): | |
date = day_info.get('date', {}) | |
date_str = f"{date.get('year', 'N/A')}-{date.get('month', 'N/A'):02d}-{date.get('day', 'N/A'):02d}" | |
tree_pollen += f"\n**Date: {date_str}**\n" | |
grass_pollen += f"\n**Date: {date_str}**\n" | |
weed_pollen += f"\n**Date: {date_str}**\n" | |
pollen_types = day_info.get('pollenTypeInfo', []) | |
# Keep track if any data was found for each category for a given day | |
tree_found = False | |
grass_found = False | |
weed_found = False | |
for pollen in pollen_types: | |
display_name = pollen.get('displayName', 'N/A') | |
in_season = pollen.get('inSeason', False) | |
if not in_season: | |
continue | |
index_info = pollen.get('indexInfo', {}) | |
index_value = index_info.get('value', 'N/A') | |
category = index_info.get('category', 'N/A') | |
# *** FIX IS HERE *** | |
# The 'healthRecommendations' is a list of strings, not a dictionary. | |
health_recs = pollen.get('healthRecommendations', []) # Default to empty list | |
formatted_pollen_info = f"- **{display_name}**: Index: {index_value} ({category})\n" | |
# Append health recommendations if available by iterating over the list. | |
if health_recs: | |
for rec in health_recs: | |
formatted_pollen_info += f" - {rec}\n" | |
plant_type = pollen.get('plantType', 'UNKNOWN') | |
if plant_type == 'TREE': | |
tree_pollen += formatted_pollen_info | |
tree_found = True | |
elif plant_type == 'GRASS': | |
grass_pollen += formatted_pollen_info | |
grass_found = True | |
elif plant_type == 'WEED': | |
weed_pollen += formatted_pollen_info | |
weed_found = True | |
if not tree_found: | |
tree_pollen += "- No significant tree pollen detected.\n" | |
if not grass_found: | |
grass_pollen += "- No significant grass pollen detected.\n" | |
if not weed_found: | |
weed_pollen += "- No significant weed pollen detected.\n" | |
return tree_pollen.strip(), grass_pollen.strip(), weed_pollen.strip() | |
except requests.exceptions.RequestException as e: | |
return f"Error connecting to the API: {e}", "", "" | |
except Exception as e: | |
return f"An unexpected error occurred: {e}", "", "" | |
# Define the Gradio Interface | |
with gr.Blocks(theme=gr.themes.Soft()) as demo: | |
gr.Markdown( | |
""" | |
# 🤧 Google Pollen API Checker | |
Enter the latitude and longitude of a location to get the 5-day pollen forecast. | |
You can find the coordinates for a location using Google Maps. | |
""" | |
) | |
with gr.Row(): | |
lat_input = gr.Textbox(label="Latitude", placeholder="e.g., 34.0522") | |
lon_input = gr.Textbox(label="Longitude", placeholder="e.g., -118.2437") | |
submit_button = gr.Button("Get Pollen Data", variant="primary") | |
gr.Markdown("---") | |
gr.Markdown("## 🌳 Tree Pollen") | |
tree_output = gr.Markdown() | |
gr.Markdown("## 🌱 Grass Pollen") | |
grass_output = gr.Markdown() | |
gr.Markdown("## 🌿 Weed Pollen") | |
weed_output = gr.Markdown() | |
# Define the action for the submit button | |
submit_button.click( | |
fn=get_pollen_data, | |
inputs=[lat_input, lon_input], | |
outputs=[tree_output, grass_output, weed_output] | |
) | |
gr.Examples( | |
examples=[ | |
["40.7128", "-74.0060"], # New York, NY | |
["34.0522", "-118.2437"], # Los Angeles, CA | |
["51.5074", "-0.1278"], # London, UK | |
], | |
inputs=[lat_input, lon_input], | |
) | |
if __name__ == "__main__": | |
demo.launch() | |