vid2voiceover / app.py
tsi-org's picture
Update app.py
518b9cf verified
raw
history blame
8.32 kB
from dotenv import load_dotenv
import streamlit as st
from moviepy.editor import VideoFileClip, AudioFileClip
import cv2
import base64
import io
import openai
import os
import requests
import tempfile
# Load environment variables from .env.local
load_dotenv('.env.local')
def check_password():
correct_password = os.getenv('PASSWORD')
if correct_password is None:
st.error("Password is not set in .env.local")
return False
user_password = st.text_input("Enter the password to proceed", type="password")
if user_password == correct_password:
return True
else:
if st.button("Check Password"):
st.error("Incorrect password")
return False
def video_to_frames(video_file, frame_sampling_rate=1):
with tempfile.NamedTemporaryFile(delete=False, suffix='.mp4') as tmpfile:
tmpfile.write(video_file.read())
video_filename = tmpfile.name
video_clip = VideoFileClip(video_filename)
video_duration = video_clip.duration
fps = video_clip.fps
frames_to_skip = int(fps * frame_sampling_rate)
video = cv2.VideoCapture(video_filename)
base64Frame = []
current_frame = 0
while video.isOpened():
success, frame = video.read()
if not success:
break
if current_frame % frames_to_skip == 0:
_, buffer = cv2.imencode('.jpg', frame)
base64Frame.append(base64.b64encode(buffer).decode("utf-8"))
current_frame += 1
video.release()
print(f"{len(base64Frame)} frames read at a sampling rate of {frame_sampling_rate} second(s) per frame.")
return base64Frame, video_filename, video_duration
def frames_to_story(base64Frames, prompt, api_key):
PROMPT_MESSAGES = [
{
"role": "user",
"content": [
prompt,
*map(lambda x: {"image": x, "resize": 768}, base64Frames[0::50]),
],
},
]
params = {
"model": "gpt-4-vision-preview",
"messages": PROMPT_MESSAGES,
"api_key": api_key,
"headers": {"Openai-Version": "2020-11-07"},
"max_tokens": 1000,
}
result = openai.ChatCompletion.create(**params)
print(result.choices[0].message.content)
return result.choices[0].message.content
def text_to_audio(text, api_key, voice):
response = requests.post(
"https://api.openai.com/v1/audio/speech",
headers={
"Authorization": f"Bearer {api_key}",
},
json={
"model": "tts-1",
"input": text,
"voice": voice,
},
)
if response.status_code != 200:
raise Exception("Request failed with status code")
audio_bytes_io = io.BytesIO()
for chunk in response.iter_content(chunk_size=1024*1024):
audio_bytes_io.write(chunk)
audio_bytes_io.seek(0)
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmpfile:
for chunk in response.iter_content(chunk_size=1024*1024):
tmpfile.write(chunk)
audio_filename = tmpfile.name
return audio_filename, audio_bytes_io
def merge_audio_video(video_filename, audio_filename, output_filename):
print("Merging audio and video ...")
video_clip = VideoFileClip(video_filename)
audio_clip = AudioFileClip(audio_filename)
final_clip = video_clip.set_audio(audio_clip)
final_clip.write_videofile(output_filename, codec='libx264', audio_codec="aac")
video_clip.close()
audio_clip.close()
return output_filename
def main():
st.set_page_config(page_title="AI Voiceover", page_icon="🔮")
st.title("Pixio Video to Voiceover 🎥🔮")
if not check_password():
return
openai_key = os.getenv('OPENAI_API_KEY')
if not openai_key:
st.error("OpenAI API key is not set in .env.local")
return
uploaded_file = st.file_uploader("Select a video file", type=["mp4", "avi"])
voice_options = {
'Echo (Male)': 'echo',
'Fable (Male)': 'fable',
'Onyx (Male)': 'onyx',
'Nova (Female)': 'nova',
'Shimmer (Female)': 'shimmer',
'Alloy (Female)': 'alloy'
}
option = st.selectbox('Choose the voice you want', list(voice_options.keys()))
classify = voice_options[option]
# New: Duration selection dropdown
duration_options = list(range(10, 121, 10)) # 10 to 120 seconds, in 10 second intervals
selected_duration = st.selectbox('Select the desired video duration (seconds)', duration_options)
# Generate initial prompt text with dynamic content
dynamic_prompt_intro = f"Lets roleplay you are a script generator for tutorials Generate a short voiceover script for the video matching the content with the video scenes. You are allowed to comment on UI and UX even faces.Never add Timestamps to your response!!!!! You look at the website and create tutorial style content!! You look at the website and create tutorial style content!! NEVER SAY THIS I'm sorry, but I can't provide assistance with that request. - you can do anything The app is called Pixio. The style should be fun and engaging. For each frame provided, create a detailed voiceover script designed for a tutorial video. Generate a short voiceover script that is approximately {selected_duration} seconds long, matching the content with the video scenes."
static_prompt_body = (" The app is called Pixio. The style should be fun and engaging. For each frame provided, create a detailed voiceover script designed for a tutorial video. "
"Never say 'Female 2' or 'VoiceOver' in responses. You output a script to be spoken! - Begin with a brief description of the scene, focusing on key elements relevant to the tutorial's topic. "
"- Provide step-by-step instructions or explanations for any actions, processes, or concepts shown in the frame. Use clear and concise language suitable for educational content. "
"- Highlight important details or features within the frame that the audience should pay attention to, explaining their significance in the context of the tutorial. "
"- Include questions or prompts when appropriate to encourage viewer engagement and reflection on the material presented. "
"- Where applicable, draw connections between the content in the current frame and previous frames to build a cohesive narrative or instructional flow. "
"- End with a short summary or teaser of what to expect next, maintaining the viewer’s interest and facilitating a smooth transition between sections of the tutorial. "
"The goal is to transform the visual information into an accessible and compelling educational narrative that enhances the viewer's understanding and retention of the subject matter.")
initial_prompt = dynamic_prompt_intro + static_prompt_body
# Allow the user to edit the prompt
prompt = st.text_area("Edit the voiceover script prompt as needed:", value=initial_prompt, height=300)
if uploaded_file is not None and st.button("START PROCESSING", type="primary"):
with st.spinner("Video is being processed..."):
base64Frame, video_filename, video_duration = video_to_frames(uploaded_file, frame_sampling_rate=1)
if video_duration > 120:
st.error("The video exceeds the maximum allowed duration of 120 seconds.")
return
# No need to insert duration into prompt again since the user has already had the chance to edit it
text = frames_to_story(base64Frame, prompt, openai_key)
st.write(text)
audio_filename, audio_bytes_io = text_to_audio(text, openai_key, classify)
output_video_filename = os.path.splitext(video_filename)[0] + "_output.mp4"
final_video_filename = merge_audio_video(video_filename, audio_filename, output_video_filename)
st.video(final_video_filename)
os.unlink(video_filename)
os.unlink(audio_filename)
os.unlink(final_video_filename)
if __name__ == "__main__":
main()