KeenWoo commited on
Commit
f4693d8
·
verified ·
1 Parent(s): 0ac4f3d

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -518
app.py DELETED
@@ -1,518 +0,0 @@
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
- question = (user_text or "").strip()
225
- if audio_file and not question:
226
- try:
227
- question = transcribe_audio(audio_file, lang=CONFIG["languages"].get(settings.get("tts_lang", "English"), "en"))
228
- except Exception as e:
229
- err_msg = f"Audio Error: {e}" if settings.get("debug_mode") else "Sorry, I couldn't understand the audio."
230
- chat_history.append({"role": "assistant", "content": err_msg})
231
- return "", None, chat_history
232
- if not question:
233
- return "", None, chat_history
234
- chat_history.append({"role": "user", "content": question})
235
- final_tags = { "scenario_tag": None, "emotion_tag": None, "topic_tag": None, "context_tags": [] }
236
- manual_behavior = settings.get("behaviour_tag", "None")
237
- manual_emotion = settings.get("emotion_tag", "None")
238
- manual_topic = settings.get("topic_tag", "None")
239
- if all(m == "None" for m in [manual_behavior, manual_emotion, manual_topic]):
240
- detected_tags = detect_tags_from_query(
241
- question, nlu_vectorstore=nlu_vectorstore, behavior_options=CONFIG["behavior_tags"],
242
- emotion_options=CONFIG["emotion_tags"], topic_options=CONFIG["topic_tags"],
243
- context_options=CONFIG["context_tags"], settings=settings)
244
- final_tags["scenario_tag"] = detected_tags.get("detected_behaviors", [None])[0]
245
- final_tags["emotion_tag"] = detected_tags.get("detected_emotion")
246
- final_tags["topic_tag"] = detected_tags.get("detected_topic")
247
- final_tags["context_tags"] = detected_tags.get("detected_contexts", [])
248
- detected_parts = [f"{k.split('_')[1]}=`{v}`" for k, v in final_tags.items() if v and v != "None"]
249
- if detected_parts:
250
- chat_history.append({"role": "assistant", "content": f"*(Auto-detected context: {', '.join(detected_parts)})*"})
251
- else:
252
- final_tags["scenario_tag"] = manual_behavior if manual_behavior != "None" else None
253
- final_tags["emotion_tag"] = manual_emotion if manual_emotion != "None" else None
254
- final_tags["topic_tag"] = manual_topic if manual_topic != "None" else None
255
- vs_general = ensure_index(settings.get("active_theme", "All"))
256
- if personal_vectorstore is None:
257
- personal_vectorstore = build_or_load_vectorstore([], PERSONAL_INDEX_PATH, is_personal=True)
258
- rag_settings = {k: settings.get(k) for k in ["role", "temperature", "language", "patient_name", "caregiver_name", "tone"]}
259
- chain = make_rag_chain(vs_general, personal_vectorstore, **rag_settings)
260
- response = answer_query(chain, question, chat_history=chat_history[:-1], **final_tags)
261
- answer = response.get("answer", "[No answer found]")
262
- chat_history.append({"role": "assistant", "content": answer})
263
- if response.get("sources"):
264
- chat_history.append({"role": "assistant", "content": f"*(Sources used: {', '.join(response['sources'])})*"})
265
- audio_out = None
266
- if settings.get("tts_on") and answer:
267
- audio_out = synthesize_tts(answer, lang=CONFIG["languages"].get(settings.get("tts_lang"), "en"))
268
- return "", gr.update(value=audio_out, visible=bool(audio_out)), chat_history
269
-
270
- def save_chat_to_memory(chat_history):
271
- global personal_vectorstore
272
- if not chat_history: return "Nothing to save."
273
- formatted_chat = [f"{m['role'].title()}: {m['content'].strip()}" for m in chat_history if not m['content'].strip().startswith("*(")]
274
- if not formatted_chat: return "No conversation to save."
275
- timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
276
- title = f"Conversation from {timestamp}"
277
- full_content = f"Title: {title}\n\nContent:\n" + "\n".join(formatted_chat)
278
- doc = Document(page_content=full_content, metadata={"source": "Saved Chat", "title": title})
279
- if personal_vectorstore is None:
280
- personal_vectorstore = build_or_load_vectorstore([doc], PERSONAL_INDEX_PATH, is_personal=True)
281
- else:
282
- personal_vectorstore.add_documents([doc])
283
- personal_vectorstore.save_local(PERSONAL_INDEX_PATH)
284
- return f"Conversation from {timestamp} saved."
285
- def list_personal_memories():
286
- global personal_vectorstore
287
- if personal_vectorstore is None or not hasattr(personal_vectorstore.docstore, '_dict') or not personal_vectorstore.docstore._dict:
288
- return gr.update(value=[["No memories", "", ""]]), gr.update(choices=[], value=None)
289
- docs = list(personal_vectorstore.docstore._dict.values())
290
- 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])
291
- def delete_personal_memory(memory_to_delete):
292
- global personal_vectorstore
293
- if personal_vectorstore is None or not memory_to_delete: return "No memory selected."
294
- all_docs = list(personal_vectorstore.docstore._dict.values())
295
- docs_to_keep = [d for d in all_docs if d.page_content != memory_to_delete]
296
- if len(all_docs) == len(docs_to_keep): return "Error: Could not find memory."
297
- if not docs_to_keep:
298
- if os.path.isdir(PERSONAL_INDEX_PATH): shutil.rmtree(PERSONAL_INDEX_PATH)
299
- personal_vectorstore = build_or_load_vectorstore([], PERSONAL_INDEX_PATH, is_personal=True)
300
- else:
301
- new_vs = FAISS.from_documents(docs_to_keep, _default_embeddings())
302
- new_vs.save_local(PERSONAL_INDEX_PATH)
303
- personal_vectorstore = new_vs
304
- return "Successfully deleted memory."
305
- def upload_knowledge(files, theme):
306
- for f in files: copy_into_theme(theme, f.name)
307
- if theme in vectorstores: del vectorstores[theme]
308
- return f"Uploaded {len(files)} file(s)."
309
- def save_file_selection(theme, enabled):
310
- man = load_manifest(theme)
311
- for fname in man['files']: man['files'][fname] = fname in enabled
312
- save_manifest(theme, man)
313
- if theme in vectorstores: del vectorstores[theme]
314
- return f"Settings saved for theme '{theme}'."
315
- def refresh_file_list_ui(theme):
316
- files = list_theme_files(theme)
317
- return gr.update(choices=[f for f, _ in files], value=[f for f, en in files if en]), f"Found {len(files)} file(s)."
318
- def auto_setup_on_load(theme):
319
- if not os.listdir(theme_upload_dir(theme)): seed_files_into_theme(theme)
320
- settings = collect_settings("caregiver", "", "", "warm", "English", "English", 0.7, "None", "None", "None", "All", True, False)
321
- files_ui, status = refresh_file_list_ui(theme)
322
- return settings, files_ui, status
323
- def run_nlu_test(test_title: str):
324
- if not test_title or not test_fixtures: return "Please select a test case.", None
325
- fixture = next((f for f in test_fixtures if f["title"] == test_title), None)
326
- if not fixture: return f"Error: Could not find test case '{test_title}'.", None
327
- actual_raw = detect_tags_from_query(
328
- fixture["turns"][0]["text"], nlu_vectorstore, CONFIG["behavior_tags"], CONFIG["emotion_tags"], CONFIG["topic_tags"], CONFIG["context_tags"]
329
- )
330
- 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", [])}
331
- pass_count, total_count, data = 0, 0, []
332
- expected = fixture["expected"]
333
- all_keys = set(expected.keys()) | set(actual.keys())
334
- for key in sorted(list(all_keys)):
335
- expected_set = set(expected.get(key, []))
336
- if not expected_set: continue
337
- total_count += 1
338
- actual_set = set(a for a in actual.get(key, []) if a and a != "None")
339
- is_pass = len(expected_set.intersection(actual_set)) > 0
340
- if is_pass: pass_count += 1
341
- data.append([key, ", ".join(sorted(list(expected_set))), ", ".join(sorted(list(actual_set))) or "None", "✅ Pass" if is_pass else "❌ Fail"])
342
- return f"## Test Result: {pass_count} / {total_count} Passed", data
343
- def load_test_fixtures():
344
- global test_fixtures
345
- test_fixtures = []
346
- fixtures_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "conversation_test_fixtures.jsonl")
347
- if not os.path.exists(fixtures_path): return gr.update(choices=[])
348
- with open(fixtures_path, "r", encoding="utf-8") as f:
349
- for line in f: test_fixtures.append(json.loads(line))
350
- return gr.update(choices=[f["title"] for f in test_fixtures])
351
- def run_all_nlu_tests():
352
- if not test_fixtures: load_test_fixtures()
353
- if not test_fixtures: return "## No test fixtures found.", []
354
- passed_tests, all_results = 0, []
355
- for fixture in test_fixtures:
356
- user_query = fixture["turns"][0]["text"]
357
- expected_results = fixture["expected"]
358
- actual_results_raw = detect_tags_from_query(user_query, nlu_vectorstore, CONFIG["behavior_tags"], CONFIG["emotion_tags"], CONFIG["topic_tags"], CONFIG["context_tags"])
359
- 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", [])}
360
- pass_count, total_count = 0, 0
361
- for key in sorted(list(expected_results.keys())):
362
- expected_set = set(expected_results.get(key, []))
363
- if not expected_set: continue
364
- total_count += 1
365
- actual_set = set(a for a in actual_results.get(key, []) if a and a != "None")
366
- if len(expected_set.intersection(actual_set)) > 0: pass_count += 1
367
- overall_result = "❌ Fail"
368
- if total_count > 0:
369
- pass_ratio = pass_count / total_count
370
- if pass_ratio == 1.0: passed_tests += 1; overall_result = "✅ Pass"
371
- elif pass_ratio > 0.65: overall_result = "⚠️ Partial"
372
- all_results.append([fixture["title"], overall_result, f"{pass_count} / {total_count}"])
373
- pass_rate = (passed_tests / len(test_fixtures)) * 100 if test_fixtures else 0
374
- return f"## Batch Summary: {passed_tests} / {len(test_fixtures)} Tests Passed ({pass_rate:.1f}%)", all_results
375
- def test_save_file():
376
- try:
377
- path = PERSONAL_DATA_BASE / "persistence_test.txt"
378
- path.write_text(f"File saved at: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
379
- return f"✅ Success! Wrote test file to: {path}"
380
- except Exception as e: return f"❌ Error! Failed to write file: {e}"
381
- def check_test_file():
382
- path = PERSONAL_DATA_BASE / "persistence_test.txt"
383
- if path.exists(): return f"✅ Success! Found test file. Contents: '{path.read_text()}'"
384
- return f"❌ Failure. Test file not found at: {path}"
385
-
386
- # --- UI Definition ---
387
- CSS = ".gradio-container { font-size: 14px; } #chatbot { min-height: 250px; } #audio_out audio { max-height: 40px; } #audio_in audio { max-height: 40px; padding: 0; }"
388
- with gr.Blocks(theme=gr.themes.Soft(), css=CSS) as demo:
389
- settings_state = gr.State({})
390
- with gr.Tab("Chat"):
391
- chatbot = gr.Chatbot(elem_id="chatbot", label="Conversation", type="messages")
392
- audio_out = gr.Audio(label="Response Audio", autoplay=True, visible=True, elem_id="audio_out")
393
- chat_status = gr.Markdown()
394
- with gr.Row():
395
- user_text = gr.Textbox(show_label=False, placeholder="Type your message here...", scale=7)
396
- submit_btn = gr.Button("Send", variant="primary", scale=1)
397
- with gr.Row():
398
- audio_in = gr.Audio(sources=["microphone"], type="filepath", label="Voice Input", elem_id="audio_in")
399
- save_btn = gr.Button("Save to Memory")
400
- clear_btn = gr.Button("Clear")
401
-
402
- with gr.Tab("Personalize"):
403
- with gr.Accordion("Add to Personal Knowledge Base", open=True):
404
- personal_title = gr.Textbox(label="Title")
405
- personal_text = gr.Textbox(lines=5, label="Text Content")
406
- with gr.Row():
407
- personal_file = gr.File(label="Upload Audio/Video/Text File")
408
- personal_image = gr.Image(type="filepath", label="Upload Image")
409
- personal_yt_url = gr.Textbox(label="Or, provide a YouTube URL")
410
- personal_add_btn = gr.Button("Add Knowledge", variant="primary")
411
- personal_status = gr.Markdown()
412
- with gr.Accordion("Manage Personal Knowledge", open=False):
413
- personal_memory_display = gr.DataFrame(headers=["Title", "Source", "Content"], label="Saved Memories", row_count=(5, "dynamic"))
414
- personal_refresh_btn = gr.Button("Refresh Memories")
415
- personal_delete_selector = gr.Dropdown(label="Select memory to delete", scale=3, interactive=True)
416
- personal_delete_btn = gr.Button("Delete Selected", variant="stop", scale=1)
417
- personal_delete_status = gr.Markdown()
418
-
419
- with gr.Tab("Testing"):
420
- gr.Markdown("## NLU Context Detection Tests")
421
- batch_summary_md = gr.Markdown("### Batch Test Summary: Not yet run.")
422
- with gr.Row():
423
- test_case_dropdown = gr.Dropdown(label="Select Single Test Case", scale=2)
424
- run_test_btn = gr.Button("Run Single Test", scale=1)
425
- run_all_btn = gr.Button("Run All Tests", variant="primary", scale=1)
426
- test_status_md = gr.Markdown("### Test Results")
427
- test_results_df = gr.DataFrame(label="Test Comparison", headers=["Test Case Title", "Result", "Categories Passed"], interactive=False)
428
-
429
- with gr.Tab("Settings"):
430
- with gr.Group():
431
- gr.Markdown("## Conversation & Persona Settings")
432
- with gr.Row():
433
- role = gr.Radio(CONFIG["roles"], value="caregiver", label="Your Role")
434
- patient_name = gr.Textbox(label="Patient's Name")
435
- caregiver_name = gr.Textbox(label="Caregiver's Name")
436
- with gr.Row():
437
- temperature = gr.Slider(0.0, 1.2, value=0.7, step=0.1, label="Creativity")
438
- tone = gr.Dropdown(CONFIG["tones"], value="warm", label="Response Tone")
439
- with gr.Row():
440
- behaviour_tag = gr.Dropdown(CONFIG["behavior_tags"], value="None", label="Behaviour Filter (Manual)")
441
- emotion_tag = gr.Dropdown(CONFIG["emotion_tags"], value="None", label="Emotion Filter (Manual)")
442
- topic_tag = gr.Dropdown(CONFIG["topic_tags"], value="None", label="Topic Tag Filter (Manual)")
443
-
444
- with gr.Accordion("Language, Voice & Debugging", open=False):
445
- language = gr.Dropdown(list(CONFIG["languages"].keys()), value="English", label="Response Language")
446
- tts_lang = gr.Dropdown(list(CONFIG["languages"].keys()), value="English", label="Voice Language")
447
- tts_on = gr.Checkbox(True, label="Enable Voice Response")
448
- debug_mode = gr.Checkbox(False, label="Show Debug Info")
449
-
450
- gr.Markdown("--- \n ## General Knowledge Base Management")
451
- with gr.Row():
452
- with gr.Column(scale=1):
453
- files_in = gr.File(file_count="multiple", file_types=[".jsonl", ".txt"], label="Upload Knowledge Files")
454
- upload_btn = gr.Button("Upload to Theme")
455
- seed_btn = gr.Button("Import Sample Data")
456
- mgmt_status = gr.Markdown()
457
- with gr.Column(scale=2):
458
- active_theme = gr.Radio(CONFIG["themes"], value="All", label="Active Knowledge Theme")
459
- files_box = gr.CheckboxGroup(choices=[], label="Enable Files for Selected Theme")
460
- with gr.Row():
461
- save_files_btn = gr.Button("Save Selection", variant="primary")
462
- refresh_btn = gr.Button("Refresh List")
463
-
464
- with gr.Accordion("Persistence Test", open=False):
465
- test_save_btn = gr.Button("1. Run Persistence Test (Save File)")
466
- check_save_btn = gr.Button("3. Check for Test File")
467
- test_status = gr.Markdown()
468
-
469
- # --- Event Wiring ---
470
- all_settings = [role, patient_name, caregiver_name, tone, language, tts_lang, temperature, behaviour_tag, emotion_tag, topic_tag, active_theme, tts_on, debug_mode]
471
- for c in all_settings: c.change(fn=collect_settings, inputs=all_settings, outputs=settings_state)
472
- submit_btn.click(fn=chat_fn, inputs=[user_text, audio_in, settings_state, chatbot], outputs=[user_text, audio_out, chatbot])
473
- save_btn.click(fn=save_chat_to_memory, inputs=[chatbot], outputs=[chat_status])
474
- clear_btn.click(lambda: (None, None, [], None, "", ""), outputs=[user_text, audio_out, chatbot, audio_in, user_text, chat_status])
475
- 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])
476
- personal_refresh_btn.click(fn=list_personal_memories, inputs=None, outputs=[personal_memory_display, personal_delete_selector])
477
- 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])
478
- 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])
479
- save_files_btn.click(save_file_selection, inputs=[active_theme, files_box], outputs=[mgmt_status])
480
- seed_btn.click(seed_files_into_theme, inputs=[active_theme]).then(refresh_file_list_ui, inputs=[active_theme], outputs=[files_box, mgmt_status])
481
- refresh_btn.click(refresh_file_list_ui, inputs=[active_theme], outputs=[files_box, mgmt_status])
482
- active_theme.change(refresh_file_list_ui, inputs=[active_theme], outputs=[files_box, mgmt_status])
483
- demo.load(auto_setup_on_load, inputs=[active_theme], outputs=[settings_state, files_box, mgmt_status])
484
- demo.load(load_test_fixtures, outputs=[test_case_dropdown])
485
- run_test_btn.click(fn=run_nlu_test, inputs=[test_case_dropdown], outputs=[test_status_md, test_results_df])
486
- run_all_btn.click(fn=run_all_nlu_tests, outputs=[batch_summary_md, test_results_df])
487
- test_save_btn.click(fn=test_save_file, inputs=None, outputs=[test_status])
488
- check_save_btn.click(fn=check_test_file, inputs=None, outputs=[test_status])
489
-
490
- # --- Startup Logic ---
491
- def pre_load_indexes():
492
- global personal_vectorstore, nlu_vectorstore
493
- print("Pre-loading all indexes at startup...")
494
- # --- NEW: Load the NLU vector store ---
495
- print(" - Loading NLU examples index...")
496
- nlu_vectorstore = bootstrap_nlu_vectorstore("nlu_training_examples.jsonl", NLU_EXAMPLES_INDEX_PATH)
497
- print(f" ...NLU index loaded.")
498
-
499
- for theme in CONFIG["themes"]:
500
- print(f" - Loading general index for theme: '{theme}'")
501
- try:
502
- ensure_index(theme)
503
- print(f" ...'{theme}' theme loaded.")
504
- except Exception as e:
505
- print(f" ...Error loading theme '{theme}': {e}")
506
-
507
- print(" - Loading personal knowledge index...")
508
- try:
509
- personal_vectorstore = build_or_load_vectorstore([], PERSONAL_INDEX_PATH, is_personal=True)
510
- print(" ...Personal knowledge loaded.")
511
- except Exception as e:
512
- print(f" ...Error loading personal knowledge: {e}")
513
- print("All indexes loaded. Application is ready.")
514
-
515
- if __name__ == "__main__":
516
- seed_files_into_theme('All')
517
- pre_load_indexes()
518
- demo.queue().launch(debug=True)