aldohenrique commited on
Commit
3153e8a
·
verified ·
1 Parent(s): 11dde31

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +76 -27
app.py CHANGED
@@ -9,16 +9,18 @@ HF_TOKEN = os.getenv("HF_TOKEN")
9
  if not HF_TOKEN:
10
  raise ValueError("Token HF_TOKEN não encontrado nas variáveis de ambiente")
11
 
12
- # Modelos disponíveis via API (escolha um que funcione bem em português)
13
  MODELS = {
14
- "qwen2.5-7b": "Qwen/Qwen2.5-7B-Instruct",
15
- "llama3.1-8b": "meta-llama/Llama-3.1-8B-Instruct",
16
- "mistral-7b": "mistralai/Mistral-7B-Instruct-v0.3",
17
- "gemma2-9b": "google/gemma-2-9b-it"
 
 
18
  }
19
 
20
- # Modelo padrão
21
- DEFAULT_MODEL = MODELS["qwen2.5-7b"]
22
 
23
  class HuggingFaceAPIClient:
24
  def __init__(self, token: str):
@@ -69,21 +71,46 @@ class HuggingFaceAPIClient:
69
  "top_p": 0.9,
70
  "do_sample": True,
71
  "return_full_text": False
 
 
 
 
72
  }
73
  }
74
 
75
  try:
76
- response = requests.post(url, headers=self.headers, json=payload, timeout=30)
77
 
78
  if response.status_code == 200:
79
  result = response.json()
80
  if isinstance(result, list) and len(result) > 0:
81
- return result[0].get("generated_text", "Resposta vazia")
82
- else:
83
- return "Formato de resposta inesperado"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  else:
85
- return f"Erro HTTP {response.status_code}: {response.text}"
86
 
 
 
87
  except Exception as e:
88
  return f"Erro na requisição: {str(e)}"
89
 
@@ -137,17 +164,39 @@ def responder_como_aldo(pergunta: str, modelo_escolhido: str = "qwen2.5-7b") ->
137
  except Exception as e:
138
  return f"Erro ao processar sua pergunta: {str(e)}"
139
 
140
- def testar_conexao():
141
- """Testa se a API está funcionando"""
142
  try:
143
- test_response = api_client.query_model(
144
- DEFAULT_MODEL,
145
- [{"role": "user", "content": "Olá, apenas responda 'Conexão OK'"}],
146
- max_tokens=50
147
- )
148
- return f"✅ Conexão OK: {test_response[:100]}..."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
149
  except Exception as e:
150
- return f"❌ Erro na conexão: {str(e)}"
 
 
 
 
 
 
 
 
151
 
152
  # Interface Gradio
153
  with gr.Blocks(title="Dr. Aldo Henrique - API Externa", theme=gr.themes.Soft()) as interface:
@@ -172,7 +221,7 @@ with gr.Blocks(title="Dr. Aldo Henrique - API Externa", theme=gr.themes.Soft())
172
 
173
  with gr.Row():
174
  botao_perguntar = gr.Button("🤔 Perguntar", variant="primary")
175
- botao_testar = gr.Button("🔍 Testar Conexão", variant="secondary")
176
 
177
  with gr.Column(scale=4):
178
  saida = gr.Textbox(
@@ -184,11 +233,11 @@ with gr.Blocks(title="Dr. Aldo Henrique - API Externa", theme=gr.themes.Soft())
184
  # Exemplos
185
  gr.Examples(
186
  examples=[
187
- ["Como implementar uma lista ligada em C?", "qwen2.5-7b"],
188
- ["Qual a diferença entre == e equals() em Java?", "qwen2.5-7b"],
189
- ["Como funciona o machine learning?", "llama3.1-8b"],
190
  ["Explique os conceitos de HTML, CSS e JavaScript", "mistral-7b"],
191
- ["O que são algoritmos de ordenação e qual é mais eficiente?", "gemma2-9b"]
192
  ],
193
  inputs=[entrada, modelo_select]
194
  )
@@ -208,7 +257,7 @@ with gr.Blocks(title="Dr. Aldo Henrique - API Externa", theme=gr.themes.Soft())
208
  )
209
 
210
  botao_testar.click(
211
- fn=testar_conexao,
212
  outputs=status_api
213
  ).then(
214
  lambda: gr.update(visible=True),
 
9
  if not HF_TOKEN:
10
  raise ValueError("Token HF_TOKEN não encontrado nas variáveis de ambiente")
11
 
12
+ # Modelos disponíveis via API (testados e funcionais)
13
  MODELS = {
14
+ "qwen2.5-3b": "Qwen/Qwen2.5-3B-Instruct",
15
+ "qwen2.5-1.5b": "Qwen/Qwen2.5-1.5B-Instruct",
16
+ "phi3-mini": "microsoft/Phi-3-mini-4k-instruct",
17
+ "llama3.2-3b": "meta-llama/Llama-3.2-3B-Instruct",
18
+ "gemma2-2b": "google/gemma-2-2b-it",
19
+ "mistral-7b": "mistralai/Mistral-7B-Instruct-v0.1"
20
  }
21
 
22
+ # Modelo padrão (mais confiável)
23
+ DEFAULT_MODEL = MODELS["qwen2.5-3b"]
24
 
25
  class HuggingFaceAPIClient:
26
  def __init__(self, token: str):
 
71
  "top_p": 0.9,
72
  "do_sample": True,
73
  "return_full_text": False
74
+ },
75
+ "options": {
76
+ "wait_for_model": True, # Espera modelo carregar
77
+ "use_cache": False
78
  }
