Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -10,125 +10,155 @@ import gradio as gr
|
|
| 10 |
|
| 11 |
load_dotenv()
|
| 12 |
|
| 13 |
-
def
|
| 14 |
-
""
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
|
|
|
| 19 |
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
tz = TimezoneFinder().timezone_at(lat=loc.latitude, lng=loc.longitude)
|
| 29 |
-
return tz or f"❌ Часовой пояс не найден."
|
| 30 |
-
except Exception as e:
|
| 31 |
-
return f"❌ Ошибка пояса: {e}"
|
| 32 |
|
| 33 |
def get_current_time_in_timezone(timezone: str) -> str:
|
| 34 |
-
"""
|
| 35 |
-
Get local time for timezone.
|
| 36 |
-
|
| 37 |
-
Args:
|
| 38 |
-
timezone (str): Timezone name.
|
| 39 |
-
|
| 40 |
-
Returns:
|
| 41 |
-
str: Current time or error.
|
| 42 |
-
"""
|
| 43 |
try:
|
| 44 |
now = datetime.datetime.now(pytz.timezone(timezone))
|
| 45 |
return now.strftime("%Y-%m-%d %H:%M:%S")
|
| 46 |
except Exception as e:
|
| 47 |
-
return f"❌ Ошибка времени: {e}"
|
| 48 |
|
| 49 |
def get_air_quality(city: str, lang: str = "en") -> str:
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
"
|
| 70 |
-
"
|
| 71 |
-
"
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
|
| 82 |
def get_weather(city: str, lang: str = "en") -> str:
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
"
|
| 103 |
-
|
| 104 |
-
"
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
|
| 115 |
def process_input(user_input: str) -> str:
|
| 116 |
lang = detect(user_input)
|
| 117 |
-
lang = lang if lang in ["en","ru","hi"] else "en"
|
| 118 |
city = user_input.strip()
|
| 119 |
tz = get_timezone_by_city(city)
|
| 120 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
aq = get_air_quality(city, lang)
|
| 122 |
-
w
|
| 123 |
-
|
| 124 |
-
parts = [f"🕒 Время: {ct}", aq, w]
|
| 125 |
-
return "\n\n".join(parts)
|
| 126 |
|
| 127 |
if __name__ == "__main__":
|
| 128 |
gr.Interface(
|
| 129 |
fn=process_input,
|
| 130 |
inputs="text",
|
| 131 |
outputs="text",
|
| 132 |
-
title="
|
| 133 |
-
description="
|
| 134 |
).launch()
|
|
|
|
| 10 |
|
| 11 |
load_dotenv()
|
| 12 |
|
| 13 |
+
def geocode_city(city: str):
|
| 14 |
+
geolocator = Nominatim(user_agent="weather_assistant")
|
| 15 |
+
location = geolocator.geocode(city, language="en")
|
| 16 |
+
if not location:
|
| 17 |
+
simple = city.split()[0]
|
| 18 |
+
location = geolocator.geocode(simple, language="en")
|
| 19 |
+
return location
|
| 20 |
|
| 21 |
+
def get_timezone_by_city(city: str) -> str:
|
| 22 |
+
location = geocode_city(city)
|
| 23 |
+
if not location:
|
| 24 |
+
return f"❌ Не удалось найти населенный пункт '{city}'."
|
| 25 |
+
tz = TimezoneFinder().timezone_at(lat=location.latitude, lng=location.longitude)
|
| 26 |
+
if not tz:
|
| 27 |
+
return f"❌ Не удалось определить часовой пояс для '{city}'."
|
| 28 |
+
return tz
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
def get_current_time_in_timezone(timezone: str) -> str:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
try:
|
| 32 |
now = datetime.datetime.now(pytz.timezone(timezone))
|
| 33 |
return now.strftime("%Y-%m-%d %H:%M:%S")
|
| 34 |
except Exception as e:
|
| 35 |
+
return f"❌ Ошибка получения времени: {e}"
|
| 36 |
|
| 37 |
def get_air_quality(city: str, lang: str = "en") -> str:
|
| 38 |
+
location = geocode_city(city)
|
| 39 |
+
if not location:
|
| 40 |
+
return f"❌ Не удалось найти населенный пункт '{city}'."
|
| 41 |
+
api_key = os.environ.get("OPENWEATHERMAP_API_KEY")
|
| 42 |
+
if not api_key:
|
| 43 |
+
return "❌ Отсутствует API-ключ OpenWeatherMap."
|
| 44 |
+
url = (f"http://api.openweathermap.org/data/2.5/air_pollution?"
|
| 45 |
+
f"lat={location.latitude}&lon={location.longitude}&appid={api_key}")
|
| 46 |
+
resp = requests.get(url)
|
| 47 |
+
if resp.status_code != 200:
|
| 48 |
+
return f"❌ Ошибка API качества воздуха: {resp.status_code}"
|
| 49 |
+
data = resp.json().get("list", [])
|
| 50 |
+
if not data:
|
| 51 |
+
return "❌ Нет данных о качестве воздуха."
|
| 52 |
+
aqi = data[0]["main"]["aqi"]
|
| 53 |
+
comps = data[0]["components"]
|
| 54 |
+
translations = {
|
| 55 |
+
"en": {
|
| 56 |
+
"title": "😷 Air Quality",
|
| 57 |
+
"aqi_desc": {1: "Good", 2: "Fair", 3: "Moderate", 4: "Poor", 5: "Very Poor"},
|
| 58 |
+
"pm2_5": "Fine particles (PM2.5)",
|
| 59 |
+
"pm10": "Coarse particles (PM10)",
|
| 60 |
+
"co": "Carbon monoxide (CO)",
|
| 61 |
+
},
|
| 62 |
+
"ru": {
|
| 63 |
+
"title": "😷 Качество воздуха",
|
| 64 |
+
"aqi_desc": {1: "Хорошее", 2: "Удовлетворительное", 3: "Среднее", 4: "Плохое", 5: "Очень плохое"},
|
| 65 |
+
"pm2_5": "Мелкие частицы (PM2.5)",
|
| 66 |
+
"pm10": "Крупные частицы (PM10)",
|
| 67 |
+
"co": "Углекислый газ (CO)",
|
| 68 |
+
},
|
| 69 |
+
"hi": {
|
| 70 |
+
"title": "😷 वायु गुणवत्ता",
|
| 71 |
+
"aqi_desc": {1: "अच्छा", 2: "संतोषजनक", 3: "मध्यम", 4: "खराब", 5: "बहुत खराब"},
|
| 72 |
+
"pm2_5": "सूक्ष्म कण (PM2.5)",
|
| 73 |
+
"pm10": "मोटे कण (PM10)",
|
| 74 |
+
"co": "कार्बन मोनोऑक्साइड (CO)",
|
| 75 |
+
},
|
| 76 |
+
}
|
| 77 |
+
t = translations.get(lang, translations["en"])
|
| 78 |
+
emoji = "🌱" if aqi <= 2 else "😷" if aqi <= 4 else "☣️"
|
| 79 |
+
return (
|
| 80 |
+
f"{t['title']}: AQI {aqi} ({t['aqi_desc'][aqi]}) {emoji}\n"
|
| 81 |
+
f"{t['pm2_5']}: {comps['pm2_5']} µg/m³\n"
|
| 82 |
+
f"{t['pm10']}: {comps['pm10']} µg/m³\n"
|
| 83 |
+
f"{t['co']}: {comps['co']} µg/m³"
|
| 84 |
+
)
|
| 85 |
|
| 86 |
def get_weather(city: str, lang: str = "en") -> str:
|
| 87 |
+
location = geocode_city(city)
|
| 88 |
+
if not location:
|
| 89 |
+
return f"❌ Не удалось найти населенный пункт '{city}'."
|
| 90 |
+
api_key = os.environ.get("OPENWEATHERMAP_API_KEY")
|
| 91 |
+
if not api_key:
|
| 92 |
+
return "❌ Отсутствует API-ключ OpenWeatherMap."
|
| 93 |
+
url = (f"http://api.openweathermap.org/data/2.5/weather?"
|
| 94 |
+
f"lat={location.latitude}&lon={location.longitude}"
|
| 95 |
+
f"&appid={api_key}&units=metric")
|
| 96 |
+
resp = requests.get(url)
|
| 97 |
+
if resp.status_code != 200:
|
| 98 |
+
return f"❌ Ошибка API погоды: {resp.status_code}"
|
| 99 |
+
d = resp.json()
|
| 100 |
+
cond = d["weather"][0]["main"]
|
| 101 |
+
temp = d["main"]["temp"]
|
| 102 |
+
hum = d["main"]["humidity"]
|
| 103 |
+
translations = {
|
| 104 |
+
"en": {
|
| 105 |
+
"title": "🌡️ Weather",
|
| 106 |
+
"temp": "Temperature",
|
| 107 |
+
"humidity": "Humidity",
|
| 108 |
+
"conditions": {
|
| 109 |
+
"Clear": "Clear ☀️", "Clouds": "Cloudy ☁️", "Rain": "Rain 🌧",
|
| 110 |
+
"Snow": "Snow ❄️", "Thunderstorm": "Storm ⛈", "Drizzle": "Drizzle 🌦",
|
| 111 |
+
"Mist": "Mist 🌫", "Haze": "Haze 🌫"
|
| 112 |
+
}
|
| 113 |
+
},
|
| 114 |
+
"ru": {
|
| 115 |
+
"title": "🌡️ Погода",
|
| 116 |
+
"temp": "Температура",
|
| 117 |
+
"humidity": "Влажность",
|
| 118 |
+
"conditions": {
|
| 119 |
+
"Clear": "Ясно ☀️", "Clouds": "Облачно ☁️", "Rain": "Дождь 🌧",
|
| 120 |
+
"Snow": "Снег ❄️", "Thunderstorm": "Гроза ⛈", "Drizzle": "Морось 🌦",
|
| 121 |
+
"Mist": "Туман 🌫", "Haze": "Дымка 🌫"
|
| 122 |
+
}
|
| 123 |
+
},
|
| 124 |
+
"hi": {
|
| 125 |
+
"title": "🌡️ मौसम",
|
| 126 |
+
"temp": "तापमान",
|
| 127 |
+
"humidity": "नमी",
|
| 128 |
+
"conditions": {
|
| 129 |
+
"Clear": "साफ ☀️", "Clouds": "बादल ☁️", "Rain": "बारिश 🌧",
|
| 130 |
+
"Snow": "बर्फ ❄️", "Thunderstorm": "तूफान ⛈", "Drizzle": "बूंदाबांदी 🌦",
|
| 131 |
+
"Mist": "कोहरा 🌫", "Haze": "धुंध 🌫"
|
| 132 |
+
}
|
| 133 |
+
},
|
| 134 |
+
}
|
| 135 |
+
t = translations.get(lang, translations["en"])
|
| 136 |
+
desc = t["conditions"].get(cond, cond)
|
| 137 |
+
return (
|
| 138 |
+
f"{t['title']}: {desc}\n"
|
| 139 |
+
f"{t['temp']}: {temp}°C\n"
|
| 140 |
+
f"{t['humidity']}: {hum}%"
|
| 141 |
+
)
|
| 142 |
|
| 143 |
def process_input(user_input: str) -> str:
|
| 144 |
lang = detect(user_input)
|
| 145 |
+
lang = lang if lang in ["en", "ru", "hi"] else "en"
|
| 146 |
city = user_input.strip()
|
| 147 |
tz = get_timezone_by_city(city)
|
| 148 |
+
if tz.startswith("❌"):
|
| 149 |
+
return tz
|
| 150 |
+
ct = get_current_time_in_timezone(tz)
|
| 151 |
+
if ct.startswith("❌"):
|
| 152 |
+
return ct
|
| 153 |
aq = get_air_quality(city, lang)
|
| 154 |
+
w = get_weather(city, lang)
|
| 155 |
+
return f"🕒 {'Time' if lang=='en' else 'Время'}: {ct}\n\n{aq}\n\n{w}"
|
|
|
|
|
|
|
| 156 |
|
| 157 |
if __name__ == "__main__":
|
| 158 |
gr.Interface(
|
| 159 |
fn=process_input,
|
| 160 |
inputs="text",
|
| 161 |
outputs="text",
|
| 162 |
+
title="Weather Assistant / Погодный ассистент",
|
| 163 |
+
description="Введите свой населенный пункт — получите время, погоду и качество воздуха."
|
| 164 |
).launch()
|