KeenWoo commited on
Commit
c20c9cd
Β·
verified Β·
1 Parent(s): f4693d8

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +534 -0
app.py ADDED
@@ -0,0 +1,534 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import shutil
4
+ import gradio as gr
5
+ import tempfile
6
+ from datetime import datetime
7
+ from typing import List, Dict, Any, Optional
8
+ from pytube import YouTube
9
+ from pathlib import Path
10
+ import re
11
+
12
+ # --- Agent Imports & Safe Fallbacks ---
13
+ try:
14
+ from alz_companion.agent import (
15
+ bootstrap_vectorstore, make_rag_chain, answer_query, synthesize_tts,
16
+ transcribe_audio, detect_tags_from_query, describe_image, build_or_load_vectorstore,
17
+ _default_embeddings
18
+ )
19
+ from alz_companion.prompts import BEHAVIOUR_TAGS, EMOTION_STYLES
20
+ from langchain.schema import Document
21
+ from langchain_community.vectorstores import FAISS
22
+ AGENT_OK = True
23
+ except Exception as e:
24
+ AGENT_OK = False
25
+ def bootstrap_vectorstore(sample_paths=None, index_path="data/"): return object()
26
+ def build_or_load_vectorstore(docs, index_path, is_personal=False): return object()
27
+ def make_rag_chain(vs_general, vs_personal, **kwargs): return lambda q, **k: {"answer": f"(Demo) You asked: {q}", "sources": []}
28
+ def answer_query(chain, q, **kwargs): return chain(q, **kwargs)
29
+ def synthesize_tts(text: str, lang: str = "en"): return None
30
+ def transcribe_audio(filepath: str, lang: str = "en"): return "This is a transcribed message."
31
+ def detect_tags_from_query(*args, **kwargs): return {"detected_behavior": "None", "detected_emotion": "None"}
32
+ def describe_image(image_path: str): return "This is a description of an image."
33
+ def _default_embeddings(): return None
34
+ class Document:
35
+ def __init__(self, page_content, metadata): self.page_content, self.metadata = page_content, metadata
36
+ class FAISS:
37
+ def __init__(self): self.docstore = type('obj', (object,), {'_dict': {}})()
38
+ BEHAVIOUR_TAGS, EMOTION_STYLES = {"None": []}, {"None": {}}
39
+ print(f"WARNING: Could not import from alz_companion ({e}). Running in UI-only demo mode.")
40
+
41
+ # --- Centralized Configuration ---
42
+ CONFIG = {
43
+ "themes": ["All", "The Father", "Still Alice", "Away from Her", "Alive Inside", "General Caregiving"],
44
+ "roles": ["patient", "caregiver"],
45
+ "behavior_tags": ["None"] + list(BEHAVIOUR_TAGS.keys()),
46
+ "emotion_tags": ["None"] + list(EMOTION_STYLES.keys()),
47
+ "topic_tags": ["None", "caregiving_advice", "medical_fact", "personal_story", "research_update", "treatment_option:home_safety", "treatment_option:long_term_care", "treatment_option:music_therapy", "treatment_option:reassurance", "treatment_option:routine_structuring", "treatment_option:validation_therapy"],
48
+ "context_tags": ["None", "disease_stage_mild", "disease_stage_moderate", "disease_stage_advanced", "disease_stage_unspecified", "interaction_mode_one_to_one", "interaction_mode_small_group", "interaction_mode_group_activity", "relationship_family", "relationship_spouse", "relationship_staff_or_caregiver", "relationship_unspecified", "setting_home_or_community", "setting_care_home", "setting_clinic_or_hospital"],
49
+ "languages": {"English": "en", "Chinese": "zh", "Cantonese": "zh-yue", "Korean": "ko", "Japanese": "ja", "Malay": "ms", "French": "fr", "Spanish": "es", "Hindi": "hi", "Arabic": "ar"},
50
+ "tones": ["warm", "empathetic", "caring", "reassuring", "calm", "optimistic", "motivating", "neutral", "formal", "humorous"]
51
+ }
52
+
53
+ # --- File Management & Vector Store Logic ---
54
+ def _storage_root() -> Path:
55
+ for p in [Path(os.getenv("SPACE_STORAGE", "")), Path("/data"), Path.home() / ".cache" / "alz_companion"]:
56
+ if not p: continue
57
+ try:
58
+ p.mkdir(parents=True, exist_ok=True)
59
+ (p / ".write_test").write_text("ok")
60
+ (p / ".write_test").unlink(missing_ok=True)
61
+ return p
62
+ except Exception: continue
63
+ tmp = Path(tempfile.gettempdir()) / "alz_companion"
64
+ tmp.mkdir(parents=True, exist_ok=True)
65
+ return tmp
66
+
67
+ STORAGE_ROOT = _storage_root()
68
+ INDEX_BASE = STORAGE_ROOT / "index"
69
+ PERSONAL_DATA_BASE = STORAGE_ROOT / "personal"
70
+ UPLOADS_BASE = INDEX_BASE / "uploads"
71
+ PERSONAL_INDEX_PATH = str(PERSONAL_DATA_BASE / "personal_faiss_index")
72
+ NLU_EXAMPLES_INDEX_PATH = str(INDEX_BASE / "nlu_examples_faiss_index")
73
+
74
+ THEME_PATHS = {t: str(INDEX_BASE / f"faiss_index_{t.replace(' ', '').lower()}") for t in CONFIG["themes"]}
75
+
76
+ os.makedirs(UPLOADS_BASE, exist_ok=True)
77
+ os.makedirs(PERSONAL_DATA_BASE, exist_ok=True)
78
+ for p in THEME_PATHS.values(): os.makedirs(p, exist_ok=True)
79
+
80
+ vectorstores = {}
81
+ personal_vectorstore = None
82
+ nlu_vectorstore = None
83
+ test_fixtures = []
84
+
85
+ try:
86
+ personal_vectorstore = build_or_load_vectorstore([], PERSONAL_INDEX_PATH, is_personal=True)
87
+ except Exception:
88
+ personal_vectorstore = None
89
+
90
+ def bootstrap_nlu_vectorstore(example_file: str, index_path: str) -> FAISS:
91
+ if not os.path.exists(example_file):
92
+ print(f"WARNING: NLU example file not found at {example_file}. NLU will be less accurate.")
93
+ return build_or_load_vectorstore([], index_path)
94
+ docs = []
95
+ with open(example_file, "r", encoding="utf-8") as f:
96
+ for line in f:
97
+ try:
98
+ data = json.loads(line)
99
+ doc = Document(page_content=data["query"], metadata=data)
100
+ docs.append(doc)
101
+ except (json.JSONDecodeError, KeyError):
102
+ continue
103
+ print(f"Found and loaded {len(docs)} NLU training examples.")
104
+ if os.path.exists(index_path):
105
+ shutil.rmtree(index_path)
106
+ return build_or_load_vectorstore(docs, index_path)
107
+
108
+ def canonical_theme(tk: str) -> str: return tk if tk in CONFIG["themes"] else "All"
109
+ def theme_upload_dir(theme: str) -> str:
110
+ p = UPLOADS_BASE / f"theme_{canonical_theme(theme).replace(' ', '').lower()}"
111
+ p.mkdir(exist_ok=True)
112
+ return str(p)
113
+ def load_manifest(theme: str) -> Dict[str, Any]:
114
+ p = os.path.join(theme_upload_dir(theme), "manifest.json")
115
+ if os.path.exists(p):
116
+ try:
117
+ with open(p, "r", encoding="utf-8") as f: return json.load(f)
118
+ except Exception: pass
119
+ return {"files": {}}
120
+ def save_manifest(theme: str, man: Dict[str, Any]):
121
+ with open(os.path.join(theme_upload_dir(theme), "manifest.json"), "w", encoding="utf-8") as f: json.dump(man, f, indent=2)
122
+ def list_theme_files(theme: str) -> List[tuple[str, bool]]:
123
+ man = load_manifest(theme)
124
+ base = theme_upload_dir(theme)
125
+ found = [(n, bool(e)) for n, e in man.get("files", {}).items() if os.path.exists(os.path.join(base, n))]
126
+ existing = {n for n, e in found}
127
+ for name in sorted(os.listdir(base)):
128
+ if name not in existing and os.path.isfile(os.path.join(base, name)): found.append((name, False))
129
+ man["files"] = dict(found)
130
+ save_manifest(theme, man)
131
+ return found
132
+ def copy_into_theme(theme: str, src_path: str) -> str:
133
+ fname = os.path.basename(src_path)
134
+ dest = os.path.join(theme_upload_dir(theme), fname)
135
+ shutil.copy2(src_path, dest)
136
+ return dest
137
+ def seed_files_into_theme(theme: str):
138
+ SEED_FILES = [("sample_data/caregiving_tips.txt", True), ("sample_data/the_father_segments_enriched_harmonized_plus.jsonl", True), ("sample_data/still_alice_enriched_harmonized_plus.jsonl", True), ("sample_data/away_from_her_enriched_harmonized_plus.jsonl", True), ("sample_data/alive_inside_enriched_harmonized.jsonl", True)]
139
+ man, changed = load_manifest(theme), False
140
+ for path, enable in SEED_FILES:
141
+ if not os.path.exists(path): continue
142
+ fname = os.path.basename(path)
143
+ if not os.path.exists(os.path.join(theme_upload_dir(theme), fname)):
144
+ copy_into_theme(theme, path)
145
+ man["files"][fname] = bool(enable)
146
+ changed = True
147
+ if changed: save_manifest(theme, man)
148
+ def ensure_index(theme='All'):
149
+ theme = canonical_theme(theme)
150
+ if theme in vectorstores: return vectorstores[theme]
151
+ upload_dir = theme_upload_dir(theme)
152
+ enabled_files = [os.path.join(upload_dir, n) for n, enabled in list_theme_files(theme) if enabled]
153
+ index_path = THEME_PATHS.get(theme)
154
+ vectorstores[theme] = bootstrap_vectorstore(sample_paths=enabled_files, index_path=index_path)
155
+ return vectorstores[theme]
156
+
157
+ # --- Gradio Callbacks ---
158
+ def collect_settings(*args):
159
+ keys = ["role", "patient_name", "caregiver_name", "tone", "language", "tts_lang", "temperature", "behaviour_tag", "emotion_tag", "topic_tag", "active_theme", "tts_on", "debug_mode"]
160
+ return dict(zip(keys, args))
161
+
162
+ def parse_and_tag_entries(text_content: str, source: str, settings: dict = None) -> List[Document]:
163
+ docs_to_add = []
164
+ for entry in re.split(r'\n(?:---|--|-|-\*-|-\.-)\n', text_content):
165
+ if not entry.strip(): continue
166
+ lines = entry.strip().split('\n')
167
+ title_line = lines[0].split(':', 1)
168
+ title = title_line[1].strip() if len(title_line) > 1 and "title:" in lines[0].lower() else "Untitled Text Entry"
169
+ content_part = "\n".join(lines[1:])
170
+ content = content_part.split(':', 1)[1].strip() if "content:" in content_part.lower() else content_part.strip()
171
+ full_content = f"Title: {title}\n\nContent: {content}"
172
+ detected_tags = detect_tags_from_query(
173
+ content, nlu_vectorstore=nlu_vectorstore, behavior_options=CONFIG["behavior_tags"],
174
+ emotion_options=CONFIG["emotion_tags"], topic_options=CONFIG["topic_tags"],
175
+ context_options=CONFIG["context_tags"], settings=settings)
176
+ metadata = {"source": source, "title": title}
177
+ if detected_tags.get("detected_behaviors"): metadata["behaviors"] = [b.lower() for b in detected_tags["detected_behaviors"]]
178
+ if detected_tags.get("detected_emotion") != "None": metadata["emotion"] = detected_tags.get("detected_emotion").lower()
179
+ if detected_tags.get("detected_topic") != "None": metadata["topic_tags"] = [detected_tags.get("detected_topic").lower()]
180
+ if detected_tags.get("detected_contexts"): metadata["context_tags"] = [c.lower() for c in detected_tags["detected_contexts"]]
181
+ docs_to_add.append(Document(page_content=full_content, metadata=metadata))
182
+ return docs_to_add
183
+
184
+ def handle_add_knowledge(title, text_input, file_input, image_input, yt_url, settings):
185
+ global personal_vectorstore
186
+ docs_to_add = []
187
+ source, content = "Unknown", ""
188
+ if text_input and text_input.strip():
189
+ source, content = "Text Input", f"Title: {title or 'Untitled'}\n\nContent: {text_input}"
190
+ elif file_input:
191
+ source = os.path.basename(file_input.name)
192
+ if file_input.name.lower().endswith('.txt'):
193
+ with open(file_input.name, 'r', encoding='utf-8') as f: content = f.read()
194
+ else:
195
+ transcribed = transcribe_audio(file_input.name)
196
+ content = f"Title: {title or 'Audio/Video Note'}\n\nContent: {transcribed}"
197
+ elif image_input:
198
+ source, description = "Image Input", describe_image(image_input)
199
+ content = f"Title: {title or 'Image Note'}\n\nContent: {description}"
200
+ elif yt_url and ("youtube.com" in yt_url or "youtu.be" in yt_url):
201
+ try:
202
+ yt = YouTube(yt_url)
203
+ with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as temp_audio_file:
204
+ yt.streams.get_audio_only().download(filename=temp_audio_file.name)
205
+ transcribed = transcribe_audio(temp_audio_file.name)
206
+ os.remove(temp_audio_file.name)
207
+ source, content = f"YouTube: {yt.title}", f"Title: {title or yt.title}\n\nContent: {transcribed}"
208
+ except Exception as e:
209
+ return f"Error processing YouTube link: {e}"
210
+ else:
211
+ return "Please provide content to add."
212
+ if content:
213
+ docs_to_add = parse_and_tag_entries(content, source, settings=settings)
214
+ if not docs_to_add: return "No processable content found to add."
215
+ if personal_vectorstore is None:
216
+ personal_vectorstore = build_or_load_vectorstore(docs_to_add, PERSONAL_INDEX_PATH, is_personal=True)
217
+ else:
218
+ personal_vectorstore.add_documents(docs_to_add)
219
+ personal_vectorstore.save_local(PERSONAL_INDEX_PATH)
220
+ return f"Successfully added {len(docs_to_add)} new memory/memories."
221
+
222
+ def chat_fn(user_text, audio_file, settings, chat_history):
223
+ global personal_vectorstore
224
+
225
+ # --- FIX START: Reverse history on entry for backend logic ---
226
+ if chat_history:
227
+ chat_history.reverse()
228
+ # --- FIX END ---
229
+
230
+ question = (user_text or "").strip()
231
+ if audio_file and not question:
232
+ try:
233
+ question = transcribe_audio(audio_file, lang=CONFIG["languages"].get(settings.get("tts_lang", "English"), "en"))
234
+ except Exception as e:
235
+ err_msg = f"Audio Error: {e}" if settings.get("debug_mode") else "Sorry, I couldn't understand the audio."
236
+ chat_history.append({"role": "assistant", "content": err_msg})
237
+ # --- FIX START: Reverse history on exit for UI display ---
238
+ return "", None, chat_history[::-1]
239
+ # --- FIX END ---
240
+ if not question:
241
+ # --- FIX START: Reverse history on exit for UI display ---
242
+ if chat_history:
243
+ chat_history.reverse()
244
+ return "", None, chat_history
245
+ # --- FIX END ---
246
+
247
+ chat_history.append({"role": "user", "content": question})
248
+ final_tags = { "scenario_tag": None, "emotion_tag": None, "topic_tag": None, "context_tags": [] }
249
+ manual_behavior = settings.get("behaviour_tag", "None")
250
+ manual_emotion = settings.get("emotion_tag", "None")
251
+ manual_topic = settings.get("topic_tag", "None")
252
+ if all(m == "None" for m in [manual_behavior, manual_emotion, manual_topic]):
253
+ detected_tags = detect_tags_from_query(
254
+ question, nlu_vectorstore=nlu_vectorstore, behavior_options=CONFIG["behavior_tags"],
255
+ emotion_options=CONFIG["emotion_tags"], topic_options=CONFIG["topic_tags"],
256
+ context_options=CONFIG["context_tags"], settings=settings)
257
+ final_tags["scenario_tag"] = detected_tags.get("detected_behaviors", [None])[0]
258
+ final_tags["emotion_tag"] = detected_tags.get("detected_emotion")
259
+ final_tags["topic_tag"] = detected_tags.get("detected_topic")
260
+ final_tags["context_tags"] = detected_tags.get("detected_contexts", [])
261
+ detected_parts = [f"{k.split('_')[1]}=`{v}`" for k, v in final_tags.items() if v and v != "None"]
262
+ if detected_parts:
263
+ chat_history.append({"role": "assistant", "content": f"*(Auto-detected context: {', '.join(detected_parts)})*"})
264
+ else:
265
+ final_tags["scenario_tag"] = manual_behavior if manual_behavior != "None" else None
266
+ final_tags["emotion_tag"] = manual_emotion if manual_emotion != "None" else None
267
+ final_tags["topic_tag"] = manual_topic if manual_topic != "None" else None
268
+ vs_general = ensure_index(settings.get("active_theme", "All"))
269
+ if personal_vectorstore is None:
270
+ personal_vectorstore = build_or_load_vectorstore([], PERSONAL_INDEX_PATH, is_personal=True)
271
+ rag_settings = {k: settings.get(k) for k in ["role", "temperature", "language", "patient_name", "caregiver_name", "tone"]}
272
+ chain = make_rag_chain(vs_general, personal_vectorstore, **rag_settings)
273
+
274
+ # The RAG chain needs the chronological history
275
+ response = answer_query(chain, question, chat_history=chat_history[:-1], **final_tags)
276
+ answer = response.get("answer", "[No answer found]")
277
+ chat_history.append({"role": "assistant", "content": answer})
278
+ if response.get("sources"):
279
+ chat_history.append({"role": "assistant", "content": f"*(Sources used: {', '.join(response['sources'])})*"})
280
+ audio_out = None
281
+ if settings.get("tts_on") and answer:
282
+ audio_out = synthesize_tts(answer, lang=CONFIG["languages"].get(settings.get("tts_lang"), "en"))
283
+
284
+ # --- FIX START: Reverse history on exit for UI display ---
285
+ return "", gr.update(value=audio_out, visible=bool(audio_out)), chat_history[::-1]
286
+ # --- FIX END ---
287
+
288
+ def save_chat_to_memory(chat_history):
289
+ global personal_vectorstore
290
+ # --- FIX START: Reverse history on entry to save chronologically ---
291
+ if chat_history:
292
+ chat_history.reverse()
293
+ # --- FIX END ---
294
+ if not chat_history: return "Nothing to save."
295
+ formatted_chat = [f"{m['role'].title()}: {m['content'].strip()}" for m in chat_history if not m['content'].strip().startswith("*(")]
296
+ if not formatted_chat: return "No conversation to save."
297
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
298
+ title = f"Conversation from {timestamp}"
299
+ full_content = f"Title: {title}\n\nContent:\n" + "\n".join(formatted_chat)
300
+ doc = Document(page_content=full_content, metadata={"source": "Saved Chat", "title": title})
301
+ if personal_vectorstore is None:
302
+ personal_vectorstore = build_or_load_vectorstore([doc], PERSONAL_INDEX_PATH, is_personal=True)
303
+ else:
304
+ personal_vectorstore.add_documents([doc])
305
+ personal_vectorstore.save_local(PERSONAL_INDEX_PATH)
306
+ return f"Conversation from {timestamp} saved."
307
+ def list_personal_memories():
308
+ global personal_vectorstore
309
+ if personal_vectorstore is None or not hasattr(personal_vectorstore.docstore, '_dict') or not personal_vectorstore.docstore._dict:
310
+ return gr.update(value=[["No memories", "", ""]]), gr.update(choices=[], value=None)
311
+ docs = list(personal_vectorstore.docstore._dict.values())
312
+ return gr.update(value=[[d.metadata.get('title', '...'), d.metadata.get('source', '...'), d.page_content] for d in docs]), gr.update(choices=[d.page_content for d in docs])
313
+ def delete_personal_memory(memory_to_delete):
314
+ global personal_vectorstore
315
+ if personal_vectorstore is None or not memory_to_delete: return "No memory selected."
316
+ all_docs = list(personal_vectorstore.docstore._dict.values())
317
+ docs_to_keep = [d for d in all_docs if d.page_content != memory_to_delete]
318
+ if len(all_docs) == len(docs_to_keep): return "Error: Could not find memory."
319
+ if not docs_to_keep:
320
+ if os.path.isdir(PERSONAL_INDEX_PATH): shutil.rmtree(PERSONAL_INDEX_PATH)
321
+ personal_vectorstore = build_or_load_vectorstore([], PERSONAL_INDEX_PATH, is_personal=True)
322
+ else:
323
+ new_vs = FAISS.from_documents(docs_to_keep, _default_embeddings())
324
+ new_vs.save_local(PERSONAL_INDEX_PATH)
325
+ personal_vectorstore = new_vs
326
+ return "Successfully deleted memory."
327
+ def upload_knowledge(files, theme):
328
+ for f in files: copy_into_theme(theme, f.name)
329
+ if theme in vectorstores: del vectorstores[theme]
330
+ return f"Uploaded {len(files)} file(s)."
331
+ def save_file_selection(theme, enabled):
332
+ man = load_manifest(theme)
333
+ for fname in man['files']: man['files'][fname] = fname in enabled
334
+ save_manifest(theme, man)
335
+ if theme in vectorstores: del vectorstores[theme]
336
+ return f"Settings saved for theme '{theme}'."
337
+ def refresh_file_list_ui(theme):
338
+ files = list_theme_files(theme)
339
+ return gr.update(choices=[f for f, _ in files], value=[f for f, en in files if en]), f"Found {len(files)} file(s)."
340
+ def auto_setup_on_load(theme):
341
+ if not os.listdir(theme_upload_dir(theme)): seed_files_into_theme(theme)
342
+ settings = collect_settings("caregiver", "", "", "warm", "English", "English", 0.7, "None", "None", "None", "All", True, False)
343
+ files_ui, status = refresh_file_list_ui(theme)
344
+ return settings, files_ui, status
345
+ def run_nlu_test(test_title: str):
346
+ if not test_title or not test_fixtures: return "Please select a test case.", None
347
+ fixture = next((f for f in test_fixtures if f["title"] == test_title), None)
348
+ if not fixture: return f"Error: Could not find test case '{test_title}'.", None
349
+ actual_raw = detect_tags_from_query(
350
+ fixture["turns"][0]["text"], nlu_vectorstore, CONFIG["behavior_tags"], CONFIG["emotion_tags"], CONFIG["topic_tags"], CONFIG["context_tags"]
351
+ )
352
+ actual = {"emotion": [actual_raw.get("detected_emotion")], "behaviors": actual_raw.get("detected_behaviors", []), "topic_tags": [actual_raw.get("detected_topic")], "context_tags": actual_raw.get("detected_contexts", [])}
353
+ pass_count, total_count, data = 0, 0, []
354
+ expected = fixture["expected"]
355
+ all_keys = set(expected.keys()) | set(actual.keys())
356
+ for key in sorted(list(all_keys)):
357
+ expected_set = set(expected.get(key, []))
358
+ if not expected_set: continue
359
+ total_count += 1
360
+ actual_set = set(a for a in actual.get(key, []) if a and a != "None")
361
+ is_pass = len(expected_set.intersection(actual_set)) > 0
362
+ if is_pass: pass_count += 1
363
+ data.append([key, ", ".join(sorted(list(expected_set))), ", ".join(sorted(list(actual_set))) or "None", "βœ… Pass" if is_pass else "❌ Fail"])
364
+ return f"## Test Result: {pass_count} / {total_count} Passed", data
365
+ def load_test_fixtures():
366
+ global test_fixtures
367
+ test_fixtures = []
368
+ fixtures_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "conversation_test_fixtures.jsonl")
369
+ if not os.path.exists(fixtures_path): return gr.update(choices=[])
370
+ with open(fixtures_path, "r", encoding="utf-8") as f:
371
+ for line in f: test_fixtures.append(json.loads(line))
372
+ return gr.update(choices=[f["title"] for f in test_fixtures])
373
+ def run_all_nlu_tests():
374
+ if not test_fixtures: load_test_fixtures()
375
+ if not test_fixtures: return "## No test fixtures found.", []
376
+ passed_tests, all_results = 0, []
377
+ for fixture in test_fixtures:
378
+ user_query = fixture["turns"][0]["text"]
379
+ expected_results = fixture["expected"]
380
+ actual_results_raw = detect_tags_from_query(user_query, nlu_vectorstore, CONFIG["behavior_tags"], CONFIG["emotion_tags"], CONFIG["topic_tags"], CONFIG["context_tags"])
381
+ actual_results = {"emotion": [actual_results_raw.get("detected_emotion")], "behaviors": actual_results_raw.get("detected_behaviors", []), "topic_tags": [actual_results_raw.get("detected_topic")], "context_tags": actual_results_raw.get("detected_contexts", [])}
382
+ pass_count, total_count = 0, 0
383
+ for key in sorted(list(expected_results.keys())):
384
+ expected_set = set(expected_results.get(key, []))
385
+ if not expected_set: continue
386
+ total_count += 1
387
+ actual_set = set(a for a in actual_results.get(key, []) if a and a != "None")
388
+ if len(expected_set.intersection(actual_set)) > 0: pass_count += 1
389
+ overall_result = "❌ Fail"
390
+ if total_count > 0:
391
+ pass_ratio = pass_count / total_count
392
+ if pass_ratio == 1.0: passed_tests += 1; overall_result = "βœ… Pass"
393
+ elif pass_ratio > 0.65: overall_result = "⚠️ Partial"
394
+ all_results.append([fixture["title"], overall_result, f"{pass_count} / {total_count}"])
395
+ pass_rate = (passed_tests / len(test_fixtures)) * 100 if test_fixtures else 0
396
+ return f"## Batch Summary: {passed_tests} / {len(test_fixtures)} Tests Passed ({pass_rate:.1f}%)", all_results
397
+ def test_save_file():
398
+ try:
399
+ path = PERSONAL_DATA_BASE / "persistence_test.txt"
400
+ path.write_text(f"File saved at: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
401
+ return f"βœ… Success! Wrote test file to: {path}"
402
+ except Exception as e: return f"❌ Error! Failed to write file: {e}"
403
+ def check_test_file():
404
+ path = PERSONAL_DATA_BASE / "persistence_test.txt"
405
+ if path.exists(): return f"βœ… Success! Found test file. Contents: '{path.read_text()}'"
406
+ return f"❌ Failure. Test file not found at: {path}"
407
+
408
+ # --- UI Definition ---
409
+ CSS = ".gradio-container { font-size: 14px; } #chatbot { min-height: 400px; } #audio_out audio { max-height: 40px; } #audio_in audio { max-height: 40px; padding: 0; }"
410
+ with gr.Blocks(theme=gr.themes.Soft(), css=CSS) as demo:
411
+ settings_state = gr.State({})
412
+ with gr.Tab("Chat"):
413
+ # --- NEW CHAT LAYOUT ---
414
+ user_text = gr.Textbox(show_label=False, placeholder="Type your message here...")
415
+ audio_in = gr.Audio(sources=["microphone"], type="filepath", label="Voice Input", elem_id="audio_in")
416
+ with gr.Row():
417
+ submit_btn = gr.Button("Send", variant="primary")
418
+ clear_btn = gr.Button("Clear")
419
+ save_btn = gr.Button("Save to Memory")
420
+ audio_out = gr.Audio(label="Response Audio", autoplay=True, visible=True, elem_id="audio_out")
421
+ chatbot = gr.Chatbot(elem_id="chatbot", label="Conversation", type="messages")
422
+ chat_status = gr.Markdown() # Moved status here, can be updated by save button
423
+
424
+ with gr.Tab("Personalize"):
425
+ with gr.Accordion("Add to Personal Knowledge Base", open=True):
426
+ personal_title = gr.Textbox(label="Title")
427
+ personal_text = gr.Textbox(lines=5, label="Text Content")
428
+ with gr.Row():
429
+ personal_file = gr.File(label="Upload Audio/Video/Text File")
430
+ personal_image = gr.Image(type="filepath", label="Upload Image")
431
+ personal_yt_url = gr.Textbox(label="Or, provide a YouTube URL")
432
+ personal_add_btn = gr.Button("Add Knowledge", variant="primary")
433
+ personal_status = gr.Markdown()
434
+ with gr.Accordion("Manage Personal Knowledge", open=False):
435
+ personal_memory_display = gr.DataFrame(headers=["Title", "Source", "Content"], label="Saved Memories", row_count=(5, "dynamic"))
436
+ personal_refresh_btn = gr.Button("Refresh Memories")
437
+ personal_delete_selector = gr.Dropdown(label="Select memory to delete", scale=3, interactive=True)
438
+ personal_delete_btn = gr.Button("Delete Selected", variant="stop", scale=1)
439
+ personal_delete_status = gr.Markdown()
440
+
441
+ with gr.Tab("Testing"):
442
+ gr.Markdown("## NLU Context Detection Tests")
443
+ batch_summary_md = gr.Markdown("### Batch Test Summary: Not yet run.")
444
+ with gr.Row():
445
+ test_case_dropdown = gr.Dropdown(label="Select Single Test Case", scale=2)
446
+ run_test_btn = gr.Button("Run Single Test", scale=1)
447
+ run_all_btn = gr.Button("Run All Tests", variant="primary", scale=1)
448
+ test_status_md = gr.Markdown("### Test Results")
449
+ test_results_df = gr.DataFrame(label="Test Comparison", headers=["Test Case Title", "Result", "Categories Passed"], interactive=False)
450
+
451
+ with gr.Tab("Settings"):
452
+ with gr.Group():
453
+ gr.Markdown("## Conversation & Persona Settings")
454
+ with gr.Row():
455
+ role = gr.Radio(CONFIG["roles"], value="caregiver", label="Your Role")
456
+ patient_name = gr.Textbox(label="Patient's Name")
457
+ caregiver_name = gr.Textbox(label="Caregiver's Name")
458
+ with gr.Row():
459
+ temperature = gr.Slider(0.0, 1.2, value=0.7, step=0.1, label="Creativity")
460
+ tone = gr.Dropdown(CONFIG["tones"], value="warm", label="Response Tone")
461
+ with gr.Row():
462
+ behaviour_tag = gr.Dropdown(CONFIG["behavior_tags"], value="None", label="Behaviour Filter (Manual)")
463
+ emotion_tag = gr.Dropdown(CONFIG["emotion_tags"], value="None", label="Emotion Filter (Manual)")
464
+ topic_tag = gr.Dropdown(CONFIG["topic_tags"], value="None", label="Topic Tag Filter (Manual)")
465
+ with gr.Accordion("Language, Voice & Debugging", open=False):
466
+ language = gr.Dropdown(list(CONFIG["languages"].keys()), value="English", label="Response Language")
467
+ tts_lang = gr.Dropdown(list(CONFIG["languages"].keys()), value="English", label="Voice Language")
468
+ tts_on = gr.Checkbox(True, label="Enable Voice Response")
469
+ debug_mode = gr.Checkbox(False, label="Show Debug Info")
470
+ gr.Markdown("--- \n ## General Knowledge Base Management")
471
+ with gr.Row():
472
+ with gr.Column(scale=1):
473
+ files_in = gr.File(file_count="multiple", file_types=[".jsonl", ".txt"], label="Upload Knowledge Files")
474
+ upload_btn = gr.Button("Upload to Theme")
475
+ seed_btn = gr.Button("Import Sample Data")
476
+ mgmt_status = gr.Markdown()
477
+ with gr.Column(scale=2):
478
+ active_theme = gr.Radio(CONFIG["themes"], value="All", label="Active Knowledge Theme")
479
+ files_box = gr.CheckboxGroup(choices=[], label="Enable Files for Selected Theme")
480
+ with gr.Row():
481
+ save_files_btn = gr.Button("Save Selection", variant="primary")
482
+ refresh_btn = gr.Button("Refresh List")
483
+ with gr.Accordion("Persistence Test", open=False):
484
+ test_save_btn = gr.Button("1. Run Persistence Test (Save File)")
485
+ check_save_btn = gr.Button("3. Check for Test File")
486
+ test_status = gr.Markdown()
487
+
488
+ # --- Event Wiring ---
489
+ all_settings = [role, patient_name, caregiver_name, tone, language, tts_lang, temperature, behaviour_tag, emotion_tag, topic_tag, active_theme, tts_on, debug_mode]
490
+ for c in all_settings: c.change(fn=collect_settings, inputs=all_settings, outputs=settings_state)
491
+ submit_btn.click(fn=chat_fn, inputs=[user_text, audio_in, settings_state, chatbot], outputs=[user_text, audio_out, chatbot])
492
+ save_btn.click(fn=save_chat_to_memory, inputs=[chatbot], outputs=[chat_status])
493
+ clear_btn.click(lambda: (None, None, [], None, "", ""), outputs=[user_text, audio_out, chatbot, audio_in, user_text, chat_status])
494
+ personal_add_btn.click(fn=handle_add_knowledge, inputs=[personal_title, personal_text, personal_file, personal_image, personal_yt_url, settings_state], outputs=[personal_status]).then(lambda: (None, None, None, None, None), outputs=[personal_title, personal_text, personal_file, personal_image, personal_yt_url])
495
+ personal_refresh_btn.click(fn=list_personal_memories, inputs=None, outputs=[personal_memory_display, personal_delete_selector])
496
+ personal_delete_btn.click(fn=delete_personal_memory, inputs=[personal_delete_selector], outputs=[personal_delete_status]).then(fn=list_personal_memories, inputs=None, outputs=[personal_memory_display, personal_delete_selector])
497
+ upload_btn.click(upload_knowledge, inputs=[files_in, active_theme], outputs=[mgmt_status]).then(refresh_file_list_ui, inputs=[active_theme], outputs=[files_box, mgmt_status])
498
+ save_files_btn.click(save_file_selection, inputs=[active_theme, files_box], outputs=[mgmt_status])
499
+ seed_btn.click(seed_files_into_theme, inputs=[active_theme]).then(refresh_file_list_ui, inputs=[active_theme], outputs=[files_box, mgmt_status])
500
+ refresh_btn.click(refresh_file_list_ui, inputs=[active_theme], outputs=[files_box, mgmt_status])
501
+ active_theme.change(refresh_file_list_ui, inputs=[active_theme], outputs=[files_box, mgmt_status])
502
+ demo.load(auto_setup_on_load, inputs=[active_theme], outputs=[settings_state, files_box, mgmt_status])
503
+ demo.load(load_test_fixtures, outputs=[test_case_dropdown])
504
+ run_test_btn.click(fn=run_nlu_test, inputs=[test_case_dropdown], outputs=[test_status_md, test_results_df])
505
+ run_all_btn.click(fn=run_all_nlu_tests, outputs=[batch_summary_md, test_results_df])
506
+ test_save_btn.click(fn=test_save_file, inputs=None, outputs=[test_status])
507
+ check_save_btn.click(fn=check_test_file, inputs=None, outputs=[test_status])
508
+
509
+ # --- Startup Logic ---
510
+ def pre_load_indexes():
511
+ global personal_vectorstore, nlu_vectorstore
512
+ print("Pre-loading all indexes at startup...")
513
+ print(" - Loading NLU examples index...")
514
+ nlu_vectorstore = bootstrap_nlu_vectorstore("nlu_training_examples.jsonl", NLU_EXAMPLES_INDEX_PATH)
515
+ print(f" ...NLU index loaded.")
516
+ for theme in CONFIG["themes"]:
517
+ print(f" - Loading general index for theme: '{theme}'")
518
+ try:
519
+ ensure_index(theme)
520
+ print(f" ...'{theme}' theme loaded.")
521
+ except Exception as e:
522
+ print(f" ...Error loading theme '{theme}': {e}")
523
+ print(" - Loading personal knowledge index...")
524
+ try:
525
+ personal_vectorstore = build_or_load_vectorstore([], PERSONAL_INDEX_PATH, is_personal=True)
526
+ print(" ...Personal knowledge loaded.")
527
+ except Exception as e:
528
+ print(f" ...Error loading personal knowledge: {e}")
529
+ print("All indexes loaded. Application is ready.")
530
+
531
+ if __name__ == "__main__":
532
+ seed_files_into_theme('All')
533
+ pre_load_indexes()
534
+ demo.queue().launch(debug=True)