awacke1 commited on
Commit
32beef2
·
verified ·
1 Parent(s): 6142169

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +193 -741
app.py CHANGED
@@ -11,15 +11,14 @@ from urllib.parse import quote
11
  from gradio_client import Client
12
  from datetime import datetime
13
 
14
- # 🌳🤖 AIKnowledgeTreeBuilder - Because every app needs a good costume!
15
-
16
  Site_Name = 'AI Knowledge Tree Builder 📈🌿 Grow Smarter with Every Click'
17
  title = "🌳✨AI Knowledge Tree Builder🛠️🤓"
18
  helpURL = 'https://huggingface.co/spaces/awacke1/AIKnowledgeTreeBuilder/'
19
  bugURL = 'https://huggingface.co/spaces/awacke1/AIKnowledgeTreeBuilder/'
20
  icons = '🌳✨🛠️🤓'
21
 
22
- SidebarOutline="""🌳🤖 Designed with the following tenets:
23
  1 📱 **Portability** - Universal access via any device & link sharing
24
  2. ⚡ **Speed of Build** - Rapid deployments < 2min to production
25
  3. 🔗 **Linkiness** - Programmatic access to AI knowledge sources
@@ -43,7 +42,6 @@ st.set_page_config(
43
 
44
  st.sidebar.markdown(SidebarOutline)
45
 
46
-
47
  # Initialize session state variables
48
  if 'selected_file' not in st.session_state:
49
  st.session_state.selected_file = None
@@ -52,519 +50,7 @@ if 'view_mode' not in st.session_state:
52
  if 'files' not in st.session_state:
53
  st.session_state.files = []
54
 
55
-
56
- BiologyAndLevel36MagicUsers="""
57
- 0. Biology Core Rules and Future Exceptions
58
- 1. Central Dogma DNA RNA Protein
59
- - Current CRISPR RNA editing 🧪
60
- - Research Gene therapy siRNA 🔬
61
- - Future Programmable genetics 🚀
62
-
63
- 2. Cell Origin
64
- - Current iPSCs organoids 🦠
65
- - Research Synthetic cells 🔬
66
- - Future De novo cell creation 🚀
67
-
68
- 3. Form Function
69
- - Current Bioprinting 🫀
70
- - Research 4D printing 🔬
71
- - Future Self assembling structures 🚀
72
-
73
- 4. Homeostasis
74
- - Current Artificial pancreas 🤖
75
- - Research Nanorobots 🔬
76
- - Future Autonomous regulation 🚀
77
-
78
- 5. Evolution
79
- - Current Directed evolution 🧫
80
- - Research Synthetic biology 🔬
81
- - Future Accelerated adaptation 🚀
82
-
83
- 6. Energy Conservation
84
- - Current Biofuel cells ⚡
85
- - Research Quantum biology 🔬
86
- - Future Biological perpetual motion 🚀
87
-
88
- 7. Cellular Life
89
- - Current Organoid systems 🔮
90
- - Research Hybrid cells 🔬
91
- - Future Silicon based life 🚀
92
-
93
- 8. Inheritance Patterns
94
- - Current Gene drives 🧩
95
- - Research Epigenetic control 🔬
96
- - Future Designed inheritance 🚀
97
-
98
- 9. Energy Requirements
99
- - Current Metabolic engineering 🔋
100
- - Research Synthetic photosynthesis 🔬
101
- - Future Zero energy life 🚀
102
-
103
- 10. Random Mutation
104
- - Current Base editing 🎯
105
- - Research Mutation prediction 🔬
106
- - Future Controlled evolution 🚀
107
-
108
- 11. Carbon Based Life
109
- - Current Alternative biochemistry 💎
110
- - Research Silicon biology 🔬
111
- - Future Non carbon life 🚀
112
-
113
- 12. Size Limitations
114
- - Current Nanostructures 📏
115
- - Research Quantum biology 🔬
116
- - Future Scalable organisms 🚀
117
-
118
- 13. Species Interdependence
119
- - Current Synthetic ecosystems 🌿
120
- - Research Artificial symbiosis 🔬
121
- - Future Independent life 🚀
122
-
123
- 14. Stimulus Response
124
- - Current Brain computer interfaces 🧠
125
- - Research Neural engineering 🔬
126
- - Future Direct consciousness control 🚀
127
-
128
- 15. Development Complexity
129
- - Current Accelerated growth 🌱
130
- - Research Development control 🔬
131
- - Future Instant maturation 🚀
132
-
133
- 16. Population Growth
134
- - Current Population control 📊
135
- - Research Sustainable ecosystems 🔬
136
- - Future Perfect equilibrium 🚀
137
-
138
- 17. Energy Flow
139
- - Current Enhanced photosynthesis 🌞
140
- - Research Energy optimization 🔬
141
- - Future Perpetual systems 🚀
142
-
143
- 18. Environmental Adaptation
144
- - Current Climate resistance 🌍
145
- - Research Universal adaptation 🔬
146
- - Future Environment independence 🚀
147
-
148
- 19. Genetic Inheritance
149
- - Current Gene editing 🧬
150
- - Research Trait programming 🔬
151
- - Future Perfect inheritance 🚀
152
-
153
- 20. Reproduction
154
- - Current Artificial wombs 👶
155
- - Research Cloning advances 🔬
156
- - Future Asexual human reproduction 🚀
157
-
158
- 21. Aging Death
159
- - Current Longevity therapy ⏰
160
- - Research Age reversal 🔬
161
- - Future Biological immortality 🚀
162
- """
163
-
164
- AITopicsToInnovate1="""
165
- 1. Major AI Industry Players 🌐
166
- 1. Research Leaders 🎯
167
- - OpenAI: GPT-4 DALL-E Foundation Models 🔵
168
- - Google: PaLM Gemini LLMs 🟦
169
- - Anthropic: Claude Constitutional AI ⚡
170
- - Meta: LLaMA Open Source LLMs 👤
171
- - xAI: Grok Conversational AI 🤖
172
-
173
- 2. Technical AI Development 🛠️
174
- 1. Architecture Advances 💫
175
- - Transformer Models Attention Mechanisms 🧠
176
- - Mixture of Experts MoE Architecture 🎪
177
- - Sparse Neural Networks 🕸️
178
- - Multi-modal LLM Systems 🌈
179
- - Flash Attention Optimization ⚔️
180
-
181
- 2. Training Methodologies 📚
182
- - LLM Supervised Fine-tuning 👨‍🏫
183
- - RLHF Reward Models 🤝
184
- - Constitutional AI Training 📜
185
- - RLAIF Feedback Models 🔄
186
- - Synthetic Data LLM Training 🎲
187
- - Chain of Thought Prompting 🧩
188
- - Tree of Thoughts Reasoning 🌳
189
-
190
- 3. Post-Training Implementation 🔧
191
- - Neural Network Distillation 🧪
192
- - LLM Quantization Methods 📊
193
- - Neural Network Pruning ���️
194
- - Knowledge Distillation Transfer 📖
195
- - Few-shot LLM Learning 🎯
196
-
197
- 3. Mechanistic Interpretability 🔬
198
- 1. Core Concepts 💡
199
- - Neural Network Growth Analysis 🌱
200
- - LLM Architecture Analysis 🏗️
201
- - Training Loss Optimization 🎨
202
- - Neural Network Analogies 🧬
203
-
204
- 2. Technical Features 📐
205
- - LLM Linear Representations ➡️
206
- - Neural Vector Arithmetic 🔢
207
- - Neural Activation Patterns 🌊
208
- - LLM Feature Detection 🔍
209
- - Neural Sparse Autoencoders 🎭
210
-
211
- 3. Network Analysis 🕵️
212
- - LLM Induction Heads 👀
213
- - Transformer Attention Analysis 🎪
214
- - Neural Circuit Analysis 🔌
215
- - LLM Feature Visualization 📈
216
- - Neural Concept Directions 🎳
217
-
218
- 4. Future AI Developments 🚀
219
- 1. AGI Timeline ⏰
220
- - AGI Capability Projections 📅
221
- - Neural Hardware Scaling 💾
222
- - LLM Training Data Limits 📉
223
- - AI Compute Resources 🗺️
224
-
225
- 2. Integration Fields 🎡
226
- - AI Biology Integration 🔮
227
- - AI Drug Discovery Systems 💊
228
- - AI Clinical Trial Analysis 🏥
229
- - AI Code Generation 🤹
230
- - AI Scientific Discovery 🧮
231
-
232
- 5. Industry Best Practices 💎
233
- 1. AI Team Building 🏢
234
- - AI Talent Development 👥
235
- - AI Research Alignment 🎪
236
- - AI Team Scaling 📊
237
- - AI Research Culture 🌟
238
-
239
- 2. AI Research Qualities 🎓
240
- - AI Research Methodology 🧭
241
- - AI Experimentation Protocols 🗝️
242
- - AI Innovation Thinking 💫
243
- - AI Testing Framework ⚖️
244
-
245
- 3. AI Safety Standards 🛡️
246
- - LLM Behavioral Specifications 📋
247
- - AI Safety Guidelines 🎮
248
- - AI Ethics Framework ⛑️
249
- - AI Industry Standards 🤲
250
-
251
- 6. Emerging Research Areas 🔮
252
- 1. Technical Focus 🎯
253
- - LLM Long Context Learning ⏳
254
- - LLM Multi-agent Interaction 👾
255
- - AI Evaluation Metrics 📌
256
- - Neural Interpretability Methods 🔭
257
-
258
- 2. AI Applications 💼
259
- - AI Automated Research 🧫
260
- - AI Code Synthesis ⌨️
261
- - AI Biological Modeling 🧯
262
- - AI Medical Diagnostics 💉
263
-
264
- 7. Model Intelligence 🧿
265
- 1. LLM System Development 🎪
266
- - LLM Prompt Engineering 📝
267
- - LLM Response Generation ♟️
268
- - LLM Behavioral Training 🎹
269
- - LLM Personality Development 🎪
270
-
271
- 2. LLM User Interaction 🎭
272
- - LLM Autonomy Alignment 🎪
273
- - LLM Safety Boundaries 🔒
274
- - LLM Communication Patterns 🗣️
275
- - LLM Performance Tuning 🎢
276
- """
277
-
278
- Multiplayer_Custom_Hosting_Game_Servers_For_Simulated_Worlds = """
279
-
280
-
281
- 0. Fantasy Domain Introduction
282
- 1. Setting the Scene
283
- - Current Create a high-fantasy realm with unique ecosystems, magical phenomena, and cultural diversity 🏞️
284
- - Research Add domain-specific entities like mythical creatures, enchanted terrains, or ancient artifacts 🧝‍♂️
285
- - Future Fully AI-generated interactive worldbuilding 🚀
286
-
287
- 2. Archetypal Overview
288
- - Current Write a summary of a classic D&D character archetype 🗡️
289
- - Research Add roles, special abilities, and motivations for NPC creation 🔮
290
- - Future AI-enhanced roleplay character dynamics 🚀
291
-
292
- 3. Entity-Focused Narrative Creation
293
- 1. Monster Mythology
294
- - Current Create monsters with unique traits like ‘Crimson Obelisk Wurm’ 🐉
295
- - Research Add lore and origin stories with detailed classifications 🔬
296
- - Future Dynamic AI monster lore generators 🚀
297
- 2. Artifact Legacy
298
- - Current Describe legendary artifacts like ‘The Aetherflame Prism’ 🧙‍♂️
299
- - Research Add historical narratives and effects on wielders 🔬
300
- - Future AI-designed item crafting 🚀
301
- 3. Heroic Figures
302
- - Current Write backstories for heroic figures like ‘Syran Stormblade’ ⚔️
303
- - Research Integrate figures into broader campaigns and their achievements 🔬
304
- - Future Procedurally generated heroes 🚀
305
-
306
- 4. Immersive Dialogues and Roleplay
307
- 1. NPC Conversations
308
- - Current Generate realistic NPC dialogues like in ‘The Ghostwood Forest’ 🗨️
309
- - Research Add depth to NPC motivations and interactions 🔬
310
- - Future AI-led adaptive NPC behavior 🚀
311
- 2. Villain Confrontations
312
- - Current Design confrontations with unique villains like ‘Eldrazar the Timeless’ 👹
313
- - Research Layer villains with complex personalities and backstories 🔬
314
- - Future AI-driven antagonist strategy generation 🚀
315
-
316
- 5. World-Building
317
- 1. Cultural Narratives
318
- - Current Describe civilizations like ‘The Emberkin’ 🌋
319
- - Research Add societal structures and traditions 🔬
320
- - Future AI-created evolving societies 🚀
321
- 2. Mythic Locations
322
- - Current Create locations like ‘The Whispering Wastes’ 🏜️
323
- - Research Integrate locations into broader world lore 🔬
324
- - Future Fully explorable AI worlds 🚀
325
- 3. Dimensional Realms
326
- - Current Design parallel dimensions like ‘The Veil of Shadows’ 🌌
327
- - Research Add magical laws and inhabitants 🔬
328
- - Future AI-generated multiverses 🚀
329
-
330
- 6. Quests and Campaigns
331
- 1. Campaign Arcs
332
- - Current Design multi-part campaigns like retrieving ‘The Obsidian Crown’ 🎯
333
- - Research Add NPC, obstacle, and objective integration 🔬
334
- - Future AI-created campaign blueprints 🚀
335
- 2. Encounter Design
336
- - Current Create encounters like facing ‘The Frostbane Golem’ 🧊
337
- - Research Add detailed strategies and reward systems 🔬
338
- - Future AI-led encounter simulations 🚀
339
- 3. Legendary Betrayals
340
- - Current Write scenarios with plot twists, e.g., ‘Thane Vorthak’s betrayal’ 🤔
341
- - Research Add motivations and dramatic tension 🔬
342
- - Future AI-generated unpredictable twists 🚀
343
-
344
- 7. AI Collaboration for Dual Perspectives
345
- 1. Scene Duality
346
- - Current Generate battle scenes like adventurers vs. a Beholder 🛡️
347
- - Research Rewrite scenes from different perspectives 🔬
348
- - Future AI-enhanced multi-perspective storytelling 🚀
349
- 2. Tag Comparison
350
- - Current Classify entities like MON, LOC, ART using NER tags 🏷️
351
- - Research Refine classifications with AI collaboration 🔬
352
- - Future Real-time AI entity extraction 🚀
353
-
354
- 8. Experimental Storytelling Techniques
355
- 1. Lore Fusion
356
- - Current Combine legends like ‘Stormcallers’ and ‘Voidseers’ 🌀
357
- - Research Create shared histories with dynamic lore layers 🔬
358
- - Future AI-driven mythos merging 🚀
359
- 2. Procedural Creativity
360
- - Current Generate tables of random D&D entities 📊
361
- - Research Add adaptive tags for dynamic storytelling 🔬
362
- - Future Procedural AI entity generation 🚀
363
-
364
- 9. Advanced NER Applications
365
- 1. Custom Tags
366
- - Current Create tags like SPELL and TRAP for dungeon-specific entities 🔗
367
- - Research Train AI on niche tags for unique entity extraction 🔬
368
- - Future AI-driven custom tag creation 🚀
369
- 2. Entity Extraction
370
- - Current Extract entities from passages like ‘The Sunken Crypts’ 🏚️
371
- - Research Add advanced AI classification accuracy 🔬
372
- - Future Automated fine-tuning for AI models 🚀
373
- 3. Dimensional Entities
374
- - Current Classify niche entities like ‘Voidwalkers’ 🌠
375
- - Research Train models for multi-dimensional lore 🔬
376
- - Future AI multiverse exploration 🚀
377
-
378
-
379
-
380
-
381
-
382
- Active Multiplayer Games 2024 🎮
383
-
384
- 1 Traditional MMORPGs 🗡️
385
-
386
- 1.1 Major MMORPGs 🏰
387
- - Final Fantasy XIV Dawntrail 2024 ⚔️
388
- - Advanced Job System Rework 🎭
389
- - Cross Platform Integration 🎪
390
- - New Housing Districts 🏘️
391
-
392
- - World of Warcraft 2024 Season 🐲
393
- - Dragon Combat System 🦋
394
- - Cross Faction Features ⚜️
395
- - Mythic Plus Seasons 🏆
396
-
397
- - Elder Scrolls Online Gold Road 🗝️
398
- - Dynamic Event System 🌟
399
- - Housing Construction 🏛️
400
- - Champion System 2.0 📊
401
-
402
- - Lost Ark Western T4 Update ⚡
403
- - Legion Raid Content 👾
404
- - Island Adventure System 🏝️
405
- - Class Balance Rework 🔰
406
-
407
- - Black Desert Online Remaster 🎪
408
- - Combat System Update 🎯
409
- - Node Empire System 🏹
410
- - Life Skill Evolution 🌳
411
-
412
- 1.2 Emerging MMORPGs 🌠
413
- - Throne and Liberty Launch 👑
414
- - Weather Combat System 🌦️
415
- - Territory Wars 🗺️
416
- - Transformation System 🐉
417
-
418
- - Pax Dei Medieval MMO ⚔️
419
- - City Management 🏰
420
- - Faith Based Magic ✨
421
- - Global Trading 💎
422
-
423
- - Blue Protocol Western Release 🌌
424
- - Action Combat Design 🎭
425
- - Class Change System ⚡
426
- - Dungeon Scaling 🗼
427
-
428
- 2 Survival MMOs 🏹
429
-
430
- 2.1 Established Survival 🛡️
431
- - Rust 2024 Updates 🦾
432
- - Electricity Programming 💡
433
- - Vehicle System Update 🚗
434
- - Automated Defenses ⚡
435
-
436
- - ARK Survival Ascended 🦖
437
- - Cross ARK System 🌐
438
- - Creature Breeding 2.0 🥚
439
- - Base Defense Network 🏰
440
-
441
- - DayZ 2024 Content 🧟
442
- - Medical System Update 💉
443
- - Disease Mechanics 🦠
444
- - Base Building 2.0 🏗️
445
-
446
- - 7 Days to Die Alpha 22 🏚️
447
- - Physics Engine Update 💥
448
- - AI Pathfinding System 🧠
449
- - Vehicle Customization 🚙
450
-
451
- 2.2 New Survival MMOs 🆕
452
- - Once Human Launch 🧬
453
- - Mutation System 🧪
454
- - Base Building Tech 🏭
455
- - Weather Impact System 🌪️
456
-
457
- - Nightingale Release 🌙
458
- - Portal Realm System 🌌
459
- - Victorian Crafting 🎩
460
- - Fae World Design 🧚
461
-
462
- 3 Hybrid MMOs 🎯
463
-
464
- 3.1 Looter Shooters 🔫
465
- - Destiny 2 2024 Season 🛸
466
- - Build System 3.0 🛠️
467
- - Raid Mechanics ⭐
468
- - Season Structure 📈
469
-
470
- - The Division 2 Year 6 🏙️
471
- - Loadout Expansion 🎒
472
- - Dark Zone Update 🌃
473
- - Manhunt System 🎯
474
-
475
- - Warframe 2024 Update 🤖
476
- - Movement Tech 2.0 🏃
477
- - Mod System Rework ⚙️
478
- - Open World Expansion 🌅
479
-
480
- 3.2 Action RPG MMOs 💫
481
- - Path of Exile 2 Beta 💎
482
- - Gem System Rework 💫
483
- - New Skill Tree 🌲
484
- - League Content 🏆
485
-
486
- - Diablo 4 Season Structure 😈
487
- - Season Journey System 🎭
488
- - World Boss Events 🐲
489
- - PvP Territories 🗡️
490
-
491
- 4 Simulation MMOs 🌍
492
-
493
- 4.1 Space Simulation 🚀
494
- - EVE Online 2024 🛸
495
- - Corporation Warfare 🏴‍☠️
496
- - Market System Update 📊
497
- - Fleet Operations 🚢
498
-
499
- - Elite Dangerous Update 🌌
500
- - Ground Combat System 👨‍🚀
501
- - Fleet Carrier Content ⭐
502
- - Planet Exploration 🪐
503
-
504
- - Star Citizen Alpha 🛸
505
- - Persistent Universe 🌍
506
- - Ship Combat Update ⚔️
507
- - Trading System 2.0 💰
508
-
509
- 4.2 World Simulation 🌎
510
- - New World Eternal 🗺️
511
- - Territory System 🏰
512
- - Crafting Update 🛠️
513
- - War System 2.0 ⚔️
514
-
515
- - Albion Online 2024 🏹
516
- - Guild Warfare Update ⚔️
517
- - Economy System 2.0 💰
518
- - Territory Control 🏰
519
-
520
- 5 Unique Multiplayer Games 🎲
521
-
522
- 5.1 Adventure Multiplayer 🗺️
523
- - Sea of Thieves 2024 ⛵
524
- - Ship Combat Physics 🌊
525
- - Crew Management 🏴‍☠️
526
- - World Events 🎪
527
-
528
- - Valheim Updates ⚡
529
- - Building System 2.0 🏗️
530
- - Boss Progression 👹
531
- - Exploration Update 🗺️
532
-
533
- 5.2 Combat Focused 🗡️
534
- - Mordhau 2024 ⚔️
535
- - Combat Physics Update 🤺
536
- - Map System Rework 🏰
537
- - Tournament System 🏆
538
-
539
- - For Honor Year 8 🛡️
540
- - Faction War Update ⚔️
541
- - Hero Rework System 🎭
542
- - Seasonal Content 🌟
543
-
544
- 6 Upcoming 2024 Games 🔮
545
-
546
- 6.1 Launching Soon 📅
547
- - Gray Zone Warfare 🎖️
548
- - Tactical Systems 🎯
549
- - Base Operations 🏢
550
- - Territory Control 🗺️
551
-
552
- - Fractured Online 🌟
553
- - City Building 🏗️
554
- - Knowledge System 📚
555
- - Player Economy 💰
556
-
557
- 6.2 In Development 🛠️
558
- - Ashes of Creation 🏰
559
- - Node System 🌱
560
- - Castle Siege ⚔️
561
- - Caravan System 🐪
562
-
563
- - Pantheon Rise of the Fallen 🌅
564
- - Climate System 🌦️
565
- - Group Content Focus 👥
566
- - Perception System 👁️
567
- """
568
 
569
  def get_display_name(filename):
570
  """Extract text from parentheses or return filename as is."""
@@ -582,30 +68,19 @@ def get_time_display(filename):
582
 
583
  def sanitize_filename(text):
584
  """Create a safe filename from text while preserving spaces."""
585
- # First replace unsafe characters with spaces
586
  safe_text = re.sub(r'[^\w\s-]', ' ', text)
587
- # Remove any multiple spaces
588
  safe_text = re.sub(r'\s+', ' ', safe_text)
589
- # Trim leading/trailing spaces
590
  safe_text = safe_text.strip()
591
- return safe_text[:50] # Limit length to 50 chars
592
 
593
  def generate_timestamp_filename(query):
594
  """Generate filename with format: 1103AM 11032024 (Query).md"""
595
- # Get current time in Central timezone
596
  central = pytz.timezone('US/Central')
597
  current_time = datetime.now(central)
598
-
599
- # Format the timestamp parts
600
- time_str = current_time.strftime("%I%M%p") # 1103AM format
601
- date_str = current_time.strftime("%m%d%Y") # 11032024 format
602
-
603
- # Clean up the query for filename - now preserving spaces
604
  safe_query = sanitize_filename(query)
605
-
606
- # Construct filename: "1103AM 11032024 (Input with spaces).md"
607
  filename = f"{time_str} {date_str} ({safe_query}).md"
608
-
609
  return filename
610
 
611
  def delete_file(file_path):
@@ -620,8 +95,6 @@ def delete_file(file_path):
620
  def save_ai_interaction(query, ai_result, is_rerun=False):
621
  """Save AI interaction to a markdown file with new filename format."""
622
  filename = generate_timestamp_filename(query)
623
-
624
- # Format the content differently for rerun vs normal query
625
  if is_rerun:
626
  content = f"""# Rerun Query
