Spaces:
Sleeping
Sleeping
Update app.py
Browse filesAdded qualitative description to temperature.
app.py
CHANGED
@@ -26,8 +26,23 @@ def get_temperature(location: str, temp_scale: str = "celsius") -> tuple[float,
|
|
26 |
location: The name of the city/location
|
27 |
temp_scale: Temperature scale to use ('celsius' or 'fahrenheit')
|
28 |
Returns:
|
29 |
-
tuple: (temperature value as float, unit as string 'C' or 'F')
|
30 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
31 |
try:
|
32 |
API_KEY = os.environ.get('WEATHER_API_KEY')
|
33 |
if not API_KEY:
|
@@ -45,15 +60,18 @@ def get_temperature(location: str, temp_scale: str = "celsius") -> tuple[float,
|
|
45 |
data = response.json()
|
46 |
|
47 |
if response.status_code == 200:
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
)
|
|
|
|
|
|
|
53 |
else:
|
54 |
error_msg = data.get('message', 'Unknown error')
|
55 |
raise Exception(f"API Error: {error_msg} (Status code: {response.status_code})")
|
56 |
-
|
57 |
except requests.Timeout:
|
58 |
raise Exception(f"Request timed out while fetching temperature for {location}")
|
59 |
except requests.RequestException as e:
|
|
|
26 |
location: The name of the city/location
|
27 |
temp_scale: Temperature scale to use ('celsius' or 'fahrenheit')
|
28 |
Returns:
|
29 |
+
tuple: (temperature value as float, unit as string 'C' or 'F', qualitative description)
|
30 |
"""
|
31 |
+
def get_description(temp_c: float) -> str:
|
32 |
+
"""Get qualitative description based on Celsius temperature"""
|
33 |
+
if temp_c <= 0: return "freezing"
|
34 |
+
if temp_c <= 10: return "cold"
|
35 |
+
if temp_c <= 20: return "mild"
|
36 |
+
if temp_c <= 30: return "warm"
|
37 |
+
return "hot"
|
38 |
+
|
39 |
+
def to_celsius(f: float) -> float:
|
40 |
+
"""Convert Fahrenheit to Celsius"""
|
41 |
+
return (f - 32) * 5/9
|
42 |
+
|
43 |
+
def to_fahrenheit(c: float) -> float:
|
44 |
+
"""Convert Celsius to Fahrenheit"""
|
45 |
+
return (c * 9/5) + 32
|
46 |
try:
|
47 |
API_KEY = os.environ.get('WEATHER_API_KEY')
|
48 |
if not API_KEY:
|
|
|
60 |
data = response.json()
|
61 |
|
62 |
if response.status_code == 200:
|
63 |
+
temp = data["main"]["temp"]
|
64 |
+
unit = 'C' if temp_scale == "celsius" else 'F'
|
65 |
+
|
66 |
+
# Convert to Celsius for description if needed
|
67 |
+
temp_c = temp if temp_scale == "celsius" else to_celsius(temp)
|
68 |
+
description = get_description(temp_c)
|
69 |
+
|
70 |
+
return (temp, unit, description)
|
71 |
else:
|
72 |
error_msg = data.get('message', 'Unknown error')
|
73 |
raise Exception(f"API Error: {error_msg} (Status code: {response.status_code})")
|
74 |
+
|
75 |
except requests.Timeout:
|
76 |
raise Exception(f"Request timed out while fetching temperature for {location}")
|
77 |
except requests.RequestException as e:
|