Silver1234 commited on
Commit
4428d24
·
verified ·
1 Parent(s): 63579f1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -27
app.py CHANGED
@@ -1,10 +1,3 @@
1
- # -*- coding: utf-8 -*-
2
- """weather-chatbot.ipynb
3
- Automatically generated by Colab.
4
- Original file is located at
5
- https://colab.research.google.com/drive/1tmn58n_sHGiBqvfBZoLx_j6-anwHaTb4
6
- """
7
-
8
  # Commented out IPython magic to ensure Python compatibility.
9
  # %pip install llama-index-llms-google-genai llama-index
10
  # %pip install requests
@@ -22,49 +15,56 @@ GEMINI_KEY = os.getenv("GEMINI_KEY")
22
  if not OPENWEATHER_API_KEY or not GEMINI_KEY:
23
  raise RuntimeError("Chaves de API não configuradas. Defina as secrets no Hugging Face Spaces.")
24
 
 
25
  llm = Gemini(
26
  model="models/gemini-2.5-flash",
27
  api_key=GEMINI_KEY
28
  )
29
 
30
- # --- Função auxiliar: buscar clima ---
31
- def get_weather(city: str, lang="pt") -> str:
32
  try:
33
- url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={OPENWEATHER_API_KEY}&units=metric&lang={lang}"
34
- response = requests.get(url)
35
- data = response.json()
36
-
37
  if data.get("cod") != 200:
38
- return f"Não consegui encontrar o clima para {city}."
39
-
 
40
  desc = data["weather"][0]["description"]
41
  temp = data["main"]["temp"]
42
  feels = data["main"]["feels_like"]
43
- country = data["sys"]["country"]
44
 
45
- # latitude e longitude -> buscar estado
46
  lat = data["coord"]["lat"]
47
  lon = data["coord"]["lon"]
48
 
49
- # Chamada reversa para obter estado/região
50
  geo_url = f"http://api.openweathermap.org/geo/1.0/reverse?lat={lat}&lon={lon}&limit=1&appid={OPENWEATHER_API_KEY}"
51
  geo_data = requests.get(geo_url).json()
52
- state = geo_data[0].get("state", "Desconhecido")
53
-
 
54
  return (
55
- f"O clima em {city} ({state}, {country}) é {desc}, "
56
  f"com temperatura de {temp}°C (sensação térmica de {feels}°C)."
57
  )
58
  except Exception as e:
59
  return f"Erro ao obter o clima: {e}"
60
 
 
 
 
61
  def chat_bot(user_input, historico):
62
  cidade = user_input.strip()
63
- clima = get_weather(cidade)
64
 
65
- messages = [
 
66
  ChatMessage(
67
- role="system",
68
  content= f"O usuário pediu o clima no seu estado na resposta: {user_input}. "
69
  f"A informação do clima é: {clima}. Responda de forma natural e educada, "
70
  f"citando todas as informações obtidas do clima. Após isso recomende ao "
@@ -72,9 +72,9 @@ def chat_bot(user_input, historico):
72
  f"baseando-se nas informações obtidas do clima.")
73
  ]
74
 
75
- response = llm.chat(messages)
76
- bot_response = response.message.content
77
- return bot_response
78
 
79
  def criar_interface():
80
  chat = gr.ChatInterface(
 
 
 
 
 
 
 
 
1
  # Commented out IPython magic to ensure Python compatibility.
2
  # %pip install llama-index-llms-google-genai llama-index
3
  # %pip install requests
 
15
  if not OPENWEATHER_API_KEY or not GEMINI_KEY:
16
  raise RuntimeError("Chaves de API não configuradas. Defina as secrets no Hugging Face Spaces.")
17
 
18
+ # Inicia a llm
19
  llm = Gemini(
20
  model="models/gemini-2.5-flash",
21
  api_key=GEMINI_KEY
22
  )
23
 
24
+ # Buscar clima
25
+ def buscar_clima(cidade: str, lang="pt") -> str:
26
  try:
27
+ url = f"http://api.openweathermap.org/data/2.5/weather?q={cidade}&appid={OPENWEATHER_API_KEY}&units=metric&lang={lang}"
28
+ resposta = requests.get(url)
29
+ data = resposta.json()
30
+
31
  if data.get("cod") != 200:
32
+ return f"Não consegui encontrar o clima para {cidade}."
33
+
34
+ # Obter dados do clima
35
  desc = data["weather"][0]["description"]
36
  temp = data["main"]["temp"]
37
  feels = data["main"]["feels_like"]
38
+ pais = data["sys"]["country"]
39
 
40
+ # obter latitude e longitude
41
  lat = data["coord"]["lat"]
42
  lon = data["coord"]["lon"]
43
 
44
+ # Chamada reversa para obter o estado
45
  geo_url = f"http://api.openweathermap.org/geo/1.0/reverse?lat={lat}&lon={lon}&limit=1&appid={OPENWEATHER_API_KEY}"
46
  geo_data = requests.get(geo_url).json()
47
+ estado = geo_data[0].get("state", "Desconhecido")
48
+
49
+ # Retorna estas informações para a llm interpretar
50
  return (
51
+ f"O clima em {cidade} ({estado}, {pais}) é {desc}, "
52
  f"com temperatura de {temp}°C (sensação térmica de {feels}°C)."
53
  )
54
  except Exception as e:
55
  return f"Erro ao obter o clima: {e}"
56
 
57
+
58
+
59
+ # Função que cria o comportamento do bot
60
  def chat_bot(user_input, historico):
61
  cidade = user_input.strip()
62
+ clima = buscar_clima(cidade)
63
 
64
+ # Prompt de instrução de comportamento para o bot
65
+ mensagens = [
66
  ChatMessage(
67
+ role="system",
68
  content= f"O usuário pediu o clima no seu estado na resposta: {user_input}. "
69
  f"A informação do clima é: {clima}. Responda de forma natural e educada, "
70
  f"citando todas as informações obtidas do clima. Após isso recomende ao "
 
72
  f"baseando-se nas informações obtidas do clima.")
73
  ]
74
 
75
+ resposta = llm.chat(mensagens)
76
+ resposta_bot = resposta.message.content
77
+ return resposta_bot
78
 
79
  def criar_interface():
80
  chat = gr.ChatInterface(