# ============================================================ # 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"""