neuralworm commited on
Commit
6c97eaf
·
1 Parent(s): 20ffe70

chore: Prepare app.py for HF Spaces (remove SSL/share), keep local config in app_local.py

Browse files
Files changed (2) hide show
  1. app.py +1 -1
  2. app_local.py +554 -0
app.py CHANGED
@@ -551,4 +551,4 @@ def build_demo() -> gr.Blocks:
551
  return demo
552
 
553
  if __name__ == "__main__":
554
- get_llm(); build_demo().launch(share=True, server_name="0.0.0.0", ssl_certfile="cert.pem", ssl_keyfile="key.pem", ssl_verify=False)
 
551
  return demo
552
 
553
  if __name__ == "__main__":
554
+ get_llm(); build_demo().launch(server_name="0.0.0.0")
app_local.py ADDED
@@ -0,0 +1,554 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ import gradio as gr
4
+ import time
5
+ import re
6
+ import codecs
7
+ import uuid
8
+ import json
9
+ import logging
10
+ import tempfile
11
+ import numpy as np
12
+ import scipy.io.wavfile as wavfile
13
+ import asyncio
14
+ import warnings
15
+ from typing import List, Tuple, Generator, Dict
16
+ from threading import Thread
17
+
18
+ # ML / Transformers
19
+ import transformers
20
+ transformers.utils.logging.set_verbosity_error()
21
+ warnings.filterwarnings("ignore", category=UserWarning, module="gradio.components.dropdown")
22
+ from transformers import AutoProcessor, Gemma3ForConditionalGeneration, TextIteratorStreamer
23
+
24
+ # --- Logging Setup ---
25
+ # Set root logger to ERROR to suppress external library noise
26
+ logging.basicConfig(level=logging.ERROR, format='%(name)s [%(levelname)s] %(message)s')
27
+
28
+ # Specific library suppressions
29
+ for lib in ["transformers", "accelerate", "httpx", "gradio", "langchain"]:
30
+ logging.getLogger(lib).setLevel(logging.ERROR)
31
+
32
+ # Application-level logger
33
+ logger = logging.getLogger("app")
34
+ logger.setLevel(logging.DEBUG)
35
+ logger.propagate = False # DO NOT propagate to root to avoid double-logging or filtering
36
+ ch = logging.StreamHandler()
37
+ ch.setLevel(logging.DEBUG)
38
+ ch.setFormatter(logging.Formatter('[app] [%(levelname)s] %(message)s'))
39
+ logger.addHandler(ch)
40
+
41
+ # --------------------------------------------------------------------
42
+ # Konfiguration & Globale States
43
+ # --------------------------------------------------------------------
44
+ EMBED_MODEL_ID = "google/embeddinggemma-300m"
45
+ LLM_MODEL_ID = "google/gemma-3-4b-it"
46
+
47
+ EMBEDDING_FUNCTION = None
48
+ LLM_MODEL = None
49
+ LLM_PROCESSOR = None
50
+
51
+ # --- UI Premium Aesthetics ---
52
+ PREMIUM_CSS = """
53
+ .glass-panel {
54
+ background: rgba(255, 255, 255, 0.05) !important;
55
+ backdrop-filter: blur(10px) !important;
56
+ border: 1px solid rgba(255, 255, 255, 0.1) !important;
57
+ border-radius: 15px !important;
58
+ box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.37) !important;
59
+ }
60
+ .sidebar-panel {
61
+ border-right: 1px solid rgba(255, 255, 255, 0.1) !important;
62
+ height: 100vh;
63
+ }
64
+ border-bottom: 2px solid #0f3460;
65
+ }
66
+ .desktop-only { display: block; }
67
+ .mobile-only { display: none; }
68
+ @media (max-width: 768px) {
69
+ .desktop-only { display: none !important; }
70
+ .mobile-only { display: block !important; }
71
+ .sidebar-panel { display: none !important; }
72
+ }
73
+ """
74
+
75
+ try:
76
+ from pypdf import PdfReader
77
+ from langchain_community.vectorstores import FAISS
78
+ from langchain_huggingface import HuggingFaceEmbeddings
79
+ from langchain_core.documents import Document
80
+ from langchain_text_splitters import RecursiveCharacterTextSplitter
81
+ from mongochain import MongoDBHandler
82
+ except ImportError:
83
+ pass
84
+
85
+ # Spiritual Integration
86
+ try:
87
+ from spiritual_bridge import get_oracle_data
88
+ except ImportError:
89
+ get_oracle_data = None
90
+
91
+ # --- Model Loading ---
92
+ def get_device() -> torch.device:
93
+ if torch.cuda.is_available(): return torch.device("cuda")
94
+ return torch.device("cpu")
95
+
96
+ def get_embedding_function():
97
+ global EMBEDDING_FUNCTION
98
+ if EMBEDDING_FUNCTION is None:
99
+ device = get_device()
100
+ logger.debug(f"Initialisiere Embedding-Modell '{EMBED_MODEL_ID}' auf Device '{device}'.")
101
+ EMBEDDING_FUNCTION = HuggingFaceEmbeddings(
102
+ model_name=EMBED_MODEL_ID,
103
+ model_kwargs={'device': device}
104
+ )
105
+ logger.debug("Embedding-Modell erfolgreich initialisiert.")
106
+ return EMBEDDING_FUNCTION
107
+
108
+ def get_llm():
109
+ global LLM_MODEL, LLM_PROCESSOR
110
+ if LLM_MODEL is None or LLM_PROCESSOR is None:
111
+ device = get_device()
112
+ logger.debug(f"Initialisiere LLM '{LLM_MODEL_ID}' auf Device '{device}'.")
113
+ dtype = torch.bfloat16 if "cuda" in device.type else torch.float32
114
+ LLM_MODEL = Gemma3ForConditionalGeneration.from_pretrained(
115
+ LLM_MODEL_ID,
116
+ dtype=dtype,
117
+ device_map="auto",
118
+ ).eval()
119
+ LLM_PROCESSOR = AutoProcessor.from_pretrained(LLM_MODEL_ID)
120
+ logger.debug("LLM und Prozessor erfolgreich initialisiert.")
121
+ return LLM_MODEL, LLM_PROCESSOR
122
+
123
+ # --- Language Detection ---
124
+ def detect_language(text: str) -> str:
125
+ if not text or len(text) < 3: return "English"
126
+ model, processor = get_llm()
127
+ prompt = f"Detect the language of the following text and return ONLY the language name (e.g., 'English', 'German', 'French'):\n\n\"{text}\""
128
+ messages = [{"role": "user", "content": [{"type": "text", "text": prompt}]}]
129
+ inputs = processor.apply_chat_template(messages, tokenize=True, add_generation_prompt=True, return_tensors="pt").to(model.device)
130
+ with torch.no_grad():
131
+ outputs = model.generate(inputs, max_new_tokens=20, do_sample=False)
132
+ raw_output = processor.batch_decode(outputs[:, inputs.shape[1]:], skip_special_tokens=True)[0].strip()
133
+ logger.debug(f"DEBUG: Raw Language Detection Output: '{raw_output}'")
134
+
135
+ keywords = ["English", "German", "French", "Spanish", "Italian", "Dutch", "Russian", "Chinese", "Japanese"]
136
+ for k in keywords:
137
+ if k.lower() in raw_output.lower():
138
+ logger.debug(f"DEBUG: Detected User Language (Normalized): '{k}'")
139
+ return k
140
+ return "English"
141
+
142
+ # --- Document Handling ---
143
+ def extract_text_from_file(path: str) -> str:
144
+ ext = os.path.splitext(path)[1].lower()
145
+ if ext in [".txt", ".md", ".markdown"]:
146
+ with open(path, "r", encoding="utf-8", errors="ignore") as f: return f.read()
147
+ if ext == ".pdf":
148
+ text_parts = []
149
+ try:
150
+ reader = PdfReader(path)
151
+ for page in reader.pages:
152
+ page_text = page.extract_text()
153
+ if page_text: text_parts.append(page_text)
154
+ return "\n\n".join(text_parts)
155
+ except Exception as e:
156
+ logger.error(f"Error reading PDF {path}: {e}"); return ""
157
+ try:
158
+ with open(path, "r", encoding="utf-8", errors="ignore") as f: return f.read()
159
+ except Exception: return ""
160
+
161
+ def get_text_splitter() -> RecursiveCharacterTextSplitter:
162
+ return RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200, length_function=len)
163
+
164
+ # --- RAG Core ---
165
+ def index_files(file_paths, mongo_uri, db_name, coll_name, use_mongo, vs_state, mh_state, progress=gr.Progress(track_tqdm=True)):
166
+ if not file_paths: return "Keine Dateien zum Indexieren ausgewählt.", vs_state, mh_state
167
+
168
+ logger.debug(f"Indexierung gestartet für {len(file_paths)} Datei(en).")
169
+ embed_fn = get_embedding_function()
170
+ splitter = get_text_splitter()
171
+ documents = []
172
+
173
+ for path in progress.tqdm(file_paths, desc="1/2: Dateien verarbeiten"):
174
+ if path is None: continue
175
+ text = extract_text_from_file(path)
176
+ if not text.strip(): continue
177
+ chunks = splitter.split_text(text)
178
+ source_name = os.path.basename(path)
179
+ for c in chunks:
180
+ documents.append(Document(page_content=c, metadata={"source": source_name}))
181
+
182
+ logger.debug(f"Total chunks created: {len(documents)}")
183
+ if not documents: return "Kein Text zum Indexieren gefunden.", vs_state, mh_state
184
+
185
+ progress(0.7, desc="2/2: Indexing...")
186
+ new_vs = FAISS.from_documents(documents, embed_fn)
187
+ if vs_state:
188
+ vs_state.merge_from(new_vs)
189
+ else:
190
+ vs_state = new_vs
191
+
192
+ mh_state = None
193
+ if use_mongo:
194
+ try:
195
+ mh_state = MongoDBHandler(uri=mongo_uri, db_name=db_name, collection_name=coll_name)
196
+ mh_state.connect()
197
+ logger.debug(f"Pushe {len(documents)} Chunks nach MongoDB...")
198
+ for doc in documents:
199
+ mh_state.insert_chunk(doc.page_content, doc.metadata)
200
+ logger.debug("MongoDB-Sync abgeschlossen.")
201
+ except Exception as e:
202
+ logger.error(f"Mongo Error: {e}")
203
+
204
+ logger.debug(f"Indexierung abgeschlossen. Gesamt: {vs_state.index.ntotal} Chunks.")
205
+ return f"Index aktualisiert: {vs_state.index.ntotal} Chunks insgesamt.", vs_state, mh_state
206
+
207
+ def clear_index():
208
+ import gc; gc.collect()
209
+ logger.debug("Vektor-Index wurde geleert.")
210
+ return "Index geleert.", None, None
211
+
212
+ def retrieve_relevant_chunks(query, vs_state, mh_state, top_k=3):
213
+ if not vs_state: return []
214
+ logger.debug(f"Suche in FAISS: '{query}'")
215
+ docs = vs_state.similarity_search(query, k=top_k)
216
+ return [{"content": d.page_content, "source": d.metadata.get("source", "Unknown")} for d in docs]
217
+
218
+ def build_rag_prompt(user_question: str, retrieved_chunks: List[Dict]) -> str:
219
+ if not retrieved_chunks: context_str = "Kein relevanter Kontext gefunden."
220
+ else:
221
+ context_parts = [f"[{i}] (Quelle: {ch['source']}): \"{ch['content']}\"" for i, ch in enumerate(retrieved_chunks, 1)]
222
+ context_str = "\n\n".join(context_parts)
223
+ return (f"Beantworte die Benutzerfrage nur basierend auf dem Kontext.\n\n"
224
+ f"--- Kontext ---\n{context_str}\n\n"
225
+ f"--- Frage ---\n{user_question}\n\n"
226
+ f"--- Antwort ---")
227
+
228
+ # --- Agent System ---
229
+ def build_agent_prompt(query, context, history, language="English", short_answers=False):
230
+ context_str = "\n".join([f"- {c['content']} (Source: {c['source']})" for i, c in enumerate(context)])
231
+
232
+ style_instruction = "Be concise." if short_answers else ""
233
+
234
+ system = f"""You are Sage 6.5, a spiritual AI guide.
235
+ Respond in {language}. {style_instruction}
236
+ If you need to use a tool, you MUST use the following JSON format inside <tool_call> tags:
237
+ <tool_call>{{"name": "tool_name", "arguments": {{"arg1": "val1"}}}}</tool_call>
238
+
239
+ Available Tools:
240
+ 1. oracle_consultation: Consult the archive for deep wisdom. Arguments: {{"topic": "str", "name": "str (Optional. Use ONLY if the user explicitly stated their name, otherwise omit)"}}
241
+ """
242
+ return system + f"\n\nContext:\n{context_str}\n\nUser Question: {query}"
243
+
244
+ def chat_agent_stream(query, history, vs_state, mh_state, user_lang=None, short_answers=False):
245
+ model, processor = get_llm()
246
+ lang = user_lang if user_lang else detect_language(query)
247
+ context = retrieve_relevant_chunks(query, vs_state, mh_state)
248
+ prompt = build_agent_prompt(query, context, history, language=lang, short_answers=short_answers)
249
+ messages = [{"role": "user", "content": [{"type": "text", "text": prompt}]}]
250
+
251
+ logger.info(f"[AGENT] 🏁 Starting Agent Loop for Query: '{query}' (Lang: {lang})")
252
+
253
+ def chat_agent_stream(query, history, vs_state, mh_state, user_lang=None, short_answers=False):
254
+ model, processor = get_llm()
255
+ lang = user_lang if user_lang else detect_language(query)
256
+ context = retrieve_relevant_chunks(query, vs_state, mh_state)
257
+ prompt = build_agent_prompt(query, context, history, language=lang, short_answers=short_answers)
258
+ messages = [{"role": "user", "content": [{"type": "text", "text": prompt}]}]
259
+
260
+ logger.info(f"[AGENT] 🏁 Starting Agent Loop for Query: '{query}' (Lang: {lang})")
261
+
262
+ max_turns = 3
263
+ for turn in range(max_turns):
264
+ logger.info(f"[AGENT] 🔄 Turn {turn+1}/{max_turns}")
265
+
266
+ input_ids = processor.apply_chat_template(messages, tokenize=True, add_generation_prompt=True, return_tensors="pt").to(model.device)
267
+ streamer = TextIteratorStreamer(processor, skip_prompt=True, skip_special_tokens=True)
268
+
269
+ gen_kwargs = {"input_ids": input_ids, "streamer": streamer, "max_new_tokens": 512, "do_sample": False}
270
+ thread = Thread(target=model.generate, kwargs=gen_kwargs)
271
+ thread.start()
272
+
273
+ current_turn_text = ""
274
+ # We yield a TUPLE: (accumulated_text_for_THIS_turn, is_final)
275
+ # But wait, the wrapper needs to handle new messages.
276
+ # Strategy: Yield just the text of THIS turn. Wrapper handles appending to a NEW history item each turn.
277
+
278
+ logger.info("[AGENT] ⏳ Streaming response...")
279
+ for new_text in streamer:
280
+ current_turn_text += new_text
281
+ clean_chunk = re.sub(r"<tool_call>.*?</tool_call>", "", current_turn_text, flags=re.DOTALL)
282
+ yield clean_chunk.strip()
283
+
284
+ logger.info(f"[AGENT] 🛑 Raw Model Output: {current_turn_text}")
285
+
286
+ # Tool Detection
287
+ tool_match = re.search(r"<tool_call>(.*?)</tool_call>", current_turn_text, re.DOTALL)
288
+ if tool_match:
289
+ # If tool found, this turn is OVER regarding user output.
290
+ # We yield a special signal to indicate "End of Message, Start Next Logic"?
291
+ # actually, if we yield, the wrapper updates history[-1].
292
+ # If we want a NEW message, we need to tell wrapper to append.
293
+ # Simplified: Use a separator? No, wrapper loop is easier.
294
+
295
+ # For now, let's keep the generator simple.
296
+ # It yields text updates for the CURRENT turn.
297
+ # Once loop breaks (tool found), we start next turn.
298
+ # BUT: How to tell wrapper "This turn is done, start a new bubble"?
299
+ # Generator yields: {"text": "...", "new_bubble": True/False}
300
+
301
+ try:
302
+ tool_data = json.loads(tool_match.group(1))
303
+ logger.info(f"[AGENT] 🛠️ Tool Call Detected: {tool_data}")
304
+
305
+ tool_name = tool_data.get("name")
306
+ tool_args = tool_data.get("arguments", {})
307
+
308
+ if tool_name == "oracle_consultation":
309
+ topic = tool_args.get("topic", "")
310
+
311
+ # Name Handling: Use provided name or default to 'Seeker'
312
+ req_name = tool_args.get("name", "").strip()
313
+ effective_name = req_name if req_name else "Seeker"
314
+
315
+ logger.info(f"[AGENT] 🔮 Executing Oracle with topic: '{topic}' for '{effective_name}'")
316
+ if get_oracle_data:
317
+ try:
318
+ # Call backend
319
+ oracle_raw = get_oracle_data(name=effective_name, topic=topic, date_str="")
320
+
321
+ # FILTERING LOGIC (User Request: Only 3 sources, no BOS API/ELS)
322
+ # We construct a filtered dictionary
323
+ filtered_result = {
324
+ "wisdom_nodes": oracle_raw.get("wisdom_nodes", [])
325
+ }
326
+ # If wisdom_nodes is missing/empty, maybe keep raw but warn?
327
+ # Use strict filtering as requested.
328
+
329
+ tool_result = json.dumps(filtered_result, indent=2)
330
+ logger.info(f"[AGENT] ✅ Oracle Result Obtained (Filtered Size: {len(tool_result)} bytes)")
331
+ except Exception as e:
332
+ logger.error(f"[AGENT] ❌ Oracle Backend Error: {e}")
333
+ tool_result = f"Error executing oracle: {str(e)}"
334
+ else:
335
+ logger.warning("[AGENT] ⚠️ Oracle module not available")
336
+ tool_result = "Oracle module not available."
337
+ else:
338
+ logger.warning(f"[AGENT] ⚠️ Unknown tool requested: {tool_name}")
339
+ tool_result = f"Unknown tool: {tool_name}"
340
+
341
+ messages.append({"role": "assistant", "content": [{"type": "text", "text": current_turn_text}]})
342
+
343
+ tool_injection = f"""<tool_result>{tool_result}</tool_result>
344
+ Now interpret this result soulfully and poetically for the user. Do not mention JSON.
345
+ IMPORTANT: Connect this smoothly to your previous statement. Ensure a fluid, cohesive narrative without abrupt jumps."""
346
+
347
+ logger.info("[AGENT] 💉 Injecting Tool Result into context for interpretation...")
348
+ messages.append({"role": "user", "content": [{"type": "text", "text": tool_injection}]})
349
+
350
+ # Yield a special marker to say "Turn Finished"
351
+ yield "__TURN_END__"
352
+ continue
353
+ except Exception as e:
354
+ logger.error(f"[AGENT] 💥 Tool parsing/logic crash: {e}")
355
+ break
356
+ else:
357
+ logger.info("[AGENT] ✨ No tool calls. Finalizing response.")
358
+ break
359
+
360
+ # --- Voice Engine ---
361
+ async def generate_speech(text: str, lang: str = "English"):
362
+ import edge_tts
363
+ VOICES = {"English": "en-US-GuyNeural", "German": "de-DE-ConradNeural", "French": "fr-FR-HenriNeural"}
364
+ voice = VOICES.get(lang, VOICES["English"])
365
+ logger.debug(f"TRACE: generate_speech() called. Text len: {len(text)}, Lang: {lang}")
366
+ temp_wav = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3")
367
+ communicate = edge_tts.Communicate(text, voice)
368
+ await communicate.save(temp_wav.name)
369
+ return temp_wav.name
370
+
371
+ def transcribe_audio(path: str):
372
+ logger.debug(f"TRACE: transcribe_audio() called with path: {path}")
373
+ return "Transcribed text"
374
+
375
+ # --- Gradio Wrappers ---
376
+ def voice_chat_wrapper(audio_path, history, threads, tid, vs_state, mh_state, short_answers):
377
+ if audio_path is None: yield history, threads, gr.update(), gr.update(), None; return
378
+ text = transcribe_audio(audio_path)
379
+ detected_lang = detect_language(text)
380
+ final_history, final_threads, final_update = history, threads, gr.update()
381
+ if text:
382
+ gen = chat_wrapper(text, history, threads, tid, vs_state, mh_state, short_answers=short_answers, lang=detected_lang)
383
+ for h, t, tr1, tr2, _ in gen:
384
+ final_history, final_threads, final_update = h, t, tr1
385
+ yield h, t, tr1, tr2, None
386
+ import asyncio
387
+ last_msg = final_history[-1]["content"] if final_history else ""
388
+ if last_msg:
389
+ voice_path = asyncio.run(generate_speech(last_msg, lang=detected_lang))
390
+ yield final_history, final_threads, final_update, final_update, voice_path
391
+ else:
392
+ yield final_history, final_threads, final_update, final_update, None
393
+
394
+ def chat_wrapper(message, history, threads, tid, vs_state, mh_state, short_answers=False, lang=None):
395
+ if not message.strip():
396
+ upd = gr.update(choices=[(v["title"], k) for k, v in threads.items()], value=tid)
397
+ yield history, threads, upd, upd, None
398
+ return
399
+ history.append({"role": "user", "content": message})
400
+ yield history, threads, gr.update(), gr.update(), None
401
+
402
+ # Start first response bubble
403
+ history.append({"role": "assistant", "content": ""})
404
+
405
+ for response_part in chat_agent_stream(message, history[:-2], vs_state, mh_state, user_lang=lang, short_answers=short_answers):
406
+ if response_part == "__TURN_END__":
407
+ # Start NEW bubble for next turn
408
+ history.append({"role": "assistant", "content": ""})
409
+ yield history, threads, gr.update(), gr.update(), None
410
+ else:
411
+ history[-1]["content"] = response_part
412
+ yield history, threads, gr.update(), gr.update(), None
413
+
414
+ # Cleanup empty bubble if exists (rare edge case)
415
+ if not history[-1]["content"]: history.pop()
416
+
417
+ if tid not in threads: threads[tid] = {"title": "Conversation", "history": []}
418
+ threads[tid]["history"] = history
419
+ if len(history) <= 2:
420
+ threads[tid]["title"] = (message[:25] + "..") if message else "Conversation"
421
+ choices = [(v["title"], k) for k, v in threads.items()]
422
+ upd = gr.update(choices=choices, value=tid)
423
+ yield history, threads, upd, upd, None
424
+
425
+ def stream_handler(stream, state):
426
+ if stream is None: return state, None
427
+ sr, y = stream
428
+ if y is None or len(y) == 0: return state, None
429
+ y = y.astype(np.float32)
430
+ y = y / np.max(np.abs(y)) if np.max(np.abs(y)) > 0 else y
431
+ rms = np.sqrt(np.mean(y**2))
432
+ SILENCE_THRESHOLD, SILENCE_CHUNKS = 0.01, 20
433
+ if state is None: state = {"buffer": [], "silence_counter": 0, "is_speaking": False}
434
+ state["buffer"].append((sr, stream[1]))
435
+ if rms > SILENCE_THRESHOLD:
436
+ state["is_speaking"], state["silence_counter"] = True, 0
437
+ elif state["is_speaking"]:
438
+ state["silence_counter"] += 1
439
+ if state["is_speaking"] and state["silence_counter"] > SILENCE_CHUNKS:
440
+ full_audio = np.concatenate([c[1] for c in state["buffer"]])
441
+ sr_final = state["buffer"][0][0]
442
+ temp_wav = tempfile.NamedTemporaryFile(delete=False, suffix=".wav")
443
+ wavfile.write(temp_wav.name, sr_final, full_audio)
444
+ return {"buffer": [], "silence_counter": 0, "is_speaking": False}, temp_wav.name
445
+ return state, None
446
+
447
+ # --- INTERNAL CALLBACKS ---
448
+ def create_new_thread_callback(threads):
449
+ nid = str(uuid.uuid4())
450
+ threads[nid] = {"title": "New Conversation", "history": []}
451
+ choices = [(v["title"], k) for k, v in threads.items()]
452
+ return threads, nid, gr.update(choices=choices, value=nid), []
453
+
454
+ def switch_thread(tid, t_state):
455
+ logger.debug(f"TRACE: switch_thread() called for tid: {tid}")
456
+ if isinstance(tid, list):
457
+ if not tid: return [], gr.update(), gr.update(), gr.update()
458
+ tid = tid[0]
459
+ tid = str(tid)
460
+ history = t_state.get(tid, {}).get("history", [])
461
+ choices = [(v["title"], k) for k, v in t_state.items()]
462
+ upd = gr.update(value=tid, choices=choices)
463
+ return history, tid, upd, upd
464
+
465
+ def session_import_handler(file):
466
+ if not file: return [], {}, None, gr.update(), gr.update()
467
+ with open(file.name, "r") as f: data = json.load(f)
468
+ imported_threads = data.get("threads", {})
469
+ active_id = data.get("active_id", list(imported_threads.keys())[0] if imported_threads else None)
470
+ history = imported_threads.get(active_id, {}).get("history", []) if active_id else []
471
+ choices = [(v["title"], k) for k, v in imported_threads.items()]
472
+ upd = gr.update(choices=choices, value=active_id)
473
+ return history, imported_threads, active_id, upd, upd
474
+
475
+ def session_export_handler(chatbot_val, threads, active_id):
476
+ export_data = {"threads": threads, "active_id": active_id}
477
+ path = "sage_session_export.json"
478
+ with open(path, "w") as f: json.dump(export_data, f, indent=2)
479
+ return path
480
+
481
+ def build_demo() -> gr.Blocks:
482
+ initial_thread_id = str(uuid.uuid4())
483
+ with gr.Blocks(title="Gemma 3 Sage v6.5 SP1", theme="soft", css=PREMIUM_CSS) as demo:
484
+ threads_state = gr.State({initial_thread_id: {"title": "New Chat", "history": []}})
485
+ active_thread_id = gr.State(initial_thread_id)
486
+ vector_store_state = gr.State(None)
487
+ mongo_handler_state = gr.State(None)
488
+
489
+ with gr.Row(elem_classes="header-tray"):
490
+ gr.Markdown("# 🌌 Gemma 3 Sage <small>v6.5 SP1</small>")
491
+
492
+ with gr.Row():
493
+ # Desktop Sidebar (Radio List)
494
+ with gr.Column(scale=1, variant="panel", elem_classes="sidebar-panel glass-panel desktop-only"):
495
+ gr.Markdown("### 🕒 Recent Chats")
496
+ # Using Radio as a list selector
497
+ thread_list = gr.Radio(choices=[(f"New Chat", initial_thread_id)], value=initial_thread_id, label=None, interactive=True, container=False)
498
+ new_thread_btn = gr.Button("➕ New Conversation", variant="secondary")
499
+
500
+ with gr.Column(scale=4):
501
+ with gr.Tabs() as tabs:
502
+ with gr.Tab("💬 Live Conversation", id=0, elem_classes="glass-panel"):
503
+
504
+ # Mobile Menu (Accordion + Dropdown)
505
+ with gr.Accordion("🕒 Conversations (Mobile)", open=False, visible=True, elem_classes="mobile-only") as mobile_sessions:
506
+ m_thread_list = gr.Dropdown(choices=[("New Chat", initial_thread_id)], value=initial_thread_id, label="Select Session")
507
+ m_new_btn = gr.Button("➕ New Conversation", variant="secondary")
508
+
509
+ chatbot = gr.Chatbot(label="Sage", type="messages", height=600, show_label=False, autoscroll=False)
510
+ with gr.Row():
511
+ msg_textbox = gr.Textbox(placeholder="Whisper your heart or type...", label=None, scale=8, container=False)
512
+ submit_btn = gr.Button("Send", variant="primary", scale=1)
513
+ # Moved Short Answer checkbox here for visibility
514
+ with gr.Row():
515
+ short_ans_cb = gr.Checkbox(label="Short Answers", value=False)
516
+ with gr.Row():
517
+ stream_state = gr.State({"buffer": [], "silence_counter": 0, "is_speaking": False})
518
+ audio_input = gr.Audio(label="Voice", sources="microphone", type="numpy", streaming=True)
519
+ processed_audio, audio_output = gr.State(None), gr.Audio(label="Sage Voice", autoplay=True, visible=False)
520
+ with gr.Row(elem_classes="glass-panel"):
521
+ export_btn = gr.Button("📤 Export Session", variant="secondary", size="sm")
522
+ import_file = gr.File(label="Import", file_count="single", height=60)
523
+ export_file = gr.File(label="Download", interactive=False, visible=False)
524
+
525
+ with gr.Tab("📚 Sacred Knowledge", id=1, elem_classes="glass-panel"):
526
+ file_uploader = gr.File(label="Upload", file_count="multiple", type="filepath")
527
+ index_button = gr.Button("🔄 Sync Index", variant="primary")
528
+ index_status = gr.Markdown("Bereit.")
529
+ with gr.Accordion("⚙️ MongoDB Settings", open=False):
530
+ mongo_uri = gr.Textbox(label="URI", value="mongodb://localhost:27017/")
531
+ mongo_db = gr.Textbox(label="DB", value="rag_db")
532
+ mongo_coll = gr.Textbox(label="Coll", value="gemma_chunks")
533
+ use_mongo_cb = gr.Checkbox(label="Sync to Mongo", value=True)
534
+ clear_mongo_btn = gr.Button("🗑️ Clear Mongo")
535
+ clear_idx_btn = gr.Button("🧹 Clear FAISS", variant="stop")
536
+
537
+ clear_mongo_btn.click(lambda u, d, c: MongoDBHandler(u, d, c).connect() and MongoDBHandler(u, d, c).clear() or "Mongo geleert", [mongo_uri, mongo_db, mongo_coll], index_status)
538
+
539
+ audio_input.stream(stream_handler, [audio_input, stream_state], [stream_state, processed_audio])
540
+ processed_audio.change(voice_chat_wrapper, [processed_audio, chatbot, threads_state, active_thread_id, vector_store_state, mongo_handler_state, short_ans_cb], [chatbot, threads_state, thread_list, m_thread_list, audio_output])
541
+ msg_textbox.submit(chat_wrapper, [msg_textbox, chatbot, threads_state, active_thread_id, vector_store_state, mongo_handler_state, short_ans_cb], [chatbot, threads_state, thread_list, m_thread_list, audio_output]).then(lambda: "", None, msg_textbox)
542
+ submit_btn.click(chat_wrapper, [msg_textbox, chatbot, threads_state, active_thread_id, vector_store_state, mongo_handler_state, short_ans_cb], [chatbot, threads_state, thread_list, m_thread_list, audio_output]).then(lambda: "", None, msg_textbox)
543
+ new_thread_btn.click(create_new_thread_callback, [threads_state], [threads_state, active_thread_id, thread_list, chatbot])
544
+ m_new_btn.click(create_new_thread_callback, [threads_state], [threads_state, active_thread_id, m_thread_list, chatbot])
545
+ thread_list.change(switch_thread, [thread_list, threads_state], [chatbot, active_thread_id, thread_list, m_thread_list])
546
+ m_thread_list.change(switch_thread, [m_thread_list, threads_state], [chatbot, active_thread_id, thread_list, m_thread_list])
547
+ index_button.click(index_files, [file_uploader, mongo_uri, mongo_db, mongo_coll, use_mongo_cb, vector_store_state, mongo_handler_state], [index_status, vector_store_state, mongo_handler_state], show_progress="full")
548
+ clear_idx_btn.click(clear_index, outputs=[index_status, vector_store_state, mongo_handler_state], show_progress="full")
549
+ import_file.change(session_import_handler, import_file, [chatbot, threads_state, active_thread_id, thread_list, m_thread_list], show_progress="full")
550
+ export_btn.click(session_export_handler, [chatbot, threads_state, active_thread_id], export_file, show_progress="full").then(lambda: gr.update(visible=True), None, export_file)
551
+ return demo
552
+
553
+ if __name__ == "__main__":
554
+ get_llm(); build_demo().launch(share=True, server_name="0.0.0.0", ssl_certfile="cert.pem", ssl_keyfile="key.pem", ssl_verify=False)