awacke1 commited on
Commit
7c0cd2b
Β·
1 Parent(s): 446fffb

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +167 -0
app.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ st.markdown("**Sections of the uploaded file:**")
127
+ for i, section in enumerate(list(document_sections)):
128
+ st.markdown(f"**Section {i+1}**\n{section}")
129
+
130
+ st.markdown("**Chat with the model:**")
131
+ for i, section in enumerate(list(document_sections)):
132
+ if i in document_responses:
133
+ st.markdown(f"**Section {i+1}**\n{document_responses[i]}")
134
+ else:
135
+ if st.button(f"Chat about Section {i+1}"):
136
+ st.write('Thinking and Reasoning with your inputs...')
137
+ response = chat_with_model(user_prompt, section)
138
+ st.write('Response:')
139
+ st.write(response)
140
+ document_responses[i] = response
141
+ filename = generate_filename(f"{user_prompt}_section_{i+1}", choice)
142
+ create_file(filename, user_prompt, response)
143
+ st.sidebar.markdown(get_table_download_link(filename), unsafe_allow_html=True)
144
+
145
+
146
+ if st.button('πŸ’¬ Chat'):
147
+ st.write('Thinking and Reasoning with your inputs...')
148
+ response = chat_with_model(user_prompt, ''.join(list(document_sections)))
149
+ st.write('Response:')
150
+ st.write(response)
151
+
152
+ filename = generate_filename(user_prompt, choice)
153
+ create_file(filename, user_prompt, response)
154
+ st.sidebar.markdown(get_table_download_link(filename), unsafe_allow_html=True)
155
+
156
+ all_files = glob.glob("*.txt") + glob.glob("*.htm") + glob.glob("*.md")
157
+ for file in all_files:
158
+ col1, col2 = st.sidebar.columns([4,1]) # adjust the ratio as needed
159
+ with col1:
160
+ st.markdown(get_table_download_link(file), unsafe_allow_html=True)
161
+ with col2:
162
+ if st.button("πŸ—‘", key=file):
163
+ os.remove(file)
164
+ st.experimental_rerun()
165
+
166
+ if __name__ == "__main__":
167
+ main()