Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
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 |
+
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 |
+
if choice == "txt":
|
25 |
+
st.sidebar.write(choicePrefix + "Text File.")
|
26 |
+
elif choice == "htm":
|
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 |
+
central = pytz.timezone('US/Central')
|
37 |
+
safe_date_time = datetime.now(central).strftime("%m%d_%I%M")
|
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 |
+
if filename.endswith(".txt"):
|
43 |
+
with open(filename, 'w') as file:
|
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 chat_with_model(prompt, document_section):
|
59 |
+
model = "gpt-3.5-turbo"
|
60 |
+
conversation = [{'role': 'system', 'content': 'You are a helpful assistant.'}]
|
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 |
+
user_prompt = st.text_area("Your question:", '', height=120)
|
115 |
+
uploaded_file = st.file_uploader("Choose a file", type=["xml", "json", "html", "htm", "md", "txt"])
|
116 |
+
max_length = 4000
|
117 |
+
|
118 |
+
document_sections = deque()
|
119 |
+
document_responses = {}
|
120 |
+
|
121 |
+
if uploaded_file is not None:
|
122 |
+
file_content = read_file_content(uploaded_file, max_length)
|
123 |
+
document_sections.extend(divide_document(file_content, max_length))
|
124 |
+
|
125 |
+
if len(document_sections) > 0:
|
126 |
+
|
127 |
+
st.markdown("**Sections of the uploaded file:**")
|
128 |
+
for i, section in enumerate(list(document_sections)):
|
129 |
+
st.markdown(f"**Section {i+1}**\n{section}")
|
130 |
+
|
131 |
+
|
132 |
+
st.markdown("**Chat with the model:**")
|
133 |
+
for i, section in enumerate(list(document_sections)):
|
134 |
+
if i in document_responses:
|
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 |
+
st.sidebar.markdown(get_table_download_link(filename), unsafe_allow_html=True)
|
156 |
+
|
157 |
+
all_files = glob.glob("*.txt") + glob.glob("*.htm") + glob.glob("*.md")
|
158 |
+
for file in all_files:
|
159 |
+
col1, col2 = st.sidebar.columns([4,1]) # adjust the ratio as needed
|
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()
|