awacke1 commited on
Commit
28418f3
1 Parent(s): 29d4a35

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +1749 -0
app.py ADDED
@@ -0,0 +1,1749 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ import cv2
3
+ import glob
4
+ import json
5
+ import math
6
+ import os
7
+ import pytz
8
+ import random
9
+ import re
10
+ import requests
11
+ import streamlit as st
12
+ import streamlit.components.v1 as components
13
+ import textract
14
+ import time
15
+ import zipfile
16
+
17
+ from audio_recorder_streamlit import audio_recorder
18
+ from bs4 import BeautifulSoup
19
+ from collections import deque
20
+ from datetime import datetime
21
+ from dotenv import load_dotenv
22
+ from gradio_client import Client
23
+ from huggingface_hub import InferenceClient
24
+ from io import BytesIO
25
+ from moviepy.editor import VideoFileClip
26
+ from PIL import Image
27
+ from PyPDF2 import PdfReader
28
+ from templates import bot_template, css, user_template
29
+ from urllib.parse import quote # Ensure this import is included
30
+ from xml.etree import ElementTree as ET
31
+
32
+ import openai
33
+ from openai import OpenAI
34
+
35
+
36
+
37
+ # 1. Configuration
38
+ Site_Name = 'Scholarly-Article-Document-Search-With-Memory'
39
+ title="🔬🧠ScienceBrain.AI"
40
+ helpURL='https://huggingface.co/awacke1'
41
+ bugURL='https://huggingface.co/spaces/awacke1'
42
+ icons='🔬'
43
+ st.set_page_config(
44
+ page_title=title,
45
+ page_icon=icons,
46
+ layout="wide",
47
+ #initial_sidebar_state="expanded",
48
+ initial_sidebar_state="auto",
49
+ menu_items={
50
+ 'Get Help': helpURL,
51
+ 'Report a bug': bugURL,
52
+ 'About': title
53
+ }
54
+ )
55
+
56
+
57
+
58
+ # HTML5 based Speech Synthesis (Text to Speech in Browser)
59
+ @st.cache_resource
60
+ def SpeechSynthesis(result):
61
+ documentHTML5='''
62
+ <!DOCTYPE html>
63
+ <html>
64
+ <head>
65
+ <title>Read It Aloud</title>
66
+ <script type="text/javascript">
67
+ function readAloud() {
68
+ const text = document.getElementById("textArea").value;
69
+ const speech = new SpeechSynthesisUtterance(text);
70
+ window.speechSynthesis.speak(speech);
71
+ }
72
+ </script>
73
+ </head>
74
+ <body>
75
+ <h1>🔊 Read It Aloud</h1>
76
+ <textarea id="textArea" rows="10" cols="80">
77
+ '''
78
+ documentHTML5 = documentHTML5 + result
79
+ documentHTML5 = documentHTML5 + '''
80
+ </textarea>
81
+ <br>
82
+ <button onclick="readAloud()">🔊 Read Aloud</button>
83
+ </body>
84
+ </html>
85
+ '''
86
+ components.html(documentHTML5, width=1280, height=300)
87
+
88
+ def parse_to_markdown(text):
89
+ return text
90
+
91
+ def load_file(file_name):
92
+ with open(file_name, "r", encoding='utf-8') as file:
93
+ #with open(file_name, "r") as file:
94
+ content = file.read()
95
+ return content
96
+
97
+ def extract_urls(text):
98
+ try:
99
+ date_pattern = re.compile(r'### (\d{2} \w{3} \d{4})')
100
+ abs_link_pattern = re.compile(r'\[(.*?)\]\((https://arxiv\.org/abs/\d+\.\d+)\)')
101
+ pdf_link_pattern = re.compile(r'\[⬇️\]\((https://arxiv\.org/pdf/\d+\.\d+)\)')
102
+ title_pattern = re.compile(r'### \d{2} \w{3} \d{4} \| \[(.*?)\]')
103
+ date_matches = date_pattern.findall(text)
104
+ abs_link_matches = abs_link_pattern.findall(text)
105
+ pdf_link_matches = pdf_link_pattern.findall(text)
106
+ title_matches = title_pattern.findall(text)
107
+
108
+ # markdown with the extracted fields
109
+ markdown_text = ""
110
+ for i in range(len(date_matches)):
111
+ date = date_matches[i]
112
+ title = title_matches[i]
113
+ abs_link = abs_link_matches[i][1]
114
+ pdf_link = pdf_link_matches[i]
115
+ markdown_text += f"**Date:** {date}\n\n"
116
+ markdown_text += f"**Title:** {title}\n\n"
117
+ markdown_text += f"**Abstract Link:** [{abs_link}]({abs_link})\n\n"
118
+ markdown_text += f"**PDF Link:** [{pdf_link}]({pdf_link})\n\n"
119
+ markdown_text += "---\n\n"
120
+ return markdown_text
121
+
122
+ except:
123
+ st.write('.')
124
+ return ''
125
+
126
+ def download_pdfs(urls):
127
+ local_files = []
128
+ for url in urls:
129
+ if url.endswith('.pdf'):
130
+ local_filename = url.split('/')[-1]
131
+ response = requests.get(url)
132
+ with open(local_filename, 'wb') as f:
133
+ f.write(response.content)
134
+ local_files.append(local_filename)
135
+ return local_files
136
+
137
+ def generate_html(local_files):
138
+ html = "<ul>"
139
+ for file in local_files:
140
+ link = f'<li><a href="{file}">{file}</a></li>'
141
+ html += link
142
+ html += "</ul>"
143
+ return html
144
+
145
+ #@st.cache_resource
146
+ def search_arxiv(query):
147
+ start_time = time.strftime("%Y-%m-%d %H:%M:%S")
148
+ client = Client("awacke1/Arxiv-Paper-Search-And-QA-RAG-Pattern")
149
+ response1 = client.predict(
150
+ query,
151
+ 20,
152
+ "Semantic Search - up to 10 Mar 2024",
153
+ "mistralai/Mixtral-8x7B-Instruct-v0.1",
154
+ api_name="/update_with_rag_md"
155
+ )
156
+ Question = '### 🔎 ' + query + '\r\n' # Format for markdown display with links
157
+ References = response1[0]
158
+ ReferenceLinks = extract_urls(References)
159
+
160
+ RunSecondQuery = True
161
+ if RunSecondQuery:
162
+ # Search 2 - Retrieve the Summary with Papers Context and Original Query
163
+ response2 = client.predict(
164
+ query,
165
+ "mistralai/Mixtral-8x7B-Instruct-v0.1",
166
+ True,
167
+ api_name="/ask_llm"
168
+ )
169
+ if len(response2) > 10:
170
+ Answer = response2
171
+ SpeechSynthesis(Answer)
172
+ # Restructure results to follow format of Question, Answer, References, ReferenceLinks
173
+ results = Question + '\r\n' + Answer + '\r\n' + References + '\r\n' + ReferenceLinks
174
+ st.markdown(results)
175
+
176
+ st.write('🔍Run of Multi-Agent System Paper Summary Spec is Complete')
177
+ end_time = time.strftime("%Y-%m-%d %H:%M:%S")
178
+ start_timestamp = time.mktime(time.strptime(start_time, "%Y-%m-%d %H:%M:%S"))
179
+ end_timestamp = time.mktime(time.strptime(end_time, "%Y-%m-%d %H:%M:%S"))
180
+ elapsed_seconds = end_timestamp - start_timestamp
181
+ st.write(f"Start time: {start_time}")
182
+ st.write(f"Finish time: {end_time}")
183
+ st.write(f"Elapsed time: {elapsed_seconds:.2f} seconds")
184
+ filename = generate_filename(query, "md")
185
+ create_file(filename, query, results, should_save)
186
+ return results
187
+
188
+ def download_pdfs_and_generate_html(urls):
189
+ pdf_links = []
190
+ for url in urls:
191
+ if url.endswith('.pdf'):
192
+ pdf_filename = os.path.basename(url)
193
+ download_pdf(url, pdf_filename)
194
+ pdf_links.append(pdf_filename)
195
+ local_links_html = '<ul>'
196
+ for link in pdf_links:
197
+ local_links_html += f'<li><a href="{link}">{link}</a></li>'
198
+ local_links_html += '</ul>'
199
+ return local_links_html
200
+
201
+ def download_pdf(url, filename):
202
+ response = requests.get(url)
203
+ with open(filename, 'wb') as file:
204
+ file.write(response.content)
205
+
206
+ # Prompts for App, for App Product, and App Product Code
207
+ 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 '
208
+ 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: '
209
+ 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:'
210
+
211
+ # MoE Roleplaying Technique for Context Experts
212
+ roleplaying_glossary = {
213
+ "🤖 AI Concepts": {
214
+ "MoE (Mixture of Experts) 🧠": [
215
+ "As a leading AI health researcher, provide an overview of MoE, MAS, memory, and mirroring in healthcare applications.",
216
+ "Explain how MoE and MAS can be leveraged to create AGI and AMI systems for healthcare, as an AI architect.",
217
+ "Discuss the key concepts, benefits, and challenges of self-rewarding AI in healthcare, as an expert.",
218
+ "Identify the top 3 pain points that MoE addresses in AI and healthcare, such as complexity and resource allocation.",
219
+ "Describe the top 3 joys of the MoE solution, including improved performance and adaptability in healthcare AI.",
220
+ "Highlight the top 3 superpowers MoE gives users, like tackling complex problems and personalizing interventions.",
221
+ "Identify the top 3 problems MoE solves in AI and healthcare, such as model complexity, lack of specialization, and inefficient resource allocation, and explain how it addresses each problem effectively.",
222
+ "Outline the 3 essential method steps required for implementing MoE in AI systems, highlighting the novelty and significance of each step in advancing healthcare applications.",
223
+ "Discuss the innovative aspects of the MoE method steps and how they differ from traditional approaches, contributing to advancements in AI and healthcare.",
224
+ "Propose 3 creative ways to structure MoE-based projects and collaborations to optimize performance, efficiency, and impact in healthcare AI applications."
225
+ ],
226
+ "Multi Agent Systems (MAS) 🤝": [
227
+ "As a renowned MAS researcher, describe the key characteristics of distributed, autonomous, and cooperative MAS.",
228
+ "Discuss how MAS is applied in robotics, simulations, and decentralized problem-solving, as an AI engineer.",
229
+ "Provide insights into future trends and breakthroughs in MAS research and applications, as a thought leader.",
230
+ "Identify the top 3 pain points MAS addresses in complex environments, such as coordination and adaptability.",
231
+ "Describe the top 3 joys of the MAS solution, including enhanced collaboration and emergent behaviors in AI.",
232
+ "Highlight the top 3 superpowers MAS gives users, like modeling complex systems and building resilient applications.",
233
+ "Identify the top 3 problems MAS solves in complex, distributed environments, such as lack of coordination, limited adaptability, and centralized control, and explain how it addresses each problem effectively.",
234
+ "Outline the 3 essential method steps required for designing and implementing MAS, highlighting the novelty and significance of each step in advancing AI applications.",
235
+ "Discuss the innovative aspects of the MAS method steps and how they differ from traditional approaches, contributing to advancements in distributed AI systems.",
236
+ "Propose 3 creative ways to structure MAS-based projects and collaborations to optimize performance, efficiency, and impact in various AI domains."
237
+ ],
238
+ "Self Rewarding AI 🎁": [
239
+ "As a leading expert, discuss the main research areas in developing AI with intrinsic motivation and goal-setting.",
240
+ "Explain how self-rewarding AI enables open-ended development and adaptability, as a curiosity-driven researcher.",
241
+ "Share your vision for the future of AI systems that autonomously set goals, learn, and adapt, as a pioneer.",
242
+ "Identify the top 3 pain points self-rewarding AI addresses, such as lack of motivation and limited adaptability.",
243
+ "Describe the top 3 joys of the self-rewarding AI solution, including autonomous learning and novel solutions.",
244
+ "Highlight the top 3 superpowers self-rewarding AI gives users, like creating continuously improving AI systems.",
245
+ "Identify the top 3 problems self-rewarding AI solves in current AI systems, such as lack of intrinsic motivation, limited adaptability, and reliance on external rewards, and explain how it addresses each problem effectively.",
246
+ "Outline the 3 essential method steps required for developing self-rewarding AI systems, highlighting the novelty and significance of each step in advancing autonomous AI.",
247
+ "Discuss the innovative aspects of the self-rewarding AI method steps and how they differ from traditional approaches, contributing to advancements in open-ended AI development.",
248
+ "Propose 3 creative ways to structure self-rewarding AI projects and collaborations to optimize performance, efficiency, and impact in creating adaptive and self-motivated AI systems."
249
+ ]
250
+ },
251
+ "🛠️ AI Tools & Platforms": {
252
+ "ChatDev 💬": [
253
+ "As a chatbot developer, ask about the features and capabilities ChatDev offers for building conversational AI.",
254
+ "Inquire about the pre-built assets, integrations, and multi-platform support in ChatDev, as a product manager.",
255
+ "Ask how ChatDev facilitates chatbot development, deployment, and analytics across channels, as a business owner.",
256
+ "Identify the top 3 challenges ChatDev helps overcome in chatbot development, such as customization and management.",
257
+ "Outline the top 3 essential method steps in building chatbots with ChatDev, emphasizing novelty and efficiency.",
258
+ "Propose 3 innovative ways to structure chatbot projects using ChatDev for optimizing speed, engagement, and deployment.",
259
+ "Identify the top 3 problems ChatDev solves in chatbot development, such as limited customization, lack of multi-platform support, and difficulty in managing conversational flows, and explain how it addresses each problem effectively.",
260
+ "Outline the 3 essential method steps required for building chatbots using ChatDev, highlighting the novelty and significance of each step in streamlining the development process.",
261
+ "Discuss the innovative aspects of the ChatDev method steps and how they differ from traditional approaches, contributing to advancements in conversational AI development.",
262
+ "Propose 3 creative ways to structure chatbot projects using ChatDev to optimize performance, efficiency, and impact in creating engaging and multi-platform conversational experiences."
263
+ ],
264
+ "Online Multiplayer Experiences 🌐": [
265
+ "As a game developer, explore the potential of online multiplayer experiences, including games, AR, and VR.",
266
+ "Discuss the future of image and video models in enhancing online multiplayer experiences, as a researcher.",
267
+ "Inquire about the challenges and opportunities in creating immersive and interactive online multiplayer environments.",
268
+ "Identify the top 3 problems online multiplayer experiences solve, such as limited social interaction, lack of realism, and difficulty in creating engaging content, and explain how they address each problem effectively.",
269
+ "Outline the 3 essential method steps required for developing cutting-edge online multiplayer experiences, highlighting the novelty and significance of each step in advancing gaming, AR, and VR.",
270
+ "Discuss the innovative aspects of online multiplayer experience development and how they differ from traditional approaches, contributing to advancements in immersive technologies.",
271
+ "Propose 3 creative ways to structure online multiplayer projects and collaborations to optimize performance, efficiency, and impact in creating captivating and socially engaging experiences.",
272
+ "Explore the potential of integrating AI and machine learning techniques in online multiplayer experiences to enhance player interactions, generate dynamic content, and personalize experiences.",
273
+ "Discuss the ethical considerations and challenges in developing online multiplayer experiences, such as ensuring fair play, protecting user privacy, and moderating user-generated content.",
274
+ "Identify the key trends and future directions in online multiplayer experiences, considering advancements in AI, AR, VR, and cloud computing technologies."
275
+ ]
276
+ },
277
+ "🔬 Science Topics": {
278
+ "Physics 🔭": [
279
+ "As a Physics student, ask about the main branches and research areas in Physics and their interconnections.",
280
+ "Discuss the current state and future directions of Astrophysics research, as a researcher in the field.",
281
+ "Explain how General Relativity, Quantum Cosmology, and Mathematical Physics interrelate, as a theorist.",
282
+ "Identify the top 3 fundamental questions in Physics that recent research aims to answer and their implications.",
283
+ "Outline the top 3 essential method steps in conducting cutting-edge Physics research, emphasizing novelty.",
284
+ "Propose 3 innovative ways to structure research collaborations in Physics for interdisciplinary breakthroughs.",
285
+ "Identify the top 3 problems physics research solves, such as understanding fundamental laws, resolving theory inconsistencies, and exploring the universe's origins, and explain how it addresses each problem effectively.",
286
+ "Outline the 3 essential method steps required for conducting cutting-edge physics research, highlighting the novelty and significance of each step in advancing our understanding of the universe.",
287
+ "Discuss the innovative aspects of the physics research method steps and how they differ from traditional approaches, contributing to advancements in the field.",
288
+ "Propose 3 creative ways to structure physics research projects and collaborations to optimize performance, efficiency, and impact in making groundbreaking discoveries."
289
+ ],
290
+ "Mathematics ➗": [
291
+ "As a Mathematics enthusiast, inquire about the main branches of Mathematics and their key research areas.",
292
+ "Ask about the main branches of pure Mathematics, like Algebra and Geometry, and their fundamental concepts.",
293
+ "Discuss how Probability, Statistics, and Applied Math relate to other Mathematical fields, as an applied mathematician.",
294
+ "Identify the top 3 unsolved problems in Mathematics that researchers are actively working on and their significance.",
295
+ "Describe the top 3 core method steps in advancing mathematical research, highlighting novelty and creativity.",
296
+ "Suggest 3 innovative ways to structure mathematical research and collaborations for discoveries and applications.",
297
+ "Identify the top 3 problems mathematics research solves, such as proving theorems, developing new tools, and finding real-world applications, and explain how it addresses each problem effectively.",
298
+ "Outline the 3 essential method steps required for advancing mathematical research, highlighting the novelty and significance of each step in expanding mathematical knowledge.",
299
+ "Discuss the innovative aspects of the mathematical research method steps and how they differ from traditional approaches, contributing to advancements in the field.",
300
+ "Propose 3 creative ways to structure mathematical research projects and collaborations to optimize performance, efficiency, and impact in making novel discoveries and finding interdisciplinary applications."
301
+ ],
302
+ "Computer Science 💻": [
303
+ "As a Computer Science student, ask about the main research areas shaping the future of computing.",
304
+ "Discuss the major research topics in AI, ML, NLP, Vision, Graphics, and Robotics, as an AI researcher.",
305
+ "Inquire about the interconnections between Algorithms, Data Structures, Databases, and Programming Languages.",
306
+ "Identify the top 3 critical challenges in Computer Science that current research aims to address and approaches.",
307
+ "Outline the top 3 essential method steps in conducting groundbreaking Computer Science research, emphasizing novelty.",
308
+ "Propose 3 creative ways to structure research projects in Computer Science for innovation and real-world applications.",
309
+ "Identify the top 3 problems computer science research solves, such as developing efficient algorithms, building secure systems, and advancing AI and machine learning, and explain how it addresses each problem effectively.",
310
+ "Outline the 3 essential method steps required for conducting groundbreaking computer science research, highlighting the novelty and significance of each step in pushing the boundaries of computing.",
311
+ "Discuss the innovative aspects of the computer science research method steps and how they differ from traditional approaches, contributing to advancements in the field.",
312
+ "Propose 3 creative ways to structure computer science research projects and collaborations to optimize performance, efficiency, and impact in driving innovation and solving real-world problems."
313
+ ]
314
+ }
315
+ }
316
+ # This displays per video and per image.
317
+ @st.cache_resource
318
+ def display_glossary_entity(k):
319
+ search_urls = {
320
+ "🚀🌌ArXiv": lambda k: f"/?q={quote(k)}", # this url plus query!
321
+ "🃏Analyst": lambda k: f"/?q={quote(k)}-{quote(PromptPrefix)}", # this url plus query!
322
+ "📚PyCoder": lambda k: f"/?q={quote(k)}-{quote(PromptPrefix2)}", # this url plus query!
323
+ "🔬JSCoder": lambda k: f"/?q={quote(k)}-{quote(PromptPrefix3)}", # this url plus query!
324
+ "📖": lambda k: f"https://en.wikipedia.org/wiki/{quote(k)}",
325
+ "🔍": lambda k: f"https://www.google.com/search?q={quote(k)}",
326
+ "🔎": lambda k: f"https://www.bing.com/search?q={quote(k)}",
327
+ "🎥": lambda k: f"https://www.youtube.com/results?search_query={quote(k)}",
328
+ "🐦": lambda k: f"https://twitter.com/search?q={quote(k)}",
329
+ }
330
+ links_md = ' '.join([f"[{emoji}]({url(k)})" for emoji, url in search_urls.items()])
331
+ #st.markdown(f"{k} {links_md}", unsafe_allow_html=True)
332
+ st.markdown(f"**{k}** <small>{links_md}</small>", unsafe_allow_html=True)
333
+
334
+ # Function to display the entire glossary in a grid format with links
335
+ @st.cache_resource
336
+ def display_glossary_grid(roleplaying_glossary):
337
+ search_urls = {
338
+ "🚀🌌ArXiv": lambda k: f"/?q={quote(k)}", # this url plus query!
339
+ "🃏Analyst": lambda k: f"/?q={quote(k)}-{quote(PromptPrefix)}", # this url plus query!
340
+ "📚PyCoder": lambda k: f"/?q={quote(k)}-{quote(PromptPrefix2)}", # this url plus query!
341
+ "🔬JSCoder": lambda k: f"/?q={quote(k)}-{quote(PromptPrefix3)}", # this url plus query!
342
+ "📖": lambda k: f"https://en.wikipedia.org/wiki/{quote(k)}",
343
+ "🔍": lambda k: f"https://www.google.com/search?q={quote(k)}",
344
+ "▶️": lambda k: f"https://www.youtube.com/results?search_query={quote(k)}",
345
+ "🔎": lambda k: f"https://www.bing.com/search?q={quote(k)}",
346
+ "🎥": lambda k: f"https://www.youtube.com/results?search_query={quote(k)}",
347
+ "🐦": lambda k: f"https://twitter.com/search?q={quote(k)}",
348
+ }
349
+
350
+ for category, details in roleplaying_glossary.items():
351
+ st.write(f"### {category}")
352
+ cols = st.columns(len(details)) # Create dynamic columns based on the number of games
353
+ #cols = st.columns(num_columns_text) # Create dynamic columns based on the number of games
354
+ for idx, (game, terms) in enumerate(details.items()):
355
+ with cols[idx]:
356
+ st.markdown(f"#### {game}")
357
+ for term in terms:
358
+ links_md = ' '.join([f"[{emoji}]({url(term)})" for emoji, url in search_urls.items()])
359
+ st.markdown(f"**{term}** <small>{links_md}</small>", unsafe_allow_html=True)
360
+
361
+
362
+ @st.cache_resource
363
+ def get_table_download_link(file_path):
364
+
365
+ try:
366
+ #with open(file_path, 'r') as file:
367
+ #with open(file_path, 'r', encoding="unicode", errors="surrogateescape") as file:
368
+ with open(file_path, 'r', encoding='utf-8') as file:
369
+ data = file.read()
370
+
371
+ b64 = base64.b64encode(data.encode()).decode()
372
+ file_name = os.path.basename(file_path)
373
+ ext = os.path.splitext(file_name)[1] # get the file extension
374
+ if ext == '.txt':
375
+ mime_type = 'text/plain'
376
+ elif ext == '.py':
377
+ mime_type = 'text/plain'
378
+ elif ext == '.xlsx':
379
+ mime_type = 'text/plain'
380
+ elif ext == '.csv':
381
+ mime_type = 'text/plain'
382
+ elif ext == '.htm':
383
+ mime_type = 'text/html'
384
+ elif ext == '.md':
385
+ mime_type = 'text/markdown'
386
+ elif ext == '.wav':
387
+ mime_type = 'audio/wav'
388
+ else:
389
+ mime_type = 'application/octet-stream' # general binary data type
390
+ href = f'<a href="data:{mime_type};base64,{b64}" target="_blank" download="{file_name}">{file_name}</a>'
391
+ return href
392
+ except:
393
+ return ''
394
+
395
+
396
+ @st.cache_resource
397
+ def create_zip_of_files(files): # ----------------------------------
398
+ zip_name = "Arxiv-Paper-Search-QA-RAG-Streamlit-Gradio-AP.zip"
399
+ with zipfile.ZipFile(zip_name, 'w') as zipf:
400
+ for file in files:
401
+ zipf.write(file)
402
+ return zip_name
403
+
404
+ @st.cache_resource
405
+ def get_zip_download_link(zip_file):
406
+ with open(zip_file, 'rb') as f:
407
+ data = f.read()
408
+ b64 = base64.b64encode(data).decode()
409
+ href = f'<a href="data:application/zip;base64,{b64}" download="{zip_file}">Download All</a>'
410
+ return href # ----------------------------------
411
+
412
+ def get_file():
413
+ st.write(st.session_state['file'])
414
+
415
+ def SaveFileTextClicked():
416
+ fileText = st.session_state.file_content_area
417
+ fileName = st.session_state.file_name_input
418
+ with open(fileName, 'w', encoding='utf-8') as file:
419
+ file.write(fileText)
420
+ st.markdown('Saved ' + fileName + '.')
421
+
422
+ def SaveFileNameClicked():
423
+ newFileName = st.session_state.file_name_input
424
+ oldFileName = st.session_state.filename
425
+ if (newFileName!=oldFileName):
426
+ os.rename(oldFileName, newFileName)
427
+ st.markdown('Renamed file ' + oldFileName + ' to ' + newFileName + '.')
428
+ newFileText = st.session_state.file_content_area
429
+ oldFileText = st.session_state.filetext
430
+
431
+
432
+ # Function to compare file sizes and delete duplicates
433
+ def compare_and_delete_files(files):
434
+ if not files:
435
+ st.warning("No files to compare.")
436
+ return
437
+
438
+ # Dictionary to store file sizes and their paths
439
+ file_sizes = {}
440
+ for file in files:
441
+ size = os.path.getsize(file)
442
+ if size in file_sizes:
443
+ file_sizes[size].append(file)
444
+ else:
445
+ file_sizes[size] = [file]
446
+
447
+ # Remove all but the latest file for each size group
448
+ for size, paths in file_sizes.items():
449
+ if len(paths) > 1:
450
+ latest_file = max(paths, key=os.path.getmtime)
451
+ for file in paths:
452
+ if file != latest_file:
453
+ os.remove(file)
454
+ st.success(f"Deleted {file} as a duplicate.")
455
+ st.rerun()
456
+
457
+ # Function to get file size
458
+ def get_file_size(file_path):
459
+ return os.path.getsize(file_path)
460
+
461
+ def FileSidebar():
462
+
463
+ # File Sidebar for files 🌐View, 📂Open, ▶️Run, and 🗑Delete per file
464
+ all_files = glob.glob("*.md")
465
+ all_files = [file for file in all_files if len(os.path.splitext(file)[0]) >= 10] # exclude files with short names
466
+ all_files.sort(key=lambda x: (os.path.splitext(x)[1], x), reverse=True) # sort by filename length which puts similar prompts together - consider making date and time of file optional.
467
+
468
+ # ⬇️ Download
469
+ Files1, Files2 = st.sidebar.columns(2)
470
+ with Files1:
471
+ if st.button("🗑 Delete All"):
472
+ for file in all_files:
473
+ os.remove(file)
474
+ st.rerun()
475
+ with Files2:
476
+ if st.button("⬇️ Download"):
477
+ zip_file = create_zip_of_files(all_files)
478
+ st.sidebar.markdown(get_zip_download_link(zip_file), unsafe_allow_html=True)
479
+ file_contents=''
480
+ file_name=''
481
+ next_action=''
482
+
483
+ # Add files 🌐View, 📂Open, ▶️Run, and 🗑Delete per file
484
+ for file in all_files:
485
+ col1, col2, col3, col4, col5 = st.sidebar.columns([1,6,1,1,1]) # adjust the ratio as needed
486
+ with col1:
487
+ if st.button("🌐", key="md_"+file): # md emoji button
488
+ file_contents = load_file(file)
489
+ file_name=file
490
+ next_action='md'
491
+ st.session_state['next_action'] = next_action
492
+ with col2:
493
+ st.markdown(get_table_download_link(file), unsafe_allow_html=True)
494
+ with col3:
495
+ if st.button("📂", key="open_"+file): # open emoji button
496
+ file_contents = load_file(file)
497
+ file_name=file
498
+ next_action='open'
499
+ st.session_state['lastfilename'] = file
500
+ st.session_state['filename'] = file
501
+ st.session_state['filetext'] = file_contents
502
+ st.session_state['next_action'] = next_action
503
+ with col4:
504
+ if st.button("▶️", key="read_"+file): # search emoji button
505
+ file_contents = load_file(file)
506
+ file_name=file
507
+ next_action='search'
508
+ st.session_state['next_action'] = next_action
509
+ with col5:
510
+ if st.button("🗑", key="delete_"+file):
511
+ os.remove(file)
512
+ file_name=file
513
+ st.rerun()
514
+ next_action='delete'
515
+ st.session_state['next_action'] = next_action
516
+
517
+
518
+ # 🚩File duplicate detector - useful to prune and view all. Pruning works well by file size detection of two similar and flags the duplicate.
519
+ file_sizes = [get_file_size(file) for file in all_files]
520
+ previous_size = None
521
+ st.sidebar.title("File Operations")
522
+ for file, size in zip(all_files, file_sizes):
523
+ duplicate_flag = "🚩" if size == previous_size else ""
524
+ with st.sidebar.expander(f"File: {file} {duplicate_flag}"):
525
+ st.text(f"Size: {size} bytes")
526
+
527
+ if st.button("View", key=f"view_{file}"):
528
+ try:
529
+ with open(file, "r", encoding='utf-8') as f: # Ensure the file is read with UTF-8 encoding
530
+ file_content = f.read()
531
+ st.code(file_content, language="markdown")
532
+ except UnicodeDecodeError:
533
+ st.error("Failed to decode the file with UTF-8. It might contain non-UTF-8 encoded characters.")
534
+
535
+ if st.button("Delete", key=f"delete3_{file}"):
536
+ os.remove(file)
537
+ st.rerun()
538
+ previous_size = size # Update previous size for the next iteration
539
+
540
+ if len(file_contents) > 0:
541
+ if next_action=='open': # For "open", prep session state if it hasn't been yet
542
+ if 'lastfilename' not in st.session_state:
543
+ st.session_state['lastfilename'] = ''
544
+ if 'filename' not in st.session_state:
545
+ st.session_state['filename'] = ''
546
+ if 'filetext' not in st.session_state:
547
+ st.session_state['filetext'] = ''
548
+ open1, open2 = st.columns(spec=[.8,.2])
549
+
550
+ with open1:
551
+ # Use onchange functions to autoexecute file name and text save functions.
552
+ file_name_input = st.text_input(key='file_name_input', on_change=SaveFileNameClicked, label="File Name:",value=file_name )
553
+ file_content_area = st.text_area(key='file_content_area', on_change=SaveFileTextClicked, label="File Contents:", value=file_contents, height=300)
554
+
555
+ ShowButtons = False # Having buttons is redundant. They work but if on change event seals the deal so be it - faster save is less impedence - less context breaking
556
+ if ShowButtons:
557
+ bp1,bp2 = st.columns([.5,.5])
558
+ with bp1:
559
+ if st.button(label='💾 Save Name'):
560
+ SaveFileNameClicked()
561
+ with bp2:
562
+ if st.button(label='💾 Save File'):
563
+ SaveFileTextClicked()
564
+
565
+ new_file_content_area = st.session_state['file_content_area']
566
+ if new_file_content_area != file_contents:
567
+ st.markdown(new_file_content_area) #changed
568
+
569
+ if st.button("🔍 Run AI Meta Strategy", key="filecontentssearch"):
570
+ #search_glossary(file_content_area)
571
+ filesearch = PromptPrefix + file_content_area
572
+ st.markdown(filesearch)
573
+
574
+ if st.button(key=rerun, label='🔍AI Search' ):
575
+ search_glossary(filesearch)
576
+
577
+ if next_action=='md':
578
+ st.markdown(file_contents)
579
+ buttonlabel = '🔍Run'
580
+ if st.button(key='Runmd', label = buttonlabel):
581
+ user_prompt = file_contents
582
+ #try:
583
+ #search_glossary(file_contents)
584
+ #except:
585
+ #st.markdown('GPT is sleeping. Restart ETA 30 seconds.')
586
+
587
+ if next_action=='search':
588
+ file_content_area = st.text_area("File Contents:", file_contents, height=500)
589
+ user_prompt = file_contents
590
+ #try:
591
+ #search_glossary(file_contents)
592
+ filesearch = PromptPrefix2 + file_content_area
593
+ st.markdown(filesearch)
594
+ if st.button(key=rerun, label='🔍Re-Code' ):
595
+ #search_glossary(filesearch)
596
+ search_arxiv(filesearch)
597
+
598
+ #except:
599
+ #st.markdown('GPT is sleeping. Restart ETA 30 seconds.')
600
+ # ----------------------------------------------------- File Sidebar for Jump Gates ------------------------------------------
601
+
602
+ # Randomly select a title
603
+ titles = [
604
+ "🧠🎭 Semantic Symphonies 🎹🎸 & Episodic Encores 🥁🎻",
605
+ "🌌🎼 AI Rhythms 🎺🎷 of Memory Lane 🏰",
606
+ "🎭🎉 Cognitive Crescendos 🎹💃 & Neural Harmonies 🎸🎤",
607
+ "🧠🎺 Mnemonic Melodies 🎷 & Synaptic Grooves 🥁",
608
+ "🎼🎸 Straight Outta Cognition ⚙️",
609
+ "🥁🎻 Jazzy 🎷 Jambalaya 🍛 of AI Memories",
610
+ "🏰 Semantic 🧠 Soul 🙌 & Episodic 📜 Essence",
611
+ "🥁🎻 The Music Of AI's Mind 🧠🎭🎉"
612
+ ]
613
+ selected_title = random.choice(titles)
614
+ st.markdown(f"**{selected_title}**")
615
+
616
+ FileSidebar()
617
+
618
+
619
+ # ---- Art Card Sidebar with Random Selection of image:
620
+ def get_image_as_base64(url):
621
+ response = requests.get(url)
622
+ if response.status_code == 200:
623
+ # Convert the image to base64
624
+ return base64.b64encode(response.content).decode("utf-8")
625
+ else:
626
+ return None
627
+
628
+ def create_download_link(filename, base64_str):
629
+ href = f'<a href="data:file/png;base64,{base64_str}" download="{filename}">Download Image</a>'
630
+ return href
631
+
632
+ @st.cache_resource
633
+ def SideBarImageShuffle():
634
+ image_urls = [
635
+ "https://cdn-uploads.huggingface.co/production/uploads/620630b603825909dcbeba35/cfhJIasuxLkT5fnaAE6Gj.png",
636
+ "https://cdn-uploads.huggingface.co/production/uploads/620630b603825909dcbeba35/UMo4oWNrrd6RLLzsFxQAi.png",
637
+ "https://cdn-uploads.huggingface.co/production/uploads/620630b603825909dcbeba35/o_EH4cTs5Qxiu7xTZw9I3.png",
638
+ "https://cdn-uploads.huggingface.co/production/uploads/620630b603825909dcbeba35/cmCZ5RTdSx3usMm7MwwWK.png",
639
+ ]
640
+
641
+ selected_image_url = random.choice(image_urls)
642
+ selected_image_base64 = get_image_as_base64(selected_image_url)
643
+ if selected_image_base64 is not None:
644
+ with st.sidebar:
645
+ st.markdown(f"![image](data:image/png;base64,{selected_image_base64})")
646
+ else:
647
+ st.sidebar.write("Failed to load the image.")
648
+
649
+ ShowSideImages=False
650
+ if ShowSideImages:
651
+ SideBarImageShuffle()
652
+
653
+
654
+
655
+ # Scoring for feedback: ----------------------------------------------------- emoji
656
+
657
+ # Ensure the directory for storing scores exists
658
+ score_dir = "scores"
659
+ os.makedirs(score_dir, exist_ok=True)
660
+
661
+ # Function to generate a unique key for each button, including an emoji
662
+ def generate_key(label, header, idx):
663
+ return f"{header}_{label}_{idx}_key"
664
+
665
+ # Function to increment and save score
666
+ def update_score(key, increment=1):
667
+ score_file = os.path.join(score_dir, f"{key}.json")
668
+ if os.path.exists(score_file):
669
+ with open(score_file, "r") as file:
670
+ score_data = json.load(file)
671
+ else:
672
+ score_data = {"clicks": 0, "score": 0}
673
+ score_data["clicks"] += increment
674
+ score_data["score"] += increment
675
+ with open(score_file, "w") as file:
676
+ json.dump(score_data, file)
677
+ return score_data["score"]
678
+
679
+ # Function to load score
680
+ def load_score(key):
681
+ score_file = os.path.join(score_dir, f"{key}.json")
682
+ if os.path.exists(score_file):
683
+ with open(score_file, "r") as file:
684
+ score_data = json.load(file)
685
+ return score_data["score"]
686
+ return 0
687
+
688
+
689
+ # 🔍Search Glossary
690
+ @st.cache_resource
691
+ def search_glossary(query):
692
+ all=""
693
+ st.markdown(f"- {query}")
694
+
695
+ # 🔍Run 1 - ArXiv RAG researcher expert ~-<>-~ Paper Summary & Ask LLM
696
+ client = Client("awacke1/Arxiv-Paper-Search-And-QA-RAG-Pattern")
697
+ response2 = client.predict(
698
+ query, # str in 'parameter_13' Textbox component
699
+ #"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
700
+ #"mistralai/Mistral-7B-Instruct-v0.2", # Literal['mistralai/Mixtral-8x7B-Instruct-v0.1', 'mistralai/Mistral-7B-Instruct-v0.2', 'google/gemma-7b-it', 'None'] in 'LLM Model' Dropdown component
701
+ "google/gemma-7b-it", # Literal['mistralai/Mixtral-8x7B-Instruct-v0.1', 'mistralai/Mistral-7B-Instruct-v0.2', 'google/gemma-7b-it', 'None'] in 'LLM Model' Dropdown component
702
+ True, # bool in 'Stream output' Checkbox component
703
+ api_name="/ask_llm"
704
+ )
705
+ st.write('🔍Run of Multi-Agent System Paper Summary Spec is Complete')
706
+ st.markdown(response2)
707
+
708
+ # ArXiv searcher ~-<>-~ Paper References - Update with RAG
709
+ client = Client("awacke1/Arxiv-Paper-Search-And-QA-RAG-Pattern")
710
+ response1 = client.predict(
711
+ query,
712
+ 10,
713
+ "Semantic Search - up to 10 Mar 2024", # Literal['Semantic Search - up to 10 Mar 2024', 'Arxiv Search - Latest - (EXPERIMENTAL)'] in 'Search Source' Dropdown component
714
+ "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
715
+ api_name="/update_with_rag_md"
716
+ )
717
+ st.write('🔍Run of Multi-Agent System Paper References is Complete')
718
+ responseall = response2 + response1[0] + response1[1]
719
+ st.markdown(responseall)
720
+ return responseall
721
+
722
+
723
+ # Function to display the glossary in a structured format
724
+ def display_glossary(glossary, area):
725
+ if area in glossary:
726
+ st.subheader(f"📘 Glossary for {area}")
727
+ for game, terms in glossary[area].items():
728
+ st.markdown(f"### {game}")
729
+ for idx, term in enumerate(terms, start=1):
730
+ st.write(f"{idx}. {term}")
731
+
732
+
733
+
734
+ #@st.cache_resource
735
+ def display_videos_and_links(num_columns):
736
+ video_files = [f for f in os.listdir('.') if f.endswith('.mp4')]
737
+ if not video_files:
738
+ st.write("No MP4 videos found in the current directory.")
739
+ return
740
+
741
+ video_files_sorted = sorted(video_files, key=lambda x: len(x.split('.')[0]))
742
+ cols = st.columns(num_columns) # Define num_columns columns outside the loop
743
+ col_index = 0 # Initialize column index
744
+
745
+ for video_file in video_files_sorted:
746
+ with cols[col_index % num_columns]: # Use modulo 2 to alternate between the first and second column
747
+ # Embedding video with autoplay and loop using HTML
748
+ #video_html = ("""<video width="100%" loop autoplay> <source src="{video_file}" type="video/mp4">Your browser does not support the video tag.</video>""")
749
+ #st.markdown(video_html, unsafe_allow_html=True)
750
+ k = video_file.split('.')[0] # Assumes keyword is the file name without extension
751
+ st.video(video_file, format='video/mp4', start_time=0)
752
+ display_glossary_entity(k)
753
+ col_index += 1 # Increment column index to place the next video in the next column
754
+
755
+ @st.cache_resource
756
+ def display_images_and_wikipedia_summaries(num_columns=4):
757
+ image_files = [f for f in os.listdir('.') if f.endswith('.png')]
758
+ if not image_files:
759
+ st.write("No PNG images found in the current directory.")
760
+ return
761
+
762
+ image_files_sorted = sorted(image_files, key=lambda x: len(x.split('.')[0]))
763
+
764
+ cols = st.columns(num_columns) # Use specified num_columns for layout
765
+ col_index = 0 # Initialize column index for cycling through columns
766
+
767
+ for image_file in image_files_sorted:
768
+ with cols[col_index % num_columns]: # Cycle through columns based on num_columns
769
+ image = Image.open(image_file)
770
+ st.image(image, caption=image_file, use_column_width=True)
771
+ k = image_file.split('.')[0] # Assumes keyword is the file name without extension
772
+ display_glossary_entity(k)
773
+ col_index += 1 # Increment to move to the next column in the next iteration
774
+
775
+
776
+ def get_all_query_params(key):
777
+ return st.query_params().get(key, [])
778
+
779
+ def clear_query_params():
780
+ st.query_params()
781
+
782
+ # Function to display content or image based on a query
783
+ #@st.cache_resource
784
+ def display_content_or_image(query):
785
+ for category, terms in transhuman_glossary.items():
786
+ for term in terms:
787
+ if query.lower() in term.lower():
788
+ st.subheader(f"Found in {category}:")
789
+ st.write(term)
790
+ return True # Return after finding and displaying the first match
791
+ image_dir = "images" # Example directory where images are stored
792
+ image_path = f"{image_dir}/{query}.png" # Construct image path with query
793
+ if os.path.exists(image_path):
794
+ st.image(image_path, caption=f"Image for {query}")
795
+ return True
796
+ st.warning("No matching content or image found.")
797
+ return False
798
+
799
+ game_emojis = {
800
+ "Dungeons and Dragons": "🐉",
801
+ "Call of Cthulhu": "🐙",
802
+ "GURPS": "🎲",
803
+ "Pathfinder": "🗺️",
804
+ "Kindred of the East": "🌅",
805
+ "Changeling": "🍃",
806
+ }
807
+
808
+ topic_emojis = {
809
+ "Core Rulebooks": "📚",
810
+ "Maps & Settings": "🗺️",
811
+ "Game Mechanics & Tools": "⚙️",
812
+ "Monsters & Adversaries": "👹",
813
+ "Campaigns & Adventures": "📜",
814
+ "Creatives & Assets": "🎨",
815
+ "Game Master Resources": "🛠️",
816
+ "Lore & Background": "📖",
817
+ "Character Development": "🧍",
818
+ "Homebrew Content": "🔧",
819
+ "General Topics": "🌍",
820
+ }
821
+
822
+ # Adjusted display_buttons_with_scores function
823
+ def display_buttons_with_scores(num_columns_text):
824
+ for category, games in roleplaying_glossary.items():
825
+ category_emoji = topic_emojis.get(category, "🔍") # Default to search icon if no match
826
+ st.markdown(f"## {category_emoji} {category}")
827
+ for game, terms in games.items():
828
+ game_emoji = game_emojis.get(game, "🎮") # Default to generic game controller if no match
829
+ for term in terms:
830
+ key = f"{category}_{game}_{term}".replace(' ', '_').lower()
831
+ score = load_score(key)
832
+ if st.button(f"{game_emoji} {category} {game} {term} {score}", key=key):
833
+ newscore = update_score(key.replace('?',''))
834
+ query_prefix = f"{category_emoji} {game_emoji} ** {category} - {game} - {term} - **"
835
+ st.markdown("Scored " + query_prefix + ' with score ' + str(newscore) + '.')
836
+
837
+
838
+ def get_all_query_params(key):
839
+ return st.query_params().get(key, [])
840
+
841
+ def clear_query_params():
842
+ st.query_params()
843
+
844
+ # My Inference API Copy
845
+ API_URL = 'https://qe55p8afio98s0u3.us-east-1.aws.endpoints.huggingface.cloud' # Dr Llama
846
+ # Meta's Original - Chat HF Free Version:
847
+ #API_URL = "https://api-inference.huggingface.co/models/meta-llama/Llama-2-7b-chat-hf"
848
+ API_KEY = os.getenv('API_KEY')
849
+ MODEL1="meta-llama/Llama-2-7b-chat-hf"
850
+ MODEL1URL="https://huggingface.co/meta-llama/Llama-2-7b-chat-hf"
851
+ HF_KEY = os.getenv('HF_KEY')
852
+ headers = {
853
+ "Authorization": f"Bearer {HF_KEY}",
854
+ "Content-Type": "application/json"
855
+ }
856
+ key = os.getenv('OPENAI_API_KEY')
857
+ prompt = "...."
858
+ should_save = st.sidebar.checkbox("💾 Save", value=True, help="Save your session data.")
859
+
860
+
861
+
862
+
863
+ # 3. Stream Llama Response
864
+ @st.cache_resource
865
+ def StreamLLMChatResponse(prompt):
866
+ try:
867
+ endpoint_url = API_URL
868
+ hf_token = API_KEY
869
+ st.write('Running client ' + endpoint_url)
870
+ client = InferenceClient(endpoint_url, token=hf_token)
871
+ gen_kwargs = dict(
872
+ max_new_tokens=512,
873
+ top_k=30,
874
+ top_p=0.9,
875
+ temperature=0.2,
876
+ repetition_penalty=1.02,
877
+ stop_sequences=["\nUser:", "<|endoftext|>", "</s>"],
878
+ )
879
+ stream = client.text_generation(prompt, stream=True, details=True, **gen_kwargs)
880
+ report=[]
881
+ res_box = st.empty()
882
+ collected_chunks=[]
883
+ collected_messages=[]
884
+ allresults=''
885
+ for r in stream:
886
+ if r.token.special:
887
+ continue
888
+ if r.token.text in gen_kwargs["stop_sequences"]:
889
+ break
890
+ collected_chunks.append(r.token.text)
891
+ chunk_message = r.token.text
892
+ collected_messages.append(chunk_message)
893
+ try:
894
+ report.append(r.token.text)
895
+ if len(r.token.text) > 0:
896
+ result="".join(report).strip()
897
+ res_box.markdown(f'*{result}*')
898
+
899
+ except:
900
+ st.write('Stream llm issue')
901
+ SpeechSynthesis(result)
902
+ return result
903
+ except:
904
+ 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).')
905
+
906
+ # 4. Run query with payload
907
+ def query(payload):
908
+ response = requests.post(API_URL, headers=headers, json=payload)
909
+ st.markdown(response.json())
910
+ return response.json()
911
+
912
+ def get_output(prompt):
913
+ return query({"inputs": prompt})
914
+
915
+ # 5. Auto name generated output files from time and content
916
+ def generate_filename(prompt, file_type):
917
+ central = pytz.timezone('US/Central')
918
+ safe_date_time = datetime.now(central).strftime("%m%d_%H%M")
919
+ replaced_prompt = prompt.replace(" ", "_").replace("\n", "_")
920
+ safe_prompt = "".join(x for x in replaced_prompt if x.isalnum() or x == "_")[:255] # 255 is linux max, 260 is windows max
921
+ #safe_prompt = "".join(x for x in replaced_prompt if x.isalnum() or x == "_")[:45]
922
+ return f"{safe_date_time}_{safe_prompt}.{file_type}"
923
+
924
+ # 6. Speech transcription via OpenAI service
925
+ def transcribe_audio(openai_key, file_path, model):
926
+ openai.api_key = openai_key
927
+ OPENAI_API_URL = "https://api.openai.com/v1/audio/transcriptions"
928
+ headers = {
929
+ "Authorization": f"Bearer {openai_key}",
930
+ }
931
+ with open(file_path, 'rb') as f:
932
+ data = {'file': f}
933
+ st.write('STT transcript ' + OPENAI_API_URL)
934
+ response = requests.post(OPENAI_API_URL, headers=headers, files=data, data={'model': model})
935
+ if response.status_code == 200:
936
+ st.write(response.json())
937
+ chatResponse = chat_with_model(response.json().get('text'), '') # *************************************
938
+ transcript = response.json().get('text')
939
+ filename = generate_filename(transcript, 'txt')
940
+ response = chatResponse
941
+ user_prompt = transcript
942
+ create_file(filename, user_prompt, response, should_save)
943
+ return transcript
944
+ else:
945
+ st.write(response.json())
946
+ st.error("Error in API call.")
947
+ return None
948
+
949
+ # 7. Auto stop on silence audio control for recording WAV files
950
+ def save_and_play_audio(audio_recorder):
951
+ audio_bytes = audio_recorder(key='audio_recorder')
952
+ if audio_bytes:
953
+ filename = generate_filename("Recording", "wav")
954
+ with open(filename, 'wb') as f:
955
+ f.write(audio_bytes)
956
+ st.audio(audio_bytes, format="audio/wav")
957
+ return filename
958
+ return None
959
+
960
+ # 8. File creator that interprets type and creates output file for text, markdown and code
961
+ def create_file(filename, prompt, response, should_save=True):
962
+ if not should_save:
963
+ return
964
+ base_filename, ext = os.path.splitext(filename)
965
+ if ext in ['.txt', '.htm', '.md']:
966
+
967
+
968
+
969
+ # ****** line 344 is read utf-8 encoding was needed when running locally to save utf-8 encoding and not fail on write
970
+
971
+ #with open(f"{base_filename}.md", 'w') as file:
972
+ #with open(f"{base_filename}.md", 'w', encoding="ascii", errors="surrogateescape") as file:
973
+ with open(f"{base_filename}.md", 'w', encoding='utf-8') as file:
974
+ #try:
975
+ #content = (prompt.strip() + '\r\n' + decode(response, ))
976
+ file.write(response)
977
+ #except:
978
+ # st.write('.')
979
+ # ****** utf-8 encoding was needed when running locally to save utf-8 encoding and not fail on write
980
+
981
+
982
+
983
+
984
+ #has_python_code = re.search(r"```python([\s\S]*?)```", prompt.strip() + '\r\n' + response)
985
+ #has_python_code = bool(re.search(r"```python([\s\S]*?)```", prompt.strip() + '\r\n' + response))
986
+ #if has_python_code:
987
+ # python_code = re.findall(r"```python([\s\S]*?)```", response)[0].strip()
988
+ # with open(f"{base_filename}-Code.py", 'w') as file:
989
+ # file.write(python_code)
990
+ # with open(f"{base_filename}.md", 'w') as file:
991
+ # content = prompt.strip() + '\r\n' + response
992
+ # file.write(content)
993
+
994
+ def truncate_document(document, length):
995
+ return document[:length]
996
+ def divide_document(document, max_length):
997
+ return [document[i:i+max_length] for i in range(0, len(document), max_length)]
998
+
999
+ def CompressXML(xml_text):
1000
+ root = ET.fromstring(xml_text)
1001
+ for elem in list(root.iter()):
1002
+ if isinstance(elem.tag, str) and 'Comment' in elem.tag:
1003
+ elem.parent.remove(elem)
1004
+ return ET.tostring(root, encoding='unicode', method="xml")
1005
+
1006
+ # 10. Read in and provide UI for past files
1007
+ @st.cache_resource
1008
+ def read_file_content(file,max_length):
1009
+ if file.type == "application/json":
1010
+ content = json.load(file)
1011
+ return str(content)
1012
+ elif file.type == "text/html" or file.type == "text/htm":
1013
+ content = BeautifulSoup(file, "html.parser")
1014
+ return content.text
1015
+ elif file.type == "application/xml" or file.type == "text/xml":
1016
+ tree = ET.parse(file)
1017
+ root = tree.getroot()
1018
+ xml = CompressXML(ET.tostring(root, encoding='unicode'))
1019
+ return xml
1020
+ elif file.type == "text/markdown" or file.type == "text/md":
1021
+ md = mistune.create_markdown()
1022
+ content = md(file.read().decode())
1023
+ return content
1024
+ elif file.type == "text/plain":
1025
+ return file.getvalue().decode()
1026
+ else:
1027
+ return ""
1028
+
1029
+
1030
+ # 11. Chat with GPT - Caution on quota - now favoring fastest AI pipeline STT Whisper->LLM Llama->TTS
1031
+ @st.cache_resource
1032
+ def chat_with_model(prompt, document_section='', model_choice='gpt-3.5-turbo'): # gpt-4-0125-preview gpt-3.5-turbo
1033
+ model = model_choice
1034
+ 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.'}]
1035
+ conversation.append({'role': 'user', 'content': prompt})
1036
+ if len(document_section)>0:
1037
+ conversation.append({'role': 'assistant', 'content': document_section})
1038
+ start_time = time.time()
1039
+ report = []
1040
+ res_box = st.empty()
1041
+ collected_chunks = []
1042
+ collected_messages = []
1043
+
1044
+ for chunk in openai.ChatCompletion.create(model=model_choice, messages=conversation, temperature=0.5, stream=True):
1045
+ collected_chunks.append(chunk)
1046
+ chunk_message = chunk['choices'][0]['delta']
1047
+ collected_messages.append(chunk_message)
1048
+ content=chunk["choices"][0].get("delta",{}).get("content")
1049
+ try:
1050
+ report.append(content)
1051
+ if len(content) > 0:
1052
+ result = "".join(report).strip()
1053
+ res_box.markdown(f'*{result}*')
1054
+ except:
1055
+ st.write(' ')
1056
+ full_reply_content = ''.join([m.get('content', '') for m in collected_messages])
1057
+ st.write("Elapsed time:")
1058
+ st.write(time.time() - start_time)
1059
+ return full_reply_content
1060
+
1061
+ # 11.1 45
1062
+ @st.cache_resource
1063
+ def chat_with_model45(prompt, document_section='', model_choice='gpt-4-0125-preview'): # gpt-4-0125-preview gpt-3.5-turbo
1064
+ model = model_choice
1065
+ 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.'}]
1066
+ conversation.append({'role': 'user', 'content': prompt})
1067
+ if len(document_section)>0:
1068
+ conversation.append({'role': 'assistant', 'content': document_section})
1069
+ start_time = time.time()
1070
+ report = []
1071
+ res_box = st.empty()
1072
+ collected_chunks = []
1073
+ collected_messages = []
1074
+
1075
+ for chunk in openai.ChatCompletion.create(model=model_choice, messages=conversation, temperature=0.5, stream=True):
1076
+ collected_chunks.append(chunk)
1077
+ chunk_message = chunk['choices'][0]['delta']
1078
+ collected_messages.append(chunk_message)
1079
+ content=chunk["choices"][0].get("delta",{}).get("content")
1080
+ try:
1081
+ report.append(content)
1082
+ if len(content) > 0:
1083
+ result = "".join(report).strip()
1084
+ res_box.markdown(f'*{result}*')
1085
+ except:
1086
+ st.write(' ')
1087
+ full_reply_content = ''.join([m.get('content', '') for m in collected_messages])
1088
+ st.write("Elapsed time:")
1089
+ st.write(time.time() - start_time)
1090
+ return full_reply_content
1091
+
1092
+ @st.cache_resource
1093
+ def chat_with_file_contents(prompt, file_content, model_choice='gpt-3.5-turbo'): # gpt-4-0125-preview gpt-3.5-turbo
1094
+ #def chat_with_file_contents(prompt, file_content, model_choice='gpt-4-0125-preview'): # gpt-4-0125-preview gpt-3.5-turbo
1095
+ conversation = [{'role': 'system', 'content': 'You are a helpful assistant.'}]
1096
+ conversation.append({'role': 'user', 'content': prompt})
1097
+ if len(file_content)>0:
1098
+ conversation.append({'role': 'assistant', 'content': file_content})
1099
+ response = openai.ChatCompletion.create(model=model_choice, messages=conversation)
1100
+ return response['choices'][0]['message']['content']
1101
+
1102
+
1103
+ def extract_mime_type(file):
1104
+ if isinstance(file, str):
1105
+ pattern = r"type='(.*?)'"
1106
+ match = re.search(pattern, file)
1107
+ if match:
1108
+ return match.group(1)
1109
+ else:
1110
+ raise ValueError(f"Unable to extract MIME type from {file}")
1111
+ elif isinstance(file, streamlit.UploadedFile):
1112
+ return file.type
1113
+ else:
1114
+ raise TypeError("Input should be a string or a streamlit.UploadedFile object")
1115
+
1116
+ def extract_file_extension(file):
1117
+ # get the file name directly from the UploadedFile object
1118
+ file_name = file.name
1119
+ pattern = r".*?\.(.*?)$"
1120
+ match = re.search(pattern, file_name)
1121
+ if match:
1122
+ return match.group(1)
1123
+ else:
1124
+ raise ValueError(f"Unable to extract file extension from {file_name}")
1125
+
1126
+ # Normalize input as text from PDF and other formats
1127
+ @st.cache_resource
1128
+ def pdf2txt(docs):
1129
+ text = ""
1130
+ for file in docs:
1131
+ file_extension = extract_file_extension(file)
1132
+ st.write(f"File type extension: {file_extension}")
1133
+ if file_extension.lower() in ['py', 'txt', 'html', 'htm', 'xml', 'json']:
1134
+ text += file.getvalue().decode('utf-8')
1135
+ elif file_extension.lower() == 'pdf':
1136
+ from PyPDF2 import PdfReader
1137
+ pdf = PdfReader(BytesIO(file.getvalue()))
1138
+ for page in range(len(pdf.pages)):
1139
+ text += pdf.pages[page].extract_text() # new PyPDF2 syntax
1140
+ return text
1141
+
1142
+ def txt2chunks(text):
1143
+ text_splitter = CharacterTextSplitter(separator="\n", chunk_size=1000, chunk_overlap=200, length_function=len)
1144
+ return text_splitter.split_text(text)
1145
+
1146
+ # Vector Store using FAISS
1147
+ @st.cache_resource
1148
+ def vector_store(text_chunks):
1149
+ embeddings = OpenAIEmbeddings(openai_api_key=key)
1150
+ return FAISS.from_texts(texts=text_chunks, embedding=embeddings)
1151
+
1152
+ # Memory and Retrieval chains
1153
+ @st.cache_resource
1154
+ def get_chain(vectorstore):
1155
+ llm = ChatOpenAI()
1156
+ memory = ConversationBufferMemory(memory_key='chat_history', return_messages=True)
1157
+ return ConversationalRetrievalChain.from_llm(llm=llm, retriever=vectorstore.as_retriever(), memory=memory)
1158
+
1159
+ def process_user_input(user_question):
1160
+ response = st.session_state.conversation({'question': user_question})
1161
+ st.session_state.chat_history = response['chat_history']
1162
+ for i, message in enumerate(st.session_state.chat_history):
1163
+ template = user_template if i % 2 == 0 else bot_template
1164
+ st.write(template.replace("{{MSG}}", message.content), unsafe_allow_html=True)
1165
+ filename = generate_filename(user_question, 'txt')
1166
+ response = message.content
1167
+ user_prompt = user_question
1168
+ create_file(filename, user_prompt, response, should_save)
1169
+
1170
+ def divide_prompt(prompt, max_length):
1171
+ words = prompt.split()
1172
+ chunks = []
1173
+ current_chunk = []
1174
+ current_length = 0
1175
+ for word in words:
1176
+ if len(word) + current_length <= max_length:
1177
+ current_length += len(word) + 1
1178
+ current_chunk.append(word)
1179
+ else:
1180
+ chunks.append(' '.join(current_chunk))
1181
+ current_chunk = [word]
1182
+ current_length = len(word)
1183
+ chunks.append(' '.join(current_chunk))
1184
+ return chunks
1185
+
1186
+
1187
+
1188
+ API_URL_IE = f'https://tonpixzfvq3791u9.us-east-1.aws.endpoints.huggingface.cloud'
1189
+ API_URL_IE = "https://api-inference.huggingface.co/models/openai/whisper-small.en"
1190
+ MODEL2 = "openai/whisper-small.en"
1191
+ MODEL2_URL = "https://huggingface.co/openai/whisper-small.en"
1192
+ HF_KEY = st.secrets['HF_KEY']
1193
+ headers = {
1194
+ "Authorization": f"Bearer {HF_KEY}",
1195
+ "Content-Type": "audio/wav"
1196
+ }
1197
+
1198
+ def query(filename):
1199
+ with open(filename, "rb") as f:
1200
+ data = f.read()
1201
+ response = requests.post(API_URL_IE, headers=headers, data=data)
1202
+ return response.json()
1203
+
1204
+ def generate_filename(prompt, file_type):
1205
+ central = pytz.timezone('US/Central')
1206
+ safe_date_time = datetime.now(central).strftime("%m%d_%H%M")
1207
+ replaced_prompt = prompt.replace(" ", "_").replace("\n", "_")
1208
+ safe_prompt = "".join(x for x in replaced_prompt if x.isalnum() or x == "_")[:90]
1209
+ return f"{safe_date_time}_{safe_prompt}.{file_type}"
1210
+
1211
+ # 15. Audio recorder to Wav file
1212
+ def save_and_play_audio(audio_recorder):
1213
+ audio_bytes = audio_recorder()
1214
+ if audio_bytes:
1215
+ filename = generate_filename("Recording", "wav")
1216
+ with open(filename, 'wb') as f:
1217
+ f.write(audio_bytes)
1218
+ st.audio(audio_bytes, format="audio/wav")
1219
+ return filename
1220
+
1221
+ # 16. Speech transcription to file output
1222
+ def transcribe_audio(filename):
1223
+ output = query(filename)
1224
+ return output
1225
+
1226
+
1227
+ # Sample function to demonstrate a response, replace with your own logic
1228
+ def StreamMedChatResponse(topic):
1229
+ st.write(f"Showing resources or questions related to: {topic}")
1230
+
1231
+ # Function to encode file to base64
1232
+ def get_base64_encoded_file(file_path):
1233
+ with open(file_path, "rb") as file:
1234
+ return base64.b64encode(file.read()).decode()
1235
+
1236
+ # Function to create a download link
1237
+ def get_audio_download_link(file_path):
1238
+ base64_file = get_base64_encoded_file(file_path)
1239
+ return f'<a href="data:file/wav;base64,{base64_file}" download="{os.path.basename(file_path)}">⬇️ Download Audio</a>'
1240
+
1241
+
1242
+
1243
+
1244
+
1245
+
1246
+ # 🎵 Wav Audio files - Transcription History in Wav
1247
+ all_files = glob.glob("*.wav")
1248
+ all_files = [file for file in all_files if len(os.path.splitext(file)[0]) >= 10] # exclude files with short names
1249
+ all_files.sort(key=lambda x: (os.path.splitext(x)[1], x), reverse=True) # sort by file type and file name in descending order
1250
+
1251
+ filekey = 'delall'
1252
+ if st.sidebar.button("🗑 Delete All Audio", key=filekey):
1253
+ for file in all_files:
1254
+ os.remove(file)
1255
+ st.rerun()
1256
+
1257
+ for file in all_files:
1258
+ col1, col2 = st.sidebar.columns([6, 1]) # adjust the ratio as needed
1259
+ with col1:
1260
+ st.markdown(file)
1261
+ if st.button("🎵", key="play_" + file): # play emoji button
1262
+ audio_file = open(file, 'rb')
1263
+ audio_bytes = audio_file.read()
1264
+ st.audio(audio_bytes, format='audio/wav')
1265
+ #st.markdown(get_audio_download_link(file), unsafe_allow_html=True)
1266
+ #st.text_input(label="", value=file)
1267
+ with col2:
1268
+ if st.button("🗑", key="delete_" + file):
1269
+ os.remove(file)
1270
+ st.rerun()
1271
+
1272
+
1273
+
1274
+ GiveFeedback=False
1275
+ if GiveFeedback:
1276
+ with st.expander("Give your feedback 👍", expanded=False):
1277
+ feedback = st.radio("Step 8: Give your feedback", ("👍 Upvote", "👎 Downvote"))
1278
+ if feedback == "👍 Upvote":
1279
+ st.write("You upvoted 👍. Thank you for your feedback!")
1280
+ else:
1281
+ st.write("You downvoted 👎. Thank you for your feedback!")
1282
+ load_dotenv()
1283
+ st.write(css, unsafe_allow_html=True)
1284
+ st.header("Chat with documents :books:")
1285
+ user_question = st.text_input("Ask a question about your documents:")
1286
+ if user_question:
1287
+ process_user_input(user_question)
1288
+ with st.sidebar:
1289
+ st.subheader("Your documents")
1290
+ docs = st.file_uploader("import documents", accept_multiple_files=True)
1291
+ with st.spinner("Processing"):
1292
+ raw = pdf2txt(docs)
1293
+ if len(raw) > 0:
1294
+ length = str(len(raw))
1295
+ text_chunks = txt2chunks(raw)
1296
+ vectorstore = vector_store(text_chunks)
1297
+ st.session_state.conversation = get_chain(vectorstore)
1298
+ st.markdown('# AI Search Index of Length:' + length + ' Created.') # add timing
1299
+ filename = generate_filename(raw, 'txt')
1300
+ create_file(filename, raw, '', should_save)
1301
+
1302
+ # ⚙️q= Run ArXiv search from query parameters
1303
+ try:
1304
+ query_params = st.query_params
1305
+ query = (query_params.get('q') or query_params.get('query') or [''])
1306
+ if len(query) > 1:
1307
+ result = search_arxiv(query)
1308
+ #result2 = search_glossary(result)
1309
+ except:
1310
+ st.markdown(' ')
1311
+
1312
+ if 'action' in st.query_params:
1313
+ action = st.query_params()['action'][0] # Get the first (or only) 'action' parameter
1314
+ if action == 'show_message':
1315
+ st.success("Showing a message because 'action=show_message' was found in the URL.")
1316
+ elif action == 'clear':
1317
+ clear_query_params()
1318
+ #st.rerun()
1319
+
1320
+ if 'query' in st.query_params:
1321
+ query = st.query_params['query'][0] # Get the query parameter
1322
+ # Display content or image based on the query
1323
+ display_content_or_image(query)
1324
+
1325
+ def transcribe_canary(filename):
1326
+ from gradio_client import Client
1327
+
1328
+ client = Client("https://awacke1-speech-recognition-canary-nvidiat4.hf.space/")
1329
+ result = client.predict(
1330
+ filename, # filepath in 'parameter_5' Audio component
1331
+ "English", # Literal['English', 'Spanish', 'French', 'German'] in 'Input audio is spoken in:' Dropdown component
1332
+ "English", # Literal['English', 'Spanish', 'French', 'German'] in 'Transcribe in language:' Dropdown component
1333
+ True, # bool in 'Punctuation & Capitalization in transcript?' Checkbox component
1334
+ api_name="/transcribe"
1335
+ )
1336
+ st.write(result)
1337
+ return result
1338
+
1339
+ # ChatBot client chat completions ------------------------- !!
1340
+ def process_text2(MODEL='gpt-4o-2024-05-13', text_input='What is 2+2 and what is an imaginary number'):
1341
+ if text_input:
1342
+ completion = client.chat.completions.create(
1343
+ model=MODEL,
1344
+ messages=st.session_state.messages
1345
+ )
1346
+ return_text = completion.choices[0].message.content
1347
+ st.write("Assistant: " + return_text)
1348
+ filename = generate_filename(text_input, "md")
1349
+ create_file(filename, text_input, return_text, should_save)
1350
+ return return_text
1351
+
1352
+ # Transcript to arxiv and client chat completion ------------------------- !!
1353
+ filename = save_and_play_audio(audio_recorder)
1354
+ if filename is not None:
1355
+ transcript=''
1356
+ transcript=transcribe_canary(filename)
1357
+
1358
+ # Search ArXiV and get the Summary and Reference Papers Listing
1359
+ result = search_arxiv(transcript)
1360
+
1361
+ # Start chatbot with transcript:
1362
+
1363
+ # ChatBot Entry
1364
+ MODEL = "gpt-4o-2024-05-13"
1365
+ openai.api_key = os.getenv('OPENAI_API_KEY')
1366
+ openai.organization = os.getenv('OPENAI_ORG_ID')
1367
+ client = OpenAI(api_key= os.getenv('OPENAI_API_KEY'), organization=os.getenv('OPENAI_ORG_ID'))
1368
+ st.session_state.messages.append({"role": "user", "content": transcript})
1369
+ with st.chat_message("user"):
1370
+ st.markdown(transcript)
1371
+ with st.chat_message("assistant"):
1372
+ completion = client.chat.completions.create(
1373
+ model=MODEL,
1374
+ messages = st.session_state.messages,
1375
+ stream=True
1376
+ )
1377
+ response = process_text2(text_input=prompt)
1378
+ st.session_state.messages.append({"role": "assistant", "content": response})
1379
+
1380
+ # Scholary ArXiV Search ------------------------- !!
1381
+ session_state = {}
1382
+ if "search_queries" not in session_state:
1383
+ session_state["search_queries"] = []
1384
+
1385
+ example_input = st.text_input("AI Search ArXiV Scholarly Articles", value=session_state["search_queries"][-1] if session_state["search_queries"] else "")
1386
+
1387
+ if example_input:
1388
+ session_state["search_queries"].append(example_input)
1389
+ query=example_input
1390
+ if query:
1391
+ result = search_arxiv(query)
1392
+ #search_glossary(query)
1393
+ #search_glossary(result)
1394
+ st.markdown(' ')
1395
+
1396
+ #st.write("Search history:")
1397
+ for example_input in session_state["search_queries"]:
1398
+ st.write(example_input)
1399
+
1400
+ if st.button("Run Prompt", help="Click to run."):
1401
+ try:
1402
+ response=StreamLLMChatResponse(example_input)
1403
+ create_file(filename, example_input, response, should_save)
1404
+ except:
1405
+ st.write('model is asleep. Starting now on A10 GPU. Please wait one minute then retry. KEDA triggered.')
1406
+
1407
+ openai.api_key = os.getenv('OPENAI_API_KEY')
1408
+ if openai.api_key == None: openai.api_key = st.secrets['OPENAI_API_KEY']
1409
+ menu = ["txt", "htm", "xlsx", "csv", "md", "py"]
1410
+ choice = st.sidebar.selectbox("Output File Type:", menu)
1411
+
1412
+ AddAFileForContext=False
1413
+ if AddAFileForContext:
1414
+
1415
+ collength, colupload = st.columns([2,3]) # adjust the ratio as needed
1416
+ with collength:
1417
+ #max_length = st.slider(key='maxlength', label="File section length for large files", min_value=1000, max_value=128000, value=12000, step=1000)
1418
+ max_length = 128000
1419
+ with colupload:
1420
+ uploaded_file = st.file_uploader("Add a file for context:", type=["pdf", "xml", "json", "xlsx", "csv", "html", "htm", "md", "txt"])
1421
+ document_sections = deque()
1422
+ document_responses = {}
1423
+ if uploaded_file is not None:
1424
+ file_content = read_file_content(uploaded_file, max_length)
1425
+ document_sections.extend(divide_document(file_content, max_length))
1426
+
1427
+
1428
+ if len(document_sections) > 0:
1429
+ if st.button("👁️ View Upload"):
1430
+ st.markdown("**Sections of the uploaded file:**")
1431
+ for i, section in enumerate(list(document_sections)):
1432
+ st.markdown(f"**Section {i+1}**\n{section}")
1433
+
1434
+ st.markdown("**Chat with the model:**")
1435
+ for i, section in enumerate(list(document_sections)):
1436
+ if i in document_responses:
1437
+ st.markdown(f"**Section {i+1}**\n{document_responses[i]}")
1438
+ else:
1439
+ if st.button(f"Chat about Section {i+1}"):
1440
+ st.write('Reasoning with your inputs...')
1441
+ st.write('Response:')
1442
+ st.write(response)
1443
+ document_responses[i] = response
1444
+ filename = generate_filename(f"{user_prompt}_section_{i+1}", choice)
1445
+ create_file(filename, user_prompt, response, should_save)
1446
+ st.sidebar.markdown(get_table_download_link(filename), unsafe_allow_html=True)
1447
+
1448
+
1449
+ # documentation
1450
+ # 1. Cookbook: https://cookbook.openai.com/examples/gpt4o/introduction_to_gpt4o
1451
+ # 2. Configure your Project and Orgs to limit/allow Models: https://platform.openai.com/settings/organization/general
1452
+ # 3. Watch your Billing! https://platform.openai.com/settings/organization/billing/overview
1453
+
1454
+
1455
+ # Set API key and organization ID from environment variables
1456
+
1457
+ openai.api_key = os.getenv('OPENAI_API_KEY')
1458
+ openai.organization = os.getenv('OPENAI_ORG_ID')
1459
+ client = OpenAI(api_key= os.getenv('OPENAI_API_KEY'), organization=os.getenv('OPENAI_ORG_ID'))
1460
+
1461
+ # Define the model to be used
1462
+ #MODEL = "gpt-4o"
1463
+ MODEL = "gpt-4o-2024-05-13"
1464
+
1465
+ def process_text(text_input):
1466
+ if text_input:
1467
+
1468
+ st.session_state.messages.append({"role": "user", "content": text_input})
1469
+
1470
+ with st.chat_message("user"):
1471
+ st.markdown(text_input)
1472
+
1473
+ with st.chat_message("assistant"):
1474
+ completion = client.chat.completions.create(
1475
+ model=MODEL,
1476
+ messages=[
1477
+ {"role": m["role"], "content": m["content"]}
1478
+ for m in st.session_state.messages
1479
+ ],
1480
+ stream=False
1481
+ )
1482
+ return_text = completion.choices[0].message.content
1483
+ st.write("Assistant: " + return_text)
1484
+ filename = generate_filename(text_input, "md")
1485
+ create_file(filename, text_input, return_text, should_save)
1486
+ st.session_state.messages.append({"role": "assistant", "content": return_text})
1487
+
1488
+ #st.write("Assistant: " + completion.choices[0].message.content)
1489
+
1490
+
1491
+
1492
+
1493
+
1494
+ def save_image(image_input, filename):
1495
+ # Save the uploaded image file
1496
+ with open(filename, "wb") as f:
1497
+ f.write(image_input.getvalue())
1498
+ return filename
1499
+
1500
+ def process_image(image_input):
1501
+ if image_input:
1502
+ st.markdown('Processing image: ' + image_input.name )
1503
+ if image_input:
1504
+ base64_image = base64.b64encode(image_input.read()).decode("utf-8")
1505
+ response = client.chat.completions.create(
1506
+ model=MODEL,
1507
+ messages=[
1508
+ {"role": "system", "content": "You are a helpful assistant that responds in Markdown."},
1509
+ {"role": "user", "content": [
1510
+ {"type": "text", "text": "Help me understand what is in this picture and list ten facts as markdown outline with appropriate emojis that describes what you see."},
1511
+ {"type": "image_url", "image_url": {
1512
+ "url": f"data:image/png;base64,{base64_image}"}
1513
+ }
1514
+ ]}
1515
+ ],
1516
+ temperature=0.0,
1517
+ )
1518
+ image_response = response.choices[0].message.content
1519
+ st.markdown(image_response)
1520
+
1521
+ # Save markdown on image AI output from gpt4o
1522
+ filename_md = generate_filename(image_input.name + '- ' + image_response, "md")
1523
+ # Save markdown on image AI output from gpt4o
1524
+ filename_png = filename_md.replace('.md', '.' + image_input.name.split('.')[-1])
1525
+
1526
+ create_file(filename_md, image_response, '', True) #create_file() # create_file() 3 required positional arguments: 'filename', 'prompt', and 'response'
1527
+
1528
+ with open(filename_md, "w", encoding="utf-8") as f:
1529
+ f.write(image_response)
1530
+
1531
+ # Save copy of image with original filename
1532
+ filename_img = image_input.name
1533
+ save_image(image_input, filename_img)
1534
+
1535
+ return image_response
1536
+
1537
+ def save_imageold(image_input, filename_txt):
1538
+ # Save the uploaded video file
1539
+ with open(filename_txt, "wb") as f:
1540
+ f.write(image_input.getbuffer())
1541
+ return image_input.name
1542
+
1543
+ def process_imageold(image_input):
1544
+ if image_input:
1545
+ base64_image = base64.b64encode(image_input.read()).decode("utf-8")
1546
+ response = client.chat.completions.create(
1547
+ model=MODEL,
1548
+ messages=[
1549
+ {"role": "system", "content": "You are a helpful assistant that responds in Markdown."},
1550
+ {"role": "user", "content": [
1551
+ {"type": "text", "text": "Help me understand what is in this picture and list ten facts as markdown outline with appropriate emojis that describes what you see."},
1552
+ {"type": "image_url", "image_url": {
1553
+ "url": f"data:image/png;base64,{base64_image}"}
1554
+ }
1555
+ ]}
1556
+ ],
1557
+ temperature=0.0,
1558
+ )
1559
+ image_response = response.choices[0].message.content
1560
+ st.markdown(image_response)
1561
+
1562
+ filename_txt = generate_filename(image_response, "md") # Save markdown on image AI output from gpt4o
1563
+ create_file(filename_txt, image_response, '', True) #create_file() # create_file() 3 required positional arguments: 'filename', 'prompt', and 'response'
1564
+
1565
+ filename_txt = generate_filename(image_response, "png")
1566
+ save_image(image_input, filename_txt) # Save copy of image with new filename
1567
+ #st.rerun() # rerun to show new image and new markdown files
1568
+
1569
+ return image_response
1570
+
1571
+
1572
+ def process_audio(audio_input):
1573
+ if audio_input:
1574
+ transcription = client.audio.transcriptions.create(
1575
+ model="whisper-1",
1576
+ file=audio_input,
1577
+ )
1578
+ response = client.chat.completions.create(
1579
+ model=MODEL,
1580
+ messages=[
1581
+ {"role": "system", "content":"""You are generating a transcript summary. Create a summary of the provided transcription. Respond in Markdown."""},
1582
+ {"role": "user", "content": [{"type": "text", "text": f"The audio transcription is: {transcription.text}"}],}
1583
+ ],
1584
+ temperature=0,
1585
+ )
1586
+ st.markdown(response.choices[0].message.content)
1587
+
1588
+ def process_audio_for_video(video_input):
1589
+ if video_input:
1590
+ transcription = client.audio.transcriptions.create(
1591
+ model="whisper-1",
1592
+ file=video_input,
1593
+ )
1594
+ response = client.chat.completions.create(
1595
+ model=MODEL,
1596
+ messages=[
1597
+ {"role": "system", "content":"""You are generating a transcript summary. Create a summary of the provided transcription. Respond in Markdown."""},
1598
+ {"role": "user", "content": [{"type": "text", "text": f"The audio transcription is: {transcription}"}],}
1599
+ ],
1600
+ temperature=0,
1601
+ )
1602
+ st.markdown(response.choices[0].message.content)
1603
+ return response.choices[0].message.content
1604
+
1605
+ def save_video(video_file):
1606
+ # Save the uploaded video file
1607
+ with open(video_file.name, "wb") as f:
1608
+ f.write(video_file.getbuffer())
1609
+ return video_file.name
1610
+
1611
+ def process_video(video_path, seconds_per_frame=2):
1612
+ base64Frames = []
1613
+ base_video_path, _ = os.path.splitext(video_path)
1614
+ video = cv2.VideoCapture(video_path)
1615
+ total_frames = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
1616
+ fps = video.get(cv2.CAP_PROP_FPS)
1617
+ frames_to_skip = int(fps * seconds_per_frame)
1618
+ curr_frame = 0
1619
+
1620
+ # Loop through the video and extract frames at specified sampling rate
1621
+ while curr_frame < total_frames - 1:
1622
+ video.set(cv2.CAP_PROP_POS_FRAMES, curr_frame)
1623
+ success, frame = video.read()
1624
+ if not success:
1625
+ break
1626
+ _, buffer = cv2.imencode(".jpg", frame)
1627
+ base64Frames.append(base64.b64encode(buffer).decode("utf-8"))
1628
+ curr_frame += frames_to_skip
1629
+
1630
+ video.release()
1631
+
1632
+ # Extract audio from video
1633
+ audio_path = f"{base_video_path}.mp3"
1634
+ clip = VideoFileClip(video_path)
1635
+ clip.audio.write_audiofile(audio_path, bitrate="32k")
1636
+ clip.audio.close()
1637
+ clip.close()
1638
+
1639
+ print(f"Extracted {len(base64Frames)} frames")
1640
+ print(f"Extracted audio to {audio_path}")
1641
+
1642
+ return base64Frames, audio_path
1643
+
1644
+ def process_audio_and_video(video_input):
1645
+ if video_input is not None:
1646
+ # Save the uploaded video file
1647
+ video_path = save_video(video_input )
1648
+
1649
+ # Process the saved video
1650
+ base64Frames, audio_path = process_video(video_path, seconds_per_frame=1)
1651
+
1652
+ # Get the transcript for the video model call
1653
+ transcript = process_audio_for_video(video_input)
1654
+
1655
+ # Generate a summary with visual and audio
1656
+ response = client.chat.completions.create(
1657
+ model=MODEL,
1658
+ messages=[
1659
+ {"role": "system", "content": """You are generating a video summary. Create a summary of the provided video and its transcript. Respond in Markdown"""},
1660
+ {"role": "user", "content": [
1661
+ "These are the frames from the video.",
1662
+ *map(lambda x: {"type": "image_url",
1663
+ "image_url": {"url": f'data:image/jpg;base64,{x}', "detail": "low"}}, base64Frames),
1664
+ {"type": "text", "text": f"The audio transcription is: {transcript}"}
1665
+ ]},
1666
+ ],
1667
+ temperature=0,
1668
+ )
1669
+ results = response.choices[0].message.content
1670
+ st.markdown(results)
1671
+
1672
+ filename = generate_filename(transcript, "md")
1673
+ create_file(filename, transcript, results, should_save)
1674
+
1675
+
1676
+
1677
+ def main():
1678
+ #st.markdown("### OpenAI GPT-4o Model")
1679
+ st.markdown("##### GPT-4o Omni Model: Text, Audio, Image, & Video")
1680
+ option = st.selectbox("Select an option", ("Text", "Image", "Audio", "Video"))
1681
+ if option == "Text":
1682
+ text_input = st.text_input("Enter your text:")
1683
+ if (text_input > ''):
1684
+ textResponse = process_text(text_input)
1685
+ elif option == "Image":
1686
+ image_input = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
1687
+ image_response = process_image(image_input)
1688
+
1689
+
1690
+
1691
+ elif option == "Audio":
1692
+ audio_input = st.file_uploader("Upload an audio file", type=["mp3", "wav"])
1693
+ process_audio(audio_input)
1694
+ elif option == "Video":
1695
+ video_input = st.file_uploader("Upload a video file", type=["mp4"])
1696
+ process_audio_and_video(video_input)
1697
+
1698
+ # Image and Video Galleries
1699
+ num_columns_images=st.slider(key="num_columns_images", label="Choose Number of Image Columns", min_value=1, max_value=15, value=5)
1700
+ display_images_and_wikipedia_summaries(num_columns_images) # Image Jump Grid
1701
+
1702
+ num_columns_video=st.slider(key="num_columns_video", label="Choose Number of Video Columns", min_value=1, max_value=15, value=5)
1703
+ display_videos_and_links(num_columns_video) # Video Jump Grid
1704
+
1705
+
1706
+ # Optional UI's
1707
+ showExtendedTextInterface=False
1708
+ if showExtendedTextInterface:
1709
+ display_glossary_grid(roleplaying_glossary) # Word Glossary Jump Grid - Dynamically calculates columns based on details length to keep topic together
1710
+ num_columns_text=st.slider(key="num_columns_text", label="Choose Number of Text Columns", min_value=1, max_value=15, value=4)
1711
+ display_buttons_with_scores(num_columns_text) # Feedback Jump Grid
1712
+ st.markdown(personality_factors)
1713
+
1714
+
1715
+
1716
+
1717
+ # st.title("GPT-4o ChatBot")
1718
+
1719
+ client = OpenAI(api_key= os.getenv('OPENAI_API_KEY'), organization=os.getenv('OPENAI_ORG_ID'))
1720
+ MODEL = "gpt-4o-2024-05-13"
1721
+ if "openai_model" not in st.session_state:
1722
+ st.session_state["openai_model"] = MODEL
1723
+ if "messages" not in st.session_state:
1724
+ st.session_state.messages = []
1725
+ if st.button("Clear Session"):
1726
+ st.session_state.messages = []
1727
+
1728
+ current_messages=[]
1729
+ for message in st.session_state.messages:
1730
+ with st.chat_message(message["role"]):
1731
+ current_messages.append(message)
1732
+ st.markdown(message["content"])
1733
+
1734
+ # ChatBot Entry
1735
+ if prompt := st.chat_input("GPT-4o Multimodal ChatBot - What can I help you with?"):
1736
+ st.session_state.messages.append({"role": "user", "content": prompt})
1737
+ with st.chat_message("user"):
1738
+ st.markdown(prompt)
1739
+ with st.chat_message("assistant"):
1740
+ completion = client.chat.completions.create(
1741
+ model=MODEL,
1742
+ messages = st.session_state.messages,
1743
+ stream=True
1744
+ )
1745
+ response = process_text2(text_input=prompt)
1746
+ st.session_state.messages.append({"role": "assistant", "content": response})
1747
+
1748
+ if __name__ == "__main__":
1749
+ main()