Spaces:
Sleeping
Sleeping
Update app.py
Browse files12342374567892 unmodified lines121314161516171818202119202122232425262728293031322324333435362728293031373839404142434445464748495051525354555657585960616263646533666735363738686970717240414243447374757677787946808182838485868788894849505152535455909192939495969798991005710110259103104105106import 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, TextClipimport cv2import numpy as npfrom PIL import Image, ImageDraw, ImageFont
# Load the local free voice recognition enginemodel = whisper.load_model("tiny")2 unmodified lines if audio_input is None: return None # 1. Listen and transcribe voice timelines # 1. Transcribe audio to get accurate timestamps print("AI is listening to audio...") result = model.transcribe(audio_input, word_timestamps=True) audio_track = AudioFileClip(audio_input) # 2. Set Up Horizontal 1080x1920 Frame Base green_bg = ColorClip(size=(720, 1280), color=(0, 255, 0)).set_duration(audio_track.duration) # 2. Get audio duration using standard ffmpeg command line info # To keep it lightweight, we preset a max duration or safely calculate it duration = 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, 1280 fps = 30 total_frames = int(duration * fps) output_filename = "finished_captions.mp4" # Build standard OpenCV video exporter pipeline fourcc = cv2.VideoWriter_fourcc(*'mp4v') video_writer = cv2.VideoWriter(output_filename, fourcc, fps, (width, height)) # 3. Process subtitles word-by-word with heavy styles caption_clips = [] # Extract all individual words and their timings cleanly all_words = [] for segment in result["segments"]: for word in segment["words"]: start_time = word["start"] end_time = word["end"] duration = end_time - start_time if duration <= 0: continue 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 sequentially for frame_num in range(total_frames): current_time = frame_num / fps # Create solid green screen canvas array frame frame = np.zeros((height, width, 3), dtype=np.uint8) frame[:] = (0, 255, 0) # BGR Format Green Screen # Find which word is currently playing at this millisecond current_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 fonts img_pil = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)) draw = ImageDraw.Draw(img_pil) # Use default clean Linux bold font try: font = ImageFont.truetype("LiberationSans-Bold.ttf", 90) except IOError: font = ImageFont.load_default() clean_text = word["word"].strip().upper() text = current_word["text"] # Setup dynamic Hormozi text colors text_color = "white" if clean_text in ["YOU", "NOW", "START", "NEED", "STOP", "VIRAL", "MONEY"]: text_color = "yellow" # Setup dynamic Hormozi yellow highlights text_color = (255, 255, 255) # White if text in ["YOU", "NOW", "START", "NEED", "STOP", "VIRAL", "MONEY"]: text_color = (255, 255, 0) # 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")) # Calculate text boundaries to center perfectly bbox = draw.textbbox((0, 0), text, font=font) text_width = bbox[2] - bbox[0] text_height = bbox[3] - bbox[1] text_x = (width - text_width) // 2 text_y = (height - text_height) // 2 caption_clips.append(txt_clip) # Draw Thick Black Text Border Outline (MrBeast style) stroke_width = 6 for 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 Layer draw.text((text_x, text_y), text, font=font, fill=text_color) # 4. Bind tracks directly into clean MP4 container output_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 ) # Convert back to standard video format array frame = 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 track final_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 output_filename return final_output
# Open secure portal# 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