awacke1 commited on
Commit
92d2cd2
โ€ข
1 Parent(s): d28168d

Delete backup.04072024.app.py

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