File size: 11,349 Bytes
bd563a8
12a8b83
 
38fc74a
2b0d420
38fc74a
2b0d420
 
 
a1926e1
2b0d420
 
da0140f
a1926e1
 
 
 
698cf01
a1926e1
698cf01
a1926e1
698cf01
a1926e1
698cf01
3b57ab8
698cf01
a1926e1
 
 
698cf01
 
 
 
 
 
 
cced9c5
12a8b83
a1926e1
 
 
12a8b83
2b0d420
 
12a8b83
698cf01
12a8b83
ac57ee0
a1926e1
 
 
698cf01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1926e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
698cf01
 
 
 
 
 
 
 
 
61093db
ac57ee0
a1926e1
 
 
698cf01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1926e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
698cf01
 
 
 
 
 
 
 
2b0d420
 
a1926e1
2b0d420
a1926e1
 
 
 
 
2b0d420
a1926e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b0d420
698cf01
a1926e1
 
 
 
 
2b0d420
698cf01
a1926e1
 
f73f8cc
cae2cb1
 
 
 
 
698cf01
 
2b0d420
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
import os
import datetime
import pytz
import requests
from dotenv import load_dotenv
from langdetect import detect
from geopy.geocoders import Nominatim
from timezonefinder import TimezoneFinder
import gradio as gr
import re

load_dotenv()

def geocode_city(city: str, lang: str = "en"):
    """
    Geocode city with fallback to simpler name and language.
    """
    geolocator = Nominatim(user_agent="weather_assistant")
    location = geolocator.geocode(city, language=lang)
    if not location:
        # fallback: first word
        simple = city.split()[0]
        location = geolocator.geocode(simple, language=lang)
    return location

def get_timezone_by_city(city: str) -> str:
    """
    Get timezone for a city.
    """
    location = geocode_city(city)
    if not location:
        return f"❌ Не удалось найти населенный пункт '{city}'."
    tz = TimezoneFinder().timezone_at(lat=location.latitude, lng=location.longitude)
    if not tz:
        return f"❌ Не удалось определить часовой пояс для '{city}'."
    return tz

def get_current_time_in_timezone(timezone: str) -> str:
    """
    Get local current time in a timezone.
    """
    try:
        now = datetime.datetime.now(pytz.timezone(timezone))
        return now.strftime("%Y-%m-%d %H:%M:%S")
    except Exception as e:
        return f"❌ Ошибка получения времени: {e}"

