awacke1 commited on
Commit
9b70442
1 Parent(s): 1b49f19

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -176
app.py CHANGED
@@ -1,194 +1,125 @@
1
  import streamlit as st
2
  import openai
3
  from openai import OpenAI
4
- import os
5
- import base64
6
- import cv2
7
  from moviepy.editor import VideoFileClip
8
- import pytz
9
  from datetime import datetime
10
- import glob
11
  from audio_recorder_streamlit import audio_recorder
12
 
13
- # Set API key and organization ID from environment variables
14
- openai.api_key = os.getenv('OPENAI_API_KEY')
15
- openai.organization = os.getenv('OPENAI_ORG_ID')
16
  client = OpenAI(api_key=os.getenv('OPENAI_API_KEY'), organization=os.getenv('OPENAI_ORG_ID'))
17
 
18
- # Define the model to be used
19
  MODEL = "gpt-4o-2024-05-13"
20
 
 
 
 
21
  def generate_filename(prompt, file_type):
22
  central = pytz.timezone('US/Central')
23
  safe_date_time = datetime.now(central).strftime("%m%d_%H%M")
24
- replaced_prompt = prompt.replace(" ", "_").replace("\n", "_")
25
- safe_prompt = "".join(x for x in replaced_prompt if x.isalnum() or x == "_")[:90]
26
  return f"{safe_date_time}_{safe_prompt}.{file_type}"
27
 
28
  def create_file(filename, prompt, response, should_save=True):
29
- if not should_save:
30
- return
31
- base_filename, ext = os.path.splitext(filename)
32
- if ext in ['.txt', '.htm', '.md']:
33
- with open(f"{base_filename}.md", 'w', encoding='utf-8') as file:
34
  file.write(response)
35
 
36
  def process_text(text_input):
37
  if text_input:
38
  st.session_state.messages.append({"role": "user", "content": text_input})
39
-
40
- with st.chat_message("user"):
41
- st.markdown(text_input)
42
-
43
- with st.chat_message("assistant"):
44
- completion = client.chat.completions.create(
45
- model=MODEL,
46
- messages=[
47
- {"role": m["role"], "content": m["content"]}
48
- for m in st.session_state.messages
49
- ],
50
- stream=False
51
- )
52
- return_text = completion.choices[0].message.content
53
- st.write("Assistant: " + return_text)
54
- filename = generate_filename(text_input, "md")
55
- create_file(filename, text_input, return_text, should_save=True)
56
- st.session_state.messages.append({"role": "assistant", "content": return_text})
57
-
58
- def process_text2(MODEL='gpt-4o-2024-05-13', text_input='What is 2+2 and what is an imaginary number'):
59
- if text_input:
60
- st.session_state.messages.append({"role": "user", "content": text_input})
61
- completion = client.chat.completions.create(
62
- model=MODEL,
63
- messages=st.session_state.messages
64
- )
65
  return_text = completion.choices[0].message.content
66
- st.write("Assistant: " + return_text)
67
  filename = generate_filename(text_input, "md")
68
- create_file(filename, text_input, return_text, should_save=True)
69
- return return_text
70
 
71
  def save_image(image_input, filename):
72
- # Save the uploaded image file
73
  with open(filename, "wb") as f:
74
  f.write(image_input.getvalue())
75
  return filename
76
 
77
  def process_image(image_input):
78
  if image_input:
79
- st.markdown('Processing image: ' + image_input.name )
80
  base64_image = base64.b64encode(image_input.read()).decode("utf-8")
81
- st.session_state.messages.append({"role": "user", "content": [
82
- {"type": "text", "text": "Help me understand what is in this picture and list ten facts as markdown outline with appropriate emojis that describes what you see."},
83
- {"type": "image_url", "image_url": {
84
- "url": f"data:image/png;base64,{base64_image}"}
85
- }
86
- ]})
87
- response = client.chat.completions.create(
88
- model=MODEL,
89
- messages=st.session_state.messages,
90
- temperature=0.0,
91
- )
92
  image_response = response.choices[0].message.content
93
- st.markdown(image_response)
94
-
95
- filename_md = generate_filename(image_input.name + '- ' + image_response, "md")
96
- filename_png = filename_md.replace('.md', '.' + image_input.name.split('.')[-1])
97
-
98
  create_file(filename_md, image_response, '', True)
99
-
100
  with open(filename_md, "w", encoding="utf-8") as f:
101
  f.write(image_response)
102
-
103
- filename_img = image_input.name
104
  save_image(image_input, filename_img)
