awacke1 commited on
Commit
04bb617
Β·
1 Parent(s): d7869d4

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +226 -0
app.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import pandas as pd
12
+
13
+ from datetime import datetime
14
+ from openai import ChatCompletion
15
+ from xml.etree import ElementTree as ET
16
+ from bs4 import BeautifulSoup
17
+ from collections import deque
18
+ from audio_recorder_streamlit import audio_recorder
19
+
20
+ openai.api_key = os.getenv('OPENAI_KEY')
21
+ st.set_page_config(page_title="GPT Streamlit Document Reasoner",layout="wide")
22
+
23
+ menu = ["txt", "htm", "md", "py", "csv", "xlsx"]
24
+ choice = st.sidebar.selectbox("Output File Type:", menu)
25
+ model_choice = st.sidebar.radio("Select Model:", ('gpt-3.5-turbo', 'gpt-3.5-turbo-0301'))
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
+ TEMPERATURE = st.sidebar.slider("Adjust Creativity:", min_value=0.1, max_value=1.0, value=0.5, step=0.1)
34
+ def chat_with_model(prompt, document_section):
35
+ model = model_choice
36
+ conversation = [{'role': 'system', 'content': 'You are a helpful assistant.'}]
37
+ conversation.append({'role': 'user', 'content': prompt})
38
+ conversation.append({'role': 'assistant', 'content': document_section})
39
+ response = openai.ChatCompletion.create(model=model, messages=conversation, temperature=TEMPERATURE)
40
+ return response['choices'][0]['message']['content']
41
+
42
+ def create_file(filename, prompt, response):
43
+ if filename.endswith(".txt"):
44
+ with open(filename, 'w') as file:
45
+ file.write(f"Prompt:\n{prompt}\nResponse:\n{response}")
46
+ elif filename.endswith(".htm"):
47
+ with open(filename, 'w') as file:
48
+ file.write(f"<h1>Prompt:</h1> <p>{prompt}</p> <h1>Response:</h1> <p>{response}</p>")
49
+ elif filename.endswith(".md"):
50
+ with open(filename, 'w') as file:
51
+ file.write(f"# Prompt:\n{prompt}\n# Response:\n{response}")
52
+ elif filename.endswith(".csv"):
53
+ response_df = pd.DataFrame({"Prompt": [prompt], "Response": [response]})
54
+ response_df.to_csv(filename, index=False)
55
+ elif filename.endswith(".xlsx"):
56
+ response_df = pd.DataFrame({"Prompt": [prompt], "Response": [response]})
57
+ response_df.to_excel(filename, index=False)
58
+
59
+ # Updated to auto process transcript to chatgpt in AI pipeline from Whisper to ChatGPT
60
+ def transcribe_audio(openai_key, file_path, model):
61
+ OPENAI_API_URL = "https://api.openai.com/v1/audio/transcriptions"
62
+ headers = {
63
+ "Authorization": f"Bearer {openai_key}",
64
+ }
65
+ with open(file_path, 'rb') as f:
66
+ data = {'file': f}
67
+ response = requests.post(OPENAI_API_URL, headers=headers, files=data, data={'model': model})
68
+ if response.status_code == 200:
69
+ st.write('Reasoning with your transcription..')
70
+ transcript=response.json().get('text')
71
+ st.write(transcript)
72
+ gptResponse = chat_with_model(transcript, '') # send transcript to ChatGPT
73
+ filename = generate_filename(transcript, choice) # auto name file with date and prompt per output file type
74
+ create_file(filename, transcript, gptResponse) # write output file
75
+ return gptResponse
76
+ else:
77
+ st.write(response.json())
78
+ st.error("Error in API call.")
79
+ return None
80
+
81
+ # Updated to call direct from transcription to chat inference.
82
+ def save_and_play_audio(audio_recorder):
83
+ audio_bytes = audio_recorder()
84
+ if audio_bytes:
85
+ filename = generate_filename("Recording", "wav")
86
+ with open(filename, 'wb') as f:
87
+ f.write(audio_bytes)
88
+ st.audio(audio_bytes, format="audio/wav")
89
+ return filename
90
+ USEAUDIO=False
91
+ if USEAUDIO:
92
+ if st.sidebar.checkbox('Use Audio Input'):
93
+ filename = save_and_play_audio(audio_recorder)
94
+ if filename is not None:
95
+ #if st.button("Transcribe"):
96
+ transcription = transcribe_audio(openai.api_key, filename, "whisper-1")
97
+ st.markdown('### Transcription:')
98
+ st.write(transcription)
99
+
100
+
101
+ def truncate_document(document, length):
102
+ return document[:length]
103
+
104
+ def divide_document(document, max_length):
105
+ return [document[i:i+max_length] for i in range(0, len(document), max_length)]
106
+
107
+ def get_table_download_link(file_path):
108
+ with open(file_path, 'r') as file:
109
+ data = file.read()
110
+ b64 = base64.b64encode(data.encode()).decode()
111
+ file_name = os.path.basename(file_path)
112
+ ext = os.path.splitext(file_name)[1] # get the file extension
113
+ if ext == '.txt':
114
+ mime_type = 'text/plain'
115
+ elif ext == '.wav':
116
+ mime_type = 'audio/x-wav'
117
+ elif ext == '.htm':
118
+ mime_type = 'text/html'
119
+ elif ext == '.md':
120
+ mime_type = 'text/markdown'
121
+ else:
122
+ mime_type = 'application/octet-stream' # general binary data type
123
+ href = f'<a href="data:{mime_type};base64,{b64}" target="_blank" download="{file_name}">{file_name}</a>'
124
+ return href
125
+
126
+ def CompressXML(xml_text):
127
+ root = ET.fromstring(xml_text)
128
+ for elem in list(root.iter()):
129
+ if isinstance(elem.tag, str) and 'Comment' in elem.tag:
130
+ elem.parent.remove(elem)
131
+ return ET.tostring(root, encoding='unicode', method="xml")
132
+
133
+ def read_file_content(file,max_length):
134
+ if file.type == "application/json":
135
+ content = json.load(file)
136
+ return str(content)
137
+ elif file.type == "text/html" or file.type == "text/htm":
138
+ content = BeautifulSoup(file, "html.parser")
139
+ return content.text
140
+ elif file.type == "application/xml" or file.type == "text/xml":
141
+ tree = ET.parse(file)
142
+ root = tree.getroot()
143
+ xml = CompressXML(ET.tostring(root, encoding='unicode'))
144
+ return xml
145
+ elif file.type == "text/markdown" or file.type == "text/md":
146
+ md = mistune.create_markdown()
147
+ content = md(file.read().decode())
148
+ return content
149
+ elif file.type == "text/plain":
150
+ return file.getvalue().decode()
151
+ elif file.type == "text/csv":
152
+ df = pd.read_csv(file)
153
+ return df.to_string(index=False)
154
+ elif file.type == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
155
+ df = pd.read_excel(file)
156
+ return df.to_string(index=False)
157
+ else:
158
+ return ""
159
+
160
+ def main():
161
+ # max_length = 12000 - optimal for gpt35 turbo. 2x=24000 for gpt4. 8x=96000 for gpt4-32k.
162
+ max_length = st.sidebar.slider("File section length for large files", min_value=1000, max_value=128000, value=12000, step=1000)
163
+
164
+ colprompt, colupload = st.columns([5,2]) # adjust the ratio as needed
165
+ with colprompt:
166
+ user_prompt = st.text_area("Enter prompts, instructions & questions:", '', height=150)
167
+ with colupload:
168
+ uploaded_file = st.file_uploader("Add a file for context:", type=["xml", "json", "html", "htm", "txt"])
169
+
170
+ document_sections = deque()
171
+ document_responses = {}
172
+
173
+ if uploaded_file is not None:
174
+ file_content = read_file_content(uploaded_file, max_length)
175
+ document_sections.extend(divide_document(file_content, max_length))
176
+
177
+ if len(document_sections) > 0:
178
+
179
+ if st.button("πŸ‘οΈ View Upload"):
180
+ st.markdown("**Sections of the uploaded file:**")
181
+ for i, section in enumerate(list(document_sections)):
182
+ st.markdown(f"**Section {i+1}**\n{section}")
183
+
184
+ st.markdown("**Chat with the model:**")
185
+ for i, section in enumerate(list(document_sections)):
186
+ if i in document_responses:
187
+ st.markdown(f"**Section {i+1}**\n{document_responses[i]}")
188
+ else:
189
+ if st.button(f"Chat about Section {i+1}"):
190
+ st.write('Reasoning with your inputs...')
191
+ response = chat_with_model(user_prompt, section)
192
+ st.write('Response:')
193
+ st.write(response)
194
+ document_responses[i] = response
195
+ filename = generate_filename(f"{user_prompt}_section_{i+1}", choice)
196
+ create_file(filename, user_prompt, response)
197
+ st.sidebar.markdown(get_table_download_link(filename), unsafe_allow_html=True)
198
+
199
+ if st.button('πŸ’¬ Chat'):
200
+ st.write('Reasoning with your inputs...')
201
+ response = chat_with_model(user_prompt, ''.join(list(document_sections)))
202
+ st.write('Response:')
203
+ st.write(response)
204
+
205
+ filename = generate_filename(user_prompt, choice)
206
+ create_file(filename, user_prompt, response)
207
+ st.sidebar.markdown(get_table_download_link(filename), unsafe_allow_html=True)
208
+
209
+ all_files = glob.glob("*.*")
210
+ all_files = [file for file in all_files if len(os.path.splitext(file)[0]) >= 20] # exclude files with short names
211
+ all_files.sort(key=lambda x: (os.path.splitext(x)[1], x), reverse=True) # sort by file type and file name in descending order
212
+
213
+ for file in all_files:
214
+ col1, col3 = st.sidebar.columns([5,1]) # adjust the ratio as needed
215
+ with col1:
216
+ try:
217
+ st.markdown(get_table_download_link(file), unsafe_allow_html=True)
218
+ except Exception as e:
219
+ st.error(f"Error occurred while processing file {file}: {str(e)}")
220
+ with col3:
221
+ if st.button("πŸ—‘", key="delete_"+file):
222
+ os.remove(file)
223
+ st.experimental_rerun()
224
+
225
+ if __name__ == "__main__":
226
+ main()