awacke1 commited on
Commit
3fd1dcd
1 Parent(s): 26b2b9a

Create app.py

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