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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -34
app.py CHANGED
@@ -4,64 +4,82 @@ import requests
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")],
 
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
  try:
9
+
10
+ # 1. Get lat/lon from Open-Meteo's Geocoding API (no key required!)
11
+ geo_res = requests.get("https://geocoding-api.open-meteo.com/v1/search", params={
12
+ "name": city,
13
+ "count": 1,
14
+ "language": "en",
15
  "format": "json"
16
+ })
17
 
18
+ if geo_res.status_code != 200:
19
+ return {"error": f"Geolocation failed. Status: {geo_res.status_code}"}
20
 
21
+ geo_data = geo_res.json()
22
+ results = geo_data.get("results", [])
23
+
24
+ if not results:
25
+ return {"error": f"Could not find location: {city}, {country}"}
26
 
27
+ lat = results[0]["latitude"]
28
+ lon = results[0]["longitude"]
29
+ timezone = results[0]["timezone"]
30
+
31
+ print(f"Location: {city}, {country}")
32
+ print(f"Latitude: {lat}, Longitude: {lon}")
33
+ print(f"Timezone: {timezone}")
34
  # 2. Get weather from Open-Meteo
35
+ weather_url = "https://api.open-meteo.com/v1/forecast"
36
+ weather_res = requests.get(weather_url, params={
37
  "latitude": lat,
38
  "longitude": lon,
39
+ "current": "temperature_2m,weathercode"
40
+ })
41
 
42
+ if weather_res.status_code != 200:
43
+ return {"error": f"Weather API failed. Status: {weather_res.status_code}"}
44
+
45
+ weather_data = weather_res.json()
46
+ current_weather = weather_data.get("current", {})
47
  temperature = current_weather.get("temperature_2m", "N/A")
48
  weather_code = current_weather.get("weathercode", "N/A")
49
 
50
+ # 3. Get timezone from lat/lon using TimeZoneDB (no key alternative)
51
+ # timezone_res = requests.get("http://worldtimeapi.org/api/timezone")
52
+
53
+ #if timezone_res.status_code != 200:
54
+ # return {"error": f"Timezone list fetch failed. Status: {timezone_res.status_code}"}
55
+
56
+ #all_timezones = timezone_res.json()
57
+ #match = next((tz for tz in all_timezones if city.lower() in tz.lower()), None)
58
+
59
+ #if not match:
60
+ # match = next((tz for tz in all_timezones if country.lower() in tz.lower()), None)
61
+
62
+ #if not match:
63
+ # return {"error": f"No matching timezone found for {city}, {country}"}
64
 
65
+ #time_detail_res = requests.get(f"http://worldtimeapi.org/api/timezone/{match}")
66
+ #if time_detail_res.status_code != 200:
67
+ # return {"error": f"Time fetch failed for zone: {match}"}
 
68
 
69
+ #time_data = time_detail_res.json()
70
+ #datetime = time_data.get("datetime", "N/A")
 
 
 
71
 
72
  return {
73
  "location": f"{city}, {country}",
74
+ "timezone": "n/a",
75
+ "local_time": "n/a",
76
  "temperature (°C)": temperature,
77
  "weather_code": weather_code
78
  }
79
 
80
  except Exception as e:
81
+ return {"error": f"{type(e).__name__}: {str(e)}"}
82
 
 
83
  iface = gr.Interface(
84
  fn=get_time_and_weather,
85
  inputs=[gr.Textbox(label="City", value="Berlin"), gr.Textbox(label="Country", value="Germany")],