def get_air_quality(city: str, lang: str = "en") -> str:
    """
    Get translated air quality info.
    """
    location = geocode_city(city)
    if not location:
        return f"❌ Не удалось найти населенный пункт '{city}'."
    api_key = os.environ.get("OPENWEATHERMAP_API_KEY")
    if not api_key:
        return "❌ Отсутствует API-ключ OpenWeatherMap."
    url = (f"http://api.openweathermap.org/data/2.5/air_pollution?"
           f"lat={location.latitude}&lon={location.longitude}&appid={api_key}")
    resp = requests.get(url)
    if resp.status_code != 200:
        return f"❌ Ошибка API качества воздуха: {resp.status_code}"
    data = resp.json().get("list", [])
    if not data:
        return "❌ Нет данных о качестве воздуха."
    aqi = data[0]["main"]["aqi"]
    comps = data[0]["components"]
    translations = {
        "en": {
            "title": "😷 Air Quality",
            "aqi_desc": {1: "Good", 2: "Fair", 3: "Moderate", 4: "Poor", 5: "Very Poor"},
            "pm2_5": "Fine particles (PM2.5)",
            "pm10": "Coarse particles (PM10)",
            "co": "Carbon monoxide (CO)",
        },
        "ru": {
            "title": "😷 Качество воздуха",
            "aqi_desc": {1: "Хорошее", 2: "Удовлетворительное", 3: "Среднее", 4: "Плохое", 5: "Очень плохое"},
            "pm2_5": "Мелкие частицы (PM2.5)",
            "pm10": "Крупные частицы (PM10)",
            "co": "Углекислый газ (CO)",
        },
        "hi": {
            "title": "😷 वायु गुणवत्ता",
            "aqi_desc": {1: "अच्छा", 2: "संतोषजनक", 3: "मध्यम", 4: "खराब", 5: "बहुत खराब"},
            "pm2_5": "सूक्ष्म कण (PM2.5)",
            "pm10": "मोटे कण (PM10)",
            "co": "कार्बन मोनोऑक्साइड (CO)",
        },
        "zh": {
            "title": "😷 空气质量",
            "aqi_desc": {1: "良好", 2: "一般", 3: "中等", 4: "较差", 5: "很差"},
            "pm2_5": "细颗粒物 (PM2.5)",
            "pm10": "可吸入颗粒物 (PM10)",
            "co": "一氧化碳 (CO)",
        },
        "es": {
            "title": "😷 Calidad del aire",
            "aqi_desc": {1: "Buena", 2: "Aceptable", 3: "Moderada", 4: "Pobre", 5: "Muy mala"},
            "pm2_5": "Partículas finas (PM2.5)",
            "pm10": "Partículas gruesas (PM10)",
            "co": "Monóxido de carbono (CO)",
        },
        "fr": {
            "title": "😷 Qualité de l'air",
            "aqi_desc": {1: "Bonne", 2: "Passable", 3: "Moyenne", 4: "Mauvaise", 5: "Très mauvaise"},
            "pm2_5": "Particules fines (PM2.5)",
            "pm10": "Particules grossières (PM10)",
            "co": "Monoxyde de carbone (CO)",
        },
        "ko": {
            "title": "😷 대기질",
            "aqi_desc": {1: "좋음", 2: "보통", 3: "보통 이상", 4: "나쁨", 5: "매우 나쁨"},
            "pm2_5": "미세먼지 (PM2.5)",
            "pm10": "먼지 (PM10)",
            "co": "일산화탄소 (CO)",
        },
    }
    t = translations.get(lang, translations["en"])
    emoji = "🌱" if aqi <= 2 else "😷" if aqi <= 4 else "☣️"
    return (
        f"{t['title']}: AQI {aqi} ({t['aqi_desc'][aqi]}) {emoji}\n"
        f"{t['pm2_5']}: {comps['pm2_5']} µg/m³\n"
        f"{t['pm10']}: {comps['pm10']} µg/m³\n"
        f"{t['co']}: {comps['co']} µg/m³"
    )