627
  Original file content used for rerun:
@@ -637,8 +110,6 @@ Original file content used for rerun:
637
  ## AI Response
638
  {ai_result}
639
  """
640
-
641
- # Save to file
642
  try:
643
  with open(filename, 'w', encoding='utf-8') as f:
644
  f.write(content)
@@ -659,50 +130,139 @@ def get_file_download_link(file_path):
659
  st.error(f"Error creating download link: {e}")
660
  return None
661
 
662
- def extract_terms(markdown_text):
663
- """Parse markdown text and extract terms."""
664
- lines = markdown_text.strip().split('\n')
665
- terms = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
666
  for line in lines:
667
- line = re.sub(r'^[#*\->\d\.\s]+', '', line).strip()
668
- if line:
669
- terms.append(line)
670
- return terms
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
671
 
672
- def extract_urls(text):
673
- try:
674
- date_pattern = re.compile(r'### (\d{2} \w{3} \d{4})')
675
- abs_link_pattern = re.compile(r'\[(.*?)\]\((https://arxiv\.org/abs/\d+\.\d+)\)')
676
- pdf_link_pattern = re.compile(r'\[⬇️\]\((https://arxiv\.org/pdf/\d+\.\d+)\)')
677
- title_pattern = re.compile(r'### \d{2} \w{3} \d{4} \| \[(.*?)\]')
678
- date_matches = date_pattern.findall(text)
679
- abs_link_matches = abs_link_pattern.findall(text)
680
- pdf_link_matches = pdf_link_pattern.findall(text)
681
- title_matches = title_pattern.findall(text)
682
-
683
- # markdown with the extracted fields
684
- markdown_text = ""
685
- for i in range(len(date_matches)):
686
- date = date_matches[i]
687
- title = title_matches[i]
688
- abs_link = abs_link_matches[i][1]
689
- pdf_link = pdf_link_matches[i]
690
- markdown_text += f"**Date:** {date}\n\n"
691
- markdown_text += f"**Title:** {title}\n\n"
692
- markdown_text += f"**Abstract Link:** [{abs_link}]({abs_link})\n\n"
693
- markdown_text += f"**PDF Link:** [{pdf_link}]({pdf_link})\n\n"
694
- markdown_text += "---\n\n"
695
- return markdown_text
696
-
697
- except:
698
- st.write('.')
699
- return ''
700
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
701
 
702
- # HTML5 based Speech Synthesis (Text to Speech in Browser)
703
  @st.cache_resource
704
  def SpeechSynthesis(result):
705
- documentHTML5='''
706
  <!DOCTYPE html>
707
  <html>
708
  <head>
@@ -719,8 +279,8 @@ def SpeechSynthesis(result):
719
  <h1>🔊 Read It Aloud</h1>
720
  <textarea id="textArea" rows="10" cols="80">
721
  '''
722
- documentHTML5 = documentHTML5 + result
723
- documentHTML5 = documentHTML5 + '''
724
  </textarea>
725
  <br>
726
  <button onclick="readAloud()">🔊 Read Aloud</button>
@@ -729,124 +289,20 @@ def SpeechSynthesis(result):
729
  '''
730
  components.html(documentHTML5, width=1280, height=300)
731
 
732
- def display_terms_with_links(terms):
733
- """Display terms with various search links."""
734
- search_urls = {
735
- "📚📖ArXiv": lambda k: f"/?q={quote(k)}", # Academic/paper theme
736
- "🔮<sup>Google</sup>": lambda k: f"https://www.google.com/search?q={quote(k)}", # Crystal ball for search
737
- "📺<sup>Youtube</sup>": lambda k: f"https://www.youtube.com/results?search_query={quote(k)}", # TV for videos
738
- "🔭<sup>Bing</sup>": lambda k: f"https://www.bing.com/search?q={quote(k)}", # Telescope for search
739
- "💡<sup>Truth</sup>": lambda k: f"https://truthsocial.com/search?q={quote(k)}", # Light bulb for insight
740
- "📱X": lambda k: f"https://twitter.com/search?q={quote(k)}", # Phone for social media
741
- }
742
- for term in terms:
743
- links_md = ' '.join([f"[{emoji}]({url(term)})" for emoji, url in search_urls.items()])
744
- st.markdown(f"- **{term}** {links_md}", unsafe_allow_html=True)
745
-
746
- def search_arxiv(query):
747
-
748
- st.write("Performing AI Lookup...")
749
- client = Client("awacke1/Arxiv-Paper-Search-And-QA-RAG-Pattern")
750
-
751
- result1 = client.predict(
752
- prompt=query,
753
- llm_model_picked="mistralai/Mixtral-8x7B-Instruct-v0.1",
754
- stream_outputs=True,
755
- api_name="/ask_llm"
756
- )
757
- st.markdown("### Mixtral-8x7B-Instruct-v0.1 Result")
758
- st.markdown(result1)
759
-
760
- result2 = client.predict(
761
- prompt=query,
762
- llm_model_picked="mistralai/Mistral-7B-Instruct-v0.2",
763
- stream_outputs=True,
764
- api_name="/ask_llm"
765
- )
766
- st.markdown("### Mistral-7B-Instruct-v0.2 Result")
767
- st.markdown(result2)
768
- combined_result = f"{result1}\n\n{result2}"
769
- #return combined_result
770
-
771
- return responseall
772
-
773
- # Function to generate a filename based on prompt and time (because names matter 🕒)
774
- def generate_filename(prompt, file_type):
775
- central = pytz.timezone('US/Central')
776
- safe_date_time = datetime.now(central).strftime("%m%d_%H%M")
777
- safe_prompt = re.sub(r'\W+', '_', prompt)[:90]
778
- return f"{safe_date_time}_{safe_prompt}.{file_type}"
779
-
780
- # Function to create and save a file (and avoid the black hole of lost data 🕳)
781
- def create_file(filename, prompt, response):
782
- with open(filename, 'w', encoding='utf-8') as file:
783
- file.write(prompt + "\n\n" + response)
784
-
785
-
786
-
787
- def perform_ai_lookup(query):
788
- start_time = time.strftime("%Y-%m-%d %H:%M:%S")
789
- client = Client("awacke1/Arxiv-Paper-Search-And-QA-RAG-Pattern")
790
- response1 = client.predict(
791
- query,
792
- 20,
793
- "Semantic Search",
794
- "mistralai/Mixtral-8x7B-Instruct-v0.1",
795
- api_name="/update_with_rag_md"
796
- )
797
- Question = '### 🔎 ' + query + '\r\n' # Format for markdown display with links
798
- References = response1[0]
799
- ReferenceLinks = extract_urls(References)
800
-
801
- RunSecondQuery = True
802
- results=''
803
- if RunSecondQuery:
804
- # Search 2 - Retrieve the Summary with Papers Context and Original Query
805
- response2 = client.predict(
806
- query,
807
- "mistralai/Mixtral-8x7B-Instruct-v0.1",
808
- True,
809
- api_name="/ask_llm"
810
- )
811
- if len(response2) > 10:
812
- Answer = response2
813
- SpeechSynthesis(Answer)
814
- # Restructure results to follow format of Question, Answer, References, ReferenceLinks
815
- results = Question + '\r\n' + Answer + '\r\n' + References + '\r\n' + ReferenceLinks
816
- st.markdown(results)
817
-
818
- st.write('🔍Run of Multi-Agent System Paper Summary Spec is Complete')
819
- end_time = time.strftime("%Y-%m-%d %H:%M:%S")
820
- start_timestamp = time.mktime(time.strptime(start_time, "%Y-%m-%d %H:%M:%S"))
821
- end_timestamp = time.mktime(time.strptime(end_time, "%Y-%m-%d %H:%M:%S"))
822
- elapsed_seconds = end_timestamp - start_timestamp
823
- st.write(f"Start time: {start_time}")
824
- st.write(f"Finish time: {end_time}")
825
- st.write(f"Elapsed time: {elapsed_seconds:.2f} seconds")
826
-
827
-
828
- filename = generate_filename(query, "md")
829
- create_file(filename, query, results)
830
- return results
831
-
832
  def display_file_content(file_path):
833
  """Display file content with editing capabilities."""
834
  try:
835
  with open(file_path, 'r', encoding='utf-8') as f:
836
  content = f.read()
837
-
838
  if st.session_state.view_mode == 'view':
839
- # Display as markdown when viewing
840
  st.markdown(content)
841
  else:
842
- # Edit functionality
843
  edited_content = st.text_area(
844
  "Edit content",
845
  content,
846
  height=400,
847
  key=f"edit_{os.path.basename(file_path)}"
848
  )
849
-
850
  if st.button("Save Changes", key=f"save_{os.path.basename(file_path)}"):
851
  try:
852
  with open(file_path, 'w', encoding='utf-8') as f:
@@ -860,62 +316,43 @@ def display_file_content(file_path):
860
  def file_management_sidebar():
861
  """Redesigned sidebar with improved layout and additional functionality."""
862
  st.sidebar.title("📁 File Management")
863
-
864
- # Get list of .md files excluding README.md
865
  md_files = [file for file in glob.glob("*.md") if file.lower() != 'readme.md']
866
  md_files.sort()
867
  st.session_state.files = md_files
868
-
869
  if md_files:
870
  st.sidebar.markdown("### Saved Files")
871
  for idx, file in enumerate(md_files):
872
- st.sidebar.markdown("---") # Separator between files
873
-
874
- # Display time
875
  st.sidebar.text(get_time_display(file))
876
-
877
- # Display download link with simplified text
878
  download_link = get_file_download_link(file)
879
  if download_link:
880
  st.sidebar.markdown(download_link, unsafe_allow_html=True)
881
-
882
- # Action buttons in a row
883
  col1, col2, col3, col4 = st.sidebar.columns(4)
884
-
885
  with col1:
886
  if st.button("📄View", key=f"view_{idx}"):
887
  st.session_state.selected_file = file
888
  st.session_state.view_mode = 'view'
889
-
890
  with col2:
891
  if st.button("✏️Edit", key=f"edit_{idx}"):
892
  st.session_state.selected_file = file
893
  st.session_state.view_mode = 'edit'
894
-
895
  with col3:
896
  if st.button("🔄Run", key=f"rerun_{idx}"):
897
  try:
898
  with open(file, 'r', encoding='utf-8') as f:
899
  content = f.read()
900
-
901
- # Prepare the prompt with the prefix
902
  rerun_prefix = """For the markdown below reduce the text to a humorous fun outline with emojis and markdown outline levels in outline that convey all the facts and adds wise quotes and funny statements to engage the reader:
