Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,168 +1,91 @@
|
|
1 |
import streamlit as st
|
2 |
import openai
|
3 |
import os
|
4 |
-
import base64
|
5 |
-
import glob
|
6 |
import json
|
7 |
-
import
|
8 |
-
import pytz
|
9 |
-
import math
|
10 |
from datetime import datetime
|
11 |
-
from openai import ChatCompletion
|
12 |
-
from xml.etree import ElementTree as ET
|
13 |
-
from bs4 import BeautifulSoup
|
14 |
from collections import deque
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
15 |
|
16 |
openai.api_key = os.getenv('OPENAI_KEY')
|
17 |
-
st.set_page_config(
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
st.sidebar.write(choicePrefix + "HTML5.")
|
28 |
-
elif choice == "md":
|
29 |
-
st.sidebar.write(choicePrefix + "Markdown.")
|
30 |
-
elif choice == "py":
|
31 |
-
st.sidebar.write(choicePrefix + "Python Code.")
|
32 |
-
|
33 |
-
max_length = st.sidebar.slider("Max document length", min_value=1000, max_value=32000, value=2000, step=1000)
|
34 |
|
35 |
def generate_filename(prompt, file_type):
|
36 |
-
|
37 |
-
|
38 |
-
safe_prompt = "".join(x for x in prompt if x.isalnum())[:28]
|
39 |
return f"{safe_date_time}_{safe_prompt}.{file_type}"
|
40 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
41 |
def create_file(filename, prompt, response):
|
42 |
-
|
43 |
-
|
44 |
-
file.write(f"Prompt:\n{prompt}\nResponse:\n{response}")
|
45 |
-
elif filename.endswith(".htm"):
|
46 |
-
with open(filename, 'w') as file:
|
47 |
-
file.write(f"<h1>Prompt:</h1> <p>{prompt}</p> <h1>Response:</h1> <p>{response}</p>")
|
48 |
-
elif filename.endswith(".md"):
|
49 |
-
with open(filename, 'w') as file:
|
50 |
-
file.write(f"# Prompt:\n{prompt}\n# Response:\n{response}")
|
51 |
-
|
52 |
-
def truncate_document(document, length):
|
53 |
-
return document[:length]
|
54 |
|
55 |
def divide_document(document, max_length):
|
56 |
return [document[i:i+max_length] for i in range(0, len(document), max_length)]
|
57 |
|
58 |
-
def
|
59 |
-
|
60 |
-
|
61 |
-
conversation.append({'role': 'user', 'content': prompt})
|
62 |
-
conversation.append({'role': 'assistant', 'content': document_section})
|
63 |
-
response = openai.ChatCompletion.create(model=model, messages=conversation)
|
64 |
-
return response['choices'][0]['message']['content']
|
65 |
-
|
66 |
-
|
67 |
-
def get_table_download_link(file_path):
|
68 |
-
with open(file_path, 'r') as file:
|
69 |
-
data = file.read()
|
70 |
-
b64 = base64.b64encode(data.encode()).decode()
|
71 |
-
file_name = os.path.basename(file_path)
|
72 |
-
ext = os.path.splitext(file_name)[1] # get the file extension
|
73 |
-
if ext == '.txt':
|
74 |
-
mime_type = 'text/plain'
|
75 |
-
elif ext == '.htm':
|
76 |
-
mime_type = 'text/html'
|
77 |
-
elif ext == '.md':
|
78 |
-
mime_type = 'text/markdown'
|
79 |
-
else:
|
80 |
-
mime_type = 'application/octet-stream' # general binary data type
|
81 |
-
href = f'<a href="data:{mime_type};base64,{b64}" target="_blank" download="{file_name}">{file_name}</a>'
|
82 |
-
return href
|
83 |
-
|
84 |
-
|
85 |
-
def CompressXML(xml_text):
|
86 |
-
root = ET.fromstring(xml_text)
|
87 |
-
for elem in list(root.iter()):
|
88 |
-
if isinstance(elem.tag, str) and 'Comment' in elem.tag:
|
89 |
-
elem.parent.remove(elem)
|
90 |
-
return ET.tostring(root, encoding='unicode', method="xml")
|
91 |
-
|
92 |
-
def read_file_content(file,max_length):
|
93 |
-
if file.type == "application/json":
|
94 |
-
content = json.load(file)
|
95 |
-
return str(content)
|
96 |
-
elif file.type == "text/html" or file.type == "text/htm":
|
97 |
-
content = BeautifulSoup(file, "html.parser")
|
98 |
-
return content.text
|
99 |
-
elif file.type == "application/xml" or file.type == "text/xml":
|
100 |
-
tree = ET.parse(file)
|
101 |
-
root = tree.getroot()
|
102 |
-
xml = CompressXML(ET.tostring(root, encoding='unicode'))
|
103 |
-
return xml
|
104 |
-
elif file.type == "text/markdown" or file.type == "text/md":
|
105 |
-
md = mistune.create_markdown()
|
106 |
-
content = md(file.read().decode())
|
107 |
-
return content
|
108 |
-
elif file.type == "text/plain":
|
109 |
-
return file.getvalue().decode()
|
110 |
-
else:
|
111 |
-
return ""
|
112 |
|
113 |
def main():
|
114 |
-
|
115 |
-
uploaded_file = st.file_uploader("
|
116 |
-
max_length = 4000
|
117 |
|
118 |
document_sections = deque()
|
119 |
-
document_responses = {}
|
120 |
-
|
121 |
if uploaded_file is not None:
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
st.markdown(f"**Section {i+1}**\n{document_responses[i]}")
|
136 |
-
else:
|
137 |
-
if st.button(f"Chat about Section {i+1}"):
|
138 |
-
st.write('Thinking and Reasoning with your inputs...')
|
139 |
-
response = chat_with_model(user_prompt, section)
|
140 |
-
st.write('Response:')
|
141 |
-
st.write(response)
|
142 |
-
document_responses[i] = response
|
143 |
-
filename = generate_filename(f"{user_prompt}_section_{i+1}", choice)
|
144 |
-
create_file(filename, user_prompt, response)
|
145 |
-
st.sidebar.markdown(get_table_download_link(filename), unsafe_allow_html=True)
|
146 |
-
|
147 |
-
if st.button('💬 Chat'):
|
148 |
-
st.write('Thinking and Reasoning with your inputs...')
|
149 |
-
response = chat_with_model(user_prompt, ''.join(list(document_sections)))
|
150 |
-
st.write('Response:')
|
151 |
-
st.write(response)
|
152 |
-
|
153 |
-
filename = generate_filename(user_prompt, choice)
|
154 |
create_file(filename, user_prompt, response)
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
with col1:
|
161 |
-
st.markdown(get_table_download_link(file), unsafe_allow_html=True)
|
162 |
-
with col2:
|
163 |
-
if st.button("🗑", key=file):
|
164 |
-
os.remove(file)
|
165 |
-
st.experimental_rerun()
|
166 |
|
167 |
if __name__ == "__main__":
|
168 |
main()
|
|
|
1 |
import streamlit as st
|
2 |
import openai
|
3 |
import os
|
|
|
|
|
4 |
import json
|
5 |
+
import requests
|
|
|
|
|
6 |
from datetime import datetime
|
|
|
|
|
|
|
7 |
from collections import deque
|
8 |
+
from openai import ChatCompletion
|
9 |
+
from audio_recorder_streamlit import audio_recorder
|
10 |
+
|
11 |
+
# Initialize configurations
|
12 |
+
configurations = {}
|
13 |
+
config_file = "configurations.json"
|
14 |
+
if os.path.exists(config_file):
|
15 |
+
with open(config_file, "r") as file:
|
16 |
+
configurations = json.load(file)
|
17 |
|
18 |
openai.api_key = os.getenv('OPENAI_KEY')
|
19 |
+
st.set_page_config(page_title="GPT Streamlit Document Reasoner", layout="wide")
|
20 |
+
|
21 |
+
model_choice = st.sidebar.radio("Select Model:", ('gpt-3.5-turbo', 'gpt-3.5-turbo-0301'))
|
22 |
+
|
23 |
+
user_prompt = st.text_area(
|
24 |
+
"Enter prompts, instructions & questions:",
|
25 |
+
configurations.get("user_prompt", ""),
|
26 |
+
height=100
|
27 |
+
)
|
28 |
+
system_prompt = configurations.get("system_prompt", "You are a helpful assistant.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
29 |
|
30 |
def generate_filename(prompt, file_type):
|
31 |
+
safe_date_time = datetime.now().strftime("%m%d_%I%M")
|
32 |
+
safe_prompt = "".join(x for x in prompt if x.isalnum())[:45]
|
|
|
33 |
return f"{safe_date_time}_{safe_prompt}.{file_type}"
|
34 |
|
35 |
+
def chat_with_model(prompt, document_section):
|
36 |
+
conversation = [{'role': 'system', 'content': system_prompt}]
|
37 |
+
conversation.append({'role': 'user', 'content': prompt})
|
38 |
+
if document_section:
|
39 |
+
conversation.append({'role': 'assistant', 'content': document_section})
|
40 |
+
response = openai.ChatCompletion.create(model=model_choice, messages=conversation)
|
41 |
+
return response
|
42 |
+
|
43 |
+
def save_and_play_audio():
|
44 |
+
audio_bytes = audio_recorder()
|
45 |
+
if audio_bytes:
|
46 |
+
filename = generate_filename("Recording", "wav")
|
47 |
+
with open(filename, 'wb') as f:
|
48 |
+
f.write(audio_bytes)
|
49 |
+
st.audio(audio_bytes, format="audio/wav")
|
50 |
+
return filename
|
51 |
+
return None
|
52 |
+
|
53 |
def create_file(filename, prompt, response):
|
54 |
+
with open(filename, 'w') as file:
|
55 |
+
file.write(f"Prompt:\n{prompt}\nResponse:\n{response}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
56 |
|
57 |
def divide_document(document, max_length):
|
58 |
return [document[i:i+max_length] for i in range(0, len(document), max_length)]
|
59 |
|
60 |
+
def handle_uploaded_file(uploaded_file, max_length):
|
61 |
+
file_content = uploaded_file.read().decode()
|
62 |
+
return divide_document(file_content, max_length)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
63 |
|
64 |
def main():
|
65 |
+
max_length = st.slider("File section length for large files", min_value=1000, max_value=128000, value=12000, step=1000)
|
66 |
+
uploaded_file = st.file_uploader("Add a file for context:", type=["txt"])
|
|
|
67 |
|
68 |
document_sections = deque()
|
|
|
|
|
69 |
if uploaded_file is not None:
|
70 |
+
document_sections.extend(handle_uploaded_file(uploaded_file, max_length))
|
71 |
+
|
72 |
+
document_responses = {}
|
73 |
+
for i, section in enumerate(document_sections):
|
74 |
+
if st.button(f"Chat about Section {i+1}"):
|
75 |
+
response = chat_with_model(user_prompt, section)
|
76 |
+
document_responses[i] = response
|
77 |
+
filename = generate_filename(f"{user_prompt}_section_{i+1}", "txt")
|
78 |
+
create_file(filename, user_prompt, response)
|
79 |
+
|
80 |
+
if st.button('Chat'):
|
81 |
+
response = chat_with_model(user_prompt, ''.join(document_sections))
|
82 |
+
filename = generate_filename(user_prompt, "txt")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
83 |
create_file(filename, user_prompt, response)
|
84 |
+
|
85 |
+
configurations["user_prompt"] = user_prompt
|
86 |
+
configurations["system_prompt"] = system_prompt
|
87 |
+
with open(config_file, "w") as file:
|
88 |
+
json.dump(configurations, file)
|
|
|
|
|
|
|
|
|
|
|
|
|
89 |
|
90 |
if __name__ == "__main__":
|
91 |
main()
|