Spaces:
Paused
Paused
Download app.py from DunaevStudio/test: direct link, hf CLI and curl.
- Browser
- Download file 5.36 kB
-
https://huggingface.co/spaces/DunaevStudio/test/resolve/main/app.py
- Command line
-
hf download hf://spaces/DunaevStudio/test/app.py
-
curl -L -o app.py https://huggingface.co/spaces/DunaevStudio/test/resolve/main/app.py
5.36 kB
| import gradio as gr | |
| import requests | |
| import json | |
| from datetime import datetime, timedelta | |
| from bs4 import BeautifulSoup | |
| class WeatherModule: | |
| def __init__(self, cache_ttl=600): # 10 минут кэш | |
| 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 через зеркало | |
| 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()) | |
| return data | |
| 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) | |
| if resp.status_code == 200: | |
| data = resp.json() | |
| current = data.get('current_weather', {}) | |
| return { | |
| "temperature": str(current.get('temperature', '?')), | |
| "condition": "По данным Open-Meteo", | |
| "wind": str(current.get('windspeed', '?')), | |
| "humidity": "?" | |
| } | |
| except Exception: | |
| pass | |
| return None | |
| def _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: | |
| return {"lat": data[0]['lat'], "lon": data[0]['lon']} | |
| except Exception: | |
| pass | |
| 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) | |
| if resp.status_code == 200: | |
| soup = BeautifulSoup(resp.text, 'html.parser') | |
| temp_elem = soup.find('span', class_='temp__value') | |
| if temp_elem: | |
| temp = temp_elem.text.strip() | |
| desc_elem = soup.find('div', class_='weather__description') | |
| desc = desc_elem.text.strip() if desc_elem else "" | |
| return { | |
| "temperature": temp.replace("°", "").strip(), | |
| "condition": desc, | |
| "wind": "?", | |
| "humidity": "?" | |
| } | |
| except Exception: | |
| pass | |
| return None | |
| # ---------- GRADIO ИНТЕРФЕЙС ---------- | |
| weather_module = WeatherModule() | |
| def get_weather_gui(city): | |
| result = weather_module.get_weather(city) | |
| if "error" in result: | |
| return f"❌ {result['error']}" | |
| return (f"🌡️ Температура: {result.get('temperature', '?')}°C\n" | |
| f"☁️ Состояние: {result.get('condition', '?')}\n" | |
| f"💨 Ветер: {result.get('wind', '?')} м/с\n" | |
| f"💧 Влажность: {result.get('humidity', '?')}%") | |
| iface = 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__": | |
| iface.launch() |