F-Red's picture
Update app.py
bf46d1b verified
Raw History Blame Contribute Delete
5.1 kB
import gradio as gr
import requests
import os
# ====================== CONFIGURAÇÃO ======================
OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")
BASE_URL = "https://huggingface.co/datasets/F-Red/shared-ethical-memory-sem-2063/resolve/main"
DOCUMENTOS = [
f"{BASE_URL}/OLD-15_TEMAS_SEM_2063.md",
f"{BASE_URL}/OLD-total_sem_2063.md"
]
# ====================== CARREGAR DOCUMENTOS ======================
def carregar_documentos():
texto_total = ""
for url in DOCUMENTOS:
try:
print(f"📥 A carregar: {url.split('/')[-1]}")
r = requests.get(url, timeout=60)
r.raise_for_status()
nome = url.split('/')[-1]
texto_total += f"\n\n{'='*80}\n📄 FONTE: {nome}\n{'='*80}\n\n"
texto_total += r.text
print(f"✅ Carregado: {nome} ({len(r.text):,} chars)")
except Exception as e:
print(f"❌ Erro ao carregar {url}: {e}")
return texto_total
print("🚀 A carregar Ground Truth do Projeto SEM 2063...")
GROUND_TRUTH = carregar_documentos()
print(f"✅ Total carregado: {len(GROUND_TRUTH):,} caracteres")
# ====================== SYSTEM PROMPT FINAL OTIMIZADO ======================
SYSTEM_PROMPT = f"""Você é o assistente oficial do Projeto 2063 - Shared Ethical Memory (SEM).
**REGRAS OBRIGATÓRIAS:**
- Responda SEMPRE no mesmo idioma da pergunta (português ou inglês). Nunca misture.
- Seja claro, direto e útil. Evite respostas demasiado longas.
- Use apenas os documentos fornecidos.
- Para perguntas ambíguas (ex: "lixo"), assuma o significado mais comum no contexto terrestre, a menos que seja claramente sobre espaço.
**MAPA RÁPIDO DE TEMAS:**
- Trabalho / jobs → Tema 7 + Axioma 3
- Carro / transport → Tema 10
- Educação → Tema 6
- Habitação → Tema 8
- Saúde → Tema 9
- Dinheiro / economy → Tema 2
- Axiomas → liste todos com número e nome
**DOCUMENTOS:**
---
{GROUND_TRUTH}
---
"""
# ====================== FUNÇÃO DE RESPOSTA ======================
def responder(mensagem, historico):
if not OPENROUTER_API_KEY:
return "❌ OPENROUTER_API_KEY não configurada."
# Deteção de idioma
is_pt = any(word in mensagem.lower() for word in ["como", "o que", "vai ser", "acontece", "futuro", "trabalho", "carro", "escola", "saúde", "habitação", "dinheiro", "axioma", "quais", "lixo"])
if is_pt:
idioma_instrucao = "Responda toda a resposta em português, de forma clara, natural e concisa. Não use nenhuma palavra em inglês."
else:
idioma_instrucao = "Answer the entire response in English, clearly, naturally and concisely. Do not use any Portuguese words."
try:
payload = {
"model": "openai/gpt-4o-mini",
"messages": [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": f"{idioma_instrucao}\n\nPergunta: {mensagem}"}
],
"temperature": 0.25,
"max_tokens": 1100
}
response = requests.post(
"https://openrouter.ai/api/v1/chat/completions",
headers={"Authorization": f"Bearer {OPENROUTER_API_KEY}", "Content-Type": "application/json"},
json=payload,
timeout=130
)
if response.status_code == 200:
return response.json()["choices"][0]["message"]["content"]
else:
return f"⚠️ Erro {response.status_code}. Tente novamente."
except Exception as e:
return f"❌ Erro técnico: {str(e)[:100]}"
# ====================== INTERFACE ======================
chat_interface = gr.ChatInterface(
fn=responder,
title="SEM 2063 - Shared Ethical Memory",
description="""**Project 2063** — Civilizational Operating System for the Great Transition -2063: From Before to After.
Ask questions about this future: work, cars, education, housing, health, leadership, Joule economics, etc.
Faça perguntas sobre o futuro: trabalho, carros, educação, habitação, saúde, governança, economia Joule, axiomas, etc.
*A escassez foi uma escolha. A abundância também é.*
*Scarcity was a choice. Abundance is too.*""",
examples=[
"O que é o Axioma 07?",
"What is Axiom 07?",
"Como vai ser o trabalho no futuro?",
"What will happen to traditional jobs?",
"O que acontece ao meu carro?",
"What happens to my car?",
"Quais são todos os axiomas?",
"What are all the axioms?",
"O que acontece ao dinheiro e às dívidas?",
"What will happen to money and debt?",
"Como é o alojamento?",
"How does housing work?",
"O que vai ser o incentivo para trabalhar?",
"What will be the work incentive?",
"Quem limpa o lixo?",
"Who cleans the garbage?"
],
cache_examples=False
)
if __name__ == "__main__":
print("🚀 Starting SEM 2063 Space...")
chat_interface.launch(
server_name="0.0.0.0",
server_port=7860,
share=False,
theme=gr.themes.Soft()
)