awacke1 commited on
Commit
d94cec6
Β·
1 Parent(s): e3c8253

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +172 -3
app.py CHANGED
@@ -16,8 +16,142 @@ from bs4 import BeautifulSoup
16
  from collections import deque
17
  from audio_recorder_streamlit import audio_recorder
18
 
19
- # Function Definitions (kept unchanged)
20
- # ...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
  def chat_with_file_contents(prompt, file_content):
23
  conversation = [{'role': 'system', 'content': 'You are a helpful assistant.'}]
@@ -74,4 +208,39 @@ def main():
74
  else:
75
  if st.button(f"Chat about Section {i+1}"):
76
  st.write('Reasoning with your inputs...')
77
- response = chat_with_model(user
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  from collections import deque
17
  from audio_recorder_streamlit import audio_recorder
18
 
19
+
20
+ def generate_filename(prompt, file_type):
21
+ central = pytz.timezone('US/Central')
22
+ safe_date_time = datetime.now(central).strftime("%m%d_%I%M")
23
+ safe_prompt = "".join(x for x in prompt if x.isalnum())[:45]
24
+ return f"{safe_date_time}_{safe_prompt}.{file_type}"
25
+
26
+ def chat_with_model(prompt, document_section):
27
+ model = model_choice
28
+ conversation = [{'role': 'system', 'content': 'You are a helpful assistant.'}]
29
+ conversation.append({'role': 'user', 'content': prompt})
30
+ if len(document_section)>0:
31
+ conversation.append({'role': 'assistant', 'content': document_section})
32
+ response = openai.ChatCompletion.create(model=model, messages=conversation)
33
+ #return response
34
+ return response['choices'][0]['message']['content']
35
+
36
+ def transcribe_audio(openai_key, file_path, model):
37
+ OPENAI_API_URL = "https://api.openai.com/v1/audio/transcriptions"
38
+ headers = {
39
+ "Authorization": f"Bearer {openai_key}",
40
+ }
41
+ with open(file_path, 'rb') as f:
42
+ data = {'file': f}
43
+ response = requests.post(OPENAI_API_URL, headers=headers, files=data, data={'model': model})
44
+ if response.status_code == 200:
45
+ st.write(response.json())
46
+
47
+ response2 = chat_with_model(response.json().get('text'), '') # *************************************
48
+ st.write('Responses:')
49
+ #st.write(response)
50
+ st.write(response2)
51
+ return response.json().get('text')
52
+ else:
53
+ st.write(response.json())
54
+ st.error("Error in API call.")
55
+ return None
56
+
57
+ def save_and_play_audio(audio_recorder):
58
+ audio_bytes = audio_recorder()
59
+ if audio_bytes:
60
+ filename = generate_filename("Recording", "wav")
61
+ with open(filename, 'wb') as f:
62
+ f.write(audio_bytes)
63
+ st.audio(audio_bytes, format="audio/wav")
64
+ return filename
65
+ return None
66
+
67
+ def create_file(filename, prompt, response):
68
+ if filename.endswith(".txt"):
69
+ with open(filename, 'w') as file:
70
+ file.write(f"Prompt:\n{prompt}\nResponse:\n{response}")
71
+ elif filename.endswith(".htm"):
72
+ with open(filename, 'w') as file:
73
+ file.write(f"<h1>Prompt:</h1> <p>{prompt}</p> <h1>Response:</h1> <p>{response}</p>")
74
+ elif filename.endswith(".md"):
75
+ with open(filename, 'w') as file:
76
+ file.write(f"# Prompt:\n{prompt}\n# Response:\n{response}")
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
+ def get_table_download_link(file_path):
82
+ with open(file_path, 'r') as file:
83
+ data = file.read()
84
+ b64 = base64.b64encode(data.encode()).decode()
85
+ file_name = os.path.basename(file_path)
86
+ ext = os.path.splitext(file_name)[1] # get the file extension
87
+ if ext == '.txt':
88
+ mime_type = 'text/plain'
89
+ elif ext == '.py':
90
+ mime_type = 'text/plain'
91
+ elif ext == '.xlsx':
92
+ mime_type = 'text/plain'
93
+ elif ext == '.csv':
94
+ mime_type = 'text/plain'
95
+ elif ext == '.htm':
96
+ mime_type = 'text/html'
97
+ elif ext == '.md':
98
+ mime_type = 'text/markdown'
99
+ else:
100
+ mime_type = 'application/octet-stream' # general binary data type
101
+ href = f'<a href="data:{mime_type};base64,{b64}" target="_blank" download="{file_name}">{file_name}</a>'
102
+ return href
103
+
104
+
105
+
106
+
107
+
108
+
109
+ def CompressXML(xml_text):
110
+ root = ET.fromstring(xml_text)
111
+ for elem in list(root.iter()):
112
+ if isinstance(elem.tag, str) and 'Comment' in elem.tag:
113
+ elem.parent.remove(elem)
114
+ return ET.tostring(root, encoding='unicode', method="xml")
115
+
116
+ def read_file_content(file,max_length):
117
+ if file.type == "application/json":
118
+ content = json.load(file)
119
+ return str(content)
120
+ elif file.type == "text/html" or file.type == "text/htm":
121
+ content = BeautifulSoup(file, "html.parser")
122
+ return content.text
123
+ elif file.type == "application/xml" or file.type == "text/xml":
124
+ tree = ET.parse(file)
125
+ root = tree.getroot()
126
+ xml = CompressXML(ET.tostring(root, encoding='unicode'))
127
+ return xml
128
+ elif file.type == "text/markdown" or file.type == "text/md":
129
+ md = mistune.create_markdown()
130
+ content = md(file.read().decode())
131
+ return content
132
+ elif file.type == "text/plain":
133
+ return file.getvalue().decode()
134
+ else:
135
+ return ""
136
+
137
+
138
+ # Sidebar and global
139
+ openai.api_key = os.getenv('OPENAI_KEY')
140
+ st.set_page_config(page_title="GPT Streamlit Document Reasoner",layout="wide")
141
+ menu = ["htm", "txt", "xlsx", "csv", "md", "py"] #619
142
+ choice = st.sidebar.selectbox("Output File Type:", menu)
143
+ model_choice = st.sidebar.radio("Select Model:", ('gpt-3.5-turbo', 'gpt-3.5-turbo-0301'))
144
+
145
+ # Audio, transcribe, GPT:
146
+ filename = save_and_play_audio(audio_recorder)
147
+ if filename is not None:
148
+ transcription = transcribe_audio(openai.api_key, filename, "whisper-1")
149
+ st.write(transcription)
150
+ gptOutput = chat_with_model(transcription, '') # *************************************
151
+ filename = generate_filename(transcription, choice)
152
+ create_file(filename, transcription, gptOutput)
153
+ st.sidebar.markdown(get_table_download_link(filename), unsafe_allow_html=True)
154
+
155
 
156
  def chat_with_file_contents(prompt, file_content):
157
  conversation = [{'role': 'system', 'content': 'You are a helpful assistant.'}]
 
208
  else:
209
  if st.button(f"Chat about Section {i+1}"):
210
  st.write('Reasoning with your inputs...')
211
+ response = chat_with_model(user_prompt, section)
212
+ st.write('Response:')
213
+ st.write(response)
214
+ document_responses[i] = response
215
+ filename = generate_filename(f"{user_prompt}_Section_{i+1}", choice)
216
+ create_file(filename, user_prompt, response)
217
+ st.sidebar.markdown(get_table_download_link(filename), unsafe_allow_html=True)
218
+
219
+ # ... document_responses logic remains the same
220
+
221
+ all_files = [file for file in glob.glob("*.{}".format(choice))]
222
+
223
+ for file in all_files:
224
+ col1, col2, col3 = st.sidebar.columns([5,1,1]) # adjust the ratio as needed
225
+ with col1:
226
+ st.markdown(get_table_download_link(file), unsafe_allow_html=True)
227
+ with col2:
228
+ if st.button("πŸ”", key="read_"+file): # search emoji button
229
+ with open(file, 'r') as f:
230
+ file_contents = f.read()
231
+ file_content_area = st.text_area("File Contents:", file_contents, height=100)
232
+ if st.button('πŸ’¬ Chat with file content'):
233
+ st.write('Reasoning with your inputs...')
234
+ response = chat_with_file_contents(user_prompt, file_contents)
235
+ st.write('Response:')
236
+ st.write(response)
237
+ filename = generate_filename(user_prompt, choice)
238
+ create_file(filename, user_prompt, response)
239
+ st.sidebar.markdown(get_table_download_link(filename), unsafe_allow_html=True)
240
+ with col3:
241
+ if st.button("πŸ—‘", key="delete_"+file):
242
+ os.remove(file)
243
+ st.experimental_rerun()
244
+
245
+ if __name__ == "__main__":
246
+ main()