105
-
106
  st.session_state.messages.append({"role": "assistant", "content": image_response})
107
-
108
  return image_response
109
 
110
  def process_audio(audio_input):
111
  if audio_input:
112
  st.session_state.messages.append({"role": "user", "content": audio_input})
113
- transcription = client.audio.transcriptions.create(
114
- model="whisper-1",
115
- file=audio_input,
116
- )
117
- response = client.chat.completions.create(
118
- model=MODEL,
119
- messages=[
120
- {"role": "system", "content":"""You are generating a transcript summary. Create a summary of the provided transcription. Respond in Markdown."""},
121
- {"role": "user", "content": [{"type": "text", "text": f"The audio transcription is: {transcription.text}"}],}
122
- ],
123
- temperature=0,
124
- )
125
  audio_response = response.choices[0].message.content
126
- st.markdown(audio_response)
127
  filename = generate_filename(transcription.text, "md")
128
  create_file(filename, transcription.text, audio_response, should_save=True)
129
  st.session_state.messages.append({"role": "assistant", "content": audio_response})
130
 
 
 
 
 
 
 
 
 
 
 
 
 
 
131
  def process_audio_for_video(video_input):
132
  if video_input:
133
  st.session_state.messages.append({"role": "user", "content": video_input})
134
- transcription = client.audio.transcriptions.create(
135
- model="whisper-1",
136
- file=video_input,
137
- )
138
- response = client.chat.completions.create(
139
- model=MODEL,
140
- messages=[
141
- {"role": "system", "content":"""You are generating a transcript summary. Create a summary of the provided transcription. Respond in Markdown."""},
142
- {"role": "user", "content": [{"type": "text", "text": f"The audio transcription is: {transcription}"}],}
143
- ],
144
- temperature=0,
145
- )
146
  video_response = response.choices[0].message.content
147
- st.markdown(video_response)
148
  filename = generate_filename(transcription, "md")
149
  create_file(filename, transcription, video_response, should_save=True)
150
  st.session_state.messages.append({"role": "assistant", "content": video_response})
151
  return video_response
152
 
153
  def save_video(video_file):
154
- # Save the uploaded video file
155
  with open(video_file.name, "wb") as f:
156
  f.write(video_file.getbuffer())
157
  return video_file.name
158
 
159
  def process_video(video_path, seconds_per_frame=2):
160
- base64Frames = []
161
- base_video_path, _ = os.path.splitext(video_path)
162
- video = cv2.VideoCapture(video_path)
163
- total_frames = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
164
- fps = video.get(cv2.CAP_PROP_FPS)
165
- frames_to_skip = int(fps * seconds_per_frame)
166
- curr_frame = 0
167
-
168
- # Loop through the video and extract frames at specified sampling rate
169
  while curr_frame < total_frames - 1:
170
  video.set(cv2.CAP_PROP_POS_FRAMES, curr_frame)
171
  success, frame = video.read()
172
- if not success:
173
- break
174
  _, buffer = cv2.imencode(".jpg", frame)
175
  base64Frames.append(base64.b64encode(buffer).decode("utf-8"))
176
  curr_frame += frames_to_skip
177
-
178
  video.release()
179
-
180
- # Extract audio from video
181
  audio_path = f"{base_video_path}.mp3"
182
  clip = VideoFileClip(video_path)
183
  clip.audio.write_audiofile(audio_path, bitrate="32k")
184
  clip.audio.close()
185
  clip.close()
186
-
187
  print(f"Extracted {len(base64Frames)} frames")
188
  print(f"Extracted audio to {audio_path}")
189
-
190
  return base64Frames, audio_path
191
-
192
  def save_and_play_audio(audio_recorder):
193
  audio_bytes = audio_recorder(key='audio_recorder')
194
  if audio_bytes:
@@ -198,42 +129,12 @@ def save_and_play_audio(audio_recorder):
198
  st.audio(audio_bytes, format="audio/wav")
199
  return filename
200
  return None
