awacke1 commited on
Commit
1e0e48c
·
verified ·
1 Parent(s): 676cc2e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +194 -590
app.py CHANGED
@@ -1,609 +1,213 @@
1
- #!/usr/bin/env python3
2
-
3
- import os
4
- import re
5
- import glob
6
- import json
7
- import base64
8
- import zipfile
9
- import random
10
- import requests
11
- import openai
12
- from PIL import Image
13
- from urllib.parse import quote
14
-
15
  import streamlit as st
16
  import streamlit.components.v1 as components
 
 
 
 
 
 
 
 
17
 
18
- # If you do model inference via huggingface_hub:
19
- # from huggingface_hub import InferenceClient
20
-
21
-
22
- ########################################################################################
23
- # 1) GLOBAL CONFIG & PLACEHOLDERS
24
- ########################################################################################
25
- BASE_URL = "https://huggingface.co/spaces/awacke1/MermaidMarkdownDiagramEditor"
26
- BASE_URL = ""
27
-
28
- PromptPrefix = "AI-Search: "
29
- PromptPrefix2 = "AI-Refine: "
30
- PromptPrefix3 = "AI-JS: "
31
-
32
- roleplaying_glossary = {
33
- "Core Rulebooks": {
34
- "Dungeons and Dragons": ["Player's Handbook", "Dungeon Master's Guide", "Monster Manual"],
35
- "GURPS": ["Basic Set Characters", "Basic Set Campaigns"]
36
- },
37
- "Campaigns & Adventures": {
38
- "Pathfinder": ["Rise of the Runelords", "Curse of the Crimson Throne"]
 
 
 
 
 
 
 
39
  }
40
- }
41
-
42
- transhuman_glossary = {
43
- "Neural Interfaces": ["Cortex Jack", "Mind-Machine Fusion"],
44
- "Cybernetics": ["Robotic Limbs", "Augmented Eyes"],
45
- }
46
-
47
- def process_text(text):
48
- """🕵️ process_text: detective style—prints lines to Streamlit for debugging."""
49
- st.write(f"process_text called with: {text}")
50
-
51
- def search_arxiv(text):
52
- """🔭 search_arxiv: pretend to search ArXiv, just prints debug."""
53
- st.write(f"search_arxiv called with: {text}")
54
-
55
- def SpeechSynthesis(text):
56
- """🗣 Simple logging for text-to-speech placeholders."""
57
- st.write(f"SpeechSynthesis called with: {text}")
58
-
59
- def process_image(image_file, prompt):
60
- """📷 Simple placeholder for image AI pipeline."""
61
- return f"[process_image placeholder] {image_file} => {prompt}"
62
-
63
- def process_video(video_file, seconds_per_frame):
64
- """🎞 Simple placeholder for video AI pipeline."""
65
- st.write(f"[process_video placeholder] {video_file}, {seconds_per_frame} sec/frame")
66
-
67
- API_URL = "https://huggingface-inference-endpoint-placeholder"
68
- API_KEY = "hf_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
69
-
70
- @st.cache_resource
71
- def InferenceLLM(prompt):
72
- """🔮 Stub returning mock response for 'prompt'."""
73
- return f"[InferenceLLM placeholder response to prompt: {prompt}]"
74
-
75
- ########################################################################################
76
- # 2) GLOSSARY & FILE UTILITY
77
- ########################################################################################
78
- @st.cache_resource
79
- def display_glossary_entity(k):
80
- """
81
- Creates multiple link emojis for a single entity.
82
- Each link might point to /?q=..., /?q=<prefix>..., or external sites.
83
- """
84
- search_urls = {
85
- "🚀🌌ArXiv": lambda x: f"/?q={quote(x)}",
86
- "🃏Analyst": lambda x: f"/?q={quote(x)}-{quote(PromptPrefix)}",
87
- "📚PyCoder": lambda x: f"/?q={quote(x)}-{quote(PromptPrefix2)}",
88
- "🔬JSCoder": lambda x: f"/?q={quote(x)}-{quote(PromptPrefix3)}",
89
- "📖": lambda x: f"https://en.wikipedia.org/wiki/{quote(x)}",
90
- "🔍": lambda x: f"https://www.google.com/search?q={quote(x)}",
91
- "🔎": lambda x: f"https://www.bing.com/search?q={quote(x)}",
92
- "🎥": lambda x: f"https://www.youtube.com/results?search_query={quote(x)}",
93
- "🐦": lambda x: f"https://twitter.com/search?q={quote(x)}",
94
  }
