Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789102 unmodified lines1314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162import os# Fix Linux system image permissions automatically before moviepy startsos.system('sed -i "s/none/read,write/g" /etc/ImageMagick-6/policy.xml')import gradio as grimport whisperfrom moviepy.editor import ColorClip, AudioFileClip, CompositeVideoClip, TextClip# Load the local free voice recognition enginemodel = whisper.load_model("tiny")2 unmodified linesif audio_input is None:return None# 1. Listen and transcribe voice timelinesresult = model.transcribe(audio_input, word_timestamps=True)audio_track = AudioFileClip(audio_input)# 2. Set Up Horizontal 1080x1920 Frame Basegreen_bg = ColorClip(size=(720, 1280), color=(0, 255, 0)).set_duration(audio_track.duration)# 3. Process subtitles word-by-word with heavy stylescaption_clips = []for segment in result["segments"]:for word in segment["words"]:start_time = word["start"]end_time = word["end"]duration = end_time - start_timeif duration <= 0:continueclean_text = word["word"].strip().upper()# Setup dynamic Hormozi text colorstext_color = "white"if clean_text in ["YOU", "NOW", "START", "NEED", "STOP", "VIRAL", "MONEY"]:text_color = "yellow"txt_clip = TextClip(clean_text, font="Liberation-Sans-Bold", fontsize=90,color=text_color, stroke_color="black", stroke_width=5,size=(720, 1280), method="caption").set_duration(duration).set_start(start_time).set_position(("center", "center"))caption_clips.append(txt_clip)# 4. Bind tracks directly into clean MP4 containeroutput_filename = "finished_captions.mp4"final_video = CompositeVideoClip([green_bg] + caption_clips).set_audio(audio_track)final_video.write_videofile(output_filename, fps=30, codec="libx264",audio_codec="aac", temp_audiofile="temp.aac",remove_temp=True, logger=None)return output_filename# Open secure portaldemo = gr.Interface(fn=make_viral_captions,inputs=gr.Audio(type="filepath", label="Upload Voice Audio Track"),1234567892 unmodified lines12131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106import osimport gradio as grimport whisperimport cv2import numpy as npfrom PIL import Image, ImageDraw, ImageFont# Load the local free voice recognition enginemodel = whisper.load_model("tiny")2 unmodified linesif audio_input is None:return None# 1. Transcribe audio to get accurate timestampsprint("AI is listening to audio...")result = model.transcribe(audio_input, word_timestamps=True)# 2. Get audio duration using standard ffmpeg command line info# To keep it lightweight, we preset a max duration or safely calculate itduration = result.get("segments", [-1])[-1].get("end", 10.0) if result.get("segments") else 10.0# Video setup settings (720x1280 vertical video frame)width, height = 720, 1280fps = 30total_frames = int(duration * fps)output_filename = "finished_captions.mp4"# Build standard OpenCV video exporter pipelinefourcc = cv2.VideoWriter_fourcc(*'mp4v')video_writer = cv2.VideoWriter(output_filename, fourcc, fps, (width, height))# Extract all individual words and their timings cleanlyall_words = []for segment in result["segments"]:for word in segment["words"]:all_words.append({"text": word["word"].strip().upper(),"start": word["start"],"end": word["end"]})print("Burning MrBeast/Hormozi styled frames...")# 3. Create the video frames sequentiallyfor frame_num in range(total_frames):current_time = frame_num / fps# Create solid green screen canvas array frameframe = np.zeros((height, width, 3), dtype=np.uint8)frame[:] = (0, 255, 0) # BGR Format Green Screen# Find which word is currently playing at this millisecondcurrent_word = next((w for w in all_words if current_time >= w["start"] and current_time <= w["end"]), None)if current_word:# Convert frame format so Pillow can draw clean anti-aliased fontsimg_pil = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))draw = ImageDraw.Draw(img_pil)# Use default clean Linux bold fonttry:font = ImageFont.truetype("LiberationSans-Bold.ttf", 90)except IOError:font = ImageFont.load_default()text = current_word["text"]# Setup dynamic Hormozi yellow highlightstext_color = (255, 255, 255) # Whiteif text in ["YOU", "NOW", "START", "NEED", "STOP", "VIRAL", "MONEY"]:text_color = (255, 255, 0) # Yellow# Calculate text boundaries to center perfectlybbox = draw.textbbox((0, 0), text, font=font)text_width = bbox[2] - bbox[0]text_height = bbox[3] - bbox[1]text_x = (width - text_width) // 2text_y = (height - text_height) // 2# Draw Thick Black Text Border Outline (MrBeast style)stroke_width = 6for dx in range(-stroke_width, stroke_width + 1):for dy in range(-stroke_width, stroke_width + 1):if dx*dx + dy*dy <= stroke_width*stroke_width:draw.text((text_x + dx, text_y + dy), text, font=font, fill=(0, 0, 0))# Draw Core Text Layerdraw.text((text_x, text_y), text, font=font, fill=text_color)# Convert back to standard video format arrayframe = cv2.cvtColor(np.array(img_pil), cv2.COLOR_RGB2BGR)video_writer.write(frame)video_writer.release()# 4. Bind original audio track directly into the finished MP4 file trackfinal_output = "viral_captions_pip.mp4"os.system(f"ffmpeg -y -i {output_filename} -i {audio_input} -c:v copy -c:a aac -map 0:v:0 -map 1:a:0 {final_output}")return final_output# Launch secure web portal layoutdemo = gr.Interface(fn=make_viral_captions,inputs=gr.Audio(type="filepath", label="Upload Voice Audio Track"),
app.py+80-36