Spaces:
Paused

File size: 5,360 Bytes
c2a9382
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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']}&current_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()