Spaces:
Running
on
CPU Upgrade
Running
on
CPU Upgrade
Update app.py
Browse files
app.py
CHANGED
@@ -15,12 +15,12 @@ from urllib.parse import quote
|
|
15 |
import streamlit as st
|
16 |
import streamlit.components.v1 as components
|
17 |
|
18 |
-
#
|
19 |
-
#from huggingface_hub import InferenceClient
|
20 |
|
21 |
-
|
22 |
-
#
|
23 |
-
|
24 |
BASE_URL = "https://huggingface.co/spaces/awacke1/MermaidMarkdownDiagramEditor"
|
25 |
|
26 |
PromptPrefix = "AI-Search: "
|
@@ -42,42 +42,45 @@ transhuman_glossary = {
|
|
42 |
"Cybernetics": ["Robotic Limbs", "Augmented Eyes"],
|
43 |
}
|
44 |
|
45 |
-
########################################################################################
|
46 |
-
# 2) SIMPLE HELPER FUNCS
|
47 |
-
########################################################################################
|
48 |
|
49 |
def process_text(text):
|
50 |
"""🕵️ process_text: detective style—prints lines to Streamlit for debugging."""
|
51 |
st.write(f"process_text called with: {text}")
|
52 |
|
|
|
53 |
def search_arxiv(text):
|
54 |
"""🔭 search_arxiv: pretend to search ArXiv, just prints debug for now."""
|
55 |
st.write(f"search_arxiv called with: {text}")
|
56 |
|
|
|
57 |
def SpeechSynthesis(text):
|
58 |
-
"""🗣 SpeechSynthesis: read lines out loud?
|
59 |
st.write(f"SpeechSynthesis called with: {text}")
|
60 |
|
|
|
61 |
def process_image(image_file, prompt):
|
62 |
"""📷 process_image: imagine an AI pipeline for images, here we just log."""
|
63 |
return f"[process_image placeholder] {image_file} => {prompt}"
|
64 |
|
|
|
65 |
def process_video(video_file, seconds_per_frame):
|
66 |
"""🎞 process_video: placeholder for video tasks, logs to Streamlit."""
|
67 |
st.write(f"[process_video placeholder] {video_file}, {seconds_per_frame} sec/frame")
|
68 |
|
|
|
69 |
API_URL = "https://huggingface-inference-endpoint-placeholder"
|
70 |
API_KEY = "hf_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
|
71 |
|
|
|
72 |
@st.cache_resource
|
73 |
def InferenceLLM(prompt):
|
74 |
"""🔮 InferenceLLM: a stub returning a mock response for 'prompt'."""
|
75 |
return f"[InferenceLLM placeholder response to prompt: {prompt}]"
|
76 |
|
77 |
-
########################################################################################
|
78 |
-
# 3) GLOSSARY & FILE UTILITY
|
79 |
-
########################################################################################
|
80 |
|
|
|
|
|
|
|
81 |
@st.cache_resource
|
82 |
def display_glossary_entity(k):
|
83 |
"""
|
@@ -98,6 +101,7 @@ def display_glossary_entity(k):
|
|
98 |
links_md = ' '.join([f"[{emoji}]({url(k)})" for emoji, url in search_urls.items()])
|
99 |
st.markdown(f"**{k}** <small>{links_md}</small>", unsafe_allow_html=True)
|
100 |
|
|
|
101 |
def display_content_or_image(query):
|
102 |
"""
|
103 |
If 'query' is in transhuman_glossary or there's an image matching 'images/<query>.png',
|
@@ -116,14 +120,15 @@ def display_content_or_image(query):
|
|
116 |
st.warning("No matching content or image found.")
|
117 |
return False
|
118 |
|
|
|
119 |
def clear_query_params():
|
120 |
-
"""
|
121 |
st.warning("Define a redirect or link without query params if you want to truly clear them.")
|
122 |
|
123 |
-
########################################################################################
|
124 |
-
# 4) FILE-HANDLING (MD files, etc.)
|
125 |
-
########################################################################################
|
126 |
|
|
|
|
|
|
|
127 |
def load_file(file_path):
|
128 |
"""Load file contents as UTF-8 text, or return empty on error."""
|
129 |
try:
|
@@ -132,6 +137,7 @@ def load_file(file_path):
|
|
132 |
except:
|
133 |
return ""
|
134 |
|
|
|
135 |
@st.cache_resource
|
136 |
def create_zip_of_files(files):
|
137 |
"""Combine multiple local files into a single .zip for user to download."""
|
@@ -141,6 +147,7 @@ def create_zip_of_files(files):
|
|
141 |
zipf.write(file)
|
142 |
return zip_name
|
143 |
|
|
|
144 |
@st.cache_resource
|
145 |
def get_zip_download_link(zip_file):
|
146 |
"""Return an <a> link to download the given zip_file (base64-encoded)."""
|
@@ -149,6 +156,7 @@ def get_zip_download_link(zip_file):
|
|
149 |
b64 = base64.b64encode(data).decode()
|
150 |
return f'<a href="data:application/zip;base64,{b64}" download="{zip_file}">Download All</a>'
|
151 |
|
|
|
152 |
def get_table_download_link(file_path):
|
153 |
"""
|
154 |
Creates a download link for a single file from your snippet.
|
@@ -174,15 +182,18 @@ def get_table_download_link(file_path):
|
|
174 |
except:
|
175 |
return ''
|
176 |
|
|
|
177 |
def get_file_size(file_path):
|
178 |
"""Get file size in bytes."""
|
179 |
return os.path.getsize(file_path)
|
180 |
|
|
|
181 |
def FileSidebar():
|
182 |
"""
|
183 |
Renders .md files in the sidebar with open/view/run/delete logic.
|
184 |
"""
|
185 |
all_files = glob.glob("*.md")
|
|
|
186 |
all_files = [f for f in all_files if len(os.path.splitext(f)[0]) >= 5]
|
187 |
all_files.sort(key=lambda x: (os.path.splitext(x)[1], x), reverse=True)
|
188 |
|
@@ -202,9 +213,9 @@ def FileSidebar():
|
|
202 |
next_action = ''
|
203 |
|
204 |
for file in all_files:
|
205 |
-
col1, col2, col3, col4, col5 = st.sidebar.columns([1,6,1,1,1])
|
206 |
with col1:
|
207 |
-
if st.button("🌐", key="md_"+file):
|
208 |
file_contents = load_file(file)
|
209 |
file_name = file
|
210 |
next_action = 'md'
|
@@ -212,7 +223,7 @@ def FileSidebar():
|
|
212 |
with col2:
|
213 |
st.markdown(get_table_download_link(file), unsafe_allow_html=True)
|
214 |
with col3:
|
215 |
-
if st.button("📂", key="open_"+file):
|
216 |
file_contents = load_file(file)
|
217 |
file_name = file
|
218 |
next_action = 'open'
|
@@ -221,13 +232,13 @@ def FileSidebar():
|
|
221 |
st.session_state['filetext'] = file_contents
|
222 |
st.session_state['next_action'] = next_action
|
223 |
with col4:
|
224 |
-
if st.button("▶️", key="read_"+file):
|
225 |
file_contents = load_file(file)
|
226 |
file_name = file
|
227 |
next_action = 'search'
|
228 |
st.session_state['next_action'] = next_action
|
229 |
with col5:
|
230 |
-
if st.button("🗑", key="delete_"+file):
|
231 |
os.remove(file)
|
232 |
st.rerun()
|
233 |
|
@@ -237,6 +248,7 @@ def FileSidebar():
|
|
237 |
with open1:
|
238 |
file_name_input = st.text_input('File Name:', file_name, key='file_name_input')
|
239 |
file_content_area = st.text_area('File Contents:', file_contents, height=300, key='file_content_area')
|
|
|
240 |
if st.button('💾 Save File'):
|
241 |
with open(file_name_input, 'w', encoding='utf-8') as f:
|
242 |
f.write(file_content_area)
|
@@ -255,15 +267,18 @@ def FileSidebar():
|
|
255 |
if st.button("🔍Run"):
|
256 |
st.write("Running GPT logic placeholder...")
|
257 |
|
258 |
-
|
259 |
-
#
|
260 |
-
|
|
|
261 |
score_dir = "scores"
|
262 |
os.makedirs(score_dir, exist_ok=True)
|
263 |
|
|
|
264 |
def generate_key(label, header, idx):
|
265 |
return f"{header}_{label}_{idx}_key"
|
266 |
|
|
|
267 |
def update_score(key, increment=1):
|
268 |
"""Increment the 'score' for a glossary item in JSON storage."""
|
269 |
score_file = os.path.join(score_dir, f"{key}.json")
|
@@ -278,6 +293,7 @@ def update_score(key, increment=1):
|
|
278 |
json.dump(score_data, file)
|
279 |
return score_data["score"]
|
280 |
|
|
|
281 |
def load_score(key):
|
282 |
"""Load the stored score from .json if it exists, else 0."""
|
283 |
file_path = os.path.join(score_dir, f"{key}.json")
|
@@ -287,6 +303,7 @@ def load_score(key):
|
|
287 |
return score_data["score"]
|
288 |
return 0
|
289 |
|
|
|
290 |
def display_buttons_with_scores(num_columns_text):
|
291 |
"""
|
292 |
Show glossary items as clickable buttons, each increments a 'score'.
|
@@ -325,10 +342,10 @@ def display_buttons_with_scores(num_columns_text):
|
|
325 |
newscore = update_score(key.replace('?', ''))
|
326 |
st.markdown(f"Scored **{category} - {game} - {term}** -> {newscore}")
|
327 |
|
328 |
-
########################################################################################
|
329 |
-
# 6) IMAGES & VIDEOS
|
330 |
-
########################################################################################
|
331 |
|
|
|
|
|
|
|
332 |
def display_images_and_wikipedia_summaries(num_columns=4):
|
333 |
"""Display .png images in a grid, referencing the name as a 'keyword'."""
|
334 |
image_files = [f for f in os.listdir('.') if f.endswith('.png')]
|
@@ -339,6 +356,7 @@ def display_images_and_wikipedia_summaries(num_columns=4):
|
|
339 |
image_files_sorted = sorted(image_files, key=lambda x: len(x.split('.')[0]))
|
340 |
cols = st.columns(num_columns)
|
341 |
col_index = 0
|
|
|
342 |
for image_file in image_files_sorted:
|
343 |
with cols[col_index % num_columns]:
|
344 |
try:
|
@@ -354,6 +372,7 @@ def display_images_and_wikipedia_summaries(num_columns=4):
|
|
354 |
st.write(f"Could not open {image_file}")
|
355 |
col_index += 1
|
356 |
|
|
|
357 |
def display_videos_and_links(num_columns=4):
|
358 |
"""Displays all .mp4/.webm in a grid, plus text input for prompts."""
|
359 |
video_files = [f for f in os.listdir('.') if f.endswith(('.mp4', '.webm'))]
|
@@ -364,6 +383,7 @@ def display_videos_and_links(num_columns=4):
|
|
364 |
video_files_sorted = sorted(video_files, key=lambda x: len(x.split('.')[0]))
|
365 |
cols = st.columns(num_columns)
|
366 |
col_index = 0
|
|
|
367 |
for video_file in video_files_sorted:
|
368 |
with cols[col_index % num_columns]:
|
369 |
k = video_file.split('.')[0]
|
@@ -378,10 +398,10 @@ def display_videos_and_links(num_columns=4):
|
|
378 |
st.error("Invalid input for seconds per frame!")
|
379 |
col_index += 1
|
380 |
|
381 |
-
########################################################################################
|
382 |
-
# 7) MERMAID
|
383 |
-
########################################################################################
|
384 |
|
|
|
|
|
|
|
385 |
def generate_mermaid_html(mermaid_code: str) -> str:
|
386 |
"""Embed mermaid_code in a minimal HTML snippet, centered."""
|
387 |
return f"""
|
@@ -410,82 +430,156 @@ def generate_mermaid_html(mermaid_code: str) -> str:
|
|
410 |
</html>
|
411 |
"""
|
412 |
|
|
|
413 |
def append_model_param(url: str, model_selected: bool) -> str:
|
414 |
-
"""If user
|
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 |
"""If link doesn't start with 'http', prepend BASE_URL so it's absolute."""
|
422 |
if url.startswith("http"):
|
423 |
return url
|
424 |
return f"{BASE_URL}{url}"
|
425 |
|
426 |
-
########################################################################################
|
427 |
-
# 8) NEW MERMAID CODE - NO DOUBLE QUOTES, USE UPPER/LOWER MERGING
|
428 |
-
########################################################################################
|
429 |
-
|
430 |
-
# The user wants no double quotes, plus a middle word like OpenUser
|
431 |
-
# Example usage:
|
432 |
-
# click U /?q=U OpenUser _blank
|
433 |
-
# which might cause syntax issues in older Mermaid, but we'll do it anyway.
|
434 |
|
|
|
435 |
DEFAULT_MERMAID = r"""
|
436 |
flowchart LR
|
437 |
U((User 😎)) -- "Talk 🗣️" --> LLM[LLM Agent 🤖\nExtract Info]
|
438 |
-
click U "/?q=User%20😎" "Open 'User 😎'" _blank
|
439 |
-
click LLM "/?q=LLM%20Agent%20Extract%20Info" "Open LLM
|
440 |
|
441 |
LLM -- "Query 🔍" --> HS[Hybrid Search 🔎\nVector+NER+Lexical]
|
442 |
-
click HS "/?q=Hybrid%20Search%20Vector+NER+Lexical" "Open
|
443 |
|
444 |
HS -- "Reason 🤔" --> RE[Reasoning Engine 🛠️\nNeuralNetwork+Medical]
|
445 |
-
click RE "/?q=Reasoning%20Engine%20NeuralNetwork+Medical" "Open
|
446 |
|
447 |
RE -- "Link 📡" --> KG((Knowledge Graph 📚\nOntology+GAR+RAG))
|
448 |
-
click KG "/?q=Knowledge%20Graph%20Ontology+GAR+RAG" "Open
|
449 |
"""
|
450 |
|
451 |
-
########################################################################################
|
452 |
-
# 9) MAIN UI
|
453 |
-
########################################################################################
|
454 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
455 |
def main():
|
456 |
-
st.set_page_config(page_title="Mermaid
|
457 |
|
458 |
# 1) Query param parsing
|
459 |
query_params = st.query_params
|
460 |
-
|
461 |
-
if
|
462 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
463 |
|
464 |
# 2) Let user pick ?model=1
|
465 |
st.sidebar.write("## Diagram Link Settings")
|
466 |
model_selected = st.sidebar.checkbox("Append ?model=1 to each link?")
|
467 |
|
468 |
-
# 3) We'll
|
|
|
469 |
lines = DEFAULT_MERMAID.strip().split("\n")
|
470 |
new_lines = []
|
471 |
for line in lines:
|
472 |
-
|
473 |
-
|
474 |
-
|
475 |
-
#
|
476 |
-
|
477 |
-
|
478 |
-
|
479 |
-
|
480 |
-
|
481 |
-
|
482 |
-
#
|
|
|
|
|
|
|
483 |
new_url = inject_base_url(old_url)
|
484 |
-
#
|
485 |
new_url = append_model_param(new_url, model_selected)
|
486 |
-
|
487 |
-
|
488 |
-
new_line = f"click {node_name} {new_url} {middle} {target}"
|
489 |
new_lines.append(new_line)
|
490 |
else:
|
491 |
new_lines.append(line)
|
@@ -493,25 +587,60 @@ def main():
|
|
493 |
new_lines.append(line)
|
494 |
|
495 |
final_mermaid = "\n".join(new_lines)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
496 |
|
497 |
-
# 4) Render the top-centered diagram
|
498 |
-
st.title("Mermaid Diagram - No Double Quotes & 'OpenUser'-style Links")
|
499 |
diagram_html = generate_mermaid_html(final_mermaid)
|
500 |
components.html(diagram_html, height=400, scrolling=True)
|
501 |
|
502 |
-
#
|
503 |
left_col, right_col = st.columns(2)
|
504 |
|
505 |
with left_col:
|
506 |
st.subheader("Markdown Side 📝")
|
507 |
if "markdown_text" not in st.session_state:
|
508 |
st.session_state["markdown_text"] = "## Hello!\nYou can type some *Markdown* here.\n"
|
509 |
-
|
510 |
-
|
511 |
-
|
512 |
-
|
|
|
513 |
st.session_state["markdown_text"] = markdown_text
|
514 |
|
|
|
515 |
colA, colB = st.columns(2)
|
516 |
with colA:
|
517 |
if st.button("🔄 Refresh Markdown"):
|
@@ -527,14 +656,14 @@ def main():
|
|
527 |
|
528 |
with right_col:
|
529 |
st.subheader("Mermaid Side 🧜♂️")
|
530 |
-
|
531 |
if "current_mermaid" not in st.session_state:
|
532 |
st.session_state["current_mermaid"] = final_mermaid
|
533 |
|
534 |
-
mermaid_input = st.text_area(
|
535 |
-
|
536 |
-
|
537 |
-
|
|
|
538 |
colC, colD = st.columns(2)
|
539 |
with colC:
|
540 |
if st.button("🎨 Refresh Diagram"):
|
@@ -550,20 +679,27 @@ def main():
|
|
550 |
st.markdown("**Mermaid Source:**")
|
551 |
st.code(mermaid_input, language="python", line_numbers=True)
|
552 |
|
553 |
-
#
|
554 |
st.markdown("---")
|
555 |
st.header("Media Galleries")
|
556 |
-
|
557 |
num_columns_images = st.slider("Choose Number of Image Columns", 1, 15, 5, key="num_columns_images")
|
558 |
display_images_and_wikipedia_summaries(num_columns_images)
|
559 |
|
560 |
num_columns_video = st.slider("Choose Number of Video Columns", 1, 15, 5, key="num_columns_video")
|
561 |
display_videos_and_links(num_columns_video)
|
562 |
|
563 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
564 |
FileSidebar()
|
565 |
|
566 |
-
#
|
567 |
titles = [
|
568 |
"🧠🎭 Semantic Symphonies & Episodic Encores",
|
569 |
"🌌🎼 AI Rhythms of Memory Lane",
|
@@ -576,7 +712,6 @@ def main():
|
|
576 |
]
|
577 |
st.markdown(f"**{random.choice(titles)}**")
|
578 |
|
579 |
-
# End of main
|
580 |
|
581 |
if __name__ == "__main__":
|
582 |
main()
|
|
|
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 |
+
# 1) GLOBAL CONFIG & PLACEHOLDERS
|
23 |
+
# =====================================================================================
|
24 |
BASE_URL = "https://huggingface.co/spaces/awacke1/MermaidMarkdownDiagramEditor"
|
25 |
|
26 |
PromptPrefix = "AI-Search: "
|
|
|
42 |
"Cybernetics": ["Robotic Limbs", "Augmented Eyes"],
|
43 |
}
|
44 |
|
|
|
|
|
|
|
45 |
|
46 |
def process_text(text):
|
47 |
"""🕵️ process_text: detective style—prints lines to Streamlit for debugging."""
|
48 |
st.write(f"process_text called with: {text}")
|
49 |
|
50 |
+
|
51 |
def search_arxiv(text):
|
52 |
"""🔭 search_arxiv: pretend to search ArXiv, just prints debug for now."""
|
53 |
st.write(f"search_arxiv called with: {text}")
|
54 |
|
55 |
+
|
56 |
def SpeechSynthesis(text):
|
57 |
+
"""🗣 SpeechSynthesis: read lines out loud? Here, we log them for demonstration."""
|
58 |
st.write(f"SpeechSynthesis called with: {text}")
|
59 |
|
60 |
+
|
61 |
def process_image(image_file, prompt):
|
62 |
"""📷 process_image: imagine an AI pipeline for images, here we just log."""
|
63 |
return f"[process_image placeholder] {image_file} => {prompt}"
|
64 |
|
65 |
+
|
66 |
def process_video(video_file, seconds_per_frame):
|
67 |
"""🎞 process_video: placeholder for video tasks, logs to Streamlit."""
|
68 |
st.write(f"[process_video placeholder] {video_file}, {seconds_per_frame} sec/frame")
|
69 |
|
70 |
+
|
71 |
API_URL = "https://huggingface-inference-endpoint-placeholder"
|
72 |
API_KEY = "hf_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
|
73 |
|
74 |
+
|
75 |
@st.cache_resource
|
76 |
def InferenceLLM(prompt):
|
77 |
"""🔮 InferenceLLM: a stub returning a mock response for 'prompt'."""
|
78 |
return f"[InferenceLLM placeholder response to prompt: {prompt}]"
|
79 |
|
|
|
|
|
|
|
80 |
|
81 |
+
# =====================================================================================
|
82 |
+
# 2) GLOSSARY & FILE UTILITY
|
83 |
+
# =====================================================================================
|
84 |
@st.cache_resource
|
85 |
def display_glossary_entity(k):
|
86 |
"""
|
|
|
101 |
links_md = ' '.join([f"[{emoji}]({url(k)})" for emoji, url in search_urls.items()])
|
102 |
st.markdown(f"**{k}** <small>{links_md}</small>", unsafe_allow_html=True)
|
103 |
|
104 |
+
|
105 |
def display_content_or_image(query):
|
106 |
"""
|
107 |
If 'query' is in transhuman_glossary or there's an image matching 'images/<query>.png',
|
|
|
120 |
st.warning("No matching content or image found.")
|
121 |
return False
|
122 |
|
123 |
+
|
124 |
def clear_query_params():
|
125 |
+
"""For fully clearing, you'd do a redirect or st.experimental_set_query_params()."""
|
126 |
st.warning("Define a redirect or link without query params if you want to truly clear them.")
|
127 |
|
|
|
|
|
|
|
128 |
|
129 |
+
# =====================================================================================
|
130 |
+
# 3) FILE-HANDLING (MD files, etc.)
|
131 |
+
# =====================================================================================
|
132 |
def load_file(file_path):
|
133 |
"""Load file contents as UTF-8 text, or return empty on error."""
|
134 |
try:
|
|
|
137 |
except:
|
138 |
return ""
|
139 |
|
140 |
+
|
141 |
@st.cache_resource
|
142 |
def create_zip_of_files(files):
|
143 |
"""Combine multiple local files into a single .zip for user to download."""
|
|
|
147 |
zipf.write(file)
|
148 |
return zip_name
|
149 |
|
150 |
+
|
151 |
@st.cache_resource
|
152 |
def get_zip_download_link(zip_file):
|
153 |
"""Return an <a> link to download the given zip_file (base64-encoded)."""
|
|
|
156 |
b64 = base64.b64encode(data).decode()
|
157 |
return f'<a href="data:application/zip;base64,{b64}" download="{zip_file}">Download All</a>'
|
158 |
|
159 |
+
|
160 |
def get_table_download_link(file_path):
|
161 |
"""
|
162 |
Creates a download link for a single file from your snippet.
|
|
|
182 |
except:
|
183 |
return ''
|
184 |
|
185 |
+
|
186 |
def get_file_size(file_path):
|
187 |
"""Get file size in bytes."""
|
188 |
return os.path.getsize(file_path)
|
189 |
|
190 |
+
|
191 |
def FileSidebar():
|
192 |
"""
|
193 |
Renders .md files in the sidebar with open/view/run/delete logic.
|
194 |
"""
|
195 |
all_files = glob.glob("*.md")
|
196 |
+
# If you want to filter out short-named or special files:
|
197 |
all_files = [f for f in all_files if len(os.path.splitext(f)[0]) >= 5]
|
198 |
all_files.sort(key=lambda x: (os.path.splitext(x)[1], x), reverse=True)
|
199 |
|
|
|
213 |
next_action = ''
|
214 |
|
215 |
for file in all_files:
|
216 |
+
col1, col2, col3, col4, col5 = st.sidebar.columns([1, 6, 1, 1, 1])
|
217 |
with col1:
|
218 |
+
if st.button("🌐", key="md_" + file):
|
219 |
file_contents = load_file(file)
|
220 |
file_name = file
|
221 |
next_action = 'md'
|
|
|
223 |
with col2:
|
224 |
st.markdown(get_table_download_link(file), unsafe_allow_html=True)
|
225 |
with col3:
|
226 |
+
if st.button("📂", key="open_" + file):
|
227 |
file_contents = load_file(file)
|
228 |
file_name = file
|
229 |
next_action = 'open'
|
|
|
232 |
st.session_state['filetext'] = file_contents
|
233 |
st.session_state['next_action'] = next_action
|
234 |
with col4:
|
235 |
+
if st.button("▶️", key="read_" + file):
|
236 |
file_contents = load_file(file)
|
237 |
file_name = file
|
238 |
next_action = 'search'
|
239 |
st.session_state['next_action'] = next_action
|
240 |
with col5:
|
241 |
+
if st.button("🗑", key="delete_" + file):
|
242 |
os.remove(file)
|
243 |
st.rerun()
|
244 |
|
|
|
248 |
with open1:
|
249 |
file_name_input = st.text_input('File Name:', file_name, key='file_name_input')
|
250 |
file_content_area = st.text_area('File Contents:', file_contents, height=300, key='file_content_area')
|
251 |
+
|
252 |
if st.button('💾 Save File'):
|
253 |
with open(file_name_input, 'w', encoding='utf-8') as f:
|
254 |
f.write(file_content_area)
|
|
|
267 |
if st.button("🔍Run"):
|
268 |
st.write("Running GPT logic placeholder...")
|
269 |
|
270 |
+
|
271 |
+
# =====================================================================================
|
272 |
+
# 4) SCORING / GLOSSARIES
|
273 |
+
# =====================================================================================
|
274 |
score_dir = "scores"
|
275 |
os.makedirs(score_dir, exist_ok=True)
|
276 |
|
277 |
+
|
278 |
def generate_key(label, header, idx):
|
279 |
return f"{header}_{label}_{idx}_key"
|
280 |
|
281 |
+
|
282 |
def update_score(key, increment=1):
|
283 |
"""Increment the 'score' for a glossary item in JSON storage."""
|
284 |
score_file = os.path.join(score_dir, f"{key}.json")
|
|
|
293 |
json.dump(score_data, file)
|
294 |
return score_data["score"]
|
295 |
|
296 |
+
|
297 |
def load_score(key):
|
298 |
"""Load the stored score from .json if it exists, else 0."""
|
299 |
file_path = os.path.join(score_dir, f"{key}.json")
|
|
|
303 |
return score_data["score"]
|
304 |
return 0
|
305 |
|
306 |
+
|
307 |
def display_buttons_with_scores(num_columns_text):
|
308 |
"""
|
309 |
Show glossary items as clickable buttons, each increments a 'score'.
|
|
|
342 |
newscore = update_score(key.replace('?', ''))
|
343 |
st.markdown(f"Scored **{category} - {game} - {term}** -> {newscore}")
|
344 |
|
|
|
|
|
|
|
345 |
|
346 |
+
# =====================================================================================
|
347 |
+
# 5) IMAGES & VIDEOS
|
348 |
+
# =====================================================================================
|
349 |
def display_images_and_wikipedia_summaries(num_columns=4):
|
350 |
"""Display .png images in a grid, referencing the name as a 'keyword'."""
|
351 |
image_files = [f for f in os.listdir('.') if f.endswith('.png')]
|
|
|
356 |
image_files_sorted = sorted(image_files, key=lambda x: len(x.split('.')[0]))
|
357 |
cols = st.columns(num_columns)
|
358 |
col_index = 0
|
359 |
+
|
360 |
for image_file in image_files_sorted:
|
361 |
with cols[col_index % num_columns]:
|
362 |
try:
|
|
|
372 |
st.write(f"Could not open {image_file}")
|
373 |
col_index += 1
|
374 |
|
375 |
+
|
376 |
def display_videos_and_links(num_columns=4):
|
377 |
"""Displays all .mp4/.webm in a grid, plus text input for prompts."""
|
378 |
video_files = [f for f in os.listdir('.') if f.endswith(('.mp4', '.webm'))]
|
|
|
383 |
video_files_sorted = sorted(video_files, key=lambda x: len(x.split('.')[0]))
|
384 |
cols = st.columns(num_columns)
|
385 |
col_index = 0
|
386 |
+
|
387 |
for video_file in video_files_sorted:
|
388 |
with cols[col_index % num_columns]:
|
389 |
k = video_file.split('.')[0]
|
|
|
398 |
st.error("Invalid input for seconds per frame!")
|
399 |
col_index += 1
|
400 |
|
|
|
|
|
|
|
401 |
|
402 |
+
# =====================================================================================
|
403 |
+
# 6) MERMAID & PARTIAL SUBGRAPH LOGIC
|
404 |
+
# =====================================================================================
|
405 |
def generate_mermaid_html(mermaid_code: str) -> str:
|
406 |
"""Embed mermaid_code in a minimal HTML snippet, centered."""
|
407 |
return f"""
|
|
|
430 |
</html>
|
431 |
"""
|
432 |
|
433 |
+
|
434 |
def append_model_param(url: str, model_selected: bool) -> str:
|
435 |
+
"""If user selects 'model=1', we append &model=1 or ?model=1 if not present."""
|
436 |
if not model_selected:
|
437 |
return url
|
438 |
delimiter = "&" if "?" in url else "?"
|
439 |
return f"{url}{delimiter}model=1"
|
440 |
|
441 |
+
|
442 |
def inject_base_url(url: str) -> str:
|
443 |
"""If link doesn't start with 'http', prepend BASE_URL so it's absolute."""
|
444 |
if url.startswith("http"):
|
445 |
return url
|
446 |
return f"{BASE_URL}{url}"
|
447 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
448 |
|
449 |
+
# Our default diagram, containing the "click" lines with /?q=...
|
450 |
DEFAULT_MERMAID = r"""
|
451 |
flowchart LR
|
452 |
U((User 😎)) -- "Talk 🗣️" --> LLM[LLM Agent 🤖\nExtract Info]
|
453 |
+
click U "/?q=User%20😎" "Open 'User 😎'" "_blank"
|
454 |
+
click LLM "/?q=LLM%20Agent%20Extract%20Info" "Open LLM" "_blank"
|
455 |
|
456 |
LLM -- "Query 🔍" --> HS[Hybrid Search 🔎\nVector+NER+Lexical]
|
457 |
+
click HS "/?q=Hybrid%20Search%20Vector+NER+Lexical" "Open HS" "_blank"
|
458 |
|
459 |
HS -- "Reason 🤔" --> RE[Reasoning Engine 🛠️\nNeuralNetwork+Medical]
|
460 |
+
click RE "/?q=Reasoning%20Engine%20NeuralNetwork+Medical" "Open RE" "_blank"
|
461 |
|
462 |
RE -- "Link 📡" --> KG((Knowledge Graph 📚\nOntology+GAR+RAG))
|
463 |
+
click KG "/?q=Knowledge%20Graph%20Ontology+GAR+RAG" "Open KG" "_blank"
|
464 |
"""
|
465 |
|
|
|
|
|
|
|
466 |
|
467 |
+
# BFS subgraph: we parse lines like A -- "Label" --> B
|
468 |
+
def parse_mermaid_edges(mermaid_text: str):
|
469 |
+
"""
|
470 |
+
🍿 parse_mermaid_edges:
|
471 |
+
- Find lines like: A -- "Label" --> B
|
472 |
+
- Return adjacency dict: edges[A] = [(label, B), ...]
|
473 |
+
"""
|
474 |
+
adjacency = {}
|
475 |
+
# e.g. U((User 😎)) -- "Talk 🗣️" --> LLM[LLM Agent 🤖\nExtract Info]
|
476 |
+
edge_pattern = re.compile(r'(\S+)\s*--\s*"([^"]*)"\s*-->\s*(\S+)')
|
477 |
+
for line in mermaid_text.split('\n'):
|
478 |
+
match = edge_pattern.search(line.strip())
|
479 |
+
if match:
|
480 |
+
nodeA, label, nodeB = match.groups()
|
481 |
+
if nodeA not in adjacency:
|
482 |
+
adjacency[nodeA] = []
|
483 |
+
adjacency[nodeA].append((label, nodeB))
|
484 |
+
return adjacency
|
485 |
+
|
486 |
+
|
487 |
+
def bfs_subgraph(adjacency, start_node, depth=1):
|
488 |
+
"""
|
489 |
+
🍎 bfs_subgraph:
|
490 |
+
- Gather edges up to 'depth' levels from start_node
|
491 |
+
- If depth=1, only direct edges from node
|
492 |
+
"""
|
493 |
+
from collections import deque
|
494 |
+
visited = set()
|
495 |
+
queue = deque([(start_node, 0)])
|
496 |
+
edges = []
|
497 |
+
|
498 |
+
while queue:
|
499 |
+
current, lvl = queue.popleft()
|
500 |
+
if current in visited:
|
501 |
+
continue
|
502 |
+
visited.add(current)
|
503 |
+
|
504 |
+
if current in adjacency and lvl < depth:
|
505 |
+
for (label, child) in adjacency[current]:
|
506 |
+
edges.append((current, label, child))
|
507 |
+
queue.append((child, lvl + 1))
|
508 |
+
|
509 |
+
return edges
|
510 |
+
|
511 |
+
|
512 |
+
def create_subgraph_mermaid(sub_edges, start_node):
|
513 |
+
"""
|
514 |
+
🍄 create_subgraph_mermaid:
|
515 |
+
- build a smaller flowchart snippet with edges from BFS
|
516 |
+
"""
|
517 |
+
sub_mermaid = "flowchart LR\n"
|
518 |
+
sub_mermaid += f" %% Subgraph for {start_node}\n"
|
519 |
+
if not sub_edges:
|
520 |
+
sub_mermaid += f" {start_node}\n"
|
521 |
+
sub_mermaid += " %% End of partial subgraph\n"
|
522 |
+
return sub_mermaid
|
523 |
+
for (A, label, B) in sub_edges:
|
524 |
+
sub_mermaid += f' {A} -- "{label}" --> {B}\n'
|
525 |
+
sub_mermaid += " %% End of partial subgraph\n"
|
526 |
+
return sub_mermaid
|
527 |
+
|
528 |
+
|
529 |
+
# =====================================================================================
|
530 |
+
# 7) MAIN APP
|
531 |
+
# =====================================================================================
|
532 |
def main():
|
533 |
+
st.set_page_config(page_title="Mermaid + BFS Subgraph + Full Logic", layout="wide")
|
534 |
|
535 |
# 1) Query param parsing
|
536 |
query_params = st.query_params
|
537 |
+
query_list = (query_params.get('q') or query_params.get('query') or [''])
|
538 |
+
q_or_query = query_list[0].strip() if len(query_list) > 0 else ""
|
539 |
+
|
540 |
+
# If 'action' param is present
|
541 |
+
if 'action' in query_params:
|
542 |
+
action_list = query_params['action']
|
543 |
+
if action_list:
|
544 |
+
action = action_list[0]
|
545 |
+
if action == 'show_message':
|
546 |
+
st.success("Showing a message because 'action=show_message' was found in the URL.")
|
547 |
+
elif action == 'clear':
|
548 |
+
clear_query_params()
|
549 |
+
|
550 |
+
# If there's a 'query=' param, display content or image
|
551 |
+
if 'query' in query_params:
|
552 |
+
query_val = query_params['query'][0]
|
553 |
+
display_content_or_image(query_val)
|
554 |
|
555 |
# 2) Let user pick ?model=1
|
556 |
st.sidebar.write("## Diagram Link Settings")
|
557 |
model_selected = st.sidebar.checkbox("Append ?model=1 to each link?")
|
558 |
|
559 |
+
# 3) We'll parse adjacency from DEFAULT_MERMAID, then do the injection for base URL
|
560 |
+
# and possible model param. We'll store the final mermaid code in session.
|
561 |
lines = DEFAULT_MERMAID.strip().split("\n")
|
562 |
new_lines = []
|
563 |
for line in lines:
|
564 |
+
if "click " in line and '"/?' in line:
|
565 |
+
# Try to parse out the URL via a simpler pattern
|
566 |
+
# e.g. click U "/?q=User%20😎" "Open 'User 😎'" "_blank"
|
567 |
+
# We'll do a quick re.split capturing 4 groups
|
568 |
+
# Example: [prefix, '/?q=User%20😎', "Open 'User 😎'", '_blank', remainder?]
|
569 |
+
pattern = r'(click\s+\S+\s+)"([^"]+)"\s+"([^"]+)"\s+"([^"]+)"'
|
570 |
+
match = re.match(pattern, line.strip())
|
571 |
+
if match:
|
572 |
+
prefix_part = match.group(1) # e.g. "click U "
|
573 |
+
old_url = match.group(2) # e.g. /?q=User%20😎
|
574 |
+
tooltip = match.group(3) # e.g. Open 'User 😎'
|
575 |
+
target = match.group(4) # e.g. _blank
|
576 |
+
|
577 |
+
# 1) base
|
578 |
new_url = inject_base_url(old_url)
|
579 |
+
# 2) model param
|
580 |
new_url = append_model_param(new_url, model_selected)
|
581 |
+
|
582 |
+
new_line = f'{prefix_part}"{new_url}" "{tooltip}" "{target}"'
|
|
|
583 |
new_lines.append(new_line)
|
584 |
else:
|
585 |
new_lines.append(line)
|
|
|
587 |
new_lines.append(line)
|
588 |
|
589 |
final_mermaid = "\n".join(new_lines)
|
590 |
+
adjacency = parse_mermaid_edges(final_mermaid)
|
591 |
+
|
592 |
+
# 4) If user clicked a shape => we show a partial subgraph as "SearchResult"
|
593 |
+
partial_subgraph_html = ""
|
594 |
+
if q_or_query:
|
595 |
+
st.info(f"process_text called with: {PromptPrefix}{q_or_query}")
|
596 |
+
|
597 |
+
# Attempt to find a node whose ID or label includes q_or_query:
|
598 |
+
# We'll do a naive approach: if q_or_query is substring ignoring spaces
|
599 |
+
possible_keys = []
|
600 |
+
for nodeKey in adjacency.keys():
|
601 |
+
# e.g. nodeKey might be 'U((User 😎))'
|
602 |
+
simplified_key = nodeKey.replace("\\n", " ").replace("[", "").replace("]", "").lower()
|
603 |
+
simplified_query = q_or_query.lower().replace("%20", " ")
|
604 |
+
if simplified_query in simplified_key:
|
605 |
+
possible_keys.append(nodeKey)
|
606 |
+
|
607 |
+
chosen_node = None
|
608 |
+
if possible_keys:
|
609 |
+
chosen_node = possible_keys[0]
|
610 |
+
else:
|
611 |
+
st.warning("No adjacency node matched the query param's text. Subgraph is empty.")
|
612 |
+
|
613 |
+
if chosen_node:
|
614 |
+
sub_edges = bfs_subgraph(adjacency, chosen_node, depth=1)
|
615 |
+
sub_mermaid = create_subgraph_mermaid(sub_edges, chosen_node)
|
616 |
+
partial_subgraph_html = generate_mermaid_html(sub_mermaid)
|
617 |
+
|
618 |
+
# 5) Show partial subgraph top-center if we have any
|
619 |
+
if partial_subgraph_html:
|
620 |
+
st.subheader("SearchResult Subgraph")
|
621 |
+
components.html(partial_subgraph_html, height=300, scrolling=False)
|
622 |
+
|
623 |
+
# 6) Render the top-centered *full* diagram
|
624 |
+
st.title("Full Mermaid Diagram (with Base URL + BFS partial subgraphs)")
|
625 |
|
|
|
|
|
626 |
diagram_html = generate_mermaid_html(final_mermaid)
|
627 |
components.html(diagram_html, height=400, scrolling=True)
|
628 |
|
629 |
+
# 7) Editor columns: Markdown & Mermaid
|
630 |
left_col, right_col = st.columns(2)
|
631 |
|
632 |
with left_col:
|
633 |
st.subheader("Markdown Side 📝")
|
634 |
if "markdown_text" not in st.session_state:
|
635 |
st.session_state["markdown_text"] = "## Hello!\nYou can type some *Markdown* here.\n"
|
636 |
+
markdown_text = st.text_area(
|
637 |
+
"Edit Markdown:",
|
638 |
+
value=st.session_state["markdown_text"],
|
639 |
+
height=300
|
640 |
+
)
|
641 |
st.session_state["markdown_text"] = markdown_text
|
642 |
|
643 |
+
# Buttons
|
644 |
colA, colB = st.columns(2)
|
645 |
with colA:
|
646 |
if st.button("🔄 Refresh Markdown"):
|
|
|
656 |
|
657 |
with right_col:
|
658 |
st.subheader("Mermaid Side 🧜♂️")
|
|
|
659 |
if "current_mermaid" not in st.session_state:
|
660 |
st.session_state["current_mermaid"] = final_mermaid
|
661 |
|
662 |
+
mermaid_input = st.text_area(
|
663 |
+
"Edit Mermaid Code:",
|
664 |
+
value=st.session_state["current_mermaid"],
|
665 |
+
height=300
|
666 |
+
)
|
667 |
colC, colD = st.columns(2)
|
668 |
with colC:
|
669 |
if st.button("🎨 Refresh Diagram"):
|
|
|
679 |
st.markdown("**Mermaid Source:**")
|
680 |
st.code(mermaid_input, language="python", line_numbers=True)
|
681 |
|
682 |
+
# 8) Show the galleries
|
683 |
st.markdown("---")
|
684 |
st.header("Media Galleries")
|
|
|
685 |
num_columns_images = st.slider("Choose Number of Image Columns", 1, 15, 5, key="num_columns_images")
|
686 |
display_images_and_wikipedia_summaries(num_columns_images)
|
687 |
|
688 |
num_columns_video = st.slider("Choose Number of Video Columns", 1, 15, 5, key="num_columns_video")
|
689 |
display_videos_and_links(num_columns_video)
|
690 |
|
691 |
+
# 9) Possibly show extended text interface
|
692 |
+
showExtendedTextInterface = False
|
693 |
+
if showExtendedTextInterface:
|
694 |
+
# e.g. display_glossary_grid(roleplaying_glossary)
|
695 |
+
# num_columns_text = st.slider("Choose Number of Text Columns", 1, 15, 4)
|
696 |
+
# display_buttons_with_scores(num_columns_text)
|
697 |
+
pass
|
698 |
+
|
699 |
+
# 10) Render the file sidebar
|
700 |
FileSidebar()
|
701 |
|
702 |
+
# 11) Random title at bottom
|
703 |
titles = [
|
704 |
"🧠🎭 Semantic Symphonies & Episodic Encores",
|
705 |
"🌌🎼 AI Rhythms of Memory Lane",
|
|
|
712 |
]
|
713 |
st.markdown(f"**{random.choice(titles)}**")
|
714 |
|
|
|
715 |
|
716 |
if __name__ == "__main__":
|
717 |
main()
|