Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,17 +1,15 @@
|
|
| 1 |
import os
|
| 2 |
-
from dotenv import load_dotenv
|
| 3 |
-
load_dotenv()
|
| 4 |
-
|
| 5 |
-
from smolagents import CodeAgent, HfApiModel, tool
|
| 6 |
import datetime
|
| 7 |
import pytz
|
| 8 |
-
import gradio as gr
|
| 9 |
-
from geopy.geocoders import Nominatim
|
| 10 |
-
from timezonefinder import TimezoneFinder
|
| 11 |
import requests
|
|
|
|
| 12 |
from langdetect import detect
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
-
@tool
|
| 15 |
def get_timezone_by_city(city: str) -> str:
|
| 16 |
"""
|
| 17 |
Get timezone for a city.
|
|
@@ -20,240 +18,117 @@ def get_timezone_by_city(city: str) -> str:
|
|
| 20 |
city (str): City name.
|
| 21 |
|
| 22 |
Returns:
|
| 23 |
-
str: Timezone
|
| 24 |
"""
|
| 25 |
try:
|
| 26 |
-
geolocator = Nominatim(user_agent="
|
| 27 |
-
|
| 28 |
-
if not
|
| 29 |
return f"❌ Город '{city}' не найден."
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
return timezone or f"❌ Часовой пояс не определён."
|
| 33 |
except Exception as e:
|
| 34 |
-
return f"❌ Ошибка
|
| 35 |
|
| 36 |
-
@tool
|
| 37 |
def get_current_time_in_timezone(timezone: str) -> str:
|
| 38 |
"""
|
| 39 |
-
Get
|
| 40 |
|
| 41 |
Args:
|
| 42 |
timezone (str): Timezone name.
|
| 43 |
|
| 44 |
Returns:
|
| 45 |
-
str:
|
| 46 |
"""
|
| 47 |
try:
|
| 48 |
-
|
| 49 |
-
return
|
| 50 |
except Exception as e:
|
| 51 |
-
return f"❌ Ошибка времени: {
|
| 52 |
|
| 53 |
-
@tool
|
| 54 |
def get_air_quality(city: str, lang: str = "en") -> str:
|
| 55 |
"""
|
| 56 |
-
Air quality in city with
|
| 57 |
|
| 58 |
Args:
|
| 59 |
city (str): City name.
|
| 60 |
lang (str): Language code.
|
| 61 |
|
| 62 |
Returns:
|
| 63 |
-
str:
|
| 64 |
"""
|
| 65 |
try:
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
if not location:
|
| 69 |
return f"❌ Город '{city}' не найден."
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
translations = {
|
| 82 |
-
"en": {
|
| 83 |
-
"title": "😷 Air Quality",
|
| 84 |
-
"aqi_desc": {1: "Good", 2: "Fair", 3: "Moderate", 4: "Poor", 5: "Very Poor"},
|
| 85 |
-
"pm2_5": "Fine particles (PM2.5)",
|
| 86 |
-
"pm10": "Coarse particles (PM10)",
|
| 87 |
-
"co": "Carbon monoxide (CO)"
|
| 88 |
-
},
|
| 89 |
-
"ru": {
|
| 90 |
-
"title": "😷 Качество воздуха",
|
| 91 |
-
"aqi_desc": {1: "Хорошее", 2: "Удовлетворительное", 3: "Среднее", 4: "Плохое", 5: "Очень плохое"},
|
| 92 |
-
"pm2_5": "Мелкодисперсные частицы (PM2.5)",
|
| 93 |
-
"pm10": "Крупнодисперсные частицы (PM10)",
|
| 94 |
-
"co": "Угарный газ (CO)"
|
| 95 |
-
},
|
| 96 |
-
"hi": {
|
| 97 |
-
"title": "😷 वायु गुणवत्ता",
|
| 98 |
-
"aqi_desc": {1: "अच्छा", 2: "संतोषजनक", 3: "मध्यम", 4: "खराब", 5: "बहुत खराब"},
|
| 99 |
-
"pm2_5": "सूक्ष्म कण (PM2.5)",
|
| 100 |
-
"pm10": "मोटे कण (PM10)",
|
| 101 |
-
"co": "कार्बन मोनोऑक्साइड (CO)"
|
| 102 |
-
}
|
| 103 |
-
}
|
| 104 |
-
|
| 105 |
-
t = translations.get(lang, translations["en"])
|
| 106 |
-
emoji = "🌱" if aqi <= 2 else "😷" if aqi <= 4 else "☣️"
|
| 107 |
-
|
| 108 |
return (
|
| 109 |
-
f"{
|
| 110 |
-
f"{
|
| 111 |
-
f"{t['pm10']}: {c['pm10']} µg/m³\n"
|
| 112 |
-
f"{t['co']}: {c['co']} µg/m³"
|
| 113 |
)
|
| 114 |
except Exception as e:
|
| 115 |
-
return f"❌ Ошибка
|
| 116 |
|
| 117 |
-
@tool
|
| 118 |
def get_weather(city: str, lang: str = "en") -> str:
|
| 119 |
"""
|
| 120 |
-
Weather
|
| 121 |
|
| 122 |
Args:
|
| 123 |
city (str): City name.
|
| 124 |
lang (str): Language code.
|
| 125 |
|
| 126 |
Returns:
|
| 127 |
-
str: Weather info
|
| 128 |
"""
|
| 129 |
try:
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
if not location:
|
| 133 |
return f"❌ Город '{city}' не найден."
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
"temp": "Temperature",
|
| 150 |
-
"humidity": "Humidity",
|
| 151 |
-
"conditions": {
|
| 152 |
-
"Clear": "Clear ☀️", "Clouds": "Cloudy ☁️", "Rain": "Rain 🌧",
|
| 153 |
-
"Snow": "Snow ❄️", "Thunderstorm": "Storm ⛈", "Drizzle": "Drizzle 🌦", "Mist": "Mist 🌫", "Haze": "Haze 🌫"
|
| 154 |
-
}
|
| 155 |
-
},
|
| 156 |
-
"ru": {
|
| 157 |
-
"title": "🌡️ Погода",
|
| 158 |
-
"temp": "Температура",
|
| 159 |
-
"humidity": "Влажность",
|
| 160 |
-
"conditions": {
|
| 161 |
-
"Clear": "Ясно ☀️", "Clouds": "Облачно ☁️", "Rain": "Дождь 🌧",
|
| 162 |
-
"Snow": "Снег ❄️", "Thunderstorm": "Гроза ⛈", "Drizzle": "Морось 🌦", "Mist": "Туман 🌫", "Haze": "Дымка 🌫"
|
| 163 |
-
}
|
| 164 |
-
},
|
| 165 |
-
"hi": {
|
| 166 |
-
"title": "🌡️ मौसम",
|
| 167 |
-
"temp": "तापमान",
|
| 168 |
-
"humidity": "नमी",
|
| 169 |
-
"conditions": {
|
| 170 |
-
"Clear": "साफ ☀️", "Clouds": "बादल ☁️", "Rain": "बारिश 🌧",
|
| 171 |
-
"Snow": "बर्फ ❄️", "Thunderstorm": "तूफान ⛈", "Drizzle": "बूंदाबांदी 🌦", "Mist": "कोहरा 🌫", "Haze": "धुंध 🌫"
|
| 172 |
-
}
|
| 173 |
-
}
|
| 174 |
-
}
|
| 175 |
-
|
| 176 |
-
t = translations.get(lang, translations["en"])
|
| 177 |
-
desc = t["conditions"].get(condition, condition)
|
| 178 |
-
|
| 179 |
-
return (
|
| 180 |
-
f"{t['title']}: {desc}\n"
|
| 181 |
-
f"{t['temp']}: {temp}°C\n"
|
| 182 |
-
f"{t['humidity']}: {humidity}%"
|
| 183 |
-
)
|
| 184 |
-
except Exception as e:
|
| 185 |
-
return f"❌ Ошибка погоды: {str(e)}"
|
| 186 |
-
|
| 187 |
-
@tool
|
| 188 |
-
def final_answer(answer: str) -> str:
|
| 189 |
-
"""
|
| 190 |
-
Return final response.
|
| 191 |
-
|
| 192 |
-
Args:
|
| 193 |
-
answer (str): The output.
|
| 194 |
-
|
| 195 |
-
Returns:
|
| 196 |
-
str: Same as input.
|
| 197 |
-
"""
|
| 198 |
-
return answer
|
| 199 |
-
|
| 200 |
-
model = HfApiModel(
|
| 201 |
-
max_tokens=1000,
|
| 202 |
-
temperature=0.5,
|
| 203 |
-
model_id='mistralai/Mixtral-8x7B-Instruct-v0.1',
|
| 204 |
-
)
|
| 205 |
-
|
| 206 |
-
system_prompt = (
|
| 207 |
-
"Ты полезный ассистент. Используй только функции: "
|
| 208 |
-
"`get_timezone_by_city`, `get_current_time_in_timezone`, `get_air_quality`, `get_weather`, `final_answer`. "
|
| 209 |
-
"В начале всегда указывай: `lang = variables['lang']` и передавай его в функции. "
|
| 210 |
-
"Ответ должен быть только на языке пользователя. В��звращай только код внутри блока:\n"
|
| 211 |
-
"```py\nfinal_answer('...')\n```<end_code>\n"
|
| 212 |
-
"❌ Никаких пояснений, комментариев, JSON, markdown, описаний вне кода."
|
| 213 |
-
)
|
| 214 |
-
|
| 215 |
-
prompt_templates = {
|
| 216 |
-
"system_prompt": system_prompt,
|
| 217 |
-
"default": "Response: {{question}}",
|
| 218 |
-
"managed_agent": {
|
| 219 |
-
"execute": "```py\nfinal_answer('...')\n```",
|
| 220 |
-
"report": "```py\nfinal_answer('Not implemented')\n```",
|
| 221 |
-
"task": "```py\nfinal_answer('Not implemented')\n```"
|
| 222 |
-
},
|
| 223 |
-
"planning": {
|
| 224 |
-
"initial_plan": "```py\nfinal_answer('Plan not needed')\n```",
|
| 225 |
-
"update_plan_pre_messages": "```py\nfinal_answer('Plan updated')\n```",
|
| 226 |
-
"update_plan_post_messages": "```py\nfinal_answer('Plan adjusted')\n```"
|
| 227 |
-
},
|
| 228 |
-
"final_answer": {
|
| 229 |
-
"pre_messages": "```py\nfinal_answer('...')\n```",
|
| 230 |
-
"template": "Final response: {{answer}}",
|
| 231 |
-
"post_messages": "```py\nfinal_answer('...')\n```"
|
| 232 |
-
}
|
| 233 |
-
}
|
| 234 |
-
|
| 235 |
-
agent = CodeAgent(
|
| 236 |
-
model=model,
|
| 237 |
-
tools=[get_timezone_by_city, get_current_time_in_timezone, get_air_quality, get_weather, final_answer],
|
| 238 |
-
prompt_templates=prompt_templates,
|
| 239 |
-
max_steps=3,
|
| 240 |
-
verbosity_level=2,
|
| 241 |
-
)
|
| 242 |
-
|
| 243 |
-
def process_input(user_input):
|
| 244 |
-
try:
|
| 245 |
-
lang = detect(user_input)
|
| 246 |
-
lang = lang if lang in ["en", "ru", "hi"] else "en"
|
| 247 |
-
agent.variables = {"lang": lang}
|
| 248 |
-
return agent.run(user_input) or "❌ Нет ответа от агента."
|
| 249 |
except Exception as e:
|
| 250 |
-
return f"❌ Ошибка: {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 251 |
|
| 252 |
if __name__ == "__main__":
|
| 253 |
gr.Interface(
|
| 254 |
fn=process_input,
|
| 255 |
inputs="text",
|
| 256 |
outputs="text",
|
| 257 |
-
title="
|
| 258 |
-
description="
|
| 259 |
-
).launch()
|
|
|
|
| 1 |
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
import datetime
|
| 3 |
import pytz
|
|
|
|
|
|
|
|
|
|
| 4 |
import requests
|
| 5 |
+
from dotenv import load_dotenv
|
| 6 |
from langdetect import detect
|
| 7 |
+
from geopy.geocoders import Nominatim
|
| 8 |
+
from timezonefinder import TimezoneFinder
|
| 9 |
+
import gradio as gr
|
| 10 |
+
|
| 11 |
+
load_dotenv()
|
| 12 |
|
|
|
|
| 13 |
def get_timezone_by_city(city: str) -> str:
|
| 14 |
"""
|
| 15 |
Get timezone for a city.
|
|
|
|
| 18 |
city (str): City name.
|
| 19 |
|
| 20 |
Returns:
|
| 21 |
+
str: Timezone or error message.
|
| 22 |
"""
|
| 23 |
try:
|
| 24 |
+
geolocator = Nominatim(user_agent="simple_bot")
|
| 25 |
+
loc = geolocator.geocode(city, language="en")
|
| 26 |
+
if not loc:
|
| 27 |
return f"❌ Город '{city}' не найден."
|
| 28 |
+
tz = TimezoneFinder().timezone_at(lat=loc.latitude, lng=loc.longitude)
|
| 29 |
+
return tz or f"❌ Часовой пояс не найден."
|
|
|
|
| 30 |
except Exception as e:
|
| 31 |
+
return f"❌ Ошибка пояса: {e}"
|
| 32 |
|
|
|
|
| 33 |
def get_current_time_in_timezone(timezone: str) -> str:
|
| 34 |
"""
|
| 35 |
+
Get local time for timezone.
|
| 36 |
|
| 37 |
Args:
|
| 38 |
timezone (str): Timezone name.
|
| 39 |
|
| 40 |
Returns:
|
| 41 |
+
str: Current time or error.
|
| 42 |
"""
|
| 43 |
try:
|
| 44 |
+
now = datetime.datetime.now(pytz.timezone(timezone))
|
| 45 |
+
return now.strftime("%Y-%m-%d %H:%M:%S")
|
| 46 |
except Exception as e:
|
| 47 |
+
return f"❌ Ошибка времени: {e}"
|
| 48 |
|
|
|
|
| 49 |
def get_air_quality(city: str, lang: str = "en") -> str:
|
| 50 |
"""
|
| 51 |
+
Air quality in city with translation.
|
| 52 |
|
| 53 |
Args:
|
| 54 |
city (str): City name.
|
| 55 |
lang (str): Language code.
|
| 56 |
|
| 57 |
Returns:
|
| 58 |
+
str: AQI info.
|
| 59 |
"""
|
| 60 |
try:
|
| 61 |
+
loc = Nominatim(user_agent="simple_bot").geocode(city, language="en")
|
| 62 |
+
if not loc:
|
|
|
|
| 63 |
return f"❌ Город '{city}' не найден."
|
| 64 |
+
key = os.environ["OPENWEATHERMAP_API_KEY"]
|
| 65 |
+
url = f"http://api.openweathermap.org/data/2.5/air_pollution?lat={loc.latitude}&lon={loc.longitude}&appid={key}"
|
| 66 |
+
data = requests.get(url).json()["list"][0]
|
| 67 |
+
aqi = data["main"]["aqi"]; c = data["components"]
|
| 68 |
+
tr = {
|
| 69 |
+
"en": ("😷 Air Quality", {1:"Good",2:"Fair",3:"Moderate",4:"Poor",5:"Very Poor"}),
|
| 70 |
+
"ru": ("😷 Качество воздуха", {1:"Хорошее",2:"Удовлетворительное",3:"Среднее",4:"Плохое",5:"Очень плохое"}),
|
| 71 |
+
"hi": ("😷 वायु गुणवत्ता", {1:"अच्छा",2:"संतोषजनक",3:"मध्यम",4:"खराब",5:"बहुत खराब"}),
|
| 72 |
+
}[lang if lang in ["en","ru","hi"] else "en"]
|
| 73 |
+
title, desc_map = tr
|
| 74 |
+
emoji = "🌱" if aqi<=2 else "😷" if aqi<=4 else "☣️"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
return (
|
| 76 |
+
f"{title}: AQI {aqi} ({desc_map[aqi]}) {emoji}\n"
|
| 77 |
+
f"PM2.5: {c['pm2_5']} µg/m³ PM10: {c['pm10']} µg/m³ CO: {c['co']} µg/m³"
|
|
|
|
|
|
|
| 78 |
)
|
| 79 |
except Exception as e:
|
| 80 |
+
return f"❌ Ошибка воздуха: {e}"
|
| 81 |
|
|
|
|
| 82 |
def get_weather(city: str, lang: str = "en") -> str:
|
| 83 |
"""
|
| 84 |
+
Weather in city with translation.
|
| 85 |
|
| 86 |
Args:
|
| 87 |
city (str): City name.
|
| 88 |
lang (str): Language code.
|
| 89 |
|
| 90 |
Returns:
|
| 91 |
+
str: Weather info.
|
| 92 |
"""
|
| 93 |
try:
|
| 94 |
+
loc = Nominatim(user_agent="simple_bot").geocode(city, language="en")
|
| 95 |
+
if not loc:
|
|
|
|
| 96 |
return f"❌ Город '{city}' не найден."
|
| 97 |
+
key = os.environ["OPENWEATHERMAP_API_KEY"]
|
| 98 |
+
url = f"http://api.openweathermap.org/data/2.5/weather?lat={loc.latitude}&lon={loc.longitude}&appid={key}&units=metric"
|
| 99 |
+
d = requests.get(url).json()
|
| 100 |
+
w = d["weather"][0]["main"]; t = d["main"]["temp"]; h = d["main"]["humidity"]
|
| 101 |
+
cfg = {
|
| 102 |
+
"en": ("🌡️ Weather", "Temperature", "Humidity",
|
| 103 |
+
{"Clear":"Clear ☀️","Clouds":"Cloudy ☁️","Rain":"Rain 🌧","Snow":"Snow ❄️","Thunderstorm":"Storm ⛈","Drizzle":"Drizzle 🌦","Mist":"Mist 🌫","Haze":"Haze 🌫"}),
|
| 104 |
+
"ru": ("🌡️ Погода", "Температура", "Влажность",
|
| 105 |
+
{"Clear":"Ясно ☀️","Clouds":"Облачно ☁️","Rain":"Дождь 🌧","Snow":"Снег ❄️","Thunderstorm":"Гроза ⛈","Drizzle":"Морось 🌦","Mist":"Туман 🌫","Haze":"Дымка 🌫"}),
|
| 106 |
+
"hi": ("🌡️ मौसम","तापमान","नमी",
|
| 107 |
+
{"Clear":"साफ ☀️","Clouds":"बादल ☁️","Rain":"बारिश 🌧","Snow":"बर्फ ❄️","Thunderstorm":"तूफान ⛈","Drizzle":"बूंदाबांदी 🌦","Mist":"कोहरा 🌫","Haze":"धुंध 🌫"}),
|
| 108 |
+
}[lang if lang in ["en","ru","hi"] else "en"]
|
| 109 |
+
title, ltemp, lhum, conds = cfg
|
| 110 |
+
desc = conds.get(w, w)
|
| 111 |
+
return f"{title}: {desc}\n{ltemp}: {t}°C {lhum}: {h}%"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
except Exception as e:
|
| 113 |
+
return f"❌ Ошибка погоды: {e}"
|
| 114 |
+
|
| 115 |
+
def process_input(user_input: str) -> str:
|
| 116 |
+
lang = detect(user_input)
|
| 117 |
+
lang = lang if lang in ["en","ru","hi"] else "en"
|
| 118 |
+
city = user_input.strip()
|
| 119 |
+
tz = get_timezone_by_city(city)
|
| 120 |
+
ct = get_current_time_in_timezone(tz) if not tz.startswith("❌") else tz
|
| 121 |
+
aq = get_air_quality(city, lang)
|
| 122 |
+
w = get_weather(city, lang)
|
| 123 |
+
# Собираем итог
|
| 124 |
+
parts = [f"🕒 Время: {ct}", aq, w]
|
| 125 |
+
return "\n\n".join(parts)
|
| 126 |
|
| 127 |
if __name__ == "__main__":
|
| 128 |
gr.Interface(
|
| 129 |
fn=process_input,
|
| 130 |
inputs="text",
|
| 131 |
outputs="text",
|
| 132 |
+
title="🌍 Городской ассистент",
|
| 133 |
+
description="Введи город — получишь время, AQI и погоду.",
|
| 134 |
+
).launch()
|