79
  }
80
 
81
  try:
82
+ response = requests.post(url, headers=self.headers, json=payload, timeout=60)
83
 
84
  if response.status_code == 200:
85
  result = response.json()
86
  if isinstance(result, list) and len(result) > 0:
87
+ generated_text = result[0].get("generated_text", "")
88
+ # Limpa o texto gerado
89
+ if generated_text:
90
+ # Remove o prompt original da resposta
91
+ if "Assistente: " in generated_text:
92
+ parts = generated_text.split("Assistente: ")
93
+ if len(parts) > 1:
94
+ return parts[-1].strip()
95
+ return generated_text.strip()
96
+ return "Resposta vazia"
97
+ elif isinstance(result, dict):
98
+ if "error" in result:
99
+ return f"Erro do modelo: {result['error']}"
100
+ elif "generated_text" in result:
101
+ return result["generated_text"].strip()
102
+ return "Formato de resposta inesperado"
103
+ elif response.status_code == 404:
104
+ return f"❌ Modelo '{model_name}' não encontrado. Tente outro modelo."
105
+ elif response.status_code == 503:
106
+ return "⏳ Modelo carregando... Aguarde alguns segundos e tente novamente."
107
+ elif response.status_code == 429:
108
+ return "⚠️ Muitas requisições. Aguarde um momento antes de tentar novamente."
109
  else:
110
+ return f"Erro HTTP {response.status_code}: {response.text[:200]}..."
111
 
112
+ except requests.Timeout:
113
+ return "⏰ Timeout - Modelo demorou muito para responder. Tente novamente."
114
  except Exception as e:
115
  return f"Erro na requisição: {str(e)}"
116
 
 
164
  except Exception as e:
165
  return f"Erro ao processar sua pergunta: {str(e)}"
166
 
167
+ def verificar_modelo_disponivel(model_name: str) -> str:
168
+ """Verifica se um modelo está disponível na API"""
169
  try:
170
+ url = f"https://api-inference.huggingface.co/models/{model_name}"
171
+ headers = {"Authorization": f"Bearer {HF_TOKEN}"}
172
+
173
+ # Teste simples
174
+ payload = {
175
+ "inputs": "Hello",
176
+ "parameters": {"max_new_tokens": 5}
177
+ }
178
+
179
+ response = requests.post(url, headers=headers, json=payload, timeout=10)
180
+
181
+ if response.status_code == 200:
182
+ return "✅ Disponível"
183
+ elif response.status_code == 404:
184
+ return "❌ Não encontrado"
185
+ elif response.status_code == 503:
186
+ return "⏳ Carregando..."
187
+ else:
188
+ return f"⚠️ Status {response.status_code}"
189
+
190
  except Exception as e:
191
+ return f"❌ Erro: {str(e)[:50]}..."
192
+
193
+ def testar_todos_modelos():
194
+ """Testa todos os modelos disponíveis"""
195
+ resultados = []
196
+ for nome, modelo in MODELS.items():
197
+ status = verificar_modelo_disponivel(modelo)
198
+ resultados.append(f"{nome}: {status}")
199
+ return "\n".join(resultados)
200
 
201
  # Interface Gradio
202
  with gr.Blocks(title="Dr. Aldo Henrique - API Externa", theme=gr.themes.Soft()) as interface:
 
221
 
222
  with gr.Row():
223
  botao_perguntar = gr.Button("🤔 Perguntar", variant="primary")
224
+ botao_testar = gr.Button("🔍 Testar Modelos", variant="secondary")
225
 
226
  with gr.Column(scale=4):
227
  saida = gr.Textbox(
 
233
  # Exemplos
234
  gr.Examples(
235
  examples=[
236
+ ["Como implementar uma lista ligada em C?", "qwen2.5-3b"],
237
+ ["Qual a diferença entre == e equals() em Java?", "phi3-mini"],
238
+ ["Como funciona o machine learning?", "llama3.2-3b"],
239
  ["Explique os conceitos de HTML, CSS e JavaScript", "mistral-7b"],
240
+ ["O que são algoritmos de ordenação e qual é mais eficiente?", "gemma2-2b"]
241
  ],
242
  inputs=[entrada, modelo_select]
243
  )
 
257
  )
258
 
259
  botao_testar.click(
260
+ fn=testar_todos_modelos,
261
  outputs=status_api
262
  ).then(
263
  lambda: gr.update(visible=True),