95
- links_md = ' '.join([f"[{emoji}]({url(k)})" for emoji, url in search_urls.items()])
96
- st.markdown(f"**{k}** <small>{links_md}</small>", unsafe_allow_html=True)
97
-
98
- def display_content_or_image(query):
99
- """
100
- If 'query' is in transhuman_glossary or there's an image matching 'images/<query>.png',
101
- show it. Otherwise warn.
102
- """
103
- for category, term_list in transhuman_glossary.items():
104
- for term in term_list:
105
- if query.lower() in term.lower():
106
- st.subheader(f"Found in {category}:")
107
- st.write(term)
108
- return True
109
- image_path = f"images/{query}.png"
110
- if os.path.exists(image_path):
111
- st.image(image_path, caption=f"Image for {query}")
112
- return True
113
- st.warning("No matching content or image found.")
114
- return False
115
-
116
- def clear_query_params():
117
- """Warn about clearing. Full clearing requires a redirect or st.experimental_set_query_params()."""
118
- st.warning("Define a redirect or link without query params if you want to truly clear them.")
119
-
120
- ########################################################################################
121
- # 3) FILE-HANDLING (MD files, etc.)
122
- ########################################################################################
123
- def load_file(file_path):
124
- """Load file contents as UTF-8 text, or return empty on error."""
125
- try:
126
- with open(file_path, "r", encoding='utf-8') as f:
127
- return f.read()
128
- except:
129
- return ""
130
-
131
- @st.cache_resource
132
- def create_zip_of_files(files):
133
- """Combine multiple local .md files into a single .zip for user to download."""
134
- zip_name = "Arxiv-Paper-Search-QA-RAG-Streamlit-Gradio-AP.zip"
135
- with zipfile.ZipFile(zip_name, 'w') as zipf:
136
- for file in files:
137
- zipf.write(file)
138
- return zip_name
139
-
140
- @st.cache_resource
141
- def get_zip_download_link(zip_file):
142
- """Return an <a> link to download the given zip_file (base64-encoded)."""
143
- with open(zip_file, 'rb') as f:
144
- data = f.read()
145
- b64 = base64.b64encode(data).decode()
146
- return f'<a href="data:application/zip;base64,{b64}" download="{zip_file}">Download All</a>'
147
-
148
- def get_table_download_link(file_path):
149
- """
150
- Creates a download link for a single file from your snippet.
151
- Encodes it as base64 data.
152
- """
153
- try:
154
- with open(file_path, 'r', encoding='utf-8') as file:
155
- data = file.read()
156
- b64 = base64.b64encode(data.encode()).decode()
157
- file_name = os.path.basename(file_path)
158
- ext = os.path.splitext(file_name)[1]
159
- mime_map = {
160
- '.txt': 'text/plain',
161
- '.py': 'text/plain',
162
- '.xlsx': 'text/plain',
163
- '.csv': 'text/plain',
164
- '.htm': 'text/html',
165
- '.md': 'text/markdown',
166
- '.wav': 'audio/wav'
167
- }
168
- mime_type = mime_map.get(ext, 'application/octet-stream')
169
- return f'<a href="data:{mime_type};base64,{b64}" target="_blank" download="{file_name}">{file_name}</a>'
170
- except:
171
- return ''
172
-
173
- def get_file_size(file_path):
174
- """Get file size in bytes."""
175
- return os.path.getsize(file_path)
176
-
177
- def FileSidebar():
178
- """
179
- Renders .md files, providing open/view/delete/run logic in the sidebar.
180
- """
181
- all_files = glob.glob("*.md")
182
- # Exclude short-named or special files if needed:
183
- all_files = [f for f in all_files if len(os.path.splitext(f)[0]) >= 5]
184
- all_files.sort(key=lambda x: (os.path.splitext(x)[1], x), reverse=True)
185
-
186
- Files1, Files2 = st.sidebar.columns(2)
187
- with Files1:
188
- if st.button("🗑 Delete All"):
189
- for file in all_files:
190
- os.remove(file)
191
- st.rerun()
192
- with Files2:
193
- if st.button("⬇️ Download"):
194
- zip_file = create_zip_of_files(all_files)
195
- st.sidebar.markdown(get_zip_download_link(zip_file), unsafe_allow_html=True)
196
-
197
- file_contents = ''
198
- file_name = ''
199
- next_action = ''
200
-
201
- for file in all_files:
202
- col1, col2, col3, col4, col5 = st.sidebar.columns([1,6,1,1,1])
203
- with col1:
204
- if st.button("🌐", key="md_"+file):
205
- file_contents = load_file(file)
206
- file_name = file
207
- next_action = 'md'
208
- st.session_state['next_action'] = next_action
209
- with col2:
210
- st.markdown(get_table_download_link(file), unsafe_allow_html=True)
211
- with col3:
212
- if st.button("📂", key="open_"+file):
213
- file_contents = load_file(file)
214
- file_name = file
215
- next_action = 'open'
216
- st.session_state['lastfilename'] = file
217
- st.session_state['filename'] = file
218
- st.session_state['filetext'] = file_contents
219
- st.session_state['next_action'] = next_action
220
- with col4:
221
- if st.button("▶️", key="read_"+file):
222
- file_contents = load_file(file)
223
- file_name = file
224
- next_action = 'search'
225
- st.session_state['next_action'] = next_action
226
- with col5:
227
- if st.button("🗑", key="delete_"+file):
228
- os.remove(file)
229
- st.rerun()
230
-
231
- if file_contents:
232
- if next_action == 'open':
233
- open1, open2 = st.columns([0.8, 0.2])
234
- with open1:
235
- file_name_input = st.text_input('File Name:', file_name, key='file_name_input')
236
- file_content_area = st.text_area('File Contents:', file_contents, height=300, key='file_content_area')
237
- if st.button('💾 Save File'):
238
- with open(file_name_input, 'w', encoding='utf-8') as f:
239
- f.write(file_content_area)
240
- st.markdown(f'Saved {file_name_input} successfully.')
241
- elif next_action == 'search':
242
- file_content_area = st.text_area("File Contents:", file_contents, height=500)
243
- user_prompt = PromptPrefix2 + file_contents
244
- st.markdown(user_prompt)
245
- if st.button('🔍Re-Code'):
246
- search_arxiv(file_contents)
247
- elif next_action == 'md':
248
- st.markdown(file_contents)
249
- SpeechSynthesis(file_contents)
250
- if st.button("🔍Run"):
251
- st.write("Running GPT logic placeholder...")
252
-
253
- ########################################################################################
254
- # 4) SCORING / GLOSSARIES
255
- ########################################################################################
256
- score_dir = "scores"
257
- os.makedirs(score_dir, exist_ok=True)
258
-
259
- def generate_key(label, header, idx):
260
- return f"{header}_{label}_{idx}_key"
261
-
262
- def update_score(key, increment=1):
263
- """
264
- Track a 'score' for each glossary item or term, saved in JSON per key.
265
- """
266
- score_file = os.path.join(score_dir, f"{key}.json")
267
- if os.path.exists(score_file):
268
- with open(score_file, "r") as file:
269
- score_data = json.load(file)
270
- else:
271
- score_data = {"clicks": 0, "score": 0}
272
- score_data["clicks"] += increment
273
- score_data["score"] += increment
274
- with open(score_file, "w") as file:
275
- json.dump(score_data, file)
276
- return score_data["score"]
277
-
278
- def load_score(key):
279
- file_path = os.path.join(score_dir, f"{key}.json")
280
- if os.path.exists(file_path):
281
- with open(file_path, "r") as file:
282
- score_data = json.load(file)
283
- return score_data["score"]
284
- return 0
285
-
286
- def display_buttons_with_scores(num_columns_text):
287
- """
288
- Show glossary items as clickable buttons that increment a 'score'.
289
- """
290
- game_emojis = {
291
- "Dungeons and Dragons": "🐉",
292
- "Call of Cthulhu": "🐙",
293
- "GURPS": "🎲",
294
- "Pathfinder": "🗺️",
295
- "Kindred of the East": "🌅",
296
- "Changeling": "🍃",
297
- }
298
- topic_emojis = {
299
- "Core Rulebooks": "📚",
300
- "Maps & Settings": "🗺️",
301
- "Game Mechanics & Tools": "⚙️",
302
- "Monsters & Adversaries": "👹",
303
- "Campaigns & Adventures": "📜",
304
- "Creatives & Assets": "🎨",
305
- "Game Master Resources": "🛠️",
306
- "Lore & Background": "📖",
307
- "Character Development": "🧍",
308
- "Homebrew Content": "🔧",
309
- "General Topics": "🌍",
310
  }
 
 
