awacke1 commited on
Commit
e63c12a
1 Parent(s): f162e9d

Create backup.app.py

Browse files
Files changed (1) hide show
  1. backup.app.py +1410 -0
backup.app.py ADDED
@@ -0,0 +1,1410 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import streamlit.components.v1 as components
3
+ import huggingface_hub
4
+ import gradio_client as gc
5
+
6
+ import os
7
+ import json
8
+ import random
9
+ import base64
10
+ import glob
11
+ import math
12
+ import openai
13
+ import pytz
14
+ import re
15
+ import requests
16
+ import textract
17
+ import time
18
+ import zipfile
19
+ import dotenv
20
+
21
+ from gradio_client import Client
22
+ from audio_recorder_streamlit import audio_recorder
23
+ from bs4 import BeautifulSoup
24
+ from collections import deque
25
+ from datetime import datetime
26
+ from dotenv import load_dotenv
27
+ from huggingface_hub import InferenceClient
28
+ from io import BytesIO
29
+ from openai import ChatCompletion
30
+ from PyPDF2 import PdfReader
31
+ from templates import bot_template, css, user_template
32
+ from xml.etree import ElementTree as ET
33
+ from PIL import Image
34
+ from urllib.parse import quote # Ensure this import is included
35
+
36
+
37
+ ## Show examples
38
+ sample_outputs = {
39
+ 'output_placeholder': 'The LLM will provide an answer to your question here...',
40
+ 'search_placeholder': '1. What is MoE, Multi Agent Systems, Self Rewarding AI, Semantic and Episodic memory, What is AutoGen, ChatDev, Omniverse, Lumiere, SORA?'
41
+ }
42
+
43
+ def save_file(content, file_type):
44
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
45
+ file_name = f"{file_type}_{timestamp}.md"
46
+ with open(file_name, "w") as file:
47
+ file.write(content)
48
+ return file_name
49
+
50
+ def load_file(file_name):
51
+ with open(file_name, "r") as file:
52
+ content = file.read()
53
+ return content
54
+
55
+
56
+ # HTML5 based Speech Synthesis (Text to Speech in Browser)
57
+ @st.cache_resource
58
+ def SpeechSynthesis(result):
59
+ documentHTML5='''
60
+ <!DOCTYPE html>
61
+ <html>
62
+ <head>
63
+ <title>Read It Aloud</title>
64
+ <script type="text/javascript">
65
+ function readAloud() {
66
+ const text = document.getElementById("textArea").value;
67
+ const speech = new SpeechSynthesisUtterance(text);
68
+ window.speechSynthesis.speak(speech);
69
+ }
70
+ </script>
71
+ </head>
72
+ <body>
73
+ <h1>🔊 Read It Aloud</h1>
74
+ <textarea id="textArea" rows="10" cols="80">
75
+ '''
76
+ documentHTML5 = documentHTML5 + result
77
+ documentHTML5 = documentHTML5 + '''
78
+ </textarea>
79
+ <br>
80
+ <button onclick="readAloud()">🔊 Read Aloud</button>
81
+ </body>
82
+ </html>
83
+ '''
84
+ components.html(documentHTML5, width=1280, height=300)
85
+
86
+ def parse_to_markdown(text):
87
+ # Split text into fields by | character
88
+ fields = text.split("|")
89
+
90
+ markdown = ""
91
+ for field in fields:
92
+ # Remove leading/trailing quotes and whitespace
93
+ field = field.strip(" '")
94
+
95
+ # Add field to markdown with whitespace separator
96
+ markdown += field + "\n\n"
97
+
98
+ return markdown
99
+
100
+ def search_arxiv(query):
101
+
102
+ # Show ArXiv Scholary Articles! ----------------*************-------------***************----------------------------------------
103
+ # st.title("▶️ Semantic and Episodic Memory System")
104
+ client = Client("awacke1/Arxiv-Paper-Search-And-QA-RAG-Pattern")
105
+
106
+ search_query = query
107
+ #top_n_results = st.slider(key='topnresults', label="Top n results as context", min_value=4, max_value=100, value=100)
108
+ #search_source = st.sidebar.selectbox(key='searchsource', label="Search Source", ["Semantic Search - up to 10 Mar 2024", "Arxiv Search - Latest - (EXPERIMENTAL)"])
109
+ search_source = "Arxiv Search - Latest - (EXPERIMENTAL)" # "Semantic Search - up to 10 Mar 2024"
110
+ #llm_model = st.sidebar.selectbox(key='llmmodel', label="LLM Model", ["mistralai/Mixtral-8x7B-Instruct-v0.1", "mistralai/Mistral-7B-Instruct-v0.2", "google/gemma-7b-it", "None"])
111
+ llm_model = "mistralai/Mixtral-8x7B-Instruct-v0.1"
112
+
113
+
114
+ st.sidebar.markdown('### 🔎 ' + query)
115
+ result = client.predict(
116
+ search_query,
117
+ 100,
118
+ search_source,
119
+ llm_model,
120
+ api_name="/update_with_rag_md"
121
+ )
122
+ result = parse_to_markdown(result)
123
+ st.markdown(result)
124
+ arxiv_results = st.text_area("ArXiv Results: ", value=result, height=700)
125
+ result = str(result) # cast as string for these - check content length and format if encoding changes..
126
+ result=result.replace('\\n', ' ')
127
+ SpeechSynthesis(result) # Search History Reader / Writer IO Memory - Audio at Same time as Reading.
128
+ filename=generate_filename(result, "md")
129
+ create_file(filename, query, result, should_save)
130
+
131
+
132
+ #file_type = st.radio("Select Which Type of Memory You Prefer:", ("Semantic", "Episodic"))
133
+ #if st.button("Save"):
134
+ # file_name = save_file(result, file_type)
135
+ # st.success(f"File saved: {file_name}")
136
+
137
+ saved_files = [f for f in os.listdir(".") if f.endswith(".md")]
138
+ selected_file = st.sidebar.selectbox("Saved Files", saved_files)
139
+
140
+ if selected_file:
141
+ file_content = load_file(selected_file)
142
+ st.sidebar.markdown(file_content)
143
+ if st.sidebar.button("🗑️ Delete"):
144
+ os.remove(selected_file)
145
+ st.warning(f"File deleted: {selected_file}")
146
+ return result
147
+
148
+ # Set page configuration with a title and favicon
149
+ st.set_page_config(
150
+ page_title="🚀🌌World Ship Design Program",
151
+ page_icon="🔍🚀🌌📖",
152
+ layout="wide",
153
+ initial_sidebar_state="expanded",
154
+ menu_items={
155
+ 'Get Help': 'https://huggingface.co/awacke1',
156
+ 'Report a bug': "https://huggingface.co/spaces/awacke1",
157
+ 'About': "# 🚀🌌World-Ship-Design"
158
+ }
159
+ )
160
+
161
+ # Prompts for App, for App Product, and App Product Code
162
+ PromptPrefix = 'Create a specification with streamlit functions creating markdown outlines and tables rich with appropriate emojis for methodical step by step rules defining the concepts at play. Use story structure architect rules to plan, structure and write three dramatic situations to include in the rules and how to play by matching the theme for topic of '
163
+ PromptPrefix2 = 'Create a streamlit python user app with full code listing to create a UI implementing the using streamlit, gradio, huggingface to create user interface elements like emoji buttons, sliders, drop downs, and data interfaces like dataframes to show tables, session_statematching this ruleset and thematic story plot line: '
164
+ PromptPrefix3 = 'Create a HTML5 aframe and javascript app using appropriate libraries to create a word game simulation with advanced libraries like aframe to render 3d scenes creating moving entities that stay within a bounding box but show text and animation in 3d for inventory, components and story entities. Show full code listing. Add a list of new random entities say 3 of a few different types to any list appropriately and use emojis to make things easier and fun to read. Use appropriate emojis in labels. Create the UI to implement storytelling in the style of a dungeon master, with features using three emoji appropriate text plot twists and recurring interesting funny fascinating and complex almost poetic named characters with genius traits and file IO, randomness, ten point choice lists, math distribution tradeoffs, witty humorous dilemnas with emoji , rewards, variables, reusable functions with parameters, and data driven app with python libraries and streamlit components for Javascript and HTML5. Use appropriate emojis for labels to summarize and list parts, function, conditions for topic:'
165
+
166
+ # Function to display the entire glossary in a grid format with links
167
+ def display_glossary_grid(roleplaying_glossary):
168
+ search_urls = {
169
+ "📖": lambda k: f"https://en.wikipedia.org/wiki/{quote(k)}",
170
+ "🔍": lambda k: f"https://www.google.com/search?q={quote(k)}",
171
+ "▶️": lambda k: f"https://www.youtube.com/results?search_query={quote(k)}",
172
+ "🔎": lambda k: f"https://www.bing.com/search?q={quote(k)}",
173
+ "🎥": lambda k: f"https://www.youtube.com/results?search_query={quote(k)}",
174
+ "🐦": lambda k: f"https://twitter.com/search?q={quote(k)}",
175
+ "🎲": lambda k: f"https://huggingface.co/spaces/awacke1/World-Ship-Design?q={quote(k)}", # this url plus query!
176
+ "🃏": lambda k: f"https://huggingface.co/spaces/awacke1/World-Ship-Design?q={quote(k)}-{quote(PromptPrefix)}", # this url plus query!
177
+ "📚": lambda k: f"https://huggingface.co/spaces/awacke1/World-Ship-Design?q={quote(k)}-{quote(PromptPrefix2)}", # this url plus query!
178
+ "🔬": lambda k: f"https://huggingface.co/spaces/awacke1/World-Ship-Design?q={quote(k)}-{quote(PromptPrefix3)}", # this url plus query!
179
+ }
180
+
181
+ for category, details in roleplaying_glossary.items():
182
+ st.write(f"### {category}")
183
+ cols = st.columns(len(details)) # Create dynamic columns based on the number of games
184
+ for idx, (game, terms) in enumerate(details.items()):
185
+ with cols[idx]:
186
+ st.markdown(f"#### {game}")
187
+ for term in terms:
188
+ gameterm = category + ' - ' + game + ' - ' + term
189
+ links_md = ' '.join([f"[{emoji}]({url(gameterm)})" for emoji, url in search_urls.items()])
190
+ #links_md = ' '.join([f"[{emoji}]({url(term)})" for emoji, url in search_urls.items()])
191
+ st.markdown(f"{term} {links_md}", unsafe_allow_html=True)
192
+
193
+ def display_glossary_entity(k):
194
+ search_urls = {
195
+ "📖": lambda k: f"https://en.wikipedia.org/wiki/{quote(k)}",
196
+ "🔍": lambda k: f"https://www.google.com/search?q={quote(k)}",
197
+ "▶️": lambda k: f"https://www.youtube.com/results?search_query={quote(k)}",
198
+ "🔎": lambda k: f"https://www.bing.com/search?q={quote(k)}",
199
+ "🎥": lambda k: f"https://www.youtube.com/results?search_query={quote(k)}",
200
+ "🐦": lambda k: f"https://twitter.com/search?q={quote(k)}",
201
+ "🎲": lambda k: f"https://huggingface.co/spaces/awacke1/World-Ship-Design?q={quote(k)}", # this url plus query!
202
+ "🃏": lambda k: f"https://huggingface.co/spaces/awacke1/World-Ship-Design?q={quote(k)}-{quote(PromptPrefix)}", # this url plus query!
203
+ "📚": lambda k: f"https://huggingface.co/spaces/awacke1/World-Ship-Design?q={quote(k)}-{quote(PromptPrefix2)}", # this url plus query!
204
+ "🔬": lambda k: f"https://huggingface.co/spaces/awacke1/World-Ship-Design?q={quote(k)}-{quote(PromptPrefix3)}", # this url plus query!
205
+ }
206
+ links_md = ' '.join([f"[{emoji}]({url(k)})" for emoji, url in search_urls.items()])
207
+ st.markdown(f"{k} {links_md}", unsafe_allow_html=True)
208
+
209
+
210
+
211
+ #st.markdown('''### 📖✨🔍 Arxiv-Paper-Search-QA-RAG-Streamlit-Gradio-AP ''')
212
+
213
+ roleplaying_glossary = {
214
+ "🤖 AI Concepts": {
215
+ "MoE (Mixture of Experts) 🧠": [
216
+ "What are Multi Agent Systems for Health",
217
+ "What is Mixture of Experts for Health",
218
+ "What are Semantic and Episodic Memory and what is Mirroring for Behavioral Health",
219
+ "What are Self Rewarding AI Systems for Health",
220
+ "How are AGI and AMI systems created using Multi Agent Systems and Mixture of Experts for Health"
221
+ ],
222
+ "Multi Agent Systems (MAS) 🤝": [
223
+ "Distributed AI systems",
224
+ "Autonomous agents interacting",
225
+ "Cooperative and competitive behavior",
226
+ "Decentralized problem-solving",
227
+ "Applications in robotics, simulations, and more"
228
+ ],
229
+ "Self Rewarding AI 🎁": [
230
+ "Intrinsic motivation for AI agents",
231
+ "Autonomous goal setting and achievement",
232
+ "Exploration and curiosity-driven learning",
233
+ "Potential for open-ended development",
234
+ "Research area in reinforcement learning"
235
+ ],
236
+ "Semantic and Episodic Memory 📚": [
237
+ "Two types of long-term memory",
238
+ "Semantic: facts and general knowledge",
239
+ "Episodic: personal experiences and events",
240
+ "Crucial for AI systems to understand and reason",
241
+ "Research in knowledge representation and retrieval"
242
+ ]
243
+ },
244
+ "🛠️ AI Tools & Platforms": {
245
+ "AutoGen 🔧": [
246
+ "Automated machine learning (AutoML) tool",
247
+ "Generates AI models based on requirements",
248
+ "Simplifies AI development process",
249
+ "Accessible to non-experts",
250
+ "Integration with various data sources"
251
+ ],
252
+ "ChatDev 💬": [
253
+ "Platform for building chatbots and conversational AI",
254
+ "Drag-and-drop interface for designing chat flows",
255
+ "Pre-built templates and integrations",
256
+ "Supports multiple messaging platforms",
257
+ "Analytics and performance tracking"
258
+ ],
259
+ "Omniverse 🌐": [
260
+ "Nvidia's 3D simulation and collaboration platform",
261
+ "Physically accurate virtual worlds",
262
+ "Supports AI training and testing",
263
+ "Used in industries like robotics, architecture, and gaming",
264
+ "Enables seamless collaboration and data exchange"
265
+ ],
266
+ "Lumiere 🎥": [
267
+ "AI-powered video analytics platform",
268
+ "Extracts insights and metadata from video content",
269
+ "Facial recognition and object detection",
270
+ "Sentiment analysis and scene understanding",
271
+ "Applications in security, media, and marketing"
272
+ ],
273
+ "SORA 🏗️": [
274
+ "Scalable Open Research Architecture",
275
+ "Framework for distributed AI research and development",
276
+ "Modular and extensible design",
277
+ "Facilitates collaboration and reproducibility",
278
+ "Supports various AI algorithms and models"
279
+ ]
280
+ },
281
+ "🚀 World Ship Design": {
282
+ "ShipHullGAN 🌊": [
283
+ "Generic parametric modeller for ship hull design",
284
+ "Uses deep convolutional generative adversarial networks (GANs)",
285
+ "Trained on diverse ship hull designs",
286
+ "Generates geometrically valid and feasible ship hull shapes",
287
+ "Enables exploration of traditional and novel designs",
288
+ "From the paper 'ShipHullGAN: A generic parametric modeller for ship hull design using deep convolutional generative model'"
289
+ ],
290
+ "B\'ezierGAN 📐": [
291
+ "Automatic generation of smooth curves",
292
+ "Maps low-dimensional parameters to B\'ezier curve points",
293
+ "Generates diverse and realistic curves",
294
+ "Preserves shape variation in latent space",
295
+ "Useful for design optimization and exploration",
296
+ "From the paper 'B\'ezierGAN: Automatic Generation of Smooth Curves from Interpretable Low-Dimensional Parameters'"
297
+ ],
298
+ "PlotMap 🗺️": [
299
+ "Automated game world layout design",
300
+ "Uses reinforcement learning to place plot elements",
301
+ "Considers spatial constraints from story",
302
+ "Enables procedural content generation for games",
303
+ "Handles multi-modal inputs (images, locations, text)",
304
+ "From the paper 'PlotMap: Automated Layout Design for Building Game Worlds'"
305
+ ],
306
+ "ShipGen ⚓": [
307
+ "Diffusion model for parametric ship hull generation",
308
+ "Considers multiple objectives and constraints",
309
+ "Generates tabular parametric design vectors",
310
+ "Uses classifier guidance to improve hull quality",
311
+ "Reduces design time and generates high-performing hulls",
312
+ "From the paper 'ShipGen: A Diffusion Model for Parametric Ship Hull Generation with Multiple Objectives and Constraints'"
313
+ ],
314
+ "Ship-D 📊": [
315
+ "Large dataset of ship hulls for machine learning",
316
+ "30,000 hulls with design and performance data",
317
+ "Includes parameterization, mesh, point cloud, images",
318
+ "Measures hydrodynamic drag under different conditions",
319
+ "Enables data-driven ship design optimization",
320
+ "From the paper 'Ship-D: Ship Hull Dataset for Design Optimization using Machine Learning'"
321
+ ]
322
+ },
323
+ "🌌 Exploring the Universe":{
324
+ "Cosmos 🪐": [
325
+ "Object-centric world modeling framework",
326
+ "Designed for compositional generalization",
327
+ "Uses neurosymbolic grounding",
328
+ "Neurosymbolic scene encodings and attention mechanism",
329
+ "Computes symbolic attributes using vision-language models",
330
+ "From the paper 'Neurosymbolic Grounding for Compositional World Models'"
331
+ ],
332
+ "Active World Model Learning 🔭": [
333
+ "Curiosity-driven exploration for world model learning",
334
+ "Constructs agent to visually explore 3D environment",
335
+ "Uses progress-based curiosity signal ($\gamma$-Progress)",
336
+ "Overcomes 'white noise problem' in exploration",
337
+ "Outperforms baseline exploration strategies",
338
+ "From the paper 'Active World Model Learning with Progress Curiosity'"
339
+ ],
340
+ "Probabilistic Worldbuilding 🎲": [
341
+ "Symbolic Bayesian model for semantic parsing and reasoning",
342
+ "Aims for general natural language understanding",
343
+ "Expresses meaning in human-readable formal language",
344
+ "Designed to generalize to new domains and tasks",
345
+ "Outperforms baselines on out-of-domain question answering",
346
+ "From the paper 'Towards General Natural Language Understanding with Probabilistic Worldbuilding'"
347
+ ],
348
+ "Language-Guided World Models 💬": [
349
+ "Capture environment dynamics from language descriptions",
350
+ "Allow efficient communication and control",
351
+ "Enable self-learning from human instruction texts",
352
+ "Tested on challenging benchmark requiring generalization",
353
+ "Improves interpretability and safety via generated plans",
354
+ "From the paper 'Language-Guided World Models: A Model-Based Approach to AI Control'"
355
+
356
+ ]
357
+ }
358
+ }
359
+
360
+ @st.cache_resource
361
+ def get_table_download_link(file_path):
362
+ with open(file_path, 'r') as file:
363
+ data = file.read()
364
+ b64 = base64.b64encode(data.encode()).decode()
365
+ file_name = os.path.basename(file_path)
366
+ ext = os.path.splitext(file_name)[1] # get the file extension
367
+ if ext == '.txt':
368
+ mime_type = 'text/plain'
369
+ elif ext == '.py':
370
+ mime_type = 'text/plain'
371
+ elif ext == '.xlsx':
372
+ mime_type = 'text/plain'
373
+ elif ext == '.csv':
374
+ mime_type = 'text/plain'
375
+ elif ext == '.htm':
376
+ mime_type = 'text/html'
377
+ elif ext == '.md':
378
+ mime_type = 'text/markdown'
379
+ elif ext == '.wav':
380
+ mime_type = 'audio/wav'
381
+ else:
382
+ mime_type = 'application/octet-stream' # general binary data type
383
+ href = f'<a href="data:{mime_type};base64,{b64}" target="_blank" download="{file_name}">{file_name}</a>'
384
+ return href
385
+
386
+
387
+ @st.cache_resource
388
+ def create_zip_of_files(files): # ----------------------------------
389
+ zip_name = "Arxiv-Paper-Search-QA-RAG-Streamlit-Gradio-AP.zip"
390
+ with zipfile.ZipFile(zip_name, 'w') as zipf:
391
+ for file in files:
392
+ zipf.write(file)
393
+ return zip_name
394
+
395
+ @st.cache_resource
396
+ def get_zip_download_link(zip_file):
397
+ with open(zip_file, 'rb') as f:
398
+ data = f.read()
399
+ b64 = base64.b64encode(data).decode()
400
+ href = f'<a href="data:application/zip;base64,{b64}" download="{zip_file}">Download All</a>'
401
+ return href # ----------------------------------
402
+
403
+ def FileSidebar():
404
+ # ----------------------------------------------------- File Sidebar for Jump Gates ------------------------------------------
405
+ # Compose a file sidebar of markdown md files:
406
+ all_files = glob.glob("*.md")
407
+ all_files = [file for file in all_files if len(os.path.splitext(file)[0]) >= 10] # exclude files with short names
408
+ all_files.sort(key=lambda x: (os.path.splitext(x)[1], x), reverse=True) # sort by file type and file name in descending order
409
+ if st.sidebar.button("🗑 Delete All Text"):
410
+ for file in all_files:
411
+ os.remove(file)
412
+ st.experimental_rerun()
413
+ if st.sidebar.button("⬇️ Download All"):
414
+ zip_file = create_zip_of_files(all_files)
415
+ st.sidebar.markdown(get_zip_download_link(zip_file), unsafe_allow_html=True)
416
+ file_contents=''
417
+ next_action=''
418
+ for file in all_files:
419
+ col1, col2, col3, col4, col5 = st.sidebar.columns([1,6,1,1,1]) # adjust the ratio as needed
420
+ with col1:
421
+ if st.button("🌐", key="md_"+file): # md emoji button
422
+ with open(file, 'r') as f:
423
+ file_contents = f.read()
424
+ next_action='md'
425
+ with col2:
426
+ st.markdown(get_table_download_link(file), unsafe_allow_html=True)
427
+ with col3:
428
+ if st.button("📂", key="open_"+file): # open emoji button
429
+ with open(file, 'r') as f:
430
+ file_contents = f.read()
431
+ next_action='open'
432
+ with col4:
433
+ if st.button("🔍", key="read_"+file): # search emoji button
434
+ with open(file, 'r') as f:
435
+ file_contents = f.read()
436
+ next_action='search'
437
+ with col5:
438
+ if st.button("🗑", key="delete_"+file):
439
+ os.remove(file)
440
+ st.experimental_rerun()
441
+
442
+
443
+ if len(file_contents) > 0:
444
+ if next_action=='open':
445
+ file_content_area = st.text_area("File Contents:", file_contents, height=500)
446
+ #try:
447
+ if st.button("🔍", key="filecontentssearch"):
448
+ #search_glossary(file_content_area)
449
+ filesearch = PromptPrefix + file_content_area
450
+ st.markdown(filesearch)
451
+ if st.button(key=rerun, label='🔍Re-Spec' ):
452
+ search_glossary(filesearch)
453
+ #except:
454
+ st.markdown('GPT is sleeping. Restart ETA 30 seconds.')
455
+
456
+ if next_action=='md':
457
+ st.markdown(file_contents)
458
+ buttonlabel = '🔍Run'
459
+ if st.button(key='Runmd', label = buttonlabel):
460
+ user_prompt = file_contents
461
+ #try:
462
+ search_glossary(file_contents)
463
+ #except:
464
+ st.markdown('GPT is sleeping. Restart ETA 30 seconds.')
465
+
466
+ if next_action=='search':
467
+ file_content_area = st.text_area("File Contents:", file_contents, height=500)
468
+ user_prompt = file_contents
469
+ #try:
470
+ #search_glossary(file_contents)
471
+ filesearch = PromptPrefix2 + file_content_area
472
+ st.markdown(filesearch)
473
+ if st.button(key=rerun, label='🔍Re-Code' ):
474
+ search_glossary(filesearch)
475
+
476
+ #except:
477
+ st.markdown('GPT is sleeping. Restart ETA 30 seconds.')
478
+ # ----------------------------------------------------- File Sidebar for Jump Gates ------------------------------------------
479
+ FileSidebar()
480
+
481
+
482
+
483
+ # ---- Art Card Sidebar with Random Selection of image:
484
+ def get_image_as_base64(url):
485
+ response = requests.get(url)
486
+ if response.status_code == 200:
487
+ # Convert the image to base64
488
+ return base64.b64encode(response.content).decode("utf-8")
489
+ else:
490
+ return None
491
+
492
+ def create_download_link(filename, base64_str):
493
+ href = f'<a href="data:file/png;base64,{base64_str}" download="{filename}">Download Image</a>'
494
+ return href
495
+ image_urls = [
496
+ "https://cdn-uploads.huggingface.co/production/uploads/620630b603825909dcbeba35/cfhJIasuxLkT5fnaAE6Gj.png",
497
+ "https://cdn-uploads.huggingface.co/production/uploads/620630b603825909dcbeba35/UMo4oWNrrd6RLLzsFxQAi.png",
498
+ "https://cdn-uploads.huggingface.co/production/uploads/620630b603825909dcbeba35/o_EH4cTs5Qxiu7xTZw9I3.png",
499
+ "https://cdn-uploads.huggingface.co/production/uploads/620630b603825909dcbeba35/cmCZ5RTdSx3usMm7MwwWK.png",
500
+ ]
501
+
502
+ selected_image_url = random.choice(image_urls)
503
+ selected_image_base64 = get_image_as_base64(selected_image_url)
504
+ if selected_image_base64 is not None:
505
+ with st.sidebar:
506
+ st.markdown(f"![image](data:image/png;base64,{selected_image_base64})")
507
+ else:
508
+ st.sidebar.write("Failed to load the image.")
509
+
510
+ # Ensure the directory for storing scores exists
511
+ score_dir = "scores"
512
+ os.makedirs(score_dir, exist_ok=True)
513
+
514
+ # Function to generate a unique key for each button, including an emoji
515
+ def generate_key(label, header, idx):
516
+ return f"{header}_{label}_{idx}_key"
517
+
518
+ # Function to increment and save score
519
+ def update_score(key, increment=1):
520
+ score_file = os.path.join(score_dir, f"{key}.json")
521
+ if os.path.exists(score_file):
522
+ with open(score_file, "r") as file:
523
+ score_data = json.load(file)
524
+ else:
525
+ score_data = {"clicks": 0, "score": 0}
526
+ score_data["clicks"] += 1
527
+ score_data["score"] += increment
528
+ with open(score_file, "w") as file:
529
+ json.dump(score_data, file)
530
+ return score_data["score"]
531
+
532
+ # Function to load score
533
+ def load_score(key):
534
+ score_file = os.path.join(score_dir, f"{key}.json")
535
+ if os.path.exists(score_file):
536
+ with open(score_file, "r") as file:
537
+ score_data = json.load(file)
538
+ return score_data["score"]
539
+ return 0
540
+
541
+ @st.cache_resource
542
+ def search_glossary(query): # 🔍Run--------------------------------------------------------
543
+ for category, terms in roleplaying_glossary.items():
544
+ if query.lower() in (term.lower() for term in terms):
545
+ st.markdown(f"#### {category}")
546
+ st.write(f"- {query}")
547
+ all=""
548
+
549
+ # 🔍Run 1 - plain query
550
+ #response = chat_with_model(query)
551
+ #response1 = chat_with_model45(query)
552
+
553
+ #all = query + ' ' + response1
554
+ #st.write('🔍Run 1 is Complete.')
555
+
556
+ # ArXiv searcher ~-<>-~
557
+ client = Client("awacke1/Arxiv-Paper-Search-And-QA-RAG-Pattern")
558
+ response1 = client.predict(
559
+ query,
560
+ 10,
561
+ "Semantic Search - up to 10 Mar 2024", # Literal['Semantic Search - up to 10 Mar 2024', 'Arxiv Search - Latest - (EXPERIMENTAL)'] in 'Search Source' Dropdown component
562
+ "mistralai/Mixtral-8x7B-Instruct-v0.1", # Literal['mistralai/Mixtral-8x7B-Instruct-v0.1', 'mistralai/Mistral-7B-Instruct-v0.2', 'google/gemma-7b-it', 'None'] in 'LLM Model' Dropdown component
563
+ api_name="/update_with_rag_md"
564
+ )
565
+ st.write('🔍Run of Multi-Agent Systems is Complete')
566
+
567
+ # experimental 45 - - - - - - - - - - - - -<><><><><>
568
+
569
+ # 🔍Run PaperSummarizer
570
+ PaperSummarizer = ' Create a paper summary as a markdown table with paper links clustering the features writing short markdown emoji outlines to extract three main ideas from each of the ten summaries. For each one create three simple points led by an emoji of the main three steps needed as method step process for implementing the idea as a single app.py streamlit python app. '
571
+ # = str(result).replace('\n', ' ').replace('|', ' ')
572
+ response2 = chat_with_model45(PaperSummarizer + str(response1))
573
+ st.write('🔍Run 3 - Paper Summarizer is Complete.')
574
+
575
+ # 🔍Run AppSpecifier
576
+ AppSpecifier = ' Design and write a streamlit python code listing and specification that implements each scientific method steps as ten functions keeping specification in a markdown table in the function comments with original paper link to outline the AI pipeline ensemble implementing code as full plan to build.'
577
+ #result = str(result).replace('\n', ' ').replace('|', ' ')
578
+ response3 = chat_with_model45(AppSpecifier + str(response2))
579
+ st.write('🔍Run 4 - AppSpecifier is Complete.')
580
+
581
+ # 🔍Run PythonAppCoder
582
+ PythonAppCoder = ' Complete this streamlit python app implementing the functions in detail using appropriate python libraries and streamlit user interface elements. Show full code listing for the completed detail app as full code listing with no comments or commentary. '
583
+ #result = str(result).replace('\n', ' ').replace('|', ' ')
584
+ response4 = chat_with_model45(PythonAppCoder + str(response3))
585
+ st.write('🔍Run Python AppCoder is Complete.')
586
+
587
+ # experimental 45 - - - - - - - - - - - - -<><><><><>
588
+
589
+ responseAll = '# Query: ' + query + '# Summary: ' + str(response2) + '# Streamlit App Specifier: ' + str(response3) + '# Complete Streamlit App: ' + str(response4) + '# Scholarly Article Links References: ' + str(response1)
590
+ filename = generate_filename(responseAll, "md")
591
+ create_file(filename, query, responseAll, should_save)
592
+
593
+ return responseAll # 🔍Run--------------------------------------------------------
594
+
595
+
596
+ # Function to display the glossary in a structured format
597
+ def display_glossary(glossary, area):
598
+ if area in glossary:
599
+ st.subheader(f"📘 Glossary for {area}")
600
+ for game, terms in glossary[area].items():
601
+ st.markdown(f"### {game}")
602
+ for idx, term in enumerate(terms, start=1):
603
+ st.write(f"{idx}. {term}")
604
+
605
+
606
+ # Function to display the entire glossary in a grid format with links
607
+ def display_glossary_grid(roleplaying_glossary):
608
+ search_urls = {
609
+ "📖": lambda k: f"https://en.wikipedia.org/wiki/{quote(k)}",
610
+ "🔍": lambda k: f"https://www.google.com/search?q={quote(k)}",
611
+ "▶️": lambda k: f"https://www.youtube.com/results?search_query={quote(k)}",
612
+ "🔎": lambda k: f"https://www.bing.com/search?q={quote(k)}",
613
+ "🎲": lambda k: f"https://huggingface.co/spaces/awacke1/World-Ship-Design?q={quote(k)}", # this url plus query!
614
+
615
+ }
616
+
617
+ for category, details in roleplaying_glossary.items():
618
+ st.write(f"### {category}")
619
+ cols = st.columns(len(details)) # Create dynamic columns based on the number of games
620
+ for idx, (game, terms) in enumerate(details.items()):
621
+ with cols[idx]:
622
+ st.markdown(f"#### {game}")
623
+ for term in terms:
624
+ links_md = ' '.join([f"[{emoji}]({url(term)})" for emoji, url in search_urls.items()])
625
+ st.markdown(f"{term} {links_md}", unsafe_allow_html=True)
626
+
627
+
628
+ @st.cache_resource
629
+ def display_videos_and_links():
630
+ video_files = [f for f in os.listdir('.') if f.endswith('.mp4')]
631
+ if not video_files:
632
+ st.write("No MP4 videos found in the current directory.")
633
+ return
634
+
635
+ video_files_sorted = sorted(video_files, key=lambda x: len(x.split('.')[0]))
636
+ num_columns=4
637
+ cols = st.columns(num_columns) # Define num_columns columns outside the loop
638
+ col_index = 0 # Initialize column index
639
+
640
+ for video_file in video_files_sorted:
641
+ with cols[col_index % num_columns]: # Use modulo 2 to alternate between the first and second column
642
+ # Embedding video with autoplay and loop using HTML
643
+ #video_html = ("""<video width="100%" loop autoplay> <source src="{video_file}" type="video/mp4">Your browser does not support the video tag.</video>""")
644
+ #st.markdown(video_html, unsafe_allow_html=True)
645
+ k = video_file.split('.')[0] # Assumes keyword is the file name without extension
646
+ st.video(video_file, format='video/mp4', start_time=0)
647
+ display_glossary_entity(k)
648
+ col_index += 1 # Increment column index to place the next video in the next column
649
+
650
+ @st.cache_resource
651
+ def display_images_and_wikipedia_summariesold():
652
+ image_files = [f for f in os.listdir('.') if f.endswith('.png')]
653
+ if not image_files:
654
+ st.write("No PNG images found in the current directory.")
655
+ return
656
+ image_files_sorted = sorted(image_files, key=lambda x: len(x.split('.')[0]))
657
+ num_columns=4
658
+
659
+ grid_sizes = [len(f.split('.')[0]) for f in image_files_sorted]
660
+ col_sizes = ['small' if size <= 4 else 'medium' if size <= 8 else 'large' for size in grid_sizes]
661
+ num_columns_map = {"small": 4, "medium": 3, "large": 2}
662
+ current_grid_size = 0
663
+ for image_file, col_size in zip(image_files_sorted, col_sizes):
664
+ if current_grid_size != num_columns_map[col_size]:
665
+ cols = st.columns(num_columns_map[col_size])
666
+ current_grid_size = num_columns_map[col_size]
667
+ col_index = 0
668
+ with cols[col_index % current_grid_size]:
669
+ image = Image.open(image_file)
670
+ st.image(image, caption=image_file, use_column_width=True)
671
+ k = image_file.split('.')[0] # Assumes keyword is the file name without extension
672
+ display_glossary_entity(k)
673
+
674
+ @st.cache_resource
675
+ def display_images_and_wikipedia_summaries(num_columns=4):
676
+ image_files = [f for f in os.listdir('.') if f.endswith('.png')]
677
+ if not image_files:
678
+ st.write("No PNG images found in the current directory.")
679
+ return
680
+
681
+ image_files_sorted = sorted(image_files, key=lambda x: len(x.split('.')[0]))
682
+
683
+ cols = st.columns(num_columns) # Use specified num_columns for layout
684
+ col_index = 0 # Initialize column index for cycling through columns
685
+
686
+ for image_file in image_files_sorted:
687
+ with cols[col_index % num_columns]: # Cycle through columns based on num_columns
688
+ image = Image.open(image_file)
689
+ st.image(image, caption=image_file, use_column_width=True)
690
+ k = image_file.split('.')[0] # Assumes keyword is the file name without extension
691
+ display_glossary_entity(k)
692
+ col_index += 1 # Increment to move to the next column in the next iteration
693
+
694
+
695
+
696
+
697
+ def get_all_query_params(key):
698
+ return st.query_params().get(key, [])
699
+
700
+ def clear_query_params():
701
+ st.query_params()
702
+
703
+ # Function to display content or image based on a query
704
+ @st.cache_resource
705
+ def display_content_or_image(query):
706
+ for category, terms in transhuman_glossary.items():
707
+ for term in terms:
708
+ if query.lower() in term.lower():
709
+ st.subheader(f"Found in {category}:")
710
+ st.write(term)
711
+ return True # Return after finding and displaying the first match
712
+ image_dir = "images" # Example directory where images are stored
713
+ image_path = f"{image_dir}/{query}.png" # Construct image path with query
714
+ if os.path.exists(image_path):
715
+ st.image(image_path, caption=f"Image for {query}")
716
+ return True
717
+ st.warning("No matching content or image found.")
718
+ return False
719
+
720
+ game_emojis = {
721
+ "Dungeons and Dragons": "🐉",
722
+ "Call of Cthulhu": "🐙",
723
+ "GURPS": "🎲",
724
+ "Pathfinder": "🗺️",
725
+ "Kindred of the East": "🌅",
726
+ "Changeling": "🍃",
727
+ }
728
+
729
+ topic_emojis = {
730
+ "Core Rulebooks": "📚",
731
+ "Maps & Settings": "🗺️",
732
+ "Game Mechanics & Tools": "⚙️",
733
+ "Monsters & Adversaries": "👹",
734
+ "Campaigns & Adventures": "📜",
735
+ "Creatives & Assets": "🎨",
736
+ "Game Master Resources": "🛠️",
737
+ "Lore & Background": "📖",
738
+ "Character Development": "🧍",
739
+ "Homebrew Content": "🔧",
740
+ "General Topics": "🌍",
741
+ }
742
+
743
+ # Adjusted display_buttons_with_scores function
744
+ def display_buttons_with_scores():
745
+ for category, games in roleplaying_glossary.items():
746
+ category_emoji = topic_emojis.get(category, "🔍") # Default to search icon if no match
747
+ st.markdown(f"## {category_emoji} {category}")
748
+ for game, terms in games.items():
749
+ game_emoji = game_emojis.get(game, "🎮") # Default to generic game controller if no match
750
+ for term in terms:
751
+ key = f"{category}_{game}_{term}".replace(' ', '_').lower()
752
+ score = load_score(key)
753
+ if st.button(f"{game_emoji} {category} {game} {term} {score}", key=key):
754
+ update_score(key)
755
+ # Create a dynamic query incorporating emojis and formatting for clarity
756
+ query_prefix = f"{category_emoji} {game_emoji} ** {category} - {game} - {term} - **"
757
+ # ----------------------------------------------------------------------------------------------
758
+ #query_body = f"Create a detailed outline for **{term}** with subpoints highlighting key aspects, using emojis for visual engagement. Include step-by-step rules and boldface important entities and ruleset elements."
759
+ query_body = f"Create a streamlit python app.py that produces a detailed markdown outline and emoji laden user interface with labels with the entity name and emojis in all labels with a set of streamlit UI components with drop down lists and dataframes and buttons with expander and sidebar for the app to run the data as default values mostly in text boxes. Feature a 3 point outline sith 3 subpoints each where each line has about six words describing this and also contain appropriate emoji for creating sumamry of all aspeccts of this topic. an outline for **{term}** with subpoints highlighting key aspects, using emojis for visual engagement. Include step-by-step rules and boldface important entities and ruleset elements."
760
+ response = search_glossary(query_prefix + query_body)
761
+
762
+
763
+ def fetch_wikipedia_summary(keyword):
764
+ # Placeholder function for fetching Wikipedia summaries
765
+ # In a real app, you might use requests to fetch from the Wikipedia API
766
+ return f"Summary for {keyword}. For more information, visit Wikipedia."
767
+
768
+ def create_search_url_youtube(keyword):
769
+ base_url = "https://www.youtube.com/results?search_query="
770
+ return base_url + keyword.replace(' ', '+')
771
+
772
+ def create_search_url_bing(keyword):
773
+ base_url = "https://www.bing.com/search?q="
774
+ return base_url + keyword.replace(' ', '+')
775
+
776
+ def create_search_url_wikipedia(keyword):
777
+ base_url = "https://www.wikipedia.org/search-redirect.php?family=wikipedia&language=en&search="
778
+ return base_url + keyword.replace(' ', '+')
779
+
780
+ def create_search_url_google(keyword):
781
+ base_url = "https://www.google.com/search?q="
782
+ return base_url + keyword.replace(' ', '+')
783
+
784
+ def create_search_url_ai(keyword):
785
+ base_url = "https://huggingface.co/spaces/awacke1/World-Ship-Design?q="
786
+ return base_url + keyword.replace(' ', '+')
787
+
788
+
789
+ def get_all_query_params(key):
790
+ return st.query_params().get(key, [])
791
+
792
+ def clear_query_params():
793
+ st.query_params()
794
+
795
+ # My Inference API Copy
796
+ API_URL = 'https://qe55p8afio98s0u3.us-east-1.aws.endpoints.huggingface.cloud' # Dr Llama
797
+ # Meta's Original - Chat HF Free Version:
798
+ #API_URL = "https://api-inference.huggingface.co/models/meta-llama/Llama-2-7b-chat-hf"
799
+ API_KEY = os.getenv('API_KEY')
800
+ MODEL1="meta-llama/Llama-2-7b-chat-hf"
801
+ MODEL1URL="https://huggingface.co/meta-llama/Llama-2-7b-chat-hf"
802
+ HF_KEY = os.getenv('HF_KEY')
803
+ headers = {
804
+ "Authorization": f"Bearer {HF_KEY}",
805
+ "Content-Type": "application/json"
806
+ }
807
+ key = os.getenv('OPENAI_API_KEY')
808
+ prompt = "...."
809
+ should_save = st.sidebar.checkbox("💾 Save", value=True, help="Save your session data.")
810
+
811
+
812
+
813
+
814
+ # 3. Stream Llama Response
815
+ # @st.cache_resource
816
+ def StreamLLMChatResponse(prompt):
817
+ try:
818
+ endpoint_url = API_URL
819
+ hf_token = API_KEY
820
+ st.write('Running client ' + endpoint_url)
821
+ client = InferenceClient(endpoint_url, token=hf_token)
822
+ gen_kwargs = dict(
823
+ max_new_tokens=512,
824
+ top_k=30,
825
+ top_p=0.9,
826
+ temperature=0.2,
827
+ repetition_penalty=1.02,
828
+ stop_sequences=["\nUser:", "<|endoftext|>", "</s>"],
829
+ )
830
+ stream = client.text_generation(prompt, stream=True, details=True, **gen_kwargs)
831
+ report=[]
832
+ res_box = st.empty()
833
+ collected_chunks=[]
834
+ collected_messages=[]
835
+ allresults=''
836
+ for r in stream:
837
+ if r.token.special:
838
+ continue
839
+ if r.token.text in gen_kwargs["stop_sequences"]:
840
+ break
841
+ collected_chunks.append(r.token.text)
842
+ chunk_message = r.token.text
843
+ collected_messages.append(chunk_message)
844
+ try:
845
+ report.append(r.token.text)
846
+ if len(r.token.text) > 0:
847
+ result="".join(report).strip()
848
+ res_box.markdown(f'*{result}*')
849
+
850
+ except:
851
+ st.write('Stream llm issue')
852
+ SpeechSynthesis(result)
853
+ return result
854
+ except:
855
+ st.write('Llama model is asleep. Starting up now on A10 - please give 5 minutes then retry as KEDA scales up from zero to activate running container(s).')
856
+
857
+ # 4. Run query with payload
858
+ def query(payload):
859
+ response = requests.post(API_URL, headers=headers, json=payload)
860
+ st.markdown(response.json())
861
+ return response.json()
862
+
863
+ def get_output(prompt):
864
+ return query({"inputs": prompt})
865
+
866
+ # 5. Auto name generated output files from time and content
867
+ def generate_filename(prompt, file_type):
868
+ central = pytz.timezone('US/Central')
869
+ safe_date_time = datetime.now(central).strftime("%m%d_%H%M")
870
+ replaced_prompt = prompt.replace(" ", "_").replace("\n", "_")
871
+ safe_prompt = "".join(x for x in replaced_prompt if x.isalnum() or x == "_")[:255] # 255 is linux max, 260 is windows max
872
+ #safe_prompt = "".join(x for x in replaced_prompt if x.isalnum() or x == "_")[:45]
873
+ return f"{safe_date_time}_{safe_prompt}.{file_type}"
874
+
875
+ # 6. Speech transcription via OpenAI service
876
+ def transcribe_audio(openai_key, file_path, model):
877
+ openai.api_key = openai_key
878
+ OPENAI_API_URL = "https://api.openai.com/v1/audio/transcriptions"
879
+ headers = {
880
+ "Authorization": f"Bearer {openai_key}",
881
+ }
882
+ with open(file_path, 'rb') as f:
883
+ data = {'file': f}
884
+ st.write('STT transcript ' + OPENAI_API_URL)
885
+ response = requests.post(OPENAI_API_URL, headers=headers, files=data, data={'model': model})
886
+ if response.status_code == 200:
887
+ st.write(response.json())
888
+ chatResponse = chat_with_model(response.json().get('text'), '') # *************************************
889
+ transcript = response.json().get('text')
890
+ filename = generate_filename(transcript, 'txt')
891
+ response = chatResponse
892
+ user_prompt = transcript
893
+ create_file(filename, user_prompt, response, should_save)
894
+ return transcript
895
+ else:
896
+ st.write(response.json())
897
+ st.error("Error in API call.")
898
+ return None
899
+
900
+ # 7. Auto stop on silence audio control for recording WAV files
901
+ def save_and_play_audio(audio_recorder):
902
+ audio_bytes = audio_recorder(key='audio_recorder')
903
+ if audio_bytes:
904
+ filename = generate_filename("Recording", "wav")
905
+ with open(filename, 'wb') as f:
906
+ f.write(audio_bytes)
907
+ st.audio(audio_bytes, format="audio/wav")
908
+ return filename
909
+ return None
910
+
911
+ # 8. File creator that interprets type and creates output file for text, markdown and code
912
+ def create_file(filename, prompt, response, should_save=True):
913
+ if not should_save:
914
+ return
915
+ base_filename, ext = os.path.splitext(filename)
916
+ if ext in ['.txt', '.htm', '.md']:
917
+ with open(f"{base_filename}.md", 'w') as file:
918
+ try:
919
+ content = prompt.strip() + '\r\n' + response
920
+ file.write(content)
921
+ except:
922
+ st.write('.')
923
+
924
+ #has_python_code = re.search(r"```python([\s\S]*?)```", prompt.strip() + '\r\n' + response)
925
+ #has_python_code = bool(re.search(r"```python([\s\S]*?)```", prompt.strip() + '\r\n' + response))
926
+ #if has_python_code:
927
+ # python_code = re.findall(r"```python([\s\S]*?)```", response)[0].strip()
928
+ # with open(f"{base_filename}-Code.py", 'w') as file:
929
+ # file.write(python_code)
930
+ # with open(f"{base_filename}.md", 'w') as file:
931
+ # content = prompt.strip() + '\r\n' + response
932
+ # file.write(content)
933
+
934
+ def truncate_document(document, length):
935
+ return document[:length]
936
+ def divide_document(document, max_length):
937
+ return [document[i:i+max_length] for i in range(0, len(document), max_length)]
938
+
939
+ def CompressXML(xml_text):
940
+ root = ET.fromstring(xml_text)
941
+ for elem in list(root.iter()):
942
+ if isinstance(elem.tag, str) and 'Comment' in elem.tag:
943
+ elem.parent.remove(elem)
944
+ return ET.tostring(root, encoding='unicode', method="xml")
945
+
946
+ # 10. Read in and provide UI for past files
947
+ @st.cache_resource
948
+ def read_file_content(file,max_length):
949
+ if file.type == "application/json":
950
+ content = json.load(file)
951
+ return str(content)
952
+ elif file.type == "text/html" or file.type == "text/htm":
953
+ content = BeautifulSoup(file, "html.parser")
954
+ return content.text
955
+ elif file.type == "application/xml" or file.type == "text/xml":
956
+ tree = ET.parse(file)
957
+ root = tree.getroot()
958
+ xml = CompressXML(ET.tostring(root, encoding='unicode'))
959
+ return xml
960
+ elif file.type == "text/markdown" or file.type == "text/md":
961
+ md = mistune.create_markdown()
962
+ content = md(file.read().decode())
963
+ return content
964
+ elif file.type == "text/plain":
965
+ return file.getvalue().decode()
966
+ else:
967
+ return ""
968
+
969
+
970
+ # 11. Chat with GPT - Caution on quota - now favoring fastest AI pipeline STT Whisper->LLM Llama->TTS
971
+ @st.cache_resource
972
+ def chat_with_model(prompt, document_section='', model_choice='gpt-3.5-turbo'): # gpt-4-0125-preview gpt-3.5-turbo
973
+ #def chat_with_model(prompt, document_section='', model_choice='gpt-4-0125-preview'): # gpt-4-0125-preview gpt-3.5-turbo
974
+ model = model_choice
975
+ conversation = [{'role': 'system', 'content': 'You are a coder, inventor, and writer of quotes on wisdom as a helpful expert in all fields of health, math, development and AI using python.'}]
976
+ conversation.append({'role': 'user', 'content': prompt})
977
+ if len(document_section)>0:
978
+ conversation.append({'role': 'assistant', 'content': document_section})
979
+ start_time = time.time()
980
+ report = []
981
+ res_box = st.empty()
982
+ collected_chunks = []
983
+ collected_messages = []
984
+
985
+ for chunk in openai.ChatCompletion.create(model=model_choice, messages=conversation, temperature=0.5, stream=True):
986
+ collected_chunks.append(chunk)
987
+ chunk_message = chunk['choices'][0]['delta']
988
+ collected_messages.append(chunk_message)
989
+ content=chunk["choices"][0].get("delta",{}).get("content")
990
+ try:
991
+ report.append(content)
992
+ if len(content) > 0:
993
+ result = "".join(report).strip()
994
+ res_box.markdown(f'*{result}*')
995
+ except:
996
+ st.write(' ')
997
+ full_reply_content = ''.join([m.get('content', '') for m in collected_messages])
998
+ st.write("Elapsed time:")
999
+ st.write(time.time() - start_time)
1000
+ return full_reply_content
1001
+
1002
+ # 11.1 45
1003
+ @st.cache_resource
1004
+ #def chat_with_model(prompt, document_section='', model_choice='gpt-3.5-turbo'): # gpt-4-0125-preview gpt-3.5-turbo
1005
+ def chat_with_model45(prompt, document_section='', model_choice='gpt-4-0125-preview'): # gpt-4-0125-preview gpt-3.5-turbo
1006
+ model = model_choice
1007
+ conversation = [{'role': 'system', 'content': 'You are a coder, inventor, and writer of quotes on wisdom as a helpful expert in all fields of health, math, development and AI using python.'}]
1008
+ conversation.append({'role': 'user', 'content': prompt})
1009
+ if len(document_section)>0:
1010
+ conversation.append({'role': 'assistant', 'content': document_section})
1011
+ start_time = time.time()
1012
+ report = []
1013
+ res_box = st.empty()
1014
+ collected_chunks = []
1015
+ collected_messages = []
1016
+
1017
+ for chunk in openai.ChatCompletion.create(model=model_choice, messages=conversation, temperature=0.5, stream=True):
1018
+ collected_chunks.append(chunk)
1019
+ chunk_message = chunk['choices'][0]['delta']
1020
+ collected_messages.append(chunk_message)
1021
+ content=chunk["choices"][0].get("delta",{}).get("content")
1022
+ try:
1023
+ report.append(content)
1024
+ if len(content) > 0:
1025
+ result = "".join(report).strip()
1026
+ res_box.markdown(f'*{result}*')
1027
+ except:
1028
+ st.write(' ')
1029
+ full_reply_content = ''.join([m.get('content', '') for m in collected_messages])
1030
+ st.write("Elapsed time:")
1031
+ st.write(time.time() - start_time)
1032
+ return full_reply_content
1033
+
1034
+ @st.cache_resource
1035
+ def chat_with_file_contents(prompt, file_content, model_choice='gpt-3.5-turbo'): # gpt-4-0125-preview gpt-3.5-turbo
1036
+ #def chat_with_file_contents(prompt, file_content, model_choice='gpt-4-0125-preview'): # gpt-4-0125-preview gpt-3.5-turbo
1037
+ conversation = [{'role': 'system', 'content': 'You are a helpful assistant.'}]
1038
+ conversation.append({'role': 'user', 'content': prompt})
1039
+ if len(file_content)>0:
1040
+ conversation.append({'role': 'assistant', 'content': file_content})
1041
+ response = openai.ChatCompletion.create(model=model_choice, messages=conversation)
1042
+ return response['choices'][0]['message']['content']
1043
+
1044
+
1045
+ def extract_mime_type(file):
1046
+ if isinstance(file, str):
1047
+ pattern = r"type='(.*?)'"
1048
+ match = re.search(pattern, file)
1049
+ if match:
1050
+ return match.group(1)
1051
+ else:
1052
+ raise ValueError(f"Unable to extract MIME type from {file}")
1053
+ elif isinstance(file, streamlit.UploadedFile):
1054
+ return file.type
1055
+ else:
1056
+ raise TypeError("Input should be a string or a streamlit.UploadedFile object")
1057
+
1058
+ def extract_file_extension(file):
1059
+ # get the file name directly from the UploadedFile object
1060
+ file_name = file.name
1061
+ pattern = r".*?\.(.*?)$"
1062
+ match = re.search(pattern, file_name)
1063
+ if match:
1064
+ return match.group(1)
1065
+ else:
1066
+ raise ValueError(f"Unable to extract file extension from {file_name}")
1067
+
1068
+ # Normalize input as text from PDF and other formats
1069
+ @st.cache_resource
1070
+ def pdf2txt(docs):
1071
+ text = ""
1072
+ for file in docs:
1073
+ file_extension = extract_file_extension(file)
1074
+ st.write(f"File type extension: {file_extension}")
1075
+ if file_extension.lower() in ['py', 'txt', 'html', 'htm', 'xml', 'json']:
1076
+ text += file.getvalue().decode('utf-8')
1077
+ elif file_extension.lower() == 'pdf':
1078
+ from PyPDF2 import PdfReader
1079
+ pdf = PdfReader(BytesIO(file.getvalue()))
1080
+ for page in range(len(pdf.pages)):
1081
+ text += pdf.pages[page].extract_text() # new PyPDF2 syntax
1082
+ return text
1083
+
1084
+ def txt2chunks(text):
1085
+ text_splitter = CharacterTextSplitter(separator="\n", chunk_size=1000, chunk_overlap=200, length_function=len)
1086
+ return text_splitter.split_text(text)
1087
+
1088
+ # Vector Store using FAISS
1089
+ @st.cache_resource
1090
+ def vector_store(text_chunks):
1091
+ embeddings = OpenAIEmbeddings(openai_api_key=key)
1092
+ return FAISS.from_texts(texts=text_chunks, embedding=embeddings)
1093
+
1094
+ # Memory and Retrieval chains
1095
+ @st.cache_resource
1096
+ def get_chain(vectorstore):
1097
+ llm = ChatOpenAI()
1098
+ memory = ConversationBufferMemory(memory_key='chat_history', return_messages=True)
1099
+ return ConversationalRetrievalChain.from_llm(llm=llm, retriever=vectorstore.as_retriever(), memory=memory)
1100
+
1101
+ def process_user_input(user_question):
1102
+ response = st.session_state.conversation({'question': user_question})
1103
+ st.session_state.chat_history = response['chat_history']
1104
+ for i, message in enumerate(st.session_state.chat_history):
1105
+ template = user_template if i % 2 == 0 else bot_template
1106
+ st.write(template.replace("{{MSG}}", message.content), unsafe_allow_html=True)
1107
+ filename = generate_filename(user_question, 'txt')
1108
+ response = message.content
1109
+ user_prompt = user_question
1110
+ create_file(filename, user_prompt, response, should_save)
1111
+
1112
+ def divide_prompt(prompt, max_length):
1113
+ words = prompt.split()
1114
+ chunks = []
1115
+ current_chunk = []
1116
+ current_length = 0
1117
+ for word in words:
1118
+ if len(word) + current_length <= max_length:
1119
+ current_length += len(word) + 1
1120
+ current_chunk.append(word)
1121
+ else:
1122
+ chunks.append(' '.join(current_chunk))
1123
+ current_chunk = [word]
1124
+ current_length = len(word)
1125
+ chunks.append(' '.join(current_chunk))
1126
+ return chunks
1127
+
1128
+
1129
+
1130
+ API_URL_IE = f'https://tonpixzfvq3791u9.us-east-1.aws.endpoints.huggingface.cloud'
1131
+ API_URL_IE = "https://api-inference.huggingface.co/models/openai/whisper-small.en"
1132
+ MODEL2 = "openai/whisper-small.en"
1133
+ MODEL2_URL = "https://huggingface.co/openai/whisper-small.en"
1134
+ HF_KEY = st.secrets['HF_KEY']
1135
+ headers = {
1136
+ "Authorization": f"Bearer {HF_KEY}",
1137
+ "Content-Type": "audio/wav"
1138
+ }
1139
+
1140
+ def query(filename):
1141
+ with open(filename, "rb") as f:
1142
+ data = f.read()
1143
+ response = requests.post(API_URL_IE, headers=headers, data=data)
1144
+ return response.json()
1145
+
1146
+ def generate_filename(prompt, file_type):
1147
+ central = pytz.timezone('US/Central')
1148
+ safe_date_time = datetime.now(central).strftime("%m%d_%H%M")
1149
+ replaced_prompt = prompt.replace(" ", "_").replace("\n", "_")
1150
+ safe_prompt = "".join(x for x in replaced_prompt if x.isalnum() or x == "_")[:90]
1151
+ return f"{safe_date_time}_{safe_prompt}.{file_type}"
1152
+
1153
+ # 15. Audio recorder to Wav file
1154
+ def save_and_play_audio(audio_recorder):
1155
+ audio_bytes = audio_recorder()
1156
+ if audio_bytes:
1157
+ filename = generate_filename("Recording", "wav")
1158
+ with open(filename, 'wb') as f:
1159
+ f.write(audio_bytes)
1160
+ st.audio(audio_bytes, format="audio/wav")
1161
+ return filename
1162
+
1163
+ # 16. Speech transcription to file output
1164
+ def transcribe_audio(filename):
1165
+ output = query(filename)
1166
+ return output
1167
+
1168
+
1169
+ # Sample function to demonstrate a response, replace with your own logic
1170
+ def StreamMedChatResponse(topic):
1171
+ st.write(f"Showing resources or questions related to: {topic}")
1172
+
1173
+ # Function to encode file to base64
1174
+ def get_base64_encoded_file(file_path):
1175
+ with open(file_path, "rb") as file:
1176
+ return base64.b64encode(file.read()).decode()
1177
+
1178
+ # Function to create a download link
1179
+ def get_audio_download_link(file_path):
1180
+ base64_file = get_base64_encoded_file(file_path)
1181
+ return f'<a href="data:file/wav;base64,{base64_file}" download="{os.path.basename(file_path)}">⬇️ Download Audio</a>'
1182
+
1183
+ # Sidebar of past encounters
1184
+ all_files = glob.glob("*.wav")
1185
+ all_files = [file for file in all_files if len(os.path.splitext(file)[0]) >= 10] # exclude files with short names
1186
+ all_files.sort(key=lambda x: (os.path.splitext(x)[1], x), reverse=True) # sort by file type and file name in descending order
1187
+
1188
+ filekey = 'delall'
1189
+ if st.sidebar.button("🗑 Delete All Audio", key=filekey):
1190
+ for file in all_files:
1191
+ os.remove(file)
1192
+ st.experimental_rerun()
1193
+
1194
+ for file in all_files:
1195
+ col1, col2 = st.sidebar.columns([6, 1]) # adjust the ratio as needed
1196
+ with col1:
1197
+ st.markdown(file)
1198
+ if st.button("🎵", key="play_" + file): # play emoji button
1199
+ audio_file = open(file, 'rb')
1200
+ audio_bytes = audio_file.read()
1201
+ st.audio(audio_bytes, format='audio/wav')
1202
+ #st.markdown(get_audio_download_link(file), unsafe_allow_html=True)
1203
+ #st.text_input(label="", value=file)
1204
+ with col2:
1205
+ if st.button("🗑", key="delete_" + file):
1206
+ os.remove(file)
1207
+ st.experimental_rerun()
1208
+
1209
+
1210
+
1211
+ GiveFeedback=False
1212
+ if GiveFeedback:
1213
+ with st.expander("Give your feedback 👍", expanded=False):
1214
+ feedback = st.radio("Step 8: Give your feedback", ("👍 Upvote", "👎 Downvote"))
1215
+ if feedback == "👍 Upvote":
1216
+ st.write("You upvoted 👍. Thank you for your feedback!")
1217
+ else:
1218
+ st.write("You downvoted 👎. Thank you for your feedback!")
1219
+ load_dotenv()
1220
+ st.write(css, unsafe_allow_html=True)
1221
+ st.header("Chat with documents :books:")
1222
+ user_question = st.text_input("Ask a question about your documents:")
1223
+ if user_question:
1224
+ process_user_input(user_question)
1225
+ with st.sidebar:
1226
+ st.subheader("Your documents")
1227
+ docs = st.file_uploader("import documents", accept_multiple_files=True)
1228
+ with st.spinner("Processing"):
1229
+ raw = pdf2txt(docs)
1230
+ if len(raw) > 0:
1231
+ length = str(len(raw))
1232
+ text_chunks = txt2chunks(raw)
1233
+ vectorstore = vector_store(text_chunks)
1234
+ st.session_state.conversation = get_chain(vectorstore)
1235
+ st.markdown('# AI Search Index of Length:' + length + ' Created.') # add timing
1236
+ filename = generate_filename(raw, 'txt')
1237
+ create_file(filename, raw, '', should_save)
1238
+
1239
+ try:
1240
+ query_params = st.query_params
1241
+ query = (query_params.get('q') or query_params.get('query') or [''])
1242
+ if query:
1243
+ result = search_arxiv(query)
1244
+ result2 = search_glossary(result)
1245
+ except:
1246
+ st.markdown(' ')
1247
+
1248
+ if 'action' in st.query_params:
1249
+ action = st.query_params()['action'][0] # Get the first (or only) 'action' parameter
1250
+ if action == 'show_message':
1251
+ st.success("Showing a message because 'action=show_message' was found in the URL.")
1252
+ elif action == 'clear':
1253
+ clear_query_params()
1254
+ st.experimental_rerun()
1255
+
1256
+ # Handling repeated keys
1257
+ #if 'multi' in st.query_params:
1258
+ # multi_values = get_all_query_params('multi')
1259
+ # st.write("Values for 'multi':", multi_values)
1260
+
1261
+ # Manual entry for demonstration
1262
+ #st.write("Enter query parameters in the URL like this: ?action=show_message&multi=1&multi=2")
1263
+
1264
+ if 'query' in st.query_params:
1265
+ query = st.query_params['query'][0] # Get the query parameter
1266
+ # Display content or image based on the query
1267
+ display_content_or_image(query)
1268
+
1269
+ # Add a clear query parameters button for convenience
1270
+ #if st.button("Clear Query Parameters", key='ClearQueryParams'):
1271
+ # This will clear the browser URL's query parameters
1272
+ # st.experimental_set_query_params
1273
+ # st.experimental_rerun()
1274
+
1275
+
1276
+ st.markdown("### 🎲🗺️ Arxiv Paper Search QA RAG MAS using Streamlit and Gradio API")
1277
+
1278
+ filename = save_and_play_audio(audio_recorder)
1279
+ if filename is not None:
1280
+ transcription = transcribe_audio(filename)
1281
+ try:
1282
+ transcript = transcription['text']
1283
+ st.write(transcript)
1284
+
1285
+ except:
1286
+ transcript=''
1287
+ st.write(transcript)
1288
+
1289
+ st.write('Reasoning with your inputs..')
1290
+ response = chat_with_model(transcript)
1291
+ st.write('Response:')
1292
+ st.write(response)
1293
+ filename = generate_filename(response, "txt")
1294
+ create_file(filename, transcript, response, should_save)
1295
+
1296
+ # Whisper to Llama:
1297
+ response = StreamLLMChatResponse(transcript)
1298
+ filename_txt = generate_filename(transcript, "md")
1299
+ create_file(filename_txt, transcript, response, should_save)
1300
+ filename_wav = filename_txt.replace('.txt', '.wav')
1301
+ import shutil
1302
+ try:
1303
+ if os.path.exists(filename):
1304
+ shutil.copyfile(filename, filename_wav)
1305
+ except:
1306
+ st.write('.')
1307
+ if os.path.exists(filename):
1308
+ os.remove(filename)
1309
+
1310
+
1311
+
1312
+
1313
+ prompt = '''
1314
+ What is MoE?
1315
+ What are Multi Agent Systems?
1316
+ What is Self Rewarding AI?
1317
+ What is Semantic and Episodic memory?
1318
+ What is AutoGen?
1319
+ What is ChatDev?
1320
+ What is Omniverse?
1321
+ What is Lumiere?
1322
+ What is SORA?
1323
+ '''
1324
+
1325
+
1326
+ # Search History to ArXiv
1327
+ session_state = {}
1328
+ if "search_queries" not in session_state:
1329
+ session_state["search_queries"] = []
1330
+ example_input = st.text_input("Search", value=session_state["search_queries"][-1] if session_state["search_queries"] else "")
1331
+ if example_input:
1332
+ session_state["search_queries"].append(example_input)
1333
+
1334
+ # Search AI
1335
+ query=example_input
1336
+ if query:
1337
+ result = search_arxiv(query)
1338
+ #search_glossary(query)
1339
+ search_glossary(result)
1340
+ st.markdown(' ')
1341
+
1342
+ st.write("Search history:")
1343
+ for example_input in session_state["search_queries"]:
1344
+ st.write(example_input)
1345
+
1346
+ if st.button("Run Prompt", help="Click to run."):
1347
+ try:
1348
+ response=StreamLLMChatResponse(example_input)
1349
+ create_file(filename, example_input, response, should_save)
1350
+ except:
1351
+ st.write('model is asleep. Starting now on A10 GPU. Please wait one minute then retry. KEDA triggered.')
1352
+
1353
+ openai.api_key = os.getenv('OPENAI_API_KEY')
1354
+ if openai.api_key == None: openai.api_key = st.secrets['OPENAI_API_KEY']
1355
+ menu = ["txt", "htm", "xlsx", "csv", "md", "py"]
1356
+ choice = st.sidebar.selectbox("Output File Type:", menu)
1357
+
1358
+ #model_choice = st.sidebar.radio("Select Model:", ('gpt-3.5-turbo', 'gpt-3.5-turbo-0301'))
1359
+ #user_prompt = st.text_area("Enter prompts, instructions & questions:", '', height=100)
1360
+
1361
+
1362
+ collength, colupload = st.columns([2,3]) # adjust the ratio as needed
1363
+ with collength:
1364
+ max_length = st.slider(key='maxlength', label="File section length for large files", min_value=1000, max_value=128000, value=12000, step=1000)
1365
+ with colupload:
1366
+ uploaded_file = st.file_uploader("Add a file for context:", type=["pdf", "xml", "json", "xlsx", "csv", "html", "htm", "md", "txt"])
1367
+ document_sections = deque()
1368
+ document_responses = {}
1369
+ if uploaded_file is not None:
1370
+ file_content = read_file_content(uploaded_file, max_length)
1371
+ document_sections.extend(divide_document(file_content, max_length))
1372
+
1373
+
1374
+ if len(document_sections) > 0:
1375
+ if st.button("👁️ View Upload"):
1376
+ st.markdown("**Sections of the uploaded file:**")
1377
+ for i, section in enumerate(list(document_sections)):
1378
+ st.markdown(f"**Section {i+1}**\n{section}")
1379
+
1380
+ st.markdown("**Chat with the model:**")
1381
+ for i, section in enumerate(list(document_sections)):
1382
+ if i in document_responses:
1383
+ st.markdown(f"**Section {i+1}**\n{document_responses[i]}")
1384
+ else:
1385
+ if st.button(f"Chat about Section {i+1}"):
1386
+ st.write('Reasoning with your inputs...')
1387
+ st.write('Response:')
1388
+ st.write(response)
1389
+ document_responses[i] = response
1390
+ filename = generate_filename(f"{user_prompt}_section_{i+1}", choice)
1391
+ create_file(filename, user_prompt, response, should_save)
1392
+ st.sidebar.markdown(get_table_download_link(filename), unsafe_allow_html=True)
1393
+
1394
+ #if st.button('💬 Chat'):
1395
+ # st.write('Reasoning with your inputs...')
1396
+ # user_prompt_sections = divide_prompt(user_prompt, max_length)
1397
+ # full_response = ''
1398
+ # for prompt_section in user_prompt_sections:
1399
+ # response = chat_with_model(prompt_section, ''.join(list(document_sections)), model_choice)
1400
+ # full_response += response + '\n' # Combine the responses
1401
+ # response = full_response
1402
+ # st.write('Response:')
1403
+ # st.write(response)
1404
+ # filename = generate_filename(user_prompt, choice)
1405
+ # create_file(filename, user_prompt, response, should_save)
1406
+
1407
+ display_glossary_grid(roleplaying_glossary) # Word Glossary Jump Grid
1408
+ display_videos_and_links() # Video Jump Grid
1409
+ display_images_and_wikipedia_summaries() # Image Jump Grid
1410
+ #display_buttons_with_scores() # Feedback Jump Grid