pikto awacke1 commited on
Commit
a5975ad
·
0 Parent(s):

Duplicate from awacke1/ChatGPT-Streamlit-2

Browse files

Co-authored-by: Aaron C Wacker <awacke1@users.noreply.huggingface.co>

Files changed (5) hide show
  1. .gitattributes +34 -0
  2. README.md +14 -0
  3. app.py +258 -0
  4. backupapp.py +152 -0
  5. requirements.txt +5 -0
.gitattributes ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tflite filter=lfs diff=lfs merge=lfs -text
29
+ *.tgz filter=lfs diff=lfs merge=lfs -text
30
+ *.wasm filter=lfs diff=lfs merge=lfs -text
31
+ *.xz filter=lfs diff=lfs merge=lfs -text
32
+ *.zip filter=lfs diff=lfs merge=lfs -text
33
+ *.zst filter=lfs diff=lfs merge=lfs -text
34
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: ChatGPT Streamlit 2
3
+ emoji: 😻😻😻
4
+ colorFrom: purple
5
+ colorTo: yellow
6
+ sdk: streamlit
7
+ sdk_version: 1.21.0
8
+ app_file: app.py
9
+ pinned: false
10
+ license: mit
11
+ duplicated_from: awacke1/ChatGPT-Streamlit-2
12
+ ---
13
+
14
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ def generate_filename(prompt, file_type):
20
+ central = pytz.timezone('US/Central')
21
+ safe_date_time = datetime.now(central).strftime("%m%d_%I%M")
22
+ safe_prompt = "".join(x for x in prompt if x.isalnum())[:45]
23
+ return f"{safe_date_time}_{safe_prompt}.{file_type}"
24
+
25
+ def chat_with_model(prompt, document_section):
26
+ model = model_choice
27
+ conversation = [{'role': 'system', 'content': 'You are a helpful assistant.'}]
28
+ conversation.append({'role': 'user', 'content': prompt})
29
+ if len(document_section)>0:
30
+ conversation.append({'role': 'assistant', 'content': document_section})
31
+ response = openai.ChatCompletion.create(model=model, messages=conversation)
32
+ #return response
33
+ return response['choices'][0]['message']['content']
34
+
35
+ def transcribe_audio(openai_key, file_path, model):
36
+ OPENAI_API_URL = "https://api.openai.com/v1/audio/transcriptions"
37
+ headers = {
38
+ "Authorization": f"Bearer {openai_key}",
39
+ }
40
+ with open(file_path, 'rb') as f:
41
+ data = {'file': f}
42
+ response = requests.post(OPENAI_API_URL, headers=headers, files=data, data={'model': model})
43
+ if response.status_code == 200:
44
+ st.write(response.json())
45
+
46
+ response2 = chat_with_model(response.json().get('text'), '') # *************************************
47
+ st.write('Responses:')
48
+ #st.write(response)
49
+ st.write(response2)
50
+ return response.json().get('text')
51
+ else:
52
+ st.write(response.json())
53
+ st.error("Error in API call.")
54
+ return None
55
+
56
+ def save_and_play_audio(audio_recorder):
57
+ audio_bytes = audio_recorder()
58
+ if audio_bytes:
59
+ filename = generate_filename("Recording", "wav")
60
+ with open(filename, 'wb') as f:
61
+ f.write(audio_bytes)
62
+ st.audio(audio_bytes, format="audio/wav")
63
+ return filename
64
+ return None
65
+
66
+ def create_file(filename, prompt, response):
67
+ if filename.endswith(".txt"):
68
+ with open(filename, 'w') as file:
69
+ file.write(f"{prompt}\n{response}")
70
+ elif filename.endswith(".htm"):
71
+ with open(filename, 'w') as file:
72
+ file.write(f"{prompt} {response}")
73
+ elif filename.endswith(".md"):
74
+ with open(filename, 'w') as file:
75
+ file.write(f"{prompt}\n\n{response}")
76
+
77
+ def truncate_document(document, length):
78
+ return document[:length]
79
+ def divide_document(document, max_length):
80
+ return [document[i:i+max_length] for i in range(0, len(document), max_length)]
81
+
82
+ def get_table_download_link(file_path):
83
+ with open(file_path, 'r') as file:
84
+ data = file.read()
85
+ b64 = base64.b64encode(data.encode()).decode()
86
+ file_name = os.path.basename(file_path)
87
+ ext = os.path.splitext(file_name)[1] # get the file extension
88
+ if ext == '.txt':
89
+ mime_type = 'text/plain'
90
+ elif ext == '.py':
91
+ mime_type = 'text/plain'
92
+ elif ext == '.xlsx':
93
+ mime_type = 'text/plain'
94
+ elif ext == '.csv':
95
+ mime_type = 'text/plain'
96
+ elif ext == '.htm':
97
+ mime_type = 'text/html'
98
+ elif ext == '.md':
99
+ mime_type = 'text/markdown'
100
+ else:
101
+ mime_type = 'application/octet-stream' # general binary data type
102
+ href = f'<a href="data:{mime_type};base64,{b64}" target="_blank" download="{file_name}">{file_name}</a>'
103
+ return href
104
+
105
+ def CompressXML(xml_text):
106
+ root = ET.fromstring(xml_text)
107
+ for elem in list(root.iter()):
108
+ if isinstance(elem.tag, str) and 'Comment' in elem.tag:
109
+ elem.parent.remove(elem)
110
+ return ET.tostring(root, encoding='unicode', method="xml")
111
+
112
+ def read_file_content(file,max_length):
113
+ if file.type == "application/json":
114
+ content = json.load(file)
115
+ return str(content)
116
+ elif file.type == "text/html" or file.type == "text/htm":
117
+ content = BeautifulSoup(file, "html.parser")
118
+ return content.text
119
+ elif file.type == "application/xml" or file.type == "text/xml":
120
+ tree = ET.parse(file)
121
+ root = tree.getroot()
122
+ xml = CompressXML(ET.tostring(root, encoding='unicode'))
123
+ return xml
124
+ elif file.type == "text/markdown" or file.type == "text/md":
125
+ md = mistune.create_markdown()
126
+ content = md(file.read().decode())
127
+ return content
128
+ elif file.type == "text/plain":
129
+ return file.getvalue().decode()
130
+ else:
131
+ return ""
132
+
133
+
134
+
135
+ def chat_with_file_contents(prompt, file_content):
136
+ conversation = [{'role': 'system', 'content': 'You are a helpful assistant.'}]
137
+ conversation.append({'role': 'user', 'content': prompt})
138
+ if len(file_content)>0:
139
+ conversation.append({'role': 'assistant', 'content': file_content})
140
+ response = openai.ChatCompletion.create(model=model_choice, messages=conversation)
141
+ return response['choices'][0]['message']['content']
142
+
143
+
144
+ # Sidebar and global
145
+ openai.api_key = os.getenv('OPENAI_KEY')
146
+ st.set_page_config(page_title="GPT Streamlit Document Reasoner",layout="wide")
147
+ menu = ["htm", "txt", "xlsx", "csv", "md", "py"] #619
148
+ choice = st.sidebar.selectbox("Output File Type:", menu)
149
+ model_choice = st.sidebar.radio("Select Model:", ('gpt-3.5-turbo', 'gpt-3.5-turbo-0301'))
150
+
151
+ # Audio, transcribe, GPT:
152
+ filename = save_and_play_audio(audio_recorder)
153
+ if filename is not None:
154
+ transcription = transcribe_audio(openai.api_key, filename, "whisper-1")
155
+ st.write(transcription)
156
+ gptOutput = chat_with_model(transcription, '') # *************************************
157
+ filename = generate_filename(transcription, choice)
158
+ create_file(filename, transcription, gptOutput)
159
+ st.sidebar.markdown(get_table_download_link(filename), unsafe_allow_html=True)
160
+
161
+
162
+ def main():
163
+ user_prompt = st.text_area("Enter prompts, instructions & questions:", '', height=100)
164
+
165
+ collength, colupload = st.columns([2,3]) # adjust the ratio as needed
166
+ with collength:
167
+ #max_length = 12000 - optimal for gpt35 turbo. 2x=24000 for gpt4. 8x=96000 for gpt4-32k.
168
+ max_length = st.slider("File section length for large files", min_value=1000, max_value=128000, value=12000, step=1000)
169
+ with colupload:
170
+ uploaded_file = st.file_uploader("Add a file for context:", type=["xml", "json", "xlsx","csv","html", "htm", "md", "txt"])
171
+
172
+ document_sections = deque()
173
+ document_responses = {}
174
+
175
+ if uploaded_file is not None:
176
+ file_content = read_file_content(uploaded_file, max_length)
177
+ document_sections.extend(divide_document(file_content, max_length))
178
+
179
+ if len(document_sections) > 0:
180
+
181
+ if st.button("👁️ View Upload"):
182
+ st.markdown("**Sections of the uploaded file:**")
183
+ for i, section in enumerate(list(document_sections)):
184
+ st.markdown(f"**Section {i+1}**\n{section}")
185
+
186
+ st.markdown("**Chat with the model:**")
187
+ for i, section in enumerate(list(document_sections)):
188
+ if i in document_responses:
189
+ st.markdown(f"**Section {i+1}**\n{document_responses[i]}")
190
+ else:
191
+ if st.button(f"Chat about Section {i+1}"):
192
+ st.write('Reasoning with your inputs...')
193
+ response = chat_with_model(user_prompt, section) # *************************************
194
+ st.write('Response:')
195
+ st.write(response)
196
+ document_responses[i] = response
197
+ filename = generate_filename(f"{user_prompt}_section_{i+1}", choice)
198
+ create_file(filename, user_prompt, response)
199
+ st.sidebar.markdown(get_table_download_link(filename), unsafe_allow_html=True)
200
+
201
+ if st.button('💬 Chat'):
202
+ st.write('Reasoning with your inputs...')
203
+ response = chat_with_model(user_prompt, ''.join(list(document_sections))) # *************************************
204
+ st.write('Response:')
205
+ st.write(response)
206
+
207
+ filename = generate_filename(user_prompt, choice)
208
+ create_file(filename, user_prompt, response)
209
+ st.sidebar.markdown(get_table_download_link(filename), unsafe_allow_html=True)
210
+
211
+ all_files = glob.glob("*.*")
212
+ all_files = [file for file in all_files if len(os.path.splitext(file)[0]) >= 20] # exclude files with short names
213
+ all_files.sort(key=lambda x: (os.path.splitext(x)[1], x), reverse=True) # sort by file type and file name in descending order
214
+
215
+ # sidebar of files
216
+ file_contents=''
217
+ next_action=''
218
+ for file in all_files:
219
+ col1, col2, col3, col4, col5 = st.sidebar.columns([1,6,1,1,1]) # adjust the ratio as needed
220
+ with col1:
221
+ if st.button("🌐", key="md_"+file): # md emoji button
222
+ with open(file, 'r') as f:
223
+ file_contents = f.read()
224
+ next_action='md'
225
+ with col2:
226
+ st.markdown(get_table_download_link(file), unsafe_allow_html=True)
227
+ with col3:
228
+ if st.button("📂", key="open_"+file): # open emoji button
229
+ with open(file, 'r') as f:
230
+ file_contents = f.read()
231
+ next_action='open'
232
+ with col4:
233
+ if st.button("🔍", key="read_"+file): # search emoji button
234
+ with open(file, 'r') as f:
235
+ file_contents = f.read()
236
+ next_action='search'
237
+ with col5:
238
+ if st.button("🗑", key="delete_"+file):
239
+ os.remove(file)
240
+ st.experimental_rerun()
241
+
242
+ if len(file_contents) > 0:
243
+ if next_action=='open':
244
+ file_content_area = st.text_area("File Contents:", file_contents, height=500)
245
+ if next_action=='md':
246
+ st.markdown(file_contents)
247
+ if next_action=='search':
248
+ file_content_area = st.text_area("File Contents:", file_contents, height=500)
249
+ st.write('Reasoning with your inputs...')
250
+ response = chat_with_file_contents(user_prompt, file_contents)
251
+ st.write('Response:')
252
+ st.write(response)
253
+ filename = generate_filename(file_content_area, choice)
254
+ create_file(filename, file_content_area, response)
255
+ st.sidebar.markdown(get_table_download_link(filename), unsafe_allow_html=True)
256
+
257
+ if __name__ == "__main__":
258
+ main()
backupapp.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 textwrap
10
+
11
+ from datetime import datetime
12
+ from openai import ChatCompletion
13
+ from xml.etree import ElementTree as ET
14
+ from bs4 import BeautifulSoup
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("Choose output file type to save results", menu)
23
+ choicePrefix = "Output and download file set to "
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 truncate_document(document, length):
36
+ return document[:length]
37
+
38
+ def chat_with_model(prompts):
39
+ model = "gpt-3.5-turbo"
40
+ conversation = [{'role': 'system', 'content': 'You are a helpful assistant.'}]
41
+ conversation.extend([{'role': 'user', 'content': prompt} for prompt in prompts])
42
+ response = openai.ChatCompletion.create(model=model, messages=conversation)
43
+ return response['choices'][0]['message']['content']
44
+
45
+ def generate_filename(prompt, file_type):
46
+ central = pytz.timezone('US/Central')
47
+ safe_date_time = datetime.now(central).strftime("%m%d_%I%M")
48
+ safe_prompt = "".join(x for x in prompt if x.isalnum())[:28]
49
+ return f"{safe_date_time}_{safe_prompt}.{file_type}"
50
+
51
+ def create_file(filename, prompt, response):
52
+ if filename.endswith(".txt"):
53
+ with open(filename, 'w') as file:
54
+ file.write(f"Prompt:\n{prompt}\nResponse:\n{response}")
55
+ elif filename.endswith(".htm"):
56
+ with open(filename, 'w') as file:
57
+ file.write(f"<h1>Prompt:</h1> <p>{prompt}</p> <h1>Response:</h1> <p>{response}</p>")
58
+ elif filename.endswith(".md"):
59
+ with open(filename, 'w') as file:
60
+ file.write(f"# Prompt:\n{prompt}\n# Response:\n{response}")
61
+
62
+ def get_table_download_link(file_path):
63
+ with open(file_path, 'r') as file:
64
+ data = file.read()
65
+ b64 = base64.b64encode(data.encode()).decode()
66
+ file_name = os.path.basename(file_path)
67
+ ext = os.path.splitext(file_name)[1]
68
+
69
+ if ext == '.txt':
70
+ mime_type = 'text/plain'
71
+ elif ext == '.htm':
72
+ mime_type = 'text/html'
73
+ elif ext == '.md':
74
+ mime_type = 'text/markdown'
75
+ else:
76
+ mime_type = 'application/octet-stream'
77
+
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
+ uploaded_file = st.file_uploader("Choose a file", type=["xml", "json", "html", "htm", "md", "txt"])
112
+
113
+ if st.button('💬 Chat'):
114
+ st.write('Thinking and Reasoning with your inputs...')
115
+ file_content = ""
116
+
117
+ if user_prompt:
118
+ prompts = textwrap.wrap(user_prompt, max_length)
119
+ for prompt in prompts:
120
+ response = chat_with_model([prompt])
121
+ st.write('Response:')
122
+ st.write(response)
123
+ filename = generate_filename(prompt, choice)
124
+ create_file(filename, prompt, response)
125
+ st.sidebar.markdown(get_table_download_link(filename), unsafe_allow_html=True)
126
+
127
+ if uploaded_file is not None:
128
+ file_content = read_file_content(uploaded_file, max_length)
129
+ document_parts = textwrap.wrap(file_content, max_length)
130
+ for part in document_parts:
131
+ response = chat_with_model([part])
132
+ st.write('Response:')
133
+ st.write(response)
134
+ filename = generate_filename(part, choice)
135
+ create_file(filename, part, response)
136
+ st.sidebar.markdown(get_table_download_link(filename), unsafe_allow_html=True)
137
+
138
+ if len(file_content) > 0:
139
+ st.text_area("File Content:", file_content, height=400) # Display file content in a scrollable text box
140
+
141
+ all_files = glob.glob("*.txt") + glob.glob("*.htm") + glob.glob("*.md")
142
+ for file in all_files:
143
+ col1, col2 = st.sidebar.columns([4,1])
144
+ with col1:
145
+ st.markdown(get_table_download_link(file), unsafe_allow_html=True)
146
+ with col2:
147
+ if st.button("🗑", key=file):
148
+ os.remove(file)
149
+ st.experimental_rerun()
150
+
151
+ if __name__ == "__main__":
152
+ main()
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ openai
2
+ beautifulsoup4
3
+ mistune
4
+ pytz
5
+ audio-recorder-streamlit