KeenWoo commited on
Commit
436f5c7
·
verified ·
1 Parent(s): 4299e9b

Delete app.py

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