903
 
904
  """
905
  full_prompt = rerun_prefix + content
906
-
907
- # Perform AI lookup and save results
908
  ai_result = perform_ai_lookup(full_prompt)
909
  saved_file = save_ai_interaction(content, ai_result, is_rerun=True)
910
-
911
  if saved_file:
912
  st.success(f"Created fun version in {saved_file}")
913
  st.session_state.selected_file = saved_file
914
  st.session_state.view_mode = 'view'
915
-
916
  except Exception as e:
917
  st.error(f"Error during rerun: {e}")
918
-
919
  with col4:
920
  if st.button("🗑️Delete", key=f"delete_{idx}"):
921
  if delete_file(file):
@@ -923,9 +360,7 @@ def file_management_sidebar():
923
  st.rerun()
924
  else:
925
  st.error(f"Failed to delete {file}")
926
-
927
  st.sidebar.markdown("---")
928
- # Option to create a new markdown file
929
  if st.sidebar.button("📝 Create New Note"):
930
  filename = generate_timestamp_filename("New Note")
931
  with open(filename, 'w', encoding='utf-8') as f:
@@ -943,22 +378,68 @@ def file_management_sidebar():
943
  st.session_state.selected_file = filename
944
  st.session_state.view_mode = 'edit'
945
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
946
  def main():
947
  st.markdown("### AI Knowledge Tree Builder 🧠🌱 Cultivate Your AI Mindscape!")
948
-
949
- # Process query parameters and AI lookup first
950
  query_params = st.query_params
951
  query = query_params.get('q', '')
952
- show_initial_content = True # Flag to control initial content display
953
 
954
- # First priority: Handle active query
955
  if query:
956
- show_initial_content = False # Hide initial content when showing query results
957
  st.write(f"### Search query received: {query}")
958
  try:
959
  ai_result = perform_ai_lookup(query)
960
-
961
- # Save the interaction
962
  saved_file = save_ai_interaction(query, ai_result)
963
  if saved_file:
964
  st.success(f"Saved interaction to {saved_file}")
@@ -967,12 +448,10 @@ def main():
967
  except Exception as e:
968
  st.error(f"Error during AI lookup: {e}")
969
 
970
- # File management sidebar
971
  file_management_sidebar()
972
-
973
- # Second priority: Display selected file content if any
974
  if st.session_state.selected_file:
975
- show_initial_content = False # Hide initial content when showing file content
976
  if os.path.exists(st.session_state.selected_file):
977
  st.markdown(f"### Current File: {st.session_state.selected_file}")
978
  display_file_content(st.session_state.selected_file)
@@ -981,35 +460,8 @@ def main():
981
  st.session_state.selected_file = None
982
  st.rerun()
983
 
984
- # Show initial content: Either when first landing or when no interactive elements are active
985
  if show_initial_content:
986
- # First show the clickable terms with links
987
- terms1 = extract_terms(AITopicsToInnovate1)
988
- terms2 = extract_terms(Multiplayer_Custom_Hosting_Game_Servers_For_Simulated_Worlds)
989
- terms3 = extract_terms(BiologyAndLevel36MagicUsers)
990
-
991
- all_terms = terms1 + terms2 + terms3
992
-
993
- col1, col2, col3, col4, col5, col6 = st.columns(6)
994
-
995
- with col1:
996
- st.markdown("#### AI Topics to Innovate With")
997
- st.markdown(AITopicsToInnovate1)
998
- with col2:
999
- st.markdown("#### AI Agent Links")
1000
- display_terms_with_links(terms1)
1001
- with col3:
1002
- st.markdown("#### Biology Innovation with Data Science and AI Solutions")
1003
- st.markdown(BiologyAndLevel36MagicUsers)
1004
- with col4:
1005
- st.markdown("#### Biology Innovation Agent Links")
1006
- display_terms_with_links(terms3)
1007
- with col5:
1008
- st.markdown("#### Multiplayer Games and MMOs")
1009
- st.markdown(Multiplayer_Custom_Hosting_Game_Servers_For_Simulated_Worlds)
1010
- with col6:
1011
- st.markdown("#### Multiplayer Game and MMO Links")
1012
- display_terms_with_links(terms2)
1013
 
1014
  if __name__ == "__main__":
1015
- main()
 
11
  from gradio_client import Client
12
  from datetime import datetime
13
 
14
+ # Page configuration
 
15
  Site_Name = 'AI Knowledge Tree Builder 📈🌿 Grow Smarter with Every Click'
16
  title = "🌳✨AI Knowledge Tree Builder🛠️🤓"
17
  helpURL = 'https://huggingface.co/spaces/awacke1/AIKnowledgeTreeBuilder/'
18
  bugURL = 'https://huggingface.co/spaces/awacke1/AIKnowledgeTreeBuilder/'
19
  icons = '🌳✨🛠️🤓'
20
 
21
+ SidebarOutline = """🌳🤖 Designed with the following tenets:
22
  1 📱 **Portability** - Universal access via any device & link sharing
