awacke1 commited on
Commit
c8fbdd5
·
1 Parent(s): b8f91aa

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +169 -0
app.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ def generate_filename(prompt, file_type):
34
+ central = pytz.timezone('US/Central')
35
+ safe_date_time = datetime.now(central).strftime("%m%d_%I%M")
36
+ safe_prompt = "".join(x for x in prompt if x.isalnum())[:28]
37
+ return f"{safe_date_time}_{safe_prompt}.{file_type}"
38
+
39
+ def create_file(filename, prompt, response):
40
+ if filename.endswith(".txt"):
41
+ with open(filename, 'w') as file:
42
+ file.write(f"Prompt:\n{prompt}\nResponse:\n{response}")
43
+ elif filename.endswith(".htm"):
44
+ with open(filename, 'w') as file:
45
+ file.write(f"<h1>Prompt:</h1> <p>{prompt}</p> <h1>Response:</h1> <p>{response}</p>")
46
+ elif filename.endswith(".md"):
47
+ with open(filename, 'w') as file:
48
+ file.write(f"# Prompt:\n{prompt}\n# Response:\n{response}")
49
+
50
+ def truncate_document(document, length):
51
+ return document[:length]
52
+
53
+ def divide_document(document, max_length):
54
+ return [document[i:i+max_length] for i in range(0, len(document), max_length)]
55
+
56
+ def chat_with_model(prompt, document_section):
57
+ model = "gpt-3.5-turbo"
58
+ conversation = [{'role': 'system', 'content': 'You are a helpful assistant.'}]
59
+ conversation.append({'role': 'user', 'content': prompt})
60
+ conversation.append({'role': 'assistant', 'content': document_section})
61
+ response = openai.ChatCompletion.create(model=model, messages=conversation)
62
+ return response['choices'][0]['message']['content']
63
+
64
+ def get_table_download_link(file_path):
65
+ with open(file_path, 'r') as file:
66
+ data = file.read()
67
+ b64 = base64.b64encode(data.encode()).decode()
68
+ file_name = os.path.basename(file_path)
69
+ ext = os.path.splitext(file_name)[1] # get the file extension
70
+ if ext == '.txt':
71
+ mime_type = 'text/plain'
72
+ elif ext == '.htm':
73
+ mime_type = 'text/html'
74
+ elif ext == '.md':
75
+ mime_type = 'text/markdown'
76
+ else:
77
+ mime_type = 'application/octet-stream' # general binary data type
78
+ href = f'<a href="data:{mime_type};base64,{b64}" target="_blank" download="{file_name}">{file_name}</a>'
79
+ return href
80
+
81
+ def CompressXML(xml_text):
82
+ root = ET.fromstring(xml_text)
83
+ for elem in list(root.iter()):
84
+ if isinstance(elem.tag, str) and 'Comment' in elem.tag:
85
+ elem.parent.remove(elem)
86
+ return ET.tostring(root, encoding='unicode', method="xml")
87
+
88
+ def read_file_content(file,max_length):
89
+ if file.type == "application/json":
90
+ content = json.load(file)
91
+ return str(content)
92
+ elif file.type == "text/html" or file.type == "text/htm":
93
+ content = BeautifulSoup(file, "html.parser")
94
+ return content.text
95
+ elif file.type == "application/xml" or file.type == "text/xml":
96
+ tree = ET.parse(file)
97
+ root = tree.getroot()
98
+ xml = CompressXML(ET.tostring(root, encoding='unicode'))
99
+ return xml
100
+ elif file.type == "text/markdown" or file.type == "text/md":
101
+ md = mistune.create_markdown()
102
+ content = md(file.read().decode())
103
+ return content
104
+ elif file.type == "text/plain":
105
+ return file.getvalue().decode()
106
+ else:
107
+ return ""
108
+
109
+ def main():
110
+ user_prompt = st.text_area("Your question:", '', height=120)
111
+
112
+ collength, colupload = st.columns([2,3]) # adjust the ratio as needed
113
+ with collength:
114
+ #max_length = 12000 - optimal for gpt35 turbo. 2x=24000 for gpt4. 8x=96000 for gpt4-32k.
115
+ max_length = st.slider("Context Section Length", min_value=1000, max_value=128000, value=12000, step=1000)
116
+ with colupload:
117
+ uploaded_file = st.file_uploader("Choose a file", type=["xml", "json", "html", "htm", "md", "txt"])
118
+
119
+ document_sections = deque()
120
+ document_responses = {}
121
+
122
+ if uploaded_file is not None:
123
+ file_content = read_file_content(uploaded_file, max_length)
124
+ document_sections.extend(divide_document(file_content, max_length))
125
+
126
+ if len(document_sections) > 0:
127
+
128
+ if st.button("👁️ View Upload"):
129
+ st.markdown("**Sections of the uploaded file:**")
130
+ for i, section in enumerate(list(document_sections)):
131
+ st.markdown(f"**Section {i+1}**\n{section}")
132
+
133
+ st.markdown("**Chat with the model:**")
134
+ for i, section in enumerate(list(document_sections)):
135
+ if i in document_responses:
136
+ st.markdown(f"**Section {i+1}**\n{document_responses[i]}")
137
+ else:
138
+ if st.button(f"Chat about Section {i+1}"):
139
+ st.write('Thinking and Reasoning with your inputs...')
140
+ response = chat_with_model(user_prompt, section)
141
+ st.write('Response:')
142
+ st.write(response)
143
+ document_responses[i] = response
144
+ filename = generate_filename(f"{user_prompt}_section_{i+1}", choice)
145
+ create_file(filename, user_prompt, response)
146
+ st.sidebar.markdown(get_table_download_link(filename), unsafe_allow_html=True)
147
+
148
+ if st.button('💬 Chat'):
149
+ st.write('Thinking and Reasoning with your inputs...')
150
+ response = chat_with_model(user_prompt, ''.join(list(document_sections)))
151
+ st.write('Response:')
152
+ st.write(response)
153
+
154
+ filename = generate_filename(user_prompt, choice)
155
+ create_file(filename, user_prompt, response)
156
+ st.sidebar.markdown(get_table_download_link(filename), unsafe_allow_html=True)
157
+
158
+ all_files = glob.glob("*.txt") + glob.glob("*.htm") + glob.glob("*.md")
159
+ for file in all_files:
160
+ col1, col2 = st.sidebar.columns([4,1]) # adjust the ratio as needed
161
+ with col1:
162
+ st.markdown(get_table_download_link(file), unsafe_allow_html=True)
163
+ with col2:
164
+ if st.button("🗑", key=file):
165
+ os.remove(file)
166
+ st.experimental_rerun()
167
+
168
+ if __name__ == "__main__":
169
+ main()