Spaces:
Runtime error
Runtime error
Update app.py
Browse files1233456878910111312131415161718202122232425262719202122232433252627281 unmodified line3031324142434445464748495051525354555657585960616233343536376869383940414243444546478 unmodified lines56575859606186626364653 unmodified lines69707172737475997677787911 unmodified lines919293117949596977 unmodified lines105106107131108109133134110111112113114import gradio as grimport requestsimport jsonfrom datetime import datetime, timedeltafrom bs4 import BeautifulSoup
class WeatherModule: def __init__(self, cache_ttl=600): # 10 минут кэш def __init__(self, cache_ttl=600): self.cache = {} self.cache_ttl = cache_ttl
def 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
data = None # 1. wttr.in data = self._from_wttr(city) if data: self.cache[city_key] = (data, datetime.now()) return data
# 2. Open-Meteo через зеркало # 1) Open-Meteo (основной) data = self._from_openmeteo(city) if data: self.cache[city_key] = (data, datetime.now()) return data
# 3. Парсинг Яндекса (запасной) # 2) Яндекс (запасной) data = self._from_yandex(city) if data: self.cache[city_key] = (data, datetime.now())1 unmodified line
return {"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 None condition = " ".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: pass return None
def _from_openmeteo(self, city): coords = self._get_coords(city) if not coords: return None try: url = f"https://open-meteo.eu/v1/forecast?latitude={coords['lat']}&longitude={coords['lon']}¤t_weather=true" resp = requests.get(url, timeout=5) 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 lines return None
def _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=5) resp = requests.get(url, headers={'User-Agent': 'WeatherBot/1.0'}, timeout=10) if resp.status_code == 200: data = resp.json() if data:3 unmodified lines return None
def _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) 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 lines pass return None
# ---------- GRADIO ИНТЕРФЕЙС ----------# ---------- Gradio интерфейс ----------weather_module = WeatherModule()
def get_weather_gui(city):7 unmodified lines
iface = gr.Interface( fn=get_weather_gui, inputs=gr.Textbox(label="Введите город", placeholder="Например: Тамбов"), inputs=gr.Textbox(label="Введите город", placeholder="Например: Москва"), outputs=gr.Textbox(label="Погода сейчас", lines=6), title="🌤️ Погодный модуль для ИИ-ассистента", description="Использует wttr.in, Open-Meteo и парсинг Яндекса с кэшированием." title="🌤️ Погодный модуль", description="Источники: Open-Meteo, Яндекс.Погода (запасной).")
if __name__ == "__main__":app.py+19-42