311
 
312
- for category, games in roleplaying_glossary.items():
313
- category_emoji = topic_emojis.get(category, "🔍")
314
- st.markdown(f"## {category_emoji} {category}")
315
- for game, terms in games.items():
316
- game_emoji = game_emojis.get(game, "🎮")
317
- for term in terms:
318
- key = f"{category}_{game}_{term}".replace(' ', '_').lower()
319
- score_val = load_score(key)
320
- if st.button(f"{game_emoji} {category} {game} {term} {score_val}", key=key):
321
- newscore = update_score(key.replace('?', ''))
322
- st.markdown(f"Scored **{category} - {game} - {term}** -> {newscore}")
323
-
324
- ########################################################################################
325
- # 5) IMAGES & VIDEOS
326
- ########################################################################################
327
-
328
- def display_images_and_wikipedia_summaries(num_columns=4):
329
- """Display .png images in a grid, referencing the name as a 'keyword'."""
330
- image_files = [f for f in os.listdir('.') if f.endswith('.png')]
331
- if not image_files:
332
- st.write("No PNG images found in the current directory.")
333
- return
334
-
335
- image_files_sorted = sorted(image_files, key=lambda x: len(x.split('.')[0]))
336
- cols = st.columns(num_columns)
337
- col_index = 0
338
- for image_file in image_files_sorted:
339
- with cols[col_index % num_columns]:
340
- try:
341
- image = Image.open(image_file)
342
- st.image(image, use_column_width=True)
343
- k = image_file.split('.')[0]
344
- display_glossary_entity(k)
345
- image_text_input = st.text_input(f"Prompt for {image_file}", key=f"image_prompt_{image_file}")
346
- if image_text_input:
347
- response = process_image(image_file, image_text_input)
348
- st.markdown(response)
349
- except:
350
- st.write(f"Could not open {image_file}")
351
- col_index += 1
352
-
353
- def display_videos_and_links(num_columns=4):
354
- """Displays all .mp4/.webm in a grid, plus text input for prompts."""
355
- video_files = [f for f in os.listdir('.') if f.endswith(('.mp4', '.webm'))]
356
- if not video_files:
357
- st.write("No MP4 or WEBM videos found in the current directory.")
358
- return
359
-
360
- video_files_sorted = sorted(video_files, key=lambda x: len(x.split('.')[0]))
361
- cols = st.columns(num_columns)
362
- col_index = 0
363
- for video_file in video_files_sorted:
364
- with cols[col_index % num_columns]:
365
- k = video_file.split('.')[0]
366
- st.video(video_file, format='video/mp4', start_time=0)
367
- display_glossary_entity(k)
368
- video_text_input = st.text_input(f"Video Prompt for {video_file}", key=f"video_prompt_{video_file}")
369
- if video_text_input:
370
- try:
371
- seconds_per_frame = 10
372
- process_video(video_file, seconds_per_frame)
373
- except ValueError:
374
- st.error("Invalid input for seconds per frame!")
375
- col_index += 1
376
-
377
- ########################################################################################
378
- # 6) MERMAID
379
- ########################################################################################
380
-
381
- def generate_mermaid_html(mermaid_code: str) -> str:
382
- """
383
- Returns HTML that centers the Mermaid diagram, loading from a CDN.
384
- """
385
  return f"""
386
- <html>
387
- <head>
388
  <script src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script>
389
- <style>
390
- .centered-mermaid {{
391
- display: flex;
392
- justify-content: center;
393
- margin: 20px auto;
394
- }}
395
- .mermaid {{
396
- max-width: 800px;
397
- }}
398
- </style>
399
- </head>
400
- <body>
401
- <div class="mermaid centered-mermaid">
402
  {mermaid_code}
403
  </div>
404
  <script>
405
- mermaid.initialize({{ startOnLoad: true }});
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
406
  </script>
407
- </body>
408
- </html>
409
- """
410
-
411
- def append_model_param(url: str, model_selected: bool) -> str:
412
- """
413
- If user checks 'Append ?model=1', we append &model=1 or ?model=1 if not present.
414
- """
415
- if not model_selected:
416
- return url
417
- delimiter = "&" if "?" in url else "?"
418
- return f"{url}{delimiter}model=1"
419
-
420
- def inject_base_url(url: str) -> str:
421
- """
422
- If a link does not start with http, prepend your BASE_URL
423
- so it becomes an absolute link to huggingface.co/spaces/...
424
- """
425
- if url.startswith("http"):
426
- return url
427
- return f"{BASE_URL}{url}"
428
-
429
- # We use 2-parameter click lines for Mermaid 11.4.1 compatibility:
430
- DEFAULT_MERMAID = r"""
431
- flowchart LR
432
- U((User 😎)) -- "Talk 🗣️" --> LLM[LLM Agent 🤖\nExtract Info]
433
- click U "?q=U" _self
434
- click LLM "?q=LLM%20Agent%20Extract%20Info" _blank
435
-
436
- LLM -- "Query 🔍" --> HS[Hybrid Search 🔎\nVector+NER+Lexical]
437
- click HS "?q=Hybrid%20Search%20Vector%20NER%20Lexical" _blank
438
-
439
- HS -- "Reason 🤔" --> RE[Reasoning Engine 🛠️\nNeuralNetwork+Medical]
440
- click RE "?q=R" _blank
441
 
442
- RE -- "Link 📡" --> KG((Knowledge Graph 📚\nOntology+GAR+RAG))
443
- click KG "?q=K" _blank
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
444
  """