201
-
202
- def process_audio_and_video(video_input):
203
- if video_input is not None:
204
- # Save the uploaded video file
205
- video_path = save_video(video_input)
206
-
207
- # Process the saved video
208
- base64Frames, audio_path = process_video(video_path, seconds_per_frame=1)
209
-
210
- # Get the transcript for the video model call
211
- transcript = process_audio_for_video(video_input)
212
-
213
- # Generate a summary with visual and audio
214
- st.session_state.messages.append({"role": "user", "content": [
215
- "These are the frames from the video.",
216
- *map(lambda x: {"type": "image_url",
217
- "image_url": {"url": f'data:image/jpg;base64,{x}', "detail": "low"}}, base64Frames),
218
- {"type": "text", "text": f"The audio transcription is: {transcript}"}
219
- ]})
220
- response = client.chat.completions.create(
221
- model=MODEL,
222
- messages=st.session_state.messages,
223
- temperature=0,
224
- )
225
- video_response = response.choices[0].message.content
226
- st.markdown(video_response)
227
-
228
- filename = generate_filename(transcript, "md")
229
- create_file(filename, transcript, video_response, should_save=True)
230
- st.session_state.messages.append({"role": "assistant", "content": video_response})
231
 
232
  def main():
233
  st.markdown("##### GPT-4o Omni Model: Text, Audio, Image, & Video")
234
  option = st.selectbox("Select an option", ("Text", "Image", "Audio", "Video"))
235
  if option == "Text":
236
- text_input = st.text_input("Enter your text:")
237
  if text_input:
238
  process_text(text_input)
239
  elif option == "Image":
@@ -245,52 +146,31 @@ def main():
245
  elif option == "Video":
246
  video_input = st.file_uploader("Upload a video file", type=["mp4"])
247
  process_audio_and_video(video_input)
248
-
249
- # File Gallery
250
- all_files = glob.glob("*.md")
251
- all_files = [file for file in all_files if len(os.path.splitext(file)[0]) >= 10] # exclude files with short names
252
- all_files.sort(key=lambda x: (os.path.splitext(x)[1], x), reverse=True) # sort by filename length which puts similar prompts together - consider making date and time of file optional.
253
-
254
  st.sidebar.title("File Gallery")
255
  for file in all_files:
256
- with st.sidebar.expander(file):
257
- with open(file, "r", encoding="utf-8") as f:
258
- file_content = f.read()
259
- st.code(file_content, language="markdown")
260
-
261
- # ChatBot Entry
262
  if prompt := st.chat_input("GPT-4o Multimodal ChatBot - What can I help you with?"):
263
  st.session_state.messages.append({"role": "user", "content": prompt})
264
- with st.chat_message("user"):
265
- st.markdown(prompt)
266
  with st.chat_message("assistant"):
267
- completion = client.chat.completions.create(
268
- model=MODEL,
269
- messages=st.session_state.messages,
270
- stream=True
271
- )
272
- response = process_text2(text_input=prompt)
273
  st.session_state.messages.append({"role": "assistant", "content": response})
274
 
275
- # Transcript to arxiv and client chat completion
276
  filename = save_and_play_audio(audio_recorder)
277
  if filename is not None:
278
  transcript = transcribe_canary(filename)
279
-
280
- # Search ArXiV and get the Summary and Reference Papers Listing
281
  result = search_arxiv(transcript)
282
-
283
- # Start chatbot with transcript:
284
  st.session_state.messages.append({"role": "user", "content": transcript})
285
- with st.chat_message("user"):
286
- st.markdown(transcript)
287
  with st.chat_message("assistant"):
288
- completion = client.chat.completions.create(
289
- model=MODEL,
290
- messages=st.session_state.messages,
291
- stream=True
292
- )
293
- response = process_text2(text_input=prompt)
294
  st.session_state.messages.append({"role": "assistant", "content": response})
295
 
296
  if __name__ == "__main__":
 
1
  import streamlit as st
2
  import openai
3
  from openai import OpenAI
4
+ import os, base64, cv2, glob
 
 
5
  from moviepy.editor import VideoFileClip
 
6
  from datetime import datetime
7
+ import pytz
8
  from audio_recorder_streamlit import audio_recorder
9
 
10
+ openai.api_key, openai.organization = os.getenv('OPENAI_API_KEY'), os.getenv('OPENAI_ORG_ID')
 
 
11
  client = OpenAI(api_key=os.getenv('OPENAI_API_KEY'), organization=os.getenv('OPENAI_ORG_ID'))
12
 
 
13
  MODEL = "gpt-4o-2024-05-13"
14
 
15
+ if 'messages' not in st.session_state:
16
+ st.session_state.messages = []
17
+
18
  def generate_filename(prompt, file_type):
19
  central = pytz.timezone('US/Central')
20
  safe_date_time = datetime.now(central).strftime("%m%d_%H%M")
21
+ safe_prompt = "".join(x for x in prompt.replace(" ", "_").replace("\n", "_") if x.isalnum() or x == "_")[:90]
 
22
  return f"{safe_date_time}_{safe_prompt}.{file_type}"
