File size: 5,591 Bytes
9c047e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
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')
                health_recs = pollen.get('healthRecommendations', {})
                
                formatted_pollen_info = f"- **{display_name}**: Index: {index_value} ({category})\n"
                
                # Append health recommendations if available
                if health_recs and health_recs.get('recommendations'):
                     for rec in health_recs.get('recommendations').values():
                         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()