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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
with st.chat_message("user"):
|
| 33 |
+
st.markdown(text_input)
|
| 34 |
+
completion = client.chat.completions.create(model=MODEL, messages=[{"role": m["role"], "content": m["content"]} for m in st.session_state.messages], stream=False)
|
| 35 |
+
return_text = completion.choices[0].message.content
|
| 36 |
+
with st.chat_message("assistant"):
|
| 37 |
+
st.markdown(return_text)
|
| 38 |
+
filename = generate_filename(text_input, "md")
|
| 39 |
+
create_file(filename, text_input, return_text)
|
| 40 |
+
st.session_state.messages.append({"role": "assistant", "content": return_text})
|
| 41 |
+
|
| 42 |
+
def process_text2(MODEL='gpt-4o-2024-05-13', text_input='What is 2+2 and what is an imaginary number'):
|
| 43 |
+
if text_input:
|
| 44 |
+
st.session_state.messages.append({"role": "user", "content": text_input})
|
| 45 |
+
completion = client.chat.completions.create(model=MODEL, messages=st.session_state.messages)
|
| 46 |
+
return_text = completion.choices[0].message.content
|
| 47 |
+
st.write("Assistant: " + return_text)
|
| 48 |
+
filename = generate_filename(text_input, "md")
|
| 49 |
+
create_file(filename, text_input, return_text, should_save=True)
|
| 50 |
+
return return_text
|
| 51 |
+
|
| 52 |
+
def save_image(image_input, filename):
|
| 53 |
+
with open(filename, "wb") as f:
|
| 54 |
+
f.write(image_input.getvalue())
|
| 55 |
+
return filename
|
| 56 |
+
|
| 57 |
+
def process_image(image_input):
|
| 58 |
+
if image_input:
|
| 59 |
+
with st.chat_message("user"):
|
| 60 |
+
st.markdown('Processing image: ' + image_input.name)
|
| 61 |
+
base64_image = base64.b64encode(image_input.read()).decode("utf-8")
|
| 62 |
+
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}"}}]})
|
| 63 |
+
response = client.chat.completions.create(model=MODEL, messages=st.session_state.messages, temperature=0.0)
|
| 64 |
+
image_response = response.choices[0].message.content
|
| 65 |
+
with st.chat_message("assistant"):
|
| 66 |
+
st.markdown(image_response)
|
| 67 |
+
filename_md, filename_img = generate_filename(image_input.name + '- ' + image_response, "md"), image_input.name
|
| 68 |
+
create_file(filename_md, image_response, '', True)
|
| 69 |
+
with open(filename_md, "w", encoding="utf-8") as f:
|
| 70 |
+
f.write(image_response)
|
| 71 |
+
save_image(image_input, filename_img)
|
| 72 |
+
st.session_state.messages.append({"role": "assistant", "content": image_response})
|
| 73 |
+
return image_response
|
| 74 |
+
|
| 75 |
+
def process_audio(audio_input):
|
| 76 |
+
if audio_input:
|
| 77 |
+
st.session_state.messages.append({"role": "user", "content": audio_input})
|
| 78 |
+
transcription = client.audio.transcriptions.create(model="whisper-1", file=audio_input)
|
| 79 |
+
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)
|
| 80 |
+
audio_response = response.choices[0].message.content
|
| 81 |
+
with st.chat_message("assistant"):
|
| 82 |
+
st.markdown(audio_response)
|
| 83 |
+
filename = generate_filename(transcription.text, "md")
|
| 84 |
+
create_file(filename, transcription.text, audio_response, should_save=True)
|
| 85 |
+
st.session_state.messages.append({"role": "assistant", "content": audio_response})
|
| 86 |
+
|
| 87 |
+
def process_audio_and_video(video_input):
|
| 88 |
+
if video_input is not None:
|
| 89 |
+
video_path = save_video(video_input)
|
| 90 |
+
base64Frames, audio_path = process_video(video_path, seconds_per_frame=1)
|
| 91 |
+
transcript = process_audio_for_video(video_input)
|
| 92 |
+
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}"}]})
|
| 93 |
+
response = client.chat.completions.create(model=MODEL, messages=st.session_state.messages, temperature=0)
|
| 94 |
+
video_response = response.choices[0].message.content
|
| 95 |
+
with st.chat_message("assistant"):
|
| 96 |
+
st.markdown(video_response)
|
| 97 |
+
filename = generate_filename(transcript, "md")
|
| 98 |
+
create_file(filename, transcript, video_response, should_save=True)
|
| 99 |
+
st.session_state.messages.append({"role": "assistant", "content": video_response})
|
| 100 |
+
|
| 101 |
+
def process_audio_for_video(video_input):
|
| 102 |
+
if video_input:
|
| 103 |
+
st.session_state.messages.append({"role": "user", "content": video_input})
|
| 104 |
+
transcription = client.audio.transcriptions.create(model="whisper-1", file=video_input)
|
| 105 |
+
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)
|
| 106 |
+
video_response = response.choices[0].message.content
|
| 107 |
+
with st.chat_message("assistant"):
|
| 108 |
+
st.markdown(video_response)
|
| 109 |
+
filename = generate_filename(transcription, "md")
|
| 110 |
+
create_file(filename, transcription, video_response, should_save=True)
|
| 111 |
+
st.session_state.messages.append({"role": "assistant", "content": video_response})
|
| 112 |
+
return video_response
|
| 113 |
+
|
| 114 |
+
def save_video(video_file):
|
| 115 |
+
with open(video_file.name, "wb") as f:
|
| 116 |
+
f.write(video_file.getbuffer())
|
| 117 |
+
return video_file.name
|
| 118 |
+
|
| 119 |
+
def process_video(video_path, seconds_per_frame=2):
|
| 120 |
+
base64Frames, base_video_path = [], os.path.splitext(video_path)[0]
|
| 121 |
+
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)
|
| 122 |
+
curr_frame, frames_to_skip = 0, int(fps * seconds_per_frame)
|
| 123 |
+
while curr_frame < total_frames - 1:
|
| 124 |
+
video.set(cv2.CAP_PROP_POS_FRAMES, curr_frame)
|
| 125 |
+
success, frame = video.read()
|
| 126 |
+
if not success: break
|
| 127 |
+
_, buffer = cv2.imencode(".jpg", frame)
|
| 128 |
+
base64Frames.append(base64.b64encode(buffer).decode("utf-8"))
|
| 129 |
+
curr_frame += frames_to_skip
|
| 130 |
+
video.release()
|
| 131 |
+
audio_path = f"{base_video_path}.mp3"
|
| 132 |
+
clip = VideoFileClip(video_path)
|
| 133 |
+
clip.audio.write_audiofile(audio_path, bitrate="32k")
|
| 134 |
+
clip.audio.close()
|
| 135 |
+
clip.close()
|
| 136 |
+
print(f"Extracted {len(base64Frames)} frames")
|
| 137 |
+
print(f"Extracted audio to {audio_path}")
|
| 138 |
+
return base64Frames, audio_path
|
| 139 |
+
|
| 140 |
+
def save_and_play_audio(audio_recorder):
|
| 141 |
+
audio_bytes = audio_recorder(key='audio_recorder')
|
| 142 |
+
if audio_bytes:
|
| 143 |
+
filename = generate_filename("Recording", "wav")
|
| 144 |
+
with open(filename, 'wb') as f:
|
| 145 |
+
f.write(audio_bytes)
|
| 146 |
+
st.audio(audio_bytes, format="audio/wav")
|
| 147 |
+
return filename
|
| 148 |
+
return None
|
| 149 |
+
|
| 150 |
+
def main():
|
| 151 |
+
st.markdown("##### GPT-4o Omni Model: Text, Audio, Image, & Video")
|
| 152 |
+
option = st.selectbox("Select an option", ("Text", "Image", "Audio", "Video"))
|
| 153 |
+
if option == "Text":
|
| 154 |
+
text_input = st.chat_input("Enter your text:")
|
| 155 |
+
if text_input:
|
| 156 |
+
process_text(text_input)
|
| 157 |
+
elif option == "Image":
|
| 158 |
+
image_input = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
|
| 159 |
+
process_image(image_input)
|
| 160 |
+
elif option == "Audio":
|
| 161 |
+
audio_input = st.file_uploader("Upload an audio file", type=["mp3", "wav"])
|
| 162 |
+
process_audio(audio_input)
|
| 163 |
+
elif option == "Video":
|
| 164 |
+
video_input = st.file_uploader("Upload a video file", type=["mp4"])
|
| 165 |
+
process_audio_and_video(video_input)
|
| 166 |
+
|
| 167 |
+
all_files = sorted(glob.glob("*.md"), key=lambda x: (os.path.splitext(x)[1], x), reverse=True)
|
| 168 |
+
all_files = [file for file in all_files if len(os.path.splitext(file)[0]) >= 10]
|
| 169 |
+
st.sidebar.title("File Gallery")
|
| 170 |
+
for file in all_files:
|
| 171 |
+
with st.sidebar.expander(file), open(file, "r", encoding="utf-8") as f:
|
| 172 |
+
st.code(f.read(), language="markdown")
|
| 173 |
+
|
| 174 |
+
if prompt := st.chat_input("GPT-4o Multimodal ChatBot - What can I help you with?"):
|
| 175 |
+
st.session_state.messages.append({"role": "user", "content": prompt})
|
| 176 |
+
with st.chat_message("user"):
|
| 177 |
+
st.markdown(prompt)
|
| 178 |
+
with st.chat_message("assistant"):
|
| 179 |
+
completion = client.chat.completions.create(model=MODEL, messages=st.session_state.messages, stream=True)
|
| 180 |
+
response = process_text2(text_input=prompt)
|
| 181 |
+
st.session_state.messages.append({"role": "assistant", "content": response})
|
| 182 |
+
|
| 183 |
+
filename = save_and_play_audio(audio_recorder)
|
| 184 |
+
if filename is not None:
|
| 185 |
+
transcript = transcribe_canary(filename)
|
| 186 |
+
result = search_arxiv(transcript)
|
| 187 |
+
st.session_state.messages.append({"role": "user", "content": transcript})
|
| 188 |
+
with st.chat_message("user"):
|
| 189 |
+
st.markdown(transcript)
|
| 190 |
+
with st.chat_message("assistant"):
|
| 191 |
+
completion = client.chat.completions.create(model=MODEL, messages=st.session_state.messages, stream=True)
|
| 192 |
+
response = process_text2(text_input=prompt)
|
| 193 |
+
st.session_state.messages.append({"role": "assistant", "content": response})
|
| 194 |
+
|
| 195 |
+
if __name__ == "__main__":
|
| 196 |
+
main()
|