awacke1 commited on
Commit
9e4dd4c
·
verified ·
1 Parent(s): b6067be

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +226 -182
app.py CHANGED
@@ -4,6 +4,41 @@ import json
4
  from PIL import Image
5
  from urllib.parse import quote # Ensure this import is included
6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  # Set page configuration with a title and favicon
8
  st.set_page_config(
9
  page_title="🗺️🛠️ RolePlayAI",
@@ -28,9 +63,149 @@ with st.expander("Help / About 📚", expanded=False):
28
  - 🎮 **How to Play:** Start your quest with URL challenges, like `?q=Cyberpunk` or `?query=Dungeons and Dragons`.
29
  ''')
30
 
31
- # -----------------------------------------------------------------Art Card Sidebar:
32
- import base64
33
- import requests
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  def get_image_as_base64(url):
35
  response = requests.get(url)
36
  if response.status_code == 200:
@@ -38,22 +213,64 @@ def get_image_as_base64(url):
38
  return base64.b64encode(response.content).decode("utf-8")
39
  else:
40
  return None
41
-
42
  def create_download_link(filename, base64_str):
43
  href = f'<a href="data:file/png;base64,{base64_str}" download="{filename}">Download Image</a>'
44
  return href
45
 
46
- image_url = "https://cdn-uploads.huggingface.co/production/uploads/620630b603825909dcbeba35/o1FI3G_BueAAanLBeqoo3.png"
 
 
 
 
 
 
47
 
48
- image_base64 = get_image_as_base64(image_url)
49
- if image_base64 is not None:
 
 
 
 
 
50
  with st.sidebar:
51
  st.markdown("""### 🗺️🛠️ RolePlayAI""")
52
- st.markdown(f"![image](data:image/png;base64,{image_base64})")
53
- download_link = create_download_link("downloaded_image.png", image_base64)
 
 
 
54
  st.markdown(download_link, unsafe_allow_html=True)
55
  else:
56
  st.sidebar.write("Failed to load the image.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
  # ------------------------------------------------------------- Art Card Sidebar
58
 
59
 
@@ -360,44 +577,6 @@ def display_content_or_image(query):
360
 
361
 
362
 
363
-
364
-
365
- # Imports
366
- import base64
367
- import glob
368
- import json
369
- import math
370
- import openai
371
- import os
372
- import pytz
373
- import re
374
- import requests
375
- import streamlit as st
376
- import textract
377
- import time
378
- import zipfile
379
- import huggingface_hub
380
- import dotenv
381
- from audio_recorder_streamlit import audio_recorder
382
- from bs4 import BeautifulSoup
383
- from collections import deque
384
- from datetime import datetime
385
- from dotenv import load_dotenv
386
- from huggingface_hub import InferenceClient
387
- from io import BytesIO
388
- #from langchain.chat_models import ChatOpenAI
389
- #from langchain.chains import ConversationalRetrievalChain
390
- #from langchain.embeddings import OpenAIEmbeddings
391
- #from langchain.memory import ConversationBufferMemory
392
- #from langchain.text_splitter import CharacterTextSplitter
393
- #from langchain.vectorstores import FAISS
394
- from openai import ChatCompletion
395
- from PyPDF2 import PdfReader
396
- from templates import bot_template, css, user_template
397
- from xml.etree import ElementTree as ET
398
- import streamlit.components.v1 as components # Import Streamlit Components for HTML5
399
-
400
-
401
  def add_Med_Licensing_Exam_Dataset():
402
  import streamlit as st
403
  from datasets import load_dataset
@@ -669,35 +848,6 @@ def truncate_document(document, length):
669
  def divide_document(document, max_length):
670
  return [document[i:i+max_length] for i in range(0, len(document), max_length)]
671
 
672
- # 9. Sidebar with UI controls to review and re-run prompts and continue responses
673
- @st.cache_resource
674
- def get_table_download_link(file_path):
675
- with open(file_path, 'r') as file:
676
- data = file.read()
677
-
678
- b64 = base64.b64encode(data.encode()).decode()
679
- file_name = os.path.basename(file_path)
680
- ext = os.path.splitext(file_name)[1] # get the file extension
681
- if ext == '.txt':
682
- mime_type = 'text/plain'
683
- elif ext == '.py':
684
- mime_type = 'text/plain'
685
- elif ext == '.xlsx':
686
- mime_type = 'text/plain'
687
- elif ext == '.csv':
688
- mime_type = 'text/plain'
689
- elif ext == '.htm':
690
- mime_type = 'text/html'
691
- elif ext == '.md':
692
- mime_type = 'text/markdown'
693
- elif ext == '.wav':
694
- mime_type = 'audio/wav'
695
- else:
696
- mime_type = 'application/octet-stream' # general binary data type
697
- href = f'<a href="data:{mime_type};base64,{b64}" target="_blank" download="{file_name}">{file_name}</a>'
698
- return href
699
-
700
-
701
  def CompressXML(xml_text):
702
  root = ET.fromstring(xml_text)
703
  for elem in list(root.iter()):
@@ -1114,112 +1264,6 @@ def main():
1114
  filename = generate_filename(user_prompt, choice)
1115
  create_file(filename, user_prompt, response, should_save)
1116
 
1117
- # Compose a file sidebar of markdown md files:
1118
- all_files = glob.glob("*.md")
1119
- all_files = [file for file in all_files if len(os.path.splitext(file)[0]) >= 10] # exclude files with short names
1120
- all_files.sort(key=lambda x: (os.path.splitext(x)[1], x), reverse=True) # sort by file type and file name in descending order
1121
- if st.sidebar.button("🗑 Delete All Text"):
1122
- for file in all_files:
1123
- os.remove(file)
1124
- st.experimental_rerun()
1125
- if st.sidebar.button("⬇️ Download All"):
1126
- zip_file = create_zip_of_files(all_files)
1127
- st.sidebar.markdown(get_zip_download_link(zip_file), unsafe_allow_html=True)
1128
- file_contents=''
1129
- next_action=''
1130
- for file in all_files:
1131
- col1, col2, col3, col4, col5 = st.sidebar.columns([1,6,1,1,1]) # adjust the ratio as needed
1132
- with col1:
1133
- if st.button("🌐", key="md_"+file): # md emoji button
1134
- with open(file, 'r') as f:
1135
- file_contents = f.read()
1136
- next_action='md'
1137
- with col2:
1138
- st.markdown(get_table_download_link(file), unsafe_allow_html=True)
1139
- with col3:
1140
- if st.button("📂", key="open_"+file): # open emoji button
1141
- with open(file, 'r') as f:
1142
- file_contents = f.read()
1143
- next_action='open'
1144
- with col4:
1145
- if st.button("🔍", key="read_"+file): # search emoji button
1146
- with open(file, 'r') as f:
1147
- file_contents = f.read()
1148
- next_action='search'
1149
- with col5:
1150
- if st.button("🗑", key="delete_"+file):
1151
- os.remove(file)
1152
- st.experimental_rerun()
1153
-
1154
-
1155
- if len(file_contents) > 0:
1156
- if next_action=='open':
1157
- file_content_area = st.text_area("File Contents:", file_contents, height=500)
1158
- if next_action=='md':
1159
- st.markdown(file_contents)
1160
-
1161
- buttonlabel = '🔍Run with Llama and GPT.'
1162
- if st.button(key='RunWithLlamaandGPT', label = buttonlabel):
1163
- user_prompt = file_contents
1164
-
1165
- # Llama versus GPT Battle!
1166
- all=""
1167
- try:
1168
- st.write('🔍Running with Llama.')
1169
- response = StreamLLMChatResponse(file_contents)
1170
- filename = generate_filename(user_prompt, "md")
1171
- create_file(filename, file_contents, response, should_save)
1172
- all=response
1173
- #SpeechSynthesis(response)
1174
- except:
1175
- st.markdown('Llama is sleeping. Restart ETA 30 seconds.')
1176
-
1177
- # gpt
1178
- try:
1179
- st.write('🔍Running with GPT.')
1180
- response2 = chat_with_model(user_prompt, file_contents, model_choice)
1181
- filename2 = generate_filename(file_contents, choice)
1182
- create_file(filename2, user_prompt, response, should_save)
1183
- all=all+response2
1184
- #SpeechSynthesis(response2)
1185
- except:
1186
- st.markdown('GPT is sleeping. Restart ETA 30 seconds.')
1187
-
1188
- SpeechSynthesis(all)
1189
-
1190
-
1191
- if next_action=='search':
1192
- file_content_area = st.text_area("File Contents:", file_contents, height=500)
1193
- st.write('🔍Running with Llama and GPT.')
1194
-
1195
- user_prompt = file_contents
1196
-
1197
- # Llama versus GPT Battle!
1198
- all=""
1199
- try:
1200
- st.write('🔍Running with Llama.')
1201
- response = StreamLLMChatResponse(file_contents)
1202
- filename = generate_filename(user_prompt, ".md")
1203
- create_file(filename, file_contents, response, should_save)
1204
- all=response
1205
- #SpeechSynthesis(response)
1206
- except:
1207
- st.markdown('Llama is sleeping. Restart ETA 30 seconds.')
1208
-
1209
- # gpt
1210
- try:
1211
- st.write('🔍Running with GPT.')
1212
- response2 = chat_with_model(user_prompt, file_contents, model_choice)
1213
- filename2 = generate_filename(file_contents, choice)
1214
- create_file(filename2, user_prompt, response, should_save)
1215
- all=all+response2
1216
- #SpeechSynthesis(response2)
1217
- except:
1218
- st.markdown('GPT is sleeping. Restart ETA 30 seconds.')
1219
-
1220
- SpeechSynthesis(all)
1221
-
1222
-
1223
  # Function to encode file to base64
1224
  def get_base64_encoded_file(file_path):
1225
  with open(file_path, "rb") as file:
 
4
  from PIL import Image
5
  from urllib.parse import quote # Ensure this import is included
6
 
7
+
8
+
9
+
10
+
11
+ # Imports
12
+ import base64
13
+ import glob
14
+ import json
15
+ import math
16
+ import openai
17
+ import os
18
+ import pytz
19
+ import re
20
+ import requests
21
+ import streamlit as st
22
+ import textract
23
+ import time
24
+ import zipfile
25
+ import huggingface_hub
26
+ import dotenv
27
+ from audio_recorder_streamlit import audio_recorder
28
+ from bs4 import BeautifulSoup
29
+ from collections import deque
30
+ from datetime import datetime
31
+ from dotenv import load_dotenv
32
+ from huggingface_hub import InferenceClient
33
+ from io import BytesIO
34
+ from openai import ChatCompletion
35
+ from PyPDF2 import PdfReader
36
+ from templates import bot_template, css, user_template
37
+ from xml.etree import ElementTree as ET
38
+ import streamlit.components.v1 as components # Import Streamlit Components for HTML5
39
+
40
+
41
+
42
  # Set page configuration with a title and favicon
43
  st.set_page_config(
44
  page_title="🗺️🛠️ RolePlayAI",
 
63
  - 🎮 **How to Play:** Start your quest with URL challenges, like `?q=Cyberpunk` or `?query=Dungeons and Dragons`.
64
  ''')
