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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Imports
|
| 2 |
+
import base64
|
| 3 |
+
import glob
|
| 4 |
+
import json
|
| 5 |
+
import math
|
| 6 |
+
#import mistune
|
| 7 |
+
import openai
|
| 8 |
+
import os
|
| 9 |
+
import pytz
|
| 10 |
+
import re
|
| 11 |
+
import requests
|
| 12 |
+
import streamlit as st
|
| 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 langchain.chat_models import ChatOpenAI
|
| 26 |
+
from langchain.chains import ConversationalRetrievalChain
|
| 27 |
+
from langchain.embeddings import OpenAIEmbeddings
|
| 28 |
+
from langchain.memory import ConversationBufferMemory
|
| 29 |
+
from langchain.text_splitter import CharacterTextSplitter
|
| 30 |
+
from langchain.vectorstores import FAISS
|
| 31 |
+
from openai import ChatCompletion
|
| 32 |
+
from PyPDF2 import PdfReader
|
| 33 |
+
from templates import bot_template, css, user_template
|
| 34 |
+
from xml.etree import ElementTree as ET
|
| 35 |
+
|
| 36 |
+
def add_Med_Licensing_Exam_Dataset():
|
| 37 |
+
import streamlit as st
|
| 38 |
+
from datasets import load_dataset
|
| 39 |
+
dataset = load_dataset("augtoma/usmle_step_1")['test'] # Using 'test' split
|
| 40 |
+
st.title("USMLE Step 1 Dataset Viewer")
|
| 41 |
+
if len(dataset) == 0:
|
| 42 |
+
st.write("π’ The dataset is empty.")
|
| 43 |
+
else:
|
| 44 |
+
st.write("""
|
| 45 |
+
π Use the search box to filter questions or use the grid to scroll through the dataset.
|
| 46 |
+
""")
|
| 47 |
+
|
| 48 |
+
# π©βπ¬ Search Box
|
| 49 |
+
search_term = st.text_input("Search for a specific question:", "")
|
| 50 |
+
# π Pagination
|
| 51 |
+
records_per_page = 100
|
| 52 |
+
num_records = len(dataset)
|
| 53 |
+
num_pages = max(int(num_records / records_per_page), 1)
|
| 54 |
+
|
| 55 |
+
# Skip generating the slider if num_pages is 1 (i.e., all records fit in one page)
|
| 56 |
+
if num_pages > 1:
|
| 57 |
+
page_number = st.select_slider("Select page:", options=list(range(1, num_pages + 1)))
|
| 58 |
+
else:
|
| 59 |
+
page_number = 1 # Only one page
|
| 60 |
+
|
| 61 |
+
# π Display Data
|
| 62 |
+
start_idx = (page_number - 1) * records_per_page
|
| 63 |
+
end_idx = start_idx + records_per_page
|
| 64 |
+
|
| 65 |
+
# π§ͺ Apply the Search Filter
|
| 66 |
+
filtered_data = []
|
| 67 |
+
for record in dataset[start_idx:end_idx]:
|
| 68 |
+
if isinstance(record, dict) and 'text' in record and 'id' in record:
|
| 69 |
+
if search_term:
|
| 70 |
+
if search_term.lower() in record['text'].lower():
|
| 71 |
+
filtered_data.append(record)
|
| 72 |
+
else:
|
| 73 |
+
filtered_data.append(record)
|
| 74 |
+
|
| 75 |
+
# π Render the Grid
|
| 76 |
+
for record in filtered_data:
|
| 77 |
+
st.write(f"## Question ID: {record['id']}")
|
| 78 |
+
st.write(f"### Question:")
|
| 79 |
+
st.write(f"{record['text']}")
|
| 80 |
+
st.write(f"### Answer:")
|
| 81 |
+
st.write(f"{record['answer']}")
|
| 82 |
+
st.write("---")
|
| 83 |
+
|
| 84 |
+
st.write(f"π Total Records: {num_records} | π Displaying {start_idx+1} to {min(end_idx, num_records)}")
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
# 1. Constants and Top Level UI Variables
|
| 89 |
+
|
| 90 |
+
# My Inference API Copy
|
| 91 |
+
# API_URL = 'https://qe55p8afio98s0u3.us-east-1.aws.endpoints.huggingface.cloud' # Dr Llama
|
| 92 |
+
# Original:
|
| 93 |
+
API_URL = "https://api-inference.huggingface.co/models/meta-llama/Llama-2-7b-chat-hf"
|
| 94 |
+
API_KEY = os.getenv('API_KEY')
|
| 95 |
+
MODEL1="meta-llama/Llama-2-7b-chat-hf"
|
| 96 |
+
MODEL1URL="https://huggingface.co/meta-llama/Llama-2-7b-chat-hf"
|
| 97 |
+
HF_KEY = os.getenv('HF_KEY')
|
| 98 |
+
headers = {
|
| 99 |
+
"Authorization": f"Bearer {HF_KEY}",
|
| 100 |
+
"Content-Type": "application/json"
|
| 101 |
+
}
|
| 102 |
+
key = os.getenv('OPENAI_API_KEY')
|
| 103 |
+
prompt = f"Write instructions to teach anyone to write a discharge plan. List the entities, features and relationships to CCDA and FHIR objects in boldface."
|
| 104 |
+
# page config and sidebar declares up front allow all other functions to see global class variables
|
| 105 |
+
# st.set_page_config(page_title="GPT Streamlit Document Reasoner", layout="wide")
|
| 106 |
+
should_save = st.sidebar.checkbox("πΎ Save", value=True, help="Save your session data.")
|
| 107 |
+
|
| 108 |
+
# 2. Prompt label button demo for LLM
|
| 109 |
+
def add_witty_humor_buttons():
|
| 110 |
+
with st.expander("Wit and Humor π€£", expanded=True):
|
| 111 |
+
# Tip about the Dromedary family
|
| 112 |
+
st.markdown("π¬ **Fun Fact**: Dromedaries, part of the camel family, have a single hump and are adapted to arid environments. Their 'superpowers' include the ability to survive without water for up to 7 days, thanks to their specialized blood cells and water storage in their hump.")
|
| 113 |
+
|
| 114 |
+
# Define button descriptions
|
| 115 |
+
descriptions = {
|
| 116 |
+
"Generate Limericks π": "Write ten random adult limericks based on quotes that are tweet length and make you laugh π",
|
| 117 |
+
"Wise Quotes π§": "Generate ten wise quotes that are tweet length π¦",
|
| 118 |
+
"Funny Rhymes π€": "Create ten funny rhymes that are tweet length πΆ",
|
| 119 |
+
"Medical Jokes π": "Create ten medical jokes that are tweet length π₯",
|
| 120 |
+
"Minnesota Humor βοΈ": "Create ten jokes about Minnesota that are tweet length π¨οΈ",
|
| 121 |
+
"Top Funny Stories π": "Create ten funny stories that are tweet length π",
|
| 122 |
+
"More Funny Rhymes ποΈ": "Create ten more funny rhymes that are tweet length π΅"
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
# Create columns
|
| 126 |
+
col1, col2, col3 = st.columns([1, 1, 1], gap="small")
|
| 127 |
+
|
| 128 |
+
# Add buttons to columns
|
| 129 |
+
if col1.button("Generate Limericks π"):
|
| 130 |
+
StreamLLMChatResponse(descriptions["Generate Limericks π"])
|
| 131 |
+
|
| 132 |
+
if col2.button("Wise Quotes π§"):
|
| 133 |
+
StreamLLMChatResponse(descriptions["Wise Quotes π§"])
|
| 134 |
+
|
| 135 |
+
if col3.button("Funny Rhymes π€"):
|
| 136 |
+
StreamLLMChatResponse(descriptions["Funny Rhymes π€"])
|
| 137 |
+
|
| 138 |
+
col4, col5, col6 = st.columns([1, 1, 1], gap="small")
|
| 139 |
+
|
| 140 |
+
if col4.button("Medical Jokes π"):
|
| 141 |
+
StreamLLMChatResponse(descriptions["Medical Jokes π"])
|
| 142 |
+
|
| 143 |
+
if col5.button("Minnesota Humor βοΈ"):
|
| 144 |
+
StreamLLMChatResponse(descriptions["Minnesota Humor βοΈ"])
|
| 145 |
+
|
| 146 |
+
if col6.button("Top Funny Stories π"):
|
| 147 |
+
StreamLLMChatResponse(descriptions["Top Funny Stories π"])
|
| 148 |
+
|
| 149 |
+
col7 = st.columns(1, gap="small")
|
| 150 |
+
|
| 151 |
+
if col7[0].button("More Funny Rhymes ποΈ"):
|
| 152 |
+
StreamLLMChatResponse(descriptions["More Funny Rhymes ποΈ"])
|
| 153 |
+
|
| 154 |
+
def addDocumentHTML5(result):
|
| 155 |
+
documentHTML5='''
|
| 156 |
+
<!DOCTYPE html>
|
| 157 |
+
<html>
|
| 158 |
+
<head>
|
| 159 |
+
<title>Read It Aloud</title>
|
| 160 |
+
<script type="text/javascript">
|
| 161 |
+
function readAloud() {
|
| 162 |
+
const text = document.getElementById("textArea").value;
|
| 163 |
+
const speech = new SpeechSynthesisUtterance(text);
|
| 164 |
+
window.speechSynthesis.speak(speech);
|
| 165 |
+
}
|
| 166 |
+
</script>
|
| 167 |
+
</head>
|
| 168 |
+
<body>
|
| 169 |
+
<h1>π Read It Aloud</h1>
|
| 170 |
+
<textarea id="textArea" rows="10" cols="80">
|
| 171 |
+
'''
|
| 172 |
+
documentHTML5 = documentHTML5 + result
|
| 173 |
+
documentHTML5 = documentHTML5 + '''
|
| 174 |
+
</textarea>
|
| 175 |
+
<br>
|
| 176 |
+
<button onclick="readAloud()">π Read Aloud</button>
|
| 177 |
+
</body>
|
| 178 |
+
</html>
|
| 179 |
+
'''
|
| 180 |
+
|
| 181 |
+
import streamlit.components.v1 as components # Import Streamlit
|
| 182 |
+
components.html(documentHTML5, width=1280, height=1024)
|
| 183 |
+
return result
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
# 3. Stream Llama Response
|
| 187 |
+
# @st.cache_resource
|
| 188 |
+
def StreamLLMChatResponse(prompt):
|
| 189 |
+
|
| 190 |
+
try:
|
| 191 |
+
endpoint_url = API_URL
|
| 192 |
+
hf_token = API_KEY
|
| 193 |
+
client = InferenceClient(endpoint_url, token=hf_token)
|
| 194 |
+
gen_kwargs = dict(
|
| 195 |
+
max_new_tokens=512,
|
| 196 |
+
top_k=30,
|
| 197 |
+
top_p=0.9,
|
| 198 |
+
temperature=0.2,
|
| 199 |
+
repetition_penalty=1.02,
|
| 200 |
+
stop_sequences=["\nUser:", "<|endoftext|>", "</s>"],
|
| 201 |
+
)
|
| 202 |
+
stream = client.text_generation(prompt, stream=True, details=True, **gen_kwargs)
|
| 203 |
+
report=[]
|
| 204 |
+
res_box = st.empty()
|
| 205 |
+
collected_chunks=[]
|
| 206 |
+
collected_messages=[]
|
| 207 |
+
allresults=''
|
| 208 |
+
for r in stream:
|
| 209 |
+
if r.token.special:
|
| 210 |
+
continue
|
| 211 |
+
if r.token.text in gen_kwargs["stop_sequences"]:
|
| 212 |
+
break
|
| 213 |
+
collected_chunks.append(r.token.text)
|
| 214 |
+
chunk_message = r.token.text
|
| 215 |
+
collected_messages.append(chunk_message)
|
| 216 |
+
try:
|
| 217 |
+
report.append(r.token.text)
|
| 218 |
+
if len(r.token.text) > 0:
|
| 219 |
+
result="".join(report).strip()
|
| 220 |
+
res_box.markdown(f'*{result}*')
|
| 221 |
+
|
| 222 |
+
except:
|
| 223 |
+
st.write('Stream llm issue')
|
| 224 |
+
add_documentHTML5(result)
|
| 225 |
+
except:
|
| 226 |
+
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).')
|
| 227 |
+
|
| 228 |
+
# 4. Run query with payload
|
| 229 |
+
def query(payload):
|
| 230 |
+
response = requests.post(API_URL, headers=headers, json=payload)
|
| 231 |
+
st.markdown(response.json())
|
| 232 |
+
return response.json()
|
| 233 |
+
def get_output(prompt):
|
| 234 |
+
return query({"inputs": prompt})
|
| 235 |
+
|
| 236 |
+
# 5. Auto name generated output files from time and content
|
| 237 |
+
def generate_filename(prompt, file_type):
|
| 238 |
+
central = pytz.timezone('US/Central')
|
| 239 |
+
safe_date_time = datetime.now(central).strftime("%m%d_%H%M")
|
| 240 |
+
replaced_prompt = prompt.replace(" ", "_").replace("\n", "_")
|
| 241 |
+
safe_prompt = "".join(x for x in replaced_prompt if x.isalnum() or x == "_")[:45]
|
| 242 |
+
return f"{safe_date_time}_{safe_prompt}.{file_type}"
|
| 243 |
+
|
| 244 |
+
# 6. Speech transcription via OpenAI service
|
| 245 |
+
def transcribe_audio(openai_key, file_path, model):
|
| 246 |
+
openai.api_key = openai_key
|
| 247 |
+
OPENAI_API_URL = "https://api.openai.com/v1/audio/transcriptions"
|
| 248 |
+
headers = {
|
| 249 |
+
"Authorization": f"Bearer {openai_key}",
|
| 250 |
+
}
|
| 251 |
+
with open(file_path, 'rb') as f:
|
| 252 |
+
data = {'file': f}
|
| 253 |
+
response = requests.post(OPENAI_API_URL, headers=headers, files=data, data={'model': model})
|
| 254 |
+
if response.status_code == 200:
|
| 255 |
+
st.write(response.json())
|
| 256 |
+
chatResponse = chat_with_model(response.json().get('text'), '') # *************************************
|
| 257 |
+
transcript = response.json().get('text')
|
| 258 |
+
filename = generate_filename(transcript, 'txt')
|
| 259 |
+
response = chatResponse
|
| 260 |
+
user_prompt = transcript
|
| 261 |
+
create_file(filename, user_prompt, response, should_save)
|
| 262 |
+
return transcript
|
| 263 |
+
else:
|
| 264 |
+
st.write(response.json())
|
| 265 |
+
st.error("Error in API call.")
|
| 266 |
+
return None
|
| 267 |
+
|
| 268 |
+
# 7. Auto stop on silence audio control for recording WAV files
|
| 269 |
+
def save_and_play_audio(audio_recorder):
|
| 270 |
+
audio_bytes = audio_recorder(key='audio_recorder')
|
| 271 |
+
if audio_bytes:
|
| 272 |
+
filename = generate_filename("Recording", "wav")
|
| 273 |
+
with open(filename, 'wb') as f:
|
| 274 |
+
f.write(audio_bytes)
|
| 275 |
+
st.audio(audio_bytes, format="audio/wav")
|
| 276 |
+
return filename
|
| 277 |
+
return None
|
| 278 |
+
|
| 279 |
+
# 8. File creator that interprets type and creates output file for text, markdown and code
|
| 280 |
+
def create_file(filename, prompt, response, should_save=True):
|
| 281 |
+
if not should_save:
|
| 282 |
+
return
|
| 283 |
+
base_filename, ext = os.path.splitext(filename)
|
| 284 |
+
has_python_code = bool(re.search(r"```python([\s\S]*?)```", response))
|
| 285 |
+
if ext in ['.txt', '.htm', '.md']:
|
| 286 |
+
with open(f"{base_filename}.md", 'w') as file:
|
| 287 |
+
content = prompt.strip() + '\r\n' + response
|
| 288 |
+
file.write(content)
|
| 289 |
+
if has_python_code:
|
| 290 |
+
python_code = re.findall(r"```python([\s\S]*?)```", response)[0].strip()
|
| 291 |
+
with open(f"{base_filename}-Code.py", 'w') as file:
|
| 292 |
+
file.write(python_code)
|
| 293 |
+
with open(f"{base_filename}.md", 'w') as file:
|
| 294 |
+
content = prompt.strip() + '\r\n' + response
|
| 295 |
+
file.write(content)
|
| 296 |
+
|
| 297 |
+
def truncate_document(document, length):
|
| 298 |
+
return document[:length]
|
| 299 |
+
def divide_document(document, max_length):
|
| 300 |
+
return [document[i:i+max_length] for i in range(0, len(document), max_length)]
|
| 301 |
+
|
| 302 |
+
# 9. Sidebar with UI controls to review and re-run prompts and continue responses
|
| 303 |
+
@st.cache_resource
|
| 304 |
+
def get_table_download_link(file_path):
|
| 305 |
+
with open(file_path, 'r') as file:
|
| 306 |
+
data = file.read()
|
| 307 |
+
|
| 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 |
+
else:
|
| 324 |
+
mime_type = 'application/octet-stream' # general binary data type
|
| 325 |
+
href = f'<a href="data:{mime_type};base64,{b64}" target="_blank" download="{file_name}">{file_name}</a>'
|
| 326 |
+
return href
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
def CompressXML(xml_text):
|
| 330 |
+
root = ET.fromstring(xml_text)
|
| 331 |
+
for elem in list(root.iter()):
|
| 332 |
+
if isinstance(elem.tag, str) and 'Comment' in elem.tag:
|
| 333 |
+
elem.parent.remove(elem)
|
| 334 |
+
return ET.tostring(root, encoding='unicode', method="xml")
|
| 335 |
+
|
| 336 |
+
# 10. Read in and provide UI for past files
|
| 337 |
+
@st.cache_resource
|
| 338 |
+
def read_file_content(file,max_length):
|
| 339 |
+
if file.type == "application/json":
|
| 340 |
+
content = json.load(file)
|
| 341 |
+
return str(content)
|
| 342 |
+
elif file.type == "text/html" or file.type == "text/htm":
|
| 343 |
+
content = BeautifulSoup(file, "html.parser")
|
| 344 |
+
return content.text
|
| 345 |
+
elif file.type == "application/xml" or file.type == "text/xml":
|
| 346 |
+
tree = ET.parse(file)
|
| 347 |
+
root = tree.getroot()
|
| 348 |
+
xml = CompressXML(ET.tostring(root, encoding='unicode'))
|
| 349 |
+
return xml
|
| 350 |
+
elif file.type == "text/markdown" or file.type == "text/md":
|
| 351 |
+
md = mistune.create_markdown()
|
| 352 |
+
content = md(file.read().decode())
|
| 353 |
+
return content
|
| 354 |
+
elif file.type == "text/plain":
|
| 355 |
+
return file.getvalue().decode()
|
| 356 |
+
else:
|
| 357 |
+
return ""
|
| 358 |
+
|
| 359 |
+
# 11. Chat with GPT - Caution on quota - now favoring fastest AI pipeline STT Whisper->LLM Llama->TTS
|
| 360 |
+
@st.cache_resource
|
| 361 |
+
def chat_with_model(prompt, document_section, model_choice='gpt-3.5-turbo'):
|
| 362 |
+
model = model_choice
|
| 363 |
+
conversation = [{'role': 'system', 'content': 'You are a helpful assistant.'}]
|
| 364 |
+
conversation.append({'role': 'user', 'content': prompt})
|
| 365 |
+
if len(document_section)>0:
|
| 366 |
+
conversation.append({'role': 'assistant', 'content': document_section})
|
| 367 |
+
start_time = time.time()
|
| 368 |
+
report = []
|
| 369 |
+
res_box = st.empty()
|
| 370 |
+
collected_chunks = []
|
| 371 |
+
collected_messages = []
|
| 372 |
+
for chunk in openai.ChatCompletion.create(model='gpt-3.5-turbo', messages=conversation, temperature=0.5, stream=True):
|
| 373 |
+
collected_chunks.append(chunk)
|
| 374 |
+
chunk_message = chunk['choices'][0]['delta']
|
| 375 |
+
collected_messages.append(chunk_message)
|
| 376 |
+
content=chunk["choices"][0].get("delta",{}).get("content")
|
| 377 |
+
try:
|
| 378 |
+
report.append(content)
|
| 379 |
+
if len(content) > 0:
|
| 380 |
+
result = "".join(report).strip()
|
| 381 |
+
res_box.markdown(f'*{result}*')
|
| 382 |
+
except:
|
| 383 |
+
st.write(' ')
|
| 384 |
+
full_reply_content = ''.join([m.get('content', '') for m in collected_messages])
|
| 385 |
+
st.write("Elapsed time:")
|
| 386 |
+
st.write(time.time() - start_time)
|
| 387 |
+
return full_reply_content
|
| 388 |
+
|
| 389 |
+
# 12. Embedding VectorDB for LLM query of documents to text to compress inputs and prompt together as Chat memory using Langchain
|
| 390 |
+
@st.cache_resource
|
| 391 |
+
def chat_with_file_contents(prompt, file_content, model_choice='gpt-3.5-turbo'):
|
| 392 |
+
conversation = [{'role': 'system', 'content': 'You are a helpful assistant.'}]
|
| 393 |
+
conversation.append({'role': 'user', 'content': prompt})
|
| 394 |
+
if len(file_content)>0:
|
| 395 |
+
conversation.append({'role': 'assistant', 'content': file_content})
|
| 396 |
+
response = openai.ChatCompletion.create(model=model_choice, messages=conversation)
|
| 397 |
+
return response['choices'][0]['message']['content']
|
| 398 |
+
|
| 399 |
+
def extract_mime_type(file):
|
| 400 |
+
if isinstance(file, str):
|
| 401 |
+
pattern = r"type='(.*?)'"
|
| 402 |
+
match = re.search(pattern, file)
|
| 403 |
+
if match:
|
| 404 |
+
return match.group(1)
|
| 405 |
+
else:
|
| 406 |
+
raise ValueError(f"Unable to extract MIME type from {file}")
|
| 407 |
+
elif isinstance(file, streamlit.UploadedFile):
|
| 408 |
+
return file.type
|
| 409 |
+
else:
|
| 410 |
+
raise TypeError("Input should be a string or a streamlit.UploadedFile object")
|
| 411 |
+
|
| 412 |
+
def extract_file_extension(file):
|
| 413 |
+
# get the file name directly from the UploadedFile object
|
| 414 |
+
file_name = file.name
|
| 415 |
+
pattern = r".*?\.(.*?)$"
|
| 416 |
+
match = re.search(pattern, file_name)
|
| 417 |
+
if match:
|
| 418 |
+
return match.group(1)
|
| 419 |
+
else:
|
| 420 |
+
raise ValueError(f"Unable to extract file extension from {file_name}")
|
| 421 |
+
|
| 422 |
+
# Normalize input as text from PDF and other formats
|
| 423 |
+
@st.cache_resource
|
| 424 |
+
def pdf2txt(docs):
|
| 425 |
+
text = ""
|
| 426 |
+
for file in docs:
|
| 427 |
+
file_extension = extract_file_extension(file)
|
| 428 |
+
st.write(f"File type extension: {file_extension}")
|
| 429 |
+
if file_extension.lower() in ['py', 'txt', 'html', 'htm', 'xml', 'json']:
|
| 430 |
+
text += file.getvalue().decode('utf-8')
|
| 431 |
+
elif file_extension.lower() == 'pdf':
|
| 432 |
+
from PyPDF2 import PdfReader
|
| 433 |
+
pdf = PdfReader(BytesIO(file.getvalue()))
|
| 434 |
+
for page in range(len(pdf.pages)):
|
| 435 |
+
text += pdf.pages[page].extract_text() # new PyPDF2 syntax
|
| 436 |
+
return text
|
| 437 |
+
|
| 438 |
+
def txt2chunks(text):
|
| 439 |
+
text_splitter = CharacterTextSplitter(separator="\n", chunk_size=1000, chunk_overlap=200, length_function=len)
|
| 440 |
+
return text_splitter.split_text(text)
|
| 441 |
+
|
| 442 |
+
# Vector Store using FAISS
|
| 443 |
+
@st.cache_resource
|
| 444 |
+
def vector_store(text_chunks):
|
| 445 |
+
embeddings = OpenAIEmbeddings(openai_api_key=key)
|
| 446 |
+
return FAISS.from_texts(texts=text_chunks, embedding=embeddings)
|
| 447 |
+
|
| 448 |
+
# Memory and Retrieval chains
|
| 449 |
+
@st.cache_resource
|
| 450 |
+
def get_chain(vectorstore):
|
| 451 |
+
llm = ChatOpenAI()
|
| 452 |
+
memory = ConversationBufferMemory(memory_key='chat_history', return_messages=True)
|
| 453 |
+
return ConversationalRetrievalChain.from_llm(llm=llm, retriever=vectorstore.as_retriever(), memory=memory)
|
| 454 |
+
|
| 455 |
+
def process_user_input(user_question):
|
| 456 |
+
response = st.session_state.conversation({'question': user_question})
|
| 457 |
+
st.session_state.chat_history = response['chat_history']
|
| 458 |
+
for i, message in enumerate(st.session_state.chat_history):
|
| 459 |
+
template = user_template if i % 2 == 0 else bot_template
|
| 460 |
+
st.write(template.replace("{{MSG}}", message.content), unsafe_allow_html=True)
|
| 461 |
+
filename = generate_filename(user_question, 'txt')
|
| 462 |
+
response = message.content
|
| 463 |
+
user_prompt = user_question
|
| 464 |
+
create_file(filename, user_prompt, response, should_save)
|
| 465 |
+
|
| 466 |
+
def divide_prompt(prompt, max_length):
|
| 467 |
+
words = prompt.split()
|
| 468 |
+
chunks = []
|
| 469 |
+
current_chunk = []
|
| 470 |
+
current_length = 0
|
| 471 |
+
for word in words:
|
| 472 |
+
if len(word) + current_length <= max_length:
|
| 473 |
+
current_length += len(word) + 1
|
| 474 |
+
current_chunk.append(word)
|
| 475 |
+
else:
|
| 476 |
+
chunks.append(' '.join(current_chunk))
|
| 477 |
+
current_chunk = [word]
|
| 478 |
+
current_length = len(word)
|
| 479 |
+
chunks.append(' '.join(current_chunk))
|
| 480 |
+
return chunks
|
| 481 |
+
|
| 482 |
+
|
| 483 |
+
# 13. Provide way of saving all and deleting all to give way of reviewing output and saving locally before clearing it
|
| 484 |
+
|
| 485 |
+
@st.cache_resource
|
| 486 |
+
def create_zip_of_files(files):
|
| 487 |
+
zip_name = "all_files.zip"
|
| 488 |
+
with zipfile.ZipFile(zip_name, 'w') as zipf:
|
| 489 |
+
for file in files:
|
| 490 |
+
zipf.write(file)
|
| 491 |
+
return zip_name
|
| 492 |
+
|
| 493 |
+
@st.cache_resource
|
| 494 |
+
def get_zip_download_link(zip_file):
|
| 495 |
+
with open(zip_file, 'rb') as f:
|
| 496 |
+
data = f.read()
|
| 497 |
+
b64 = base64.b64encode(data).decode()
|
| 498 |
+
href = f'<a href="data:application/zip;base64,{b64}" download="{zip_file}">Download All</a>'
|
| 499 |
+
return href
|
| 500 |
+
|
| 501 |
+
# 14. Inference Endpoints for Whisper (best fastest STT) on NVIDIA T4 and Llama (best fastest AGI LLM) on NVIDIA A10
|
| 502 |
+
# My Inference Endpoint
|
| 503 |
+
API_URL_IE = f'https://tonpixzfvq3791u9.us-east-1.aws.endpoints.huggingface.cloud'
|
| 504 |
+
# Original
|
| 505 |
+
API_URL_IE = "https://api-inference.huggingface.co/models/openai/whisper-small.en"
|
| 506 |
+
MODEL2 = "openai/whisper-small.en"
|
| 507 |
+
MODEL2_URL = "https://huggingface.co/openai/whisper-small.en"
|
| 508 |
+
#headers = {
|
| 509 |
+
# "Authorization": "Bearer XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
|
| 510 |
+
# "Content-Type": "audio/wav"
|
| 511 |
+
#}
|
| 512 |
+
HF_KEY = os.getenv('HF_KEY')
|
| 513 |
+
headers = {
|
| 514 |
+
"Authorization": f"Bearer {HF_KEY}",
|
| 515 |
+
"Content-Type": "audio/wav"
|
| 516 |
+
}
|
| 517 |
+
|
| 518 |
+
#@st.cache_resource
|
| 519 |
+
def query(filename):
|
| 520 |
+
with open(filename, "rb") as f:
|
| 521 |
+
data = f.read()
|
| 522 |
+
response = requests.post(API_URL_IE, headers=headers, data=data)
|
| 523 |
+
return response.json()
|
| 524 |
+
|
| 525 |
+
def generate_filename(prompt, file_type):
|
| 526 |
+
central = pytz.timezone('US/Central')
|
| 527 |
+
safe_date_time = datetime.now(central).strftime("%m%d_%H%M")
|
| 528 |
+
replaced_prompt = prompt.replace(" ", "_").replace("\n", "_")
|
| 529 |
+
safe_prompt = "".join(x for x in replaced_prompt if x.isalnum() or x == "_")[:90]
|
| 530 |
+
return f"{safe_date_time}_{safe_prompt}.{file_type}"
|
| 531 |
+
|
| 532 |
+
# 15. Audio recorder to Wav file
|
| 533 |
+
def save_and_play_audio(audio_recorder):
|
| 534 |
+
audio_bytes = audio_recorder()
|
| 535 |
+
if audio_bytes:
|
| 536 |
+
filename = generate_filename("Recording", "wav")
|
| 537 |
+
with open(filename, 'wb') as f:
|
| 538 |
+
f.write(audio_bytes)
|
| 539 |
+
st.audio(audio_bytes, format="audio/wav")
|
| 540 |
+
return filename
|
| 541 |
+
|
| 542 |
+
# 16. Speech transcription to file output
|
| 543 |
+
def transcribe_audio(filename):
|
| 544 |
+
output = query(filename)
|
| 545 |
+
return output
|
| 546 |
+
|
| 547 |
+
def whisper_main():
|
| 548 |
+
st.title("Speech to Text")
|
| 549 |
+
st.write("Record your speech and get the text.")
|
| 550 |
+
|
| 551 |
+
# Audio, transcribe, GPT:
|
| 552 |
+
filename = save_and_play_audio(audio_recorder)
|
| 553 |
+
if filename is not None:
|
| 554 |
+
transcription = transcribe_audio(filename)
|
| 555 |
+
try:
|
| 556 |
+
transcription = transcription['text']
|
| 557 |
+
except:
|
| 558 |
+
st.write('Whisper model is asleep. Starting up now on T4 GPU - please give 5 minutes then retry as it scales up from zero to activate running container(s).')
|
| 559 |
+
|
| 560 |
+
st.write(transcription)
|
| 561 |
+
response = StreamLLMChatResponse(transcription)
|
| 562 |
+
# st.write(response) - redundant with streaming result?
|
| 563 |
+
filename = generate_filename(transcription, ".txt")
|
| 564 |
+
create_file(filename, transcription, response, should_save)
|
| 565 |
+
#st.sidebar.markdown(get_table_download_link(filename), unsafe_allow_html=True)
|
| 566 |
+
|
| 567 |
+
|
| 568 |
+
# 17. Main
|
| 569 |
+
def main():
|
| 570 |
+
|
| 571 |
+
st.title("AI Drome Llama")
|
| 572 |
+
prompt = f"Write ten funny jokes that are tweet length stories that make you laugh. Show as markdown outline with emojis for each."
|
| 573 |
+
|
| 574 |
+
# Add Wit and Humor buttons
|
| 575 |
+
add_witty_humor_buttons()
|
| 576 |
+
|
| 577 |
+
example_input = st.text_input("Enter your example text:", value=prompt, help="Enter text to get a response from DromeLlama.")
|
| 578 |
+
if st.button("Run Prompt With DromeLlama", help="Click to run the prompt."):
|
| 579 |
+
try:
|
| 580 |
+
StreamLLMChatResponse(example_input)
|
| 581 |
+
except:
|
| 582 |
+
st.write('DromeLlama is asleep. Starting up now on A10 - please give 5 minutes then retry as KEDA scales up from zero to activate running container(s).')
|
| 583 |
+
|
| 584 |
+
openai.api_key = os.getenv('OPENAI_KEY')
|
| 585 |
+
menu = ["txt", "htm", "xlsx", "csv", "md", "py"]
|
| 586 |
+
choice = st.sidebar.selectbox("Output File Type:", menu)
|
| 587 |
+
model_choice = st.sidebar.radio("Select Model:", ('gpt-3.5-turbo', 'gpt-3.5-turbo-0301'))
|
| 588 |
+
user_prompt = st.text_area("Enter prompts, instructions & questions:", '', height=100)
|
| 589 |
+
collength, colupload = st.columns([2,3]) # adjust the ratio as needed
|
| 590 |
+
with collength:
|
| 591 |
+
max_length = st.slider("File section length for large files", min_value=1000, max_value=128000, value=12000, step=1000)
|
| 592 |
+
with colupload:
|
| 593 |
+
uploaded_file = st.file_uploader("Add a file for context:", type=["pdf", "xml", "json", "xlsx", "csv", "html", "htm", "md", "txt"])
|
| 594 |
+
document_sections = deque()
|
| 595 |
+
document_responses = {}
|
| 596 |
+
if uploaded_file is not None:
|
| 597 |
+
file_content = read_file_content(uploaded_file, max_length)
|
| 598 |
+
document_sections.extend(divide_document(file_content, max_length))
|
| 599 |
+
if len(document_sections) > 0:
|
| 600 |
+
if st.button("ποΈ View Upload"):
|
| 601 |
+
st.markdown("**Sections of the uploaded file:**")
|
| 602 |
+
for i, section in enumerate(list(document_sections)):
|
| 603 |
+
st.markdown(f"**Section {i+1}**\n{section}")
|
| 604 |
+
st.markdown("**Chat with the model:**")
|
| 605 |
+
for i, section in enumerate(list(document_sections)):
|
| 606 |
+
if i in document_responses:
|
| 607 |
+
st.markdown(f"**Section {i+1}**\n{document_responses[i]}")
|
| 608 |
+
else:
|
| 609 |
+
if st.button(f"Chat about Section {i+1}"):
|
| 610 |
+
st.write('Reasoning with your inputs...')
|
| 611 |
+
response = chat_with_model(user_prompt, section, model_choice)
|
| 612 |
+
st.write('Response:')
|
| 613 |
+
st.write(response)
|
| 614 |
+
document_responses[i] = response
|
| 615 |
+
filename = generate_filename(f"{user_prompt}_section_{i+1}", choice)
|
| 616 |
+
create_file(filename, user_prompt, response, should_save)
|
| 617 |
+
st.sidebar.markdown(get_table_download_link(filename), unsafe_allow_html=True)
|
| 618 |
+
if st.button('π¬ Chat'):
|
| 619 |
+
st.write('Reasoning with your inputs...')
|
| 620 |
+
user_prompt_sections = divide_prompt(user_prompt, max_length)
|
| 621 |
+
full_response = ''
|
| 622 |
+
for prompt_section in user_prompt_sections:
|
| 623 |
+
response = chat_with_model(prompt_section, ''.join(list(document_sections)), model_choice)
|
| 624 |
+
full_response += response + '\n' # Combine the responses
|
| 625 |
+
response = full_response
|
| 626 |
+
st.write('Response:')
|
| 627 |
+
st.write(response)
|
| 628 |
+
filename = generate_filename(user_prompt, choice)
|
| 629 |
+
create_file(filename, user_prompt, response, should_save)
|
| 630 |
+
st.sidebar.markdown(get_table_download_link(filename), unsafe_allow_html=True)
|
| 631 |
+
|
| 632 |
+
# Compose a file sidebar of past encounters
|
| 633 |
+
all_files = glob.glob("*.*")
|
| 634 |
+
all_files = [file for file in all_files if len(os.path.splitext(file)[0]) >= 20] # exclude files with short names
|
| 635 |
+
all_files.sort(key=lambda x: (os.path.splitext(x)[1], x), reverse=True) # sort by file type and file name in descending order
|
| 636 |
+
if st.sidebar.button("π Delete All"):
|
| 637 |
+
for file in all_files:
|
| 638 |
+
os.remove(file)
|
| 639 |
+
st.experimental_rerun()
|
| 640 |
+
if st.sidebar.button("β¬οΈ Download All"):
|
| 641 |
+
zip_file = create_zip_of_files(all_files)
|
| 642 |
+
st.sidebar.markdown(get_zip_download_link(zip_file), unsafe_allow_html=True)
|
| 643 |
+
file_contents=''
|
| 644 |
+
next_action=''
|
| 645 |
+
for file in all_files:
|
| 646 |
+
col1, col2, col3, col4, col5 = st.sidebar.columns([1,6,1,1,1]) # adjust the ratio as needed
|
| 647 |
+
with col1:
|
| 648 |
+
if st.button("π", key="md_"+file): # md emoji button
|
| 649 |
+
with open(file, 'r') as f:
|
| 650 |
+
file_contents = f.read()
|
| 651 |
+
next_action='md'
|
| 652 |
+
with col2:
|
| 653 |
+
st.markdown(get_table_download_link(file), unsafe_allow_html=True)
|
| 654 |
+
with col3:
|
| 655 |
+
if st.button("π", key="open_"+file): # open emoji button
|
| 656 |
+
with open(file, 'r') as f:
|
| 657 |
+
file_contents = f.read()
|
| 658 |
+
next_action='open'
|
| 659 |
+
with col4:
|
| 660 |
+
if st.button("π", key="read_"+file): # search emoji button
|
| 661 |
+
with open(file, 'r') as f:
|
| 662 |
+
file_contents = f.read()
|
| 663 |
+
next_action='search'
|
| 664 |
+
with col5:
|
| 665 |
+
if st.button("π", key="delete_"+file):
|
| 666 |
+
os.remove(file)
|
| 667 |
+
st.experimental_rerun()
|
| 668 |
+
|
| 669 |
+
|
| 670 |
+
if len(file_contents) > 0:
|
| 671 |
+
if next_action=='open':
|
| 672 |
+
file_content_area = st.text_area("File Contents:", file_contents, height=500)
|
| 673 |
+
addDocumentHTML5(file_contents)
|
| 674 |
+
if next_action=='md':
|
| 675 |
+
st.markdown(file_contents)
|
| 676 |
+
addDocumentHTML5(file_contents)
|
| 677 |
+
if next_action=='search':
|
| 678 |
+
file_content_area = st.text_area("File Contents:", file_contents, height=500)
|
| 679 |
+
st.write('Reasoning with your inputs...')
|
| 680 |
+
|
| 681 |
+
# new - llama
|
| 682 |
+
response = StreamLLMChatResponse(file_contents)
|
| 683 |
+
filename = generate_filename(user_prompt, ".md")
|
| 684 |
+
#create_file(filename, response, '', should_save)
|
| 685 |
+
#addDocumentHTML5(file_contents)
|
| 686 |
+
addDocumentHTML5(response)
|
| 687 |
+
|
| 688 |
+
# old - gpt
|
| 689 |
+
#response = chat_with_model(user_prompt, file_contents, model_choice)
|
| 690 |
+
#filename = generate_filename(file_contents, choice)
|
| 691 |
+
#create_file(filename, user_prompt, response, should_save)
|
| 692 |
+
|
| 693 |
+
st.experimental_rerun()
|
| 694 |
+
|
| 695 |
+
# Feedback
|
| 696 |
+
# Step: Give User a Way to Upvote or Downvote
|
| 697 |
+
feedback = st.radio("Step 8: Give your feedback", ("π Upvote", "π Downvote"))
|
| 698 |
+
if feedback == "π Upvote":
|
| 699 |
+
st.write("You upvoted π. Thank you for your feedback!")
|
| 700 |
+
else:
|
| 701 |
+
st.write("You downvoted π. Thank you for your feedback!")
|
| 702 |
+
|
| 703 |
+
load_dotenv()
|
| 704 |
+
st.write(css, unsafe_allow_html=True)
|
| 705 |
+
st.header("Chat with documents :books:")
|
| 706 |
+
user_question = st.text_input("Ask a question about your documents:")
|
| 707 |
+
if user_question:
|
| 708 |
+
process_user_input(user_question)
|
| 709 |
+
with st.sidebar:
|
| 710 |
+
st.subheader("Your documents")
|
| 711 |
+
docs = st.file_uploader("import documents", accept_multiple_files=True)
|
| 712 |
+
with st.spinner("Processing"):
|
| 713 |
+
raw = pdf2txt(docs)
|
| 714 |
+
if len(raw) > 0:
|
| 715 |
+
length = str(len(raw))
|
| 716 |
+
text_chunks = txt2chunks(raw)
|
| 717 |
+
vectorstore = vector_store(text_chunks)
|
| 718 |
+
st.session_state.conversation = get_chain(vectorstore)
|
| 719 |
+
st.markdown('# AI Search Index of Length:' + length + ' Created.') # add timing
|
| 720 |
+
filename = generate_filename(raw, 'txt')
|
| 721 |
+
create_file(filename, raw, '', should_save)
|
| 722 |
+
|
| 723 |
+
# 18. Run AI Pipeline
|
| 724 |
+
if __name__ == "__main__":
|
| 725 |
+
whisper_main()
|
| 726 |
+
main()
|