Spaces:
Runtime error
Runtime error
Update app.py
Browse files1234567891011121314151617181920212223242526272829303132333435361 unmodified line38394041424344454647484950515253545556575859606162636465666768697071728 unmodified lines8182838485868788893 unmodified lines9394959697989910010110211 unmodified lines1141151161171181191207 unmodified lines128129130131132133134135136137import gradio as grimport requestsimport jsonfrom datetime import datetime, timedeltafrom bs4 import BeautifulSoupclass WeatherModule:def __init__(self, cache_ttl=600): # 10 минут кэшself.cache = {}self.cache_ttl = cache_ttldef get_weather(self, city):"""Главный метод: возвращает погоду по названию города"""city_key = city.lower().strip()if city_key in self.cache:data, timestamp = self.cache[city_key]if datetime.now() - timestamp < timedelta(seconds=self.cache_ttl):return datadata = None# 1. wttr.indata = self._from_wttr(city)if data:self.cache[city_key] = (data, datetime.now())return data# 2. Open-Meteo через зеркалоdata = self._from_openmeteo(city)if data:self.cache[city_key] = (data, datetime.now())return data# 3. Парсинг Яндекса (запасной)data = self._from_yandex(city)if data:self.cache[city_key] = (data, datetime.now())1 unmodified linereturn {"error": "Не удалось получить погоду"}def _from_wttr(self, city):try:url = f"https://wttr.in/{city}?format=%C+%t+%w+%h"resp = requests.get(url, timeout=5)if resp.status_code == 200:parts = resp.text.strip().split()if len(parts) < 3:return Nonecondition = " ".join(parts[:-3])temp = parts[-3] if len(parts) >= 3 else "?"wind = parts[-2] if len(parts) >= 2 else "?"humidity = parts[-1] if parts else "?"return {"temperature": temp.replace("°C", "").strip(),"condition": condition,"wind": wind.replace("km/h", "").strip(),"humidity": humidity.replace("%", "").strip()}except Exception:passreturn Nonedef _from_openmeteo(self, city):coords = self._get_coords(city)if not coords:return Nonetry:url = f"https://open-meteo.eu/v1/forecast?latitude={coords['lat']}&longitude={coords['lon']}¤t_weather=true"resp = requests.get(url, timeout=5)if resp.status_code == 200:data = resp.json()current = data.get('current_weather', {})8 unmodified linesreturn Nonedef _get_coords(self, city):try:url = f"https://nominatim.openstreetmap.org/search?q={city}&format=json&limit=1"resp = requests.get(url, headers={'User-Agent': 'WeatherBot/1.0'}, timeout=5)if resp.status_code == 200:data = resp.json()if data:3 unmodified linesreturn Nonedef _from_yandex(self, city):try:url = f"https://yandex.ru/pogoda/{city.lower()}"headers = {'User-Agent': 'Mozilla/5.0'}resp = requests.get(url, headers=headers, timeout=5)if resp.status_code == 200:soup = BeautifulSoup(resp.text, 'html.parser')temp_elem = soup.find('span', class_='temp__value')11 unmodified linespassreturn None# ---------- GRADIO ИНТЕРФЕЙС ----------weather_module = WeatherModule()def get_weather_gui(city):7 unmodified linesiface = gr.Interface(fn=get_weather_gui,inputs=gr.Textbox(label="Введите город", placeholder="Например: Тамбов"),outputs=gr.Textbox(label="Погода сейчас", lines=6),title="🌤️ Погодный модуль для ИИ-ассистента",description="Использует wttr.in, Open-Meteo и парсинг Яндекса с кэшированием.")if __name__ == "__main__":123456789101112131415161718192021222324252627281 unmodified line3031323334353637383940414243444546478 unmodified lines565758596061626364653 unmodified lines697071727374757677787911 unmodified lines919293949596977 unmodified lines105106107108109110111112113114import gradio as grimport requestsfrom datetime import datetime, timedeltafrom bs4 import BeautifulSoupclass WeatherModule:def __init__(self, cache_ttl=600):self.cache = {}self.cache_ttl = cache_ttldef get_weather(self, city):city_key = city.lower().strip()# кэшif city_key in self.cache:data, timestamp = self.cache[city_key]if datetime.now() - timestamp < timedelta(seconds=self.cache_ttl):return data# 1) Open-Meteo (основной)data = self._from_openmeteo(city)if data:self.cache[city_key] = (data, datetime.now())return data# 2) Яндекс (запасной)data = self._from_yandex(city)if data:self.cache[city_key] = (data, datetime.now())1 unmodified linereturn {"error": "Не удалось получить погоду"}def _from_openmeteo(self, city):coords = self._get_coords(city)if not coords:return Nonetry:url = (f"https://api.open-meteo.com/v1/forecast"f"?latitude={coords['lat']}&longitude={coords['lon']}"f"¤t_weather=true")# увеличим таймаут до 10 секундresp = requests.get(url, timeout=10)if resp.status_code == 200:data = resp.json()current = data.get('current_weather', {})8 unmodified linesreturn Nonedef _get_coords(self, city):# используем Nominatim, но с запасным таймаутомtry:url = f"https://nominatim.openstreetmap.org/search?q={city}&format=json&limit=1"resp = requests.get(url, headers={'User-Agent': 'WeatherBot/1.0'}, timeout=10)if resp.status_code == 200:data = resp.json()if data:3 unmodified linesreturn Nonedef _from_yandex(self, city):# парсинг Яндекса – работает редко, но оставимtry:url = f"https://yandex.ru/pogoda/{city.lower()}"headers = {'User-Agent': 'Mozilla/5.0'}resp = requests.get(url, headers=headers, timeout=10)if resp.status_code == 200:soup = BeautifulSoup(resp.text, 'html.parser')temp_elem = soup.find('span', class_='temp__value')11 unmodified linespassreturn None# ---------- Gradio интерфейс ----------weather_module = WeatherModule()def get_weather_gui(city):7 unmodified linesiface = gr.Interface(fn=get_weather_gui,inputs=gr.Textbox(label="Введите город", placeholder="Например: Москва"),outputs=gr.Textbox(label="Погода сейчас", lines=6),title="🌤️ Погодный модуль",description="Источники: Open-Meteo, Яндекс.Погода (запасной).")if __name__ == "__main__":
app.py+19-42