Chris4K commited on
Commit
7ee7854
·
verified ·
1 Parent(s): fdad14a

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +74 -0
app.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import requests
3
+
4
+ def get_time_and_weather(city: str, country: str) -> dict:
5
+ """
6
+ Returns the current time and weather for the specified city and country.
7
+
8
+ Args:
9
+ city (str): Name of the city (e.g., 'Berlin')
10
+ country (str): Name of the country (e.g., 'Germany')
11
+
12
+ Returns:
13
+ dict: A dictionary containing current time and weather conditions.
14
+ """
15
+ try:
16
+ # 1. Get lat/lon from Nominatim (OpenStreetMap)
17
+ geocode = requests.get("https://nominatim.openstreetmap.org/search", params={
18
+ "q": f"{city}, {country}",
19
+ "format": "json"
20
+ }).json()
21
+
22
+ if not geocode:
23
+ return {"error": f"Could not find location: {city}, {country}"}
24
+
25
+ lat = geocode[0]["lat"]
26
+ lon = geocode[0]["lon"]
27
+
28
+ # 2. Get weather from Open-Meteo
29
+ weather = requests.get("https://api.open-meteo.com/v1/forecast", params={
30
+ "latitude": lat,
31
+ "longitude": lon,
32
+ "current": "temperature_2m,weathercode",
33
+ }).json()
34
+
35
+ current_weather = weather.get("current", {})
36
+ temperature = current_weather.get("temperature_2m", "N/A")
37
+ weather_code = current_weather.get("weathercode", "N/A")
38
+
39
+ # 3. Get time from WorldTimeAPI
40
+ time_data = requests.get(f"http://worldtimeapi.org/api/timezone").json()
41
+ timezone_url = f"http://worldtimeapi.org/api/timezone"
42
+
43
+ # Best effort: Try to find closest matching timezone
44
+ tz_list = time_data if isinstance(time_data, list) else []
45
+ location_part = city.replace(" ", "_")
46
+ match = next((tz for tz in tz_list if location_part.lower() in tz.lower()), None)
47
+
48
+ if match:
49
+ time_result = requests.get(f"http://worldtimeapi.org/api/timezone/{match}").json()
50
+ datetime = time_result.get("datetime", "N/A")
51
+ else:
52
+ datetime = "Could not determine timezone"
53
+
54
+ return {
55
+ "location": f"{city}, {country}",
56
+ "local_time": datetime,
57
+ "temperature (°C)": temperature,
58
+ "weather_code": weather_code
59
+ }
60
+
61
+ except Exception as e:
62
+ return {"error": str(e)}
63
+
64
+ # Gradio interface
65
+ iface = gr.Interface(
66
+ fn=get_time_and_weather,
67
+ inputs=[gr.Textbox(label="City", value="Berlin"), gr.Textbox(label="Country", value="Germany")],
68
+ outputs=[gr.JSON()],
69
+ title="🌍 Weather & Time Oracle",
70
+ description="Enter a city and country to get the local time and current weather.",
71
+ )
72
+
73
+ if __name__ == "__main__":
74
+ iface.launch(mcp_server=True, share=True, debug=True)