sage-two-visual / interface_sage_gradio.py
Felipe Maya Muniz
files 2
2c75f8e
# --- interface_sage_gradio.py ---
import gradio as gr
import numpy as np
import replicate
from sentence_transformers import SentenceTransformer
from transformers import pipeline
import os
import json
# === Configurações ===
replicate_client = replicate.Client(api_token=os.environ["REPLICATE_API_TOKEN"])
EMBEDDING_MODEL = SentenceTransformer("all-MiniLM-L6-v2")
GPT = pipeline("text-generation", model="gpt2-large")
MODEL = "gnai-creator/sage-two:f236bf1fc94263e266db57a32ea4014aef91c0ca6a34ac0e98ba1b0e83ca09af"
RESET_PASSWORD = os.environ.get("PASSWORD", "")
JUDGMENT_MAP = {
"reflection": [0, 1, 2],
"anger": [3, 4],
"hope": [5, 6],
"denial": [7],
"intuition": [10, 11],
"skepticism": [15],
"acceptance": [20],
"despair": [30],
"justice": [40, 41, 42],
"transcendence": [60, 61, 62]
}
PROMPTS = {
"reflection": "As an ancient sage before eternity, poetically reflect on:",
"anger": "With restrained fury and sharp words, express your indignation about:",
"hope": "With the stars' glow and the faith of the righteous, speak of the light in:",
"denial": "Firmly deny, as one who sees beyond illusion, the truth in:",
"intuition": "Whisper with mysticism and metaphors what your soul feels about:",
"skepticism": "With cold logic and analytical eyes, deeply question:",
"acceptance": "With the serenity of a monk and the pace of the wind, accept and comment:",
"despair": "With empty eyes and an exhausted heart, murmur about the pain in:",
"justice": "Raise your voice with nobility and purpose. Speak about justice in:",
"transcendence": "As a being beyond existence, reveal a fragment of the infinite about:"
}
def run_sage_two(sequence, reset=False):
output = replicate_client.run(
MODEL,
input={"sequence": sequence, "reset": reset}
)
if isinstance(output, dict):
return [float(x) for x in output["output"]]
elif isinstance(output, list):
return [float(x) for x in output]
else:
raise ValueError(f"Unexpected output format: {output}")
def interpret_vector(vector):
intensity = {}
for name, idxs in JUDGMENT_MAP.items():
values = [vector[i] for i in idxs if i < len(vector)]
if values:
intensity[name] = float(np.mean(values))
return max(intensity, key=intensity.get)
def question_to_response(question, reset=False):
embedding = EMBEDDING_MODEL.encode(question)
sequence = [[embedding.tolist() for _ in range(10)]]
sequence_str = json.dumps(sequence)
vector = run_sage_two(sequence_str, reset=reset)
intention = interpret_vector(vector)
prompt = PROMPTS.get(intention, "With ancient wisdom, respond to this question:") + " " + question
response = GPT(prompt, max_length=250, max_new_tokens=200, num_return_sequences=1)[0]["generated_text"]
return response.strip(), intention
def respond(question, reset_flag, password, chat_history):
if reset_flag and password != RESET_PASSWORD:
response = "Senha incorreta. A memória não foi resetada.\n\n"
intention = "error"
noreset_response, noreset_intention = question_to_response(question, reset=False)
response += noreset_response
if noreset_intention != "error":
response += f"\n\n🛡 Symbolic Intention: **{noreset_intention}**"
chat_history.append((question, response))
return chat_history, chat_history
else:
response, intention = question_to_response(question, reset=reset_flag)
full_response = f"{response}\n\n🛡 Symbolic Intention: **{intention}**" if intention != "error" else response
chat_history.append((question, full_response))
return chat_history, chat_history
with gr.Blocks() as demo:
gr.Markdown("""
# SAGE-2: Symbolic Adaptive General Engine
Ask anything. SAGE will interpret your symbolic intention before responding.
""")
chatbot = gr.Chatbot(label="SAGE responds")
inp = gr.Textbox(label="Your question")
reset_checkbox = gr.Checkbox(label="Reset symbolic consciousness?")
password_box = gr.Textbox(label="Password", type="password")
state = gr.State([])
btn = gr.Button("Ask")
btn.click(fn=respond, inputs=[inp, reset_checkbox, password_box, state], outputs=[chatbot, state])
if __name__ == "__main__":
demo.launch()