awacke1 commited on
Commit
7611821
Β·
1 Parent(s): 0ec70c8

Create app.py

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