def get_weather(city: str, lang: str = "en") -> str:
    """
    Get translated weather info.
    """
    location = geocode_city(city)
    if not location:
        return f"❌ Не удалось найти населенный пункт '{city}'."
    api_key = os.environ.get("OPENWEATHERMAP_API_KEY")
    if not api_key:
        return "❌ Отсутствует API-ключ OpenWeatherMap."
    url = (f"http://api.openweathermap.org/data/2.5/weather?"
           f"lat={location.latitude}&lon={location.longitude}"
           f"&appid={api_key}&units=metric")
    resp = requests.get(url)
    if resp.status_code != 200:
        return f"❌ Ошибка API погоды: {resp.status_code}"
    d = resp.json()
    cond = d["weather"][0]["main"]
    temp = d["main"]["temp"]
    hum = d["main"]["humidity"]
    translations = {
        "en": {
            "title": "🌡️ Weather",
            "temp": "Temperature",
            "humidity": "Humidity",
            "conditions": {
                "Clear": "Clear ☀️", "Clouds": "Cloudy ☁️", "Rain": "Rain 🌧",
                "Snow": "Snow ❄️", "Thunderstorm": "Storm ⛈", "Drizzle": "Drizzle 🌦",
                "Mist": "Mist 🌫", "Haze": "Haze 🌫"
            }
        },
        "ru": {
            "title": "🌡️ Погода",
            "temp": "Температура",
            "humidity": "Влажность",
            "conditions": {
                "Clear": "Ясно ☀️", "Clouds": "Облачно ☁️", "Rain": "Дождь 🌧",
                "Snow": "Снег ❄️", "Thunderstorm": "Гроза ⛈", "Drizzle": "Морось 🌦",
                "Mist": "Туман 🌫", "Haze": "Дымка 🌫"
            }
        },
        "hi": {
            "title": "🌡️ मौसम",
            "temp": "तापमान",
            "humidity": "नमी",
            "conditions": {
                "Clear": "साफ ☀️", "Clouds": "बादल ☁️", "Rain": "बारिश 🌧",
                "Snow": "बर्फ ❄️", "Thunderstorm": "तूफान ⛈", "Drizzle": "बूंदाबांदी 🌦",
                "Mist": "कोहरा 🌫", "Haze": "धुंध 🌫"
            }
        },
        "zh": {
            "title": "🌡️ 天气",
            "temp": "温度",
            "humidity": "湿度",
            "conditions": {
                "Clear": "晴 ☀️", "Clouds": "多云 ☁️", "Rain": "雨 🌧",
                "Snow": "雪 ❄️", "Thunderstorm": "雷暴 ⛈", "Drizzle": "毛毛雨 🌦",
                "Mist": "雾 🌫", "Haze": "霾 🌫"
            }
        },
        "es": {
            "title": "🌡️ Clima",
            "temp": "Temperatura",
            "humidity": "Humedad",
            "conditions": {
                "Clear": "Despejado ☀️", "Clouds": "Nublado ☁️", "Rain": "Lluvia 🌧",
                "Snow": "Nieve ❄️", "Thunderstorm": "Tormenta ⛈", "Drizzle": "Llovizna 🌦",
                "Mist": "Niebla 🌫", "Haze": "Calina 🌫"
            }
        },
        "fr": {
            "title": "🌡️ Météo",
            "temp": "Température",
            "humidity": "Humidité",
            "conditions": {
                "Clear": "Dégagé ☀️", "Clouds": "Nuageux ☁️", "Rain": "Pluie 🌧",
                "Snow": "Neige ❄️", "Thunderstorm": "Orage ⛈", "Drizzle": "Bruine 🌦",
                "Mist": "Brume 🌫", "Haze": "Brume légère 🌫"
            }
        },
        "ko": {
            "title": "🌡️ 날씨",
            "temp": "온도",
            "humidity": "습도",
            "conditions": {
                "Clear": "맑음 ☀️", "Clouds": "흐림 ☁️", "Rain": "비 🌧",
                "Snow": "눈 ❄️", "Thunderstorm": "뇌우 ⛈", "Drizzle": "이슬비 🌦",
                "Mist": "안개 🌫", "Haze": "실안개 🌫"
            }
        },
    }
    t = translations.get(lang, translations["en"])
    desc = t["conditions"].get(cond, cond)
    return (
        f"{t['title']}: {desc}\n"
        f"{t['temp']}: {temp}°C\n"
        f"{t['humidity']}: {hum}%"
    )

def process_input(user_input: str) -> str:

    lang = detect(user_input)
    if lang not in ["en","ru","hi","zh","es","fr","ko"]:
        if re.search(r'[\u0400-\u04FF]', user_input):
            lang = "ru"
        else:
            lang = "en"
    city = user_input.strip()

    loc_disp = geocode_city(city, lang)
    if not loc_disp:
        return f"❌ Не удалось найти населенный пункт '{city}'."
    parts = loc_disp.raw.get("display_name", "").split(", ")
    city_disp = parts[0]
    region_disp = parts[1] if len(parts) > 2 else ""
    country_disp = parts[-1] if parts else ""

    location_labels = {
        "en": "📍 Location",
        "ru": "📍 Местоположение",
        "hi": "📍 स्थान",
        "zh": "📍 位置",
        "es": "📍 Ubicación",
        "fr": "📍 Emplacement",
        "ko": "📍 위치",
    }
    time_labels = {
        "en": "🕒 Time",
        "ru": "🕒 Время",
        "hi": "🕒 समय",
        "zh": "🕒 时间",
        "es": "🕒 Hora",
        "fr": "🕒 Heure",
        "ko": "🕒 시간",
    }

    location_line = f"{location_labels.get(lang,'📍 Location')}: {city_disp}"
    if region_disp:
        location_line += f", {region_disp}"
    if country_disp:
        location_line += f", {country_disp}"

    tz = get_timezone_by_city(city)
    if tz.startswith("❌"):
        time_line = tz
    else:
        ct = get_current_time_in_timezone(tz)
        time_line = f"{time_labels.get(lang,'🕒 Time')}: {ct}"

    aq = get_air_quality(city, lang)
    w = get_weather(city, lang)

    return f"{location_line}\n\n{time_line}\n\n{aq}\n\n{w}"

if __name__ == "__main__":
    gr.Interface(
        fn=process_input,
        inputs="text",
        outputs="text",
        title="Weather Assistant / Погодный ассистент",
        description="Введите свой населенный пункт — получите время, погоду и качество воздуха."
    ).launch()