Spaces:
Sleeping
Sleeping
Update app.py
Browse files4 unmodified lines567891011121314151617181920212223242526272829303132333435363 unmodified lines4041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051064 unmodified linesimport numpy as npfrom PIL import Image, ImageDraw, ImageFont# Load the local free voice recognition enginemodel = whisper.load_model("tiny")def make_viral_captions(audio_input):if 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"]:3 unmodified lines"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"),4 unmodified lines56789101112131415161718192021222324252627282930313 unmodified lines353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182834 unmodified linesimport numpy as npfrom PIL import Image, ImageDraw, ImageFont# Initialize lightweight speech capture modelmodel = whisper.load_model("tiny")def make_viral_captions(audio_input):if audio_input is None:return Noneprint("AI is listening to audio...")result = model.transcribe(audio_input, word_timestamps=True)# Safely get the audio lengthduration = result["segments"][-1]["end"] if result.get("segments") else 10.0width, height = 720, 1280fps = 30total_frames = int(duration * fps)output_filename = "finished_captions.mp4"fourcc = cv2.VideoWriter_fourcc(*'mp4v')video_writer = cv2.VideoWriter(output_filename, fourcc, fps, (width, height))all_words = []for segment in result["segments"]:for word in segment["words"]:3 unmodified lines"end": word["end"]})print("Burning frames...")for frame_num in range(total_frames):current_time = frame_num / fps# Build pure green background frameframe = np.zeros((height, width, 3), dtype=np.uint8)frame[:] = (0, 255, 0)current_word = next((w for w in all_words if current_time >= w["start"] and current_time <= w["end"]), None)if current_word:img_pil = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))draw = ImageDraw.Draw(img_pil)font = ImageFont.load_default()text = current_word["text"]text_color = (255, 255, 255) # Whiteif text in ["YOU", "NOW", "START", "NEED", "STOP", "VIRAL", "MONEY"]:text_color = (255, 255, 0) # Yellow# Clean centering math valuestext_x = (width - 100) // 2text_y = (height - 50) // 2# Text Outlinestroke_width = 4for dx in range(-stroke_width, stroke_width + 1):for dy in range(-stroke_width, stroke_width + 1):draw.text((text_x + dx, text_y + dy), text, font=font, fill=(0, 0, 0))# Text Filldraw.text((text_x, text_y), text, font=font, fill=text_color)frame = cv2.cvtColor(np.array(img_pil), cv2.COLOR_RGB2BGR)video_writer.write(frame)video_writer.release()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 final_outputdemo = gr.Interface(fn=make_viral_captions,inputs=gr.Audio(type="filepath", label="Upload Voice Audio Track"),
app.py+14-37