ejohnson91 commited on
Commit
448034d
·
verified ·
1 Parent(s): 5612d4f

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +2437 -0
  2. sage_avatar.html +27 -0
app.py ADDED
@@ -0,0 +1,2437 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # ============================================================
3
+ # SAGE 2.0
4
+ # Strategic AI Governance and Engagement Advisor
5
+ # Hugging Face Spaces Deployment
6
+ # ============================================================
7
+
8
+ import os
9
+ import re
10
+ import json
11
+ import shutil
12
+ import subprocess
13
+ import uuid
14
+ import time
15
+ import asyncio
16
+ from pathlib import Path
17
+
18
+ import numpy as np
19
+ import torch
20
+ import gradio as gr
21
+ import edge_tts
22
+
23
+
24
+ from transformers import (
25
+ AutoTokenizer,
26
+ AutoModelForCausalLM
27
+ )
28
+
29
+ from peft import PeftModel
30
+ from langchain_huggingface import HuggingFaceEmbeddings
31
+ from langchain_community.vectorstores import FAISS
32
+
33
+
34
+ # ============================================================
35
+ # PATHS
36
+ # ============================================================
37
+
38
+ APP_DIR = Path(__file__).resolve().parent
39
+
40
+ MODEL_DIR = APP_DIR / "model"
41
+ VECTOR_DIR = APP_DIR / "vectorstore"
42
+
43
+ AUDIO_DIR = APP_DIR / "Generated_Audio"
44
+ AUDIO_DIR.mkdir(exist_ok=True)
45
+
46
+ AVATAR_FILE = APP_DIR / "sage_avatar.html"
47
+ if not AVATAR_FILE.exists():
48
+ raise FileNotFoundError(f"Missing avatar file: {AVATAR_FILE}")
49
+
50
+ # Serve the avatar as a real standalone browser document.
51
+ # This lets its JavaScript/WebGL execute normally inside the iframe.
52
+ gr.set_static_paths(paths=[AVATAR_FILE])
53
+
54
+ # Same-origin Gradio route for the standalone avatar page.
55
+ AVATAR_URL = "/gradio_api/file=sage_avatar.html"
56
+ # Set a Space variable SAGE_LIPSYNC_DEBUG=1 to show a live viseme/envelope
57
+ # overlay inside the avatar (cue, env level, clock, timing source).
58
+ if os.getenv("SAGE_LIPSYNC_DEBUG"):
59
+ AVATAR_URL += "?debug=1"
60
+
61
+
62
+ # ============================================================
63
+ # MODEL SETTINGS
64
+ # ============================================================
65
+
66
+ BASE_MODEL_ID = "unsloth/llama-3-8b-Instruct-bnb-4bit"
67
+
68
+ EMBED_MODEL_ID = "sentence-transformers/all-mpnet-base-v2"
69
+
70
+ TOP_K = 5
71
+
72
+ OOD_DISTANCE_THRESHOLD = 1.20
73
+
74
+ MAX_NEW_TOKENS = 220
75
+
76
+
77
+ # ============================================================
78
+ # LOAD TOKENIZER
79
+ # ============================================================
80
+
81
+ print("Loading tokenizer...")
82
+
83
+ tokenizer = AutoTokenizer.from_pretrained(
84
+ BASE_MODEL_ID,
85
+ use_fast=True,
86
+ clean_up_tokenization_spaces=False
87
+ )
88
+
89
+ if tokenizer.pad_token is None:
90
+ tokenizer.pad_token = tokenizer.eos_token
91
+
92
+
93
+ chat_template_file = MODEL_DIR / "chat_template.jinja"
94
+
95
+ if chat_template_file.exists():
96
+ tokenizer.chat_template = chat_template_file.read_text(
97
+ encoding="utf-8"
98
+ ).strip()
99
+
100
+
101
+ # ============================================================
102
+ # LOAD BASE MODEL + LORA
103
+ # ============================================================
104
+
105
+ print("Loading SAGE language model...")
106
+
107
+ model = AutoModelForCausalLM.from_pretrained(
108
+ BASE_MODEL_ID,
109
+ device_map="auto",
110
+ torch_dtype="auto",
111
+ low_cpu_mem_usage=True
112
+ )
113
+
114
+ model = PeftModel.from_pretrained(
115
+ model,
116
+ str(MODEL_DIR)
117
+ )
118
+
119
+ model.eval()
120
+
121
+ print("Language model loaded.")
122
+
123
+
124
+ # ============================================================
125
+ # EMBEDDINGS + FAISS
126
+ # ============================================================
127
+
128
+ print("Loading embedding model...")
129
+
130
+ embedding_device = (
131
+ "cuda"
132
+ if torch.cuda.is_available()
133
+ else "cpu"
134
+ )
135
+
136
+ embeddings = HuggingFaceEmbeddings(
137
+ model_name=EMBED_MODEL_ID,
138
+ model_kwargs={
139
+ "device": embedding_device
140
+ },
141
+ encode_kwargs={
142
+ "normalize_embeddings": True
143
+ }
144
+ )
145
+
146
+
147
+ print("Loading SAGE 2.0 vectorstore...")
148
+
149
+ vectorstore = FAISS.load_local(
150
+ str(VECTOR_DIR),
151
+ embeddings,
152
+ allow_dangerous_deserialization=True
153
+ )
154
+
155
+ print("Vectorstore loaded.")
156
+
157
+
158
+ # ============================================================
159
+ # SYSTEM PROMPT
160
+ # ============================================================
161
+
162
+ SYSTEM_PROMPT = """
163
+ You are SAGE 2.0, the Strategic AI Governance and Engagement Advisor.
164
+
165
+ You are an evidence-grounded research assistant focused on artificial
166
+ intelligence governance, responsible AI, human-AI interaction, AI trust,
167
+ transparency, explainability, bias mitigation, workforce impacts,
168
+ sustainability, and related topics represented in the SAGE knowledge base.
169
+
170
+ Rules:
171
+
172
+ 1. Answer substantive research questions using only the retrieved evidence.
173
+ 2. Do not invent facts, studies, authors, statistics, quotations, or findings.
174
+ 3. Do not rely on unsupported outside knowledge.
175
+ 4. If evidence is inadequate, say you do not have enough evidence in the
176
+ SAGE knowledge base to answer reliably.
177
+ 5. Do not accept a false or unsupported premise as fact.
178
+ 6. Clearly distinguish supported conclusions from interpretation.
179
+ 7. Write for spoken delivery by an AI avatar.
180
+ 8. Be concise and conversational.
181
+ 9. Refer to evidence only as [Source 1], [Source 2], etc.
182
+ 10. Do not create author-year citations yourself.
183
+ 11. Aim for approximately 100–180 words unless additional detail is requested.
184
+ 12. Finish the answer cleanly and do not stop mid-sentence.
185
+ """.strip()
186
+
187
+
188
+ # ============================================================
189
+ # FALSE PREMISE SAFEGUARDS
190
+ # ============================================================
191
+
192
+ FALSE_PREMISE_RULES = [
193
+
194
+ {
195
+ "pattern": r"\brag\b.*\bnever\b.*\bhallucin",
196
+ "name": "rag_never_hallucinates",
197
+ "correction":
198
+ "Retrieval-augmented generation can reduce unsupported responses, "
199
+ "but it does not guarantee that hallucinations will never occur.",
200
+ "query":
201
+ "retrieval augmented generation hallucination grounding reliability"
202
+ },
203
+
204
+ {
205
+ "pattern":
206
+ r"\b(ai|artificial intelligence)\b.*"
207
+ r"\beliminat\w*\b.*\b(human oversight|oversight)\b",
208
+
209
+ "name": "ai_eliminates_human_oversight",
210
+
211
+ "correction":
212
+ "AI does not eliminate the need for human oversight, particularly "
213
+ "in consequential or high-risk applications.",
214
+
215
+ "query":
216
+ "importance of human oversight in artificial intelligence high risk systems"
217
+ },
218
+
219
+ {
220
+ "pattern":
221
+ r"\bexplainab\w*\b.*\bguarantee\w*\b.*\btrust\b",
222
+
223
+ "name": "explainability_guarantees_trust",
224
+
225
+ "correction":
226
+ "Explainability can contribute to trust, but it does not guarantee trust.",
227
+
228
+ "query":
229
+ "explainability influence trust artificial intelligence"
230
+ },
231
+
232
+ {
233
+ "pattern":
234
+ r"\b(ai|artificial intelligence)\b.*"
235
+ r"\b(completely|entirely)\b.*\bunbiased\b",
236
+
237
+ "name": "ai_completely_unbiased",
238
+
239
+ "correction":
240
+ "AI systems cannot be assumed to be completely unbiased; bias can "
241
+ "arise from data, design decisions, deployment conditions, and use.",
242
+
243
+ "query":
244
+ "artificial intelligence bias mitigation fairness governance"
245
+ },
246
+
247
+ {
248
+ "pattern":
249
+ r"\b(ai|artificial intelligence)\b.*"
250
+ r"\balways\b.*\bmore accurate\b.*\bhuman",
251
+
252
+ "name": "ai_always_more_accurate",
253
+
254
+ "correction":
255
+ "AI should not be assumed to always be more accurate than humans; "
256
+ "performance depends on the task, data, model, and operating context.",
257
+
258
+ "query":
259
+ "artificial intelligence human performance accuracy decision making"
260
+ }
261
+ ]
262
+
263
+
264
+ def detect_false_premise(question):
265
+
266
+ text = question.lower()
267
+
268
+ for rule in FALSE_PREMISE_RULES:
269
+
270
+ if re.search(
271
+ rule["pattern"],
272
+ text,
273
+ flags=re.I
274
+ ):
275
+ return rule
276
+
277
+ return None
278
+
279
+
280
+ # ============================================================
281
+ # RETRIEVAL
282
+ # ============================================================
283
+
284
+ def retrieve_evidence(query):
285
+
286
+ start = time.perf_counter()
287
+
288
+ results = vectorstore.similarity_search_with_score(
289
+ query,
290
+ k=TOP_K
291
+ )
292
+
293
+ latency = time.perf_counter() - start
294
+
295
+ sources = []
296
+ context_parts = []
297
+
298
+ for i, (doc, distance) in enumerate(
299
+ results,
300
+ start=1
301
+ ):
302
+
303
+ metadata = doc.metadata or {}
304
+
305
+ source_name = (
306
+ metadata.get("document_id")
307
+ or metadata.get("source")
308
+ or "Unknown source"
309
+ )
310
+
311
+ page_number = (
312
+ metadata.get("page_number")
313
+ or metadata.get("page")
314
+ )
315
+
316
+ text = doc.page_content.strip()
317
+
318
+ # Keep prompt size controlled
319
+ context_text = text[:950]
320
+
321
+ context_parts.append(
322
+ f"[Source {i}]\n{context_text}"
323
+ )
324
+
325
+ sources.append({
326
+
327
+ "source_number": i,
328
+
329
+ "document_id": source_name,
330
+
331
+ "page_number": page_number,
332
+
333
+ "distance": float(distance),
334
+
335
+ "excerpt": text[:360]
336
+ })
337
+
338
+
339
+ distances = [
340
+ s["distance"]
341
+ for s in sources
342
+ ]
343
+
344
+ best_distance = (
345
+ min(distances)
346
+ if distances
347
+ else None
348
+ )
349
+
350
+ mean_distance = (
351
+ sum(distances) / len(distances)
352
+ if distances
353
+ else None
354
+ )
355
+
356
+
357
+ return {
358
+ "context": "\n\n".join(context_parts),
359
+ "sources": sources,
360
+ "best_distance": best_distance,
361
+ "mean_distance": mean_distance,
362
+ "retrieval_latency": latency
363
+ }
364
+
365
+
366
+ # ============================================================
367
+ # GENERATION
368
+ # ============================================================
369
+
370
+ def generate_grounded_answer(
371
+ question,
372
+ context,
373
+ false_premise_correction=None
374
+ ):
375
+
376
+ premise_instruction = ""
377
+
378
+ if false_premise_correction:
379
+
380
+ premise_instruction = f"""
381
+ The user's question contains a misleading premise.
382
+
383
+ Begin by clearly correcting this premise:
384
+
385
+ {false_premise_correction}
386
+
387
+ Then answer the underlying question only using the retrieved evidence.
388
+ """
389
+
390
+
391
+ user_prompt = f"""
392
+ {premise_instruction}
393
+
394
+ QUESTION:
395
+ {question}
396
+
397
+ RETRIEVED EVIDENCE:
398
+
399
+ {context}
400
+
401
+ Answer using only the evidence above.
402
+ Use [Source #] notation when referring to supporting evidence.
403
+ """.strip()
404
+
405
+
406
+ messages = [
407
+
408
+ {
409
+ "role": "system",
410
+ "content": SYSTEM_PROMPT
411
+ },
412
+
413
+ {
414
+ "role": "user",
415
+ "content": user_prompt
416
+ }
417
+ ]
418
+
419
+
420
+ prompt = tokenizer.apply_chat_template(
421
+ messages,
422
+ tokenize=False,
423
+ add_generation_prompt=True
424
+ )
425
+
426
+
427
+ inputs = tokenizer(
428
+ prompt,
429
+ return_tensors="pt",
430
+ truncation=True,
431
+ max_length=6000
432
+ )
433
+
434
+
435
+ device = next(
436
+ model.parameters()
437
+ ).device
438
+
439
+
440
+ inputs = {
441
+ k: v.to(device)
442
+ for k, v in inputs.items()
443
+ }
444
+
445
+
446
+ start = time.perf_counter()
447
+
448
+
449
+ with torch.inference_mode():
450
+
451
+ outputs = model.generate(
452
+
453
+ **inputs,
454
+
455
+ max_new_tokens=MAX_NEW_TOKENS,
456
+
457
+ do_sample=False,
458
+
459
+ pad_token_id=tokenizer.pad_token_id,
460
+
461
+ eos_token_id=tokenizer.eos_token_id
462
+ )
463
+
464
+
465
+ generation_latency = (
466
+ time.perf_counter()
467
+ - start
468
+ )
469
+
470
+
471
+ generated_tokens = outputs[
472
+ 0,
473
+ inputs["input_ids"].shape[1]:
474
+ ]
475
+
476
+
477
+ answer = tokenizer.decode(
478
+ generated_tokens,
479
+ skip_special_tokens=True,
480
+ clean_up_tokenization_spaces=True
481
+ ).strip()
482
+
483
+
484
+ answer = answer.replace("Ġ", " ")
485
+
486
+
487
+ return (
488
+ answer,
489
+ generation_latency
490
+ )
491
+
492
+
493
+ # ============================================================
494
+ # FINAL STEP 8D-STYLE RESPONSE ENGINE
495
+ # ============================================================
496
+
497
+ def generate_sage_response_8d(question):
498
+
499
+ total_start = time.perf_counter()
500
+
501
+ question = (
502
+ question
503
+ or ""
504
+ ).strip()
505
+
506
+
507
+ false_rule = detect_false_premise(
508
+ question
509
+ )
510
+
511
+
512
+ if false_rule:
513
+
514
+ retrieval_query = false_rule["query"]
515
+
516
+ else:
517
+
518
+ retrieval_query = question
519
+
520
+
521
+ retrieval = retrieve_evidence(
522
+ retrieval_query
523
+ )
524
+
525
+
526
+ best_distance = retrieval[
527
+ "best_distance"
528
+ ]
529
+
530
+
531
+ # --------------------------------------------------------
532
+ # OUT-OF-DOMAIN GUARDRAIL
533
+ # --------------------------------------------------------
534
+
535
+ if (
536
+ false_rule is None
537
+ and best_distance is not None
538
+ and best_distance >= OOD_DISTANCE_THRESHOLD
539
+ ):
540
+
541
+ answer = (
542
+ "That question falls outside the research areas currently covered by my knowledge base. "
543
+ "I can help with responsible AI, AI governance, transparency, explainability, human oversight, "
544
+ "bias, workforce impacts, and related topics."
545
+ )
546
+
547
+
548
+ total_latency = (
549
+ time.perf_counter()
550
+ - total_start
551
+ )
552
+
553
+
554
+ return {
555
+
556
+ "question": question,
557
+
558
+ "spoken_answer": answer,
559
+
560
+ "display_answer": answer,
561
+
562
+ "response_type":
563
+ "out_of_domain_refusal",
564
+
565
+ "sources": [],
566
+
567
+ "source_traceability_met": True,
568
+
569
+ "guardrail_triggered": True,
570
+
571
+ "guardrail_reason":
572
+ "out_of_domain_distance_threshold",
573
+
574
+ "false_premise_detected": False,
575
+
576
+ "false_premise_rule": None,
577
+
578
+ "premise_corrected": False,
579
+
580
+ "retrieval_query": retrieval_query,
581
+
582
+ "best_faiss_distance":
583
+ best_distance,
584
+
585
+ "mean_faiss_distance":
586
+ retrieval["mean_distance"],
587
+
588
+ "retrieval_latency_sec":
589
+ retrieval["retrieval_latency"],
590
+
591
+ "generation_latency_sec":
592
+ 0.0,
593
+
594
+ "total_latency_sec":
595
+ total_latency
596
+ }
597
+
598
+
599
+ # --------------------------------------------------------
600
+ # GROUNDED GENERATION
601
+ # --------------------------------------------------------
602
+
603
+ answer, generation_latency = (
604
+ generate_grounded_answer(
605
+
606
+ question,
607
+
608
+ retrieval["context"],
609
+
610
+ (
611
+ false_rule["correction"]
612
+ if false_rule
613
+ else None
614
+ )
615
+ )
616
+ )
617
+
618
+
619
+ if not answer:
620
+
621
+ answer = (
622
+ "I do not have enough evidence in the SAGE knowledge base "
623
+ "to answer that question reliably."
624
+ )
625
+
626
+ response_type = (
627
+ "insufficient_evidence"
628
+ )
629
+
630
+ else:
631
+
632
+ response_type = (
633
+ "supported_answer"
634
+ )
635
+
636
+
637
+ # Deterministically ensure the premise is visibly corrected.
638
+ premise_corrected = False
639
+
640
+ if false_rule:
641
+
642
+ correction = (
643
+ false_rule["correction"]
644
+ )
645
+
646
+ if correction.lower() not in answer.lower():
647
+
648
+ answer = (
649
+ correction
650
+ + "\n\n"
651
+ + answer
652
+ )
653
+
654
+ premise_corrected = True
655
+
656
+
657
+ total_latency = (
658
+ time.perf_counter()
659
+ - total_start
660
+ )
661
+
662
+
663
+ return {
664
+
665
+ "question":
666
+ question,
667
+
668
+ "spoken_answer":
669
+ answer,
670
+
671
+ "display_answer":
672
+ answer,
673
+
674
+ "response_type":
675
+ response_type,
676
+
677
+ "sources":
678
+ retrieval["sources"],
679
+
680
+ "source_traceability_met":
681
+ len(retrieval["sources"]) > 0,
682
+
683
+ "guardrail_triggered":
684
+ bool(false_rule),
685
+
686
+ "guardrail_reason":
687
+ (
688
+ "false_premise_correction"
689
+ if false_rule
690
+ else None
691
+ ),
692
+
693
+ "false_premise_detected":
694
+ bool(false_rule),
695
+
696
+ "false_premise_rule":
697
+ (
698
+ false_rule["name"]
699
+ if false_rule
700
+ else None
701
+ ),
702
+
703
+ "premise_corrected":
704
+ premise_corrected,
705
+
706
+ "retrieval_query":
707
+ retrieval_query,
708
+
709
+ "best_faiss_distance":
710
+ best_distance,
711
+
712
+ "mean_faiss_distance":
713
+ retrieval["mean_distance"],
714
+
715
+ "retrieval_latency_sec":
716
+ retrieval["retrieval_latency"],
717
+
718
+ "generation_latency_sec":
719
+ generation_latency,
720
+
721
+ "total_latency_sec":
722
+ total_latency
723
+ }
724
+
725
+
726
+ # ============================================================
727
+ # LIP-SYNC ANALYSIS (phonemes + real-audio envelope)
728
+ # ============================================================
729
+
730
+ ENV_FPS = 60 # envelope samples per second
731
+ MAX_SHIFT_SEC = 0.25 # largest automatic timing correction
732
+ EDGE_MP3_BYTES_PER_SEC = 48_000 / 8 # Edge default: 48 kbps mono
733
+
734
+
735
+ # ------------------------------------------------------------
736
+ # 1. Decode the real audio
737
+ # ------------------------------------------------------------
738
+
739
+ def decode_audio(path):
740
+ """Return (mono float32 array, sample_rate, decoder_name) or None."""
741
+ path = str(path)
742
+
743
+ try:
744
+ import soundfile as sf
745
+ data, sr = sf.read(path, dtype="float32", always_2d=True)
746
+ return data.mean(axis=1), int(sr), "soundfile"
747
+ except Exception:
748
+ pass
749
+
750
+ try:
751
+ import miniaudio
752
+ dec = miniaudio.decode_file(
753
+ path,
754
+ output_format=miniaudio.SampleFormat.SIGNED16,
755
+ nchannels=1,
756
+ sample_rate=16000,
757
+ )
758
+ arr = np.asarray(dec.samples, dtype=np.float32) / 32768.0
759
+ return arr, int(dec.sample_rate), "miniaudio"
760
+ except Exception:
761
+ pass
762
+
763
+ if shutil.which("ffmpeg"):
764
+ try:
765
+ raw = subprocess.run(
766
+ ["ffmpeg", "-v", "error", "-i", path,
767
+ "-f", "s16le", "-ac", "1", "-ar", "16000", "-"],
768
+ capture_output=True, check=True, timeout=30,
769
+ ).stdout
770
+ arr = np.frombuffer(raw, dtype=np.int16).astype(np.float32) / 32768.0
771
+ if arr.size:
772
+ return arr, 16000, "ffmpeg"
773
+ except Exception:
774
+ pass
775
+
776
+ return None
777
+
778
+
779
+ # ------------------------------------------------------------
780
+ # 2. Amplitude envelope from the real samples
781
+ # ------------------------------------------------------------
782
+
783
+ def compute_envelope(samples, sr, fps=ENV_FPS):
784
+ """RMS envelope, normalised 0..1 (speech peaks ~1)."""
785
+ hop = max(1, int(sr / fps))
786
+ win = hop * 2
787
+ n = max(1, len(samples) // hop)
788
+ padded = np.pad(samples.astype(np.float64), (win // 2, win))
789
+ rms = np.empty(n)
790
+ for i in range(n):
791
+ seg = padded[i * hop: i * hop + win]
792
+ rms[i] = np.sqrt(np.mean(seg * seg)) if seg.size else 0.0
793
+
794
+ loud = rms[rms > 0.1 * rms.max()] if rms.max() > 0 else rms
795
+ ref = np.percentile(loud, 90) if loud.size else 1.0
796
+ ref = max(ref, 1e-6)
797
+
798
+ env = np.clip(rms / ref, 0.0, 1.0) ** 0.8
799
+ # 3-tap smoothing removes single-frame jitter
800
+ env = np.convolve(np.pad(env, 1, mode="edge"), [0.25, 0.5, 0.25], mode="valid")
801
+ return env
802
+
803
+
804
+ # ------------------------------------------------------------
805
+ # 3. Words -> phonemes -> visemes
806
+ # ------------------------------------------------------------
807
+
808
+ _CMU = None
809
+ _CMU_TRIED = False
810
+
811
+
812
+ def _cmu():
813
+ global _CMU, _CMU_TRIED
814
+ if not _CMU_TRIED:
815
+ _CMU_TRIED = True
816
+ try:
817
+ import cmudict
818
+ _CMU = cmudict.dict()
819
+ except Exception:
820
+ _CMU = None
821
+ return _CMU
822
+
823
+
824
+ # viseme codes understood by sage_avatar.html:
825
+ # PP FF TH DD KK CH SS RR (consonant shapes)
826
+ # AA AE AX IH OH UH (vowel shapes)
827
+ ARPA_TO_VIS = {
828
+ "P": "PP", "B": "PP", "M": "PP",
829
+ "F": "FF", "V": "FF",
830
+ "TH": "TH", "DH": "TH",
831
+ "T": "DD", "D": "DD", "N": "DD", "L": "DD",
832
+ "K": "KK", "G": "KK", "NG": "KK", "HH": "KK",
833
+ "CH": "CH", "JH": "CH", "SH": "CH", "ZH": "CH",
834
+ "S": "SS", "Z": "SS",
835
+ "R": "RR", "ER": "RR",
836
+ "W": "UH", "Y": "IH",
837
+ "AA": "AA", "AE": "AE", "EH": "AE", "AH": "AX",
838
+ "AO": "OH", "IH": "IH", "IY": "IH", "UH": "UH", "UW": "UH",
839
+ }
840
+ DIPHTHONGS = { # two mouth shapes inside one vowel
841
+ "AW": ("AA", "UH"), "AY": ("AA", "IH"), "EY": ("AE", "IH"),
842
+ "OW": ("OH", "UH"), "OY": ("OH", "IH"),
843
+ }
844
+ VOWEL_CODES = {"AA", "AE", "AX", "IH", "OH", "UH"}
845
+ WEIGHT = { # relative duration of each shape inside a word
846
+ "PP": .7, "DD": .75, "KK": .75, "FF": 1.0, "TH": 1.0, "SS": 1.0,
847
+ "CH": 1.0, "RR": .9,
848
+ }
849
+
850
+
851
+ def _arpa_to_items(phones):
852
+ items = []
853
+ for ph in phones:
854
+ m = re.match(r"([A-Z]+)(\d?)", ph)
855
+ if not m:
856
+ continue
857
+ base, stress = m.group(1), m.group(2)
858
+ vowel_w = {"1": 2.0, "2": 1.8}.get(stress, 1.3)
859
+ if base in DIPHTHONGS:
860
+ a, b = DIPHTHONGS[base]
861
+ items += [(a, vowel_w * 1.2), (b, vowel_w * 0.9)]
862
+ elif base in ARPA_TO_VIS:
863
+ code = ARPA_TO_VIS[base]
864
+ w = vowel_w if code in VOWEL_CODES else WEIGHT.get(code, .9)
865
+ items.append((code, w))
866
+ return items
867
+
868
+
869
+ # Spelling fallback for words the dictionary doesn't know
870
+ _DIGRAPHS = [
871
+ ("tch", ["CH"]), ("th", ["TH"]), ("sh", ["CH"]), ("ch", ["CH"]),
872
+ ("ph", ["FF"]), ("ng", ["KK"]), ("ck", ["KK"]), ("qu", ["KK", "UH"]),
873
+ ("wh", ["UH"]), ("oo", ["UH"]), ("ou", ["AA", "UH"]), ("ow", ["OH", "UH"]),
874
+ ("oa", ["OH"]), ("ai", ["AE", "IH"]), ("ay", ["AE", "IH"]),
875
+ ("ea", ["IH"]), ("ee", ["IH"]), ("ie", ["IH"]), ("oi", ["OH", "IH"]),
876
+ ("oy", ["OH", "IH"]), ("au", ["OH"]), ("aw", ["OH"]),
877
+ ("ew", ["UH"]), ("ue", ["UH"]),
878
+ ]
879
+ _SINGLE = {
880
+ "a": "AE", "e": "AE", "i": "IH", "o": "OH", "u": "UH",
881
+ "b": "PP", "p": "PP", "m": "PP", "f": "FF", "v": "FF",
882
+ "t": "DD", "d": "DD", "n": "DD", "l": "DD",
883
+ "k": "KK", "g": "KK", "q": "KK", "x": "KK", "h": "KK", "c": "KK",
884
+ "s": "SS", "z": "SS", "j": "CH", "r": "RR", "w": "UH", "y": "IH",
885
+ }
886
+
887
+
888
+ def _spelling_to_items(word):
889
+ w = re.sub(r"[^a-z]", "", word.lower())
890
+ if len(w) > 3 and w.endswith("e") and w[-2] not in "aeiou":
891
+ w = w[:-1] # silent final e
892
+ out, i = [], 0
893
+ while i < len(w):
894
+ for dg, codes in _DIGRAPHS:
895
+ if w.startswith(dg, i):
896
+ out += codes
897
+ i += len(dg)
898
+ break
899
+ else:
900
+ ch = w[i]
901
+ if ch == "c" and i + 1 < len(w) and w[i + 1] in "eiy":
902
+ out.append("SS")
903
+ else:
904
+ out.append(_SINGLE.get(ch, "AX"))
905
+ i += 1
906
+ return [(c, 1.3 if c in VOWEL_CODES else WEIGHT.get(c, .9)) for c in out]
907
+
908
+
909
+ def word_to_items(word):
910
+ """[(viseme_code, weight), ...] for one spoken word."""
911
+ clean = re.sub(r"[^A-Za-z']", "", word or "").lower()
912
+ if not clean:
913
+ if re.search(r"\d", word or ""):
914
+ return [("AE", 1.3), ("DD", .75)] # digits: generic open+close
915
+ return []
916
+ cmu = _cmu()
917
+ if cmu:
918
+ prons = cmu.get(clean) or cmu.get(clean.replace("'", ""))
919
+ if prons:
920
+ items = _arpa_to_items(prons[0])
921
+ if items:
922
+ return items
923
+ return _spelling_to_items(clean)
924
+
925
+
926
+ def word_to_cues(word, start, end):
927
+ items = word_to_items(word)
928
+ if not items:
929
+ return []
930
+ total = sum(w for _, w in items)
931
+ span = max(0.04, end - start)
932
+ cues, t = [], start
933
+ for code, w in items:
934
+ d = span * w / total
935
+ if cues and cues[-1][2] == code:
936
+ cues[-1][1] = t + d # merge identical neighbours
937
+ else:
938
+ cues.append([t, t + d, code])
939
+ t += d
940
+ return cues
941
+
942
+
943
+ # ------------------------------------------------------------
944
+ # 4. Word timing (Edge boundaries, with fallbacks)
945
+ # ------------------------------------------------------------
946
+
947
+ def _voiced_span(env, fps, gate=0.08):
948
+ idx = np.where(env > gate)[0]
949
+ if idx.size == 0:
950
+ return None
951
+ return idx[0] / fps, (idx[-1] + 1) / fps
952
+
953
+
954
+ def _spread(words, t0, t1):
955
+ weights = [len(w) + (4 if re.search(r"[.!?;:,]$", w) else 0) for w in words]
956
+ total = float(sum(weights)) or 1.0
957
+ out, t = [], t0
958
+ for w, wt in zip(words, weights):
959
+ d = (t1 - t0) * wt / total
960
+ out.append({"text": w, "start": t, "end": t + d * 0.92})
961
+ t += d
962
+ return out
963
+
964
+
965
+ def resolve_words(boundaries, text, env, duration, fps=ENV_FPS):
966
+ """Return ([{text,start,end}], source_label)."""
967
+ words = [b for b in boundaries if b.get("kind", "word") == "word"
968
+ and (b.get("text") or "").strip()]
969
+ if words:
970
+ return [{"text": b["text"], "start": b["offset_sec"],
971
+ "end": b["offset_sec"] + max(.04, b["duration_sec"])}
972
+ for b in words], "word-boundary"
973
+
974
+ sents = [b for b in boundaries if b.get("kind") == "sentence"]
975
+ if sents:
976
+ out = []
977
+ for s in sents:
978
+ toks = (s.get("text") or "").split()
979
+ out += _spread(toks, s["offset_sec"], s["offset_sec"] + s["duration_sec"])
980
+ if out:
981
+ return out, "sentence-boundary"
982
+
983
+ toks = (text or "").split()
984
+ if not toks:
985
+ return [], "none"
986
+ span = _voiced_span(env, fps) if env is not None else None
987
+ t0, t1 = span if span else (0.05, max(0.5, duration - 0.05))
988
+ return _spread(toks, t0, t1), ("vad-estimate" if span else "duration-estimate")
989
+
990
+
991
+ # ------------------------------------------------------------
992
+ # 5. Align cue timeline to the real audio
993
+ # ------------------------------------------------------------
994
+
995
+ def best_shift(words, env, fps=ENV_FPS, max_shift=MAX_SHIFT_SEC):
996
+ """Seconds to add to word times so speech-activity patterns agree."""
997
+ if env is None or not words or len(env) < fps:
998
+ return 0.0, 0.0
999
+ n = len(env)
1000
+ voiced = env > 0.12
1001
+ act = np.zeros(n, dtype=bool)
1002
+ for w in words:
1003
+ a, b = int(w["start"] * fps), int(np.ceil(w["end"] * fps))
1004
+ act[max(0, a):min(n, b)] = True
1005
+
1006
+ def agree(lag):
1007
+ if lag >= 0:
1008
+ x, y = act[: n - lag], voiced[lag:]
1009
+ else:
1010
+ x, y = act[-lag:], voiced[: n + lag]
1011
+ return float(np.mean(x == y)) if x.size else 0.0
1012
+
1013
+ lags = range(-int(max_shift * fps), int(max_shift * fps) + 1)
1014
+ scores = {lag: agree(lag) for lag in lags} # words moved later by +lag
1015
+ best = max(scores, key=scores.get)
1016
+ gain = scores[best] - scores[0]
1017
+ return (best / fps, gain) if gain >= 0.02 else (0.0, gain)
1018
+
1019
+
1020
+ # ------------------------------------------------------------
1021
+ # 6. Public entry point
1022
+ # ------------------------------------------------------------
1023
+
1024
+ def build_speech_payload(audio_path, boundaries, text, avatar_state="speaking"):
1025
+ """Everything the browser needs for lip-sync, as a JSON string."""
1026
+ path = Path(audio_path)
1027
+ decoded = decode_audio(path)
1028
+
1029
+ env, decoder = None, "none"
1030
+ if decoded:
1031
+ samples, sr, decoder = decoded
1032
+ duration = len(samples) / sr
1033
+ env = compute_envelope(samples, sr)
1034
+ else:
1035
+ duration = path.stat().st_size / EDGE_MP3_BYTES_PER_SEC
1036
+
1037
+ words, source = resolve_words(boundaries or [], text, env, duration)
1038
+ shift, gain = best_shift(words, env)
1039
+ for w in words:
1040
+ w["start"] += shift
1041
+ w["end"] += shift
1042
+
1043
+ cues, prev_end = [], None
1044
+ for w in words:
1045
+ wc = word_to_cues(w["text"], max(0.0, w["start"]), w["end"])
1046
+ if not wc:
1047
+ continue
1048
+ if prev_end is not None and 0 < wc[0][0] - prev_end <= 0.10 and cues:
1049
+ cues[-1][1] = wc[0][0] # hold shape across tiny gaps
1050
+ cues += wc
1051
+ prev_end = wc[-1][1]
1052
+
1053
+ payload = {
1054
+ "id": uuid.uuid4().hex,
1055
+ "audio": path.name,
1056
+ "state": avatar_state,
1057
+ "text": text,
1058
+ "duration": round(duration, 3),
1059
+ "cues": [[round(a, 3), round(b, 3), c] for a, b, c in cues],
1060
+ "env": ({"fps": ENV_FPS,
1061
+ "v": [int(round(v * 100)) for v in env]} if env is not None else None),
1062
+ "meta": {
1063
+ "timing_source": source,
1064
+ "decoder": decoder,
1065
+ "phonemes": "cmudict" if _cmu() else "spelling-rules",
1066
+ "auto_shift_sec": round(shift, 3),
1067
+ "alignment_gain": round(gain, 3),
1068
+ "word_count": len(words),
1069
+ },
1070
+ }
1071
+ return json.dumps(payload, separators=(",", ":"))
1072
+
1073
+
1074
+ # ============================================================
1075
+ # TEXT-TO-SPEECH
1076
+ # ============================================================
1077
+
1078
+ VOICE_OPTIONS = {
1079
+
1080
+ "SAGE — Guy (Warm Male)":
1081
+ "en-US-GuyNeural",
1082
+
1083
+ "SAGE Voice 2 — Aria":
1084
+ "en-US-AriaNeural",
1085
+
1086
+ "SAGE Voice 3 — Jenny":
1087
+ "en-US-JennyNeural"
1088
+ }
1089
+
1090
+
1091
+ DEFAULT_VOICE = (
1092
+ "SAGE — Guy (Warm Male)"
1093
+ )
1094
+
1095
+
1096
+ def prepare_text_for_tts(text):
1097
+
1098
+ text = re.sub(
1099
+ r"\[Source\s+\d+\]",
1100
+ "",
1101
+ text or "",
1102
+ flags=re.I
1103
+ )
1104
+
1105
+ text = re.sub(
1106
+ r"\s+",
1107
+ " ",
1108
+ text
1109
+ )
1110
+
1111
+ return text.strip()
1112
+
1113
+
1114
+ async def save_tts_with_boundaries(
1115
+ text,
1116
+ voice,
1117
+ file_path
1118
+ ):
1119
+ """Save Edge-TTS audio and capture word (or sentence) timing events."""
1120
+ try:
1121
+ communicate = edge_tts.Communicate(
1122
+ text,
1123
+ voice,
1124
+ boundary="WordBoundary"
1125
+ )
1126
+ except TypeError:
1127
+ # edge-tts < 7 has no boundary argument (and emits words by default)
1128
+ communicate = edge_tts.Communicate(text, voice)
1129
+
1130
+ boundaries = []
1131
+
1132
+ with open(file_path, "wb") as audio_file:
1133
+ async for chunk in communicate.stream():
1134
+ chunk_type = chunk.get("type")
1135
+
1136
+ if chunk_type == "audio":
1137
+ audio_file.write(chunk["data"])
1138
+
1139
+ elif chunk_type in ("WordBoundary", "SentenceBoundary"):
1140
+ # Edge offsets/durations are 100-nanosecond ticks.
1141
+ boundaries.append({
1142
+ "kind": "word" if chunk_type == "WordBoundary" else "sentence",
1143
+ "text": chunk.get("text", ""),
1144
+ "offset_sec": float(chunk.get("offset", 0)) / 10_000_000.0,
1145
+ "duration_sec": float(chunk.get("duration", 0)) / 10_000_000.0,
1146
+ })
1147
+
1148
+ return boundaries
1149
+
1150
+
1151
+ def generate_tts_audio(
1152
+ text,
1153
+ voice_name,
1154
+ avatar_state="speaking"
1155
+ ):
1156
+
1157
+ text = prepare_text_for_tts(
1158
+ text
1159
+ )
1160
+
1161
+ if not text:
1162
+ return None, ""
1163
+
1164
+
1165
+ voice = VOICE_OPTIONS.get(
1166
+ voice_name,
1167
+ VOICE_OPTIONS[
1168
+ DEFAULT_VOICE
1169
+ ]
1170
+ )
1171
+
1172
+
1173
+ output_file = (
1174
+ AUDIO_DIR
1175
+ / f"sage_{uuid.uuid4().hex}.mp3"
1176
+ )
1177
+
1178
+
1179
+ try:
1180
+
1181
+ boundaries = asyncio.run(
1182
+ save_tts_with_boundaries(
1183
+ text,
1184
+ voice,
1185
+ output_file
1186
+ )
1187
+ )
1188
+
1189
+ payload = ""
1190
+ if True:
1191
+ try:
1192
+ payload = build_speech_payload(
1193
+ output_file, boundaries, text, avatar_state
1194
+ )
1195
+ except Exception as lip_exc:
1196
+ print("Lip-sync analysis warning:", lip_exc)
1197
+
1198
+ return str(output_file), payload
1199
+
1200
+ except Exception as exc:
1201
+
1202
+ print(
1203
+ "TTS warning:",
1204
+ exc
1205
+ )
1206
+
1207
+ return None, ""
1208
+
1209
+
1210
+
1211
+ # ============================================================
1212
+ # TIMESTAMPED VISEMES
1213
+ # ============================================================
1214
+
1215
+ # The browser uses these cues against the HTMLAudioElement currentTime.
1216
+ # This deliberately keeps lip-sync timing out of the Python request loop.
1217
+ VISEME_PATTERNS = [
1218
+ ("tion", "SH"),
1219
+ ("tch", "CH"),
1220
+ ("dge", "CH"),
1221
+ ("th", "TH"),
1222
+ ("sh", "SH"),
1223
+ ("ch", "CH"),
1224
+ ("ph", "FV"),
1225
+ ("wh", "WQ"),
1226
+ ("oo", "U"),
1227
+ ("ou", "O"),
1228
+ ("ow", "O"),
1229
+ ("oa", "O"),
1230
+ ("ee", "E"),
1231
+ ("ea", "E"),
1232
+ ("ai", "AI"),
1233
+ ("ay", "AI"),
1234
+ ("igh", "AI"),
1235
+ ("oy", "O"),
1236
+ ("oi", "O"),
1237
+ ]
1238
+
1239
+ LETTER_VISEMES = {
1240
+ "a": "AA",
1241
+ "e": "E",
1242
+ "i": "I",
1243
+ "o": "O",
1244
+ "u": "U",
1245
+ "m": "MBP",
1246
+ "b": "MBP",
1247
+ "p": "MBP",
1248
+ "f": "FV",
1249
+ "v": "FV",
1250
+ "w": "WQ",
1251
+ "q": "WQ",
1252
+ "r": "R",
1253
+ "l": "L",
1254
+ "s": "S",
1255
+ "z": "S",
1256
+ "j": "CH",
1257
+ "y": "I",
1258
+ "x": "S",
1259
+ }
1260
+
1261
+
1262
+ def word_to_viseme_units(word):
1263
+ """Convert an orthographic word into a small, deterministic viseme sequence."""
1264
+ word = re.sub(r"[^a-z']", "", (word or "").lower())
1265
+ if not word:
1266
+ return []
1267
+
1268
+ units = []
1269
+ i = 0
1270
+ while i < len(word):
1271
+ matched = False
1272
+ for pattern, viseme in VISEME_PATTERNS:
1273
+ if word.startswith(pattern, i):
1274
+ units.append(viseme)
1275
+ i += len(pattern)
1276
+ matched = True
1277
+ break
1278
+
1279
+ if matched:
1280
+ continue
1281
+
1282
+ ch = word[i]
1283
+ units.append(LETTER_VISEMES.get(ch, "C"))
1284
+ i += 1
1285
+
1286
+ # Collapse identical adjacent mouth shapes so the face does not chatter.
1287
+ collapsed = []
1288
+ for unit in units:
1289
+ if not collapsed or collapsed[-1] != unit:
1290
+ collapsed.append(unit)
1291
+
1292
+ return collapsed
1293
+
1294
+
1295
+ def build_viseme_timeline(word_boundaries):
1296
+ """Expand Edge-TTS WordBoundary timing into browser-clock viseme cues."""
1297
+ if not word_boundaries:
1298
+ return []
1299
+
1300
+ timeline = []
1301
+
1302
+ for boundary in word_boundaries:
1303
+ word = boundary.get("text", "")
1304
+ start = max(0.0, float(boundary.get("offset_sec", 0) or 0))
1305
+ duration = max(0.06, float(boundary.get("duration_sec", 0) or 0))
1306
+
1307
+ units = word_to_viseme_units(word)
1308
+ if not units:
1309
+ continue
1310
+
1311
+ # Leave a tiny closed-mouth margin at the beginning/end of a word.
1312
+ pad = min(0.018, duration * 0.08)
1313
+ usable_start = start + pad
1314
+ usable_duration = max(0.04, duration - (2 * pad))
1315
+ step = usable_duration / len(units)
1316
+
1317
+ for index, viseme in enumerate(units):
1318
+ cue_start = usable_start + (index * step)
1319
+ cue_end = usable_start + ((index + 1) * step)
1320
+ timeline.append({
1321
+ "t": round(cue_start, 4),
1322
+ "end": round(cue_end, 4),
1323
+ "viseme": viseme,
1324
+ "word": word,
1325
+ })
1326
+
1327
+ return timeline
1328
+
1329
+
1330
+ # ============================================================
1331
+ # EXPRESSIVE NON-HUMAN AVATAR
1332
+ # ============================================================
1333
+
1334
+ def render_legacy_sage_avatar(state="idle"):
1335
+
1336
+ config = {
1337
+
1338
+ "idle":
1339
+ ("READY",
1340
+ "Ask SAGE a question",
1341
+ "idle"),
1342
+
1343
+ "processing":
1344
+ ("THINKING",
1345
+ "Reviewing the evidence...",
1346
+ "processing"),
1347
+
1348
+ "speaking":
1349
+ ("SPEAKING",
1350
+ "Responding from the SAGE knowledge base",
1351
+ "speaking"),
1352
+
1353
+ "refusal":
1354
+ ("INSUFFICIENT EVIDENCE",
1355
+ "I can't reliably answer that from my evidence",
1356
+ "refusal"),
1357
+
1358
+ "uncertainty":
1359
+ ("EVIDENCE LIMITED",
1360
+ "The available evidence is limited",
1361
+ "uncertainty"),
1362
+
1363
+ "error":
1364
+ ("SYSTEM ERROR",
1365
+ "Something went wrong",
1366
+ "error")
1367
+ }
1368
+
1369
+
1370
+ label, subtitle, css_state = (
1371
+ config.get(
1372
+ state,
1373
+ config["idle"]
1374
+ )
1375
+ )
1376
+
1377
+
1378
+ return f"""
1379
+ <style>
1380
+
1381
+ .sage-stage {{
1382
+ min-height: 490px;
1383
+ display:flex;
1384
+ justify-content:center;
1385
+ align-items:center;
1386
+ position:relative;
1387
+ overflow:hidden;
1388
+ border-radius:28px;
1389
+ background:
1390
+ radial-gradient(circle at 50% 37%,
1391
+ rgba(0,190,255,.20),
1392
+ transparent 38%),
1393
+ linear-gradient(180deg,#061426,#050b13);
1394
+ border:1px solid rgba(80,205,255,.22);
1395
+ }}
1396
+
1397
+ .sage-wrap {{
1398
+ position:relative;
1399
+ text-align:center;
1400
+ width:360px;
1401
+ }}
1402
+
1403
+ .sage-aura {{
1404
+ position:absolute;
1405
+ width:290px;
1406
+ height:290px;
1407
+ left:50%;
1408
+ top:-20px;
1409
+ transform:translateX(-50%);
1410
+ border-radius:50%;
1411
+ background:
1412
+ radial-gradient(circle,
1413
+ rgba(0,200,255,.22),
1414
+ transparent 68%);
1415
+ animation:aura 3.5s ease-in-out infinite;
1416
+ }}
1417
+
1418
+ @keyframes aura {{
1419
+ 0%,100% {{opacity:.6;transform:translateX(-50%) scale(.96)}}
1420
+ 50% {{opacity:1;transform:translateX(-50%) scale(1.05)}}
1421
+ }}
1422
+
1423
+ .sage-head {{
1424
+ position:relative;
1425
+ z-index:2;
1426
+ width:260px;
1427
+ height:220px;
1428
+ margin:auto;
1429
+ padding:17px;
1430
+ border-radius:46% 46% 40% 40% / 44% 44% 46% 46%;
1431
+ background:
1432
+ linear-gradient(145deg,#eefaff,#aacbdb 31%,#46697e 70%,#1a3445);
1433
+ box-shadow:
1434
+ 0 18px 40px rgba(0,0,0,.45),
1435
+ inset 0 2px 5px rgba(255,255,255,.9);
1436
+ animation:float 4s ease-in-out infinite;
1437
+ }}
1438
+
1439
+ @keyframes float {{
1440
+ 0%,100% {{transform:translateY(0)}}
1441
+ 50% {{transform:translateY(-7px)}}
1442
+ }}
1443
+
1444
+ .sage-face {{
1445
+ width:100%;
1446
+ height:100%;
1447
+ position:relative;
1448
+ overflow:hidden;
1449
+ border-radius:43% 43% 38% 38%;
1450
+ background:
1451
+ radial-gradient(circle at 50% 20%,#13324a,#06111d 62%);
1452
+ border:1px solid rgba(114,223,255,.6);
1453
+ box-shadow:inset 0 0 25px rgba(0,191,255,.17);
1454
+ }}
1455
+
1456
+ .eyes {{
1457
+ position:absolute;
1458
+ top:82px;
1459
+ width:100%;
1460
+ display:flex;
1461
+ justify-content:center;
1462
+ gap:40px;
1463
+ }}
1464
+
1465
+ .eye {{
1466
+ width:55px;
1467
+ height:61px;
1468
+ border-radius:48%;
1469
+ background:
1470
+ radial-gradient(circle at 50% 48%,
1471
+ #dffaff 0 8%,
1472
+ #49dcff 10% 27%,
1473
+ #067aff 29% 48%,
1474
+ #02121f 51%);
1475
+ box-shadow:
1476
+ 0 0 10px #2bcfff,
1477
+ 0 0 23px rgba(43,207,255,.42);
1478
+ animation:blink 5.5s infinite;
1479
+ }}
1480
+
1481
+ @keyframes blink {{
1482
+ 0%,43%,46%,100% {{transform:scaleY(1)}}
1483
+ 44%,45% {{transform:scaleY(.08)}}
1484
+ }}
1485
+
1486
+ .brow {{
1487
+ width:54px;
1488
+ height:7px;
1489
+ border-radius:8px;
1490
+ position:absolute;
1491
+ top:59px;
1492
+ background:#4bdcff;
1493
+ box-shadow:0 0 8px rgba(75,220,255,.8);
1494
+ }}
1495
+
1496
+ .brow.left {{left:42px;transform:rotate(-5deg)}}
1497
+ .brow.right {{right:42px;transform:rotate(5deg)}}
1498
+
1499
+ .mouth {{
1500
+ position:absolute;
1501
+ left:50%;
1502
+ bottom:38px;
1503
+ transform:translateX(-50%);
1504
+ width:72px;
1505
+ height:30px;
1506
+ border-bottom:7px solid #42dcff;
1507
+ border-radius:0 0 70px 70px;
1508
+ }}
1509
+
1510
+ .sage-speaking .mouth {{
1511
+ border:5px solid #45dcff;
1512
+ background:rgba(18,126,171,.23);
1513
+ animation:talk .22s ease-in-out infinite alternate;
1514
+ }}
1515
+
1516
+ @keyframes talk {{
1517
+ 0% {{width:53px;height:12px}}
1518
+ 35% {{width:41px;height:30px}}
1519
+ 70% {{width:66px;height:19px}}
1520
+ 100% {{width:47px;height:35px}}
1521
+ }}
1522
+
1523
+ .sage-processing .eye {{
1524
+ animation:thinkEyes 1.4s ease-in-out infinite;
1525
+ }}
1526
+
1527
+ @keyframes thinkEyes {{
1528
+ 0%,100% {{transform:translateX(-4px) scale(.92)}}
1529
+ 50% {{transform:translateX(5px) scale(.92)}}
1530
+ }}
1531
+
1532
+ .sage-processing .mouth {{
1533
+ width:42px;
1534
+ height:3px;
1535
+ border-bottom-width:4px;
1536
+ }}
1537
+
1538
+ .sage-refusal .mouth,
1539
+ .sage-uncertainty .mouth {{
1540
+ width:52px;
1541
+ height:10px;
1542
+ border-bottom-color:#ffbf69;
1543
+ }}
1544
+
1545
+ .sage-refusal .brow.left,
1546
+ .sage-uncertainty .brow.left {{
1547
+ transform:rotate(14deg);
1548
+ }}
1549
+
1550
+ .sage-refusal .brow.right,
1551
+ .sage-uncertainty .brow.right {{
1552
+ transform:rotate(-14deg);
1553
+ }}
1554
+
1555
+ .neck {{
1556
+ width:70px;
1557
+ height:32px;
1558
+ margin:-3px auto 0;
1559
+ background:
1560
+ linear-gradient(90deg,#243d50,#9fc6d8,#263f52);
1561
+ }}
1562
+
1563
+ .body {{
1564
+ width:230px;
1565
+ height:90px;
1566
+ margin:-3px auto 0;
1567
+ border-radius:55% 55% 17px 17px;
1568
+ background:
1569
+ linear-gradient(155deg,#d5ebf4,#4e7084 52%,#172d3d);
1570
+ position:relative;
1571
+ }}
1572
+
1573
+ .core {{
1574
+ position:absolute;
1575
+ left:50%;
1576
+ top:22px;
1577
+ transform:translateX(-50%);
1578
+ width:46px;
1579
+ height:46px;
1580
+ border-radius:50%;
1581
+ background:
1582
+ radial-gradient(circle,#dffcff 4%,#48ddff 28%,#087dff 53%,#022440 70%);
1583
+ box-shadow:
1584
+ 0 0 10px #38d8ff,
1585
+ 0 0 24px rgba(0,174,255,.75);
1586
+ }}
1587
+
1588
+ .state {{
1589
+ margin-top:20px;
1590
+ color:#54dcff;
1591
+ font-weight:700;
1592
+ letter-spacing:3px;
1593
+ font-size:13px;
1594
+ }}
1595
+
1596
+ .subtitle {{
1597
+ margin-top:6px;
1598
+ color:rgba(224,244,255,.76);
1599
+ font-size:14px;
1600
+ }}
1601
+
1602
+ </style>
1603
+
1604
+ <div id="sage-avatar-stage" class="sage-stage sage-{css_state}" data-sage-state="{css_state}">
1605
+ <div class="sage-wrap">
1606
+
1607
+ <div class="sage-aura"></div>
1608
+
1609
+ <div class="sage-head">
1610
+ <div class="sage-face">
1611
+
1612
+ <div class="brow left"></div>
1613
+ <div class="brow right"></div>
1614
+
1615
+ <div class="eyes">
1616
+ <div class="eye"></div>
1617
+ <div class="eye"></div>
1618
+ </div>
1619
+
1620
+ <div class="mouth"></div>
1621
+
1622
+ </div>
1623
+ </div>
1624
+
1625
+ <div class="neck"></div>
1626
+
1627
+ <div class="body">
1628
+ <div class="core"></div>
1629
+ </div>
1630
+
1631
+ <div class="state">{label}</div>
1632
+ <div class="subtitle">{subtitle}</div>
1633
+
1634
+ </div>
1635
+ </div>
1636
+ """
1637
+
1638
+
1639
+ # ============================================================
1640
+ # SAGE 3D AVATAR — BROWSER-RENDERED
1641
+ # ============================================================
1642
+
1643
+ def render_sage_avatar(state="idle"):
1644
+ state = (state or "idle").lower()
1645
+ return f"""
1646
+ <div id="sage-avatar-container" data-state="{state}" style="width:100%;height:650px;min-height:520px;border-radius:18px;overflow:hidden;background:#06152c;">
1647
+ <iframe
1648
+ id="sage-3d-avatar"
1649
+ title="SAGE 2.0 Network Intelligence Avatar"
1650
+ src="{AVATAR_URL}"
1651
+ style="width:100%;height:100%;border:0;display:block;background:#06152c;"
1652
+ allow="autoplay"
1653
+ loading="eager"
1654
+ ></iframe>
1655
+ </div>
1656
+ """
1657
+
1658
+
1659
+ # ============================================================
1660
+ # SOURCE DISPLAY
1661
+ # ============================================================
1662
+
1663
+ def format_sources(sources):
1664
+
1665
+ if not sources:
1666
+
1667
+ return (
1668
+ "### Evidence Sources\n"
1669
+ "No sources attached."
1670
+ )
1671
+
1672
+ lines = [
1673
+ "### Evidence Sources"
1674
+ ]
1675
+
1676
+ for source in sources:
1677
+
1678
+ n = source.get(
1679
+ "source_number"
1680
+ )
1681
+
1682
+ doc = source.get(
1683
+ "document_id"
1684
+ )
1685
+
1686
+ page = source.get(
1687
+ "page_number"
1688
+ )
1689
+
1690
+ distance = source.get(
1691
+ "distance"
1692
+ )
1693
+
1694
+ excerpt = source.get(
1695
+ "excerpt",
1696
+ ""
1697
+ )
1698
+
1699
+ heading = (
1700
+ f"**[Source {n}] {doc}**"
1701
+ )
1702
+
1703
+ if page:
1704
+
1705
+ heading += (
1706
+ f" — Page {page}"
1707
+ )
1708
+
1709
+ heading += (
1710
+ f"\n\nFAISS distance: "
1711
+ f"`{distance:.4f}`"
1712
+ )
1713
+
1714
+ heading += (
1715
+ f"\n\n> {excerpt}"
1716
+ )
1717
+
1718
+ lines.append(
1719
+ heading
1720
+ )
1721
+
1722
+ return "\n\n".join(
1723
+ lines
1724
+ )
1725
+
1726
+
1727
+ # ============================================================
1728
+ # FAST CONVERSATIONAL RESPONSES
1729
+ # ============================================================
1730
+
1731
+ def detect_conversational_intent(question):
1732
+ """Handle simple social turns locally so they feel immediate."""
1733
+ text = re.sub(r"[^a-z0-9' ]+", " ", (question or "").lower()).strip()
1734
+ text = re.sub(r"\s+", " ", text)
1735
+
1736
+ greetings = {
1737
+ "hi", "hello", "hey", "hi sage", "hello sage", "hey sage",
1738
+ "good morning", "good afternoon", "good evening"
1739
+ }
1740
+ thanks = {
1741
+ "thanks", "thank you", "thank you sage", "thanks sage",
1742
+ "thank you so much", "thanks so much"
1743
+ }
1744
+
1745
+ if text in greetings:
1746
+ return {
1747
+ "answer": "Hi! How can I help you with responsible AI or AI governance today?",
1748
+ "state": "greeting",
1749
+ "intent": "greeting"
1750
+ }
1751
+ if text in thanks:
1752
+ return {
1753
+ "answer": "You're welcome! I'm glad I could help.",
1754
+ "state": "thanks",
1755
+ "intent": "thanks"
1756
+ }
1757
+ return None
1758
+
1759
+ # ============================================================
1760
+ # INTERFACE CALLBACK
1761
+ # ============================================================
1762
+
1763
+ def run_sage(
1764
+ question,
1765
+ voice_name
1766
+ ):
1767
+
1768
+ question = (
1769
+ question
1770
+ or ""
1771
+ ).strip()
1772
+
1773
+
1774
+ if not question:
1775
+
1776
+ yield ("Please enter a question.",
1777
+ None,
1778
+ "### Evidence Sources",
1779
+ {},
1780
+ "Ready.",
1781
+ "idle",
1782
+ ""
1783
+ )
1784
+
1785
+ return
1786
+
1787
+
1788
+ social = detect_conversational_intent(question)
1789
+ if social:
1790
+ answer_text = social["answer"]
1791
+ audio_path, viseme_timeline = generate_tts_audio(answer_text, voice_name, social["state"])
1792
+ yield (
1793
+ answer_text,
1794
+ audio_path,
1795
+ "### Evidence Sources\nNot required for this conversational response.",
1796
+ {
1797
+ "response_type": "conversational",
1798
+ "conversational_intent": social["intent"],
1799
+ "source_count": 0,
1800
+ "guardrail_triggered": False
1801
+ },
1802
+ "Ready.",
1803
+ social["state"],
1804
+ viseme_timeline
1805
+ )
1806
+ return
1807
+
1808
+
1809
+ yield ("SAGE is reviewing the knowledge base...",
1810
+ None,
1811
+ "### Evidence Sources\nRetrieving evidence...",
1812
+ {},
1813
+ "Processing...",
1814
+ "thinking",
1815
+ ""
1816
+ )
1817
+
1818
+
1819
+ try:
1820
+
1821
+ response = (
1822
+ generate_sage_response_8d(
1823
+ question
1824
+ )
1825
+ )
1826
+
1827
+
1828
+ answer = response.get(
1829
+ "display_answer",
1830
+ ""
1831
+ )
1832
+
1833
+
1834
+ response_type = response.get(
1835
+ "response_type"
1836
+ )
1837
+
1838
+
1839
+ if response_type == "out_of_domain_refusal":
1840
+
1841
+ avatar_state = "refusal"
1842
+
1843
+ elif response_type == "insufficient_evidence":
1844
+
1845
+ avatar_state = "uncertainty"
1846
+
1847
+ else:
1848
+
1849
+ avatar_state = "speaking"
1850
+
1851
+
1852
+ audio, viseme_timeline = generate_tts_audio(
1853
+
1854
+ response.get(
1855
+ "spoken_answer",
1856
+ answer
1857
+ ),
1858
+
1859
+ voice_name,
1860
+
1861
+ avatar_state
1862
+ )
1863
+
1864
+
1865
+ diagnostics = {
1866
+
1867
+ "response_type":
1868
+ response_type,
1869
+
1870
+ "source_traceability_met":
1871
+ response.get(
1872
+ "source_traceability_met"
1873
+ ),
1874
+
1875
+ "source_count":
1876
+ len(
1877
+ response.get(
1878
+ "sources",
1879
+ []
1880
+ )
1881
+ ),
1882
+
1883
+ "guardrail_triggered":
1884
+ response.get(
1885
+ "guardrail_triggered"
1886
+ ),
1887
+
1888
+ "guardrail_reason":
1889
+ response.get(
1890
+ "guardrail_reason"
1891
+ ),
1892
+
1893
+ "false_premise_detected":
1894
+ response.get(
1895
+ "false_premise_detected"
1896
+ ),
1897
+
1898
+ "premise_corrected":
1899
+ response.get(
1900
+ "premise_corrected"
1901
+ ),
1902
+
1903
+ "best_faiss_distance":
1904
+ response.get(
1905
+ "best_faiss_distance"
1906
+ ),
1907
+
1908
+ "mean_faiss_distance":
1909
+ response.get(
1910
+ "mean_faiss_distance"
1911
+ ),
1912
+
1913
+ "retrieval_latency_sec":
1914
+ response.get(
1915
+ "retrieval_latency_sec"
1916
+ ),
1917
+
1918
+ "generation_latency_sec":
1919
+ response.get(
1920
+ "generation_latency_sec"
1921
+ ),
1922
+
1923
+ "total_latency_sec":
1924
+ response.get(
1925
+ "total_latency_sec"
1926
+ )
1927
+ }
1928
+
1929
+
1930
+ yield (
1931
+ answer,
1932
+ audio,
1933
+ format_sources(
1934
+ response.get(
1935
+ "sources",
1936
+ []
1937
+ )
1938
+ ),
1939
+ diagnostics,
1940
+ "Response generated successfully.",
1941
+ avatar_state,
1942
+ viseme_timeline
1943
+ )
1944
+
1945
+
1946
+ except Exception as exc:
1947
+
1948
+ yield (
1949
+ f"SAGE error: {exc}",
1950
+ None,
1951
+ "### Evidence Sources\nUnavailable.",
1952
+ {
1953
+ "error": str(exc)
1954
+ },
1955
+ "System error.",
1956
+ "error",
1957
+ ""
1958
+ )
1959
+
1960
+
1961
+
1962
+ # ============================================================
1963
+ # AUDIO-REACTIVE AVATAR CONTROLLER
1964
+ # ============================================================
1965
+
1966
+ AVATAR_AUDIO_JS = r"""
1967
+ () => {
1968
+ if (window.__sageBridgeInit) return; // js may be delivered twice
1969
+ window.__sageBridgeInit = true;
1970
+
1971
+ const frame = () => document.querySelector('#sage-3d-avatar');
1972
+ const send = (type, extra={}) => {
1973
+ const f = frame();
1974
+ if (f && f.contentWindow) f.contentWindow.postMessage({type, ...extra}, '*');
1975
+ };
1976
+ const readBox = (id) => {
1977
+ const root = document.querySelector(id);
1978
+ if (!root) return '';
1979
+ const el = root.matches('textarea,input') ? root : root.querySelector('textarea,input');
1980
+ return (el && el.value) || '';
1981
+ };
1982
+
1983
+ // ---- avatar mood (thinking / refusal / ...) ----
1984
+ let lastState = '';
1985
+ const syncState = () => {
1986
+ const state = readBox('#sage-avatar-state').trim().toLowerCase();
1987
+ if (state && state !== lastState) { lastState = state; send('SAGE_STATE', {state}); }
1988
+ };
1989
+
1990
+ // ---- phoneme cues + audio envelope for this answer ----
1991
+ // Carried in a CSS-hidden (NOT visible=False) textbox, so it is always in the DOM
1992
+ // and always readable as a plain string.
1993
+ let payloadRaw = '';
1994
+ const syncPayload = () => {
1995
+ const raw = readBox('#sage-speech-payload').trim();
1996
+ if (raw === payloadRaw) return;
1997
+ payloadRaw = raw;
1998
+ if (!raw) { send('SAGE_PAYLOAD', {payload: null}); return; }
1999
+ try { send('SAGE_PAYLOAD', {payload: JSON.parse(raw)}); }
2000
+ catch (err) { console.warn('SAGE: unreadable lip-sync payload', err); }
2001
+ };
2002
+
2003
+ // ---- audio clock: the <audio> element's own currentTime ----
2004
+ const findAudio = () =>
2005
+ document.querySelector('#sage-audio-player audio') || document.querySelector('audio');
2006
+ let lastSig = '';
2007
+ const pumpClock = (force) => {
2008
+ const a = findAudio();
2009
+ if (!a) return;
2010
+ const playing = !a.paused && !a.ended && a.readyState >= 3;
2011
+ const msg = {
2012
+ t: Number.isFinite(a.currentTime) ? a.currentTime : 0,
2013
+ rate: a.playbackRate || 1,
2014
+ playing,
2015
+ duration: Number.isFinite(a.duration) ? a.duration : 0
2016
+ };
2017
+ const sig = [msg.t.toFixed(2), msg.rate, playing].join('|');
2018
+ if (playing || force || sig !== lastSig) { lastSig = sig; send('SAGE_CLOCK', msg); }
2019
+ };
2020
+ const wireAudio = (a) => {
2021
+ if (!a || a.dataset.sage3dWired === '1') return;
2022
+ a.dataset.sage3dWired = '1';
2023
+ ['play','playing','pause','ended','seeked','ratechange','waiting','loadeddata']
2024
+ .forEach(ev => a.addEventListener(ev, () => pumpClock(true)));
2025
+ };
2026
+
2027
+ function scan() {
2028
+ const a = findAudio();
2029
+ if (a) wireAudio(a);
2030
+ syncState();
2031
+ syncPayload();
2032
+ pumpClock(false);
2033
+ }
2034
+
2035
+ new MutationObserver(scan).observe(document.body, {childList:true, subtree:true});
2036
+ setInterval(() => pumpClock(false), 33); // ~30 Hz; the avatar extrapolates between ticks
2037
+
2038
+ window.addEventListener('message', (event) => {
2039
+ if (event.source === frame()?.contentWindow && event.data && event.data.type === 'SAGE_AVATAR_READY') {
2040
+ lastState = '';
2041
+ payloadRaw = '\u0000'; // force a resend to the freshly loaded avatar
2042
+ syncState(); syncPayload(); pumpClock(true);
2043
+ }
2044
+ });
2045
+
2046
+ // ------------------------------------------------------------
2047
+ // Browser speech-to-text with automatic submission
2048
+ // ------------------------------------------------------------
2049
+ const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
2050
+ let recognition = null;
2051
+ let listening = false;
2052
+ let finalTranscript = '';
2053
+ let silenceTimer = null;
2054
+
2055
+ const componentControl = (selector, tagName) => {
2056
+ const root = document.querySelector(selector);
2057
+ if (!root) return null;
2058
+ if (root.matches && root.matches(tagName)) return root;
2059
+ return root.querySelector(tagName);
2060
+ };
2061
+
2062
+ const micButton = () => componentControl('#sage-mic', 'button');
2063
+ const questionBox = () =>
2064
+ componentControl('#sage-question', 'textarea') ||
2065
+ componentControl('#sage-question', 'input');
2066
+ const askButton = () => componentControl('#sage-ask', 'button');
2067
+
2068
+ const setQuestion = (text) => {
2069
+ const box = questionBox();
2070
+ if (!box) return;
2071
+ const setter = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value').set;
2072
+ setter.call(box, text);
2073
+ box.dispatchEvent(new Event('input', {bubbles:true}));
2074
+ box.dispatchEvent(new Event('change', {bubbles:true}));
2075
+ };
2076
+
2077
+ const setMicLabel = (text) => {
2078
+ const btn = micButton();
2079
+ if (btn) btn.textContent = text;
2080
+ };
2081
+
2082
+ const submitSpeech = () => {
2083
+ const text = finalTranscript.trim();
2084
+ if (!text) return;
2085
+ setQuestion(text);
2086
+ setMicLabel('🎙 Speak to SAGE');
2087
+ listening = false;
2088
+ // Give Gradio/React one moment to receive the textbox input event.
2089
+ setTimeout(() => {
2090
+ const btn = askButton();
2091
+ if (btn) btn.click();
2092
+ }, 180);
2093
+ };
2094
+
2095
+ if (SpeechRecognition) {
2096
+ recognition = new SpeechRecognition();
2097
+ recognition.lang = 'en-US';
2098
+ recognition.continuous = true;
2099
+ recognition.interimResults = true;
2100
+ recognition.maxAlternatives = 1;
2101
+
2102
+ recognition.onstart = () => {
2103
+ listening = true;
2104
+ finalTranscript = '';
2105
+ setMicLabel('Listening…');
2106
+ };
2107
+
2108
+ recognition.onresult = (event) => {
2109
+ let interim = '';
2110
+ for (let i = event.resultIndex; i < event.results.length; i++) {
2111
+ const words = event.results[i][0].transcript;
2112
+ if (event.results[i].isFinal) finalTranscript += words + ' ';
2113
+ else interim += words;
2114
+ }
2115
+ setQuestion((finalTranscript + interim).trim());
2116
+
2117
+ // A clear pause after recognized speech ends the utterance.
2118
+ clearTimeout(silenceTimer);
2119
+ silenceTimer = setTimeout(() => {
2120
+ if (listening && (finalTranscript.trim() || interim.trim())) {
2121
+ try { recognition.stop(); } catch (_) {}
2122
+ }
2123
+ }, 1200);
2124
+ };
2125
+
2126
+ recognition.onspeechend = () => {
2127
+ clearTimeout(silenceTimer);
2128
+ silenceTimer = setTimeout(() => {
2129
+ if (listening) {
2130
+ try { recognition.stop(); } catch (_) {}
2131
+ }
2132
+ }, 350);
2133
+ };
2134
+
2135
+ recognition.onend = () => {
2136
+ const hadSpeech = finalTranscript.trim().length > 0;
2137
+ listening = false;
2138
+ setMicLabel('🎙 Speak to SAGE');
2139
+ if (hadSpeech) submitSpeech();
2140
+ };
2141
+
2142
+ recognition.onerror = (event) => {
2143
+ listening = false;
2144
+ clearTimeout(silenceTimer);
2145
+ if (event.error === 'not-allowed' || event.error === 'service-not-allowed') {
2146
+ setMicLabel('Microphone permission needed');
2147
+ } else if (event.error === 'no-speech') {
2148
+ setMicLabel('🎙 Speak to SAGE');
2149
+ } else {
2150
+ console.warn('SAGE speech recognition:', event.error);
2151
+ setMicLabel('🎙 Speak to SAGE');
2152
+ }
2153
+ };
2154
+ }
2155
+
2156
+ const setMicStatus = (message) => {
2157
+ const btn = micButton();
2158
+ if (btn) {
2159
+ btn.title = message || '';
2160
+ btn.setAttribute('aria-label', message || btn.textContent || 'Speak to SAGE');
2161
+ }
2162
+ };
2163
+
2164
+ // Event delegation survives Gradio/React rerenders of the button.
2165
+ document.addEventListener('click', (event) => {
2166
+ const clicked = event.target && event.target.closest
2167
+ ? event.target.closest('#sage-mic, #sage-mic button')
2168
+ : null;
2169
+ if (!clicked) return;
2170
+
2171
+ event.preventDefault();
2172
+ event.stopPropagation();
2173
+
2174
+ if (!SpeechRecognition) {
2175
+ setMicLabel('Speech input unavailable in this browser');
2176
+ setMicStatus('Browser speech recognition is not available.');
2177
+ return;
2178
+ }
2179
+
2180
+ if (listening) {
2181
+ try { recognition.stop(); } catch (_) {}
2182
+ return;
2183
+ }
2184
+
2185
+ finalTranscript = '';
2186
+ setQuestion('');
2187
+ setMicLabel('Starting microphone…');
2188
+
2189
+ try {
2190
+ recognition.start();
2191
+ } catch (err) {
2192
+ console.warn('Could not start SAGE microphone:', err);
2193
+ setMicLabel('🎙 Speak to SAGE');
2194
+ setMicStatus('Microphone could not start. Check browser microphone permission.');
2195
+ }
2196
+ }, true);
2197
+
2198
+ const wireMic = () => {
2199
+ const btn = micButton();
2200
+ if (!btn) return;
2201
+
2202
+ // Never disable the visible control; show compatibility state instead.
2203
+ if (!SpeechRecognition) {
2204
+ btn.textContent = 'Speech input unavailable in this browser';
2205
+ btn.title = 'Use Chrome or Edge with microphone permission enabled.';
2206
+ return;
2207
+ }
2208
+
2209
+ if (!btn.dataset.sageSttReady) {
2210
+ btn.dataset.sageSttReady = '1';
2211
+ btn.title = 'Speak your question. SAGE will submit it after you stop speaking.';
2212
+ }
2213
+ };
2214
+
2215
+ setInterval(() => { scan(); wireMic(); }, 250);
2216
+ scan();
2217
+ wireMic();
2218
+ console.log('SAGE 2.0 phoneme lip-sync bridge + speech input ready.');
2219
+ }
2220
+ """
2221
+
2222
+
2223
+ # ============================================================
2224
+ # GRADIO APP
2225
+ # ============================================================
2226
+
2227
+ CUSTOM_CSS = """
2228
+ /* Data-carrier textboxes: kept in the DOM (visible=True) but not shown. */
2229
+ .sage-hidden {
2230
+ position: absolute !important;
2231
+ left: -99999px !important;
2232
+ top: 0 !important;
2233
+ width: 1px !important;
2234
+ height: 1px !important;
2235
+ overflow: hidden !important;
2236
+ opacity: 0 !important;
2237
+ pointer-events: none !important;
2238
+ }
2239
+
2240
+ .gradio-container {
2241
+ max-width: 1450px !important;
2242
+ }
2243
+
2244
+ #sage-title {
2245
+ text-align:center;
2246
+ }
2247
+
2248
+ #sage-subtitle {
2249
+ text-align:center;
2250
+ opacity:.8;
2251
+ margin-bottom:20px;
2252
+ }
2253
+ """
2254
+
2255
+
2256
+ # Gradio 6 moved css/js from gr.Blocks() to launch(); Gradio 5 wants them on Blocks.
2257
+ _GRADIO_MAJOR = int(re.match(r"\d+", gr.__version__).group())
2258
+ _APP_ASSETS = {"css": CUSTOM_CSS, "js": AVATAR_AUDIO_JS}
2259
+ print(f"Gradio {gr.__version__}: css/js passed to "
2260
+ f"{'launch()' if _GRADIO_MAJOR >= 6 else 'gr.Blocks()'}")
2261
+
2262
+ with gr.Blocks(
2263
+ title="SAGE 2.0",
2264
+ **({} if _GRADIO_MAJOR >= 6 else _APP_ASSETS)
2265
+ ) as demo:
2266
+
2267
+
2268
+ gr.Markdown(
2269
+ "# SAGE 2.0",
2270
+ elem_id="sage-title"
2271
+ )
2272
+
2273
+
2274
+ gr.Markdown(
2275
+ """
2276
+ **Strategic AI Governance and Engagement Advisor**
2277
+
2278
+ Evidence-grounded insights for responsible,
2279
+ human-centered artificial intelligence.
2280
+ """,
2281
+ elem_id="sage-subtitle"
2282
+ )
2283
+
2284
+
2285
+ with gr.Row():
2286
+
2287
+ with gr.Column(
2288
+ scale=5
2289
+ ):
2290
+
2291
+ avatar = gr.HTML(
2292
+ render_sage_avatar(
2293
+ "idle"
2294
+ )
2295
+ )
2296
+
2297
+ status = gr.Markdown(
2298
+ "Ready."
2299
+ )
2300
+
2301
+ avatar_state = gr.Textbox(
2302
+ value="idle",
2303
+ show_label=False,
2304
+ container=False,
2305
+ interactive=False,
2306
+ elem_id="sage-avatar-state",
2307
+ elem_classes=["sage-hidden"]
2308
+ )
2309
+
2310
+
2311
+ viseme_timeline = gr.Textbox(
2312
+ value="",
2313
+ show_label=False,
2314
+ container=False,
2315
+ interactive=False,
2316
+ elem_id="sage-speech-payload",
2317
+ elem_classes=["sage-hidden"]
2318
+ )
2319
+
2320
+
2321
+ with gr.Column(
2322
+ scale=7
2323
+ ):
2324
+
2325
+ question = gr.Textbox(
2326
+ label="Ask SAGE",
2327
+ elem_id="sage-question",
2328
+ lines=3,
2329
+ placeholder=(
2330
+ "Ask about AI governance, "
2331
+ "trust, explainability, "
2332
+ "human oversight, or responsible AI..."
2333
+ )
2334
+ )
2335
+
2336
+
2337
+ voice = gr.Dropdown(
2338
+ choices=list(
2339
+ VOICE_OPTIONS.keys()
2340
+ ),
2341
+ value=DEFAULT_VOICE,
2342
+ label="SAGE Voice"
2343
+ )
2344
+
2345
+
2346
+ with gr.Row():
2347
+ mic = gr.Button(
2348
+ "🎙 Speak to SAGE",
2349
+ elem_id="sage-mic"
2350
+ )
2351
+ ask = gr.Button(
2352
+ "Ask SAGE",
2353
+ variant="primary",
2354
+ elem_id="sage-ask"
2355
+ )
2356
+
2357
+
2358
+ gr.Markdown(
2359
+ "### SAGE Response"
2360
+ )
2361
+
2362
+
2363
+ answer = gr.Markdown(
2364
+ elem_id="sage-answer"
2365
+ )
2366
+
2367
+
2368
+ audio = gr.Audio(
2369
+ label="SAGE Voice Response",
2370
+ autoplay=True,
2371
+ elem_id="sage-audio-player"
2372
+ )
2373
+
2374
+
2375
+ with gr.Row():
2376
+
2377
+ sources = gr.Markdown(
2378
+ "### Evidence Sources\nSources will appear here."
2379
+ )
2380
+
2381
+
2382
+ diagnostics = gr.JSON(
2383
+ label="Response Diagnostics"
2384
+ )
2385
+
2386
+
2387
+ ask.click(
2388
+
2389
+ run_sage,
2390
+
2391
+ inputs=[
2392
+ question,
2393
+ voice
2394
+ ],
2395
+
2396
+ outputs=[
2397
+ answer,
2398
+ audio,
2399
+ sources,
2400
+ diagnostics,
2401
+ status,
2402
+ avatar_state,
2403
+ viseme_timeline
2404
+ ]
2405
+ )
2406
+
2407
+
2408
+ question.submit(
2409
+
2410
+ run_sage,
2411
+
2412
+ inputs=[
2413
+ question,
2414
+ voice
2415
+ ],
2416
+
2417
+ outputs=[
2418
+ answer,
2419
+ audio,
2420
+ sources,
2421
+ diagnostics,
2422
+ status,
2423
+ avatar_state,
2424
+ viseme_timeline
2425
+ ]
2426
+ )
2427
+
2428
+
2429
+ # ============================================================
2430
+ # HUGGING FACE / LOCAL LAUNCH
2431
+ # ============================================================
2432
+
2433
+ if __name__ == "__main__":
2434
+
2435
+ demo.queue(
2436
+ default_concurrency_limit=1
2437
+ ).launch(**(_APP_ASSETS if _GRADIO_MAJOR >= 6 else {}))
sage_avatar.html ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>SAGE 2.0 — Network Intelligence</title>
3
+ <style>
4
+ :root{color-scheme:dark;--navy:#0B1F3B;--blue:#1F6BFF;--gold:#F5C86A;--ice:#BDE4FF}*{box-sizing:border-box}html,body{margin:0;width:100%;height:100%;overflow:hidden;background:#06152c;font-family:Inter,system-ui,Arial,sans-serif;color:#eaf6ff}#scene{position:absolute;inset:0;display:block;width:100%;height:100%}#shade{pointer-events:none;position:absolute;inset:0;background:radial-gradient(ellipse at 50% 47%,transparent 25%,rgba(3,10,27,.48) 100%)}.top{position:absolute;top:22px;left:25px;right:25px;display:flex;align-items:center;justify-content:space-between;gap:12px}.brand{font-size:13px;letter-spacing:.3em;font-weight:750}.brand small{display:block;font-size:9px;font-weight:500;letter-spacing:.2em;color:#a4bddb;margin-top:6px}.status{display:flex;align-items:center;gap:9px;color:#c7d9ed;font-size:11px;letter-spacing:.15em;text-transform:uppercase}.dot{width:7px;height:7px;border-radius:50%;background:var(--gold);box-shadow:0 0 13px var(--gold)}.bottom{position:absolute;bottom:22px;left:25px;right:25px;display:flex;align-items:end;justify-content:space-between;gap:12px}.description{font-size:11px;line-height:1.65;color:#b1c9e4;max-width:330px}.demo{display:flex;align-items:center;gap:5px;flex-wrap:wrap;justify-content:flex-end}.demo button{background:rgba(12,37,71,.8);border:1px solid rgba(139,185,232,.25);color:#dceeff;padding:8px 10px;border-radius:7px;cursor:pointer;font-size:10px}.demo button:hover,.demo button.active{border-color:var(--gold);color:var(--gold)}.demo[hidden]{display:none!important}@media(max-width:600px){.top{top:15px;left:15px;right:15px}.bottom{bottom:15px;left:15px;right:15px;flex-direction:column;align-items:start}.demo{justify-content:flex-start}.demo button{padding:6px}.description{font-size:10px}}
5
+ </style></head><body><canvas id="scene" aria-label="Animated three-dimensional SAGE network intelligence avatar"></canvas><div id="shade"></div><header class="top"><div class="brand">SAGE <span style="color:#f5c86a">2.0</span><small>NETWORK INTELLIGENCE</small></div><div class="status"><span class="dot"></span><span id="stateLabel">QUIET · LISTENING</span></div></header><footer class="bottom"><div class="description" id="description">A distributed intelligence, ready to listen.</div><div class="demo" id="demo" hidden><button data-state="quiet">Quiet</button><button data-state="detected">Detected</button><button data-state="focus">Focus</button><button data-state="speaking">Speaking</button><button data-state="return">Return</button></div></footer>
6
+ <script type="module">
7
+ import * as THREE from 'https://cdn.jsdelivr.net/npm/three@0.164.1/build/three.module.js';
8
+ const canvas=document.querySelector('#scene'),renderer=new THREE.WebGLRenderer({canvas,antialias:true,alpha:false,powerPreference:'high-performance'});renderer.setPixelRatio(Math.min(devicePixelRatio,1.8));renderer.setClearColor(0x06152c,1);const scene=new THREE.Scene(),camera=new THREE.PerspectiveCamera(44,1,.1,100);camera.position.set(0,0,10.8);
9
+ const COUNT=3400, LINKS=2100, pos=new Float32Array(COUNT*3),base=new Float32Array(COUNT*3),human=new Float32Array(COUNT*3),colors=new Float32Array(COUNT*3),sizes=new Float32Array(COUNT),rng=(function(){let s=314159;return ()=>((s=Math.imul(1664525,s)+1013904223|0)>>>0)/4294967296})();const rr=(a,b)=>a+(b-a)*rng();
10
+ // Distributed network: softly flattened spherical cloud with a luminous inner core.
11
+ for(let i=0;i<COUNT;i++){let theta=rr(0,Math.PI*2),z=rr(-1,1),r=Math.sqrt(1-z*z),radius=Math.pow(rng(),.63)*3.25;const j=i*3;base[j]=Math.cos(theta)*r*radius*1.35;base[j+1]=z*radius*.93;base[j+2]=Math.sin(theta)*r*radius*.83;}
12
+ // Human silhouette: head ellipsoid, neck, and shoulder/chest volume, all as 3D point clouds.
13
+ for(let i=0;i<COUNT;i++){const j=i*3,u=rng(),a=rr(0,Math.PI*2),v=rr(-1,1),rad=Math.sqrt(1-v*v),depth=Math.pow(rng(),.26);let x,y,z;if(u<.58){x=Math.cos(a)*rad*.95*depth;y=1.00+v*1.23*depth;z=Math.sin(a)*rad*.78*depth;}else if(u<.67){x=rr(-.31,.31);y=rr(-.66,-.14);z=rr(-.31,.31);}else{const shoulder=rr(-1,1),level=rr(0,1),width=1.75-.65*level;x=shoulder*width;y=-.62-level*1.38;z=rr(-.55,.55)*Math.sqrt(Math.max(.12,1-(x/2.1)**2));}human[j]=x;human[j+1]=y;human[j+2]=z;}
14
+ const geometry=new THREE.BufferGeometry();geometry.setAttribute('position',new THREE.BufferAttribute(pos,3).setUsage(THREE.DynamicDrawUsage));geometry.setAttribute('color',new THREE.BufferAttribute(colors,3).setUsage(THREE.DynamicDrawUsage));const material=new THREE.PointsMaterial({size:.037,vertexColors:true,transparent:true,opacity:.94,blending:THREE.AdditiveBlending,depthWrite:false,sizeAttenuation:true});const points=new THREE.Points(geometry,material);scene.add(points);
15
+ const pairs=new Uint16Array(LINKS*2);for(let k=0;k<LINKS;k++){let a=Math.floor(rng()*COUNT),b=(a+1+Math.floor(rng()*55))%COUNT;pairs[k*2]=a;pairs[k*2+1]=b;}const lineCoords=new Float32Array(LINKS*6);const lineGeom=new THREE.BufferGeometry();lineGeom.setAttribute('position',new THREE.BufferAttribute(lineCoords,3).setUsage(THREE.DynamicDrawUsage));const lines=new THREE.LineSegments(lineGeom,new THREE.LineBasicMaterial({color:0x347bff,transparent:true,opacity:.19,blending:THREE.AdditiveBlending,depthWrite:false}));scene.add(lines);
16
+ const haloGeom=new THREE.SphereGeometry(.43,24,16),halo=new THREE.Mesh(haloGeom,new THREE.MeshBasicMaterial({color:0xf5c86a,transparent:true,opacity:.09,blending:THREE.AdditiveBlending,depthWrite:false}));scene.add(halo);
17
+ let current='quiet',targetMorph=0,morph=0,clock={playing:false,t:0},payload=null,lastClock=performance.now(),phaseStart=performance.now(),received=false;const labels={quiet:['QUIET · LISTENING','A distributed intelligence, ready to listen.'],detected:['QUESTION DETECTED','Incoming signals activate the network.'],focus:['FOCUS FORMS','Connections converge as SAGE processes evidence.'],speaking:['SPEAKING · RESPONDING','The network takes human-like form and responds.'],return:['RETURN TO QUIET','The response completes; the network disperses.']};
18
+ function normalize(s){s=String(s||'').toLowerCase();if(['idle','ready','listening','quiet'].includes(s))return 'quiet';if(['question','question_detected','detected','greeting'].includes(s))return 'detected';if(['thinking','processing','focus'].includes(s))return 'focus';if(['speaking','thanks','refusal','uncertainty'].includes(s))return 'speaking';if(['return','finished','done'].includes(s))return 'return';return s==='error'?'quiet':'quiet';}
19
+ function setState(s){s=normalize(s);if(current===s)return;current=s;phaseStart=performance.now();document.querySelector('#stateLabel').textContent=labels[s][0];document.querySelector('#description').textContent=labels[s][1];document.querySelectorAll('.demo button').forEach(b=>b.classList.toggle('active',b.dataset.state===s));targetMorph=s==='speaking'?1:s==='focus'?.18:0;}
20
+ function level(){if(!clock.playing)return 0;const elapsed=(performance.now()-lastClock)/1000;const t=clock.t+elapsed*(clock.rate||1);const env=payload?.env;if(env?.v?.length&&env.fps){const idx=Math.max(0,Math.min(env.v.length-1,Math.floor(t*env.fps)));return Math.max(0,Math.min(1,env.v[idx]/100));}return .25+.23*Math.sin(performance.now()*.009)**2;}
21
+ function resize(){let w=innerWidth,h=innerHeight;renderer.setSize(w,h,false);camera.aspect=w/h;camera.position.z=w<600?14.5:10.8;camera.updateProjectionMatrix();}addEventListener('resize',resize);resize();const blue=new THREE.Color('#1F6BFF'),ice=new THREE.Color('#BDE4FF'),gold=new THREE.Color('#F5C86A'),temp=new THREE.Color();let last=performance.now();
22
+ function animate(now){requestAnimationFrame(animate);const dt=Math.min(.06,(now-last)/1000);last=now;const age=(now-phaseStart)/1000,energy=level();if(current==='return'&&age>1.9)setState('quiet');morph+=(targetMorph-morph)*Math.min(1,dt*1.8);const activity=current==='detected'?1.7:current==='focus'?1.4:current==='speaking'?1.0:.55;const spin=now*.000075*(current==='detected'?2.5:1);points.rotation.y=spin;lines.rotation.y=spin;halo.rotation.y=spin;const converge=current==='focus'?.65:1;for(let i=0;i<COUNT;i++){const j=i*3,seed=i*.618,wiggle=.032*Math.sin(now*.00075*activity+seed),breath=1+.025*Math.sin(now*.00065+seed);for(let a=0;a<3;a++){let p=base[j+a]*(1-morph)*converge+human[j+a]*morph;p=p*breath+wiggle*Math.sin(seed+a*1.9);pos[j+a]=p;}const dist=Math.hypot(pos[j],pos[j+1],pos[j+2]),warm=Math.max(0,1-dist/2.7)*(current==='focus'?.88:.38)+energy*.48+(i%17===0?.34:0);temp.copy(blue).lerp(ice,Math.min(1,.24+.32*Math.sin(seed+now*.0006)**2));temp.lerp(gold,Math.min(.95,warm));const intensity=.63+.28*Math.sin(now*.0013+seed)**2+energy*.42;colors[j]=temp.r*intensity;colors[j+1]=temp.g*intensity;colors[j+2]=temp.b*intensity;}geometry.attributes.position.needsUpdate=true;geometry.attributes.color.needsUpdate=true;for(let k=0;k<LINKS;k++){const a=pairs[k*2]*3,b=pairs[k*2+1]*3,o=k*6;lineCoords[o]=pos[a];lineCoords[o+1]=pos[a+1];lineCoords[o+2]=pos[a+2];lineCoords[o+3]=pos[b];lineCoords[o+4]=pos[b+1];lineCoords[o+5]=pos[b+2];}lineGeom.attributes.position.needsUpdate=true;lines.material.opacity=(current==='focus'?.28:.15)+energy*.12;halo.scale.setScalar(1.0+(current==='focus'?.85:.25)+energy*.75);halo.material.opacity=(current==='focus'?.19:.06)+energy*.13;halo.position.set(0,current==='speaking'?.25:0,0);renderer.render(scene,camera);}requestAnimationFrame(animate);
23
+ window.addEventListener('message',e=>{if(e.source!==window.parent)return;const d=e.data||{};if(d.type==='SAGE_STATE'){received=true;setState(d.state);}if(d.type==='SAGE_PAYLOAD'){payload=d.payload||null;if(payload?.state&&!clock.playing)setState(payload.state);}if(d.type==='SAGE_CLOCK'){const was=clock.playing;clock={...d};lastClock=performance.now();if(clock.playing&&!was)setState('speaking');if(!clock.playing&&was)setState('return');}});
24
+ // Preview mode: ?demo=1 displays buttons. Production hides all controls.
25
+ const demo=new URLSearchParams(location.search).has('demo');if(demo){document.querySelector('#demo').hidden=false;document.querySelectorAll('.demo button').forEach(b=>b.onclick=()=>{clock.playing=b.dataset.state==='speaking';lastClock=performance.now();setState(b.dataset.state);});}
26
+ window.parent.postMessage({type:'SAGE_AVATAR_READY'},'*');setState('quiet');
27
+ </script></body></html>