65
 
66
+
67
+ # 9. Sidebar with UI controls to review and re-run prompts and continue responses
68
+ @st.cache_resource
69
+ def get_table_download_link(file_path):
70
+ with open(file_path, 'r') as file:
71
+ data = file.read()
72
+
73
+ b64 = base64.b64encode(data.encode()).decode()
74
+ file_name = os.path.basename(file_path)
75
+ ext = os.path.splitext(file_name)[1] # get the file extension
76
+ if ext == '.txt':
77
+ mime_type = 'text/plain'
78
+ elif ext == '.py':
79
+ mime_type = 'text/plain'
80
+ elif ext == '.xlsx':
81
+ mime_type = 'text/plain'
82
+ elif ext == '.csv':
83
+ mime_type = 'text/plain'
84
+ elif ext == '.htm':
85
+ mime_type = 'text/html'
86
+ elif ext == '.md':
87
+ mime_type = 'text/markdown'
88
+ elif ext == '.wav':
89
+ mime_type = 'audio/wav'
90
+ else:
91
+ mime_type = 'application/octet-stream' # general binary data type
92
+ href = f'<a href="data:{mime_type};base64,{b64}" target="_blank" download="{file_name}">{file_name}</a>'
93
+ return href
94
+
95
+ def FileSidebar():
96
+ # ----------------------------------------------------- File Sidebar for Jump Gates ------------------------------------------
97
+
98
+ # Compose a file sidebar of markdown md files:
99
+ all_files = glob.glob("*.md")
100
+ all_files = [file for file in all_files if len(os.path.splitext(file)[0]) >= 10] # exclude files with short names
101
+ all_files.sort(key=lambda x: (os.path.splitext(x)[1], x), reverse=True) # sort by file type and file name in descending order
102
+ if st.sidebar.button("🗑 Delete All Text"):
103
+ for file in all_files:
104
+ os.remove(file)
105
+ st.experimental_rerun()
106
+ if st.sidebar.button("⬇️ Download All"):
107
+ zip_file = create_zip_of_files(all_files)
108
+ st.sidebar.markdown(get_zip_download_link(zip_file), unsafe_allow_html=True)
109
+ file_contents=''
110
+ next_action=''
111
+ for file in all_files:
112
+ col1, col2, col3, col4, col5 = st.sidebar.columns([1,6,1,1,1]) # adjust the ratio as needed
113
+ with col1:
114
+ if st.button("🌐", key="md_"+file): # md emoji button
115
+ with open(file, 'r') as f:
116
+ file_contents = f.read()
117
+ next_action='md'
118
+ with col2:
119
+ st.markdown(get_table_download_link(file), unsafe_allow_html=True)
120
+ with col3:
121
+ if st.button("📂", key="open_"+file): # open emoji button
122
+ with open(file, 'r') as f:
123
+ file_contents = f.read()
124
+ next_action='open'
125
+ with col4:
126
+ if st.button("🔍", key="read_"+file): # search emoji button
127
+ with open(file, 'r') as f:
128
+ file_contents = f.read()
129
+ next_action='search'
130
+ with col5:
131
+ if st.button("🗑", key="delete_"+file):
132
+ os.remove(file)
133
+ st.experimental_rerun()
134
+
135
+
136
+ if len(file_contents) > 0:
137
+ if next_action=='open':
138
+ file_content_area = st.text_area("File Contents:", file_contents, height=500)
139
+ if next_action=='md':
140
+ st.markdown(file_contents)
141
+
142
+ buttonlabel = '🔍Run with Llama and GPT.'
143
+ if st.button(key='RunWithLlamaandGPT', label = buttonlabel):
144
+ user_prompt = file_contents
145
+
146
+ # Llama versus GPT Battle!
147
+ all=""
148
+ try:
149
+ st.write('🔍Running with Llama.')
150
+ response = StreamLLMChatResponse(file_contents)
151
+ filename = generate_filename(user_prompt, "md")
152
+ create_file(filename, file_contents, response, should_save)
153
+ all=response
154
+ #SpeechSynthesis(response)
155
+ except:
156
+ st.markdown('Llama is sleeping. Restart ETA 30 seconds.')
157
+
158
+ # gpt
159
+ try:
160
+ st.write('🔍Running with GPT.')
161
+ response2 = chat_with_model(user_prompt, file_contents, model_choice)
162
+ filename2 = generate_filename(file_contents, choice)
163
+ create_file(filename2, user_prompt, response, should_save)
164
+ all=all+response2
165
+ #SpeechSynthesis(response2)
166
+ except:
167
+ st.markdown('GPT is sleeping. Restart ETA 30 seconds.')
168
+
169
+ SpeechSynthesis(all)
170
+
171
+
172
+ if next_action=='search':
173
+ file_content_area = st.text_area("File Contents:", file_contents, height=500)
174
+ st.write('🔍Running with Llama and GPT.')
175
+
176
+ user_prompt = file_contents
177
+
178
+ # Llama versus GPT Battle!
179
+ all=""
180
+ try:
181
+ st.write('🔍Running with Llama.')
182
+ response = StreamLLMChatResponse(file_contents)
183
+ filename = generate_filename(user_prompt, ".md")
184
+ create_file(filename, file_contents, response, should_save)
185
+ all=response
186
+ #SpeechSynthesis(response)
187
+ except:
188
+ st.markdown('Llama is sleeping. Restart ETA 30 seconds.')
189
+
190
+ # gpt
191
+ try:
192
+ st.write('🔍Running with GPT.')
193
+ response2 = chat_with_model(user_prompt, file_contents, model_choice)
194
+ filename2 = generate_filename(file_contents, choice)
195
+ create_file(filename2, user_prompt, response, should_save)
196
+ all=all+response2
197
+ #SpeechSynthesis(response2)
198
+ except:
199
+ st.markdown('GPT is sleeping. Restart ETA 30 seconds.')
200
+
201
+ SpeechSynthesis(all)
202
+
203
+ FileSidebar()
204
+ # ----------------------------------------------------- File Sidebar for Jump Gates ------------------------------------------
205
+
206
+
207
+ # ---- Art Card Sidebar with Random Selection of image------------------------------
208
+
209
  def get_image_as_base64(url):
