awacke1 commited on
Commit
2eae422
·
verified ·
1 Parent(s): e504b85

Delete app.0523.plainvanilla.py

Browse files
Files changed (1) hide show
  1. app.0523.plainvanilla.py +0 -237
app.0523.plainvanilla.py DELETED
@@ -1,237 +0,0 @@
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
- from PIL import Image
10
-
11
- openai.api_key, openai.organization = os.getenv('OPENAI_API_KEY'), os.getenv('OPENAI_ORG_ID')
12
- client = OpenAI(api_key=os.getenv('OPENAI_API_KEY'), organization=os.getenv('OPENAI_ORG_ID'))
13
-
14
- MODEL = "gpt-4o-2024-05-13"
15
-
16
- if 'messages' not in st.session_state:
17
- st.session_state.messages = []
18
-
19
- def generate_filename(prompt, file_type):
20
- central = pytz.timezone('US/Central')
21
- safe_date_time = datetime.now(central).strftime("%m%d_%H%M")
22
- safe_prompt = "".join(x for x in prompt.replace(" ", "_").replace("\n", "_") if x.isalnum() or x == "_")[:90]
23
- return f"{safe_date_time}_{safe_prompt}.{file_type}"
24
-
25
- def create_file(filename, prompt, response, should_save=True):
26
- if should_save and os.path.splitext(filename)[1] in ['.txt', '.htm', '.md']:
27
- with open(os.path.splitext(filename)[0] + ".md", 'w', encoding='utf-8') as file:
28
- file.write(response)
29
-
30
- def process_text(text_input):
31
- if text_input:
32
- st.session_state.messages.append({"role": "user", "content": text_input})
33
- with st.chat_message("user"):
34
- st.markdown(text_input)
35
- completion = client.chat.completions.create(model=MODEL, messages=[{"role": m["role"], "content": m["content"]} for m in st.session_state.messages], stream=False)
36
- return_text = completion.choices[0].message.content
37
- with st.chat_message("assistant"):
38
- st.markdown(return_text)
39
- filename = generate_filename(text_input, "md")
40
- create_file(filename, text_input, return_text)
41
- st.session_state.messages.append({"role": "assistant", "content": return_text})
42
-
43
- def process_text2(MODEL='gpt-4o-2024-05-13', text_input='What is 2+2 and what is an imaginary number'):
44
- if text_input:
45
- st.session_state.messages.append({"role": "user", "content": text_input})
46
- completion = client.chat.completions.create(model=MODEL, messages=st.session_state.messages)
47
- return_text = completion.choices[0].message.content
48
- st.write("Assistant: " + return_text)
49
- filename = generate_filename(text_input, "md")
50
- create_file(filename, text_input, return_text, should_save=True)
51
- return return_text
52
-
53
- def save_image(image_input, filename):
54
- with open(filename, "wb") as f:
55
- f.write(image_input.getvalue())
56
- return filename
57
-
58
- def process_image(image_input):
59
- if image_input:
60
- with st.chat_message("user"):
61
- st.markdown('Processing image: ' + image_input.name)
62
- base64_image = base64.b64encode(image_input.read()).decode("utf-8")
63
- 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}"}}]})
64
- response = client.chat.completions.create(model=MODEL, messages=st.session_state.messages, temperature=0.0)
65
- image_response = response.choices[0].message.content
66
- with st.chat_message("assistant"):
67
- st.markdown(image_response)
68
- filename_md, filename_img = generate_filename(image_input.name + '- ' + image_response, "md"), image_input.name
69
- create_file(filename_md, image_response, '', True)
70
- with open(filename_md, "w", encoding="utf-8") as f:
71
- f.write(image_response)
72
- save_image(image_input, filename_img)
73
- st.session_state.messages.append({"role": "assistant", "content": image_response})
74
- return image_response
75
-
76
- def process_audio(audio_input):
77
- if audio_input:
78
- st.session_state.messages.append({"role": "user", "content": audio_input})
79
- transcription = client.audio.transcriptions.create(model="whisper-1", file=audio_input)
80
- 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)
81
- audio_response = response.choices[0].message.content
82
- with st.chat_message("assistant"):
83
- st.markdown(audio_response)
84
- filename = generate_filename(transcription.text, "md")
85
- create_file(filename, transcription.text, audio_response, should_save=True)
86
- st.session_state.messages.append({"role": "assistant", "content": audio_response})
87
-
88
- def process_audio_and_video(video_input):
89
- if video_input is not None:
90
- video_path = save_video(video_input)
91
- base64Frames, audio_path = process_video(video_path, seconds_per_frame=1)
92
- transcript = process_audio_for_video(video_input)
93
- 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}"}]})
94
- response = client.chat.completions.create(model=MODEL, messages=st.session_state.messages, temperature=0)
95
- video_response = response.choices[0].message.content
96
- with st.chat_message("assistant"):
97
- st.markdown(video_response)
98
- filename = generate_filename(transcript, "md")
99
- create_file(filename, transcript, video_response, should_save=True)
100
- st.session_state.messages.append({"role": "assistant", "content": video_response})
101
-
102
- def process_audio_for_video(video_input):
103
- if video_input:
104
- st.session_state.messages.append({"role": "user", "content": video_input})
105
- transcription = client.audio.transcriptions.create(model="whisper-1", file=video_input)
106
- 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)
107
- video_response = response.choices[0].message.content
108
- with st.chat_message("assistant"):
109
- st.markdown(video_response)
110
- filename = generate_filename(transcription.text, "md")
111
- create_file(filename, transcription.text, video_response, should_save=True)
112
- st.session_state.messages.append({"role": "assistant", "content": video_response})
113
- return video_response
114
-
115
- def save_video(video_file):
116
- with open(video_file.name, "wb") as f:
117
- f.write(video_file.getbuffer())
118
- return video_file.name
119
-
120
- def process_video(video_path, seconds_per_frame=2):
121
- base64Frames, base_video_path = [], os.path.splitext(video_path)[0]
122
- 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)
123
- curr_frame, frames_to_skip = 0, int(fps * seconds_per_frame)
124
- while curr_frame < total_frames - 1:
125
- video.set(cv2.CAP_PROP_POS_FRAMES, curr_frame)
126
- success, frame = video.read()
127
- if not success: break
128
- _, buffer = cv2.imencode(".jpg", frame)
129
- base64Frames.append(base64.b64encode(buffer).decode("utf-8"))
130
- curr_frame += frames_to_skip
131
- video.release()
132
- audio_path = f"{base_video_path}.mp3"
133
- clip = VideoFileClip(video_path)
134
- clip.audio.write_audiofile(audio_path, bitrate="32k")
135
- clip.audio.close()
136
- clip.close()
137
- print(f"Extracted {len(base64Frames)} frames")
138
- print(f"Extracted audio to {audio_path}")
139
- return base64Frames, audio_path
140
-
141
- def save_and_play_audio(audio_recorder):
142
- audio_bytes = audio_recorder(key='audio_recorder')
143
- if audio_bytes:
144
- filename = generate_filename("Recording", "wav")
145
- with open(filename, 'wb') as f:
146
- f.write(audio_bytes)
147
- st.audio(audio_bytes, format="audio/wav")
148
- return filename
149
- return None
150
-
151
- @st.cache_resource
152
- def display_videos_and_links(num_columns):
153
- video_files = [f for f in os.listdir('.') if f.endswith('.mp4')]
154
- if not video_files:
155
- st.write("No MP4 videos found in the current directory.")
156
- return
157
- video_files_sorted = sorted(video_files, key=lambda x: len(x.split('.')[0]))
158
- cols = st.columns(num_columns) # Define num_columns columns outside the loop
159
- col_index = 0 # Initialize column index
160
- for video_file in video_files_sorted:
161
- with cols[col_index % num_columns]: # Use modulo 2 to alternate between the first and second column
162
- k = video_file.split('.')[0] # Assumes keyword is the file name without extension
163
- st.video(video_file, format='video/mp4', start_time=0)
164
- display_glossary_entity(k)
165
- col_index += 1 # Increment column index to place the next video in the next column
166
-
167
- @st.cache_resource
168
- def display_images_and_wikipedia_summaries(num_columns=4):
169
- image_files = [f for f in os.listdir('.') if f.endswith('.png')]
170
- if not image_files:
171
- st.write("No PNG images found in the current directory.")
172
- return
173
- image_files_sorted = sorted(image_files, key=lambda x: len(x.split('.')[0]))
174
- cols = st.columns(num_columns) # Use specified num_columns for layout
175
- col_index = 0 # Initialize column index for cycling through columns
176
- for image_file in image_files_sorted:
177
- with cols[col_index % num_columns]: # Cycle through columns based on num_columns
178
- image = Image.open(image_file)
179
- st.image(image, caption=image_file, use_column_width=True)
180
- k = image_file.split('.')[0] # Assumes keyword is the file name without extension
181
- #display_glossary_entity(k)
182
- col_index += 1 # Increment to move to the next column in the next iteration
183
-
184
- def main():
185
- st.markdown("##### GPT-4o Omni Model: Text, Audio, Image, & Video")
186
- option = st.selectbox("Select an option", ("Text", "Image", "Audio", "Video"))
187
- if option == "Text":
188
- text_input = st.chat_input("Enter your text:")
189
- if text_input:
190
- process_text(text_input)
191
- elif option == "Image":
192
- image_input = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
193
- process_image(image_input)
194
- elif option == "Audio":
195
- audio_input = st.file_uploader("Upload an audio file", type=["mp3", "wav"])
196
- process_audio(audio_input)
197
- elif option == "Video":
198
- video_input = st.file_uploader("Upload a video file", type=["mp4"])
199
- process_audio_and_video(video_input)
200
-
201
- all_files = sorted(glob.glob("*.md"), key=lambda x: (os.path.splitext(x)[1], x), reverse=True)
202
- all_files = [file for file in all_files if len(os.path.splitext(file)[0]) >= 10]
203
- st.sidebar.title("File Gallery")
204
- for file in all_files:
205
- with st.sidebar.expander(file), open(file, "r", encoding="utf-8") as f:
206
- st.code(f.read(), language="markdown")
207
-
208
- if prompt := st.chat_input("GPT-4o Multimodal ChatBot - What can I help you with?"):
209
- st.session_state.messages.append({"role": "user", "content": prompt})
210
- with st.chat_message("user"):
211
- st.markdown(prompt)
212
- with st.chat_message("assistant"):
213
- completion = client.chat.completions.create(model=MODEL, messages=st.session_state.messages, stream=True)
214
- response = process_text2(text_input=prompt)
215
- st.session_state.messages.append({"role": "assistant", "content": response})
216
-
217
- filename = save_and_play_audio(audio_recorder)
218
- if filename is not None:
219
- transcript = transcribe_canary(filename)
220
- result = search_arxiv(transcript)
221
- st.session_state.messages.append({"role": "user", "content": transcript})
222
- with st.chat_message("user"):
223
- st.markdown(transcript)
224
- with st.chat_message("assistant"):
225
- completion = client.chat.completions.create(model=MODEL, messages=st.session_state.messages, stream=True)
226
- response = process_text2(text_input=prompt)
227
- st.session_state.messages.append({"role": "assistant", "content": response})
228
-
229
- # Image and Video Galleries
230
- num_columns_images=st.slider(key="num_columns_images", label="Choose Number of Image Columns", min_value=1, max_value=15, value=5)
231
- display_images_and_wikipedia_summaries(num_columns_images) # Image Jump Grid
232
-
233
- num_columns_video=st.slider(key="num_columns_video", label="Choose Number of Video Columns", min_value=1, max_value=15, value=5)
234
- display_videos_and_links(num_columns_video) # Video Jump Grid
235
-
236
- if __name__ == "__main__":
237
- main()