awacke1 commited on
Commit
549eeff
1 Parent(s): f107425

Upload 3 files

Browse files
Arxiv-Paper-Search-QA-RAG-Streamlit-Gradio-AP.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0db1beaf2a830a14ec819ac46a1882d418523aa8a392ebdaf24e0cdaf905e40e
3
+ size 380614
app.py ADDED
@@ -0,0 +1,1620 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import streamlit.components.v1 as components
3
+ import os
4
+ import json
5
+ import random
6
+ import base64
7
+ import glob
8
+ import math
9
+ import openai
10
+ import pytz
11
+ import re
12
+ import requests
13
+ import textract
14
+ import time
15
+ import zipfile
16
+ import dotenv
17
+
18
+ from gradio_client import Client
19
+ from audio_recorder_streamlit import audio_recorder
20
+ from bs4 import BeautifulSoup
21
+ from collections import deque
22
+ from datetime import datetime
23
+ from dotenv import load_dotenv
24
+ from huggingface_hub import InferenceClient
25
+ from io import BytesIO
26
+ from openai import ChatCompletion
27
+ from PyPDF2 import PdfReader
28
+ from templates import bot_template, css, user_template
29
+ from xml.etree import ElementTree as ET
30
+ from PIL import Image
31
+ from urllib.parse import quote # Ensure this import is included
32
+
33
+ # 1. Configuration
34
+ Site_Name = 'Scholarly-Article-Document-Search-With-Memory'
35
+ title="🔬🧠ScienceBrain.AI"
36
+ helpURL='https://huggingface.co/awacke1'
37
+ bugURL='https://huggingface.co/spaces/awacke1'
38
+ icons='🔬'
39
+
40
+ st.set_page_config(
41
+ page_title=title,
42
+ page_icon=icons,
43
+ layout="wide",
44
+ initial_sidebar_state="expanded",
45
+ menu_items={
46
+ 'Get Help': helpURL,
47
+ 'Report a bug': bugURL,
48
+ 'About': title
49
+ }
50
+ )
51
+
52
+
53
+ def load_file(file_name):
54
+ with open(file_name, "r", encoding='utf-8') as file:
55
+ #with open(file_name, "r") as file:
56
+ content = file.read()
57
+ return content
58
+
59
+
60
+ # HTML5 based Speech Synthesis (Text to Speech in Browser)
61
+ @st.cache_resource
62
+ def SpeechSynthesis(result):
63
+ documentHTML5='''
64
+ <!DOCTYPE html>
65
+ <html>
66
+ <head>
67
+ <title>Read It Aloud</title>
68
+ <script type="text/javascript">
69
+ function readAloud() {
70
+ const text = document.getElementById("textArea").value;
71
+ const speech = new SpeechSynthesisUtterance(text);
72
+ window.speechSynthesis.speak(speech);
73
+ }
74
+ </script>
75
+ </head>
76
+ <body>
77
+ <h1>🔊 Read It Aloud</h1>
78
+ <textarea id="textArea" rows="10" cols="80">
79
+ '''
80
+ documentHTML5 = documentHTML5 + result
81
+ documentHTML5 = documentHTML5 + '''
82
+ </textarea>
83
+ <br>
84
+ <button onclick="readAloud()">🔊 Read Aloud</button>
85
+ </body>
86
+ </html>
87
+ '''
88
+ components.html(documentHTML5, width=1280, height=300)
89
+
90
+ def parse_to_markdown(text):
91
+ return text
92
+
93
+
94
+
95
+
96
+ import re
97
+
98
+ def extract_urls(text):
99
+ try:
100
+ # Regular expression patterns to find the required fields
101
+ date_pattern = re.compile(r'### (\d{2} \w{3} \d{4})')
102
+ abs_link_pattern = re.compile(r'\[(.*?)\]\((https://arxiv\.org/abs/\d+\.\d+)\)')
103
+ pdf_link_pattern = re.compile(r'\[⬇️\]\((https://arxiv\.org/pdf/\d+\.\d+)\)')
104
+ title_pattern = re.compile(r'### \d{2} \w{3} \d{4} \| \[(.*?)\]')
105
+
106
+ # Find all occurrences of the required fields using the regular expression patterns
107
+ date_matches = date_pattern.findall(text)
108
+ abs_link_matches = abs_link_pattern.findall(text)
109
+ pdf_link_matches = pdf_link_pattern.findall(text)
110
+ title_matches = title_pattern.findall(text)
111
+
112
+ # Generate markdown string with the extracted fields
113
+ markdown_text = ""
114
+ for i in range(len(date_matches)):
115
+ date = date_matches[i]
116
+ title = title_matches[i]
117
+ abs_link = abs_link_matches[i][1]
118
+ pdf_link = pdf_link_matches[i]
119
+
120
+ markdown_text += f"**Date:** {date}\n\n"
121
+ markdown_text += f"**Title:** {title}\n\n"
122
+ markdown_text += f"**Abstract Link:** [{abs_link}]({abs_link})\n\n"
123
+ markdown_text += f"**PDF Link:** [{pdf_link}]({pdf_link})\n\n"
124
+ markdown_text += "---\n\n"
125
+
126
+ return markdown_text
127
+ except:
128
+ st.write('.')
129
+ return ''
130
+
131
+
132
+
133
+ def download_pdfs(urls):
134
+ local_files = []
135
+ for url in urls:
136
+ if url.endswith('.pdf'):
137
+ local_filename = url.split('/')[-1]
138
+ response = requests.get(url)
139
+ with open(local_filename, 'wb') as f:
140
+ f.write(response.content)
141
+ local_files.append(local_filename)
142
+ return local_files
143
+
144
+ def generate_html(local_files):
145
+ html = "<ul>"
146
+ for file in local_files:
147
+ link = f'<li><a href="{file}">{file}</a></li>'
148
+ html += link
149
+ html += "</ul>"
150
+ return html
151
+
152
+ #@st.cache_resource
153
+ def search_arxiv(query):
154
+ start_time = time.strftime("%Y-%m-%d %H:%M:%S")
155
+ client = Client("awacke1/Arxiv-Paper-Search-And-QA-RAG-Pattern")
156
+
157
+ # Search 1 - Retrieve the Papers
158
+ client = Client("awacke1/Arxiv-Paper-Search-And-QA-RAG-Pattern")
159
+ response1 = client.predict(
160
+ query,
161
+ 20,
162
+ "Semantic Search - up to 10 Mar 2024",
163
+ "mistralai/Mixtral-8x7B-Instruct-v0.1",
164
+ api_name="/update_with_rag_md"
165
+ )
166
+ Question = '### 🔎 ' + query + '\r\n' # Format for markdown display with links
167
+ References = response1[0]
168
+
169
+ # URLs from the response
170
+ ReferenceLinks = extract_urls(References)
171
+
172
+ RunSecondQuery = True
173
+ if RunSecondQuery:
174
+ # Search 2 - Retrieve the Summary with Papers Context and Original Query
175
+ response2 = client.predict(
176
+ query,
177
+ "mistralai/Mixtral-8x7B-Instruct-v0.1",
178
+ True,
179
+ api_name="/ask_llm"
180
+ )
181
+ if len(response2) > 10:
182
+ Answer = response2
183
+ SpeechSynthesis(Answer)
184
+ # Restructure results to follow format of Question, Answer, References, ReferenceLinks
185
+ results = Question + '\r\n' + Answer + '\r\n' + References + '\r\n' + ReferenceLinks
186
+ st.markdown(results)
187
+
188
+ st.write('🔍Run of Multi-Agent System Paper Summary Spec is Complete')
189
+ end_time = time.strftime("%Y-%m-%d %H:%M:%S")
190
+
191
+ # Output
192
+ start_timestamp = time.mktime(time.strptime(start_time, "%Y-%m-%d %H:%M:%S"))
193
+ end_timestamp = time.mktime(time.strptime(end_time, "%Y-%m-%d %H:%M:%S"))
194
+ elapsed_seconds = end_timestamp - start_timestamp
195
+ st.write(f"Start time: {start_time}")
196
+ st.write(f"Finish time: {end_time}")
197
+ st.write(f"Elapsed time: {elapsed_seconds:.2f} seconds")
198
+ filename = generate_filename(query, "md")
199
+ create_file(filename, query, results, should_save)
200
+ return results
201
+
202
+ def download_pdfs_and_generate_html(urls):
203
+ pdf_links = []
204
+ for url in urls:
205
+ if url.endswith('.pdf'):
206
+ pdf_filename = os.path.basename(url)
207
+ download_pdf(url, pdf_filename)
208
+ pdf_links.append(pdf_filename)
209
+ local_links_html = '<ul>'
210
+ for link in pdf_links:
211
+ local_links_html += f'<li><a href="{link}">{link}</a></li>'
212
+ local_links_html += '</ul>'
213
+ return local_links_html
214
+
215
+ def download_pdf(url, filename):
216
+ response = requests.get(url)
217
+ with open(filename, 'wb') as file:
218
+ file.write(response.content)
219
+
220
+ # Prompts for App, for App Product, and App Product Code
221
+ 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 '
222
+ 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: '
223
+ 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:'
224
+
225
+
226
+ roleplaying_glossary = {
227
+ "🤖 AI Concepts": {
228
+ "MoE (Mixture of Experts) 🧠": [
229
+ "What are Multi Agent Systems for Health",
230
+ "What is Mixture of Experts for Health",
231
+ "What are Semantic and Episodic Memory and what is Mirroring for Behavioral Health",
232
+ "What are Self Rewarding AI Systems for Health",
233
+ "How are AGI and AMI systems created using Multi Agent Systems and Mixture of Experts for Health"
234
+ ],
235
+ "Multi Agent Systems (MAS) 🤝": [
236
+ "Distributed AI systems",
237
+ "Autonomous agents interacting",
238
+ "Cooperative and competitive behavior",
239
+ "Decentralized problem-solving",
240
+ "Applications in robotics, simulations, and more"
241
+ ],
242
+ "Self Rewarding AI 🎁": [
243
+ "Intrinsic motivation for AI agents",
244
+ "Autonomous goal setting and achievement",
245
+ "Exploration and curiosity-driven learning",
246
+ "Potential for open-ended development",
247
+ "Research area in reinforcement learning"
248
+ ],
249
+ "Semantic and Episodic Memory 📚": [
250
+ "Two types of long-term memory",
251
+ "Semantic: facts and general knowledge",
252
+ "Episodic: personal experiences and events",
253
+ "Crucial for AI systems to understand and reason",
254
+ "Research in knowledge representation and retrieval"
255
+ ]
256
+ },
257
+ "🛠️ AI Tools & Platforms": {
258
+ "AutoGen 🔧": [
259
+ "Automated machine learning (AutoML) tool",
260
+ "Generates AI models based on requirements",
261
+ "Simplifies AI development process",
262
+ "Accessible to non-experts",
263
+ "Integration with various data sources"
264
+ ],
265
+ "ChatDev 💬": [
266
+ "Platform for building chatbots and conversational AI",
267
+ "Drag-and-drop interface for designing chat flows",
268
+ "Pre-built templates and integrations",
269
+ "Supports multiple messaging platforms",
270
+ "Analytics and performance tracking"
271
+ ],
272
+ "Omniverse 🌐": [
273
+ "Nvidia's 3D simulation and collaboration platform",
274
+ "Physically accurate virtual worlds",
275
+ "Supports AI training and testing",
276
+ "Used in industries like robotics, architecture, and gaming",
277
+ "Enables seamless collaboration and data exchange"
278
+ ],
279
+ "Lumiere 🎥": [
280
+ "AI-powered video analytics platform",
281
+ "Extracts insights and metadata from video content",
282
+ "Facial recognition and object detection",
283
+ "Sentiment analysis and scene understanding",
284
+ "Applications in security, media, and marketing"
285
+ ],
286
+ "SORA 🏗️": [
287
+ "Scalable Open Research Architecture",
288
+ "Framework for distributed AI research and development",
289
+ "Modular and extensible design",
290
+ "Facilitates collaboration and reproducibility",
291
+ "Supports various AI algorithms and models"
292
+ ]
293
+ },
294
+ "🔬 Science Topics": {
295
+ "Physics 🔭": [
296
+ "Astrophysics: galaxies, cosmology, planets, high energy phenomena, instrumentation, solar/stellar",
297
+
298
+ "Condensed Matter: disordered systems, materials science, nano/mesoscale, quantum gases, soft matter, statistical mechanics, superconductivity",
299
+ "General Relativity and Quantum Cosmology",
300
+ "High Energy Physics: experiment, lattice, phenomenology, theory",
301
+ "Mathematical Physics",
302
+ "Nonlinear Sciences: adaptation, cellular automata, chaos, solvable systems, pattern formation",
303
+ "Nuclear: experiment, theory",
304
+ "Physics: accelerators, atmospherics, atomic/molecular, biophysics, chemical, computational, education, fluids, geophysics, optics, plasma, popular, space"
305
+ ],
306
+ "Mathematics ➗": [
307
+ "Algebra: geometry, topology, number theory, combinatorics, representation theory",
308
+ "Analysis: PDEs, functional, numerical, spectral theory, ODEs, complex variables",
309
+ "Geometry: algebraic, differential, metric, symplectic, topological",
310
+ "Probability and Statistics",
311
+ "Applied Math: information theory, optimization and control"
312
+ ],
313
+ "Computer Science 💻": [
314
+ "Artificial Intelligence and Machine Learning",
315
+
316
+ "Computation and Language, Complexity, Engineering, Finance, Science",
317
+ "Computer Vision, Graphics, Robotics",
318
+ "Cryptography, Security, Blockchain",
319
+ "Data Structures, Algorithms, Databases",
320
+ "Distributed and Parallel Computing",
321
+ "Formal Languages, Automata, Logic",
322
+ "Information Theory, Signal Processing",
323
+ "Networks, Internet Architecture, Social Networks",
324
+ "Programming Languages, Software Engineering"
325
+ ],
326
+ "Quantitative Biology 🧬": [
327
+ "Biomolecules, Cell Behavior, Genomics",
328
+ "Molecular Networks, Neurons and Cognition",
329
+ "Populations, Evolution, Ecology",
330
+ "Quantitative Methods, Subcellular Processes",
331
+ "Tissues, Organs, Organisms"
332
+ ],
333
+
334
+ "Quantitative Finance 📈": [
335
+ "Computational and Mathematical Finance",
336
+ "Econometrics and Statistical Finance",
337
+
338
+ "Economics, Portfolio Management, Trading",
339
+ "Pricing, Risk Management"
340
+ ],
341
+ "Electrical Engineering 🔌": [
342
+ "Audio, Speech, Image and Video Processing",
343
+ "Communications and Information Theory",
344
+ "Signal Processing, Controls, Robotics",
345
+ "Electronic Circuits, Embedded Systems"
346
+ ]
347
+ }
348
+ }
349
+
350
+
351
+ # This displays per video and per image.
352
+ @st.cache_resource
353
+ def display_glossary_entity(k):
354
+ search_urls = {
355
+ "🚀🌌ArXiv": lambda k: f"/?q={quote(k)}", # this url plus query!
356
+ "🃏Analyst": lambda k: f"/?q={quote(k)}-{quote(PromptPrefix)}", # this url plus query!
357
+ "📚PyCoder": lambda k: f"/?q={quote(k)}-{quote(PromptPrefix2)}", # this url plus query!
358
+ "🔬JSCoder": lambda k: f"/?q={quote(k)}-{quote(PromptPrefix3)}", # this url plus query!
359
+ "📖Wiki": lambda k: f"https://en.wikipedia.org/wiki/{quote(k)}",
360
+ "🔍Google": lambda k: f"https://www.google.com/search?q={quote(k)}",
361
+ "🔎Bing": lambda k: f"https://www.bing.com/search?q={quote(k)}",
362
+ "🎥YouTube": lambda k: f"https://www.youtube.com/results?search_query={quote(k)}",
363
+ "🐦Twitter": lambda k: f"https://twitter.com/search?q={quote(k)}",
364
+ }
365
+ links_md = ' '.join([f"[{emoji}]({url(k)})" for emoji, url in search_urls.items()])
366
+ #st.markdown(f"{k} {links_md}", unsafe_allow_html=True)
367
+ st.markdown(f"**{k}** <small>{links_md}</small>", unsafe_allow_html=True)
368
+
369
+ # Function to display the entire glossary in a grid format with links
370
+ @st.cache_resource
371
+ def display_glossary_grid(roleplaying_glossary):
372
+ search_urls = {
373
+ "🚀🌌ArXiv": lambda k: f"/?q={quote(k)}", # this url plus query!
374
+ "🃏Analyst": lambda k: f"/?q={quote(k)}-{quote(PromptPrefix)}", # this url plus query!
375
+ "📚PyCoder": lambda k: f"/?q={quote(k)}-{quote(PromptPrefix2)}", # this url plus query!
376
+ "🔬JSCoder": lambda k: f"/?q={quote(k)}-{quote(PromptPrefix3)}", # this url plus query!
377
+ "📖Wiki": lambda k: f"https://en.wikipedia.org/wiki/{quote(k)}",
378
+ "🔍Google": lambda k: f"https://www.google.com/search?q={quote(k)}",
379
+ "▶️YouTube": lambda k: f"https://www.youtube.com/results?search_query={quote(k)}",
380
+ "🔎Bing": lambda k: f"https://www.bing.com/search?q={quote(k)}",
381
+ "🎥YouTube": lambda k: f"https://www.youtube.com/results?search_query={quote(k)}",
382
+ "🐦Twitter": lambda k: f"https://twitter.com/search?q={quote(k)}",
383
+ }
384
+
385
+ for category, details in roleplaying_glossary.items():
386
+ st.write(f"### {category}")
387
+ cols = st.columns(len(details)) # Create dynamic columns based on the number of games
388
+ #cols = st.columns(num_columns_text) # Create dynamic columns based on the number of games
389
+ for idx, (game, terms) in enumerate(details.items()):
390
+ with cols[idx]:
391
+ st.markdown(f"#### {game}")
392
+ for term in terms:
393
+ links_md = ' '.join([f"[{emoji}]({url(term)})" for emoji, url in search_urls.items()])
394
+ st.markdown(f"**{term}** <small>{links_md}</small>", unsafe_allow_html=True)
395
+
396
+
397
+ @st.cache_resource
398
+ def get_table_download_link(file_path):
399
+
400
+ try:
401
+ #with open(file_path, 'r') as file:
402
+ #with open(file_path, 'r', encoding="unicode", errors="surrogateescape") as file:
403
+ with open(file_path, 'r', encoding='utf-8') as file:
404
+ data = file.read()
405
+
406
+ b64 = base64.b64encode(data.encode()).decode()
407
+ file_name = os.path.basename(file_path)
408
+ ext = os.path.splitext(file_name)[1] # get the file extension
409
+ if ext == '.txt':
410
+ mime_type = 'text/plain'
411
+ elif ext == '.py':
412
+ mime_type = 'text/plain'
413
+ elif ext == '.xlsx':
414
+ mime_type = 'text/plain'
415
+ elif ext == '.csv':
416
+ mime_type = 'text/plain'
417
+ elif ext == '.htm':
418
+ mime_type = 'text/html'
419
+ elif ext == '.md':
420
+ mime_type = 'text/markdown'
421
+ elif ext == '.wav':
422
+ mime_type = 'audio/wav'
423
+ else:
424
+ mime_type = 'application/octet-stream' # general binary data type
425
+ href = f'<a href="data:{mime_type};base64,{b64}" target="_blank" download="{file_name}">{file_name}</a>'
426
+ return href
427
+ except:
428
+ return ''
429
+
430
+
431
+ @st.cache_resource
432
+ def create_zip_of_files(files): # ----------------------------------
433
+ zip_name = "Arxiv-Paper-Search-QA-RAG-Streamlit-Gradio-AP.zip"
434
+ with zipfile.ZipFile(zip_name, 'w') as zipf:
435
+ for file in files:
436
+ zipf.write(file)
437
+ return zip_name
438
+
439
+ @st.cache_resource
440
+ def get_zip_download_link(zip_file):
441
+ with open(zip_file, 'rb') as f:
442
+ data = f.read()
443
+ b64 = base64.b64encode(data).decode()
444
+ href = f'<a href="data:application/zip;base64,{b64}" download="{zip_file}">Download All</a>'
445
+ return href # ----------------------------------
446
+
447
+ def get_file():
448
+ st.write(st.session_state['file'])
449
+
450
+ def SaveFileTextClicked():
451
+ fileText = st.session_state.file_content_area
452
+ fileName = st.session_state.file_name_input
453
+ with open(fileName, 'w', encoding='utf-8') as file:
454
+ file.write(fileText)
455
+ st.markdown('Saved ' + fileName + '.')
456
+
457
+ def SaveFileNameClicked():
458
+ newFileName = st.session_state.file_name_input
459
+ oldFileName = st.session_state.filename
460
+ if (newFileName!=oldFileName):
461
+ os.rename(oldFileName, newFileName)
462
+ st.markdown('Renamed file ' + oldFileName + ' to ' + newFileName + '.')
463
+ newFileText = st.session_state.file_content_area
464
+ oldFileText = st.session_state.filetext
465
+
466
+
467
+ # Function to compare file sizes and delete duplicates
468
+ def compare_and_delete_files(files):
469
+ if not files:
470
+ st.warning("No files to compare.")
471
+ return
472
+
473
+ # Dictionary to store file sizes and their paths
474
+ file_sizes = {}
475
+ for file in files:
476
+ size = os.path.getsize(file)
477
+ if size in file_sizes:
478
+ file_sizes[size].append(file)
479
+ else:
480
+ file_sizes[size] = [file]
481
+
482
+ # Remove all but the latest file for each size group
483
+ for size, paths in file_sizes.items():
484
+ if len(paths) > 1:
485
+ latest_file = max(paths, key=os.path.getmtime)
486
+ for file in paths:
487
+ if file != latest_file:
488
+ os.remove(file)
489
+ st.success(f"Deleted {file} as a duplicate.")
490
+ st.rerun()
491
+
492
+ # Function to get file size
493
+ def get_file_size(file_path):
494
+ return os.path.getsize(file_path)
495
+
496
+ def FileSidebar():
497
+
498
+ # File Sidebar for files 🌐View, 📂Open, ▶️Run, and 🗑Delete per file
499
+ all_files = glob.glob("*.md")
500
+ all_files = [file for file in all_files if len(os.path.splitext(file)[0]) >= 10] # exclude files with short names
501
+ all_files.sort(key=lambda x: (os.path.splitext(x)[1], x), reverse=True) # sort by filename length which puts similar prompts together - consider making date and time of file optional.
502
+
503
+
504
+
505
+ # Button to compare files and delete duplicates
506
+ #if st.button("Compare and Delete Duplicates"):
507
+ # compare_and_delete_files(all_files)
508
+
509
+
510
+
511
+ # ⬇️ Download
512
+ Files1, Files2 = st.sidebar.columns(2)
513
+ with Files1:
514
+ if st.button("🗑 Delete All"):
515
+ for file in all_files:
516
+ os.remove(file)
517
+ st.rerun()
518
+ with Files2:
519
+ if st.button("⬇️ Download"):
520
+ zip_file = create_zip_of_files(all_files)
521
+ st.sidebar.markdown(get_zip_download_link(zip_file), unsafe_allow_html=True)
522
+ file_contents=''
523
+ file_name=''
524
+ next_action=''
525
+
526
+
527
+ # Add files 🌐View, 📂Open, ▶️Run, and 🗑Delete per file
528
+ for file in all_files:
529
+ col1, col2, col3, col4, col5 = st.sidebar.columns([1,6,1,1,1]) # adjust the ratio as needed
530
+ with col1:
531
+ if st.button("🌐", key="md_"+file): # md emoji button
532
+ file_contents = load_file(file)
533
+ file_name=file
534
+ next_action='md'
535
+ st.session_state['next_action'] = next_action
536
+ with col2:
537
+ st.markdown(get_table_download_link(file), unsafe_allow_html=True)
538
+ with col3:
539
+ if st.button("📂", key="open_"+file): # open emoji button
540
+ file_contents = load_file(file)
541
+ file_name=file
542
+ next_action='open'
543
+ st.session_state['lastfilename'] = file
544
+ st.session_state['filename'] = file
545
+ st.session_state['filetext'] = file_contents
546
+ st.session_state['next_action'] = next_action
547
+ with col4:
548
+ if st.button("▶️", key="read_"+file): # search emoji button
549
+ file_contents = load_file(file)
550
+ file_name=file
551
+ next_action='search'
552
+ st.session_state['next_action'] = next_action
553
+ with col5:
554
+ if st.button("🗑", key="delete_"+file):
555
+ os.remove(file)
556
+ file_name=file
557
+ st.rerun()
558
+ next_action='delete'
559
+ st.session_state['next_action'] = next_action
560
+
561
+
562
+ # 🚩File duplicate detector - useful to prune and view all. Pruning works well by file size detection of two similar and flags the duplicate.
563
+ file_sizes = [get_file_size(file) for file in all_files]
564
+ previous_size = None
565
+ st.sidebar.title("File Operations")
566
+ for file, size in zip(all_files, file_sizes):
567
+ duplicate_flag = "🚩" if size == previous_size else ""
568
+ with st.sidebar.expander(f"File: {file} {duplicate_flag}"):
569
+ st.text(f"Size: {size} bytes")
570
+
571
+ if st.button("View", key=f"view_{file}"):
572
+ try:
573
+ with open(file, "r", encoding='utf-8') as f: # Ensure the file is read with UTF-8 encoding
574
+ file_content = f.read()
575
+ st.code(file_content, language="markdown")
576
+ except UnicodeDecodeError:
577
+ st.error("Failed to decode the file with UTF-8. It might contain non-UTF-8 encoded characters.")
578
+
579
+ if st.button("Delete", key=f"delete3_{file}"):
580
+ os.remove(file)
581
+ st.rerun()
582
+ previous_size = size # Update previous size for the next iteration
583
+
584
+ if len(file_contents) > 0:
585
+ if next_action=='open': # For "open", prep session state if it hasn't been yet
586
+ if 'lastfilename' not in st.session_state:
587
+ st.session_state['lastfilename'] = ''
588
+ if 'filename' not in st.session_state:
589
+ st.session_state['filename'] = ''
590
+ if 'filetext' not in st.session_state:
591
+ st.session_state['filetext'] = ''
592
+ open1, open2 = st.columns(spec=[.8,.2])
593
+
594
+ with open1:
595
+ # Use onchange functions to autoexecute file name and text save functions.
596
+ file_name_input = st.text_input(key='file_name_input', on_change=SaveFileNameClicked, label="File Name:",value=file_name )
597
+ file_content_area = st.text_area(key='file_content_area', on_change=SaveFileTextClicked, label="File Contents:", value=file_contents, height=300)
598
+
599
+ ShowButtons = False # Having buttons is redundant. They work but if on change event seals the deal so be it - faster save is less impedence - less context breaking
600
+ if ShowButtons:
601
+ bp1,bp2 = st.columns([.5,.5])
602
+ with bp1:
603
+ if st.button(label='💾 Save Name'):
604
+ SaveFileNameClicked()
605
+ with bp2:
606
+ if st.button(label='💾 Save File'):
607
+ SaveFileTextClicked()
608
+
609
+ new_file_content_area = st.session_state['file_content_area']
610
+ if new_file_content_area != file_contents:
611
+ st.markdown(new_file_content_area) #changed
612
+
613
+ if st.button("🔍 Run AI Meta Strategy", key="filecontentssearch"):
614
+ #search_glossary(file_content_area)
615
+ filesearch = PromptPrefix + file_content_area
616
+ st.markdown(filesearch)
617
+
618
+ if st.button(key=rerun, label='🔍AI Search' ):
619
+ search_glossary(filesearch)
620
+
621
+ if next_action=='md':
622
+ st.markdown(file_contents)
623
+ buttonlabel = '🔍Run'
624
+ if st.button(key='Runmd', label = buttonlabel):
625
+ user_prompt = file_contents
626
+ #try:
627
+ #search_glossary(file_contents)
628
+ #except:
629
+ #st.markdown('GPT is sleeping. Restart ETA 30 seconds.')
630
+
631
+ if next_action=='search':
632
+ file_content_area = st.text_area("File Contents:", file_contents, height=500)
633
+ user_prompt = file_contents
634
+ #try:
635
+ #search_glossary(file_contents)
636
+ filesearch = PromptPrefix2 + file_content_area
637
+ st.markdown(filesearch)
638
+ if st.button(key=rerun, label='🔍Re-Code' ):
639
+ #search_glossary(filesearch)
640
+ search_arxiv(filesearch)
641
+
642
+ #except:
643
+ #st.markdown('GPT is sleeping. Restart ETA 30 seconds.')
644
+ # ----------------------------------------------------- File Sidebar for Jump Gates ------------------------------------------
645
+
646
+ # Randomly select a title
647
+ titles = [
648
+ "🧠🎭 Semantic Symphonies 🎹🎸 & Episodic Encores 🥁🎻",
649
+ "🌌🎼 AI Rhythms 🎺🎷 of Memory Lane 🏰",
650
+ "🎭🎉 Cognitive Crescendos 🎹💃 & Neural Harmonies 🎸🎤",
651
+ "🧠🎺 Mnemonic Melodies 🎷 & Synaptic Grooves 🥁",
652
+ "🎼🎸 Straight Outta Cognition ⚙️",
653
+ "🥁🎻 Jazzy 🎷 Jambalaya 🍛 of AI Memories",
654
+ "🏰 Semantic 🧠 Soul 🙌 & Episodic 📜 Essence",
655
+ "🥁🎻 The Music Of AI's Mind 🧠🎭🎉"
656
+ ]
657
+
658
+ selected_title = random.choice(titles)
659
+ st.markdown(f"**{selected_title}**")
660
+
661
+ FileSidebar()
662
+
663
+
664
+ # ---- Art Card Sidebar with Random Selection of image:
665
+ def get_image_as_base64(url):
666
+ response = requests.get(url)
667
+ if response.status_code == 200:
668
+ # Convert the image to base64
669
+ return base64.b64encode(response.content).decode("utf-8")
670
+ else:
671
+ return None
672
+
673
+ def create_download_link(filename, base64_str):
674
+ href = f'<a href="data:file/png;base64,{base64_str}" download="{filename}">Download Image</a>'
675
+ return href
676
+
677
+ @st.cache_resource
678
+ def SideBarImageShuffle():
679
+ image_urls = [
680
+ "https://cdn-uploads.huggingface.co/production/uploads/620630b603825909dcbeba35/cfhJIasuxLkT5fnaAE6Gj.png",
681
+ "https://cdn-uploads.huggingface.co/production/uploads/620630b603825909dcbeba35/UMo4oWNrrd6RLLzsFxQAi.png",
682
+ "https://cdn-uploads.huggingface.co/production/uploads/620630b603825909dcbeba35/o_EH4cTs5Qxiu7xTZw9I3.png",
683
+ "https://cdn-uploads.huggingface.co/production/uploads/620630b603825909dcbeba35/cmCZ5RTdSx3usMm7MwwWK.png",
684
+ ]
685
+
686
+ selected_image_url = random.choice(image_urls)
687
+ selected_image_base64 = get_image_as_base64(selected_image_url)
688
+ if selected_image_base64 is not None:
689
+ with st.sidebar:
690
+ st.markdown(f"![image](data:image/png;base64,{selected_image_base64})")
691
+ else:
692
+ st.sidebar.write("Failed to load the image.")
693
+
694
+ ShowSideImages=False
695
+ if ShowSideImages:
696
+ SideBarImageShuffle()
697
+
698
+ # Ensure the directory for storing scores exists
699
+ score_dir = "scores"
700
+ os.makedirs(score_dir, exist_ok=True)
701
+
702
+ # Function to generate a unique key for each button, including an emoji
703
+ def generate_key(label, header, idx):
704
+ return f"{header}_{label}_{idx}_key"
705
+
706
+ # Function to increment and save score
707
+ def update_score(key, increment=1):
708
+ score_file = os.path.join(score_dir, f"{key}.json")
709
+ if os.path.exists(score_file):
710
+ with open(score_file, "r") as file:
711
+ score_data = json.load(file)
712
+ else:
713
+ score_data = {"clicks": 0, "score": 0}
714
+ score_data["clicks"] += 1
715
+ score_data["score"] += increment
716
+ with open(score_file, "w") as file:
717
+ json.dump(score_data, file)
718
+ return score_data["score"]
719
+
720
+ # Function to load score
721
+ def load_score(key):
722
+ score_file = os.path.join(score_dir, f"{key}.json")
723
+ if os.path.exists(score_file):
724
+ with open(score_file, "r") as file:
725
+ score_data = json.load(file)
726
+ return score_data["score"]
727
+ return 0
728
+
729
+
730
+ # 🔍Search Glossary
731
+ @st.cache_resource
732
+ def search_glossary(query):
733
+ #for category, terms in roleplaying_glossary.items():
734
+ # if query.lower() in (term.lower() for term in terms):
735
+ # st.markdown(f"#### {category}")
736
+ # st.write(f"- {query}")
737
+ all=""
738
+ st.markdown(f"- {query}")
739
+
740
+
741
+ # 🔍Run 1 - plain query
742
+ #response = chat_with_model(query)
743
+ #response1 = chat_with_model45(query)
744
+ #all = query + ' ' + response1
745
+ #st.write('🔍Run 1 is Complete.')
746
+
747
+ # ArXiv searcher ~-<>-~ Paper Summary - Ask LLM
748
+ client = Client("awacke1/Arxiv-Paper-Search-And-QA-RAG-Pattern")
749
+ response2 = client.predict(
750
+ query, # str in 'parameter_13' Textbox component
751
+ #"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
752
+ #"mistralai/Mistral-7B-Instruct-v0.2", # Literal['mistralai/Mixtral-8x7B-Instruct-v0.1', 'mistralai/Mistral-7B-Instruct-v0.2', 'google/gemma-7b-it', 'None'] in 'LLM Model' Dropdown component
753
+ "google/gemma-7b-it", # Literal['mistralai/Mixtral-8x7B-Instruct-v0.1', 'mistralai/Mistral-7B-Instruct-v0.2', 'google/gemma-7b-it', 'None'] in 'LLM Model' Dropdown component
754
+ True, # bool in 'Stream output' Checkbox component
755
+ api_name="/ask_llm"
756
+ )
757
+ st.write('🔍Run of Multi-Agent System Paper Summary Spec is Complete')
758
+ st.markdown(response2)
759
+
760
+ # ArXiv searcher ~-<>-~ Paper References - Update with RAG
761
+ client = Client("awacke1/Arxiv-Paper-Search-And-QA-RAG-Pattern")
762
+ response1 = client.predict(
763
+ query,
764
+ 10,
765
+ "Semantic Search - up to 10 Mar 2024", # Literal['Semantic Search - up to 10 Mar 2024', 'Arxiv Search - Latest - (EXPERIMENTAL)'] in 'Search Source' Dropdown component
766
+ "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
767
+ api_name="/update_with_rag_md"
768
+ )
769
+ st.write('🔍Run of Multi-Agent System Paper References is Complete')
770
+ #st.markdown(response1)
771
+
772
+ responseall = response2 + response1[0] + response1[1]
773
+ st.markdown(responseall)
774
+ return responseall
775
+
776
+ # GPT 35 turbo and GPT 45 - - - - - - - - - - - - -<><><><><>:
777
+ RunPostArxivLLM = False
778
+ if RunPostArxivLLM:
779
+ # 🔍Run PaperSummarizer
780
+ 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. '
781
+ response2 = chat_with_model(PaperSummarizer + str(response1))
782
+ st.write('🔍Run 3 - Paper Summarizer is Complete.')
783
+
784
+ # 🔍Run AppSpecifier
785
+ 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.'
786
+ response3 = chat_with_model(AppSpecifier + str(response2))
787
+ st.write('🔍Run 4 - AppSpecifier is Complete.')
788
+
789
+ # 🔍Run PythonAppCoder
790
+ 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. '
791
+ #result = str(result).replace('\n', ' ').replace('|', ' ')
792
+ # response4 = chat_with_model45(PythonAppCoder + str(response3))
793
+ response4 = chat_with_model(PythonAppCoder + str(response3))
794
+ st.write('🔍Run Python AppCoder is Complete.')
795
+
796
+ # experimental 45 - - - - - - - - - - - - -<><><><><>
797
+
798
+ responseAll = '# Query: ' + query + '# Summary: ' + str(response2) + '# Streamlit App Specifier: ' + str(response3) + '# Complete Streamlit App: ' + str(response4) + '# Scholarly Article Links References: ' + str(response1)
799
+ filename = generate_filename(responseAll, "md")
800
+ create_file(filename, query, responseAll, should_save)
801
+
802
+ return responseAll # 🔍Run--------------------------------------------------------
803
+ else:
804
+ return response1
805
+
806
+ # Function to display the glossary in a structured format
807
+ def display_glossary(glossary, area):
808
+ if area in glossary:
809
+ st.subheader(f"📘 Glossary for {area}")
810
+ for game, terms in glossary[area].items():
811
+ st.markdown(f"### {game}")
812
+ for idx, term in enumerate(terms, start=1):
813
+ st.write(f"{idx}. {term}")
814
+
815
+
816
+
817
+ #@st.cache_resource
818
+ def display_videos_and_links(num_columns):
819
+ video_files = [f for f in os.listdir('.') if f.endswith('.mp4')]
820
+ if not video_files:
821
+ st.write("No MP4 videos found in the current directory.")
822
+ return
823
+
824
+ video_files_sorted = sorted(video_files, key=lambda x: len(x.split('.')[0]))
825
+ cols = st.columns(num_columns) # Define num_columns columns outside the loop
826
+ col_index = 0 # Initialize column index
827
+
828
+ for video_file in video_files_sorted:
829
+ with cols[col_index % num_columns]: # Use modulo 2 to alternate between the first and second column
830
+ # Embedding video with autoplay and loop using HTML
831
+ #video_html = ("""<video width="100%" loop autoplay> <source src="{video_file}" type="video/mp4">Your browser does not support the video tag.</video>""")
832
+ #st.markdown(video_html, unsafe_allow_html=True)
833
+ k = video_file.split('.')[0] # Assumes keyword is the file name without extension
834
+ st.video(video_file, format='video/mp4', start_time=0)
835
+ display_glossary_entity(k)
836
+ col_index += 1 # Increment column index to place the next video in the next column
837
+
838
+ @st.cache_resource
839
+ def display_images_and_wikipedia_summaries(num_columns=4):
840
+ image_files = [f for f in os.listdir('.') if f.endswith('.png')]
841
+ if not image_files:
842
+ st.write("No PNG images found in the current directory.")
843
+ return
844
+
845
+ image_files_sorted = sorted(image_files, key=lambda x: len(x.split('.')[0]))
846
+
847
+ cols = st.columns(num_columns) # Use specified num_columns for layout
848
+ col_index = 0 # Initialize column index for cycling through columns
849
+
850
+ for image_file in image_files_sorted:
851
+ with cols[col_index % num_columns]: # Cycle through columns based on num_columns
852
+ image = Image.open(image_file)
853
+ st.image(image, caption=image_file, use_column_width=True)
854
+ k = image_file.split('.')[0] # Assumes keyword is the file name without extension
855
+ display_glossary_entity(k)
856
+ col_index += 1 # Increment to move to the next column in the next iteration
857
+
858
+
859
+ def get_all_query_params(key):
860
+ return st.query_params().get(key, [])
861
+
862
+ def clear_query_params():
863
+ st.query_params()
864
+
865
+ # Function to display content or image based on a query
866
+ #@st.cache_resource
867
+ def display_content_or_image(query):
868
+ for category, terms in transhuman_glossary.items():
869
+ for term in terms:
870
+ if query.lower() in term.lower():
871
+ st.subheader(f"Found in {category}:")
872
+ st.write(term)
873
+ return True # Return after finding and displaying the first match
874
+ image_dir = "images" # Example directory where images are stored
875
+ image_path = f"{image_dir}/{query}.png" # Construct image path with query
876
+ if os.path.exists(image_path):
877
+ st.image(image_path, caption=f"Image for {query}")
878
+ return True
879
+ st.warning("No matching content or image found.")
880
+ return False
881
+
882
+ game_emojis = {
883
+ "Dungeons and Dragons": "🐉",
884
+ "Call of Cthulhu": "🐙",
885
+ "GURPS": "🎲",
886
+ "Pathfinder": "🗺️",
887
+ "Kindred of the East": "🌅",
888
+ "Changeling": "🍃",
889
+ }
890
+
891
+ topic_emojis = {
892
+ "Core Rulebooks": "📚",
893
+ "Maps & Settings": "🗺️",
894
+ "Game Mechanics & Tools": "⚙️",
895
+ "Monsters & Adversaries": "👹",
896
+ "Campaigns & Adventures": "📜",
897
+ "Creatives & Assets": "🎨",
898
+ "Game Master Resources": "🛠️",
899
+ "Lore & Background": "📖",
900
+ "Character Development": "🧍",
901
+ "Homebrew Content": "🔧",
902
+ "General Topics": "🌍",
903
+ }
904
+
905
+ # Adjusted display_buttons_with_scores function
906
+ def display_buttons_with_scores(num_columns_text):
907
+
908
+
909
+ for category, games in roleplaying_glossary.items():
910
+ category_emoji = topic_emojis.get(category, "🔍") # Default to search icon if no match
911
+ st.markdown(f"## {category_emoji} {category}")
912
+ for game, terms in games.items():
913
+ game_emoji = game_emojis.get(game, "🎮") # Default to generic game controller if no match
914
+ for term in terms:
915
+ key = f"{category}_{game}_{term}".replace(' ', '_').lower()
916
+ score = load_score(key)
917
+ if st.button(f"{game_emoji} {category} {game} {term} {score}", key=key):
918
+ update_score(key)
919
+ # Create a dynamic query incorporating emojis and formatting for clarity
920
+ query_prefix = f"{category_emoji} {game_emoji} ** {category} - {game} - {term} - **"
921
+ # ----------------------------------------------------------------------------------------------
922
+ #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."
923
+ 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."
924
+ response = search_glossary(query_prefix + query_body)
925
+
926
+
927
+
928
+ def get_all_query_params(key):
929
+ return st.query_params().get(key, [])
930
+
931
+ def clear_query_params():
932
+ st.query_params()
933
+
934
+ # My Inference API Copy
935
+ API_URL = 'https://qe55p8afio98s0u3.us-east-1.aws.endpoints.huggingface.cloud' # Dr Llama
936
+ # Meta's Original - Chat HF Free Version:
937
+ #API_URL = "https://api-inference.huggingface.co/models/meta-llama/Llama-2-7b-chat-hf"
938
+ API_KEY = os.getenv('API_KEY')
939
+ MODEL1="meta-llama/Llama-2-7b-chat-hf"
940
+ MODEL1URL="https://huggingface.co/meta-llama/Llama-2-7b-chat-hf"
941
+ HF_KEY = os.getenv('HF_KEY')
942
+ headers = {
943
+ "Authorization": f"Bearer {HF_KEY}",
944
+ "Content-Type": "application/json"
945
+ }
946
+ key = os.getenv('OPENAI_API_KEY')
947
+ prompt = "...."
948
+ should_save = st.sidebar.checkbox("💾 Save", value=True, help="Save your session data.")
949
+
950
+
951
+
952
+
953
+ # 3. Stream Llama Response
954
+ @st.cache_resource
955
+ def StreamLLMChatResponse(prompt):
956
+ try:
957
+ endpoint_url = API_URL
958
+ hf_token = API_KEY
959
+ st.write('Running client ' + endpoint_url)
960
+ client = InferenceClient(endpoint_url, token=hf_token)
961
+ gen_kwargs = dict(
962
+ max_new_tokens=512,
963
+ top_k=30,
964
+ top_p=0.9,
965
+ temperature=0.2,
966
+ repetition_penalty=1.02,
967
+ stop_sequences=["\nUser:", "<|endoftext|>", "</s>"],
968
+ )
969
+ stream = client.text_generation(prompt, stream=True, details=True, **gen_kwargs)
970
+ report=[]
971
+ res_box = st.empty()
972
+ collected_chunks=[]
973
+ collected_messages=[]
974
+ allresults=''
975
+ for r in stream:
976
+ if r.token.special:
977
+ continue
978
+ if r.token.text in gen_kwargs["stop_sequences"]:
979
+ break
980
+ collected_chunks.append(r.token.text)
981
+ chunk_message = r.token.text
982
+ collected_messages.append(chunk_message)
983
+ try:
984
+ report.append(r.token.text)
985
+ if len(r.token.text) > 0:
986
+ result="".join(report).strip()
987
+ res_box.markdown(f'*{result}*')
988
+
989
+ except:
990
+ st.write('Stream llm issue')
991
+ SpeechSynthesis(result)
992
+ return result
993
+ except:
994
+ 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).')
995
+
996
+ # 4. Run query with payload
997
+ def query(payload):
998
+ response = requests.post(API_URL, headers=headers, json=payload)
999
+ st.markdown(response.json())
1000
+ return response.json()
1001
+
1002
+ def get_output(prompt):
1003
+ return query({"inputs": prompt})
1004
+
1005
+ # 5. Auto name generated output files from time and content
1006
+ def generate_filename(prompt, file_type):
1007
+ central = pytz.timezone('US/Central')
1008
+ safe_date_time = datetime.now(central).strftime("%m%d_%H%M")
1009
+ replaced_prompt = prompt.replace(" ", "_").replace("\n", "_")
1010
+ safe_prompt = "".join(x for x in replaced_prompt if x.isalnum() or x == "_")[:255] # 255 is linux max, 260 is windows max
1011
+ #safe_prompt = "".join(x for x in replaced_prompt if x.isalnum() or x == "_")[:45]
1012
+ return f"{safe_date_time}_{safe_prompt}.{file_type}"
1013
+
1014
+ # 6. Speech transcription via OpenAI service
1015
+ def transcribe_audio(openai_key, file_path, model):
1016
+ openai.api_key = openai_key
1017
+ OPENAI_API_URL = "https://api.openai.com/v1/audio/transcriptions"
1018
+ headers = {
1019
+ "Authorization": f"Bearer {openai_key}",
1020
+ }
1021
+ with open(file_path, 'rb') as f:
1022
+ data = {'file': f}
1023
+ st.write('STT transcript ' + OPENAI_API_URL)
1024
+ response = requests.post(OPENAI_API_URL, headers=headers, files=data, data={'model': model})
1025
+ if response.status_code == 200:
1026
+ st.write(response.json())
1027
+ chatResponse = chat_with_model(response.json().get('text'), '') # *************************************
1028
+ transcript = response.json().get('text')
1029
+ filename = generate_filename(transcript, 'txt')
1030
+ response = chatResponse
1031
+ user_prompt = transcript
1032
+ create_file(filename, user_prompt, response, should_save)
1033
+ return transcript
1034
+ else:
1035
+ st.write(response.json())
1036
+ st.error("Error in API call.")
1037
+ return None
1038
+
1039
+ # 7. Auto stop on silence audio control for recording WAV files
1040
+ def save_and_play_audio(audio_recorder):
1041
+ audio_bytes = audio_recorder(key='audio_recorder')
1042
+ if audio_bytes:
1043
+ filename = generate_filename("Recording", "wav")
1044
+ with open(filename, 'wb') as f:
1045
+ f.write(audio_bytes)
1046
+ st.audio(audio_bytes, format="audio/wav")
1047
+ return filename
1048
+ return None
1049
+
1050
+ # 8. File creator that interprets type and creates output file for text, markdown and code
1051
+ def create_file(filename, prompt, response, should_save=True):
1052
+ if not should_save:
1053
+ return
1054
+ base_filename, ext = os.path.splitext(filename)
1055
+ if ext in ['.txt', '.htm', '.md']:
1056
+
1057
+
1058
+
1059
+ # ****** line 344 is read utf-8 encoding was needed when running locally to save utf-8 encoding and not fail on write
1060
+
1061
+ #with open(f"{base_filename}.md", 'w') as file:
1062
+ #with open(f"{base_filename}.md", 'w', encoding="ascii", errors="surrogateescape") as file:
1063
+ with open(f"{base_filename}.md", 'w', encoding='utf-8') as file:
1064
+ #try:
1065
+ #content = (prompt.strip() + '\r\n' + decode(response, ))
1066
+ file.write(response)
1067
+ #except:
1068
+ # st.write('.')
1069
+ # ****** utf-8 encoding was needed when running locally to save utf-8 encoding and not fail on write
1070
+
1071
+
1072
+
1073
+
1074
+ #has_python_code = re.search(r"```python([\s\S]*?)```", prompt.strip() + '\r\n' + response)
1075
+ #has_python_code = bool(re.search(r"```python([\s\S]*?)```", prompt.strip() + '\r\n' + response))
1076
+ #if has_python_code:
1077
+ # python_code = re.findall(r"```python([\s\S]*?)```", response)[0].strip()
1078
+ # with open(f"{base_filename}-Code.py", 'w') as file:
1079
+ # file.write(python_code)
1080
+ # with open(f"{base_filename}.md", 'w') as file:
1081
+ # content = prompt.strip() + '\r\n' + response
1082
+ # file.write(content)
1083
+
1084
+ def truncate_document(document, length):
1085
+ return document[:length]
1086
+ def divide_document(document, max_length):
1087
+ return [document[i:i+max_length] for i in range(0, len(document), max_length)]
1088
+
1089
+ def CompressXML(xml_text):
1090
+ root = ET.fromstring(xml_text)
1091
+ for elem in list(root.iter()):
1092
+ if isinstance(elem.tag, str) and 'Comment' in elem.tag:
1093
+ elem.parent.remove(elem)
1094
+ return ET.tostring(root, encoding='unicode', method="xml")
1095
+
1096
+ # 10. Read in and provide UI for past files
1097
+ @st.cache_resource
1098
+ def read_file_content(file,max_length):
1099
+ if file.type == "application/json":
1100
+ content = json.load(file)
1101
+ return str(content)
1102
+ elif file.type == "text/html" or file.type == "text/htm":
1103
+ content = BeautifulSoup(file, "html.parser")
1104
+ return content.text
1105
+ elif file.type == "application/xml" or file.type == "text/xml":
1106
+ tree = ET.parse(file)
1107
+ root = tree.getroot()
1108
+ xml = CompressXML(ET.tostring(root, encoding='unicode'))
1109
+ return xml
1110
+ elif file.type == "text/markdown" or file.type == "text/md":
1111
+ md = mistune.create_markdown()
1112
+ content = md(file.read().decode())
1113
+ return content
1114
+ elif file.type == "text/plain":
1115
+ return file.getvalue().decode()
1116
+ else:
1117
+ return ""
1118
+
1119
+
1120
+ # 11. Chat with GPT - Caution on quota - now favoring fastest AI pipeline STT Whisper->LLM Llama->TTS
1121
+ @st.cache_resource
1122
+ def chat_with_model(prompt, document_section='', model_choice='gpt-3.5-turbo'): # gpt-4-0125-preview gpt-3.5-turbo
1123
+ model = model_choice
1124
+ 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.'}]
1125
+ conversation.append({'role': 'user', 'content': prompt})
1126
+ if len(document_section)>0:
1127
+ conversation.append({'role': 'assistant', 'content': document_section})
1128
+ start_time = time.time()
1129
+ report = []
1130
+ res_box = st.empty()
1131
+ collected_chunks = []
1132
+ collected_messages = []
1133
+
1134
+ for chunk in openai.ChatCompletion.create(model=model_choice, messages=conversation, temperature=0.5, stream=True):
1135
+ collected_chunks.append(chunk)
1136
+ chunk_message = chunk['choices'][0]['delta']
1137
+ collected_messages.append(chunk_message)
1138
+ content=chunk["choices"][0].get("delta",{}).get("content")
1139
+ try:
1140
+ report.append(content)
1141
+ if len(content) > 0:
1142
+ result = "".join(report).strip()
1143
+ res_box.markdown(f'*{result}*')
1144
+ except:
1145
+ st.write(' ')
1146
+ full_reply_content = ''.join([m.get('content', '') for m in collected_messages])
1147
+ st.write("Elapsed time:")
1148
+ st.write(time.time() - start_time)
1149
+ return full_reply_content
1150
+
1151
+ # 11.1 45
1152
+ @st.cache_resource
1153
+ def chat_with_model45(prompt, document_section='', model_choice='gpt-4-0125-preview'): # gpt-4-0125-preview gpt-3.5-turbo
1154
+ model = model_choice
1155
+ 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.'}]
1156
+ conversation.append({'role': 'user', 'content': prompt})
1157
+ if len(document_section)>0:
1158
+ conversation.append({'role': 'assistant', 'content': document_section})
1159
+ start_time = time.time()
1160
+ report = []
1161
+ res_box = st.empty()
1162
+ collected_chunks = []
1163
+ collected_messages = []
1164
+
1165
+ for chunk in openai.ChatCompletion.create(model=model_choice, messages=conversation, temperature=0.5, stream=True):
1166
+ collected_chunks.append(chunk)
1167
+ chunk_message = chunk['choices'][0]['delta']
1168
+ collected_messages.append(chunk_message)
1169
+ content=chunk["choices"][0].get("delta",{}).get("content")
1170
+ try:
1171
+ report.append(content)
1172
+ if len(content) > 0:
1173
+ result = "".join(report).strip()
1174
+ res_box.markdown(f'*{result}*')
1175
+ except:
1176
+ st.write(' ')
1177
+ full_reply_content = ''.join([m.get('content', '') for m in collected_messages])
1178
+ st.write("Elapsed time:")
1179
+ st.write(time.time() - start_time)
1180
+ return full_reply_content
1181
+
1182
+ @st.cache_resource
1183
+ def chat_with_file_contents(prompt, file_content, model_choice='gpt-3.5-turbo'): # gpt-4-0125-preview gpt-3.5-turbo
1184
+ #def chat_with_file_contents(prompt, file_content, model_choice='gpt-4-0125-preview'): # gpt-4-0125-preview gpt-3.5-turbo
1185
+ conversation = [{'role': 'system', 'content': 'You are a helpful assistant.'}]
1186
+ conversation.append({'role': 'user', 'content': prompt})
1187
+ if len(file_content)>0:
1188
+ conversation.append({'role': 'assistant', 'content': file_content})
1189
+ response = openai.ChatCompletion.create(model=model_choice, messages=conversation)
1190
+ return response['choices'][0]['message']['content']
1191
+
1192
+
1193
+ def extract_mime_type(file):
1194
+ if isinstance(file, str):
1195
+ pattern = r"type='(.*?)'"
1196
+ match = re.search(pattern, file)
1197
+ if match:
1198
+ return match.group(1)
1199
+ else:
1200
+ raise ValueError(f"Unable to extract MIME type from {file}")
1201
+ elif isinstance(file, streamlit.UploadedFile):
1202
+ return file.type
1203
+ else:
1204
+ raise TypeError("Input should be a string or a streamlit.UploadedFile object")
1205
+
1206
+ def extract_file_extension(file):
1207
+ # get the file name directly from the UploadedFile object
1208
+ file_name = file.name
1209
+ pattern = r".*?\.(.*?)$"
1210
+ match = re.search(pattern, file_name)
1211
+ if match:
1212
+ return match.group(1)
1213
+ else:
1214
+ raise ValueError(f"Unable to extract file extension from {file_name}")
1215
+
1216
+ # Normalize input as text from PDF and other formats
1217
+ @st.cache_resource
1218
+ def pdf2txt(docs):
1219
+ text = ""
1220
+ for file in docs:
1221
+ file_extension = extract_file_extension(file)
1222
+ st.write(f"File type extension: {file_extension}")
1223
+ if file_extension.lower() in ['py', 'txt', 'html', 'htm', 'xml', 'json']:
1224
+ text += file.getvalue().decode('utf-8')
1225
+ elif file_extension.lower() == 'pdf':
1226
+ from PyPDF2 import PdfReader
1227
+ pdf = PdfReader(BytesIO(file.getvalue()))
1228
+ for page in range(len(pdf.pages)):
1229
+ text += pdf.pages[page].extract_text() # new PyPDF2 syntax
1230
+ return text
1231
+
1232
+ def txt2chunks(text):
1233
+ text_splitter = CharacterTextSplitter(separator="\n", chunk_size=1000, chunk_overlap=200, length_function=len)
1234
+ return text_splitter.split_text(text)
1235
+
1236
+ # Vector Store using FAISS
1237
+ @st.cache_resource
1238
+ def vector_store(text_chunks):
1239
+ embeddings = OpenAIEmbeddings(openai_api_key=key)
1240
+ return FAISS.from_texts(texts=text_chunks, embedding=embeddings)
1241
+
1242
+ # Memory and Retrieval chains
1243
+ @st.cache_resource
1244
+ def get_chain(vectorstore):
1245
+ llm = ChatOpenAI()
1246
+ memory = ConversationBufferMemory(memory_key='chat_history', return_messages=True)
1247
+ return ConversationalRetrievalChain.from_llm(llm=llm, retriever=vectorstore.as_retriever(), memory=memory)
1248
+
1249
+ def process_user_input(user_question):
1250
+ response = st.session_state.conversation({'question': user_question})
1251
+ st.session_state.chat_history = response['chat_history']
1252
+ for i, message in enumerate(st.session_state.chat_history):
1253
+ template = user_template if i % 2 == 0 else bot_template
1254
+ st.write(template.replace("{{MSG}}", message.content), unsafe_allow_html=True)
1255
+ filename = generate_filename(user_question, 'txt')
1256
+ response = message.content
1257
+ user_prompt = user_question
1258
+ create_file(filename, user_prompt, response, should_save)
1259
+
1260
+ def divide_prompt(prompt, max_length):
1261
+ words = prompt.split()
1262
+ chunks = []
1263
+ current_chunk = []
1264
+ current_length = 0
1265
+ for word in words:
1266
+ if len(word) + current_length <= max_length:
1267
+ current_length += len(word) + 1
1268
+ current_chunk.append(word)
1269
+ else:
1270
+ chunks.append(' '.join(current_chunk))
1271
+ current_chunk = [word]
1272
+ current_length = len(word)
1273
+ chunks.append(' '.join(current_chunk))
1274
+ return chunks
1275
+
1276
+
1277
+
1278
+ API_URL_IE = f'https://tonpixzfvq3791u9.us-east-1.aws.endpoints.huggingface.cloud'
1279
+ API_URL_IE = "https://api-inference.huggingface.co/models/openai/whisper-small.en"
1280
+ MODEL2 = "openai/whisper-small.en"
1281
+ MODEL2_URL = "https://huggingface.co/openai/whisper-small.en"
1282
+ HF_KEY = st.secrets['HF_KEY']
1283
+ headers = {
1284
+ "Authorization": f"Bearer {HF_KEY}",
1285
+ "Content-Type": "audio/wav"
1286
+ }
1287
+
1288
+ def query(filename):
1289
+ with open(filename, "rb") as f:
1290
+ data = f.read()
1291
+ response = requests.post(API_URL_IE, headers=headers, data=data)
1292
+ return response.json()
1293
+
1294
+ def generate_filename(prompt, file_type):
1295
+ central = pytz.timezone('US/Central')
1296
+ safe_date_time = datetime.now(central).strftime("%m%d_%H%M")
1297
+ replaced_prompt = prompt.replace(" ", "_").replace("\n", "_")
1298
+ safe_prompt = "".join(x for x in replaced_prompt if x.isalnum() or x == "_")[:90]
1299
+ return f"{safe_date_time}_{safe_prompt}.{file_type}"
1300
+
1301
+ # 15. Audio recorder to Wav file
1302
+ def save_and_play_audio(audio_recorder):
1303
+ audio_bytes = audio_recorder()
1304
+ if audio_bytes:
1305
+ filename = generate_filename("Recording", "wav")
1306
+ with open(filename, 'wb') as f:
1307
+ f.write(audio_bytes)
1308
+ st.audio(audio_bytes, format="audio/wav")
1309
+ return filename
1310
+
1311
+ # 16. Speech transcription to file output
1312
+ def transcribe_audio(filename):
1313
+ output = query(filename)
1314
+ return output
1315
+
1316
+
1317
+ # Sample function to demonstrate a response, replace with your own logic
1318
+ def StreamMedChatResponse(topic):
1319
+ st.write(f"Showing resources or questions related to: {topic}")
1320
+
1321
+ # Function to encode file to base64
1322
+ def get_base64_encoded_file(file_path):
1323
+ with open(file_path, "rb") as file:
1324
+ return base64.b64encode(file.read()).decode()
1325
+
1326
+ # Function to create a download link
1327
+ def get_audio_download_link(file_path):
1328
+ base64_file = get_base64_encoded_file(file_path)
1329
+ return f'<a href="data:file/wav;base64,{base64_file}" download="{os.path.basename(file_path)}">⬇️ Download Audio</a>'
1330
+
1331
+
1332
+
1333
+
1334
+
1335
+
1336
+ # 🎵 Wav Audio files - Transcription History in Wav
1337
+ all_files = glob.glob("*.wav")
1338
+ all_files = [file for file in all_files if len(os.path.splitext(file)[0]) >= 10] # exclude files with short names
1339
+ all_files.sort(key=lambda x: (os.path.splitext(x)[1], x), reverse=True) # sort by file type and file name in descending order
1340
+
1341
+ filekey = 'delall'
1342
+ if st.sidebar.button("🗑 Delete All Audio", key=filekey):
1343
+ for file in all_files:
1344
+ os.remove(file)
1345
+ st.rerun()
1346
+
1347
+ for file in all_files:
1348
+ col1, col2 = st.sidebar.columns([6, 1]) # adjust the ratio as needed
1349
+ with col1:
1350
+ st.markdown(file)
1351
+ if st.button("🎵", key="play_" + file): # play emoji button
1352
+ audio_file = open(file, 'rb')
1353
+ audio_bytes = audio_file.read()
1354
+ st.audio(audio_bytes, format='audio/wav')
1355
+ #st.markdown(get_audio_download_link(file), unsafe_allow_html=True)
1356
+ #st.text_input(label="", value=file)
1357
+ with col2:
1358
+ if st.button("🗑", key="delete_" + file):
1359
+ os.remove(file)
1360
+ st.rerun()
1361
+
1362
+
1363
+
1364
+ GiveFeedback=False
1365
+ if GiveFeedback:
1366
+ with st.expander("Give your feedback 👍", expanded=False):
1367
+ feedback = st.radio("Step 8: Give your feedback", ("👍 Upvote", "👎 Downvote"))
1368
+ if feedback == "👍 Upvote":
1369
+ st.write("You upvoted 👍. Thank you for your feedback!")
1370
+ else:
1371
+ st.write("You downvoted 👎. Thank you for your feedback!")
1372
+ load_dotenv()
1373
+ st.write(css, unsafe_allow_html=True)
1374
+ st.header("Chat with documents :books:")
1375
+ user_question = st.text_input("Ask a question about your documents:")
1376
+ if user_question:
1377
+ process_user_input(user_question)
1378
+ with st.sidebar:
1379
+ st.subheader("Your documents")
1380
+ docs = st.file_uploader("import documents", accept_multiple_files=True)
1381
+ with st.spinner("Processing"):
1382
+ raw = pdf2txt(docs)
1383
+ if len(raw) > 0:
1384
+ length = str(len(raw))
1385
+ text_chunks = txt2chunks(raw)
1386
+ vectorstore = vector_store(text_chunks)
1387
+ st.session_state.conversation = get_chain(vectorstore)
1388
+ st.markdown('# AI Search Index of Length:' + length + ' Created.') # add timing
1389
+ filename = generate_filename(raw, 'txt')
1390
+ create_file(filename, raw, '', should_save)
1391
+
1392
+ # ⚙️q= Run ArXiv search from query parameters
1393
+ try:
1394
+ query_params = st.query_params
1395
+ query = (query_params.get('q') or query_params.get('query') or [''])
1396
+ if len(query) > 1:
1397
+ result = search_arxiv(query)
1398
+ #result2 = search_glossary(result)
1399
+ except:
1400
+ st.markdown(' ')
1401
+
1402
+ if 'action' in st.query_params:
1403
+ action = st.query_params()['action'][0] # Get the first (or only) 'action' parameter
1404
+ if action == 'show_message':
1405
+ st.success("Showing a message because 'action=show_message' was found in the URL.")
1406
+ elif action == 'clear':
1407
+ clear_query_params()
1408
+ #st.rerun()
1409
+
1410
+ if 'query' in st.query_params:
1411
+ query = st.query_params['query'][0] # Get the query parameter
1412
+ # Display content or image based on the query
1413
+ display_content_or_image(query)
1414
+
1415
+ def transcribe_canary(filename):
1416
+ from gradio_client import Client
1417
+
1418
+ client = Client("https://awacke1-speech-recognition-canary-nvidiat4.hf.space/")
1419
+ result = client.predict(
1420
+ filename, # filepath in 'parameter_5' Audio component
1421
+ "English", # Literal['English', 'Spanish', 'French', 'German'] in 'Input audio is spoken in:' Dropdown component
1422
+ "English", # Literal['English', 'Spanish', 'French', 'German'] in 'Transcribe in language:' Dropdown component
1423
+ True, # bool in 'Punctuation & Capitalization in transcript?' Checkbox component
1424
+ api_name="/transcribe"
1425
+ )
1426
+ st.write(result)
1427
+ return result
1428
+
1429
+ filename = save_and_play_audio(audio_recorder)
1430
+ if filename is not None:
1431
+ transcript=''
1432
+
1433
+ transcript=transcribe_canary(filename)
1434
+ result = search_arxiv(transcript)
1435
+ #result2 = search_glossary(result)
1436
+ #st.markdown(result)
1437
+ #st.markdown
1438
+
1439
+
1440
+ #transcription = transcribe_audio(filename)
1441
+ #try:
1442
+ # transcript = transcription['text']
1443
+ # st.write(transcript)
1444
+
1445
+ #except:
1446
+ # transcript=''
1447
+ # st.write(transcript)
1448
+
1449
+ #st.write('Reasoning with your inputs..')
1450
+ #response = chat_with_model(transcript)
1451
+ #st.write('Response:')
1452
+ #st.write(response)
1453
+ #filename = generate_filename(response, "txt")
1454
+ #create_file(filename, transcript, response, should_save)
1455
+
1456
+ # Whisper to Llama:
1457
+ response = StreamLLMChatResponse(transcript)
1458
+ filename_txt = generate_filename(transcript, "md")
1459
+ create_file(filename_txt, transcript, response, should_save)
1460
+ filename_wav = filename_txt.replace('.txt', '.wav')
1461
+ import shutil
1462
+ try:
1463
+ if os.path.exists(filename):
1464
+ shutil.copyfile(filename, filename_wav)
1465
+ except:
1466
+ st.write('.')
1467
+ if os.path.exists(filename):
1468
+ os.remove(filename)
1469
+
1470
+
1471
+
1472
+
1473
+ prompt = '''
1474
+ What is MoE?
1475
+ What are Multi Agent Systems?
1476
+ What is Self Rewarding AI?
1477
+ What is Semantic and Episodic memory?
1478
+ What is AutoGen?
1479
+ What is ChatDev?
1480
+ What is Omniverse?
1481
+ What is Lumiere?
1482
+ What is SORA?
1483
+ '''
1484
+
1485
+ import streamlit as st
1486
+
1487
+ personality_factors = """
1488
+ 1. 🌈 Openness (Being open to new things)
1489
+ - 🎭 Imagination (Enjoying fantasy and daydreaming)
1490
+ - 🎨 Artistic Interests (Appreciating beauty and art)
1491
+ - 🎸 Creativity (Coming up with new ideas)
1492
+ - 🌍 Curiosity (Wanting to explore and learn)
1493
+ - 🌿 Unconventional (Being different and unique)
1494
+ - 🧩 Complexity (Enjoying deep thoughts and feelings)
1495
+ - 🌌 Adventurousness (Seeking new experiences)
1496
+
1497
+ 2. 💼 Conscientiousness (Being organized and reliable)
1498
+ - 🎯 Competence (Feeling capable and effective)
1499
+ - 📊 Orderliness (Keeping things neat and tidy)
1500
+ - 📅 Dutifulness (Following rules and doing what's right)
1501
+ - 🏆 Achievement (Working hard to reach goals)
1502
+ - 🧘‍♀️ Self-Discipline (Staying focused and in control)
1503
+ - 🤔 Thoughtfulness (Thinking before acting)
1504
+ - 🕰️ Time Management (Using time wisely)
1505
+ - 🧽 Perfectionism (Wanting things to be just right)
1506
+
1507
+ 3. 🎉 Extraversion (Being outgoing and social)
1508
+ - 🤗 Friendliness (Being kind and welcoming)
1509
+ - 👥 Sociability (Enjoying being with others)
1510
+ - 🗣️ Assertiveness (Speaking up and taking charge)
1511
+ - ⚡ Energy (Being active and lively)
1512
+ - 🎢 Excitement (Seeking thrills and fun)
1513
+ - 😊 Cheerfulness (Feeling happy and positive)
1514
+ - 🎤 Talkativeness (Enjoying conversation)
1515
+ - 🌞 Enthusiasm (Showing excitement and interest)
1516
+
1517
+ 4. 🤝 Agreeableness (Being kind and cooperative)
1518
+ - 🤲 Trust (Believing in others' goodness)
1519
+ - 🌿 Honesty (Being truthful and sincere)
1520
+ - 🤝 Cooperation (Working well with others)
1521
+ - 🌸 Helpfulness (Being generous and caring)
1522
+ - 🕊️ Compliance (Following rules and respecting authority)
1523
+ - 🙏 Modesty (Being humble and down-to-earth)
1524
+ - 💕 Empathy (Understanding others' feelings)
1525
+ - 🫂 Compassion (Caring about others' well-being)
1526
+
1527
+ 5. 😔 Neuroticism (Feeling negative emotions easily)
1528
+ - 😰 Anxiety (Worrying and feeling nervous)
1529
+ - 😡 Anger (Getting upset and frustrated)
1530
+ - 😢 Sadness (Feeling down and unhappy)
1531
+ - 😳 Self-Consciousness (Feeling shy and uneasy)
1532
+ - 🎢 Impulsiveness (Acting without thinking)
1533
+ - 🍃 Vulnerability (Being easily hurt or upset)
1534
+ - 🌪️ Moodiness (Having ups and downs in feelings)
1535
+ - 🎭 Negativity (Focusing on the bad side of things)
1536
+ """
1537
+
1538
+
1539
+ session_state = {}
1540
+ if "search_queries" not in session_state:
1541
+ session_state["search_queries"] = []
1542
+ example_input = st.text_input("Search", value=session_state["search_queries"][-1] if session_state["search_queries"] else "")
1543
+ if example_input:
1544
+ session_state["search_queries"].append(example_input)
1545
+
1546
+ # Search AI
1547
+ query=example_input
1548
+ if query:
1549
+ result = search_arxiv(query)
1550
+ #search_glossary(query)
1551
+ #search_glossary(result)
1552
+ st.markdown(' ')
1553
+
1554
+ #st.write("Search history:")
1555
+ for example_input in session_state["search_queries"]:
1556
+ st.write(example_input)
1557
+
1558
+ if st.button("Run Prompt", help="Click to run."):
1559
+ try:
1560
+ response=StreamLLMChatResponse(example_input)
1561
+ create_file(filename, example_input, response, should_save)
1562
+ except:
1563
+ st.write('model is asleep. Starting now on A10 GPU. Please wait one minute then retry. KEDA triggered.')
1564
+
1565
+ openai.api_key = os.getenv('OPENAI_API_KEY')
1566
+ if openai.api_key == None: openai.api_key = st.secrets['OPENAI_API_KEY']
1567
+ menu = ["txt", "htm", "xlsx", "csv", "md", "py"]
1568
+ choice = st.sidebar.selectbox("Output File Type:", menu)
1569
+
1570
+ #model_choice = st.sidebar.radio("Select Model:", ('gpt-3.5-turbo', 'gpt-3.5-turbo-0301'))
1571
+ #user_prompt = st.text_area("Enter prompts, instructions & questions:", '', height=100)
1572
+ AddAFileForContext=False
1573
+ if AddAFileForContext:
1574
+
1575
+ collength, colupload = st.columns([2,3]) # adjust the ratio as needed
1576
+ with collength:
1577
+ #max_length = st.slider(key='maxlength', label="File section length for large files", min_value=1000, max_value=128000, value=12000, step=1000)
1578
+ max_length = 128000
1579
+ with colupload:
1580
+ uploaded_file = st.file_uploader("Add a file for context:", type=["pdf", "xml", "json", "xlsx", "csv", "html", "htm", "md", "txt"])
1581
+ document_sections = deque()
1582
+ document_responses = {}
1583
+ if uploaded_file is not None:
1584
+ file_content = read_file_content(uploaded_file, max_length)
1585
+ document_sections.extend(divide_document(file_content, max_length))
1586
+
1587
+
1588
+ if len(document_sections) > 0:
1589
+ if st.button("👁️ View Upload"):
1590
+ st.markdown("**Sections of the uploaded file:**")
1591
+ for i, section in enumerate(list(document_sections)):
1592
+ st.markdown(f"**Section {i+1}**\n{section}")
1593
+
1594
+ st.markdown("**Chat with the model:**")
1595
+ for i, section in enumerate(list(document_sections)):
1596
+ if i in document_responses:
1597
+ st.markdown(f"**Section {i+1}**\n{document_responses[i]}")
1598
+ else:
1599
+ if st.button(f"Chat about Section {i+1}"):
1600
+ st.write('Reasoning with your inputs...')
1601
+ st.write('Response:')
1602
+ st.write(response)
1603
+ document_responses[i] = response
1604
+ filename = generate_filename(f"{user_prompt}_section_{i+1}", choice)
1605
+ create_file(filename, user_prompt, response, should_save)
1606
+ st.sidebar.markdown(get_table_download_link(filename), unsafe_allow_html=True)
1607
+
1608
+
1609
+ num_columns_video=st.slider(key="num_columns_video", label="Choose Number of Video Columns", min_value=1, max_value=15, value=2)
1610
+ display_videos_and_links(num_columns_video) # Video Jump Grid
1611
+
1612
+ num_columns_images=st.slider(key="num_columns_images", label="Choose Number of Image Columns", min_value=1, max_value=15, value=2)
1613
+ display_images_and_wikipedia_summaries(num_columns_images) # Image Jump Grid
1614
+
1615
+ display_glossary_grid(roleplaying_glossary) # Word Glossary Jump Grid - Dynamically calculates columns based on details length to keep topic together
1616
+
1617
+ num_columns_text=st.slider(key="num_columns_text", label="Choose Number of Text Columns", min_value=1, max_value=15, value=4)
1618
+ display_buttons_with_scores(num_columns_text) # Feedback Jump Grid
1619
+
1620
+ st.markdown(personality_factors)
requirements.txt ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ gradio_client
2
+ huggingface_hub
3
+ audio-recorder-streamlit
4
+ beautifulsoup4
5
+ faiss-cpu
6
+ langchain
7
+ mistune
8
+ openai==0.28
9
+ PyPDF2
10
+ python-dotenv
11
+ pytz
12
+ streamlit
13
+ tiktoken
14
+ textract