KeenWoo commited on
Commit
4e8a55a
·
verified ·
1 Parent(s): 2ba4668

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +437 -0
app.py ADDED
@@ -0,0 +1,437 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
10
+ # --- Agent Imports & Safe Fallbacks ---
11
+ try:
12
+ from alz_companion.agent import (
13
+ bootstrap_vectorstore, make_rag_chain, answer_query, synthesize_tts,
14
+ transcribe_audio, detect_tags_from_query, describe_image, build_or_load_vectorstore,
15
+ _default_embeddings
16
+ )
17
+ from alz_companion.prompts import BEHAVIOUR_TAGS, EMOTION_STYLES
18
+ from langchain.schema import Document
19
+ from langchain_community.vectorstores import FAISS
20
+ AGENT_OK = True
21
+ except Exception as e:
22
+ AGENT_OK = False
23
+ # Define all fallback functions and classes
24
+ def bootstrap_vectorstore(sample_paths=None, index_path="data/"): return object()
25
+ def build_or_load_vectorstore(docs, index_path, is_personal=False): return object()
26
+ def make_rag_chain(vs_general, vs_personal, **kwargs): return lambda q, **k: {"answer": f"(Demo) You asked: {q}", "sources": []}
27
+ def answer_query(chain, q, **kwargs): return chain(q, **kwargs)
28
+ def synthesize_tts(text: str, lang: str = "en"): return None
29
+ def transcribe_audio(filepath: str, lang: str = "en"): return "This is a transcribed message."
30
+ def detect_tags_from_query(query: str, behavior_options: list, emotion_options: list): return {"detected_behavior": "None", "detected_emotion": "None"}
31
+ def describe_image(image_path: str): return "This is a description of an image."
32
+ def _default_embeddings(): return None
33
+ class Document:
34
+ def __init__(self, page_content, metadata):
35
+ self.page_content = page_content
36
+ self.metadata = metadata
37
+ class FAISS:
38
+ def __init__(self):
39
+ self.docstore = type('obj', (object,), {'_dict': {}})()
40
+ BEHAVIOUR_TAGS = {"None": []}
41
+ EMOTION_STYLES = {"None": {}}
42
+ print(f"WARNING: Could not import from alz_companion ({e}). Running in UI-only demo mode.")
43
+
44
+ # --- Centralized Configuration ---
45
+ CONFIG = {
46
+ "themes": ["All", "The Father", "Still Alice", "Away from Her", "General Caregiving"],
47
+ "roles": ["patient", "caregiver"],
48
+ "behavior_tags": ["None"] + list(BEHAVIOUR_TAGS.keys()),
49
+ "emotion_tags": ["None"] + list(EMOTION_STYLES.keys()),
50
+ "languages": {"English": "en", "Chinese": "zh", "Malay": "ms", "French": "fr", "Spanish": "es"},
51
+ "tones": ["warm", "neutral", "formal", "playful"]
52
+ }
53
+
54
+ # --- File Management & Vector Store Logic ---
55
+ INDEX_BASE = os.getenv('INDEX_BASE', 'data')
56
+ UPLOADS_BASE = os.path.join(INDEX_BASE, "uploads")
57
+ PERSONAL_INDEX_PATH = os.path.join(INDEX_BASE, "personal_faiss_index")
58
+ os.makedirs(UPLOADS_BASE, exist_ok=True)
59
+ THEME_PATHS = {t: os.path.join(INDEX_BASE, f"faiss_index_{t.replace(' ', '').lower()}") for t in CONFIG["themes"]}
60
+ vectorstores = {}
61
+ personal_vectorstore = None
62
+
63
+ def canonical_theme(tk: str) -> str: return tk if tk in CONFIG["themes"] else "All"
64
+ def theme_upload_dir(theme: str) -> str:
65
+ p = os.path.join(UPLOADS_BASE, f"theme_{canonical_theme(theme).replace(' ', '').lower()}")
66
+ os.makedirs(p, exist_ok=True)
67
+ return p
68
+ def load_manifest(theme: str) -> Dict[str, Any]:
69
+ p = os.path.join(theme_upload_dir(theme), "manifest.json")
70
+ if os.path.exists(p):
71
+ try:
72
+ with open(p, "r", encoding="utf-8") as f: return json.load(f)
73
+ except Exception: pass
74
+ return {"files": {}}
75
+ def save_manifest(theme: str, man: Dict[str, Any]):
76
+ with open(os.path.join(theme_upload_dir(theme), "manifest.json"), "w", encoding="utf-8") as f: json.dump(man, f, indent=2)
77
+ def list_theme_files(theme: str) -> List[tuple[str, bool]]:
78
+ man = load_manifest(theme)
79
+ base = theme_upload_dir(theme)
80
+ found = [(n, bool(e)) for n, e in man.get("files", {}).items() if os.path.exists(os.path.join(base, n))]
81
+ existing = {n for n, e in found}
82
+ for name in sorted(os.listdir(base)):
83
+ if name not in existing and os.path.isfile(os.path.join(base, name)): found.append((name, False))
84
+ man["files"] = dict(found)
85
+ save_manifest(theme, man)
86
+ return found
87
+ def copy_into_theme(theme: str, src_path: str) -> str:
88
+ fname = os.path.basename(src_path)
89
+ dest = os.path.join(theme_upload_dir(theme), fname)
90
+ shutil.copy2(src_path, dest)
91
+ return dest
92
+ def seed_files_into_theme(theme: str):
93
+ SEED_FILES = [
94
+ ("sample_data/caregiving_tips.txt", True),
95
+ ("sample_data/the_father_segments_tagged_with_emotion_hybrid.jsonl", True),
96
+ ("sample_data/still_alice_segments_tagged_with_emotion_hybrid.jsonl", True),
97
+ ("sample_data/away_from_her_segments_tagged_with_emotion_hybrid.jsonl", True)
98
+ ]
99
+ man, changed = load_manifest(theme), False
100
+ for path, enable in SEED_FILES:
101
+ if not os.path.exists(path): continue
102
+ fname = os.path.basename(path)
103
+ if not os.path.exists(os.path.join(theme_upload_dir(theme), fname)):
104
+ copy_into_theme(theme, path)
105
+ man["files"][fname] = bool(enable)
106
+ changed = True
107
+ if changed: save_manifest(theme, man)
108
+
109
+ def ensure_index(theme='All'):
110
+ theme = canonical_theme(theme)
111
+ if theme in vectorstores: return vectorstores[theme]
112
+ upload_dir = theme_upload_dir(theme)
113
+ enabled_files = [os.path.join(upload_dir, n) for n, enabled in list_theme_files(theme) if enabled]
114
+ index_path = THEME_PATHS.get(theme)
115
+ vectorstores[theme] = bootstrap_vectorstore(sample_paths=enabled_files, index_path=index_path)
116
+ return vectorstores[theme]
117
+
118
+ # --- Gradio Callbacks ---
119
+ def collect_settings(*args):
120
+ keys = ["role", "patient_name", "caregiver_name", "tone", "language", "tts_lang", "temperature", "behaviour_tag", "emotion_tag", "active_theme", "tts_on", "debug_mode"]
121
+ return dict(zip(keys, args))
122
+
123
+ def add_personal_knowledge(text_input, file_input, image_input):
124
+ global personal_vectorstore
125
+ if not any([text_input, file_input, image_input]):
126
+ return "Please provide text, a file, or an image to add."
127
+ content_text, content_source = "", ""
128
+ if text_input and text_input.strip():
129
+ content_text, content_source = text_input.strip(), "Text Input"
130
+ elif file_input:
131
+ content_text, content_source = transcribe_audio(file_input.name), os.path.basename(file_input.name)
132
+ elif image_input:
133
+ content_text, content_source = describe_image(image_input.name), "Image Input"
134
+ if not content_text:
135
+ return "Could not extract any text content to add."
136
+ print("Auto-tagging personal memory...")
137
+ behavior_options = CONFIG.get("behavior_tags", [])
138
+ emotion_options = CONFIG.get("emotion_tags", [])
139
+ detected_tags = detect_tags_from_query(content_text, behavior_options=behavior_options, emotion_options=emotion_options)
140
+ detected_behavior = detected_tags.get("detected_behavior")
141
+ detected_emotion = detected_tags.get("detected_emotion")
142
+ print(f" ...Detected Behavior: {detected_behavior}, Emotion: {detected_emotion}")
143
+ metadata = {"source": content_source}
144
+ if detected_behavior and detected_behavior != "None":
145
+ metadata["behaviors"] = [detected_behavior.lower()]
146
+ if detected_emotion and detected_emotion != "None":
147
+ metadata["emotion"] = detected_emotion.lower()
148
+ doc_to_add = Document(page_content=content_text, metadata=metadata)
149
+ if personal_vectorstore is None:
150
+ personal_vectorstore = build_or_load_vectorstore([doc_to_add], PERSONAL_INDEX_PATH, is_personal=True)
151
+ else:
152
+ personal_vectorstore.add_documents([doc_to_add])
153
+ personal_vectorstore.save_local(PERSONAL_INDEX_PATH)
154
+ return f"Successfully added memory with tags (Behavior: {detected_behavior}, Emotion: {detected_emotion})"
155
+
156
+ def add_youtube_knowledge(youtube_url):
157
+ global personal_vectorstore
158
+ if not youtube_url or not ("youtube.com" in youtube_url or "youtu.be" in youtube_url):
159
+ return "Please provide a valid YouTube URL."
160
+ try:
161
+ print(f"Downloading audio from YouTube URL: {youtube_url}")
162
+ yt = YouTube(youtube_url)
163
+ video_title = yt.title
164
+ audio_stream = yt.streams.get_audio_only()
165
+ with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as temp_audio_file:
166
+ audio_stream.download(filename=temp_audio_file.name)
167
+ temp_audio_path = temp_audio_file.name
168
+ print(f"Audio downloaded to temporary path: {temp_audio_path}")
169
+ content_text = transcribe_audio(temp_audio_path)
170
+ content_source = f"YouTube: {video_title}"
171
+ os.remove(temp_audio_path)
172
+ if not content_text:
173
+ return "Could not extract any spoken text from the YouTube video."
174
+ print("Auto-tagging personal memory from YouTube...")
175
+ behavior_options = CONFIG.get("behavior_tags", [])
176
+ emotion_options = CONFIG.get("emotion_tags", [])
177
+ detected_tags = detect_tags_from_query(content_text, behavior_options=behavior_options, emotion_options=emotion_options)
178
+ detected_behavior, detected_emotion = detected_tags.get("detected_behavior"), detected_tags.get("detected_emotion")
179
+ print(f" ...Detected Behavior: {detected_behavior}, Emotion: {detected_emotion}")
180
+ metadata = {"source": content_source}
181
+ if detected_behavior and detected_behavior != "None":
182
+ metadata["behaviors"] = [detected_behavior.lower()]
183
+ if detected_emotion and detected_emotion != "None":
184
+ metadata["emotion"] = detected_emotion.lower()
185
+ doc_to_add = Document(page_content=content_text, metadata=metadata)
186
+ if personal_vectorstore is None:
187
+ personal_vectorstore = build_or_load_vectorstore([doc_to_add], PERSONAL_INDEX_PATH, is_personal=True)
188
+ else:
189
+ personal_vectorstore.add_documents([doc_to_add])
190
+ personal_vectorstore.save_local(PERSONAL_INDEX_PATH)
191
+ return f"Successfully added memory from '{video_title}' with tags (Behavior: {detected_behavior}, Emotion: {detected_emotion})"
192
+ except Exception as e:
193
+ print(f"Error processing YouTube link: {e}")
194
+ return f"Error: Could not process the YouTube link. Details: {e}"
195
+
196
+ def save_chat_to_memory(chat_history):
197
+ global personal_vectorstore
198
+ if not chat_history:
199
+ return "Nothing to save."
200
+ formatted_chat = []
201
+ for message in chat_history:
202
+ role = "User" if message["role"] == "user" else "Assistant"
203
+ content = message["content"].strip()
204
+ if content.startswith("*(Auto-detected context:"):
205
+ continue
206
+ formatted_chat.append(f"{role}: {content}")
207
+ conversation_text = "\n".join(formatted_chat)
208
+ if not conversation_text:
209
+ return "No conversation content to save."
210
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
211
+ doc_to_add = Document(page_content=conversation_text, metadata={"source": f"Conversation saved on {timestamp}"})
212
+ if personal_vectorstore is None:
213
+ personal_vectorstore = build_or_load_vectorstore([doc_to_add], PERSONAL_INDEX_PATH, is_personal=True)
214
+ else:
215
+ personal_vectorstore.add_documents([doc_to_add])
216
+ personal_vectorstore.save_local(PERSONAL_INDEX_PATH)
217
+ print(f"Saved conversation to long-term memory.")
218
+ return f"Conversation from {timestamp} saved successfully to long-term memory!"
219
+
220
+ def list_personal_memories():
221
+ global personal_vectorstore
222
+ if personal_vectorstore is None or not hasattr(personal_vectorstore.docstore, '_dict') or not personal_vectorstore.docstore._dict:
223
+ return gr.update(value=[["No memories to display", ""]]), gr.update(choices=["No memories to select"], value=None)
224
+ docs = list(personal_vectorstore.docstore._dict.values())
225
+ dataframe_data = [[doc.metadata.get('source', 'Unknown'), doc.page_content] for doc in docs]
226
+ dropdown_choices = [doc.page_content for doc in docs]
227
+ return gr.update(value=dataframe_data), gr.update(choices=dropdown_choices)
228
+
229
+ def delete_personal_memory(memory_to_delete):
230
+ global personal_vectorstore
231
+ if personal_vectorstore is None or not memory_to_delete:
232
+ return "Knowledge base is empty or no memory selected."
233
+ all_docs = list(personal_vectorstore.docstore._dict.values())
234
+ docs_to_keep = [doc for doc in all_docs if doc.page_content != memory_to_delete]
235
+ if len(all_docs) == len(docs_to_keep):
236
+ return "Error: Could not find the selected memory to delete."
237
+ print(f"Deleting memory. {len(docs_to_keep)} memories remaining.")
238
+ if not docs_to_keep:
239
+ if os.path.isdir(PERSONAL_INDEX_PATH):
240
+ shutil.rmtree(PERSONAL_INDEX_PATH)
241
+ personal_vectorstore = build_or_load_vectorstore([], PERSONAL_INDEX_PATH, is_personal=True)
242
+ else:
243
+ new_vs = FAISS.from_documents(docs_to_keep, _default_embeddings())
244
+ new_vs.save_local(PERSONAL_INDEX_PATH)
245
+ personal_vectorstore = new_vs
246
+ return "Successfully deleted memory. The list will now refresh."
247
+
248
+ def chat_fn(user_text, audio_file, settings, chat_history):
249
+ global personal_vectorstore
250
+ question = (user_text or "").strip()
251
+ if audio_file and not question:
252
+ try:
253
+ voice_lang_name = settings.get("tts_lang", "English")
254
+ voice_lang_code = CONFIG["languages"].get(voice_lang_name, "en")
255
+ question = transcribe_audio(audio_file, lang=voice_lang_code)
256
+ except Exception as e:
257
+ err_msg = f"Audio Error: {e}" if settings.get("debug_mode") else "Sorry, I couldn't understand the audio."
258
+ chat_history.append({"role": "assistant", "content": err_msg})
259
+ return "", None, chat_history
260
+ if not question:
261
+ return "", None, chat_history
262
+ chat_history.append({"role": "user", "content": question})
263
+ manual_behavior_tag = settings.get("behaviour_tag")
264
+ manual_emotion_tag = settings.get("emotion_tag")
265
+ if manual_behavior_tag not in [None, "None"] or manual_emotion_tag not in [None, "None"]:
266
+ scenario_tag, emotion_tag = manual_behavior_tag, manual_emotion_tag
267
+ else:
268
+ behavior_options = CONFIG.get("behavior_tags", [])
269
+ emotion_options = CONFIG.get("emotion_tags", [])
270
+ detected_tags = detect_tags_from_query(question, behavior_options=behavior_options, emotion_options=emotion_options)
271
+ scenario_tag, emotion_tag = detected_tags.get("detected_behavior"), detected_tags.get("detected_emotion")
272
+ if (scenario_tag and scenario_tag != "None") or (emotion_tag and emotion_tag != "None"):
273
+ detected_msg = f"*(Auto-detected context: Behavior=`{scenario_tag}`, Emotion=`{emotion_tag}`)*"
274
+ chat_history.append({"role": "assistant", "content": detected_msg})
275
+ active_theme = settings.get("active_theme", "All")
276
+ vs_general = ensure_index(active_theme)
277
+ if personal_vectorstore is None:
278
+ personal_vectorstore = build_or_load_vectorstore([], PERSONAL_INDEX_PATH, is_personal=True)
279
+ rag_chain_settings = {"role": settings.get("role"), "temperature": settings.get("temperature"), "language": settings.get("language"), "patient_name": settings.get("patient_name"), "caregiver_name": settings.get("caregiver_name"), "tone": settings.get("tone"),}
280
+ chain = make_rag_chain(vs_general, personal_vectorstore, **rag_chain_settings)
281
+ if scenario_tag == "None": scenario_tag = None
282
+ if emotion_tag == "None": emotion_tag = None
283
+ simple_history = chat_history[:-1]
284
+ response = answer_query(chain, question, chat_history=simple_history, scenario_tag=scenario_tag, emotion_tag=emotion_tag)
285
+ answer = response.get("answer", "[No answer found]")
286
+ chat_history.append({"role": "assistant", "content": answer})
287
+ audio_out = None
288
+ if settings.get("tts_on") and answer:
289
+ tts_lang_code = CONFIG["languages"].get(settings.get("tts_lang"), "en")
290
+ audio_out = synthesize_tts(answer, lang=tts_lang_code)
291
+ from gradio import update
292
+ return "", (update(value=audio_out, visible=bool(audio_out))), chat_history
293
+
294
+ def upload_knowledge(files, current_theme):
295
+ if not files: return "No files were selected to upload."
296
+ added = 0
297
+ for f in files:
298
+ try:
299
+ copy_into_theme(current_theme, f.name); added += 1
300
+ except Exception as e: print(f"Error uploading file {f.name}: {e}")
301
+ if added > 0 and current_theme in vectorstores: del vectorstores[current_theme]
302
+ return f"Uploaded {added} file(s). Refreshing file list..."
303
+ def save_file_selection(current_theme, enabled_files):
304
+ man = load_manifest(current_theme)
305
+ for fname in man['files']: man['files'][fname] = fname in enabled_files
306
+ save_manifest(current_theme, man)
307
+ if current_theme in vectorstores: del vectorstores[current_theme]
308
+ return f"Settings saved. Index for theme '{current_theme}' will rebuild on the next query."
309
+ def refresh_file_list_ui(current_theme):
310
+ files = list_theme_files(current_theme)
311
+ enabled = [f for f, en in files if en]
312
+ msg = f"Found {len(files)} file(s). {len(enabled)} enabled."
313
+ return gr.update(choices=[f for f, _ in files], value=enabled), msg
314
+ def auto_setup_on_load(current_theme):
315
+ theme_dir = theme_upload_dir(current_theme)
316
+ if not os.listdir(theme_dir):
317
+ print("First-time setup: Auto-seeding sample data...")
318
+ seed_files_into_theme(current_theme)
319
+ all_settings = collect_settings("patient", "", "", "warm", "English", "English", 0.7, "None", "None", "All", True, False)
320
+ files_ui, status_msg = refresh_file_list_ui(current_theme)
321
+ return all_settings, files_ui, status_msg
322
+
323
+ # --- UI Definition ---
324
+ CSS = ".gradio-container { font-size: 14px; } #chatbot { min-height: 250px; } #audio_out audio { max-height: 40px; } #audio_in audio { max-height: 40px; padding: 0; }"
325
+
326
+ with gr.Blocks(theme=gr.themes.Soft(), css=CSS) as demo:
327
+ settings_state = gr.State({})
328
+
329
+ with gr.Tab("Chat"):
330
+ user_text = gr.Textbox(show_label=False, placeholder="Type your message here...")
331
+ audio_in = gr.Audio(sources=["microphone"], type="filepath", label="Voice Input", elem_id="audio_in")
332
+ with gr.Row():
333
+ submit_btn = gr.Button("Send", variant="primary")
334
+ save_btn = gr.Button("Save to Memory")
335
+ clear_btn = gr.Button("Clear")
336
+ chat_status = gr.Markdown()
337
+ audio_out = gr.Audio(label="Response Audio", autoplay=True, visible=True, elem_id="audio_out")
338
+ chatbot = gr.Chatbot(elem_id="chatbot", label="Conversation", type="messages")
339
+
340
+ with gr.Tab("Personalize"):
341
+ with gr.Accordion("Add to Personal Knowledge Base", open=True):
342
+ gr.Markdown("Add personal notes, memories, or descriptions of people and places.")
343
+ personal_text = gr.Textbox(lines=5, label="Text Input", placeholder="e.g., 'My father's name is John. He loves listening to Frank Sinatra music.'")
344
+ personal_add_text_btn = gr.Button("Add Text to Memory")
345
+ personal_file = gr.File(label="Upload Audio/Video File")
346
+ personal_add_file_btn = gr.Button("Add Audio/Video to Memory")
347
+ personal_image = gr.Image(type="filepath", label="Upload Image")
348
+ personal_add_image_btn = gr.Button("Add Image to Memory")
349
+ personal_yt_url = gr.Textbox(label="YouTube URL Input", placeholder="Paste a YouTube link here...")
350
+ personal_add_yt_btn = gr.Button("Add YouTube Video to Memory", variant="primary")
351
+ personal_status = gr.Markdown()
352
+ with gr.Accordion("Manage Personal Knowledge", open=False):
353
+ personal_memory_display = gr.DataFrame(headers=["Source", "Content"], label="Saved Personal Memories", interactive=False, row_count=(5, "dynamic"))
354
+ with gr.Row():
355
+ personal_refresh_btn = gr.Button("Refresh Memories")
356
+ with gr.Row():
357
+ personal_delete_selector = gr.Dropdown(label="Select a memory to delete", scale=3, interactive=True)
358
+ personal_delete_btn = gr.Button("Delete Selected Memory", variant="stop", scale=1)
359
+ personal_delete_status = gr.Markdown()
360
+
361
+ with gr.Tab("Settings"):
362
+ with gr.Group():
363
+ gr.Markdown("## Conversation & Persona Settings")
364
+ with gr.Row():
365
+ role = gr.Radio(CONFIG["roles"], value="caregiver", label="Your Role")
366
+ temperature = gr.Slider(0.0, 1.2, value=0.7, step=0.1, label="Creativity")
367
+ tone = gr.Dropdown(CONFIG["tones"], value="warm", label="Response Tone")
368
+ with gr.Row():
369
+ patient_name = gr.Textbox(label="Patient's Name", placeholder="e.g., 'Dad' or 'John'")
370
+ caregiver_name = gr.Textbox(label="Caregiver's Name", placeholder="e.g., 'me' or 'Jane'")
371
+ behaviour_tag = gr.Dropdown(CONFIG["behavior_tags"], value="None", label="Behaviour Filter (Manual Override)")
372
+ emotion_tag = gr.Dropdown(CONFIG["emotion_tags"], value="None", label="Emotion Filter (Manual Override)")
373
+ with gr.Accordion("Language, Voice & Debugging", open=False):
374
+ language = gr.Dropdown(list(CONFIG["languages"].keys()), value="English", label="Response Language")
375
+ tts_lang = gr.Dropdown(list(CONFIG["languages"].keys()), value="English", label="Voice Language")
376
+ tts_on = gr.Checkbox(True, label="Enable Voice Response (TTS)")
377
+ debug_mode = gr.Checkbox(False, label="Show Debug Info")
378
+ gr.Markdown("--- \n ## General Knowledge Base Management")
379
+ active_theme = gr.Radio(CONFIG["themes"], value="All", label="Active Knowledge Theme")
380
+ with gr.Row():
381
+ with gr.Column(scale=1):
382
+ files_in = gr.File(file_count="multiple", file_types=[".jsonl", ".txt"], label="Upload Knowledge Files")
383
+ upload_btn = gr.Button("Upload to Theme", variant="secondary")
384
+ seed_btn = gr.Button("Import Sample Data", variant="secondary")
385
+ with gr.Column(scale=2):
386
+ mgmt_status = gr.Markdown()
387
+ files_box = gr.CheckboxGroup(choices=[], label="Enable Files for the Selected Theme")
388
+ with gr.Row():
389
+ save_files_btn = gr.Button("Save Selection", variant="primary")
390
+ refresh_btn = gr.Button("Refresh List")
391
+
392
+ # --- Event Wiring ---
393
+ all_settings_components = [role, patient_name, caregiver_name, tone, language, tts_lang, temperature, behaviour_tag, emotion_tag, active_theme, tts_on, debug_mode]
394
+ for component in all_settings_components:
395
+ component.change(fn=collect_settings, inputs=all_settings_components, outputs=settings_state)
396
+
397
+ submit_btn.click(fn=chat_fn, inputs=[user_text, audio_in, settings_state, chatbot], outputs=[user_text, audio_out, chatbot])
398
+ save_btn.click(fn=save_chat_to_memory, inputs=[chatbot], outputs=[chat_status])
399
+ clear_btn.click(lambda: (None, None, [], None, "", ""), outputs=[user_text, audio_out, chatbot, audio_in, user_text, chat_status])
400
+
401
+ personal_add_text_btn.click(fn=add_personal_knowledge, inputs=[personal_text, gr.State(None), gr.State(None)], outputs=[personal_status]).then(lambda: None, outputs=[personal_text])
402
+ personal_add_file_btn.click(fn=add_personal_knowledge, inputs=[gr.State(None), personal_file, gr.State(None)], outputs=[personal_status]).then(lambda: None, outputs=[personal_file])
403
+ personal_add_image_btn.click(fn=add_personal_knowledge, inputs=[gr.State(None), gr.State(None), personal_image], outputs=[personal_status]).then(lambda: None, outputs=[personal_image])
404
+ personal_add_yt_btn.click(fn=add_youtube_knowledge, inputs=[personal_yt_url], outputs=[personal_status]).then(lambda: None, outputs=[personal_yt_url])
405
+
406
+ personal_refresh_btn.click(fn=list_personal_memories, inputs=None, outputs=[personal_memory_display, personal_delete_selector])
407
+ 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])
408
+
409
+ 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])
410
+ save_files_btn.click(save_file_selection, inputs=[active_theme, files_box], outputs=[mgmt_status])
411
+ seed_btn.click(seed_files_into_theme, inputs=[active_theme]).then(refresh_file_list_ui, inputs=[active_theme], outputs=[files_box, mgmt_status])
412
+ refresh_btn.click(refresh_file_list_ui, inputs=[active_theme], outputs=[files_box, mgmt_status])
413
+ active_theme.change(refresh_file_list_ui, inputs=[active_theme], outputs=[files_box, mgmt_status])
414
+ demo.load(auto_setup_on_load, inputs=[active_theme], outputs=[settings_state, files_box, mgmt_status])
415
+
416
+ # --- Startup Logic ---
417
+ def pre_load_indexes():
418
+ global personal_vectorstore
419
+ print("Pre-loading all knowledge base indexes at startup...")
420
+ for theme in CONFIG["themes"]:
421
+ print(f" - Loading general index for theme: '{theme}'")
422
+ try:
423
+ ensure_index(theme)
424
+ print(f" ...'{theme}' theme loaded successfully.")
425
+ except Exception as e:
426
+ print(f" ...Error loading theme '{theme}': {e}")
427
+ print(" - Loading personal knowledge index...")
428
+ try:
429
+ personal_vectorstore = build_or_load_vectorstore([], PERSONAL_INDEX_PATH, is_personal=True)
430
+ print(" ...Personal knowledge loaded successfully.")
431
+ except Exception as e:
432
+ print(f" ...Error loading personal knowledge: {e}")
433
+ print("All indexes loaded. Application is ready.")
434
+
435
+ if __name__ == "__main__":
436
+ pre_load_indexes()
437
+ demo.queue().launch(debug=True)