Subham9126 commited on
Commit
035dbf9
Β·
verified Β·
1 Parent(s): 9ca18cc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +76 -51
app.py CHANGED
@@ -1,49 +1,67 @@
1
  import gradio as gr
2
  from datetime import datetime
3
- from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
4
  import pycountry
5
  import pytz
 
 
6
 
7
- def get_country_datetime(country_name: str) -> dict:
 
 
 
 
8
  """
9
- Get the current date and time for all timezones of a given country.
10
-
11
- Args:
12
- country_name (str): The full or partial name of the country.
13
- Examples: "India", "United States", "Brazil"
14
 
15
- Returns:
16
- dict: {
17
- "country": "India",
18
- "alpha_2": "IN",
19
- "datetime_info": [
20
- {
21
- "timezone": "Asia/Kolkata",
22
- "datetime": "2025-10-05 18:42:31",
23
- "utc_offset": "+0530",
24
- "timezone_abbr": "IST"
25
- }
26
- ]
27
- }
28
  """
29
 
30
- # Step 1: Find the country
31
- try:
32
- country = pycountry.countries.get(name=country_name)
33
- if not country:
34
- country = pycountry.countries.search_fuzzy(country_name)[0]
35
- except (LookupError, IndexError, AttributeError):
36
- raise ValueError(f"Country '{country_name}' not found in ISO registry.")
37
 
38
- # Step 2: Get timezones
39
  try:
 
 
 
 
40
  timezones = pytz.country_timezones.get(country.alpha_2, [])
41
  if not timezones:
42
- raise ValueError(f"No timezones found for country '{country.name}'.")
43
- except Exception as e:
44
- raise ValueError(f"Error retrieving timezones for '{country.name}': {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
 
46
- # Step 3: Generate datetime info
47
  datetime_info = []
48
  utc_now = datetime.now(ZoneInfo("UTC"))
49
  for tz_name in timezones:
@@ -56,13 +74,11 @@ def get_country_datetime(country_name: str) -> dict:
56
  "utc_offset": local_time.strftime("%z"),
57
  "timezone_abbr": local_time.strftime("%Z")
58
  })
59
- except ZoneInfoNotFoundError:
60
  continue
61
 