23
  2. ⚡ **Speed of Build** - Rapid deployments < 2min to production
24
  3. 🔗 **Linkiness** - Programmatic access to AI knowledge sources
 
42
 
43
  st.sidebar.markdown(SidebarOutline)
44
 
 
45
  # Initialize session state variables
46
  if 'selected_file' not in st.session_state:
47
  st.session_state.selected_file = None
 
50
  if 'files' not in st.session_state:
51
  st.session_state.files = []
52
 
53
+ # --- Utility Functions ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
 
55
  def get_display_name(filename):
56
  """Extract text from parentheses or return filename as is."""
 
68
 
69
  def sanitize_filename(text):
70
  """Create a safe filename from text while preserving spaces."""
 
71
  safe_text = re.sub(r'[^\w\s-]', ' ', text)
 
72
  safe_text = re.sub(r'\s+', ' ', safe_text)
 
73
  safe_text = safe_text.strip()
74
+ return safe_text[:50]
75
 
76
  def generate_timestamp_filename(query):
77
  """Generate filename with format: 1103AM 11032024 (Query).md"""
 
78
  central = pytz.timezone('US/Central')
79
  current_time = datetime.now(central)
80
+ time_str = current_time.strftime("%I%M%p")
81
+ date_str = current_time.strftime("%m%d%Y")
 
 
 
 
82
  safe_query = sanitize_filename(query)
 
 