210
  response = requests.get(url)
211
  if response.status_code == 200:
 
213
  return base64.b64encode(response.content).decode("utf-8")
214
  else:
215
  return None
216
+
217
  def create_download_link(filename, base64_str):
218
  href = f'<a href="data:file/png;base64,{base64_str}" download="{filename}">Download Image</a>'
219
  return href
220
 
221
+ # List of image URLs
222
+ image_urls = [
223
+ "https://cdn-uploads.huggingface.co/production/uploads/620630b603825909dcbeba35/o1FI3G_BueAAanLBeqoo3.png",
224
+ # "https://cdn-uploads.huggingface.co/production/uploads/620630b603825909dcbeba35/gv1xmIiXh1NGTeeV-cYF2.png",
225
+ # "https://cdn-uploads.huggingface.co/production/uploads/620630b603825909dcbeba35/2YsnDyc_nDNW71PPKozdN.png",
226
+ # "https://cdn-uploads.huggingface.co/production/uploads/620630b603825909dcbeba35/G_GkRD_IT3f14K7gWlbwi.png"
227
+ ]
228
 
229
+ # Select a random URL from the list
230
+ selected_image_url = random.choice(image_urls)
231
+
232
+ # Get the base64 encoded string of the selected image
233
+ selected_image_base64 = get_image_as_base64(selected_image_url)
234
+
235
+ if selected_image_base64 is not None:
236
  with st.sidebar:
237
  st.markdown("""### 🗺️🛠️ RolePlayAI""")
238
+ # Display the image
239
+ st.markdown(f"![image](data:image/png;base64,{selected_image_base64})")
240
+
241
+ # Create and display the download link
242
+ download_link = create_download_link("downloaded_image.png", selected_image_base64)
243
  st.markdown(download_link, unsafe_allow_html=True)
244
  else:
245
  st.sidebar.write("Failed to load the image.")
246
+
247
+ # ---- Art Card Sidebar with random selection of image. -------------------------------
248
+
249
+
250
+
251
+ #def get_image_as_base64(url):
252
+ # response = requests.get(url)
253
+ # if response.status_code == 200:
254
+ # Convert the image to base64
255
+ # return base64.b64encode(response.content).decode("utf-8")
256
+ # else:
257
+ # return None
258
+
259
+ #def create_download_link(filename, base64_str):
260
+ # href = f'<a href="data:file/png;base64,{base64_str}" download="{filename}">Download Image</a>'
261
+ # return href
262
+
263
+ #image_url = "https://cdn-uploads.huggingface.co/production/uploads/620630b603825909dcbeba35/o1FI3G_BueAAanLBeqoo3.png"
264
+
265
+ #image_base64 = get_image_as_base64(image_url)
266
+ #if image_base64 is not None:
267
+ # with st.sidebar:
268
+ # st.markdown("""### 🗺️🛠️ RolePlayAI""")
269
+ # st.markdown(f"![image](data:image/png;base64,{image_base64})")
270
+ # download_link = create_download_link("downloaded_image.png", image_base64)
271
+ # st.markdown(download_link, unsafe_allow_html=True)
272
+ #else:
273
+ # st.sidebar.write("Failed to load the image.")
274
  # ------------------------------------------------------------- Art Card Sidebar
275
 
276
 
 
577
 
578
 
579
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
580
  def add_Med_Licensing_Exam_Dataset():
581
  import streamlit as st
582
  from datasets import load_dataset
 
848
  def divide_document(document, max_length):
849
  return [document[i:i+max_length] for i in range(0, len(document), max_length)]
850
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
851
  def CompressXML(xml_text):
852
  root = ET.fromstring(xml_text)
853
  for elem in list(root.iter()):
 
1264
  filename = generate_filename(user_prompt, choice)
1265
  create_file(filename, user_prompt, response, should_save)
1266
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1267
  # Function to encode file to base64
1268
  def get_base64_encoded_file(file_path):
1269
  with open(file_path, "rb") as file: