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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
76 |
if __name__ == "__main__":
|
|
|
77 |
main()
|
78 |
|
79 |
|
@@ -81,3 +1387,5 @@ if __name__ == "__main__":
|
|
81 |
|
82 |
|
83 |
|
|
|
|
|
|
73 |
os.remove(selected_file)
|
74 |
st.warning(f"File deleted: {selected_file}")
|
75 |
|
76 |
+
|
77 |
+
|
78 |
+
|
79 |
+
import streamlit as st
|
80 |
+
import streamlit.components.v1 as components
|
81 |
+
import os
|
82 |
+
import json
|
83 |
+
import random
|
84 |
+
import base64
|
85 |
+
import glob
|
86 |
+
import math
|
87 |
+
import openai
|
88 |
+
import pytz
|
89 |
+
import re
|
90 |
+
import requests
|
91 |
+
import textract
|
92 |
+
import time
|
93 |
+
import zipfile
|
94 |
+
import huggingface_hub
|
95 |
+
import dotenv
|
96 |
+
from audio_recorder_streamlit import audio_recorder
|
97 |
+
from bs4 import BeautifulSoup
|
98 |
+
from collections import deque
|
99 |
+
from datetime import datetime
|
100 |
+
from dotenv import load_dotenv
|
101 |
+
from huggingface_hub import InferenceClient
|
102 |
+
from io import BytesIO
|
103 |
+
from openai import ChatCompletion
|
104 |
+
from PyPDF2 import PdfReader
|
105 |
+
from templates import bot_template, css, user_template
|
106 |
+
from xml.etree import ElementTree as ET
|
107 |
+
from PIL import Image
|
108 |
+
from urllib.parse import quote # Ensure this import is included
|
109 |
+
|
110 |
+
# Set page configuration with a title and favicon
|
111 |
+
st.set_page_config(
|
112 |
+
page_title="📖🔍WordGameAI",
|
113 |
+
page_icon="🔍📖",
|
114 |
+
layout="wide",
|
115 |
+
initial_sidebar_state="expanded",
|
116 |
+
menu_items={
|
117 |
+
'Get Help': 'https://huggingface.co/awacke1',
|
118 |
+
'Report a bug': "https://huggingface.co/spaces/awacke1/WebDataDownload",
|
119 |
+
'About': "# Midjourney: https://discord.com/channels/@me/997514686608191558"
|
120 |
+
}
|
121 |
+
)
|
122 |
+
|
123 |
+
#PromptPrefix = 'Create a markdown outline and table with appropriate emojis for top ten graphic novel plotlines where you are defining the method steps of play for topic of '
|
124 |
+
#PromptPrefix2 = 'Create a streamlit python app. Show full code listing. Create a UI implementing each feature creatively with python, streamlit, using variables and smart tables with word and idiom keys, creating reusable dense functions with graphic novel entity 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: '
|
125 |
+
|
126 |
+
# Prompts for App, for App Product, and App Product Code
|
127 |
+
PromptPrefix = 'Create a word game rule set and background story with streamlit markdown outlines and tables with appropriate emojis for methodical step by step rules defining the game play rules. Use story structure architect rules to plan, structure and write three dramatic situations to include in the word game rules matching the theme for topic of '
|
128 |
+
PromptPrefix2 = 'Create a streamlit python user app with full code listing to create a UI implementing the plans, structure, situations and tables as python functions creating a word game with parts of speech and humorous word play which operates like word game rules and creates a compelling fun story using streamlit to create user interface elements like emoji buttons, sliders, drop downs, and data interfaces like dataframes to show tables, session_state to track inventory, character advancement and experience, locations, file_uploader to allow the user to add images which are saved and referenced shown in gallery, camera_input to take character picture, on_change = function callbacks with continual running plots that change when you change data or click a button, randomness and word and letter rolls using emojis and st.markdown, st.expander for groupings and clusters of things, st.columns and other UI controls in streamlit as a game. Create inline data tables and list dictionaries for entities implemented as variables for the word game rule entities and stats. Design it as a fun data driven game app and show full python code listing for this ruleset and thematic story plot line: '
|
129 |
+
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:'
|
130 |
+
|
131 |
+
# Function to display the entire glossary in a grid format with links
|
132 |
+
def display_glossary_grid(roleplaying_glossary):
|
133 |
+
search_urls = {
|
134 |
+
"📖": lambda k: f"https://en.wikipedia.org/wiki/{quote(k)}",
|
135 |
+
"🔍": lambda k: f"https://www.google.com/search?q={quote(k)}",
|
136 |
+
"▶️": lambda k: f"https://www.youtube.com/results?search_query={quote(k)}",
|
137 |
+
"🔎": lambda k: f"https://www.bing.com/search?q={quote(k)}",
|
138 |
+
"🐦": lambda k: f"https://twitter.com/search?q={quote(k)}",
|
139 |
+
"🎲": lambda k: f"https://huggingface.co/spaces/awacke1/WordGameAI?q={quote(k)}", # this url plus query!
|
140 |
+
"🃏": lambda k: f"https://huggingface.co/spaces/awacke1/WordGameAI?q={quote(k)}-{quote(PromptPrefix)}", # this url plus query!
|
141 |
+
"📚": lambda k: f"https://huggingface.co/spaces/awacke1/WordGameAI?q={quote(k)}-{quote(PromptPrefix2)}", # this url plus query!
|
142 |
+
"🔬": lambda k: f"https://huggingface.co/spaces/awacke1/WordGameAI?q={quote(k)}-{quote(PromptPrefix3)}", # this url plus query!
|
143 |
+
}
|
144 |
+
|
145 |
+
for category, details in roleplaying_glossary.items():
|
146 |
+
st.write(f"### {category}")
|
147 |
+
cols = st.columns(len(details)) # Create dynamic columns based on the number of games
|
148 |
+
for idx, (game, terms) in enumerate(details.items()):
|
149 |
+
with cols[idx]:
|
150 |
+
st.markdown(f"#### {game}")
|
151 |
+
for term in terms:
|
152 |
+
gameterm = category + ' - ' + game + ' - ' + term
|
153 |
+
links_md = ' '.join([f"[{emoji}]({url(gameterm)})" for emoji, url in search_urls.items()])
|
154 |
+
#links_md = ' '.join([f"[{emoji}]({url(term)})" for emoji, url in search_urls.items()])
|
155 |
+
st.markdown(f"{term} {links_md}", unsafe_allow_html=True)
|
156 |
+
|
157 |
+
def display_glossary_entity(k):
|
158 |
+
search_urls = {
|
159 |
+
"📖": lambda k: f"https://en.wikipedia.org/wiki/{quote(k)}",
|
160 |
+
"🔍": lambda k: f"https://www.google.com/search?q={quote(k)}",
|
161 |
+
"▶️": lambda k: f"https://www.youtube.com/results?search_query={quote(k)}",
|
162 |
+
"🔎": lambda k: f"https://www.bing.com/search?q={quote(k)}",
|
163 |
+
"🐦": lambda k: f"https://twitter.com/search?q={quote(k)}",
|
164 |
+
"🎲": lambda k: f"https://huggingface.co/spaces/awacke1/WordGameAI?q={quote(k)}", # this url plus query!
|
165 |
+
"🃏": lambda k: f"https://huggingface.co/spaces/awacke1/WordGameAI?q={quote(k)}-{quote(PromptPrefix)}", # this url plus query!
|
166 |
+
"📚": lambda k: f"https://huggingface.co/spaces/awacke1/WordGameAI?q={quote(k)}-{quote(PromptPrefix2)}", # this url plus query!
|
167 |
+
"🔬": lambda k: f"https://huggingface.co/spaces/awacke1/WordGameAI?q={quote(k)}-{quote(PromptPrefix3)}", # this url plus query!
|
168 |
+
}
|
169 |
+
links_md = ' '.join([f"[{emoji}]({url(k)})" for emoji, url in search_urls.items()])
|
170 |
+
st.markdown(f"{k} {links_md}", unsafe_allow_html=True)
|
171 |
+
|
172 |
+
|
173 |
+
|
174 |
+
st.markdown('''### 📖✨🔍 WordGameAI ''')
|
175 |
+
with st.expander("Help / About 📚", expanded=False):
|
176 |
+
st.markdown('''
|
177 |
+
- 🚀 **Unlock Words:** Elevate your vocabulary with AI. Turns words into thrilling experiences.
|
178 |
+
- 📚 **Features:** Creates extensive glossaries & exciting challenges.
|
179 |
+
- 🧙♂️ **Experience:** Become a word wizard, boost your language skills.
|
180 |
+
- 🔎 **Query Use:** Input `?q=Palindrome` or `?query=Anagram` in URL for new challenges.
|
181 |
+
''')
|
182 |
+
|
183 |
+
|
184 |
+
roleplaying_glossary = {
|
185 |
+
"👨👩👧👦 Top Family Games": {
|
186 |
+
"Big Easy Busket": ["New Orleans culture", "Band formation", "Song performance", "Location strategy", "Diversity celebration", "3-day gameplay"],
|
187 |
+
"Bonanza": [
|
188 |
+
"Bean planting and harvesting",
|
189 |
+
"Bid and trade interaction",
|
190 |
+
"Quirky card artwork",
|
191 |
+
"Hand management",
|
192 |
+
"Negotiation skills",
|
193 |
+
"Set collecting",
|
194 |
+
"Fun with large groups",
|
195 |
+
"Laughter and enjoyment"
|
196 |
+
],
|
197 |
+
"Love Letter": [
|
198 |
+
"Valentine's Day theme",
|
199 |
+
"Simple gameplay mechanics",
|
200 |
+
"Card effects and strategy",
|
201 |
+
"Deduction to find love letter's sender",
|
202 |
+
"Take that elements",
|
203 |
+
"Fun for celebrating love",
|
204 |
+
"Engagement and elimination",
|
205 |
+
"Quick and engaging play"
|
206 |
+
],
|
207 |
+
"The Novel Shogun": [
|
208 |
+
"Japanese History 1600s",
|
209 |
+
"Perrigrine Falcon",
|
210 |
+
"Yellow Nape Amazon Parrot",
|
211 |
+
"Bill Ackman on Investing",
|
212 |
+
"Portugal History 1600s",
|
213 |
+
"England History 1600s",
|
214 |
+
"Building a Board with Different Points of View",
|
215 |
+
"Canadian Pacific Railway",
|
216 |
+
"Merchant Ships and Pilots"
|
217 |
+
],
|
218 |
+
"Votes for Women": [
|
219 |
+
"World Social Justice Day theme",
|
220 |
+
"Card-driven game exploring American women's suffrage movement",
|
221 |
+
"1 to 4 player game",
|
222 |
+
"Released in 2022 by Fort Circle Games",
|
223 |
+
"Covers 1848 to 1920 suffrage movement",
|
224 |
+
"Includes competitive, cooperative, and solitary play modes",
|
225 |
+
"Engages players in the ratification or rejection of the 19th Amendment",
|
226 |
+
"Educational content on women's rights history",
|
227 |
+
"Mechanics include area majority, dice rolling, cooperative play, and campaign-driven gameplay"
|
228 |
+
],
|
229 |
+
},
|
230 |
+
"📚 Traditional Word Games": {
|
231 |
+
"Scrabble": ["Tile placement", "Word formation", "Point scoring"],
|
232 |
+
"Boggle": ["Letter grid", "Timed word search", "Word length points"],
|
233 |
+
"Crossword Puzzles": ["Clue solving", "Word filling", "Thematic puzzles"],
|
234 |
+
"Banagrams": ["Tile shuffling", "Personal anagram puzzles", "Speed challenge"],
|
235 |
+
"Hangman": ["Word guessing", "Letter guessing", "Limited attempts"],
|
236 |
+
},
|
237 |
+
"💡 Digital Word Games": {
|
238 |
+
"Words With Friends": ["Digital Scrabble-like", "Online multiplayer", "Social interaction"],
|
239 |
+
"Wordle": ["Daily word guessing", "Limited tries", "Shareable results"],
|
240 |
+
"Letterpress": ["Competitive word search", "Territory control", "Strategic letter usage"],
|
241 |
+
"Alphabear": ["Word formation", "Cute characters", "Puzzle strategy"],
|
242 |
+
},
|
243 |
+
"🎮 Game Design and Mechanics": {
|
244 |
+
"Gameplay Dynamics": ["Word discovery", "Strategic placement", "Time pressure"],
|
245 |
+
"Player Engagement": ["Daily challenges", "Leaderboards", "Community puzzles"],
|
246 |
+
"Learning and Development": ["Vocabulary building", "Spelling practice", "Cognitive skills"],
|
247 |
+
},
|
248 |
+
"🌐 Online Platforms & Tools": {
|
249 |
+
"Multiplayer Platforms": ["Real-time competition", "Asynchronous play", "Global matchmaking"],
|
250 |
+
"Educational Tools": ["Learning modes", "Progress tracking", "Skill levels"],
|
251 |
+
"Community Features": ["Forums", "Tips and tricks sharing", "Tournament organization"],
|
252 |
+
},
|
253 |
+
"🎖️ Competitive Scene": {
|
254 |
+
"Scrabble Tournaments": ["Official rules", "National and international", "Professional rankings"],
|
255 |
+
"Crossword Competitions": ["Speed solving", "Puzzle variety", "Prizes and recognition"],
|
256 |
+
"Wordle Challenges": ["Streaks", "Perfect scores", "Community leaderboards"],
|
257 |
+
},
|
258 |
+
"📚 Lore & Background": {
|
259 |
+
"History of Word Games": ["Evolution over time", "Cultural significance", "Famous games"],
|
260 |
+
"Iconic Word Game Creators": ["Creators and designers", "Inspirational stories", "Game development"],
|
261 |
+
"Word Games in Literature": ["Literary puzzles", "Wordplay in writing", "Famous examples"],
|
262 |
+
},
|
263 |
+
"🛠️ Resources & Development": {
|
264 |
+
"Game Creation Tools": ["Word game generators", "Puzzle design software", "Community mods"],
|
265 |
+
"Educational Resources": ["Vocabulary lists", "Word game strategies", "Learning methodologies"],
|
266 |
+
"Digital Platforms": ["App development", "Online game hosting", "Social media integration"],
|
267 |
+
},
|
268 |
+
|
269 |
+
}
|
270 |
+
|
271 |
+
|
272 |
+
|
273 |
+
# HTML5 based Speech Synthesis (Text to Speech in Browser)
|
274 |
+
@st.cache_resource
|
275 |
+
def SpeechSynthesis(result):
|
276 |
+
documentHTML5='''
|
277 |
+
<!DOCTYPE html>
|
278 |
+
<html>
|
279 |
+
<head>
|
280 |
+
<title>Read It Aloud</title>
|
281 |
+
<script type="text/javascript">
|
282 |
+
function readAloud() {
|
283 |
+
const text = document.getElementById("textArea").value;
|
284 |
+
const speech = new SpeechSynthesisUtterance(text);
|
285 |
+
window.speechSynthesis.speak(speech);
|
286 |
+
}
|
287 |
+
</script>
|
288 |
+
</head>
|
289 |
+
<body>
|
290 |
+
<h1>🔊 Read It Aloud</h1>
|
291 |
+
<textarea id="textArea" rows="10" cols="80">
|
292 |
+
'''
|
293 |
+
documentHTML5 = documentHTML5 + result
|
294 |
+
documentHTML5 = documentHTML5 + '''
|
295 |
+
</textarea>
|
296 |
+
<br>
|
297 |
+
<button onclick="readAloud()">🔊 Read Aloud</button>
|
298 |
+
</body>
|
299 |
+
</html>
|
300 |
+
'''
|
301 |
+
components.html(documentHTML5, width=1280, height=300)
|
302 |
+
|
303 |
+
|
304 |
+
@st.cache_resource
|
305 |
+
def get_table_download_link(file_path):
|
306 |
+
with open(file_path, 'r') as file:
|
307 |
+
data = file.read()
|
308 |
+
b64 = base64.b64encode(data.encode()).decode()
|
309 |
+
file_name = os.path.basename(file_path)
|
310 |
+
ext = os.path.splitext(file_name)[1] # get the file extension
|
311 |
+
if ext == '.txt':
|
312 |
+
mime_type = 'text/plain'
|
313 |
+
elif ext == '.py':
|
314 |
+
mime_type = 'text/plain'
|
315 |
+
elif ext == '.xlsx':
|
316 |
+
mime_type = 'text/plain'
|
317 |
+
elif ext == '.csv':
|
318 |
+
mime_type = 'text/plain'
|
319 |
+
elif ext == '.htm':
|
320 |
+
mime_type = 'text/html'
|
321 |
+
elif ext == '.md':
|
322 |
+
mime_type = 'text/markdown'
|
323 |
+
elif ext == '.wav':
|
324 |
+
mime_type = 'audio/wav'
|
325 |
+
else:
|
326 |
+
mime_type = 'application/octet-stream' # general binary data type
|
327 |
+
href = f'<a href="data:{mime_type};base64,{b64}" target="_blank" download="{file_name}">{file_name}</a>'
|
328 |
+
return href
|
329 |
+
|
330 |
+
|
331 |
+
@st.cache_resource
|
332 |
+
def create_zip_of_files(files): # ----------------------------------
|
333 |
+
zip_name = "WordGameAI.zip"
|
334 |
+
with zipfile.ZipFile(zip_name, 'w') as zipf:
|
335 |
+
for file in files:
|
336 |
+
zipf.write(file)
|
337 |
+
return zip_name
|
338 |
+
@st.cache_resource
|
339 |
+
def get_zip_download_link(zip_file):
|
340 |
+
with open(zip_file, 'rb') as f:
|
341 |
+
data = f.read()
|
342 |
+
b64 = base64.b64encode(data).decode()
|
343 |
+
href = f'<a href="data:application/zip;base64,{b64}" download="{zip_file}">Download All</a>'
|
344 |
+
return href # ----------------------------------
|
345 |
+
|
346 |
+
|
347 |
+
def FileSidebar():
|
348 |
+
# ----------------------------------------------------- File Sidebar for Jump Gates ------------------------------------------
|
349 |
+
# Compose a file sidebar of markdown md files:
|
350 |
+
all_files = glob.glob("*.md")
|
351 |
+
all_files = [file for file in all_files if len(os.path.splitext(file)[0]) >= 10] # exclude files with short names
|
352 |
+
all_files.sort(key=lambda x: (os.path.splitext(x)[1], x), reverse=True) # sort by file type and file name in descending order
|
353 |
+
if st.sidebar.button("🗑 Delete All Text"):
|
354 |
+
for file in all_files:
|
355 |
+
os.remove(file)
|
356 |
+
st.experimental_rerun()
|
357 |
+
if st.sidebar.button("⬇️ Download All"):
|
358 |
+
zip_file = create_zip_of_files(all_files)
|
359 |
+
st.sidebar.markdown(get_zip_download_link(zip_file), unsafe_allow_html=True)
|
360 |
+
file_contents=''
|
361 |
+
next_action=''
|
362 |
+
for file in all_files:
|
363 |
+
col1, col2, col3, col4, col5 = st.sidebar.columns([1,6,1,1,1]) # adjust the ratio as needed
|
364 |
+
with col1:
|
365 |
+
if st.button("🌐", key="md_"+file): # md emoji button
|
366 |
+
with open(file, 'r') as f:
|
367 |
+
file_contents = f.read()
|
368 |
+
next_action='md'
|
369 |
+
with col2:
|
370 |
+
st.markdown(get_table_download_link(file), unsafe_allow_html=True)
|
371 |
+
with col3:
|
372 |
+
if st.button("📂", key="open_"+file): # open emoji button
|
373 |
+
with open(file, 'r') as f:
|
374 |
+
file_contents = f.read()
|
375 |
+
next_action='open'
|
376 |
+
with col4:
|
377 |
+
if st.button("🔍", key="read_"+file): # search emoji button
|
378 |
+
with open(file, 'r') as f:
|
379 |
+
file_contents = f.read()
|
380 |
+
next_action='search'
|
381 |
+
with col5:
|
382 |
+
if st.button("🗑", key="delete_"+file):
|
383 |
+
os.remove(file)
|
384 |
+
st.experimental_rerun()
|
385 |
+
|
386 |
+
|
387 |
+
if len(file_contents) > 0:
|
388 |
+
if next_action=='open':
|
389 |
+
file_content_area = st.text_area("File Contents:", file_contents, height=500)
|
390 |
+
try:
|
391 |
+
if st.button("🔍", key="filecontentssearch"):
|
392 |
+
#search_glossary(file_content_area)
|
393 |
+
filesearch = PromptPrefix + file_content_area
|
394 |
+
st.markdown(filesearch)
|
395 |
+
if st.button(key=rerun, label='🔍Re-Spec' ):
|
396 |
+
search_glossary(filesearch)
|
397 |
+
except:
|
398 |
+
st.markdown('GPT is sleeping. Restart ETA 30 seconds.')
|
399 |
+
|
400 |
+
if next_action=='md':
|
401 |
+
st.markdown(file_contents)
|
402 |
+
buttonlabel = '🔍Run'
|
403 |
+
if st.button(key='Runmd', label = buttonlabel):
|
404 |
+
user_prompt = file_contents
|
405 |
+
try:
|
406 |
+
search_glossary(file_contents)
|
407 |
+
except:
|
408 |
+
st.markdown('GPT is sleeping. Restart ETA 30 seconds.')
|
409 |
+
|
410 |
+
if next_action=='search':
|
411 |
+
file_content_area = st.text_area("File Contents:", file_contents, height=500)
|
412 |
+
user_prompt = file_contents
|
413 |
+
try:
|
414 |
+
#search_glossary(file_contents)
|
415 |
+
filesearch = PromptPrefix2 + file_content_area
|
416 |
+
st.markdown(filesearch)
|
417 |
+
if st.button(key=rerun, label='🔍Re-Code' ):
|
418 |
+
search_glossary(filesearch)
|
419 |
+
|
420 |
+
except:
|
421 |
+
st.markdown('GPT is sleeping. Restart ETA 30 seconds.')
|
422 |
+
# ----------------------------------------------------- File Sidebar for Jump Gates ------------------------------------------
|
423 |
+
|
424 |
+
|
425 |
+
FileSidebar()
|
426 |
+
|
427 |
+
|
428 |
+
|
429 |
+
# ---- Art Card Sidebar with Random Selection of image:
|
430 |
+
def get_image_as_base64(url):
|
431 |
+
response = requests.get(url)
|
432 |
+
if response.status_code == 200:
|
433 |
+
# Convert the image to base64
|
434 |
+
return base64.b64encode(response.content).decode("utf-8")
|
435 |
+
else:
|
436 |
+
return None
|
437 |
+
def create_download_link(filename, base64_str):
|
438 |
+
href = f'<a href="data:file/png;base64,{base64_str}" download="{filename}">Download Image</a>'
|
439 |
+
return href
|
440 |
+
image_urls = [
|
441 |
+
"https://cdn-uploads.huggingface.co/production/uploads/620630b603825909dcbeba35/gv1xmIiXh1NGTeeV-cYF2.png",
|
442 |
+
"https://cdn-uploads.huggingface.co/production/uploads/620630b603825909dcbeba35/2YsnDyc_nDNW71PPKozdN.png",
|
443 |
+
"https://cdn-uploads.huggingface.co/production/uploads/620630b603825909dcbeba35/G_GkRD_IT3f14K7gWlbwi.png",
|
444 |
+
]
|
445 |
+
selected_image_url = random.choice(image_urls)
|
446 |
+
selected_image_base64 = get_image_as_base64(selected_image_url)
|
447 |
+
if selected_image_base64 is not None:
|
448 |
+
with st.sidebar:
|
449 |
+
#st.markdown("""### Word Game AI""")
|
450 |
+
st.markdown(f"![image](data:image/png;base64,{selected_image_base64})")
|
451 |
+
else:
|
452 |
+
st.sidebar.write("Failed to load the image.")
|
453 |
+
# ---- Art Card Sidebar with random selection of image.
|
454 |
+
|
455 |
+
|
456 |
+
|
457 |
+
|
458 |
+
|
459 |
+
# Ensure the directory for storing scores exists
|
460 |
+
score_dir = "scores"
|
461 |
+
os.makedirs(score_dir, exist_ok=True)
|
462 |
+
|
463 |
+
# Function to generate a unique key for each button, including an emoji
|
464 |
+
def generate_key(label, header, idx):
|
465 |
+
return f"{header}_{label}_{idx}_key"
|
466 |
+
|
467 |
+
# Function to increment and save score
|
468 |
+
def update_score(key, increment=1):
|
469 |
+
score_file = os.path.join(score_dir, f"{key}.json")
|
470 |
+
if os.path.exists(score_file):
|
471 |
+
with open(score_file, "r") as file:
|
472 |
+
score_data = json.load(file)
|
473 |
+
else:
|
474 |
+
score_data = {"clicks": 0, "score": 0}
|
475 |
+
|
476 |
+
score_data["clicks"] += 1
|
477 |
+
score_data["score"] += increment
|
478 |
+
|
479 |
+
with open(score_file, "w") as file:
|
480 |
+
json.dump(score_data, file)
|
481 |
+
|
482 |
+
return score_data["score"]
|
483 |
+
|
484 |
+
# Function to load score
|
485 |
+
def load_score(key):
|
486 |
+
score_file = os.path.join(score_dir, f"{key}.json")
|
487 |
+
if os.path.exists(score_file):
|
488 |
+
with open(score_file, "r") as file:
|
489 |
+
score_data = json.load(file)
|
490 |
+
return score_data["score"]
|
491 |
+
return 0
|
492 |
+
|
493 |
+
@st.cache_resource
|
494 |
+
def search_glossary(query): # 🔍Run--------------------------------------------------------
|
495 |
+
for category, terms in roleplaying_glossary.items():
|
496 |
+
if query.lower() in (term.lower() for term in terms):
|
497 |
+
st.markdown(f"#### {category}")
|
498 |
+
st.write(f"- {query}")
|
499 |
+
|
500 |
+
all=""
|
501 |
+
|
502 |
+
WordGameRules="""Generate 10 high-information words related to word game rules, used in context with emojis:
|
503 |
+
1. 📜 Rules: The official guidelines that govern the gameplay and objectives of a word game.
|
504 |
+
2. ⏰ Time Limit: A constraint on the duration allowed for players to complete their turns or the entire game.
|
505 |
+
3. 🎲 Dice: Used in some word games to randomly determine letter selection or point values.
|
506 |
+
4. 📚 Dictionary: A reference book used to validate the legitimacy of words formed by players.
|
507 |
+
5. 🔠 Alphabet: The set of letters used to construct words in the game, often with varying point values.
|
508 |
+
6. 🔄 Turn: The opportunity for each player to form words or perform actions as per the game rules.
|
509 |
+
7. 🧩 Board: The playing surface on which letter tiles are placed to form words in certain word games.
|
510 |
+
8. 🔍 Challenge: An action that allows players to contest the validity of words formed by their opponents.
|
511 |
+
9. 💰 Score: Points earned by players for forming valid words, often based on letter values and word length.
|
512 |
+
10. ❌ Pass: An option for players to skip their turn if unable to form a word, sometimes with penalties."""
|
513 |
+
|
514 |
+
WordGamePython="""Generate 10 high-information words related to word game programming in Python, used in context with emojis:
|
515 |
+
1. 🐍 Python: A high-level programming language known for its simplicity and readability.
|
516 |
+
2. 📜 String: A data type used to represent text, essential for handling words in a word game.
|
517 |
+
3. 🎲 Random: A Python module that generates random numbers, useful for letter selection or AI opponents.
|
518 |
+
4. 📝 Input: A function that allows players to enter their words or actions through the command line.
|
519 |
+
5. 📊 List: A data structure that stores multiple elements, handy for managing game components like letters or words.
|
520 |
+
6. 🔍 Validation: The process of checking if a word entered by a player is valid according to the game rules.
|
521 |
+
7. 🔄 Loop: A programming construct that allows repeated execution of code, useful for turn-based gameplay.
|
522 |
+
8. 🎨 Pygame: A popular Python library for creating games with graphics and sound.
|
523 |
+
9. 💾 File I/O: Reading from and writing to files, useful for storing game data like high scores or word lists.
|
524 |
+
10. 🤖 AI: Implementing artificial intelligence techniques to create computer-controlled opponents in word games."""
|
525 |
+
|
526 |
+
|
527 |
+
WordGamePython2="""1. 🎨 Streamlit: A Python library for building interactive web apps, perfect for creating word games.
|
528 |
+
Example: st.title("Welcome to the Word Guessing Game! 🎮")
|
529 |
+
|
530 |
+
2. 🗃️ JSON: A lightweight data interchange format, useful for storing and loading game data.
|
531 |
+
Example: game_data = json.loads(st.secrets["game_data"])
|
532 |
+
|
533 |
+
3. 🎲 Random: A Python module for generating random numbers, handy for selecting random words or letters.
|
534 |
+
Example: random_word = random.choice(word_list)
|
535 |
+
|
536 |
+
4. 🕒 Time: A Python module for handling time-related tasks, such as measuring game duration or implementing timers.
|
537 |
+
Example: start_time = time.time()
|
538 |
+
|
539 |
+
5. 📝 Regex: Short for Regular Expressions, a powerful tool for pattern matching and text manipulation.
|
540 |
+
Example: if re.match(r"^[a-zA-Z]+$", user_input):
|
541 |
+
|
542 |
+
6. 🌐 Requests: A Python library for making HTTP requests, useful for fetching word lists or definitions from online APIs.
|
543 |
+
Example: response = requests.get("https://api.wordnik.com/v4/words.json/randomWord")
|
544 |
+
|
545 |
+
7. 🖼️ PIL (Python Imaging Library): A library for opening, manipulating, and saving images, great for adding visual elements to your word game.
|
546 |
+
Example: image = Image.open("background.jpg")
|
547 |
+
|
548 |
+
8. 🔗 URLLib: A Python module for handling URLs, useful for encoding and decoding special characters in word-related URLs.
|
549 |
+
Example: encoded_word = quote(user_input)
|
550 |
+
|
551 |
+
9. 💾 IO (Input/Output): A Python module for handling input and output operations, such as reading from and writing to files or in-memory buffers.
|
552 |
+
Example: word_list = BytesIO(requests.get("https://example.com/words.txt").content)
|
553 |
+
|
554 |
+
10. 🧩 Collections: A Python module providing useful data structures, such as deque for efficient list manipulation.
|
555 |
+
Example: letter_queue = deque(random.sample(string.ascii_uppercase, 10))"""
|
556 |
+
|
557 |
+
|
558 |
+
WordGameJavascript="""Generate 10 high-information words related to word game programming in Javascript, used in context with emojis:
|
559 |
+
1. 🌐 Javascript: A versatile programming language commonly used for web-based games and interactivity.
|
560 |
+
2. 🏷️ HTML: The markup language used to structure the content of web pages, including game elements.
|
561 |
+
3. 🎨 CSS: A stylesheet language used to describe the presentation and layout of HTML elements in a game.
|
562 |
+
4. 📜 String: A primitive data type in Javascript used to represent textual data, crucial for word games.
|
563 |
+
5. 🎲 Math.random(): A built-in Javascript function that generates random numbers, handy for letter selection or AI moves.
|
564 |
+
6. 📝 prompt(): A function that displays a dialog box prompting the player to enter a word or make a choice.
|
565 |
+
7. 🔍 RegExp: Regular expressions in Javascript, useful for pattern matching and validating player input.
|
566 |
+
8. 🖱️ addEventListener(): A method used to attach event handlers to elements, enabling interactivity in the game.
|
567 |
+
9. 💾 localStorage: A web storage object that allows data to be stored in the browser, useful for saving game progress.
|
568 |
+
10. 🤖 AI: Implementing artificial intelligence algorithms in Javascript to create computer-controlled opponents."""
|
569 |
+
|
570 |
+
# 🔍Run 1 - plain query
|
571 |
+
response = chat_with_model(query)
|
572 |
+
all = query + ' ' + response
|
573 |
+
st.write('🔍Run 1 is Complete.')
|
574 |
+
|
575 |
+
# 🔍Run 2 - Specification Expert - Write a Document to Specify Inner Dialog of Expert
|
576 |
+
specquery = 'For the topic of: ' + query + ', Write a specification which documents your inner dialog as an expert storyteller and word game creator.'
|
577 |
+
specquery = specquery + 'For each one of the Game Features of the specification write three short fun game rules with a plan and description on how to play. Write each like a specification and a story and a game blending fun and humorous ideas which allow a player to get better at all modalities of language.'
|
578 |
+
specquery = specquery + 'Here is the list of word game rules you will expand on how with plan and specification. Use markdown code, tables and outlines. Use appropriate emojis for each rule and feature. Make it easy to read with emojis, boldface and outlines and titles (#, ##, ###, ####) along with (** around text for bold):'
|
579 |
+
specquery = specquery + WordGameRules
|
580 |
+
specresponse = chat_with_model(specquery)
|
581 |
+
all = all + specquery + ' ' + specresponse
|
582 |
+
st.write('🔍Run 2 is Complete.')
|
583 |
+
SpeechSynthesis(response + ' ' + specresponse)
|
584 |
+
|
585 |
+
# 🔍Run 3 - Coding Expert - Write a Streamlit Python program with app.py and requirements.txt
|
586 |
+
codequery = 'Write a streamlit python program which implements line for line each function and UI in the rule specification with coded features for each as a functionCreate a streamlit user interface for each for input and output for the user for each feature to play a complete word game called: '
|
587 |
+
codequery = codequery + query + '.'
|
588 |
+
codequery = codequery + 'Use python features for word game such as the python game here: '
|
589 |
+
codequery = codequery + WordGamePython
|
590 |
+
codequery = codequery + 'Create a visually appealing UI (plan and code them from specification) so the user has fun interacting with these game features so each should have a small ui possibly st.expander or use of select and list boxes etc to make the UI flow well having multiple action centers where the screen and text change due to random and lists with you adding lots of tables of words etc which make it fun: '
|
591 |
+
codequery = codequery + 'Also use the specification to serve as your feature set for the word game you are writing in python and streamlit. Include the entire specification as markdown inside the program.'
|
592 |
+
codequery = codequery + specresponse # feed forward expert output to next expert agent
|
593 |
+
coderesponse = chat_with_model(codequery)
|
594 |
+
all = all + codequery + ' ' + coderesponse
|
595 |
+
st.write('🔍Run 3 is Complete.')
|
596 |
+
|
597 |
+
# todo - add back python execution located elsewhere here in comment. acw 2/24/2022/6:20
|
598 |
+
|
599 |
+
# 🔍Run 4 - Code Completion Expert -
|
600 |
+
webquery = 'Revise and expand on features in my game for ' + query + '. For each python function, improve the feature by adding 3 to 5 code lines each that implements the feature and UI in detail for streamlit so the user can play each feature.'
|
601 |
+
#webquery = webquery + 'Please study my Javascript preferences on word game features here: '
|
602 |
+
webquery = webquery + WordGamePython2
|
603 |
+
#webquery = webquery + 'The objective of this exercise is to create a visually appealing UI so the user has fun interacting with these game features so each should use timers, randomness, word tables, and features found in word games in a dynamic html5 app with javascript which make it fun.'
|
604 |
+
webquery = webquery + 'use this code written in python and streamlit, expanding language features in python and streamlit functions along with popular third party python libraries.'
|
605 |
+
webquery = webquery + coderesponse # feed forward expert output to next expert agent
|
606 |
+
webresponse = chat_with_model(webquery)
|
607 |
+
all = all + webquery + ' ' + webresponse
|
608 |
+
st.write('🔍Run 4 is Complete.')
|
609 |
+
|
610 |
+
#PromptPrefix2 = 'Create a streamlit python user app with full code listing to create a UI implementing the plans, structure, situations and tables as python functions creating a word game with parts of speech and humorous word play which operates like word game rules and creates a compelling fun story using streamlit to create user interface elements like emoji buttons, sliders, drop downs, and data interfaces like dataframes to show tables, session_state to track inventory, character advancement and experience, locations, file_uploader to allow the user to add images which are saved and referenced shown in gallery, camera_input to take character picture, on_change = function callbacks with continual running plots that change when you change data or click a button, randomness and word and letter rolls using emojis and st.markdown, st.expander for groupings and clusters of things, st.columns and other UI controls in streamlit as a game. Create inline data tables and list dictionaries for entities implemented as variables for the word game rule entities and stats. Design it as a fun data driven game app and show full python code listing for this ruleset and thematic story plot line: '
|
611 |
+
#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:'
|
612 |
+
|
613 |
+
response = response + specresponse + coderesponse + webresponse
|
614 |
+
filename = generate_filename(response, "md")
|
615 |
+
create_file(filename, query, response, should_save)
|
616 |
+
queries = query + specquery + codequery + webquery
|
617 |
+
|
618 |
+
#SpeechSynthesis(response)
|
619 |
+
return all # 🔍Run--------------------------------------------------------
|
620 |
+
|
621 |
+
|
622 |
+
# Function to display the glossary in a structured format
|
623 |
+
def display_glossary(glossary, area):
|
624 |
+
if area in glossary:
|
625 |
+
st.subheader(f"📘 Glossary for {area}")
|
626 |
+
for game, terms in glossary[area].items():
|
627 |
+
st.markdown(f"### {game}")
|
628 |
+
for idx, term in enumerate(terms, start=1):
|
629 |
+
st.write(f"{idx}. {term}")
|
630 |
+
|
631 |
+
|
632 |
+
# Function to display the entire glossary in a grid format with links
|
633 |
+
def display_glossary_grid(roleplaying_glossary):
|
634 |
+
search_urls = {
|
635 |
+
"📖": lambda k: f"https://en.wikipedia.org/wiki/{quote(k)}",
|
636 |
+
"🔍": lambda k: f"https://www.google.com/search?q={quote(k)}",
|
637 |
+
"▶️": lambda k: f"https://www.youtube.com/results?search_query={quote(k)}",
|
638 |
+
"🔎": lambda k: f"https://www.bing.com/search?q={quote(k)}",
|
639 |
+
"🎲": lambda k: f"https://huggingface.co/spaces/awacke1/MixableWordGameAI?q={quote(k)}", # this url plus query!
|
640 |
+
|
641 |
+
}
|
642 |
+
|
643 |
+
for category, details in roleplaying_glossary.items():
|
644 |
+
st.write(f"### {category}")
|
645 |
+
cols = st.columns(len(details)) # Create dynamic columns based on the number of games
|
646 |
+
for idx, (game, terms) in enumerate(details.items()):
|
647 |
+
with cols[idx]:
|
648 |
+
st.markdown(f"#### {game}")
|
649 |
+
for term in terms:
|
650 |
+
links_md = ' '.join([f"[{emoji}]({url(term)})" for emoji, url in search_urls.items()])
|
651 |
+
st.markdown(f"{term} {links_md}", unsafe_allow_html=True)
|
652 |
+
|
653 |
+
|
654 |
+
@st.cache_resource
|
655 |
+
def display_videos_and_links():
|
656 |
+
video_files = [f for f in os.listdir('.') if f.endswith('.mp4')]
|
657 |
+
if not video_files:
|
658 |
+
st.write("No MP4 videos found in the current directory.")
|
659 |
+
return
|
660 |
+
|
661 |
+
video_files_sorted = sorted(video_files, key=lambda x: len(x.split('.')[0]))
|
662 |
+
|
663 |
+
cols = st.columns(2) # Define 2 columns outside the loop
|
664 |
+
col_index = 0 # Initialize column index
|
665 |
+
|
666 |
+
for video_file in video_files_sorted:
|
667 |
+
with cols[col_index % 2]: # Use modulo 2 to alternate between the first and second column
|
668 |
+
# Embedding video with autoplay and loop using HTML
|
669 |
+
#video_html = ("""<video width="100%" loop autoplay> <source src="{video_file}" type="video/mp4">Your browser does not support the video tag.</video>""")
|
670 |
+
#st.markdown(video_html, unsafe_allow_html=True)
|
671 |
+
k = video_file.split('.')[0] # Assumes keyword is the file name without extension
|
672 |
+
st.video(video_file, format='video/mp4', start_time=0)
|
673 |
+
display_glossary_entity(k)
|
674 |
+
col_index += 1 # Increment column index to place the next video in the next column
|
675 |
+
|
676 |
+
@st.cache_resource
|
677 |
+
def display_images_and_wikipedia_summaries():
|
678 |
+
image_files = [f for f in os.listdir('.') if f.endswith('.png')]
|
679 |
+
if not image_files:
|
680 |
+
st.write("No PNG images found in the current directory.")
|
681 |
+
return
|
682 |
+
image_files_sorted = sorted(image_files, key=lambda x: len(x.split('.')[0]))
|
683 |
+
grid_sizes = [len(f.split('.')[0]) for f in image_files_sorted]
|
684 |
+
col_sizes = ['small' if size <= 4 else 'medium' if size <= 8 else 'large' for size in grid_sizes]
|
685 |
+
num_columns_map = {"small": 4, "medium": 3, "large": 2}
|
686 |
+
current_grid_size = 0
|
687 |
+
for image_file, col_size in zip(image_files_sorted, col_sizes):
|
688 |
+
if current_grid_size != num_columns_map[col_size]:
|
689 |
+
cols = st.columns(num_columns_map[col_size])
|
690 |
+
current_grid_size = num_columns_map[col_size]
|
691 |
+
col_index = 0
|
692 |
+
with cols[col_index % current_grid_size]:
|
693 |
+
image = Image.open(image_file)
|
694 |
+
st.image(image, caption=image_file, use_column_width=True)
|
695 |
+
k = image_file.split('.')[0] # Assumes keyword is the file name without extension
|
696 |
+
display_glossary_entity(k)
|
697 |
+
|
698 |
+
def get_all_query_params(key):
|
699 |
+
return st.query_params().get(key, [])
|
700 |
+
|
701 |
+
def clear_query_params():
|
702 |
+
st.query_params()
|
703 |
+
|
704 |
+
# Function to display content or image based on a query
|
705 |
+
@st.cache_resource
|
706 |
+
def display_content_or_image(query):
|
707 |
+
for category, terms in transhuman_glossary.items():
|
708 |
+
for term in terms:
|
709 |
+
if query.lower() in term.lower():
|
710 |
+
st.subheader(f"Found in {category}:")
|
711 |
+
st.write(term)
|
712 |
+
return True # Return after finding and displaying the first match
|
713 |
+
image_dir = "images" # Example directory where images are stored
|
714 |
+
image_path = f"{image_dir}/{query}.png" # Construct image path with query
|
715 |
+
if os.path.exists(image_path):
|
716 |
+
st.image(image_path, caption=f"Image for {query}")
|
717 |
+
return True
|
718 |
+
st.warning("No matching content or image found.")
|
719 |
+
return False
|
720 |
+
|
721 |
+
|
722 |
+
game_emojis = {
|
723 |
+
"Dungeons and Dragons": "🐉",
|
724 |
+
"Call of Cthulhu": "🐙",
|
725 |
+
"GURPS": "🎲",
|
726 |
+
"Pathfinder": "🗺️",
|
727 |
+
"Kindred of the East": "🌅",
|
728 |
+
"Changeling": "🍃",
|
729 |
+
}
|
730 |
+
|
731 |
+
topic_emojis = {
|
732 |
+
"Core Rulebooks": "📚",
|
733 |
+
"Maps & Settings": "🗺️",
|
734 |
+
"Game Mechanics & Tools": "⚙️",
|
735 |
+
"Monsters & Adversaries": "👹",
|
736 |
+
"Campaigns & Adventures": "📜",
|
737 |
+
"Creatives & Assets": "🎨",
|
738 |
+
"Game Master Resources": "🛠️",
|
739 |
+
"Lore & Background": "📖",
|
740 |
+
"Character Development": "🧍",
|
741 |
+
"Homebrew Content": "🔧",
|
742 |
+
"General Topics": "🌍",
|
743 |
+
}
|
744 |
+
|
745 |
+
# Adjusted display_buttons_with_scores function
|
746 |
+
def display_buttons_with_scores():
|
747 |
+
for category, games in roleplaying_glossary.items():
|
748 |
+
category_emoji = topic_emojis.get(category, "🔍") # Default to search icon if no match
|
749 |
+
st.markdown(f"## {category_emoji} {category}")
|
750 |
+
for game, terms in games.items():
|
751 |
+
game_emoji = game_emojis.get(game, "🎮") # Default to generic game controller if no match
|
752 |
+
for term in terms:
|
753 |
+
key = f"{category}_{game}_{term}".replace(' ', '_').lower()
|
754 |
+
score = load_score(key)
|
755 |
+
if st.button(f"{game_emoji} {category} {game} {term} {score}", key=key):
|
756 |
+
update_score(key)
|
757 |
+
# Create a dynamic query incorporating emojis and formatting for clarity
|
758 |
+
query_prefix = f"{category_emoji} {game_emoji} ** {category} - {game} - {term} - **"
|
759 |
+
# ----------------------------------------------------------------------------------------------
|
760 |
+
#query_body = f"Create a detailed outline for **{term}** with subpoints highlighting key aspects, using emojis for visual engagement. Include step-by-step rules and boldface important entities and ruleset elements."
|
761 |
+
query_body = f"Create a streamlit python app.py that produces a detailed markdown outline and emoji laden user interface with labels with the entity name and emojis in all labels with a set of streamlit UI components with drop down lists and dataframes and buttons with expander and sidebar for the app to run the data as default values mostly in text boxes. Feature a 3 point outline sith 3 subpoints each where each line has about six words describing this and also contain appropriate emoji for creating sumamry of all aspeccts of this topic. an outline for **{term}** with subpoints highlighting key aspects, using emojis for visual engagement. Include step-by-step rules and boldface important entities and ruleset elements."
|
762 |
+
response = search_glossary(query_prefix + query_body)
|
763 |
+
|
764 |
+
|
765 |
+
def fetch_wikipedia_summary(keyword):
|
766 |
+
# Placeholder function for fetching Wikipedia summaries
|
767 |
+
# In a real app, you might use requests to fetch from the Wikipedia API
|
768 |
+
return f"Summary for {keyword}. For more information, visit Wikipedia."
|
769 |
+
|
770 |
+
def create_search_url_youtube(keyword):
|
771 |
+
base_url = "https://www.youtube.com/results?search_query="
|
772 |
+
return base_url + keyword.replace(' ', '+')
|
773 |
+
|
774 |
+
def create_search_url_bing(keyword):
|
775 |
+
base_url = "https://www.bing.com/search?q="
|
776 |
+
return base_url + keyword.replace(' ', '+')
|
777 |
+
|
778 |
+
def create_search_url_wikipedia(keyword):
|
779 |
+
base_url = "https://www.wikipedia.org/search-redirect.php?family=wikipedia&language=en&search="
|
780 |
+
return base_url + keyword.replace(' ', '+')
|
781 |
+
|
782 |
+
def create_search_url_google(keyword):
|
783 |
+
base_url = "https://www.google.com/search?q="
|
784 |
+
return base_url + keyword.replace(' ', '+')
|
785 |
+
|
786 |
+
def create_search_url_ai(keyword):
|
787 |
+
base_url = "https://huggingface.co/spaces/awacke1/MixableWordGameAI?q="
|
788 |
+
return base_url + keyword.replace(' ', '+')
|
789 |
+
|
790 |
+
def display_images_and_wikipedia_summaries():
|
791 |
+
image_files = [f for f in os.listdir('.') if f.endswith('.png')]
|
792 |
+
if not image_files:
|
793 |
+
st.write("No PNG images found in the current directory.")
|
794 |
+
return
|
795 |
+
|
796 |
+
for image_file in image_files:
|
797 |
+
image = Image.open(image_file)
|
798 |
+
st.image(image, caption=image_file, use_column_width=True)
|
799 |
+
|
800 |
+
keyword = image_file.split('.')[0] # Assumes keyword is the file name without extension
|
801 |
+
|
802 |
+
# Display Wikipedia and Google search links
|
803 |
+
wikipedia_url = create_search_url_wikipedia(keyword)
|
804 |
+
google_url = create_search_url_google(keyword)
|
805 |
+
youtube_url = create_search_url_youtube(keyword)
|
806 |
+
bing_url = create_search_url_bing(keyword)
|
807 |
+
ai_url = create_search_url_ai(keyword)
|
808 |
+
|
809 |
+
|
810 |
+
links_md = f"""
|
811 |
+
[Wikipedia]({wikipedia_url}) |
|
812 |
+
[Google]({google_url}) |
|
813 |
+
[YouTube]({youtube_url}) |
|
814 |
+
[Bing]({bing_url}) |
|
815 |
+
[AI]({ai_url})
|
816 |
+
"""
|
817 |
+
st.markdown(links_md)
|
818 |
+
|
819 |
+
|
820 |
+
def get_all_query_params(key):
|
821 |
+
return st.query_params().get(key, [])
|
822 |
+
|
823 |
+
def clear_query_params():
|
824 |
+
st.query_params()
|
825 |
+
|
826 |
+
|
827 |
+
|
828 |
+
# My Inference API Copy
|
829 |
+
API_URL = 'https://qe55p8afio98s0u3.us-east-1.aws.endpoints.huggingface.cloud' # Dr Llama
|
830 |
+
# Meta's Original - Chat HF Free Version:
|
831 |
+
#API_URL = "https://api-inference.huggingface.co/models/meta-llama/Llama-2-7b-chat-hf"
|
832 |
+
API_KEY = os.getenv('API_KEY')
|
833 |
+
MODEL1="meta-llama/Llama-2-7b-chat-hf"
|
834 |
+
MODEL1URL="https://huggingface.co/meta-llama/Llama-2-7b-chat-hf"
|
835 |
+
HF_KEY = os.getenv('HF_KEY')
|
836 |
+
headers = {
|
837 |
+
"Authorization": f"Bearer {HF_KEY}",
|
838 |
+
"Content-Type": "application/json"
|
839 |
+
}
|
840 |
+
key = os.getenv('OPENAI_API_KEY')
|
841 |
+
prompt = "...."
|
842 |
+
should_save = st.sidebar.checkbox("💾 Save", value=True, help="Save your session data.")
|
843 |
+
|
844 |
+
|
845 |
+
|
846 |
+
|
847 |
+
# 3. Stream Llama Response
|
848 |
+
# @st.cache_resource
|
849 |
+
def StreamLLMChatResponse(prompt):
|
850 |
+
try:
|
851 |
+
endpoint_url = API_URL
|
852 |
+
hf_token = API_KEY
|
853 |
+
st.write('Running client ' + endpoint_url)
|
854 |
+
client = InferenceClient(endpoint_url, token=hf_token)
|
855 |
+
gen_kwargs = dict(
|
856 |
+
max_new_tokens=512,
|
857 |
+
top_k=30,
|
858 |
+
top_p=0.9,
|
859 |
+
temperature=0.2,
|
860 |
+
repetition_penalty=1.02,
|
861 |
+
stop_sequences=["\nUser:", "<|endoftext|>", "</s>"],
|
862 |
+
)
|
863 |
+
stream = client.text_generation(prompt, stream=True, details=True, **gen_kwargs)
|
864 |
+
report=[]
|
865 |
+
res_box = st.empty()
|
866 |
+
collected_chunks=[]
|
867 |
+
collected_messages=[]
|
868 |
+
allresults=''
|
869 |
+
for r in stream:
|
870 |
+
if r.token.special:
|
871 |
+
continue
|
872 |
+
if r.token.text in gen_kwargs["stop_sequences"]:
|
873 |
+
break
|
874 |
+
collected_chunks.append(r.token.text)
|
875 |
+
chunk_message = r.token.text
|
876 |
+
collected_messages.append(chunk_message)
|
877 |
+
try:
|
878 |
+
report.append(r.token.text)
|
879 |
+
if len(r.token.text) > 0:
|
880 |
+
result="".join(report).strip()
|
881 |
+
res_box.markdown(f'*{result}*')
|
882 |
+
|
883 |
+
except:
|
884 |
+
st.write('Stream llm issue')
|
885 |
+
SpeechSynthesis(result)
|
886 |
+
return result
|
887 |
+
except:
|
888 |
+
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).')
|
889 |
+
|
890 |
+
# 4. Run query with payload
|
891 |
+
def query(payload):
|
892 |
+
response = requests.post(API_URL, headers=headers, json=payload)
|
893 |
+
st.markdown(response.json())
|
894 |
+
return response.json()
|
895 |
+
|
896 |
+
def get_output(prompt):
|
897 |
+
return query({"inputs": prompt})
|
898 |
+
|
899 |
+
# 5. Auto name generated output files from time and content
|
900 |
+
def generate_filename(prompt, file_type):
|
901 |
+
central = pytz.timezone('US/Central')
|
902 |
+
safe_date_time = datetime.now(central).strftime("%m%d_%H%M")
|
903 |
+
replaced_prompt = prompt.replace(" ", "_").replace("\n", "_")
|
904 |
+
safe_prompt = "".join(x for x in replaced_prompt if x.isalnum() or x == "_")[:255] # 255 is linux max, 260 is windows max
|
905 |
+
#safe_prompt = "".join(x for x in replaced_prompt if x.isalnum() or x == "_")[:45]
|
906 |
+
return f"{safe_date_time}_{safe_prompt}.{file_type}"
|
907 |
+
|
908 |
+
# 6. Speech transcription via OpenAI service
|
909 |
+
def transcribe_audio(openai_key, file_path, model):
|
910 |
+
openai.api_key = openai_key
|
911 |
+
OPENAI_API_URL = "https://api.openai.com/v1/audio/transcriptions"
|
912 |
+
headers = {
|
913 |
+
"Authorization": f"Bearer {openai_key}",
|
914 |
+
}
|
915 |
+
with open(file_path, 'rb') as f:
|
916 |
+
data = {'file': f}
|
917 |
+
st.write('STT transcript ' + OPENAI_API_URL)
|
918 |
+
response = requests.post(OPENAI_API_URL, headers=headers, files=data, data={'model': model})
|
919 |
+
if response.status_code == 200:
|
920 |
+
st.write(response.json())
|
921 |
+
chatResponse = chat_with_model(response.json().get('text'), '') # *************************************
|
922 |
+
transcript = response.json().get('text')
|
923 |
+
filename = generate_filename(transcript, 'txt')
|
924 |
+
response = chatResponse
|
925 |
+
user_prompt = transcript
|
926 |
+
create_file(filename, user_prompt, response, should_save)
|
927 |
+
return transcript
|
928 |
+
else:
|
929 |
+
st.write(response.json())
|
930 |
+
st.error("Error in API call.")
|
931 |
+
return None
|
932 |
+
|
933 |
+
# 7. Auto stop on silence audio control for recording WAV files
|
934 |
+
def save_and_play_audio(audio_recorder):
|
935 |
+
audio_bytes = audio_recorder(key='audio_recorder')
|
936 |
+
if audio_bytes:
|
937 |
+
filename = generate_filename("Recording", "wav")
|
938 |
+
with open(filename, 'wb') as f:
|
939 |
+
f.write(audio_bytes)
|
940 |
+
st.audio(audio_bytes, format="audio/wav")
|
941 |
+
return filename
|
942 |
+
return None
|
943 |
+
|
944 |
+
# 8. File creator that interprets type and creates output file for text, markdown and code
|
945 |
+
def create_file(filename, prompt, response, should_save=True):
|
946 |
+
if not should_save:
|
947 |
+
return
|
948 |
+
base_filename, ext = os.path.splitext(filename)
|
949 |
+
if ext in ['.txt', '.htm', '.md']:
|
950 |
+
with open(f"{base_filename}.md", 'w') as file:
|
951 |
+
try:
|
952 |
+
content = prompt.strip() + '\r\n' + response
|
953 |
+
file.write(content)
|
954 |
+
except:
|
955 |
+
st.write('.')
|
956 |
+
|
957 |
+
#has_python_code = re.search(r"```python([\s\S]*?)```", prompt.strip() + '\r\n' + response)
|
958 |
+
#has_python_code = bool(re.search(r"```python([\s\S]*?)```", prompt.strip() + '\r\n' + response))
|
959 |
+
#if has_python_code:
|
960 |
+
# python_code = re.findall(r"```python([\s\S]*?)```", response)[0].strip()
|
961 |
+
# with open(f"{base_filename}-Code.py", 'w') as file:
|
962 |
+
# file.write(python_code)
|
963 |
+
# with open(f"{base_filename}.md", 'w') as file:
|
964 |
+
# content = prompt.strip() + '\r\n' + response
|
965 |
+
# file.write(content)
|
966 |
+
|
967 |
+
def truncate_document(document, length):
|
968 |
+
return document[:length]
|
969 |
+
def divide_document(document, max_length):
|
970 |
+
return [document[i:i+max_length] for i in range(0, len(document), max_length)]
|
971 |
+
|
972 |
+
def CompressXML(xml_text):
|
973 |
+
root = ET.fromstring(xml_text)
|
974 |
+
for elem in list(root.iter()):
|
975 |
+
if isinstance(elem.tag, str) and 'Comment' in elem.tag:
|
976 |
+
elem.parent.remove(elem)
|
977 |
+
return ET.tostring(root, encoding='unicode', method="xml")
|
978 |
+
|
979 |
+
# 10. Read in and provide UI for past files
|
980 |
+
@st.cache_resource
|
981 |
+
def read_file_content(file,max_length):
|
982 |
+
if file.type == "application/json":
|
983 |
+
content = json.load(file)
|
984 |
+
return str(content)
|
985 |
+
elif file.type == "text/html" or file.type == "text/htm":
|
986 |
+
content = BeautifulSoup(file, "html.parser")
|
987 |
+
return content.text
|
988 |
+
elif file.type == "application/xml" or file.type == "text/xml":
|
989 |
+
tree = ET.parse(file)
|
990 |
+
root = tree.getroot()
|
991 |
+
xml = CompressXML(ET.tostring(root, encoding='unicode'))
|
992 |
+
return xml
|
993 |
+
elif file.type == "text/markdown" or file.type == "text/md":
|
994 |
+
md = mistune.create_markdown()
|
995 |
+
content = md(file.read().decode())
|
996 |
+
return content
|
997 |
+
elif file.type == "text/plain":
|
998 |
+
return file.getvalue().decode()
|
999 |
+
else:
|
1000 |
+
return ""
|
1001 |
+
|
1002 |
+
|
1003 |
+
# 11. Chat with GPT - Caution on quota - now favoring fastest AI pipeline STT Whisper->LLM Llama->TTS
|
1004 |
+
@st.cache_resource
|
1005 |
+
def chat_with_model(prompt, document_section='', model_choice='gpt-3.5-turbo'): # gpt-4-0125-preview gpt-3.5-turbo
|
1006 |
+
#def chat_with_model(prompt, document_section='', model_choice='gpt-4-0125-preview'): # gpt-4-0125-preview gpt-3.5-turbo
|
1007 |
+
model = model_choice
|
1008 |
+
conversation = [{'role': 'system', 'content': 'You are a helpful assistant.'}]
|
1009 |
+
conversation.append({'role': 'user', 'content': prompt})
|
1010 |
+
if len(document_section)>0:
|
1011 |
+
conversation.append({'role': 'assistant', 'content': document_section})
|
1012 |
+
start_time = time.time()
|
1013 |
+
report = []
|
1014 |
+
res_box = st.empty()
|
1015 |
+
collected_chunks = []
|
1016 |
+
collected_messages = []
|
1017 |
+
|
1018 |
+
for chunk in openai.ChatCompletion.create(model=model_choice, messages=conversation, temperature=0.5, stream=True):
|
1019 |
+
collected_chunks.append(chunk)
|
1020 |
+
chunk_message = chunk['choices'][0]['delta']
|
1021 |
+
collected_messages.append(chunk_message)
|
1022 |
+
content=chunk["choices"][0].get("delta",{}).get("content")
|
1023 |
+
try:
|
1024 |
+
report.append(content)
|
1025 |
+
if len(content) > 0:
|
1026 |
+
result = "".join(report).strip()
|
1027 |
+
res_box.markdown(f'*{result}*')
|
1028 |
+
except:
|
1029 |
+
st.write(' ')
|
1030 |
+
full_reply_content = ''.join([m.get('content', '') for m in collected_messages])
|
1031 |
+
st.write("Elapsed time:")
|
1032 |
+
st.write(time.time() - start_time)
|
1033 |
+
return full_reply_content
|
1034 |
+
|
1035 |
+
@st.cache_resource
|
1036 |
+
def chat_with_file_contents(prompt, file_content, model_choice='gpt-3.5-turbo'): # gpt-4-0125-preview gpt-3.5-turbo
|
1037 |
+
#def chat_with_file_contents(prompt, file_content, model_choice='gpt-4-0125-preview'): # gpt-4-0125-preview gpt-3.5-turbo
|
1038 |
+
conversation = [{'role': 'system', 'content': 'You are a helpful assistant.'}]
|
1039 |
+
conversation.append({'role': 'user', 'content': prompt})
|
1040 |
+
if len(file_content)>0:
|
1041 |
+
conversation.append({'role': 'assistant', 'content': file_content})
|
1042 |
+
response = openai.ChatCompletion.create(model=model_choice, messages=conversation)
|
1043 |
+
return response['choices'][0]['message']['content']
|
1044 |
+
|
1045 |
+
|
1046 |
+
def extract_mime_type(file):
|
1047 |
+
if isinstance(file, str):
|
1048 |
+
pattern = r"type='(.*?)'"
|
1049 |
+
match = re.search(pattern, file)
|
1050 |
+
if match:
|
1051 |
+
return match.group(1)
|
1052 |
+
else:
|
1053 |
+
raise ValueError(f"Unable to extract MIME type from {file}")
|
1054 |
+
elif isinstance(file, streamlit.UploadedFile):
|
1055 |
+
return file.type
|
1056 |
+
else:
|
1057 |
+
raise TypeError("Input should be a string or a streamlit.UploadedFile object")
|
1058 |
+
|
1059 |
+
def extract_file_extension(file):
|
1060 |
+
# get the file name directly from the UploadedFile object
|
1061 |
+
file_name = file.name
|
1062 |
+
pattern = r".*?\.(.*?)$"
|
1063 |
+
match = re.search(pattern, file_name)
|
1064 |
+
if match:
|
1065 |
+
return match.group(1)
|
1066 |
+
else:
|
1067 |
+
raise ValueError(f"Unable to extract file extension from {file_name}")
|
1068 |
+
|
1069 |
+
# Normalize input as text from PDF and other formats
|
1070 |
+
@st.cache_resource
|
1071 |
+
def pdf2txt(docs):
|
1072 |
+
text = ""
|
1073 |
+
for file in docs:
|
1074 |
+
file_extension = extract_file_extension(file)
|
1075 |
+
st.write(f"File type extension: {file_extension}")
|
1076 |
+
if file_extension.lower() in ['py', 'txt', 'html', 'htm', 'xml', 'json']:
|
1077 |
+
text += file.getvalue().decode('utf-8')
|
1078 |
+
elif file_extension.lower() == 'pdf':
|
1079 |
+
from PyPDF2 import PdfReader
|
1080 |
+
pdf = PdfReader(BytesIO(file.getvalue()))
|
1081 |
+
for page in range(len(pdf.pages)):
|
1082 |
+
text += pdf.pages[page].extract_text() # new PyPDF2 syntax
|
1083 |
+
return text
|
1084 |
+
|
1085 |
+
def txt2chunks(text):
|
1086 |
+
text_splitter = CharacterTextSplitter(separator="\n", chunk_size=1000, chunk_overlap=200, length_function=len)
|
1087 |
+
return text_splitter.split_text(text)
|
1088 |
+
|
1089 |
+
# Vector Store using FAISS
|
1090 |
+
@st.cache_resource
|
1091 |
+
def vector_store(text_chunks):
|
1092 |
+
embeddings = OpenAIEmbeddings(openai_api_key=key)
|
1093 |
+
return FAISS.from_texts(texts=text_chunks, embedding=embeddings)
|
1094 |
+
|
1095 |
+
# Memory and Retrieval chains
|
1096 |
+
@st.cache_resource
|
1097 |
+
def get_chain(vectorstore):
|
1098 |
+
llm = ChatOpenAI()
|
1099 |
+
memory = ConversationBufferMemory(memory_key='chat_history', return_messages=True)
|
1100 |
+
return ConversationalRetrievalChain.from_llm(llm=llm, retriever=vectorstore.as_retriever(), memory=memory)
|
1101 |
+
|
1102 |
+
def process_user_input(user_question):
|
1103 |
+
response = st.session_state.conversation({'question': user_question})
|
1104 |
+
st.session_state.chat_history = response['chat_history']
|
1105 |
+
for i, message in enumerate(st.session_state.chat_history):
|
1106 |
+
template = user_template if i % 2 == 0 else bot_template
|
1107 |
+
st.write(template.replace("{{MSG}}", message.content), unsafe_allow_html=True)
|
1108 |
+
filename = generate_filename(user_question, 'txt')
|
1109 |
+
response = message.content
|
1110 |
+
user_prompt = user_question
|
1111 |
+
create_file(filename, user_prompt, response, should_save)
|
1112 |
+
|
1113 |
+
def divide_prompt(prompt, max_length):
|
1114 |
+
words = prompt.split()
|
1115 |
+
chunks = []
|
1116 |
+
current_chunk = []
|
1117 |
+
current_length = 0
|
1118 |
+
for word in words:
|
1119 |
+
if len(word) + current_length <= max_length:
|
1120 |
+
current_length += len(word) + 1
|
1121 |
+
current_chunk.append(word)
|
1122 |
+
else:
|
1123 |
+
chunks.append(' '.join(current_chunk))
|
1124 |
+
current_chunk = [word]
|
1125 |
+
current_length = len(word)
|
1126 |
+
chunks.append(' '.join(current_chunk))
|
1127 |
+
return chunks
|
1128 |
+
|
1129 |
+
|
1130 |
+
|
1131 |
+
API_URL_IE = f'https://tonpixzfvq3791u9.us-east-1.aws.endpoints.huggingface.cloud'
|
1132 |
+
API_URL_IE = "https://api-inference.huggingface.co/models/openai/whisper-small.en"
|
1133 |
+
MODEL2 = "openai/whisper-small.en"
|
1134 |
+
MODEL2_URL = "https://huggingface.co/openai/whisper-small.en"
|
1135 |
+
HF_KEY = st.secrets['HF_KEY']
|
1136 |
+
headers = {
|
1137 |
+
"Authorization": f"Bearer {HF_KEY}",
|
1138 |
+
"Content-Type": "audio/wav"
|
1139 |
+
}
|
1140 |
+
|
1141 |
+
def query(filename):
|
1142 |
+
with open(filename, "rb") as f:
|
1143 |
+
data = f.read()
|
1144 |
+
response = requests.post(API_URL_IE, headers=headers, data=data)
|
1145 |
+
return response.json()
|
1146 |
+
|
1147 |
+
def generate_filename(prompt, file_type):
|
1148 |
+
central = pytz.timezone('US/Central')
|
1149 |
+
safe_date_time = datetime.now(central).strftime("%m%d_%H%M")
|
1150 |
+
replaced_prompt = prompt.replace(" ", "_").replace("\n", "_")
|
1151 |
+
safe_prompt = "".join(x for x in replaced_prompt if x.isalnum() or x == "_")[:90]
|
1152 |
+
return f"{safe_date_time}_{safe_prompt}.{file_type}"
|
1153 |
+
|
1154 |
+
# 15. Audio recorder to Wav file
|
1155 |
+
def save_and_play_audio(audio_recorder):
|
1156 |
+
audio_bytes = audio_recorder()
|
1157 |
+
if audio_bytes:
|
1158 |
+
filename = generate_filename("Recording", "wav")
|
1159 |
+
with open(filename, 'wb') as f:
|
1160 |
+
f.write(audio_bytes)
|
1161 |
+
st.audio(audio_bytes, format="audio/wav")
|
1162 |
+
return filename
|
1163 |
+
|
1164 |
+
# 16. Speech transcription to file output
|
1165 |
+
def transcribe_audio(filename):
|
1166 |
+
output = query(filename)
|
1167 |
+
return output
|
1168 |
+
|
1169 |
+
def whisper_main():
|
1170 |
+
filename = save_and_play_audio(audio_recorder)
|
1171 |
+
if filename is not None:
|
1172 |
+
transcription = transcribe_audio(filename)
|
1173 |
+
try:
|
1174 |
+
transcript = transcription['text']
|
1175 |
+
st.write(transcript)
|
1176 |
+
|
1177 |
+
except:
|
1178 |
+
transcript=''
|
1179 |
+
st.write(transcript)
|
1180 |
+
|
1181 |
+
st.write('Reasoning with your inputs..')
|
1182 |
+
response = chat_with_model(transcript)
|
1183 |
+
st.write('Response:')
|
1184 |
+
st.write(response)
|
1185 |
+
filename = generate_filename(response, "txt")
|
1186 |
+
create_file(filename, transcript, response, should_save)
|
1187 |
+
|
1188 |
+
# Whisper to Llama:
|
1189 |
+
response = StreamLLMChatResponse(transcript)
|
1190 |
+
filename_txt = generate_filename(transcript, "md")
|
1191 |
+
create_file(filename_txt, transcript, response, should_save)
|
1192 |
+
filename_wav = filename_txt.replace('.txt', '.wav')
|
1193 |
+
import shutil
|
1194 |
+
try:
|
1195 |
+
if os.path.exists(filename):
|
1196 |
+
shutil.copyfile(filename, filename_wav)
|
1197 |
+
except:
|
1198 |
+
st.write('.')
|
1199 |
+
if os.path.exists(filename):
|
1200 |
+
os.remove(filename)
|
1201 |
+
|
1202 |
+
|
1203 |
+
|
1204 |
+
# Sample function to demonstrate a response, replace with your own logic
|
1205 |
+
def StreamMedChatResponse(topic):
|
1206 |
+
st.write(f"Showing resources or questions related to: {topic}")
|
1207 |
+
|
1208 |
+
|
1209 |
+
|
1210 |
+
# 17. Main
|
1211 |
+
def main():
|
1212 |
+
prompt = PromptPrefix2
|
1213 |
+
with st.expander("Prompts 📚", expanded=False):
|
1214 |
+
example_input = st.text_input("Enter your prompt text:", value=prompt, help="Enter text to get a response.")
|
1215 |
+
if st.button("Run Prompt", help="Click to run."):
|
1216 |
+
try:
|
1217 |
+
response=StreamLLMChatResponse(example_input)
|
1218 |
+
create_file(filename, example_input, response, should_save)
|
1219 |
+
except:
|
1220 |
+
st.write('model is asleep. Starting now on A10 GPU. Please wait one minute then retry. KEDA triggered.')
|
1221 |
+
openai.api_key = os.getenv('OPENAI_API_KEY')
|
1222 |
+
if openai.api_key == None: openai.api_key = st.secrets['OPENAI_API_KEY']
|
1223 |
+
menu = ["txt", "htm", "xlsx", "csv", "md", "py"]
|
1224 |
+
choice = st.sidebar.selectbox("Output File Type:", menu)
|
1225 |
+
model_choice = st.sidebar.radio("Select Model:", ('gpt-3.5-turbo', 'gpt-3.5-turbo-0301'))
|
1226 |
+
user_prompt = st.text_area("Enter prompts, instructions & questions:", '', height=100)
|
1227 |
+
collength, colupload = st.columns([2,3]) # adjust the ratio as needed
|
1228 |
+
with collength:
|
1229 |
+
max_length = st.slider("File section length for large files", min_value=1000, max_value=128000, value=12000, step=1000)
|
1230 |
+
with colupload:
|
1231 |
+
uploaded_file = st.file_uploader("Add a file for context:", type=["pdf", "xml", "json", "xlsx", "csv", "html", "htm", "md", "txt"])
|
1232 |
+
document_sections = deque()
|
1233 |
+
document_responses = {}
|
1234 |
+
if uploaded_file is not None:
|
1235 |
+
file_content = read_file_content(uploaded_file, max_length)
|
1236 |
+
document_sections.extend(divide_document(file_content, max_length))
|
1237 |
+
if len(document_sections) > 0:
|
1238 |
+
if st.button("👁️ View Upload"):
|
1239 |
+
st.markdown("**Sections of the uploaded file:**")
|
1240 |
+
for i, section in enumerate(list(document_sections)):
|
1241 |
+
st.markdown(f"**Section {i+1}**\n{section}")
|
1242 |
+
st.markdown("**Chat with the model:**")
|
1243 |
+
for i, section in enumerate(list(document_sections)):
|
1244 |
+
if i in document_responses:
|
1245 |
+
st.markdown(f"**Section {i+1}**\n{document_responses[i]}")
|
1246 |
+
else:
|
1247 |
+
if st.button(f"Chat about Section {i+1}"):
|
1248 |
+
st.write('Reasoning with your inputs...')
|
1249 |
+
#response = chat_with_model(user_prompt, section, model_choice)
|
1250 |
+
st.write('Response:')
|
1251 |
+
st.write(response)
|
1252 |
+
document_responses[i] = response
|
1253 |
+
filename = generate_filename(f"{user_prompt}_section_{i+1}", choice)
|
1254 |
+
create_file(filename, user_prompt, response, should_save)
|
1255 |
+
st.sidebar.markdown(get_table_download_link(filename), unsafe_allow_html=True)
|
1256 |
+
if st.button('💬 Chat'):
|
1257 |
+
st.write('Reasoning with your inputs...')
|
1258 |
+
user_prompt_sections = divide_prompt(user_prompt, max_length)
|
1259 |
+
full_response = ''
|
1260 |
+
for prompt_section in user_prompt_sections:
|
1261 |
+
response = chat_with_model(prompt_section, ''.join(list(document_sections)), model_choice)
|
1262 |
+
full_response += response + '\n' # Combine the responses
|
1263 |
+
response = full_response
|
1264 |
+
st.write('Response:')
|
1265 |
+
st.write(response)
|
1266 |
+
filename = generate_filename(user_prompt, choice)
|
1267 |
+
create_file(filename, user_prompt, response, should_save)
|
1268 |
+
|
1269 |
+
|
1270 |
+
# Function to encode file to base64
|
1271 |
+
def get_base64_encoded_file(file_path):
|
1272 |
+
with open(file_path, "rb") as file:
|
1273 |
+
return base64.b64encode(file.read()).decode()
|
1274 |
+
|
1275 |
+
# Function to create a download link
|
1276 |
+
def get_audio_download_link(file_path):
|
1277 |
+
base64_file = get_base64_encoded_file(file_path)
|
1278 |
+
return f'<a href="data:file/wav;base64,{base64_file}" download="{os.path.basename(file_path)}">⬇️ Download Audio</a>'
|
1279 |
+
|
1280 |
+
# Compose a file sidebar of past encounters
|
1281 |
+
all_files = glob.glob("*.wav")
|
1282 |
+
all_files = [file for file in all_files if len(os.path.splitext(file)[0]) >= 10] # exclude files with short names
|
1283 |
+
all_files.sort(key=lambda x: (os.path.splitext(x)[1], x), reverse=True) # sort by file type and file name in descending order
|
1284 |
+
|
1285 |
+
filekey = 'delall'
|
1286 |
+
if st.sidebar.button("🗑 Delete All Audio", key=filekey):
|
1287 |
+
for file in all_files:
|
1288 |
+
os.remove(file)
|
1289 |
+
st.experimental_rerun()
|
1290 |
+
|
1291 |
+
for file in all_files:
|
1292 |
+
col1, col2 = st.sidebar.columns([6, 1]) # adjust the ratio as needed
|
1293 |
+
with col1:
|
1294 |
+
st.markdown(file)
|
1295 |
+
if st.button("🎵", key="play_" + file): # play emoji button
|
1296 |
+
audio_file = open(file, 'rb')
|
1297 |
+
audio_bytes = audio_file.read()
|
1298 |
+
st.audio(audio_bytes, format='audio/wav')
|
1299 |
+
#st.markdown(get_audio_download_link(file), unsafe_allow_html=True)
|
1300 |
+
#st.text_input(label="", value=file)
|
1301 |
+
with col2:
|
1302 |
+
if st.button("🗑", key="delete_" + file):
|
1303 |
+
os.remove(file)
|
1304 |
+
st.experimental_rerun()
|
1305 |
+
|
1306 |
+
|
1307 |
+
|
1308 |
+
GiveFeedback=False
|
1309 |
+
if GiveFeedback:
|
1310 |
+
with st.expander("Give your feedback 👍", expanded=False):
|
1311 |
+
feedback = st.radio("Step 8: Give your feedback", ("👍 Upvote", "👎 Downvote"))
|
1312 |
+
if feedback == "👍 Upvote":
|
1313 |
+
st.write("You upvoted 👍. Thank you for your feedback!")
|
1314 |
+
else:
|
1315 |
+
st.write("You downvoted 👎. Thank you for your feedback!")
|
1316 |
+
load_dotenv()
|
1317 |
+
st.write(css, unsafe_allow_html=True)
|
1318 |
+
st.header("Chat with documents :books:")
|
1319 |
+
user_question = st.text_input("Ask a question about your documents:")
|
1320 |
+
if user_question:
|
1321 |
+
process_user_input(user_question)
|
1322 |
+
with st.sidebar:
|
1323 |
+
st.subheader("Your documents")
|
1324 |
+
docs = st.file_uploader("import documents", accept_multiple_files=True)
|
1325 |
+
with st.spinner("Processing"):
|
1326 |
+
raw = pdf2txt(docs)
|
1327 |
+
if len(raw) > 0:
|
1328 |
+
length = str(len(raw))
|
1329 |
+
text_chunks = txt2chunks(raw)
|
1330 |
+
vectorstore = vector_store(text_chunks)
|
1331 |
+
st.session_state.conversation = get_chain(vectorstore)
|
1332 |
+
st.markdown('# AI Search Index of Length:' + length + ' Created.') # add timing
|
1333 |
+
filename = generate_filename(raw, 'txt')
|
1334 |
+
create_file(filename, raw, '', should_save)
|
1335 |
+
|
1336 |
+
|
1337 |
+
try:
|
1338 |
+
query_params = st.query_params
|
1339 |
+
query = (query_params.get('q') or query_params.get('query') or [''])
|
1340 |
+
if query: search_glossary(query)
|
1341 |
+
except:
|
1342 |
+
st.markdown(' ')
|
1343 |
+
|
1344 |
+
# Display the glossary grid
|
1345 |
+
st.markdown("### 🎲🗺️ Word Game Gallery")
|
1346 |
+
|
1347 |
+
display_glossary_grid(roleplaying_glossary) # Word Glossary Jump Grid
|
1348 |
+
display_buttons_with_scores() # Feedback Jump Grid
|
1349 |
+
display_videos_and_links() # Video Jump Grid
|
1350 |
+
display_images_and_wikipedia_summaries() # Image Jump Grid
|
1351 |
+
|
1352 |
+
|
1353 |
+
if 'action' in st.query_params:
|
1354 |
+
action = st.query_params()['action'][0] # Get the first (or only) 'action' parameter
|
1355 |
+
if action == 'show_message':
|
1356 |
+
st.success("Showing a message because 'action=show_message' was found in the URL.")
|
1357 |
+
elif action == 'clear':
|
1358 |
+
clear_query_params()
|
1359 |
+
st.experimental_rerun()
|
1360 |
+
|
1361 |
+
# Handling repeated keys
|
1362 |
+
if 'multi' in st.query_params:
|
1363 |
+
multi_values = get_all_query_params('multi')
|
1364 |
+
st.write("Values for 'multi':", multi_values)
|
1365 |
+
|
1366 |
+
# Manual entry for demonstration
|
1367 |
+
st.write("Enter query parameters in the URL like this: ?action=show_message&multi=1&multi=2")
|
1368 |
+
|
1369 |
+
if 'query' in st.query_params:
|
1370 |
+
query = st.query_params['query'][0] # Get the query parameter
|
1371 |
+
# Display content or image based on the query
|
1372 |
+
display_content_or_image(query)
|
1373 |
+
|
1374 |
+
# Add a clear query parameters button for convenience
|
1375 |
+
if st.button("Clear Query Parameters", key='ClearQueryParams'):
|
1376 |
+
# This will clear the browser URL's query parameters
|
1377 |
+
st.experimental_set_query_params
|
1378 |
+
st.experimental_rerun()
|
1379 |
+
|
1380 |
+
# 18. Run AI Pipeline
|
1381 |
if __name__ == "__main__":
|
1382 |
+
whisper_main()
|
1383 |
main()
|
1384 |
|
1385 |
|
|
|
1387 |
|
1388 |
|
1389 |
|
1390 |
+
|
1391 |
+
|