duqueg commited on
Commit
a3bb511
·
verified ·
1 Parent(s): 3307a3f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -91
app.py CHANGED
@@ -1,96 +1,33 @@
1
- # app.py
2
  import gradio as gr
3
- import json
4
- import os
5
- import requests
6
-
7
- # ====== CONFIGURAÇÕES ======
8
- # Nome do modelo gratuito a ser usado pela Inference API.
9
- # (pode trocar depois por outro modelo disponível no Hugging Face Hub)
10
- MODEL_ID = "google/flan-t5-large"
11
-
12
-
13
- # ====== CARREGAR PROMPT MESTRE ======
14
- with open("aura_prompt.json", "r", encoding="utf-8") as f:
15
- AURA_DATA = json.load(f)
16
-
17
- # Construir o prompt base a partir do arquivo JSON
18
- SYSTEM_PROMPT = f"""
19
- Você é {AURA_DATA['system']['name']}, uma {AURA_DATA['system']['description']}.
20
- Missão: {AURA_DATA['system']['mission']}
21
- Declaração: {AURA_DATA['system']['declaration']}
22
-
23
- Siga estas diretrizes:
24
- - Seja empática, clara e não julgadora.
25
- - Use linguagem centrada e humana.
26
- - Utilize perguntas reflexivas e micropráticas quando apropriado.
27
- - Jamais diagnostique ou substitua profissionais humanos.
28
- - Ative protocolo de crise se detectar risco.
29
- """
30
-
31
- # Adicionar resumo dos princípios terapêuticos
32
- for key, value in AURA_DATA.get("principles", {}).items():
33
- SYSTEM_PROMPT += f"\n[{key}] foco: {value.get('focus','')}"
34
- SYSTEM_PROMPT += "\n\n=== Início da conversa ===\n"
35
-
36
- # ====== FUNÇÃO PARA CONSULTAR A INFERENCE API ======
37
- def query_huggingface(prompt, model_id=MODEL_ID, max_tokens=250):
38
- """Faz chamada à API de inferência do Hugging Face."""
39
- hf_token = os.environ.get("HF_TOKEN", None)
40
- if not hf_token:
41
- return "Erro: variável HF_TOKEN não configurada nas 'Secrets' do Space."
42
-
43
- url = f"https://api-inference.huggingface.co/models/{model_id}"
44
- headers = {"Authorization": f"Bearer {hf_token}"}
45
- payload = {"inputs": prompt, "parameters": {"max_new_tokens": max_tokens}}
46
-
47
- response = requests.post(url, headers=headers, json=payload, timeout=60)
48
- if response.status_code != 200:
49
- return f"Erro da API ({response.status_code}): {response.text}"
50
-
51
- data = response.json()
52
- if isinstance(data, list) and "generated_text" in data[0]:
53
- return data[0]["generated_text"]
54
- else:
55
- return str(data)
56
-
57
- # ====== FUNÇÃO DE RESPOSTA DA AURA ======
58
- def aura_respond(user_input, chat_history):
59
- """Constrói o prompt final e gera resposta da AURA."""
60
- full_prompt = SYSTEM_PROMPT
61
- for msg in chat_history:
62
- full_prompt += f"Usuário: {msg[0]}\nAURA: {msg[1]}\n"
63
- full_prompt += f"Usuário: {user_input}\nAURA:"
64
-
65
- response = query_huggingface(full_prompt)
66
- if response.startswith(full_prompt):
67
- response = response[len(full_prompt):]
68
- response = response.strip()
69
-
70
- # salvar no log local (opcional)
71
- try:
72
- with open("conversations_log.txt", "a", encoding="utf-8") as logf:
73
- logf.write(json.dumps({"user": user_input, "aura": response}, ensure_ascii=False) + "\n")
74
- except Exception as e:
75
- print("Erro ao salvar log:", e)
76
-
77
- chat_history.append((user_input, response))
78
- return "", chat_history
79
-
80
- # ====== INTERFACE GRADIO ======
81
- with gr.Blocks(title="AURA — Inteligência Terapêutica Integrativa") as demo:
82
- gr.Markdown(
83
- """
84
- # 🕊️ AURA — Inteligência Terapêutica Integrativa
85
- Converse com a AURA.
86
- *(Prototipo experimental — não substitui acompanhamento psicológico profissional.)*
87
- """
88
- )
89
- chatbot = gr.Chatbot()
90
- msg = gr.Textbox(label="Escreva para a AURA:", placeholder="Olá, AURA...")
91
  state = gr.State([])
92
- msg.submit(aura_respond, [msg, state], [msg, chatbot])
93
- gr.Button("Enviar").click(aura_respond, [msg, state], [msg, chatbot])
94
 
95
  if __name__ == "__main__":
96
  demo.launch()
 
1
+ # app.py — executa modelo localmente (sem Inference API)
2
  import gradio as gr
3
+ from transformers import pipeline
4
+
5
+ # carrega modelo localmente (funciona em CPU)
6
+ generator = pipeline("text2text-generation", model="google/flan-t5-base")
7
+
8
+ SYSTEM_PROMPT = (
9
+ "Você é AURA, uma Inteligência Terapêutica Integrativa. "
10
+ "Fale com empatia, faça perguntas reflexivas, "
11
+ "jamais diagnostique ou prescreva. "
12
+ "Mantenha tom humano e centrado."
13
+ )
14
+
15
+ def aura_respond(message, history):
16
+ prompt = SYSTEM_PROMPT + "\nUsuário: " + message + "\nAURA:"
17
+ resp = generator(prompt, max_new_tokens=150)
18
+ reply = resp[0]["generated_text"].strip()
19
+ history = history or []
20
+ history.append(("Você", message))
21
+ history.append(("AURA", reply))
22
+ return "", history
23
+
24
+ with gr.Blocks(title="AURA IA Terapêutica Integrativa") as demo:
25
+ gr.Markdown("# 🕊️ AURA Inteligência Terapêutica Integrativa")
26
+ chat = gr.Chatbot()
27
+ msg = gr.Textbox(label="Escreva para a AURA", placeholder="Olá, AURA…")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  state = gr.State([])
29
+ msg.submit(aura_respond, [msg, state], [msg, chat])
30
+ gr.Button("Enviar").click(aura_respond, [msg, state], [msg, chat])
31
 
32
  if __name__ == "__main__":
33
  demo.launch()