Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -7,117 +7,51 @@ import json
|
|
7 |
import mistune
|
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 |
-
|
17 |
-
|
18 |
-
page_title="GPT Streamlit Document Reasoner",
|
19 |
-
layout="wide")
|
20 |
-
|
21 |
-
menu = ["txt", "htm", "md", "py"]
|
22 |
-
choice = st.sidebar.selectbox("Output file type:", menu)
|
23 |
-
choicePrefix = "Output file type is "
|
24 |
|
25 |
-
|
26 |
-
st.sidebar.write(choicePrefix + "Text File.")
|
27 |
-
elif choice == "htm":
|
28 |
-
st.sidebar.write(choicePrefix + "HTML5.")
|
29 |
-
elif choice == "md":
|
30 |
-
st.sidebar.write(choicePrefix + "Markdown.")
|
31 |
-
elif choice == "py":
|
32 |
-
st.sidebar.write(choicePrefix + "Python Code.")
|
33 |
-
|
34 |
-
model_choice = st.sidebar.radio("Select Model:", ('gpt-3.5-turbo', 'gpt-3.5-turbo-0301'))
|
35 |
-
|
36 |
-
def chat_with_model(prompt, document_section):
|
37 |
-
model = model_choice
|
38 |
conversation = [{'role': 'system', 'content': 'You are a helpful assistant.'}]
|
39 |
conversation.append({'role': 'user', 'content': prompt})
|
40 |
-
|
41 |
-
|
|
|
42 |
return response['choices'][0]['message']['content']
|
43 |
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
def create_file(filename, prompt, response):
|
51 |
-
if filename.endswith(".txt"):
|
52 |
-
with open(filename, 'w') as file:
|
53 |
-
file.write(f"Prompt:\n{prompt}\nResponse:\n{response}")
|
54 |
-
elif filename.endswith(".htm"):
|
55 |
-
with open(filename, 'w') as file:
|
56 |
-
file.write(f"<h1>Prompt:</h1> <p>{prompt}</p> <h1>Response:</h1> <p>{response}</p>")
|
57 |
-
elif filename.endswith(".md"):
|
58 |
-
with open(filename, 'w') as file:
|
59 |
-
file.write(f"# Prompt:\n{prompt}\n# Response:\n{response}")
|
60 |
-
|
61 |
-
def truncate_document(document, length):
|
62 |
-
return document[:length]
|
63 |
-
|
64 |
-
def divide_document(document, max_length):
|
65 |
-
return [document[i:i+max_length] for i in range(0, len(document), max_length)]
|
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 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
content = json.load(file)
|
94 |
-
return str(content)
|
95 |
-
elif file.type == "text/html" or file.type == "text/htm":
|
96 |
-
content = BeautifulSoup(file, "html.parser")
|
97 |
-
return content.text
|
98 |
-
elif file.type == "application/xml" or file.type == "text/xml":
|
99 |
-
tree = ET.parse(file)
|
100 |
-
root = tree.getroot()
|
101 |
-
xml = CompressXML(ET.tostring(root, encoding='unicode'))
|
102 |
-
return xml
|
103 |
-
elif file.type == "text/markdown" or file.type == "text/md":
|
104 |
-
md = mistune.create_markdown()
|
105 |
-
content = md(file.read().decode())
|
106 |
-
return content
|
107 |
-
elif file.type == "text/plain":
|
108 |
-
return file.getvalue().decode()
|
109 |
-
else:
|
110 |
-
return ""
|
111 |
|
112 |
def main():
|
113 |
-
user_prompt = st.text_area("
|
114 |
|
115 |
collength, colupload = st.columns([2,3]) # adjust the ratio as needed
|
116 |
with collength:
|
117 |
-
|
118 |
-
max_length = st.slider("Context Section Length", min_value=1000, max_value=128000, value=12000, step=1000)
|
119 |
with colupload:
|
120 |
-
uploaded_file = st.file_uploader("
|
121 |
|
122 |
document_sections = deque()
|
123 |
document_responses = {}
|
@@ -139,36 +73,5 @@ def main():
|
|
139 |
st.markdown(f"**Section {i+1}**\n{document_responses[i]}")
|
140 |
else:
|
141 |
if st.button(f"Chat about Section {i+1}"):
|
142 |
-
st.write('
|
143 |
-
response = chat_with_model(
|
144 |
-
st.write('Response:')
|
145 |
-
st.write(response)
|
146 |
-
document_responses[i] = response
|
147 |
-
filename = generate_filename(f"{user_prompt}_section_{i+1}", choice)
|
148 |
-
create_file(filename, user_prompt, response)
|
149 |
-
st.sidebar.markdown(get_table_download_link(filename), unsafe_allow_html=True)
|
150 |
-
|
151 |
-
if st.button('💬 Chat'):
|
152 |
-
st.write('Thinking and Reasoning with your inputs...')
|
153 |
-
response = chat_with_model(user_prompt, ''.join(list(document_sections)))
|
154 |
-
st.write('Response:')
|
155 |
-
st.write(response)
|
156 |
-
|
157 |
-
filename = generate_filename(user_prompt, choice)
|
158 |
-
create_file(filename, user_prompt, response)
|
159 |
-
st.sidebar.markdown(get_table_download_link(filename), unsafe_allow_html=True)
|
160 |
-
|
161 |
-
all_files = glob.glob("*.*")
|
162 |
-
all_files = [file for file in all_files if len(os.path.splitext(file)[0]) >= 20] # exclude files with short names
|
163 |
-
all_files = sorted(all_files, key=lambda x: (os.path.splitext(x)[1], x)) # sort by file type and file name
|
164 |
-
for file in all_files:
|
165 |
-
col1, col3 = st.sidebar.columns([5,1]) # adjust the ratio as needed
|
166 |
-
with col1:
|
167 |
-
st.markdown(get_table_download_link(file), unsafe_allow_html=True)
|
168 |
-
with col3:
|
169 |
-
if st.button("🗑", key="delete_"+file):
|
170 |
-
os.remove(file)
|
171 |
-
st.experimental_rerun()
|
172 |
-
|
173 |
-
if __name__ == "__main__":
|
174 |
-
main()
|
|
|
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 |
+
# Function Definitions (kept unchanged)
|
20 |
+
# ...
|
|
|
|
|
|
|
|
|
|
|
|
|
21 |
|
22 |
+
def chat_with_file_contents(prompt, file_content):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
23 |
conversation = [{'role': 'system', 'content': 'You are a helpful assistant.'}]
|
24 |
conversation.append({'role': 'user', 'content': prompt})
|
25 |
+
if len(file_content)>0:
|
26 |
+
conversation.append({'role': 'assistant', 'content': file_content})
|
27 |
+
response = openai.ChatCompletion.create(model=model_choice, messages=conversation)
|
28 |
return response['choices'][0]['message']['content']
|
29 |
|
30 |
+
# Sidebar and global
|
31 |
+
openai.api_key = os.getenv('OPENAI_KEY')
|
32 |
+
st.set_page_config(page_title="GPT Streamlit Document Reasoner",layout="wide")
|
33 |
+
menu = ["htm", "txt", "xlsx", "csv", "md", "py"] #619
|
34 |
+
choice = st.sidebar.selectbox("Output File Type:", menu)
|
35 |
+
model_choice = st.sidebar.radio("Select Model:", ('gpt-3.5-turbo', 'gpt-3.5-turbo-0301'))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
36 |
|
37 |
+
# Audio, transcribe, GPT:
|
38 |
+
filename = save_and_play_audio(audio_recorder)
|
39 |
+
if filename is not None:
|
40 |
+
transcription = transcribe_audio(openai.api_key, filename, "whisper-1")
|
41 |
+
st.write(transcription)
|
42 |
+
gptOutput = chat_with_model(transcription, '')
|
43 |
+
filename = generate_filename(transcription, choice)
|
44 |
+
create_file(filename, transcription, gptOutput)
|
45 |
+
st.sidebar.markdown(get_table_download_link(filename), unsafe_allow_html=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
46 |
|
47 |
def main():
|
48 |
+
user_prompt = st.text_area("Enter prompts, instructions & questions:", '', height=100)
|
49 |
|
50 |
collength, colupload = st.columns([2,3]) # adjust the ratio as needed
|
51 |
with collength:
|
52 |
+
max_length = st.slider("File section length for large files", min_value=1000, max_value=128000, value=12000, step=1000)
|
|
|
53 |
with colupload:
|
54 |
+
uploaded_file = st.file_uploader("Add a file for context:", type=["xml", "json", "xlsx","csv","html", "htm", "md", "txt"])
|
55 |
|
56 |
document_sections = deque()
|
57 |
document_responses = {}
|
|
|
73 |
st.markdown(f"**Section {i+1}**\n{document_responses[i]}")
|
74 |
else:
|
75 |
if st.button(f"Chat about Section {i+1}"):
|
76 |
+
st.write('Reasoning with your inputs...')
|
77 |
+
response = chat_with_model(user
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|