445
 
446
- ########################################################################################
447
- # 7) MAIN UI
448
- ########################################################################################
449
-
450
  def main():
451
- st.set_page_config(page_title="Mermaid + Two-Parameter Click + LetterMap", layout="wide")
452
-
453
- # 1) Provide a letter map:
454
- letter_map = {
455
- "K": "Knowledge Graph Ontology, GAR, and RAG",
456
- "R": "Reasoning Engine NeuralNetwork Medical",
457
- "U": "User Node Something",
458
- "HS": "Hybrid Search Vector NER Lexical", # if you want multiple letters
459
- "LLM Agent Extract Info": "LLM Agent expansions etc."
460
- }
461
-
462
- query_params = st.query_params
463
- q_list = (query_params.get('q') or query_params.get('query') or [''])
464
- if q_list:
465
- q_val = q_list[0].strip()
466
- if q_val:
467
- # 2) If q_val is in letter_map, display that line
468
- if q_val in letter_map:
469
- expanded_line = letter_map[q_val]
470
- st.write(f"**Expanded**: {expanded_line}")
471
- else:
472
- # fallback to normal "AI-Search: q_val"
473
- search_payload = PromptPrefix + q_val
474
- st.markdown(search_payload)
475
- process_text(search_payload)
476
-
477
- if 'action' in query_params:
478
- action_list = query_params['action']
479
- if action_list:
480
- action = action_list[0]
481
- if action == 'show_message':
482
- st.success("Showing a message because 'action=show_message' was found in the URL.")
483
- elif action == 'clear':
484
- clear_query_params()
485
-
486
- # If a 'query=' param is present, show content or image
487
- if 'query' in query_params:
488
- paramQ = query_params['query'][0]
489
- display_content_or_image(paramQ)
490
-
491
- st.sidebar.write("## Diagram Link Settings")
492
- model_selected = st.sidebar.checkbox("Append ?model=1 to each link?")
493
-
494
- # Rebuild the click lines for the two-parameter approach
495
- lines = DEFAULT_MERMAID.strip().split("\n")
496
- new_lines = []
497
- for line in lines:
498
- # e.g. click U "/?q=K" _blank
499
- if line.strip().startswith("click ") and '"/?' in line:
500
- pattern = r'(click\s+\S+\s+)"([^"]+)"\s+(\S+)'
501
- match = re.match(pattern, line.strip())
502
- if match:
503
- prefix_part = match.group(1) # e.g. "click U "
504
- old_url = match.group(2) # e.g. /?q=K
505
- target = match.group(3) # e.g. _blank
506
-
507
- new_url = inject_base_url(old_url)
508
- new_url = append_model_param(new_url, model_selected)
509
- new_line = f'{prefix_part}"{new_url}" {target}'
510
- new_lines.append(new_line)
511
- else:
512
- new_lines.append(line)
513
- else:
514
- new_lines.append(line)
515
-
516
- final_mermaid = "\n".join(new_lines)
517
-
518
- # Render the top-centered Mermaid diagram
519
- st.sidebar.markdown("**Mermaid Diagram** - 2-Parameter for v11.4.1")
520
- diagram_html = generate_mermaid_html(final_mermaid)
521
- components.html(diagram_html, height=400, scrolling=True)
522
-
523
- # Two-column: left => Markdown, right => Mermaid
524
- left_col, right_col = st.columns(2)
525
-
526
- # -- Left: Markdown
527
- with left_col:
528
- st.subheader("Markdown Side 📝")
529
- if "markdown_text" not in st.session_state:
530
- st.session_state["markdown_text"] = "## Hello!\nYou can type some *Markdown* here.\n"
531
-
532
- markdown_text = st.text_area("Edit Markdown:",
533
- value=st.session_state["markdown_text"],
534
- height=300)
535
- st.session_state["markdown_text"] = markdown_text
536
-
537
- colA, colB = st.columns(2)
538
- with colA:
539
- if st.button("🔄 Refresh Markdown"):
540
- st.write("**Markdown** content refreshed! 🍿")
541
- with colB:
542
- if st.button("❌ Clear Markdown"):
543
- st.session_state["markdown_text"] = ""
544
- st.rerun()
545
-
546
- st.markdown("---")
547
- st.markdown("**Preview:**")
548
- st.markdown(markdown_text)
549
-
550
- # -- Right: Mermaid
551
- with right_col:
552
- st.subheader("Mermaid Side 🧜‍♂️")
553
- if "current_mermaid" not in st.session_state:
554
- st.session_state["current_mermaid"] = final_mermaid
555
-
556
- mermaid_input = st.text_area("Edit Mermaid Code:",
557
- value=st.session_state["current_mermaid"],
558
- height=300)
559
-
560
- colC, colD = st.columns(2)
561
- with colC:
562
- if st.button("🎨 Refresh Diagram"):
563
- st.session_state["current_mermaid"] = mermaid_input
564
- st.write("**Mermaid** diagram refreshed! 🌈")
565
- st.rerun()
566
- with colD:
567
- if st.button("❌ Clear Mermaid"):
568
- st.session_state["current_mermaid"] = ""
569
- st.rerun()
570
-
571
- st.markdown("---")
572
- st.markdown("**Mermaid Source:**")
573
- st.code(mermaid_input, language="python", line_numbers=True)
574
-
575
- # Media Galleries
576
- st.markdown("---")
577
- st.header("Media Galleries")
578
-
579
- num_columns_images = st.slider("Choose Number of Image Columns", 1, 15, 5, key="num_columns_images")
580
- display_images_and_wikipedia_summaries(num_columns_images)
581
-
582
- num_columns_video = st.slider("Choose Number of Video Columns", 1, 15, 5, key="num_columns_video")
583
- display_videos_and_links(num_columns_video)
584
-
585
- # Extended text interface
586
- showExtendedTextInterface = False
587
- if showExtendedTextInterface:
588
- # e.g. display_buttons_with_scores(...)
589
- pass
590
-
591
- # File Sidebar
592
- FileSidebar()
593
-
594
- # Random Title
595
- titles = [
596
- "🧠🎭 Semantic Symphonies & Episodic Encores",
597
- "🌌🎼 AI Rhythms of Memory Lane",
598
- "🎭🎉 Cognitive Crescendos & Neural Harmonies",
599
- "🧠🎺 Mnemonic Melodies & Synaptic Grooves",
600
- "🎼🎸 Straight Outta Cognition",
601
- "🥁🎻 Jazzy Jambalaya of AI Memories",
602
- "🏰 Semantic Soul & Episodic Essence",
603
- "🥁🎻 The Music Of AI's Mind"
604
- ]
605
- st.markdown(f"**{random.choice(titles)}**")
606
-
607
 
