Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,64 +1,140 @@
|
|
1 |
import gradio as gr
|
2 |
-
from
|
3 |
-
|
4 |
-
|
5 |
-
For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
|
6 |
-
"""
|
7 |
-
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
|
8 |
-
|
9 |
-
|
10 |
-
def respond(
|
11 |
-
message,
|
12 |
-
history: list[tuple[str, str]],
|
13 |
-
system_message,
|
14 |
-
max_tokens,
|
15 |
-
temperature,
|
16 |
-
top_p,
|
17 |
-
):
|
18 |
-
messages = [{"role": "system", "content": system_message}]
|
19 |
-
|
20 |
-
for val in history:
|
21 |
-
if val[0]:
|
22 |
-
messages.append({"role": "user", "content": val[0]})
|
23 |
-
if val[1]:
|
24 |
-
messages.append({"role": "assistant", "content": val[1]})
|
25 |
-
|
26 |
-
messages.append({"role": "user", "content": message})
|
27 |
-
|
28 |
-
response = ""
|
29 |
-
|
30 |
-
for message in client.chat_completion(
|
31 |
-
messages,
|
32 |
-
max_tokens=max_tokens,
|
33 |
-
stream=True,
|
34 |
-
temperature=temperature,
|
35 |
-
top_p=top_p,
|
36 |
-
):
|
37 |
-
token = message.choices[0].delta.content
|
38 |
-
|
39 |
-
response += token
|
40 |
-
yield response
|
41 |
-
|
42 |
-
|
43 |
-
"""
|
44 |
-
For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
|
45 |
-
"""
|
46 |
-
demo = gr.ChatInterface(
|
47 |
-
respond,
|
48 |
-
additional_inputs=[
|
49 |
-
gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
|
50 |
-
gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
|
51 |
-
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
|
52 |
-
gr.Slider(
|
53 |
-
minimum=0.1,
|
54 |
-
maximum=1.0,
|
55 |
-
value=0.95,
|
56 |
-
step=0.05,
|
57 |
-
label="Top-p (nucleus sampling)",
|
58 |
-
),
|
59 |
-
],
|
60 |
-
)
|
61 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
62 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
63 |
if __name__ == "__main__":
|
64 |
-
|
|
|
|
1 |
import gradio as gr
|
2 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
|
3 |
+
import json
|
4 |
+
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
5 |
|
6 |
+
class RevalidaBot:
|
7 |
+
def __init__(self):
|
8 |
+
# Inicializa o modelo
|
9 |
+
self.model_id = "meta-llama/Llama-2-7b-chat-hf"
|
10 |
+
self.tokenizer = AutoTokenizer.from_pretrained(self.model_id)
|
11 |
+
self.pipeline = pipeline(
|
12 |
+
"text-generation",
|
13 |
+
model=self.model_id,
|
14 |
+
tokenizer=self.tokenizer,
|
15 |
+
max_length=500
|
16 |
+
)
|
17 |
+
|
18 |
+
# Carrega a base de conhecimento
|
19 |
+
self.knowledge = self.load_knowledge()
|
20 |
+
|
21 |
+
# Define os comandos disponíveis
|
22 |
+
self.commands = {
|
23 |
+
"/start": self.start_command,
|
24 |
+
"/estudo": self.study_mode,
|
25 |
+
"/caso": self.clinical_case,
|
26 |
+
"/questao": self.question_mode,
|
27 |
+
"/ajuda": self.help_command
|
28 |
+
}
|
29 |
|
30 |
+
def load_knowledge(self):
|
31 |
+
"""Carrega base de conhecimento do Revalida"""
|
32 |
+
try:
|
33 |
+
if os.path.exists("knowledge_base.json"):
|
34 |
+
with open("knowledge_base.json", "r", encoding="utf-8") as f:
|
35 |
+
return json.load(f)
|
36 |
+
return {}
|
37 |
+
except Exception as e:
|
38 |
+
print(f"Erro ao carregar conhecimento: {e}")
|
39 |
+
return {}
|
40 |
+
|
41 |
+
def process_message(self, message, history):
|
42 |
+
"""Processa mensagens recebidas"""
|
43 |
+
try:
|
44 |
+
# Verifica se é um comando
|
45 |
+
if message.startswith("/"):
|
46 |
+
command = message.split()[0]
|
47 |
+
if command in self.commands:
|
48 |
+
return self.commands[command](message)
|
49 |
+
return "Comando não reconhecido. Use /ajuda para ver os comandos disponíveis."
|
50 |
+
|
51 |
+
# Processa pergunta normal
|
52 |
+
return self.generate_response(message, history)
|
53 |
+
|
54 |
+
except Exception as e:
|
55 |
+
return f"Desculpe, ocorreu um erro: {str(e)}"
|
56 |
+
|
57 |
+
def generate_response(self, message, history):
|
58 |
+
"""Gera resposta para perguntas sobre o Revalida"""
|
59 |
+
prompt = f"""
|
60 |
+
Pergunta sobre Revalida: {message}
|
61 |
+
|
62 |
+
Como assistente especializado em Revalida, forneça uma resposta:
|
63 |
+
1. Objetiva e direta
|
64 |
+
2. Baseada em evidências
|
65 |
+
3. Focada no exame
|
66 |
+
4. Com exemplos práticos quando relevante
|
67 |
+
"""
|
68 |
+
|
69 |
+
response = self.pipeline(prompt, max_length=500)[0]['generated_text']
|
70 |
+
return response
|
71 |
+
|
72 |
+
# Comandos
|
73 |
+
def start_command(self, _):
|
74 |
+
return """🏥 Bem-vindo ao Assistente Revalida!
|
75 |
+
|
76 |
+
Comandos disponíveis:
|
77 |
+
/estudo - Modo estudo direcionado
|
78 |
+
/caso - Gerar caso clínico
|
79 |
+
/questao - Questão exemplo
|
80 |
+
/ajuda - Ver ajuda
|
81 |
+
|
82 |
+
Digite sua dúvida a qualquer momento!"""
|
83 |
+
|
84 |
+
def study_mode(self, message):
|
85 |
+
topic = message.replace("/estudo", "").strip()
|
86 |
+
if not topic:
|
87 |
+
return "Por favor, especifique o tópico após /estudo. Exemplo: /estudo clínica médica"
|
88 |
+
|
89 |
+
prompt = f"Prepare um resumo focado para o Revalida sobre: {topic}"
|
90 |
+
return self.generate_response(prompt, None)
|
91 |
+
|
92 |
+
def clinical_case(self, _):
|
93 |
+
prompt = "Gere um caso clínico objetivo para estudo do Revalida"
|
94 |
+
return self.generate_response(prompt, None)
|
95 |
+
|
96 |
+
def question_mode(self, _):
|
97 |
+
prompt = "Crie uma questão de múltipla escolha no estilo Revalida"
|
98 |
+
return self.generate_response(prompt, None)
|
99 |
+
|
100 |
+
def help_command(self, _):
|
101 |
+
return """📚 Comandos do Assistente Revalida:
|
102 |
+
|
103 |
+
/start - Iniciar/Reiniciar
|
104 |
+
/estudo [tópico] - Estudar um tópico específico
|
105 |
+
/caso - Gerar caso clínico para estudo
|
106 |
+
/questao - Gerar questão exemplo
|
107 |
+
/ajuda - Ver esta mensagem
|
108 |
+
|
109 |
+
💡 Dicas:
|
110 |
+
- Digite sua dúvida normalmente para perguntar
|
111 |
+
- Seja específico nas perguntas
|
112 |
+
- Use os comandos para funções especiais"""
|
113 |
+
|
114 |
+
def create_interface():
|
115 |
+
"""Cria a interface Gradio"""
|
116 |
+
bot = RevalidaBot()
|
117 |
+
|
118 |
+
with gr.Blocks(title="Assistente Revalida") as interface:
|
119 |
+
gr.Markdown("# 🏥 Assistente Revalida")
|
120 |
+
gr.Markdown("### Seu companheiro de estudos para o Revalida")
|
121 |
+
|
122 |
+
chatbot = gr.Chatbot()
|
123 |
+
msg = gr.Textbox(
|
124 |
+
placeholder="Digite sua mensagem ou comando aqui...",
|
125 |
+
show_label=False
|
126 |
+
)
|
127 |
+
clear = gr.ClearButton([msg, chatbot])
|
128 |
+
|
129 |
+
msg.submit(
|
130 |
+
bot.process_message,
|
131 |
+
[msg, chatbot],
|
132 |
+
[chatbot]
|
133 |
+
)
|
134 |
+
|
135 |
+
return interface
|
136 |
+
|
137 |
+
# Inicia a interface
|
138 |
if __name__ == "__main__":
|
139 |
+
interface = create_interface()
|
140 |
+
interface.launch()
|