23
 
24
  def create_file(filename, prompt, response, should_save=True):
25
+ if should_save and os.path.splitext(filename)[1] in ['.txt', '.htm', '.md']:
26
+ with open(os.path.splitext(filename)[0] + ".md", 'w', encoding='utf-8') as file:
 
 
 
27
  file.write(response)
28
 
29
  def process_text(text_input):
30
  if text_input:
31
  st.session_state.messages.append({"role": "user", "content": text_input})
32
+ st.chat_message("user", text_input)
33
+ completion = client.chat.completions.create(model=MODEL, messages=[{"role": m["role"], "content": m["content"]} for m in st.session_state.messages], stream=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  return_text = completion.choices[0].message.content
35
+ st.chat_message("assistant", return_text)
36
  filename = generate_filename(text_input, "md")
37
+ create_file(filename, text_input, return_text)
38
+ st.session_state.messages.append({"role": "assistant", "content": return_text})
39
 
40
  def save_image(image_input, filename):
 
41
  with open(filename, "wb") as f:
42
  f.write(image_input.getvalue())
43
  return filename
44
 
45
  def process_image(image_input):
46
  if image_input:
47
+ st.chat_message("user", 'Processing image: ' + image_input.name)
48
  base64_image = base64.b64encode(image_input.read()).decode("utf-8")
49
+ st.session_state.messages.append({"role": "user", "content": [{"type": "text", "text": "Help me understand what is in this picture and list ten facts as markdown outline with appropriate emojis that describes what you see."}, {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{base64_image}"}}]})
50
+ response = client.chat.completions.create(model=MODEL, messages=st.session_state.messages, temperature=0.0)
 
 
 
 
 
 
 
 
 
51
  image_response = response.choices[0].message.content
52
+ st.chat_message("assistant", image_response)
53
+ filename_md, filename_img = generate_filename(image_input.name + '- ' + image_response, "md"), image_input.name
 
 
 
54
  create_file(filename_md, image_response, '', True)
 
55
  with open(filename_md, "w", encoding="utf-8") as f:
56
  f.write(image_response)
 
 
57
  save_image(image_input, filename_img)
 
58
  st.session_state.messages.append({"role": "assistant", "content": image_response})
 
59
  return image_response
60
 
61
  def process_audio(audio_input):
62
  if audio_input:
63
  st.session_state.messages.append({"role": "user", "content": audio_input})
64
+ transcription = client.audio.transcriptions.create(model="whisper-1", file=audio_input)
65
+ response = client.chat.completions.create(model=MODEL, messages=[{"role": "system", "content":"You are generating a transcript summary. Create a summary of the provided transcription. Respond in Markdown."}, {"role": "user", "content": [{"type": "text", "text": f"The audio transcription is: {transcription.text}"}]}], temperature=0)
 
 
 
 
 
 
 
 
 
 
66
  audio_response = response.choices[0].message.content
67
+ st.chat_message("assistant", audio_response)
68
  filename = generate_filename(transcription.text, "md")
69
  create_file(filename, transcription.text, audio_response, should_save=True)
70
  st.session_state.messages.append({"role": "assistant", "content": audio_response})
71
 
72
+ def process_audio_and_video(video_input):
73
+ if video_input is not None:
74
+ video_path = save_video(video_input)
75
+ base64Frames, audio_path = process_video(video_path, seconds_per_frame=1)
76
+ transcript = process_audio_for_video(video_input)
77
+ st.session_state.messages.append({"role": "user", "content": ["These are the frames from the video.", *map(lambda x: {"type": "image_url", "image_url": {"url": f'data:image/jpg;base64,{x}', "detail": "low"}}, base64Frames), {"type": "text", "text": f"The audio transcription is: {transcript}"}]})
78
+ response = client.chat.completions.create(model=MODEL, messages=st.session_state.messages, temperature=0)
79
+ video_response = response.choices[0].message.content
80
+ st.chat_message("assistant", video_response)
81
+ filename = generate_filename(transcript, "md")
82
+ create_file(filename, transcript, video_response, should_save=True)
83
+ st.session_state.messages.append({"role": "assistant", "content": video_response})
84
+
85
  def process_audio_for_video(video_input):
86
  if video_input:
87
  st.session_state.messages.append({"role": "user", "content": video_input})
88
+ transcription = client.audio.transcriptions.create(model="whisper-1", file=video_input)
89
+ response = client.chat.completions.create(model=MODEL, messages=[{"role": "system", "content":"You are generating a transcript summary. Create a summary of the provided transcription. Respond in Markdown."}, {"role": "user", "content": [{"type": "text", "text": f"The audio transcription is: {transcription}"}]}], temperature=0)
 
 
 
 
 
 
 
 
 
 
90
  video_response = response.choices[0].message.content
91
+ st.chat_message("assistant", video_response)
92
  filename = generate_filename(transcription, "md")
93
  create_file(filename, transcription, video_response, should_save=True)
94
  st.session_state.messages.append({"role": "assistant", "content": video_response})
95
  return video_response
96
 
97
  def save_video(video_file):
 
98
  with open(video_file.name, "wb") as f:
99
  f.write(video_file.getbuffer())
100
  return video_file.name
101
 
102
  def process_video(video_path, seconds_per_frame=2):
103
+ base64Frames, base_video_path = [], os.path.splitext(video_path)[0]
104
+ video, total_frames, fps = cv2.VideoCapture(video_path), int(cv2.VideoCapture(video_path).get(cv2.CAP_PROP_FRAME_COUNT)), cv2.VideoCapture(video_path).get(cv2.CAP_PROP_FPS)
105
+ curr_frame, frames_to_skip = 0, int(fps * seconds_per_frame)
 
 
 
 
 
 
106
  while curr_frame < total_frames - 1:
107
  video.set(cv2.CAP_PROP_POS_FRAMES, curr_frame)
108
  success, frame = video.read()
109
+ if not success: break
 
110
  _, buffer = cv2.imencode(".jpg", frame)
111
  base64Frames.append(base64.b64encode(buffer).decode("utf-8"))
112
  curr_frame += frames_to_skip
 
113
  video.release()
 
 
114
  audio_path = f"{base_video_path}.mp3"
115
  clip = VideoFileClip(video_path)
116
  clip.audio.write_audiofile(audio_path, bitrate="32k")
117
  clip.audio.close()
118
  clip.close()
 
119
  print(f"Extracted {len(base64Frames)} frames")
120
  print(f"Extracted audio to {audio_path}")
 
121
  return base64Frames, audio_path
122
+
123
  def save_and_play_audio(audio_recorder):
124
  audio_bytes = audio_recorder(key='audio_recorder')
125
  if audio_bytes:
 
129
  st.audio(audio_bytes, format="audio/wav")
130
  return filename
131
  return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
 
133
  def main():
134
  st.markdown("##### GPT-4o Omni Model: Text, Audio, Image, & Video")
135
  option = st.selectbox("Select an option", ("Text", "Image", "Audio", "Video"))
136
  if option == "Text":
137
+ text_input = st.chat_input("Enter your text:")
138
  if text_input:
139
  process_text(text_input)
140
  elif option == "Image":
 
146
  elif option == "Video":
147
  video_input = st.file_uploader("Upload a video file", type=["mp4"])
148
  process_audio_and_video(video_input)
149
+
150
+ all_files = sorted(glob.glob("*.md"), key=lambda x: (os.path.splitext(x)[1], x), reverse=True)
151
+ all_files = [file for file in all_files if len(os.path.splitext(file)[0]) >= 10]
 
 
 
152
  st.sidebar.title("File Gallery")
153
  for file in all_files:
154
+ with st.sidebar.expander(file), open(file, "r", encoding="utf-8") as f:
155
+ st.code(f.read(), language="markdown")
156
+
 
 
 
157
  if prompt := st.chat_input("GPT-4o Multimodal ChatBot - What can I help you with?"):
158
  st.session_state.messages.append({"role": "user", "content": prompt})
159
+ st.chat_message("user", prompt)
 
160
  with st.chat_message("assistant"):
161
+ completion = client.chat.completions.create(model=MODEL, messages=st.session_state.messages, stream=True)
162
+ response = process_text(text_input=prompt)
 
 
 
 
163
  st.session_state.messages.append({"role": "assistant", "content": response})
164
 
 
165
  filename = save_and_play_audio(audio_recorder)
166
  if filename is not None:
167
  transcript = transcribe_canary(filename)
 
 
168
  result = search_arxiv(transcript)
 
 
169
  st.session_state.messages.append({"role": "user", "content": transcript})
170
+ st.chat_message("user", transcript)
 
171
  with st.chat_message("assistant"):
172
+ completion = client.chat.completions.create(model=MODEL, messages=st.session_state.messages, stream=True)
173
+ response = process_text(text_input=prompt)
 
 
 
 
174
  st.session_state.messages.append({"role": "assistant", "content": response})
175
 
176
  if __name__ == "__main__":