62
- if not datetime_info:
63
- raise ValueError(f"Could not retrieve datetime for any timezone in '{country.name}'.")
64
-
65
  return {
 
66
  "country": country.name,
67
  "alpha_2": country.alpha_2,
68
  "datetime_info": datetime_info
@@ -70,19 +86,28 @@ def get_country_datetime(country_name: str) -> dict:
70
 
71
  # -------------------- GRADIO INTERFACE --------------------
72
 
73
- def format_result(country_name):
74
  try:
75
- result = get_country_datetime(country_name)
76
- lines = [
77
- f"🌍 **Country:** {result['country']} ({result['alpha_2']})",
78
- "\n**Timezones:**"
79
- ]
80
- for info in result["datetime_info"]:
81
- lines.append(
82
- f"- {info['timezone']} β†’ {info['datetime']} "
83
- f"(UTC{info['utc_offset']}, {info['timezone_abbr']})"
84
- )
 
 
 
 
 
 
 
 
85
  return "\n".join(lines)
 
86
  except ValueError as e:
87
  return f"❌ {str(e)}"
88
  except Exception as e:
@@ -90,11 +115,11 @@ def format_result(country_name):
90
 
91
  app = gr.Interface(
92
  fn=format_result,
93
- inputs=gr.Textbox(label="Enter Country Name", placeholder="e.g. India, United States, Brazil"),
94
  outputs=gr.Markdown(label="Current Date & Time Information"),
95
- title="🌎 Country DateTime Lookup",
96
- description="Enter a country name to get the current date and time across all its timezones.",
97
- examples=[["India"], ["United States"], ["Australia"], ["Brazil"], ["Russia"]]
98
  )
99
 
100
  if __name__ == "__main__":
 
1
  import gradio as gr
2
  from datetime import datetime
3
+ from zoneinfo import ZoneInfo
4
  import pycountry
5
  import pytz
6
+ from timezonefinder import TimezoneFinder
7
+ from geopy.geocoders import Nominatim
8
 
9
+ # Initialize helpers
10
+ geolocator = Nominatim(user_agent="country_datetime_app")
11
+ tf = TimezoneFinder()
12
+
13
+ def get_country_datetime(location_name: str) -> dict:
14
  """
15
+ Get the current date and time for a given country or city.
 
 
 
 
16
 
17
+ - If a country name is provided: returns all its timezones.
18
+ - If a city name is provided: returns the detected country + its local time.
 
 
 
 
 
 
 
 
 
 
 
19
  """
20
 
21
+ location_name = location_name.strip()
22
+ if not location_name:
23
+ raise ValueError("Please enter a valid country or city name.")
 
 
 
 
24
 
25
+ # Try to find as a country first
26
  try:
27
+ country = pycountry.countries.get(name=location_name)
28
+ if not country:
29
+ country = pycountry.countries.search_fuzzy(location_name)[0]
30
+ # Got a valid country β€” fetch all its timezones
31
  timezones = pytz.country_timezones.get(country.alpha_2, [])
32
  if not timezones:
33
+ raise ValueError(f"No timezones found for {country.name}")
34
+ result_type = "country"
35
+ except Exception:
36
+ # Not a country β†’ try to geolocate as a city
37
+ location = geolocator.geocode(location_name)
38
+ if not location:
39
+ raise ValueError(f"Location '{location_name}' not found.")
40
+ tz_name = tf.timezone_at(lng=location.longitude, lat=location.latitude)
41
+ if not tz_name:
42
+ raise ValueError(f"Could not determine timezone for '{location_name}'.")
43
+ try:
44
+ timezone = ZoneInfo(tz_name)
45
+ local_time = datetime.now(timezone)
46
+ country_code = location.raw.get("address", {}).get("country_code", "").upper()
47
+ country = pycountry.countries.get(alpha_2=country_code) if country_code else None
48
+ country_name = country.name if country else "Unknown"
49
+ return {
50
+ "query_type": "city",
51
+ "city": location_name,
52
+ "country": country_name,
53
+ "alpha_2": country_code,
54
+ "datetime_info": [{
55
+ "timezone": tz_name,
56
+ "datetime": local_time.strftime("%Y-%m-%d %H:%M:%S"),
57
+ "utc_offset": local_time.strftime("%z"),
58
+ "timezone_abbr": local_time.strftime("%Z")
59
+ }]
60
+ }
61
+ except Exception:
62
+ raise ValueError(f"Error retrieving datetime for '{location_name}'.")
63
 
64
+ # If it was a valid country
65
  datetime_info = []
66
  utc_now = datetime.now(ZoneInfo("UTC"))
67
  for tz_name in timezones:
 
74
  "utc_offset": local_time.strftime("%z"),
75
  "timezone_abbr": local_time.strftime("%Z")
76
  })
77
+ except Exception:
78
  continue
79
 
 
 
 
80
  return {
81
+ "query_type": "country",
82
  "country": country.name,
83
  "alpha_2": country.alpha_2,
84
  "datetime_info": datetime_info
 
86
 
87
  # -------------------- GRADIO INTERFACE --------------------
88
 
89
+ def format_result(location):
90
  try:
91
+ result = get_country_datetime(location)
92
+ lines = []
93
+
94
+ if result["query_type"] == "city":
95
+ info = result["datetime_info"][0]
96
+ lines.append(f"πŸ™οΈ **City:** {result['city']}")
97
+ lines.append(f"🌍 **Country:** {result['country']} ({result['alpha_2']})")
98
+ lines.append(f"πŸ•’ **Local Time:** {info['datetime']} (UTC{info['utc_offset']}, {info['timezone_abbr']})")
99
+
100
+ else: # country mode
101
+ lines.append(f"🌍 **Country:** {result['country']} ({result['alpha_2']})")
102
+ lines.append("\n**Timezones:**")
103
+ for info in result["datetime_info"]:
104
+ lines.append(
105
+ f"- {info['timezone']} β†’ {info['datetime']} "
106
+ f"(UTC{info['utc_offset']}, {info['timezone_abbr']})"
107
+ )
108
+
109
  return "\n".join(lines)
110
+
111
  except ValueError as e:
112
  return f"❌ {str(e)}"
113
  except Exception as e:
 
115
 
116
  app = gr.Interface(
117
  fn=format_result,
118
+ inputs=gr.Textbox(label="Enter Country or City Name", placeholder="e.g. India, Kolkata, New York, Brazil"),
119
  outputs=gr.Markdown(label="Current Date & Time Information"),
120
+ title="🌎 Smart DateTime Lookup",
121
+ description="Enter any **country** or **city** name to get the current date and time automatically.",
122
+ examples=[["India"], ["Kolkata"], ["Jaipur"], ["New York"], ["Sydney"], ["Russia"]]
123
  )
124
 
125
  if __name__ == "__main__":