608
  if __name__ == "__main__":
609
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
  import streamlit.components.v1 as components
3
+ import asyncio
4
+ import edge_tts
5
+ import os
6
+ import base64
7
+ import json
8
+ from datetime import datetime
9
+ from typing import Optional, Dict, List
10
+ import glob
11
 
12
+ # Configure page
13
+ st.set_page_config(
14
+ page_title="Research Assistant",
15
+ page_icon="🔬",
16
+ layout="wide",
17
+ initial_sidebar_state="expanded"
18
+ )
19
+
20
+ # Initialize session state
21
+ if 'current_query' not in st.session_state:
22
+ st.session_state.current_query = ''
23
+ if 'last_response' not in st.session_state:
24
+ st.session_state.last_response = ''
25
+ if 'audio_queue' not in st.session_state:
26
+ st.session_state.audio_queue = []
27
+ if 'mermaid_history' not in st.session_state:
28
+ st.session_state.mermaid_history = []
29
+
30
+ # Custom CSS
31
+ st.markdown("""
32
+ <style>
33
+ .main { background-color: #f5f5f5; }
34
+ .stMarkdown { font-family: 'Inter', sans-serif; }
35
+ .diagram-container {
36
+ background: white;
37
+ padding: 20px;
38
+ border-radius: 10px;
39
+ box-shadow: 0 2px 4px rgba(0,0,0,0.1);
40
  }
41
+ .results-container {
42
+ margin-top: 20px;
43
+ padding: 15px;
44
+ background: white;
45
+ border-radius: 10px;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  }
47
+ .audio-player {
48
+ width: 100%;
49
+ margin: 10px 0;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  }
51
+ </style>
52
+ """, unsafe_allow_html=True)
53
 
