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