83
  filename = f"{time_str} {date_str} ({safe_query}).md"
 
84
  return filename
85
 
86
  def delete_file(file_path):
 
95
  def save_ai_interaction(query, ai_result, is_rerun=False):
96
  """Save AI interaction to a markdown file with new filename format."""
97
  filename = generate_timestamp_filename(query)
 
 
98
  if is_rerun:
99
  content = f"""# Rerun Query
100
  Original file content used for rerun:
 
110
  ## AI Response
111
  {ai_result}
112
  """
 
 
113
  try:
114
  with open(filename, 'w', encoding='utf-8') as f:
115
  f.write(content)
 
130
  st.error(f"Error creating download link: {e}")
131
  return None
132
 
133
+ # --- New Functions for Markdown File Parsing and Link Tree ---
134
+
135
+ def clean_item_text(line):
136
+ """
137
+ Remove emoji and numbered prefix from a line.
138
+ E.g., "🔧 1. Low-level system integrations compilers Cplusplus" becomes
139
+ "Low-level system integrations compilers Cplusplus".
140
+ Also remove any bold markdown markers.
141
+ """
142
+ # Remove leading emoji and number+period
143
+ cleaned = re.sub(r'^[^\w]*(\d+\.\s*)', '', line)
144
+ # Remove any remaining emoji (simple unicode range) and ** markers
145
+ cleaned = re.sub(r'[\U0001F300-\U0001FAFF]', '', cleaned)
146
+ cleaned = cleaned.replace("**", "")
147
+ return cleaned.strip()
148
+
149
+ def clean_header_text(header_line):
150
+ """
151
+ Extract header text from a markdown header line.
152
+ E.g., "🔧 **Systems, Infrastructure & Low-Level Engineering**" becomes
153
+ "Systems, Infrastructure & Low-Level Engineering".
154
+ """
155
+ match = re.search(r'\*\*(.*?)\*\*', header_line)
156
+ if match:
157
+ return match.group(1).strip()
158
+ return header_line.strip()
159
+
160
+ def parse_markdown_sections(md_text):
161
+ """
162
+ Parse markdown text into sections.
163
+ Each section starts with a header line containing bold text.
164
+ Returns a list of dicts with keys: 'header' and 'items' (list of lines).
165
+ Skips any content before the first header.
166
+ """
167
+ sections = []
168
+ current_section = None
169
+ lines = md_text.splitlines()
170
  for line in lines:
171
+ if line.strip() == "":
172
+ continue
173
+ # Check if line is a header (contains bold markdown and an emoji)
174
+ if '**' in line:
175
+ header = clean_header_text(line)
176
+ current_section = {'header': header, 'raw': line, 'items': []}
177
+ sections.append(current_section)
178
+ elif current_section is not None:
179
+ # Only add lines that appear to be list items (start with an emoji and number)
180
+ if re.match(r'^[^\w]*\d+\.\s+', line):
181
+ current_section['items'].append(line)
182
+ else:
183
+ if current_section['items']:
184
+ current_section['items'][-1] += " " + line.strip()
185
+ else:
186
+ current_section['items'].append(line)
187
+ return sections
188
+
189
+ def display_section_items(items):
190
+ """
191
+ Display list of items as links.
192
+ For each item, clean the text and generate search links using your original link set.
193
+ """
194
+ search_urls = {
195
+ "📚📖ArXiv": lambda k: f"/?q={quote(k)}",
196
+ "🔮<sup>Google</sup>": lambda k: f"https://www.google.com/search?q={quote(k)}",
197
+ "📺<sup>Youtube</sup>": lambda k: f"https://www.youtube.com/results?search_query={quote(k)}",
198
+ "🔭<sup>Bing</sup>": lambda k: f"https://www.bing.com/search?q={quote(k)}",
199
+ "💡<sup>Truth</sup>": lambda k: f"https://truthsocial.com/search?q={quote(k)}",
200
+ "📱X": lambda k: f"https://twitter.com/search?q={quote(k)}",
201
+ }
202
+ for item in items:
203
+ cleaned_text = clean_item_text(item)
204
+ links_md = ' '.join([f"[{emoji}]({url(cleaned_text)})" for emoji, url in search_urls.items()])
205
+ st.markdown(f"- **{cleaned_text}** {links_md}", unsafe_allow_html=True)
206
+
207
+ def display_markdown_tree():
208
+ """
209
+ Allow user to upload a .md file or load README.md.
210
+ Parse the markdown into sections and display each section in a collapsed expander
211
+ with the original markdown and a link tree of items.
212
+ """
213
+ st.markdown("## Markdown Tree Parser")
214
+ uploaded_file = st.file_uploader("Upload a Markdown file", type=["md"])
215
+ if uploaded_file is not None:
216
+ md_content = uploaded_file.read().decode("utf-8")
217
+ else:
218
+ if os.path.exists("README.md"):
219
+ with open("README.md", "r", encoding="utf-8") as f:
220
+ md_content = f.read()
221
+ else:
222
+ st.info("No Markdown file uploaded and README.md not found.")
223
+ return
224
 