54
+ def generate_mermaid_html(mermaid_code: str, height: int = 400) -> str:
55
+ """Generate responsive Mermaid diagram HTML with click handling."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
  return f"""
57
+ <div class="diagram-container">
 
58
  <script src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script>
59
+ <div class="mermaid" style="height: {height}px;">
 
 
 
 
 
 
 
 
 
 
 
 
60
  {mermaid_code}
61
  </div>
62
  <script>
63
+ mermaid.initialize({{
64
+ startOnLoad: true,
65
+ securityLevel: 'loose',
66
+ theme: 'default'
67
+ }});
68
+
69
+ document.addEventListener('click', (e) => {{
70
+ if (e.target.tagName === 'g' && e.target.classList.contains('node')) {{
71
+ const nodeId = e.target.id;
72
+ window.parent.postMessage({{
73
+ type: 'node_clicked',
74
+ nodeId: nodeId,
75
+ isStreamlitMessage: true
76
+ }}, '*');
77
+ }}
78
+ }});
79
  </script>
80
+ </div>
81
+ """
82
+
83
+ async def generate_speech(text: str, voice: str = "en-US-AriaNeural") -> Optional[str]:
84
+ """Generate speech using Edge TTS."""
85
+ if not text.strip():
86
+ return None
87
+
88
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
89
+ output_file = f"speech_{timestamp}.mp3"
90
+
91
+ communicate = edge_tts.Communicate(text, voice)
92
+ await communicate.save(output_file)
93
+
94
+ return output_file
95
+
96
+ def process_arxiv_search(query: str) -> Dict:
97
+ """Process Arxiv search with your existing research code."""
98
+ # Integrate your Arxiv search code here
99
+ # This is a placeholder that simulates a response
100
+ return {
101
+ "title": "Sample Research Paper",
102
+ "abstract": "This is a sample abstract...",
103
+ "authors": ["Author 1", "Author 2"],
104
+ "url": "https://arxiv.org/abs/..."
105
+ }
 
 
 
 
 
 
 
 
106
 
107
+ def create_audio_player(file_path: str) -> str:
108
+ """Create an HTML audio player with download button."""
109
+ with open(file_path, "rb") as audio_file:
110
+ audio_bytes = audio_file.read()
111
+ audio_b64 = base64.b64encode(audio_bytes).decode()
112
+
113
+ return f"""
114
+ <div class="audio-player">
115
+ <audio controls style="width: 100%">
116
+ <source src="data:audio/mp3;base64,{audio_b64}" type="audio/mp3">
117
+ Your browser does not support the audio element.
118
+ </audio>
119
+ <a href="data:audio/mp3;base64,{audio_b64}"
120
+ download="{os.path.basename(file_path)}"
121
+ style="margin-top: 5px; display: inline-block;">
122
+ Download Audio
123
+ </a>
124
+ </div>
125
+ """
126
+
127
+ def handle_node_click(node_id: str):
128
+ """Handle Mermaid diagram node clicks."""
129
+ # Convert node ID to search query
130
+ query = node_id.replace('_', ' ')
131
+
132
+ # Perform search
133
+ results = process_arxiv_search(query)
134
+
135
+ # Generate speech from results
136
+ asyncio.run(generate_speech(results['abstract']))
137
+
138
+ # Update session state
139
+ st.session_state.current_query = query
140
+ st.session_state.last_response = results
141
+
142
+ # Main Mermaid diagram definition
143
+ RESEARCH_DIAGRAM = """
144
+ graph TD
145
+ A[Literature Review] --> B[Data Analysis]
146
+ B --> C[Results]
147
+ C --> D[Conclusions]
148
+
149
+ click A callback "Research Methodology"
150
+ click B callback "Statistical Analysis"
151
+ click C callback "Research Findings"
152
+ click D callback "Research Impact"
153
+
154
+ style A fill:#f9f,stroke:#333,stroke-width:4px
155
+ style B fill:#bbf,stroke:#333,stroke-width:4px
156
+ style C fill:#bfb,stroke:#333,stroke-width:4px
157
+ style D fill:#fbb,stroke:#333,stroke-width:4px
158
  """
159
 
 
 
 
 
160
  def main():
161
+ st.title("📚 Research Assistant")
162
+
163
+ # Sidebar configuration
164
+ st.sidebar.header("Configuration")
165
+ voice_option = st.sidebar.selectbox(
166
+ "Select Voice",
167
+ ["en-US-AriaNeural", "en-US-GuyNeural", "en-GB-SoniaNeural"]
168
+ )
169
+
170
+ # Main layout
171
+ col1, col2 = st.columns([2, 3])
172
+
173
+ with col1:
174
+ st.subheader("Research Map")
175
+ components.html(
176
+ generate_mermaid_html(RESEARCH_DIAGRAM),
177
+ height=500,
178
+ scrolling=True
179
+ )
180
+
181
+ st.markdown("### Recent Searches")
182
+ for query in st.session_state.mermaid_history[-5:]:
183
+ st.info(query)
184
+
185
+ with col2:
186
+ st.subheader("Research Results")
187
+
188
+ # Manual search option
189
+ search_query = st.text_input("Enter search query:")
190
+ if st.button("Search"):
191
+ handle_node_click(search_query)
192
+
193
+ # Display current results
194
+ if st.session_state.last_response:
195
+ with st.container():
196
+ st.markdown("#### Latest Results")
197
+ st.json(st.session_state.last_response)
198
+
199
+ # Audio playback
200
+ audio_files = glob.glob("speech_*.mp3")
201
+ if audio_files:
202
+ latest_audio = max(audio_files, key=os.path.getctime)
203
+ st.markdown(create_audio_player(latest_audio), unsafe_allow_html=True)
204
+
205
+ # Cleanup old audio files
206
+ for file in glob.glob("speech_*.mp3")[:-5]: # Keep only last 5 files
207
+ try:
208
+ os.remove(file)
209
+ except:
210
+ pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
211
 
212
  if __name__ == "__main__":
213
+ main()