awacke1 commited on
Commit
133ecd2
1 Parent(s): 92d2cd2

Delete backup.04102024.app.py

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