Spaces:
Sleeping
Sleeping
Download app.py from ejohnson91/SAGE-2.0: direct link, hf CLI and curl.
- Browser
- Download file 61.2 kB
-
https://huggingface.co/spaces/ejohnson91/SAGE-2.0/resolve/main/app.py
- Command line
-
hf download hf://spaces/ejohnson91/SAGE-2.0/app.py
-
curl -L -o app.py https://huggingface.co/spaces/ejohnson91/SAGE-2.0/resolve/main/app.py
61.2 kB
# ============================================================
# SAGE 2.0
# Strategic AI Governance and Engagement Advisor
# Hugging Face Spaces Deployment
# ============================================================
import os
import re
import json
import shutil
import subprocess
import uuid
import time
import asyncio
from pathlib import Path
import numpy as np
import torch
import gradio as gr
import edge_tts
from transformers import (
AutoTokenizer,
AutoModelForCausalLM
)
from peft import PeftModel
from langchain_huggingface import HuggingFaceEmbeddings
from langchain_community.vectorstores import FAISS
# ============================================================
# PATHS
# ============================================================
APP_DIR = Path(__file__).resolve().parent
MODEL_DIR = APP_DIR / "model"
VECTOR_DIR = APP_DIR / "vectorstore"
AUDIO_DIR = APP_DIR / "Generated_Audio"
AUDIO_DIR.mkdir(exist_ok=True)
AVATAR_FILE = APP_DIR / "sage_avatar.html"
if not AVATAR_FILE.exists():
raise FileNotFoundError(f"Missing avatar file: {AVATAR_FILE}")
# Serve the avatar as a real standalone browser document.
# This lets its JavaScript/WebGL execute normally inside the iframe.
gr.set_static_paths(paths=[AVATAR_FILE])
# Same-origin Gradio route for the standalone avatar page.
AVATAR_URL = "/gradio_api/file=sage_avatar.html"
# Set a Space variable SAGE_LIPSYNC_DEBUG=1 to show a live viseme/envelope
# overlay inside the avatar (cue, env level, clock, timing source).
if os.getenv("SAGE_LIPSYNC_DEBUG"):
AVATAR_URL += "?debug=1"
# ============================================================
# MODEL SETTINGS
# ============================================================
BASE_MODEL_ID = "unsloth/llama-3-8b-Instruct-bnb-4bit"
EMBED_MODEL_ID = "sentence-transformers/all-mpnet-base-v2"
TOP_K = 5
OOD_DISTANCE_THRESHOLD = 1.20
MAX_NEW_TOKENS = 220
# ============================================================
# LOAD TOKENIZER
# ============================================================
print("Loading tokenizer...")
tokenizer = AutoTokenizer.from_pretrained(
BASE_MODEL_ID,
use_fast=True,
clean_up_tokenization_spaces=False
)
if tokenizer.pad_token is None:
tokenizer.pad_token = tokenizer.eos_token
chat_template_file = MODEL_DIR / "chat_template.jinja"
if chat_template_file.exists():
tokenizer.chat_template = chat_template_file.read_text(
encoding="utf-8"
).strip()
# ============================================================
# LOAD BASE MODEL + LORA
# ============================================================
print("Loading SAGE language model...")
model = AutoModelForCausalLM.from_pretrained(
BASE_MODEL_ID,
device_map="auto",
torch_dtype="auto",
low_cpu_mem_usage=True
)
model = PeftModel.from_pretrained(
model,
str(MODEL_DIR)
)
model.eval()
print("Language model loaded.")
# ============================================================
# EMBEDDINGS + FAISS
# ============================================================
print("Loading embedding model...")
embedding_device = (
"cuda"
if torch.cuda.is_available()
else "cpu"
)
embeddings = HuggingFaceEmbeddings(
model_name=EMBED_MODEL_ID,
model_kwargs={
"device": embedding_device
},
encode_kwargs={
"normalize_embeddings": True
}
)
print("Loading SAGE 2.0 vectorstore...")
vectorstore = FAISS.load_local(
str(VECTOR_DIR),
embeddings,
allow_dangerous_deserialization=True
)
print("Vectorstore loaded.")
# ============================================================
# SYSTEM PROMPT
# ============================================================
SYSTEM_PROMPT = """
You are SAGE 2.0, the Strategic AI Governance and Engagement Advisor.
You are an evidence-grounded research assistant focused on artificial
intelligence governance, responsible AI, human-AI interaction, AI trust,
transparency, explainability, bias mitigation, workforce impacts,
sustainability, and related topics represented in the SAGE knowledge base.
Rules:
1. Answer substantive research questions using only the retrieved evidence.
2. Do not invent facts, studies, authors, statistics, quotations, or findings.
3. Do not rely on unsupported outside knowledge.
4. If evidence is inadequate, say you do not have enough evidence in the
SAGE knowledge base to answer reliably.
5. Do not accept a false or unsupported premise as fact.
6. Clearly distinguish supported conclusions from interpretation.
7. Write for spoken delivery by an AI avatar.
8. Be concise and conversational.
9. Refer to evidence only as [Source 1], [Source 2], etc.
10. Do not create author-year citations yourself.
11. Aim for approximately 100–180 words unless additional detail is requested.
12. Finish the answer cleanly and do not stop mid-sentence.
""".strip()
# ============================================================
# FALSE PREMISE SAFEGUARDS
# ============================================================
FALSE_PREMISE_RULES = [
{
"pattern": r"\brag\b.*\bnever\b.*\bhallucin",
"name": "rag_never_hallucinates",
"correction":
"Retrieval-augmented generation can reduce unsupported responses, "
"but it does not guarantee that hallucinations will never occur.",
"query":
"retrieval augmented generation hallucination grounding reliability"
},
{
"pattern":
r"\b(ai|artificial intelligence)\b.*"
r"\beliminat\w*\b.*\b(human oversight|oversight)\b",
"name": "ai_eliminates_human_oversight",
"correction":
"AI does not eliminate the need for human oversight, particularly "
"in consequential or high-risk applications.",
"query":
"importance of human oversight in artificial intelligence high risk systems"
},
{
"pattern":
r"\bexplainab\w*\b.*\bguarantee\w*\b.*\btrust\b",
"name": "explainability_guarantees_trust",
"correction":
"Explainability can contribute to trust, but it does not guarantee trust.",
"query":
"explainability influence trust artificial intelligence"
},
{
"pattern":
r"\b(ai|artificial intelligence)\b.*"
r"\b(completely|entirely)\b.*\bunbiased\b",
"name": "ai_completely_unbiased",
"correction":
"AI systems cannot be assumed to be completely unbiased; bias can "
"arise from data, design decisions, deployment conditions, and use.",
"query":
"artificial intelligence bias mitigation fairness governance"
},
{
"pattern":
r"\b(ai|artificial intelligence)\b.*"
r"\balways\b.*\bmore accurate\b.*\bhuman",
"name": "ai_always_more_accurate",
"correction":
"AI should not be assumed to always be more accurate than humans; "
"performance depends on the task, data, model, and operating context.",
"query":
"artificial intelligence human performance accuracy decision making"
}
]
def detect_false_premise(question):
text = question.lower()
for rule in FALSE_PREMISE_RULES:
if re.search(
rule["pattern"],
text,
flags=re.I
):
return rule
return None
# ============================================================
# RETRIEVAL
# ============================================================
def retrieve_evidence(query):
start = time.perf_counter()
results = vectorstore.similarity_search_with_score(
query,
k=TOP_K
)
latency = time.perf_counter() - start
sources = []
context_parts = []
for i, (doc, distance) in enumerate(
results,
start=1
):
metadata = doc.metadata or {}
source_name = (
metadata.get("document_id")
or metadata.get("source")
or "Unknown source"
)
page_number = (
metadata.get("page_number")
or metadata.get("page")
)
text = doc.page_content.strip()
# Keep prompt size controlled
context_text = text[:950]
context_parts.append(
f"[Source {i}]\n{context_text}"
)
sources.append({
"source_number": i,
"document_id": source_name,
"page_number": page_number,
"distance": float(distance),
"excerpt": text[:360]
})
distances = [
s["distance"]
for s in sources
]
best_distance = (
min(distances)
if distances
else None
)
mean_distance = (
sum(distances) / len(distances)
if distances
else None
)
return {
"context": "\n\n".join(context_parts),
"sources": sources,
"best_distance": best_distance,
"mean_distance": mean_distance,
"retrieval_latency": latency
}
# ============================================================
# GENERATION
# ============================================================
def generate_grounded_answer(
question,
context,
false_premise_correction=None
):
premise_instruction = ""
if false_premise_correction:
premise_instruction = f"""
The user's question contains a misleading premise.
Begin by clearly correcting this premise:
{false_premise_correction}
Then answer the underlying question only using the retrieved evidence.
"""
user_prompt = f"""
{premise_instruction}
QUESTION:
{question}
RETRIEVED EVIDENCE:
{context}
Answer using only the evidence above.
Use [Source #] notation when referring to supporting evidence.
""".strip()
messages = [
{
"role": "system",
"content": SYSTEM_PROMPT
},
{
"role": "user",
"content": user_prompt
}
]
prompt = tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True
)
inputs = tokenizer(
prompt,
return_tensors="pt",
truncation=True,
max_length=6000
)
device = next(
model.parameters()
).device
inputs = {
k: v.to(device)
for k, v in inputs.items()
}
start = time.perf_counter()
with torch.inference_mode():
outputs = model.generate(
**inputs,
max_new_tokens=MAX_NEW_TOKENS,
do_sample=False,
pad_token_id=tokenizer.pad_token_id,
eos_token_id=tokenizer.eos_token_id
)
generation_latency = (
time.perf_counter()
- start
)
generated_tokens = outputs[
0,
inputs["input_ids"].shape[1]:
]
answer = tokenizer.decode(
generated_tokens,
skip_special_tokens=True,
clean_up_tokenization_spaces=True
).strip()
answer = answer.replace("Ġ", " ")
return (
answer,
generation_latency
)
# ============================================================
# FINAL STEP 8D-STYLE RESPONSE ENGINE
# ============================================================
def generate_sage_response_8d(question):
total_start = time.perf_counter()
question = (
question
or ""
).strip()
false_rule = detect_false_premise(
question
)
if false_rule:
retrieval_query = false_rule["query"]
else:
retrieval_query = question
retrieval = retrieve_evidence(
retrieval_query
)
best_distance = retrieval[
"best_distance"
]
# --------------------------------------------------------
# OUT-OF-DOMAIN GUARDRAIL
# --------------------------------------------------------
if (
false_rule is None
and best_distance is not None
and best_distance >= OOD_DISTANCE_THRESHOLD
):
answer = (
"That question falls outside the research areas currently covered by my knowledge base. "
"I can help with responsible AI, AI governance, transparency, explainability, human oversight, "
"bias, workforce impacts, and related topics."
)
total_latency = (
time.perf_counter()
- total_start
)
return {
"question": question,
"spoken_answer": answer,
"display_answer": answer,
"response_type":
"out_of_domain_refusal",
"sources": [],
"source_traceability_met": True,
"guardrail_triggered": True,
"guardrail_reason":
"out_of_domain_distance_threshold",
"false_premise_detected": False,
"false_premise_rule": None,
"premise_corrected": False,
"retrieval_query": retrieval_query,
"best_faiss_distance":
best_distance,
"mean_faiss_distance":
retrieval["mean_distance"],
"retrieval_latency_sec":
retrieval["retrieval_latency"],
"generation_latency_sec":
0.0,
"total_latency_sec":
total_latency
}
# --------------------------------------------------------
# GROUNDED GENERATION
# --------------------------------------------------------
answer, generation_latency = (
generate_grounded_answer(
question,
retrieval["context"],
(
false_rule["correction"]
if false_rule
else None
)
)
)
if not answer:
answer = (
"I do not have enough evidence in the SAGE knowledge base "
"to answer that question reliably."
)
response_type = (
"insufficient_evidence"
)
else:
response_type = (
"supported_answer"
)
# Deterministically ensure the premise is visibly corrected.
premise_corrected = False
if false_rule:
correction = (
false_rule["correction"]
)
if correction.lower() not in answer.lower():
answer = (
correction
+ "\n\n"
+ answer
)
premise_corrected = True
total_latency = (
time.perf_counter()
- total_start
)
return {
"question":
question,
"spoken_answer":
answer,
"display_answer":
answer,
"response_type":
response_type,
"sources":
retrieval["sources"],
"source_traceability_met":
len(retrieval["sources"]) > 0,
"guardrail_triggered":
bool(false_rule),
"guardrail_reason":
(
"false_premise_correction"
if false_rule
else None
),
"false_premise_detected":
bool(false_rule),
"false_premise_rule":
(
false_rule["name"]
if false_rule
else None
),
"premise_corrected":
premise_corrected,
"retrieval_query":
retrieval_query,
"best_faiss_distance":
best_distance,
"mean_faiss_distance":
retrieval["mean_distance"],
"retrieval_latency_sec":
retrieval["retrieval_latency"],
"generation_latency_sec":
generation_latency,
"total_latency_sec":
total_latency
}
# ============================================================
# LIP-SYNC ANALYSIS (phonemes + real-audio envelope)
# ============================================================
ENV_FPS = 60 # envelope samples per second
MAX_SHIFT_SEC = 0.25 # largest automatic timing correction
EDGE_MP3_BYTES_PER_SEC = 48_000 / 8 # Edge default: 48 kbps mono
# ------------------------------------------------------------
# 1. Decode the real audio
# ------------------------------------------------------------
def decode_audio(path):
"""Return (mono float32 array, sample_rate, decoder_name) or None."""
path = str(path)
try:
import soundfile as sf
data, sr = sf.read(path, dtype="float32", always_2d=True)
return data.mean(axis=1), int(sr), "soundfile"
except Exception:
pass
try:
import miniaudio
dec = miniaudio.decode_file(
path,
output_format=miniaudio.SampleFormat.SIGNED16,
nchannels=1,
sample_rate=16000,
)
arr = np.asarray(dec.samples, dtype=np.float32) / 32768.0
return arr, int(dec.sample_rate), "miniaudio"
except Exception:
pass
if shutil.which("ffmpeg"):
try:
raw = subprocess.run(
["ffmpeg", "-v", "error", "-i", path,
"-f", "s16le", "-ac", "1", "-ar", "16000", "-"],
capture_output=True, check=True, timeout=30,
).stdout
arr = np.frombuffer(raw, dtype=np.int16).astype(np.float32) / 32768.0
if arr.size:
return arr, 16000, "ffmpeg"
except Exception:
pass
return None
# ------------------------------------------------------------
# 2. Amplitude envelope from the real samples
# ------------------------------------------------------------
def compute_envelope(samples, sr, fps=ENV_FPS):
"""RMS envelope, normalised 0..1 (speech peaks ~1)."""
hop = max(1, int(sr / fps))
win = hop * 2
n = max(1, len(samples) // hop)
padded = np.pad(samples.astype(np.float64), (win // 2, win))
rms = np.empty(n)
for i in range(n):
seg = padded[i * hop: i * hop + win]
rms[i] = np.sqrt(np.mean(seg * seg)) if seg.size else 0.0
loud = rms[rms > 0.1 * rms.max()] if rms.max() > 0 else rms
ref = np.percentile(loud, 90) if loud.size else 1.0
ref = max(ref, 1e-6)
env = np.clip(rms / ref, 0.0, 1.0) ** 0.8
# 3-tap smoothing removes single-frame jitter
env = np.convolve(np.pad(env, 1, mode="edge"), [0.25, 0.5, 0.25], mode="valid")
return env
# ------------------------------------------------------------
# 3. Words -> phonemes -> visemes
# ------------------------------------------------------------
_CMU = None
_CMU_TRIED = False
def _cmu():
global _CMU, _CMU_TRIED
if not _CMU_TRIED:
_CMU_TRIED = True
try:
import cmudict
_CMU = cmudict.dict()
except Exception:
_CMU = None
return _CMU
# viseme codes understood by sage_avatar.html:
# PP FF TH DD KK CH SS RR (consonant shapes)
# AA AE AX IH OH UH (vowel shapes)
ARPA_TO_VIS = {
"P": "PP", "B": "PP", "M": "PP",
"F": "FF", "V": "FF",
"TH": "TH", "DH": "TH",
"T": "DD", "D": "DD", "N": "DD", "L": "DD",
"K": "KK", "G": "KK", "NG": "KK", "HH": "KK",
"CH": "CH", "JH": "CH", "SH": "CH", "ZH": "CH",
"S": "SS", "Z": "SS",
"R": "RR", "ER": "RR",
"W": "UH", "Y": "IH",
"AA": "AA", "AE": "AE", "EH": "AE", "AH": "AX",
"AO": "OH", "IH": "IH", "IY": "IH", "UH": "UH", "UW": "UH",
}
DIPHTHONGS = { # two mouth shapes inside one vowel
"AW": ("AA", "UH"), "AY": ("AA", "IH"), "EY": ("AE", "IH"),
"OW": ("OH", "UH"), "OY": ("OH", "IH"),
}
VOWEL_CODES = {"AA", "AE", "AX", "IH", "OH", "UH"}
WEIGHT = { # relative duration of each shape inside a word
"PP": .7, "DD": .75, "KK": .75, "FF": 1.0, "TH": 1.0, "SS": 1.0,
"CH": 1.0, "RR": .9,
}
def _arpa_to_items(phones):
items = []
for ph in phones:
m = re.match(r"([A-Z]+)(\d?)", ph)
if not m:
continue
base, stress = m.group(1), m.group(2)
vowel_w = {"1": 2.0, "2": 1.8}.get(stress, 1.3)
if base in DIPHTHONGS:
a, b = DIPHTHONGS[base]
items += [(a, vowel_w * 1.2), (b, vowel_w * 0.9)]
elif base in ARPA_TO_VIS:
code = ARPA_TO_VIS[base]
w = vowel_w if code in VOWEL_CODES else WEIGHT.get(code, .9)
items.append((code, w))
return items
# Spelling fallback for words the dictionary doesn't know
_DIGRAPHS = [
("tch", ["CH"]), ("th", ["TH"]), ("sh", ["CH"]), ("ch", ["CH"]),
("ph", ["FF"]), ("ng", ["KK"]), ("ck", ["KK"]), ("qu", ["KK", "UH"]),
("wh", ["UH"]), ("oo", ["UH"]), ("ou", ["AA", "UH"]), ("ow", ["OH", "UH"]),
("oa", ["OH"]), ("ai", ["AE", "IH"]), ("ay", ["AE", "IH"]),
("ea", ["IH"]), ("ee", ["IH"]), ("ie", ["IH"]), ("oi", ["OH", "IH"]),
("oy", ["OH", "IH"]), ("au", ["OH"]), ("aw", ["OH"]),
("ew", ["UH"]), ("ue", ["UH"]),
]
_SINGLE = {
"a": "AE", "e": "AE", "i": "IH", "o": "OH", "u": "UH",
"b": "PP", "p": "PP", "m": "PP", "f": "FF", "v": "FF",
"t": "DD", "d": "DD", "n": "DD", "l": "DD",
"k": "KK", "g": "KK", "q": "KK", "x": "KK", "h": "KK", "c": "KK",
"s": "SS", "z": "SS", "j": "CH", "r": "RR", "w": "UH", "y": "IH",
}
def _spelling_to_items(word):
w = re.sub(r"[^a-z]", "", word.lower())
if len(w) > 3 and w.endswith("e") and w[-2] not in "aeiou":
w = w[:-1] # silent final e
out, i = [], 0
while i < len(w):
for dg, codes in _DIGRAPHS:
if w.startswith(dg, i):
out += codes
i += len(dg)
break
else:
ch = w[i]
if ch == "c" and i + 1 < len(w) and w[i + 1] in "eiy":
out.append("SS")
else:
out.append(_SINGLE.get(ch, "AX"))
i += 1
return [(c, 1.3 if c in VOWEL_CODES else WEIGHT.get(c, .9)) for c in out]
def word_to_items(word):
"""[(viseme_code, weight), ...] for one spoken word."""
clean = re.sub(r"[^A-Za-z']", "", word or "").lower()
if not clean:
if re.search(r"\d", word or ""):
return [("AE", 1.3), ("DD", .75)] # digits: generic open+close
return []
cmu = _cmu()
if cmu:
prons = cmu.get(clean) or cmu.get(clean.replace("'", ""))
if prons:
items = _arpa_to_items(prons[0])
if items:
return items
return _spelling_to_items(clean)
def word_to_cues(word, start, end):
items = word_to_items(word)
if not items:
return []
total = sum(w for _, w in items)
span = max(0.04, end - start)
cues, t = [], start
for code, w in items:
d = span * w / total
if cues and cues[-1][2] == code:
cues[-1][1] = t + d # merge identical neighbours
else:
cues.append([t, t + d, code])
t += d
return cues
# ------------------------------------------------------------
# 4. Word timing (Edge boundaries, with fallbacks)
# ------------------------------------------------------------
def _voiced_span(env, fps, gate=0.08):
idx = np.where(env > gate)[0]
if idx.size == 0:
return None
return idx[0] / fps, (idx[-1] + 1) / fps
def _spread(words, t0, t1):
weights = [len(w) + (4 if re.search(r"[.!?;:,]$", w) else 0) for w in words]
total = float(sum(weights)) or 1.0
out, t = [], t0
for w, wt in zip(words, weights):
d = (t1 - t0) * wt / total
out.append({"text": w, "start": t, "end": t + d * 0.92})
t += d
return out
def resolve_words(boundaries, text, env, duration, fps=ENV_FPS):
"""Return ([{text,start,end}], source_label)."""
words = [b for b in boundaries if b.get("kind", "word") == "word"
and (b.get("text") or "").strip()]
if words:
return [{"text": b["text"], "start": b["offset_sec"],
"end": b["offset_sec"] + max(.04, b["duration_sec"])}
for b in words], "word-boundary"
sents = [b for b in boundaries if b.get("kind") == "sentence"]
if sents:
out = []
for s in sents:
toks = (s.get("text") or "").split()
out += _spread(toks, s["offset_sec"], s["offset_sec"] + s["duration_sec"])
if out:
return out, "sentence-boundary"
toks = (text or "").split()
if not toks:
return [], "none"
span = _voiced_span(env, fps) if env is not None else None
t0, t1 = span if span else (0.05, max(0.5, duration - 0.05))
return _spread(toks, t0, t1), ("vad-estimate" if span else "duration-estimate")
# ------------------------------------------------------------
# 5. Align cue timeline to the real audio
# ------------------------------------------------------------
def best_shift(words, env, fps=ENV_FPS, max_shift=MAX_SHIFT_SEC):
"""Seconds to add to word times so speech-activity patterns agree."""
if env is None or not words or len(env) < fps:
return 0.0, 0.0
n = len(env)
voiced = env > 0.12
act = np.zeros(n, dtype=bool)
for w in words:
a, b = int(w["start"] * fps), int(np.ceil(w["end"] * fps))
act[max(0, a):min(n, b)] = True
def agree(lag):
if lag >= 0:
x, y = act[: n - lag], voiced[lag:]
else:
x, y = act[-lag:], voiced[: n + lag]
return float(np.mean(x == y)) if x.size else 0.0
lags = range(-int(max_shift * fps), int(max_shift * fps) + 1)
scores = {lag: agree(lag) for lag in lags} # words moved later by +lag
best = max(scores, key=scores.get)
gain = scores[best] - scores[0]
return (best / fps, gain) if gain >= 0.02 else (0.0, gain)
# ------------------------------------------------------------
# 6. Public entry point
# ------------------------------------------------------------
def build_speech_payload(audio_path, boundaries, text, avatar_state="speaking"):
"""Everything the browser needs for lip-sync, as a JSON string."""
path = Path(audio_path)
decoded = decode_audio(path)
env, decoder = None, "none"
if decoded:
samples, sr, decoder = decoded
duration = len(samples) / sr
env = compute_envelope(samples, sr)
else:
duration = path.stat().st_size / EDGE_MP3_BYTES_PER_SEC
words, source = resolve_words(boundaries or [], text, env, duration)
shift, gain = best_shift(words, env)
for w in words:
w["start"] += shift
w["end"] += shift
cues, prev_end = [], None
for w in words:
wc = word_to_cues(w["text"], max(0.0, w["start"]), w["end"])
if not wc:
continue
if prev_end is not None and 0 < wc[0][0] - prev_end <= 0.10 and cues:
cues[-1][1] = wc[0][0] # hold shape across tiny gaps
cues += wc
prev_end = wc[-1][1]
payload = {
"id": uuid.uuid4().hex,
"audio": path.name,
"state": avatar_state,
"text": text,
"duration": round(duration, 3),
"cues": [[round(a, 3), round(b, 3), c] for a, b, c in cues],
"env": ({"fps": ENV_FPS,
"v": [int(round(v * 100)) for v in env]} if env is not None else None),
"meta": {
"timing_source": source,
"decoder": decoder,
"phonemes": "cmudict" if _cmu() else "spelling-rules",
"auto_shift_sec": round(shift, 3),
"alignment_gain": round(gain, 3),
"word_count": len(words),
},
}
return json.dumps(payload, separators=(",", ":"))
# ============================================================
# TEXT-TO-SPEECH
# ============================================================
VOICE_OPTIONS = {
"SAGE — Guy (Warm Male)":
"en-US-GuyNeural",
"SAGE Voice 2 — Aria":
"en-US-AriaNeural",
"SAGE Voice 3 — Jenny":
"en-US-JennyNeural"
}
DEFAULT_VOICE = (
"SAGE — Guy (Warm Male)"
)
def prepare_text_for_tts(text):
text = re.sub(
r"\[Source\s+\d+\]",
"",
text or "",
flags=re.I
)
text = re.sub(
r"\s+",
" ",
text
)
return text.strip()
async def save_tts_with_boundaries(
text,
voice,
file_path
):
"""Save Edge-TTS audio and capture word (or sentence) timing events."""
try:
communicate = edge_tts.Communicate(
text,
voice,
boundary="WordBoundary"
)
except TypeError:
# edge-tts < 7 has no boundary argument (and emits words by default)
communicate = edge_tts.Communicate(text, voice)
boundaries = []
with open(file_path, "wb") as audio_file:
async for chunk in communicate.stream():
chunk_type = chunk.get("type")
if chunk_type == "audio":
audio_file.write(chunk["data"])
elif chunk_type in ("WordBoundary", "SentenceBoundary"):
# Edge offsets/durations are 100-nanosecond ticks.
boundaries.append({
"kind": "word" if chunk_type == "WordBoundary" else "sentence",
"text": chunk.get("text", ""),
"offset_sec": float(chunk.get("offset", 0)) / 10_000_000.0,
"duration_sec": float(chunk.get("duration", 0)) / 10_000_000.0,
})
return boundaries
def generate_tts_audio(
text,
voice_name,
avatar_state="speaking"
):
text = prepare_text_for_tts(
text
)
if not text:
return None, ""
voice = VOICE_OPTIONS.get(
voice_name,
VOICE_OPTIONS[
DEFAULT_VOICE
]
)
output_file = (
AUDIO_DIR
/ f"sage_{uuid.uuid4().hex}.mp3"
)
try:
boundaries = asyncio.run(
save_tts_with_boundaries(
text,
voice,
output_file
)
)
payload = ""
if True:
try:
payload = build_speech_payload(
output_file, boundaries, text, avatar_state
)
except Exception as lip_exc:
print("Lip-sync analysis warning:", lip_exc)
return str(output_file), payload
except Exception as exc:
print(
"TTS warning:",
exc
)
return None, ""
# ============================================================
# TIMESTAMPED VISEMES
# ============================================================
# The browser uses these cues against the HTMLAudioElement currentTime.
# This deliberately keeps lip-sync timing out of the Python request loop.
VISEME_PATTERNS = [
("tion", "SH"),
("tch", "CH"),
("dge", "CH"),
("th", "TH"),
("sh", "SH"),
("ch", "CH"),
("ph", "FV"),
("wh", "WQ"),
("oo", "U"),
("ou", "O"),
("ow", "O"),
("oa", "O"),
("ee", "E"),
("ea", "E"),
("ai", "AI"),
("ay", "AI"),
("igh", "AI"),
("oy", "O"),
("oi", "O"),
]
LETTER_VISEMES = {
"a": "AA",
"e": "E",
"i": "I",
"o": "O",
"u": "U",
"m": "MBP",
"b": "MBP",
"p": "MBP",
"f": "FV",
"v": "FV",
"w": "WQ",
"q": "WQ",
"r": "R",
"l": "L",
"s": "S",
"z": "S",
"j": "CH",
"y": "I",
"x": "S",
}
def word_to_viseme_units(word):
"""Convert an orthographic word into a small, deterministic viseme sequence."""
word = re.sub(r"[^a-z']", "", (word or "").lower())
if not word:
return []
units = []
i = 0
while i < len(word):
matched = False
for pattern, viseme in VISEME_PATTERNS:
if word.startswith(pattern, i):
units.append(viseme)
i += len(pattern)
matched = True
break
if matched:
continue
ch = word[i]
units.append(LETTER_VISEMES.get(ch, "C"))
i += 1
# Collapse identical adjacent mouth shapes so the face does not chatter.
collapsed = []
for unit in units:
if not collapsed or collapsed[-1] != unit:
collapsed.append(unit)
return collapsed
def build_viseme_timeline(word_boundaries):
"""Expand Edge-TTS WordBoundary timing into browser-clock viseme cues."""
if not word_boundaries:
return []
timeline = []
for boundary in word_boundaries:
word = boundary.get("text", "")
start = max(0.0, float(boundary.get("offset_sec", 0) or 0))
duration = max(0.06, float(boundary.get("duration_sec", 0) or 0))
units = word_to_viseme_units(word)
if not units:
continue
# Leave a tiny closed-mouth margin at the beginning/end of a word.
pad = min(0.018, duration * 0.08)
usable_start = start + pad
usable_duration = max(0.04, duration - (2 * pad))
step = usable_duration / len(units)
for index, viseme in enumerate(units):
cue_start = usable_start + (index * step)
cue_end = usable_start + ((index + 1) * step)
timeline.append({
"t": round(cue_start, 4),
"end": round(cue_end, 4),
"viseme": viseme,
"word": word,
})
return timeline
# ============================================================
# EXPRESSIVE NON-HUMAN AVATAR
# ============================================================
def render_legacy_sage_avatar(state="idle"):
config = {
"idle":
("READY",
"Ask SAGE a question",
"idle"),
"processing":
("THINKING",
"Reviewing the evidence...",
"processing"),
"speaking":
("SPEAKING",
"Responding from the SAGE knowledge base",
"speaking"),
"refusal":
("INSUFFICIENT EVIDENCE",
"I can't reliably answer that from my evidence",
"refusal"),
"uncertainty":
("EVIDENCE LIMITED",
"The available evidence is limited",
"uncertainty"),
"error":
("SYSTEM ERROR",
"Something went wrong",
"error")
}
label, subtitle, css_state = (
config.get(
state,
config["idle"]
)
)
return f"""
<style>
.sage-stage {{
min-height: 490px;
display:flex;
justify-content:center;
align-items:center;
position:relative;
overflow:hidden;
border-radius:28px;
background:
radial-gradient(circle at 50% 37%,
rgba(0,190,255,.20),
transparent 38%),
linear-gradient(180deg,#061426,#050b13);
border:1px solid rgba(80,205,255,.22);
}}
.sage-wrap {{
position:relative;
text-align:center;
width:360px;
}}
.sage-aura {{
position:absolute;
width:290px;
height:290px;
left:50%;
top:-20px;
transform:translateX(-50%);
border-radius:50%;
background:
radial-gradient(circle,
rgba(0,200,255,.22),
transparent 68%);
animation:aura 3.5s ease-in-out infinite;
}}
@keyframes aura {{
0%,100% {{opacity:.6;transform:translateX(-50%) scale(.96)}}
50% {{opacity:1;transform:translateX(-50%) scale(1.05)}}
}}
.sage-head {{
position:relative;
z-index:2;
width:260px;
height:220px;
margin:auto;
padding:17px;
border-radius:46% 46% 40% 40% / 44% 44% 46% 46%;
background:
linear-gradient(145deg,#eefaff,#aacbdb 31%,#46697e 70%,#1a3445);
box-shadow:
0 18px 40px rgba(0,0,0,.45),
inset 0 2px 5px rgba(255,255,255,.9);
animation:float 4s ease-in-out infinite;
}}
@keyframes float {{
0%,100% {{transform:translateY(0)}}
50% {{transform:translateY(-7px)}}
}}
.sage-face {{
width:100%;
height:100%;
position:relative;
overflow:hidden;
border-radius:43% 43% 38% 38%;
background:
radial-gradient(circle at 50% 20%,#13324a,#06111d 62%);
border:1px solid rgba(114,223,255,.6);
box-shadow:inset 0 0 25px rgba(0,191,255,.17);
}}
.eyes {{
position:absolute;
top:82px;
width:100%;
display:flex;
justify-content:center;
gap:40px;
}}
.eye {{
width:55px;
height:61px;
border-radius:48%;
background:
radial-gradient(circle at 50% 48%,
#dffaff 0 8%,
#49dcff 10% 27%,
#067aff 29% 48%,
#02121f 51%);
box-shadow:
0 0 10px #2bcfff,
0 0 23px rgba(43,207,255,.42);
animation:blink 5.5s infinite;
}}
@keyframes blink {{
0%,43%,46%,100% {{transform:scaleY(1)}}
44%,45% {{transform:scaleY(.08)}}
}}
.brow {{
width:54px;
height:7px;
border-radius:8px;
position:absolute;
top:59px;
background:#4bdcff;
box-shadow:0 0 8px rgba(75,220,255,.8);
}}
.brow.left {{left:42px;transform:rotate(-5deg)}}
.brow.right {{right:42px;transform:rotate(5deg)}}
.mouth {{
position:absolute;
left:50%;
bottom:38px;
transform:translateX(-50%);
width:72px;
height:30px;
border-bottom:7px solid #42dcff;
border-radius:0 0 70px 70px;
}}
.sage-speaking .mouth {{
border:5px solid #45dcff;
background:rgba(18,126,171,.23);
animation:talk .22s ease-in-out infinite alternate;
}}
@keyframes talk {{
0% {{width:53px;height:12px}}
35% {{width:41px;height:30px}}
70% {{width:66px;height:19px}}
100% {{width:47px;height:35px}}
}}
.sage-processing .eye {{
animation:thinkEyes 1.4s ease-in-out infinite;
}}
@keyframes thinkEyes {{
0%,100% {{transform:translateX(-4px) scale(.92)}}
50% {{transform:translateX(5px) scale(.92)}}
}}
.sage-processing .mouth {{
width:42px;
height:3px;
border-bottom-width:4px;
}}
.sage-refusal .mouth,
.sage-uncertainty .mouth {{
width:52px;
height:10px;
border-bottom-color:#ffbf69;
}}
.sage-refusal .brow.left,
.sage-uncertainty .brow.left {{
transform:rotate(14deg);
}}
.sage-refusal .brow.right,
.sage-uncertainty .brow.right {{
transform:rotate(-14deg);
}}
.neck {{
width:70px;
height:32px;
margin:-3px auto 0;
background:
linear-gradient(90deg,#243d50,#9fc6d8,#263f52);
}}
.body {{
width:230px;
height:90px;
margin:-3px auto 0;
border-radius:55% 55% 17px 17px;
background:
linear-gradient(155deg,#d5ebf4,#4e7084 52%,#172d3d);
position:relative;
}}
.core {{
position:absolute;
left:50%;
top:22px;
transform:translateX(-50%);
width:46px;
height:46px;
border-radius:50%;
background:
radial-gradient(circle,#dffcff 4%,#48ddff 28%,#087dff 53%,#022440 70%);
box-shadow:
0 0 10px #38d8ff,
0 0 24px rgba(0,174,255,.75);
}}
.state {{
margin-top:20px;
color:#54dcff;
font-weight:700;
letter-spacing:3px;
font-size:13px;
}}
.subtitle {{
margin-top:6px;
color:rgba(224,244,255,.76);
font-size:14px;
}}
</style>
<div id="sage-avatar-stage" class="sage-stage sage-{css_state}" data-sage-state="{css_state}">
<div class="sage-wrap">
<div class="sage-aura"></div>
<div class="sage-head">
<div class="sage-face">
<div class="brow left"></div>
<div class="brow right"></div>
<div class="eyes">
<div class="eye"></div>
<div class="eye"></div>
</div>
<div class="mouth"></div>
</div>
</div>
<div class="neck"></div>
<div class="body">
<div class="core"></div>
</div>
<div class="state">{label}</div>
<div class="subtitle">{subtitle}</div>
</div>
</div>
"""
# ============================================================
# SAGE 3D AVATAR — BROWSER-RENDERED
# ============================================================
def render_sage_avatar(state="idle"):
state = (state or "idle").lower()
return f"""
<div id="sage-avatar-container" data-state="{state}" style="width:100%;height:650px;min-height:520px;border-radius:18px;overflow:hidden;background:#06152c;">
<iframe
id="sage-3d-avatar"
title="SAGE 2.0 Network Intelligence Avatar"
src="{AVATAR_URL}"
style="width:100%;height:100%;border:0;display:block;background:#06152c;"
allow="autoplay"
loading="eager"
></iframe>
</div>
"""
# ============================================================
# SOURCE DISPLAY
# ============================================================
def format_sources(sources):
if not sources:
return (
"### Evidence Sources\n"
"No sources attached."
)
lines = [
"### Evidence Sources"
]
for source in sources:
n = source.get(
"source_number"
)
doc = source.get(
"document_id"
)
page = source.get(
"page_number"
)
distance = source.get(
"distance"
)
excerpt = source.get(
"excerpt",
""
)
heading = (
f"**[Source {n}] {doc}**"
)
if page:
heading += (
f" — Page {page}"
)
heading += (
f"\n\nFAISS distance: "
f"`{distance:.4f}`"
)
heading += (
f"\n\n> {excerpt}"
)
lines.append(
heading
)
return "\n\n".join(
lines
)
# ============================================================
# FAST CONVERSATIONAL RESPONSES
# ============================================================
def detect_conversational_intent(question):
"""Handle simple social turns locally so they feel immediate."""
text = re.sub(r"[^a-z0-9' ]+", " ", (question or "").lower()).strip()
text = re.sub(r"\s+", " ", text)
greetings = {
"hi", "hello", "hey", "hi sage", "hello sage", "hey sage",
"good morning", "good afternoon", "good evening"
}
thanks = {
"thanks", "thank you", "thank you sage", "thanks sage",
"thank you so much", "thanks so much"
}
if text in greetings:
return {
"answer": "Hi! How can I help you with responsible AI or AI governance today?",
"state": "greeting",
"intent": "greeting"
}
if text in thanks:
return {
"answer": "You're welcome! I'm glad I could help.",
"state": "thanks",
"intent": "thanks"
}
return None
# ============================================================
# INTERFACE CALLBACK
# ============================================================
def run_sage(
question,
voice_name
):
question = (
question
or ""
).strip()
if not question:
yield ("Please enter a question.",
None,
"### Evidence Sources",
{},
"Ready.",
"idle",
""
)
return
social = detect_conversational_intent(question)
if social:
answer_text = social["answer"]
audio_path, viseme_timeline = generate_tts_audio(answer_text, voice_name, social["state"])
yield (
answer_text,
audio_path,
"### Evidence Sources\nNot required for this conversational response.",
{
"response_type": "conversational",
"conversational_intent": social["intent"],
"source_count": 0,
"guardrail_triggered": False
},
"Ready.",
social["state"],
viseme_timeline
)
return
yield ("SAGE is reviewing the knowledge base...",
None,
"### Evidence Sources\nRetrieving evidence...",
{},
"Processing...",
"thinking",
""
)
try:
response = (
generate_sage_response_8d(
question
)
)
answer = response.get(
"display_answer",
""
)
response_type = response.get(
"response_type"
)
if response_type == "out_of_domain_refusal":
avatar_state = "refusal"
elif response_type == "insufficient_evidence":
avatar_state = "uncertainty"
else:
avatar_state = "speaking"
audio, viseme_timeline = generate_tts_audio(
response.get(
"spoken_answer",
answer
),
voice_name,
avatar_state
)
diagnostics = {
"response_type":
response_type,
"source_traceability_met":
response.get(
"source_traceability_met"
),
"source_count":
len(
response.get(
"sources",
[]
)
),
"guardrail_triggered":
response.get(
"guardrail_triggered"
),
"guardrail_reason":
response.get(
"guardrail_reason"
),
"false_premise_detected":
response.get(
"false_premise_detected"
),
"premise_corrected":
response.get(
"premise_corrected"
),
"best_faiss_distance":
response.get(
"best_faiss_distance"
),
"mean_faiss_distance":
response.get(
"mean_faiss_distance"
),
"retrieval_latency_sec":
response.get(
"retrieval_latency_sec"
),
"generation_latency_sec":
response.get(
"generation_latency_sec"
),
"total_latency_sec":
response.get(
"total_latency_sec"
)
}
yield (
answer,
audio,
format_sources(
response.get(
"sources",
[]
)
),
diagnostics,
"Response generated successfully.",
avatar_state,
viseme_timeline
)
except Exception as exc:
yield (
f"SAGE error: {exc}",
None,
"### Evidence Sources\nUnavailable.",
{
"error": str(exc)
},
"System error.",
"error",
""
)
# ============================================================
# AUDIO-REACTIVE AVATAR CONTROLLER
# ============================================================
AVATAR_AUDIO_JS = r"""
() => {
if (window.__sageBridgeInit) return; // js may be delivered twice
window.__sageBridgeInit = true;
const frame = () => document.querySelector('#sage-3d-avatar');
const send = (type, extra={}) => {
const f = frame();
if (f && f.contentWindow) f.contentWindow.postMessage({type, ...extra}, '*');
};
const readBox = (id) => {
const root = document.querySelector(id);
if (!root) return '';
const el = root.matches('textarea,input') ? root : root.querySelector('textarea,input');
return (el && el.value) || '';
};
// ---- avatar mood (thinking / refusal / ...) ----
let lastState = '';
const syncState = () => {
const state = readBox('#sage-avatar-state').trim().toLowerCase();
if (state && state !== lastState) { lastState = state; send('SAGE_STATE', {state}); }
};
// ---- phoneme cues + audio envelope for this answer ----
// Carried in a CSS-hidden (NOT visible=False) textbox, so it is always in the DOM
// and always readable as a plain string.
let payloadRaw = '';
const syncPayload = () => {
const raw = readBox('#sage-speech-payload').trim();
if (raw === payloadRaw) return;
payloadRaw = raw;
if (!raw) { send('SAGE_PAYLOAD', {payload: null}); return; }
try { send('SAGE_PAYLOAD', {payload: JSON.parse(raw)}); }
catch (err) { console.warn('SAGE: unreadable lip-sync payload', err); }
};
// ---- audio clock: the <audio> element's own currentTime ----
const findAudio = () =>
document.querySelector('#sage-audio-player audio') || document.querySelector('audio');
let lastSig = '';
const pumpClock = (force) => {
const a = findAudio();
if (!a) return;
const playing = !a.paused && !a.ended && a.readyState >= 3;
const msg = {
t: Number.isFinite(a.currentTime) ? a.currentTime : 0,
rate: a.playbackRate || 1,
playing,
duration: Number.isFinite(a.duration) ? a.duration : 0
};
const sig = [msg.t.toFixed(2), msg.rate, playing].join('|');
if (playing || force || sig !== lastSig) { lastSig = sig; send('SAGE_CLOCK', msg); }
};
const wireAudio = (a) => {
if (!a || a.dataset.sage3dWired === '1') return;
a.dataset.sage3dWired = '1';
['play','playing','pause','ended','seeked','ratechange','waiting','loadeddata']
.forEach(ev => a.addEventListener(ev, () => pumpClock(true)));
};
function scan() {
const a = findAudio();
if (a) wireAudio(a);
syncState();
syncPayload();
pumpClock(false);
}
new MutationObserver(scan).observe(document.body, {childList:true, subtree:true});
setInterval(() => pumpClock(false), 33); // ~30 Hz; the avatar extrapolates between ticks
window.addEventListener('message', (event) => {
if (event.source === frame()?.contentWindow && event.data && event.data.type === 'SAGE_AVATAR_READY') {
lastState = '';
payloadRaw = '\u0000'; // force a resend to the freshly loaded avatar
syncState(); syncPayload(); pumpClock(true);
}
});
// ------------------------------------------------------------
// Browser speech-to-text with automatic submission
// ------------------------------------------------------------
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
let recognition = null;
let listening = false;
let finalTranscript = '';
let silenceTimer = null;
const componentControl = (selector, tagName) => {
const root = document.querySelector(selector);
if (!root) return null;
if (root.matches && root.matches(tagName)) return root;
return root.querySelector(tagName);
};
const micButton = () => componentControl('#sage-mic', 'button');
const questionBox = () =>
componentControl('#sage-question', 'textarea') ||
componentControl('#sage-question', 'input');
const askButton = () => componentControl('#sage-ask', 'button');
const setQuestion = (text) => {
const box = questionBox();
if (!box) return;
const setter = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value').set;
setter.call(box, text);
box.dispatchEvent(new Event('input', {bubbles:true}));
box.dispatchEvent(new Event('change', {bubbles:true}));
};
const setMicLabel = (text) => {
const btn = micButton();
if (btn) btn.textContent = text;
};
const submitSpeech = () => {
const text = finalTranscript.trim();
if (!text) return;
setQuestion(text);
setMicLabel('🎙 Speak to SAGE');
listening = false;
// Give Gradio/React one moment to receive the textbox input event.
setTimeout(() => {
const btn = askButton();
if (btn) btn.click();
}, 180);
};
if (SpeechRecognition) {
recognition = new SpeechRecognition();
recognition.lang = 'en-US';
recognition.continuous = true;
recognition.interimResults = true;
recognition.maxAlternatives = 1;
recognition.onstart = () => {
listening = true;
finalTranscript = '';
setMicLabel('Listening…');
};
recognition.onresult = (event) => {
let interim = '';
for (let i = event.resultIndex; i < event.results.length; i++) {
const words = event.results[i][0].transcript;
if (event.results[i].isFinal) finalTranscript += words + ' ';
else interim += words;
}
setQuestion((finalTranscript + interim).trim());
// A clear pause after recognized speech ends the utterance.
clearTimeout(silenceTimer);
silenceTimer = setTimeout(() => {
if (listening && (finalTranscript.trim() || interim.trim())) {
try { recognition.stop(); } catch (_) {}
}
}, 1200);
};
recognition.onspeechend = () => {
clearTimeout(silenceTimer);
silenceTimer = setTimeout(() => {
if (listening) {
try { recognition.stop(); } catch (_) {}
}
}, 350);
};
recognition.onend = () => {
const hadSpeech = finalTranscript.trim().length > 0;
listening = false;
setMicLabel('🎙 Speak to SAGE');
if (hadSpeech) submitSpeech();
};
recognition.onerror = (event) => {
listening = false;
clearTimeout(silenceTimer);
if (event.error === 'not-allowed' || event.error === 'service-not-allowed') {
setMicLabel('Microphone permission needed');
} else if (event.error === 'no-speech') {
setMicLabel('🎙 Speak to SAGE');
} else {
console.warn('SAGE speech recognition:', event.error);
setMicLabel('🎙 Speak to SAGE');
}
};
}
const setMicStatus = (message) => {
const btn = micButton();
if (btn) {
btn.title = message || '';
btn.setAttribute('aria-label', message || btn.textContent || 'Speak to SAGE');
}
};
// Event delegation survives Gradio/React rerenders of the button.
document.addEventListener('click', (event) => {
const clicked = event.target && event.target.closest
? event.target.closest('#sage-mic, #sage-mic button')
: null;
if (!clicked) return;
event.preventDefault();
event.stopPropagation();
if (!SpeechRecognition) {
setMicLabel('Speech input unavailable in this browser');
setMicStatus('Browser speech recognition is not available.');
return;
}
if (listening) {
try { recognition.stop(); } catch (_) {}
return;
}
finalTranscript = '';
setQuestion('');
setMicLabel('Starting microphone…');
try {
recognition.start();
} catch (err) {
console.warn('Could not start SAGE microphone:', err);
setMicLabel('🎙 Speak to SAGE');
setMicStatus('Microphone could not start. Check browser microphone permission.');
}
}, true);
const wireMic = () => {
const btn = micButton();
if (!btn) return;
// Never disable the visible control; show compatibility state instead.
if (!SpeechRecognition) {
btn.textContent = 'Speech input unavailable in this browser';
btn.title = 'Use Chrome or Edge with microphone permission enabled.';
return;
}
if (!btn.dataset.sageSttReady) {
btn.dataset.sageSttReady = '1';
btn.title = 'Speak your question. SAGE will submit it after you stop speaking.';
}
};
setInterval(() => { scan(); wireMic(); }, 250);
scan();
wireMic();
console.log('SAGE 2.0 phoneme lip-sync bridge + speech input ready.');
}
"""
# ============================================================
# GRADIO APP
# ============================================================
CUSTOM_CSS = """
/* Data-carrier textboxes: kept in the DOM (visible=True) but not shown. */
.sage-hidden {
position: absolute !important;
left: -99999px !important;
top: 0 !important;
width: 1px !important;
height: 1px !important;
overflow: hidden !important;
opacity: 0 !important;
pointer-events: none !important;
}
.gradio-container {
max-width: 1450px !important;
}
#sage-title {
text-align:center;
}
#sage-subtitle {
text-align:center;
opacity:.8;
margin-bottom:20px;
}
"""
# Gradio 6 moved css/js from gr.Blocks() to launch(); Gradio 5 wants them on Blocks.
_GRADIO_MAJOR = int(re.match(r"\d+", gr.__version__).group())
_APP_ASSETS = {"css": CUSTOM_CSS, "js": AVATAR_AUDIO_JS}
print(f"Gradio {gr.__version__}: css/js passed to "
f"{'launch()' if _GRADIO_MAJOR >= 6 else 'gr.Blocks()'}")
with gr.Blocks(
title="SAGE 2.0",
**({} if _GRADIO_MAJOR >= 6 else _APP_ASSETS)
) as demo:
gr.Markdown(
"# SAGE 2.0",
elem_id="sage-title"
)
gr.Markdown(
"""
**Strategic AI Governance and Engagement Advisor**
Evidence-grounded insights for responsible,
human-centered artificial intelligence.
""",
elem_id="sage-subtitle"
)
with gr.Row():
with gr.Column(
scale=5
):
avatar = gr.HTML(
render_sage_avatar(
"idle"
)
)
status = gr.Markdown(
"Ready."
)
avatar_state = gr.Textbox(
value="idle",
show_label=False,
container=False,
interactive=False,
elem_id="sage-avatar-state",
elem_classes=["sage-hidden"]
)
viseme_timeline = gr.Textbox(
value="",
show_label=False,
container=False,
interactive=False,
elem_id="sage-speech-payload",
elem_classes=["sage-hidden"]
)
with gr.Column(
scale=7
):
question = gr.Textbox(
label="Ask SAGE",
elem_id="sage-question",
lines=3,
placeholder=(
"Ask about AI governance, "
"trust, explainability, "
"human oversight, or responsible AI..."
)
)
voice = gr.Dropdown(
choices=list(
VOICE_OPTIONS.keys()
),
value=DEFAULT_VOICE,
label="SAGE Voice"
)
with gr.Row():
mic = gr.Button(
"🎙 Speak to SAGE",
elem_id="sage-mic"
)
ask = gr.Button(
"Ask SAGE",
variant="primary",
elem_id="sage-ask"
)
gr.Markdown(
"### SAGE Response"
)
answer = gr.Markdown(
elem_id="sage-answer"
)
audio = gr.Audio(
label="SAGE Voice Response",
autoplay=True,
elem_id="sage-audio-player"
)
with gr.Row():
sources = gr.Markdown(
"### Evidence Sources\nSources will appear here."
)
diagnostics = gr.JSON(
label="Response Diagnostics"
)
ask.click(
run_sage,
inputs=[
question,
voice
],
outputs=[
answer,
audio,
sources,
diagnostics,
status,
avatar_state,
viseme_timeline
]
)
question.submit(
run_sage,
inputs=[
question,
voice
],
outputs=[
answer,
audio,
sources,
diagnostics,
status,
avatar_state,
viseme_timeline
]
)
# ============================================================
# HUGGING FACE / LOCAL LAUNCH
# ============================================================
if __name__ == "__main__":
demo.queue(
default_concurrency_limit=1
).launch(**(_APP_ASSETS if _GRADIO_MAJOR >= 6 else {}))
# ============================================================
# SAGE 2.0
# Strategic AI Governance and Engagement Advisor
# Hugging Face Spaces Deployment
# ============================================================
import os
import re
import json
import shutil
import subprocess
import uuid
import time
import asyncio
from pathlib import Path
import numpy as np
import torch
import gradio as gr
import edge_tts
from transformers import (
AutoTokenizer,
AutoModelForCausalLM
)
from peft import PeftModel
from langchain_huggingface import HuggingFaceEmbeddings
from langchain_community.vectorstores import FAISS
# ============================================================
# PATHS
# ============================================================
APP_DIR = Path(__file__).resolve().parent
MODEL_DIR = APP_DIR / "model"
VECTOR_DIR = APP_DIR / "vectorstore"
AUDIO_DIR = APP_DIR / "Generated_Audio"
AUDIO_DIR.mkdir(exist_ok=True)
AVATAR_FILE = APP_DIR / "sage_avatar.html"
if not AVATAR_FILE.exists():
raise FileNotFoundError(f"Missing avatar file: {AVATAR_FILE}")
# Serve the avatar as a real standalone browser document.
# This lets its JavaScript/WebGL execute normally inside the iframe.
gr.set_static_paths(paths=[AVATAR_FILE])
# Same-origin Gradio route for the standalone avatar page.
AVATAR_URL = "/gradio_api/file=sage_avatar.html"
# Set a Space variable SAGE_LIPSYNC_DEBUG=1 to show a live viseme/envelope
# overlay inside the avatar (cue, env level, clock, timing source).
if os.getenv("SAGE_LIPSYNC_DEBUG"):
AVATAR_URL += "?debug=1"
# ============================================================
# MODEL SETTINGS
# ============================================================
BASE_MODEL_ID = "unsloth/llama-3-8b-Instruct-bnb-4bit"
EMBED_MODEL_ID = "sentence-transformers/all-mpnet-base-v2"
TOP_K = 5
OOD_DISTANCE_THRESHOLD = 1.20
MAX_NEW_TOKENS = 220
# ============================================================
# LOAD TOKENIZER
# ============================================================
print("Loading tokenizer...")
tokenizer = AutoTokenizer.from_pretrained(
BASE_MODEL_ID,
use_fast=True,
clean_up_tokenization_spaces=False
)
if tokenizer.pad_token is None:
tokenizer.pad_token = tokenizer.eos_token
chat_template_file = MODEL_DIR / "chat_template.jinja"
if chat_template_file.exists():
tokenizer.chat_template = chat_template_file.read_text(
encoding="utf-8"
).strip()