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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import openai
|
| 3 |
+
import os
|
| 4 |
+
import base64
|
| 5 |
+
import glob
|
| 6 |
+
import json
|
| 7 |
+
import mistune
|
| 8 |
+
import pytz
|
| 9 |
+
import math
|
| 10 |
+
import requests
|
| 11 |
+
|
| 12 |
+
from datetime import datetime
|
| 13 |
+
from openai import ChatCompletion
|
| 14 |
+
from xml.etree import ElementTree as ET
|
| 15 |
+
from bs4 import BeautifulSoup
|
| 16 |
+
from collections import deque
|
| 17 |
+
from audio_recorder_streamlit import audio_recorder
|
| 18 |
+
|
| 19 |
+
openai.api_key = os.getenv('OPENAI_KEY')
|
| 20 |
+
st.set_page_config(page_title="GPT Streamlit Document Reasoner",layout="wide")
|
| 21 |
+
|
| 22 |
+
menu = ["htm", "txt", "xlsx", "csv", "md", "py"] #619
|
| 23 |
+
choice = st.sidebar.selectbox("Output File Type:", menu)
|
| 24 |
+
model_choice = st.sidebar.radio("Select Model:", ('gpt-3.5-turbo', 'gpt-3.5-turbo-0301'))
|
| 25 |
+
|
| 26 |
+
def generate_filename(prompt, file_type):
|
| 27 |
+
central = pytz.timezone('US/Central')
|
| 28 |
+
safe_date_time = datetime.now(central).strftime("%m%d_%I%M")
|
| 29 |
+
safe_prompt = "".join(x for x in prompt if x.isalnum())[:45]
|
| 30 |
+
return f"{safe_date_time}_{safe_prompt}.{file_type}"
|
| 31 |
+
|
| 32 |
+
def chat_with_model(prompt, document_section):
|
| 33 |
+
model = model_choice
|
| 34 |
+
conversation = [{'role': 'system', 'content': 'You are a helpful assistant.'}]
|
| 35 |
+
conversation.append({'role': 'user', 'content': prompt})
|
| 36 |
+
if len(document_section)>0:
|
| 37 |
+
conversation.append({'role': 'assistant', 'content': document_section})
|
| 38 |
+
response = openai.ChatCompletion.create(model=model, messages=conversation)
|
| 39 |
+
return response
|
| 40 |
+
#return response['choices'][0]['message']['content']
|
| 41 |
+
|
| 42 |
+
def transcribe_audio(openai_key, file_path, model):
|
| 43 |
+
OPENAI_API_URL = "https://api.openai.com/v1/audio/transcriptions"
|
| 44 |
+
headers = {
|
| 45 |
+
"Authorization": f"Bearer {openai_key}",
|
| 46 |
+
}
|
| 47 |
+
with open(file_path, 'rb') as f:
|
| 48 |
+
data = {'file': f}
|
| 49 |
+
response = requests.post(OPENAI_API_URL, headers=headers, files=data, data={'model': model})
|
| 50 |
+
if response.status_code == 200:
|
| 51 |
+
st.write(response.json())
|
| 52 |
+
response2 = chat_with_model(response.json().get('text'), '')
|
| 53 |
+
st.write('Responses:')
|
| 54 |
+
#st.write(response)
|
| 55 |
+
st.write(response2)
|
| 56 |
+
return response.json().get('text')
|
| 57 |
+
else:
|
| 58 |
+
st.write(response.json())
|
| 59 |
+
st.error("Error in API call.")
|
| 60 |
+
return None
|
| 61 |
+
|
| 62 |
+
def save_and_play_audio(audio_recorder):
|
| 63 |
+
audio_bytes = audio_recorder()
|
| 64 |
+
if audio_bytes:
|
| 65 |
+
filename = generate_filename("Recording", "wav")
|
| 66 |
+
with open(filename, 'wb') as f:
|
| 67 |
+
f.write(audio_bytes)
|
| 68 |
+
st.audio(audio_bytes, format="audio/wav")
|
| 69 |
+
return filename
|
| 70 |
+
return None
|
| 71 |
+
|
| 72 |
+
def create_file(filename, prompt, response):
|
| 73 |
+
if filename.endswith(".txt"):
|
| 74 |
+
with open(filename, 'w') as file:
|
| 75 |
+
file.write(f"Prompt:\n{prompt}\nResponse:\n{response}")
|
| 76 |
+
elif filename.endswith(".htm"):
|
| 77 |
+
with open(filename, 'w') as file:
|
| 78 |
+
file.write(f"<h1>Prompt:</h1> <p>{prompt}</p> <h1>Response:</h1> <p>{response}</p>")
|
| 79 |
+
elif filename.endswith(".md"):
|
| 80 |
+
with open(filename, 'w') as file:
|
| 81 |
+
file.write(f"# Prompt:\n{prompt}\n# Response:\n{response}")
|
| 82 |
+
def truncate_document(document, length):
|
| 83 |
+
return document[:length]
|
| 84 |
+
def divide_document(document, max_length):
|
| 85 |
+
return [document[i:i+max_length] for i in range(0, len(document), max_length)]
|
| 86 |
+
def get_table_download_link(file_path):
|
| 87 |
+
with open(file_path, 'r') as file:
|
| 88 |
+
data = file.read()
|
| 89 |
+
b64 = base64.b64encode(data.encode()).decode()
|
| 90 |
+
file_name = os.path.basename(file_path)
|
| 91 |
+
ext = os.path.splitext(file_name)[1] # get the file extension
|
| 92 |
+
if ext == '.txt':
|
| 93 |
+
mime_type = 'text/plain'
|
| 94 |
+
elif ext == '.py':
|
| 95 |
+
mime_type = 'text/plain'
|
| 96 |
+
elif ext == '.xlsx':
|
| 97 |
+
mime_type = 'text/plain'
|
| 98 |
+
elif ext == '.csv':
|
| 99 |
+
mime_type = 'text/plain'
|
| 100 |
+
elif ext == '.htm':
|
| 101 |
+
mime_type = 'text/html'
|
| 102 |
+
elif ext == '.md':
|
| 103 |
+
mime_type = 'text/markdown'
|
| 104 |
+
else:
|
| 105 |
+
mime_type = 'application/octet-stream' # general binary data type
|
| 106 |
+
href = f'<a href="data:{mime_type};base64,{b64}" target="_blank" download="{file_name}">{file_name}</a>'
|
| 107 |
+
return href
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
# Audio, transcribe, GPT:
|
| 112 |
+
filename = save_and_play_audio(audio_recorder)
|
| 113 |
+
if filename is not None:
|
| 114 |
+
transcription = transcribe_audio(openai.api_key, filename, "whisper-1")
|
| 115 |
+
st.write(transcription)
|
| 116 |
+
gptOutput = chat_with_model(transcription, '') # push transcript through as prompt
|
| 117 |
+
filename = generate_filename(transcription, choice)
|
| 118 |
+
create_file(filename, transcription, gptOutput)
|
| 119 |
+
st.sidebar.markdown(get_table_download_link(filename), unsafe_allow_html=True)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def CompressXML(xml_text):
|
| 126 |
+
root = ET.fromstring(xml_text)
|
| 127 |
+
for elem in list(root.iter()):
|
| 128 |
+
if isinstance(elem.tag, str) and 'Comment' in elem.tag:
|
| 129 |
+
elem.parent.remove(elem)
|
| 130 |
+
return ET.tostring(root, encoding='unicode', method="xml")
|
| 131 |
+
|
| 132 |
+
def read_file_content(file,max_length):
|
| 133 |
+
if file.type == "application/json":
|
| 134 |
+
content = json.load(file)
|
| 135 |
+
return str(content)
|
| 136 |
+
elif file.type == "text/html" or file.type == "text/htm":
|
| 137 |
+
content = BeautifulSoup(file, "html.parser")
|
| 138 |
+
return content.text
|
| 139 |
+
elif file.type == "application/xml" or file.type == "text/xml":
|
| 140 |
+
tree = ET.parse(file)
|
| 141 |
+
root = tree.getroot()
|
| 142 |
+
xml = CompressXML(ET.tostring(root, encoding='unicode'))
|
| 143 |
+
return xml
|
| 144 |
+
elif file.type == "text/markdown" or file.type == "text/md":
|
| 145 |
+
md = mistune.create_markdown()
|
| 146 |
+
content = md(file.read().decode())
|
| 147 |
+
return content
|
| 148 |
+
elif file.type == "text/plain":
|
| 149 |
+
return file.getvalue().decode()
|
| 150 |
+
else:
|
| 151 |
+
return ""
|
| 152 |
+
|
| 153 |
+
def main():
|
| 154 |
+
user_prompt = st.text_area("Enter prompts, instructions & questions:", '', height=100)
|
| 155 |
+
|
| 156 |
+
collength, colupload = st.columns([2,3]) # adjust the ratio as needed
|
| 157 |
+
with collength:
|
| 158 |
+
#max_length = 12000 - optimal for gpt35 turbo. 2x=24000 for gpt4. 8x=96000 for gpt4-32k.
|
| 159 |
+
max_length = st.slider("File section length for large files", min_value=1000, max_value=128000, value=12000, step=1000)
|
| 160 |
+
with colupload:
|
| 161 |
+
uploaded_file = st.file_uploader("Add a file for context:", type=["xml", "json", "xlsx","csv","html", "htm", "md", "txt"])
|
| 162 |
+
|
| 163 |
+
document_sections = deque()
|
| 164 |
+
document_responses = {}
|
| 165 |
+
|
| 166 |
+
if uploaded_file is not None:
|
| 167 |
+
file_content = read_file_content(uploaded_file, max_length)
|
| 168 |
+
document_sections.extend(divide_document(file_content, max_length))
|
| 169 |
+
|
| 170 |
+
if len(document_sections) > 0:
|
| 171 |
+
|
| 172 |
+
if st.button("👁️ View Upload"):
|
| 173 |
+
st.markdown("**Sections of the uploaded file:**")
|
| 174 |
+
for i, section in enumerate(list(document_sections)):
|
| 175 |
+
st.markdown(f"**Section {i+1}**\n{section}")
|
| 176 |
+
|
| 177 |
+
st.markdown("**Chat with the model:**")
|
| 178 |
+
for i, section in enumerate(list(document_sections)):
|
| 179 |
+
if i in document_responses:
|
| 180 |
+
st.markdown(f"**Section {i+1}**\n{document_responses[i]}")
|
| 181 |
+
else:
|
| 182 |
+
if st.button(f"Chat about Section {i+1}"):
|
| 183 |
+
st.write('Reasoning with your inputs...')
|
| 184 |
+
response = chat_with_model(user_prompt, section)
|
| 185 |
+
st.write('Response:')
|
| 186 |
+
st.write(response)
|
| 187 |
+
document_responses[i] = response
|
| 188 |
+
filename = generate_filename(f"{user_prompt}_section_{i+1}", choice)
|
| 189 |
+
create_file(filename, user_prompt, response)
|
| 190 |
+
st.sidebar.markdown(get_table_download_link(filename), unsafe_allow_html=True)
|
| 191 |
+
|
| 192 |
+
if st.button('💬 Chat'):
|
| 193 |
+
st.write('Reasoning with your inputs...')
|
| 194 |
+
response = chat_with_model(user_prompt, ''.join(list(document_sections)))
|
| 195 |
+
st.write('Response:')
|
| 196 |
+
st.write(response)
|
| 197 |
+
|
| 198 |
+
filename = generate_filename(user_prompt, choice)
|
| 199 |
+
create_file(filename, user_prompt, response)
|
| 200 |
+
st.sidebar.markdown(get_table_download_link(filename), unsafe_allow_html=True)
|
| 201 |
+
|
| 202 |
+
all_files = glob.glob("*.*")
|
| 203 |
+
all_files = [file for file in all_files if len(os.path.splitext(file)[0]) >= 20] # exclude files with short names
|
| 204 |
+
all_files.sort(key=lambda x: (os.path.splitext(x)[1], x), reverse=True) # sort by file type and file name in descending order
|
| 205 |
+
|
| 206 |
+
for file in all_files:
|
| 207 |
+
col1, col3 = st.sidebar.columns([5,1]) # adjust the ratio as needed
|
| 208 |
+
with col1:
|
| 209 |
+
st.markdown(get_table_download_link(file), unsafe_allow_html=True)
|
| 210 |
+
with col3:
|
| 211 |
+
if st.button("🗑", key="delete_"+file):
|
| 212 |
+
os.remove(file)
|
| 213 |
+
st.experimental_rerun()
|
| 214 |
+
|
| 215 |
+
if __name__ == "__main__":
|
| 216 |
+
main()
|