awacke1 commited on
Commit
05f51d1
·
verified ·
1 Parent(s): cc8083d

Update app.py

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