awacke1 commited on
Commit
c72a4af
·
verified ·
1 Parent(s): e98f617

Create app.py

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