Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -39,15 +39,38 @@ def get_air_quality(city: str) -> str:
|
|
| 39 |
str: The AQI value along with air quality status.
|
| 40 |
"""
|
| 41 |
try:
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
|
| 46 |
-
#
|
| 47 |
-
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
|
| 50 |
-
return f"Raw search results logged for debugging."
|
| 51 |
except Exception as e:
|
| 52 |
return f"Error fetching AQI: {e}"
|
| 53 |
|
|
|
|
| 39 |
str: The AQI value along with air quality status.
|
| 40 |
"""
|
| 41 |
try:
|
| 42 |
+
# Step 1: Search for the city on AQI.in to find the correct country path
|
| 43 |
+
search_url = f"https://www.aqi.in/search?query={city.replace(' ', '+')}"
|
| 44 |
+
search_response = requests.get(search_url)
|
| 45 |
+
|
| 46 |
+
if search_response.status_code != 200:
|
| 47 |
+
return f"Failed to fetch AQI data for {city}. Status Code: {search_response.status_code}"
|
| 48 |
+
|
| 49 |
+
# Step 2: Extract the correct city URL from search results
|
| 50 |
+
import re
|
| 51 |
+
match = re.search(r'href="(/dashboard/[^"]+)"', search_response.text)
|
| 52 |
+
|
| 53 |
+
if not match:
|
| 54 |
+
return f"No AQI data found for {city}."
|
| 55 |
+
|
| 56 |
+
city_url_path = match.group(1)
|
| 57 |
+
city_url = f"https://www.aqi.in{city_url_path}"
|
| 58 |
|
| 59 |
+
# Step 3: Fetch AQI details from the city's AQI page
|
| 60 |
+
city_response = requests.get(city_url)
|
| 61 |
+
|
| 62 |
+
if city_response.status_code != 200:
|
| 63 |
+
return f"Failed to fetch AQI data for {city}. Status Code: {city_response.status_code}"
|
| 64 |
+
|
| 65 |
+
# Step 4: Extract AQI value using regex
|
| 66 |
+
match = re.search(r"AQI is (\d+)", city_response.text)
|
| 67 |
+
|
| 68 |
+
if match:
|
| 69 |
+
aqi_value = match.group(1)
|
| 70 |
+
return f"Air Quality in {city}: AQI {aqi_value} ({city_url})"
|
| 71 |
+
|
| 72 |
+
return f"No AQI data found for {city}."
|
| 73 |
|
|
|
|
| 74 |
except Exception as e:
|
| 75 |
return f"Error fetching AQI: {e}"
|
| 76 |
|