Spaces:
Sleeping
Sleeping
| from fastapi import FastAPI, Request | |
| from fastapi.responses import JSONResponse | |
| from fastapi.middleware.cors import CORSMiddleware | |
| import json | |
| import requests | |
| app = FastAPI() | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| with open("weather_codes.json", "r") as f: | |
| weather_code_meanings = json.load(f) | |
| async def get_weather(request: Request): | |
| try: | |
| data = await request.json() | |
| city = data.get("city") | |
| if not city: | |
| return JSONResponse(content={"report": "❌ City not provided."}) | |
| geo_url = f"https://geocoding-api.open-meteo.com/v1/search?name={city}&count=1" | |
| geo_data = requests.get(geo_url).json() | |
| if not geo_data.get("results"): | |
| return JSONResponse(content={"report": "❌ City not found."}) | |
| loc = geo_data["results"][0] | |
| lat, lon = loc["latitude"], loc["longitude"] | |
| name = loc["name"] | |
| weather_url = f"https://api.open-meteo.com/v1/forecast?latitude={lat}&longitude={lon}¤t_weather=true" | |
| weather_data = requests.get(weather_url).json() | |
| current = weather_data["current_weather"] | |
| condition = weather_code_meanings.get(str(current["weathercode"]), "Unknown") | |
| report = f""" Weather Report for {name} | |
| Time: {current['time']} | |
| Condition: {condition} | |
| Day or Night: {"Daytime" if current["is_day"] else "Nighttime"} | |
| Temperature: {current['temperature']}°C | |
| Wind Speed: {current['windspeed']} km/h""" | |
| return JSONResponse(content={"report": report}) | |
| except Exception as e: | |
| return JSONResponse(content={"report": f"❌ Error: {str(e)}"}) | |