225
+ sections = parse_markdown_sections(md_content)
226
+ if not sections:
227
+ st.info("No sections found in the markdown file.")
228
+ return
229
+
230
+ for sec in sections:
231
+ with st.expander(sec['header'], expanded=False):
232
+ st.markdown(f"**Original Markdown:**\n\n{sec['raw']}\n")
233
+ if sec['items']:
234
+ st.markdown("**Link Tree:**")
235
+ display_section_items(sec['items'])
236
+ else:
237
+ st.write("No items found in this section.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
238
 
239
+ # --- Existing AI and File Management Functions ---
240
+
241
+ def search_arxiv(query):
242
+ st.write("Performing AI Lookup...")
243
+ client = Client("awacke1/Arxiv-Paper-Search-And-QA-RAG-Pattern")
244
+ result1 = client.predict(
245
+ prompt=query,
246
+ llm_model_picked="mistralai/Mixtral-8x7B-Instruct-v0.1",
247
+ stream_outputs=True,
248
+ api_name="/ask_llm"
249
+ )
250
+ st.markdown("### Mixtral-8x7B-Instruct-v0.1 Result")
251
+ st.markdown(result1)
252
+ result2 = client.predict(
253
+ prompt=query,
254
+ llm_model_picked="mistralai/Mistral-7B-Instruct-v0.2",
255
+ stream_outputs=True,
256
+ api_name="/ask_llm"
257
+ )
258
+ st.markdown("### Mistral-7B-Instruct-v0.2 Result")
259
+ st.markdown(result2)
260
+ combined_result = f"{result1}\n\n{result2}"
261
+ return combined_result
262
 
 
263
  @st.cache_resource
264
  def SpeechSynthesis(result):
265
+ documentHTML5 = '''
266
  <!DOCTYPE html>
267
  <html>
268
  <head>
 
279
  <h1>🔊 Read It Aloud</h1>
280
  <textarea id="textArea" rows="10" cols="80">
281
  '''
282
+ documentHTML5 += result
283
+ documentHTML5 += '''
284
  </textarea>
285
  <br>
286
  <button onclick="readAloud()">🔊 Read Aloud</button>
 
289
  '''
290
  components.html(documentHTML5, width=1280, height=300)
291
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
292
  def display_file_content(file_path):
293
  """Display file content with editing capabilities."""
294
  try:
295
  with open(file_path, 'r', encoding='utf-8') as f:
296
  content = f.read()
 
297
  if st.session_state.view_mode == 'view':
 
298
  st.markdown(content)
299
  else:
 
300
  edited_content = st.text_area(
301
  "Edit content",
302
  content,
303
  height=400,
304
  key=f"edit_{os.path.basename(file_path)}"
305
  )
 
306
  if st.button("Save Changes", key=f"save_{os.path.basename(file_path)}"):
307
  try:
308
  with open(file_path, 'w', encoding='utf-8') as f:
 
316
  def file_management_sidebar():
317
  """Redesigned sidebar with improved layout and additional functionality."""
318
  st.sidebar.title("📁 File Management")
 
 
319
  md_files = [file for file in glob.glob("*.md") if file.lower() != 'readme.md']
320
  md_files.sort()
321
  st.session_state.files = md_files
 
322
  if md_files:
323
  st.sidebar.markdown("### Saved Files")
324
  for idx, file in enumerate(md_files):
325
+ st.sidebar.markdown("---")
 
 
326
  st.sidebar.text(get_time_display(file))
 
 
327
  download_link = get_file_download_link(file)
328
  if download_link:
329
  st.sidebar.markdown(download_link, unsafe_allow_html=True)
 
 
330
  col1, col2, col3, col4 = st.sidebar.columns(4)
 
331
  with col1:
332
  if st.button("📄View", key=f"view_{idx}"):
333
  st.session_state.selected_file = file
334
  st.session_state.view_mode = 'view'
 
335
  with col2:
336
  if st.button("✏️Edit", key=f"edit_{idx}"):
337
  st.session_state.selected_file = file
338
  st.session_state.view_mode = 'edit'
 
339
  with col3:
340
  if st.button("🔄Run", key=f"rerun_{idx}"):
341
  try:
342
  with open(file, 'r', encoding='utf-8') as f:
343
  content = f.read()
 
 
344
  rerun_prefix = """For the markdown below reduce the text to a humorous fun outline with emojis and markdown outline levels in outline that convey all the facts and adds wise quotes and funny statements to engage the reader:
345
 
346
  """
347
  full_prompt = rerun_prefix + content
 
 
348
  ai_result = perform_ai_lookup(full_prompt)
349
  saved_file = save_ai_interaction(content, ai_result, is_rerun=True)
 
350
  if saved_file:
351
  st.success(f"Created fun version in {saved_file}")
352
  st.session_state.selected_file = saved_file
353
  st.session_state.view_mode = 'view'
 
354
  except Exception as e:
355
  st.error(f"Error during rerun: {e}")
 
356
  with col4:
357
  if st.button("🗑️Delete", key=f"delete_{idx}"):
358
  if delete_file(file):
 
360
  st.rerun()
361
  else:
362
  st.error(f"Failed to delete {file}")
 
363
  st.sidebar.markdown("---")
 
364
  if st.sidebar.button("📝 Create New Note"):
365
  filename = generate_timestamp_filename("New Note")
366
  with open(filename, 'w', encoding='utf-8') as f:
 
378
  st.session_state.selected_file = filename
379
  st.session_state.view_mode = 'edit'
380
 
381
+ def perform_ai_lookup(query):
382
+ start_time = time.strftime("%Y-%m-%d %H:%M:%S")
383
+ client = Client("awacke1/Arxiv-Paper-Search-And-QA-RAG-Pattern")
384
+ response1 = client.predict(
385
+ query,
386
+ 20,
387
+ "Semantic Search",
388
+ "mistralai/Mixtral-8x7B-Instruct-v0.1",
389
+ api_name="/update_with_rag_md"
390
+ )
391
+ Question = '### 🔎 ' + query + '\r\n'
392
+ References = response1[0]
393
+ ReferenceLinks = ""
394
+ results = ""
395
+ RunSecondQuery = True
396
+ if RunSecondQuery:
397
+ response2 = client.predict(
398
+ query,
399
+ "mistralai/Mixtral-8x7B-Instruct-v0.1",
400
+ True,
401
+ api_name="/ask_llm"
402
+ )
403
+ if len(response2) > 10:
404
+ Answer = response2
405
+ SpeechSynthesis(Answer)
406
+ results = Question + '\r\n' + Answer + '\r\n' + References + '\r\n' + ReferenceLinks
407
+ st.markdown(results)
408
+ st.write('🔍Run of Multi-Agent System Paper Summary Spec is Complete')
409
+ end_time = time.strftime("%Y-%m-%d %H:%M:%S")
410
+ start_timestamp = time.mktime(time.strptime(start_time, "%Y-%m-%d %H:%M:%S"))
411
+ end_timestamp = time.mktime(time.strptime(end_time, "%Y-%m-%d %H:%M:%S"))
412
+ elapsed_seconds = end_timestamp - start_timestamp
413
+ st.write(f"Start time: {start_time}")
414
+ st.write(f"Finish time: {end_time}")
415
+ st.write(f"Elapsed time: {elapsed_seconds:.2f} seconds")
416
+ filename = generate_filename(query, "md")
417
+ create_file(filename, query, results)
418
+ return results
419
+
420
+ def generate_filename(prompt, file_type):
421
+ central = pytz.timezone('US/Central')
422
+ safe_date_time = datetime.now(central).strftime("%m%d_%H%M")
423
+ safe_prompt = re.sub(r'\W+', '_', prompt)[:90]
424
+ return f"{safe_date_time}_{safe_prompt}.{file_type}"
425
+
426
+ def create_file(filename, prompt, response):
427
+ with open(filename, 'w', encoding='utf-8') as file:
428
+ file.write(prompt + "\n\n" + response)
429
+
430
+ # --- Main Application ---
431
+
432
  def main():
433
  st.markdown("### AI Knowledge Tree Builder 🧠🌱 Cultivate Your AI Mindscape!")
 
 
434
  query_params = st.query_params
435
  query = query_params.get('q', '')
436
+ show_initial_content = True
437
 
 
438
  if query:
439
+ show_initial_content = False
440
  st.write(f"### Search query received: {query}")
441
  try:
442
  ai_result = perform_ai_lookup(query)
 
 
443
  saved_file = save_ai_interaction(query, ai_result)
444
  if saved_file:
445
  st.success(f"Saved interaction to {saved_file}")
 
448
  except Exception as e:
449
  st.error(f"Error during AI lookup: {e}")
450
 
 
451
  file_management_sidebar()
452
+
 
453
  if st.session_state.selected_file:
454
+ show_initial_content = False
455
  if os.path.exists(st.session_state.selected_file):
456
  st.markdown(f"### Current File: {st.session_state.selected_file}")
457
  display_file_content(st.session_state.selected_file)
 
460
  st.session_state.selected_file = None
461
  st.rerun()
462
 
 
463
  if show_initial_content:
464
+ display_markdown_tree()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
465
 
466
  if __name__ == "__main__":
467
+ main()