Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100import osimport subprocessimport gradio as grimport whispertry:model = whisper.load_model("tiny")except Exception as e:model = Nonedef generate_viral_caption_pipeline(audio_input):if audio_input is None or model is None:return Noneprint("[SYSTEM] Executing AI Speech Audio Transcription Matrix...")result = model.transcribe(audio_input, word_timestamps=True)duration = 10.0if result.get("segments"):duration = result["segments"][-1]["end"]ass_filename = "subtitles.ass"video_raw = "canvas_base.mp4"final_output = "viral_captions_pip.mp4"# ----------------------------------------------------# GENERATE ADVANCED SUB-STATION ALPHA VECTOR SCRIPT# ----------------------------------------------------with open(ass_filename, "w", encoding="utf-8") as f:f.write("[Script Info]\nScriptType: v4.00+\nPlayResX: 720\nPlayResY: 1280\n\n")f.write("[V4+ Styles]\nFormat: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\n")# Thick 4px black borders, Arial Black font for that signature high-end layout stylef.write("Style: Hormozi,Arial Black,42,&H00FFFFFF,&H000000FF,&H00000000,&H00000000,-1,0,0,0,100,100,2,0,1,4,1,5,10,10,10,1\n\n")f.write("[Events]\nFormat: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n")for segment in result.get("segments", []):for word in segment.get("words", []):start_time = word["start"]end_time = word["end"]def format_ass_time(secs):h = int(secs // 3600)m = int((secs % 3600) // 60)s = secs % 60return f"{h}:{m:02d}:{s:05.2f}"t_start = format_ass_time(start_time)t_end = format_ass_time(end_time)raw_text = word["word"].strip().upper()# Setup Advanced Word Color Matching Playbooks# Note: ASS Color format uses &H00BBGGRR (Blue Blue, Green Green, Red Red)# π‘ YELLOW preset wordsyellow_words = ["YOU", "NOW", "START", "NEED", "LOOK", "LISTEN", "THIS", "WAIT", "WATCH"]# π’ GREEN preset wordsgreen_words = ["MONEY", "CASH", "WIN", "BEST", "PERFECT", "FAST", "POWERFUL", "SMART", "MAKE", "MAKING"]# π΄ RED preset wordsred_words = ["STOP", "FREEZE", "WRONG", "BAD", "CUT", "FAIL", "NO", "DON'T", "NEVER", "CLOSE"]# π PINK preset wordspink_words = ["VIRAL", "INSANE", "SHOCKING", "SECRET", "WHAT", "CRAZY", "WOW", "AMAZING", "BROKE"]if raw_text in yellow_words:formatted_text = f"{{\\1c&H0000FFFF\\fscx112\\fscy112}}{raw_text}{{\\r}}"elif raw_text in green_words:formatted_text = f"{{\\1c&H0000FF00\\fscx112\\fscy112}}{raw_text}{{\\r}}"elif raw_text in red_words:formatted_text = f"{{\\1c&H000000FF\\fscx112\\fscy112}}{raw_text}{{\\r}}"elif raw_text in pink_words:formatted_text = f"{{\\1c&H00CC00FF\\fscx112\\fscy112}}{raw_text}{{\\r}}"else:# Standard elegant white for normal fill text wordsformatted_text = f"{{\\fscx100\\fscy100}}{raw_text}{{\\r}}"f.write(f"Dialogue: 0,{t_start},{t_end},Hormozi,,0,0,0,,{formatted_text}\n")# ----------------------------------------------------# HARDWARE FUSION GRAPHICS CHANNELS# ----------------------------------------------------subprocess.run(['ffmpeg', '-y', '-f', 'lavfi', '-i', f'color=c=0x00ff00:s=720x1280:d={duration}:r=30','-c:v', 'libx264', '-pix_fmt', 'yuv420p', video_raw], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)subprocess.run(['ffmpeg', '-y', '-i', video_raw, '-i', audio_input,'-vf', f'ass={ass_filename}', '-c:v', 'libx264', '-c:a', 'aac','-map', '0:v:0', '-map', '1:a:0', '-shortest', final_output], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)return final_outputdemo = gr.Interface(fn=generate_viral_caption_pipeline,inputs=gr.Audio(type="filepath", label="Input Audio Node File"),outputs=gr.Video(label="Output High-Speed Green Screen MP4 Node File"),title="Viral Caption Engine Pro")demo.launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114import osimport gradio as grimport whisperimport cv2import numpy as np# Load the lightning fast voice frameworktry:model = whisper.load_model("tiny")except Exception as e:model = Nonedef make_viral_captions(audio_input):if audio_input is None or model is None:return Noneprint("AI is listening to audio...")result = model.transcribe(audio_input, word_timestamps=True)# Safely calculate total duration lengthduration = 10.0if result.get("segments"):duration = result["segments"][-1]["end"]width, height = 720, 1280fps = 30total_frames = int(duration * fps)output_filename = "raw_canvas_video.mp4"final_output = "viral_captions_pip.mp4"# Setup professional high-speed video encoder channelfourcc = cv2.VideoWriter_fourcc(*'mp4v')video_writer = cv2.VideoWriter(output_filename, fourcc, fps, (width, height))# Extract all text items cleanly into a flat timed list arrayall_words = []for segment in result.get("segments", []):for word in segment.get("words", []):all_words.append({"text": word["word"].strip().upper(),"start": word["start"],"end": word["end"]})print("Rendering vector text tracks...")for frame_num in range(total_frames):current_time = frame_num / fps# Build pristine solid green background matrix layer blockframe = np.zeros((height, width, 3), dtype=np.uint8)frame[:] = (0, 255, 0) # Pure Green BGR Plane# Match current playback millisecond timestamp against our text track arraycurrent_word = Nonefor w in all_words:if current_time >= w["start"] and current_time <= w["end"]:current_word = wbreakif current_word:text = current_word["text"]# π¨ The Creator Color Playbook (BGR Format)# Standard pristine white filltext_color = (255, 255, 255)# π‘ YELLOW highlights for focus/action wordsif text in ["YOU", "NOW", "START", "NEED", "LOOK", "LISTEN", "THIS", "WAIT", "WATCH"]:text_color = (0, 255, 255)# π’ GREEN highlights for money/success wordselif text in ["MONEY", "CASH", "WIN", "BEST", "PERFECT", "FAST", "POWERFUL", "SMART", "MAKE", "MAKING"]:text_color = (0, 255, 0)# π΄ RED highlights for punchy/negative wordselif text in ["STOP", "FREEZE", "WRONG", "BAD", "CUT", "FAIL", "NO", "DON'T", "NEVER", "CLOSE"]:text_color = (0, 0, 255)# π PINK highlights for viral shock wordselif text in ["VIRAL", "INSANE", "SHOCKING", "SECRET", "WHAT", "CRAZY", "WOW", "AMAZING", "BROKE"]:text_color = (203, 192, 255)# π οΈ ADVANCED VECTOR GRAPHICS RENDERING SIZING ENGINEfont = cv2.FONT_HERSHEY_DUPLEXfont_scale = 3.2 # Massive text layoutthickness = 8 # Ultra bold stroke lines# Calculate precise spatial geometry mapping data to center text blocktext_size = cv2.getTextSize(text, font, font_scale, thickness)[0]text_x = (width - text_size[0]) // 2text_y = (height + text_size[1]) // 2# Draw Hard-Edge Jet Black Text Border Outline (Alex Hormozi Preset Layout)# This completely blocks green pixels from creeping inside your text borderscv2.putText(frame, text, (text_x, text_y), font, font_scale, (0, 0, 0), thickness + 14, lineType=cv2.LINE_AA)# Render Core colored typography text layer precisely inside the center frame slotcv2.putText(frame, text, (text_x, text_y), font, font_scale, text_color, thickness, lineType=cv2.LINE_AA)video_writer.write(frame)video_writer.release()# 5. Lock audio stream straight to file tracks via system pipelineos.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 responsive web browser console view portaldemo = gr.Interface(fn=make_viral_captions,inputs=gr.Audio(type="filepath", label="Upload Voice Audio Track"),outputs=gr.Video(label="Download Green Screen Caption MP4 Layer"),title="Viral Caption Tool Engine Pro")demo.launch()
app.py+86-72