awacke1 commited on
Commit
28885ca
Β·
1 Parent(s): 7c16b81

Create backupapp.py

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