Update app.py
Browse files
app.py
CHANGED
|
@@ -10,42 +10,95 @@ client_main = InferenceClient(token=HF_TOKEN, model="meta-llama/Llama-3.1-8B-Ins
|
|
| 10 |
client_aux1 = InferenceClient(token=HF_TOKEN, model="google/flan-t5-large")
|
| 11 |
client_aux2 = InferenceClient(token=HF_TOKEN, model="facebook/bart-large-cnn")
|
| 12 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
# Função principal de resposta
|
| 14 |
def respond(message, history, system_message, max_tokens, temperature, top_p):
|
| 15 |
try:
|
| 16 |
-
# --- Passo 1: Llama 3.1 via
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
# Adiciona mensagens do histórico
|
| 21 |
-
chat.add_message("system", system_message)
|
| 22 |
for h in history:
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
# --- Passo 2: FLAN-T5 (reformulação) ---
|
| 35 |
result_aux1 = client_aux1.text_generation(
|
| 36 |
prompt=f"Reformule este texto de forma clara e concisa:\n{response_main}",
|
| 37 |
max_new_tokens=max_tokens
|
| 38 |
)
|
| 39 |
-
response_aux1 = result_aux1
|
| 40 |
|
| 41 |
# --- Passo 3: BART (resumo em 3 frases) ---
|
| 42 |
result_aux2 = client_aux2.text_generation(
|
| 43 |
prompt=f"Resuma este texto em 3 frases:\n{response_aux1}",
|
| 44 |
max_new_tokens=150
|
| 45 |
)
|
| 46 |
-
response_aux2 = result_aux2
|
| 47 |
|
| 48 |
except Exception as e:
|
|
|
|
| 49 |
response_aux2 = f"Erro ao gerar resposta: {e}"
|
| 50 |
|
| 51 |
# Atualiza histórico no formato Gradio Chatbot
|
|
|
|
| 10 |
client_aux1 = InferenceClient(token=HF_TOKEN, model="google/flan-t5-large")
|
| 11 |
client_aux2 = InferenceClient(token=HF_TOKEN, model="facebook/bart-large-cnn")
|
| 12 |
|
| 13 |
+
# Função utilitária para extrair texto gerado de objetos de resposta variados
|
| 14 |
+
def _extract_text_from_response(obj):
|
| 15 |
+
# tenta algumas formas comuns de resposta dependendo da versão do SDK/backend
|
| 16 |
+
if obj is None:
|
| 17 |
+
return ""
|
| 18 |
+
# caso: objeto com atributo 'content'
|
| 19 |
+
if hasattr(obj, "content"):
|
| 20 |
+
try:
|
| 21 |
+
return obj.content
|
| 22 |
+
except Exception:
|
| 23 |
+
pass
|
| 24 |
+
# caso: objeto com atributo 'generated_text'
|
| 25 |
+
if hasattr(obj, "generated_text"):
|
| 26 |
+
try:
|
| 27 |
+
return obj.generated_text
|
| 28 |
+
except Exception:
|
| 29 |
+
pass
|
| 30 |
+
# caso: resposta no estilo choices -> choices[0].message["content"]
|
| 31 |
+
try:
|
| 32 |
+
if hasattr(obj, "choices") and len(obj.choices) > 0:
|
| 33 |
+
choice = obj.choices[0]
|
| 34 |
+
# se for um dict-like
|
| 35 |
+
if isinstance(choice, dict) and "message" in choice and "content" in choice["message"]:
|
| 36 |
+
return choice["message"]["content"]
|
| 37 |
+
# se choice tiver atributo 'message'
|
| 38 |
+
if hasattr(choice, "message") and isinstance(choice.message, dict) and "content" in choice.message:
|
| 39 |
+
return choice.message["content"]
|
| 40 |
+
except Exception:
|
| 41 |
+
pass
|
| 42 |
+
# fallback: str()
|
| 43 |
+
return str(obj)
|
| 44 |
+
|
| 45 |
# Função principal de resposta
|
| 46 |
def respond(message, history, system_message, max_tokens, temperature, top_p):
|
| 47 |
try:
|
| 48 |
+
# --- Passo 1: Llama 3.1 via chamada stateless com lista de messages ---
|
| 49 |
+
# Monta lista de mensagens (system + histórico + user atual)
|
| 50 |
+
messages = []
|
| 51 |
+
messages.append({"role": "system", "content": system_message or ""})
|
|
|
|
|
|
|
| 52 |
for h in history:
|
| 53 |
+
# espera itens do histórico no formato {"role": "user"/"assistant", "content": "..."}
|
| 54 |
+
role = h.get("role", "user")
|
| 55 |
+
content = h.get("content", "")
|
| 56 |
+
messages.append({"role": role, "content": content})
|
| 57 |
+
messages.append({"role": "user", "content": message})
|
| 58 |
+
|
| 59 |
+
# Envia as mensagens para o chat do Llama (stateless)
|
| 60 |
+
# Observação: alguns backends aceitam send_message(messages=...), outros aceitam send_message() após add_message.
|
| 61 |
+
# Aqui tentamos enviar a lista diretamente.
|
| 62 |
+
chat_proxy = client_main.chat
|
| 63 |
+
try:
|
| 64 |
+
# tentativa principal: enviar mensagens diretamente
|
| 65 |
+
response_main_obj = chat_proxy.send_message(
|
| 66 |
+
messages=messages,
|
| 67 |
+
max_new_tokens=max_tokens,
|
| 68 |
+
temperature=temperature,
|
| 69 |
+
top_p=top_p
|
| 70 |
+
)
|
| 71 |
+
except TypeError:
|
| 72 |
+
# se a assinatura não aceitar messages=..., tentamos criar um novo chat proxy e adicionar mensagens manualmente
|
| 73 |
+
# (nem todos os ProxyClientChat expõem criação limpa; então adicionamos e depois geramos)
|
| 74 |
+
# Este bloco tenta usar add_message() sequencialmente.
|
| 75 |
+
# Nota: se add_message falhar, cairá no except geral abaixo.
|
| 76 |
+
for msg_item in messages:
|
| 77 |
+
chat_proxy.add_message(msg_item["role"], msg_item["content"])
|
| 78 |
+
response_main_obj = chat_proxy.send_message(
|
| 79 |
+
max_new_tokens=max_tokens,
|
| 80 |
+
temperature=temperature,
|
| 81 |
+
top_p=top_p
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
response_main = _extract_text_from_response(response_main_obj)
|
| 85 |
|
| 86 |
# --- Passo 2: FLAN-T5 (reformulação) ---
|
| 87 |
result_aux1 = client_aux1.text_generation(
|
| 88 |
prompt=f"Reformule este texto de forma clara e concisa:\n{response_main}",
|
| 89 |
max_new_tokens=max_tokens
|
| 90 |
)
|
| 91 |
+
response_aux1 = _extract_text_from_response(result_aux1)
|
| 92 |
|
| 93 |
# --- Passo 3: BART (resumo em 3 frases) ---
|
| 94 |
result_aux2 = client_aux2.text_generation(
|
| 95 |
prompt=f"Resuma este texto em 3 frases:\n{response_aux1}",
|
| 96 |
max_new_tokens=150
|
| 97 |
)
|
| 98 |
+
response_aux2 = _extract_text_from_response(result_aux2)
|
| 99 |
|
| 100 |
except Exception as e:
|
| 101 |
+
# Mensagem de erro amigável para o usuário (mantemos o traceback curto)
|
| 102 |
response_aux2 = f"Erro ao gerar resposta: {e}"
|
| 103 |
|
| 104 |
# Atualiza histórico no formato Gradio Chatbot
|