|
| 1 | +# /// script |
| 2 | +# requires-python = ">=3.13" |
| 3 | +# dependencies = [ |
| 4 | +# "moviepy", |
| 5 | +# "faster_whisper", |
| 6 | +# "pydub", |
| 7 | +# "onnxruntime", |
| 8 | +# "prompt_toolkit", |
| 9 | +# "openai", |
| 10 | +# "requests" |
| 11 | +# ] |
| 12 | +# /// |
| 13 | + |
| 14 | +from moviepy import VideoFileClip |
| 15 | +from faster_whisper import WhisperModel |
| 16 | +from prompt_toolkit import prompt |
| 17 | +from prompt_toolkit.completion import PathCompleter |
| 18 | +from pathlib import Path |
| 19 | +import openai |
| 20 | + |
| 21 | +import requests |
| 22 | +import os |
| 23 | + |
| 24 | +from pydantic import BaseModel |
| 25 | +from typing import List |
| 26 | + |
| 27 | +from uuid import uuid4 |
| 28 | + |
| 29 | + |
| 30 | +class ScriptSegment(BaseModel): |
| 31 | + scene: str |
| 32 | + kecs: List[str] |
| 33 | + |
| 34 | + |
| 35 | +class Segment(BaseModel): |
| 36 | + logicalparts: List[str] |
| 37 | + |
| 38 | + |
| 39 | +PEXELS_API_KEY = os.getenv("PEXELS_API_KEY") # Set this in your environment |
| 40 | +PEXELS_SEARCH_URL = "https://api.pexels.com/videos/search" |
| 41 | + |
| 42 | +HEADERS = {"Authorization": PEXELS_API_KEY} |
| 43 | + |
| 44 | + |
| 45 | +def search_and_download_pexels_videos( |
| 46 | + kecs, output_dir="pexels_downloads", max_per_term=2 |
| 47 | +): |
| 48 | + os.makedirs(output_dir, exist_ok=True) |
| 49 | + |
| 50 | + for term in kecs: |
| 51 | + print(f"\n🔍 Searching Pexels for: {term}") |
| 52 | + params = {"query": term, "per_page": max_per_term} |
| 53 | + response = requests.get(PEXELS_SEARCH_URL, headers=HEADERS, params=params) |
| 54 | + |
| 55 | + if response.status_code != 200: |
| 56 | + print(f"❌ Error searching '{term}': {response.text}") |
| 57 | + continue |
| 58 | + |
| 59 | + videos = response.json().get("videos", []) |
| 60 | + for video in videos: |
| 61 | + url = video["video_files"][0]["link"] |
| 62 | + ext = url.split("?")[0].split(".")[-1] |
| 63 | + idx = str(uuid4())[:4] |
| 64 | + filename = f"{term.replace(' ', '_')}_{idx}.{ext}" |
| 65 | + |
| 66 | + print(f"⬇️ Downloading: {filename}") |
| 67 | + vid_data = requests.get(url) |
| 68 | + with open(os.path.join(output_dir, filename), "wb") as f: |
| 69 | + f.write(vid_data.content) |
| 70 | + |
| 71 | + |
| 72 | +def select_mp4_file(): |
| 73 | + print("Enter path to .mp4 file (Tab to autocomplete):") |
| 74 | + completer = PathCompleter(only_directories=False) |
| 75 | + path = prompt("File: ", completer=completer) |
| 76 | + |
| 77 | + if path.lower().endswith(".mp4") and Path(path).exists(): |
| 78 | + return path |
| 79 | + else: |
| 80 | + print("Invalid or non-existent file.") |
| 81 | + return None |
| 82 | + |
| 83 | + |
| 84 | +def extract_audio(mp4_path, audio_path="extracted_audio.wav"): |
| 85 | + video = VideoFileClip(mp4_path) |
| 86 | + video.audio.write_audiofile(audio_path, codec="pcm_s16le") # saves as WAV |
| 87 | + return audio_path |
| 88 | + |
| 89 | + |
| 90 | +def transcribe(audio_path, model_size="base"): |
| 91 | + model = WhisperModel( |
| 92 | + model_size, compute_type="int8" |
| 93 | + ) # use "float16" if you have GPU |
| 94 | + segments, _ = model.transcribe(audio_path) |
| 95 | + |
| 96 | + transcript = "" |
| 97 | + for segment in segments: |
| 98 | + transcript += f"{segment.text.strip()} " |
| 99 | + return transcript.strip() |
| 100 | + |
| 101 | + |
| 102 | +def write_transcript(transcript, transcript_file="transcript.txt"): |
| 103 | + with open(transcript_file, "w") as f: |
| 104 | + f.write(transcript) |
| 105 | + |
| 106 | + |
| 107 | +def extract_segments(transcript: str): |
| 108 | + SYSTEM_PROMPT = """ |
| 109 | +You are a script analysis tool. Given a transcript, break it down into logical parts like scenes or topic sections of a script. |
| 110 | +return: |
| 111 | +- logicalparts: a list of parts from the given transcript. |
| 112 | +
|
| 113 | +Only respond in the provided JSON schema. No explanation. |
| 114 | +""" |
| 115 | + |
| 116 | + client = openai.OpenAI() |
| 117 | + response = client.beta.chat.completions.parse( |
| 118 | + model="gpt-4o-mini-2024-07-18", |
| 119 | + messages=[ |
| 120 | + {"role": "system", "content": SYSTEM_PROMPT}, |
| 121 | + {"role": "user", "content": transcript}, |
| 122 | + ], |
| 123 | + temperature=0.5, |
| 124 | + response_format=Segment, |
| 125 | + ) |
| 126 | + |
| 127 | + return response.choices[0].message.parsed |
| 128 | + |
| 129 | + |
| 130 | +def extract_kecs(scene: str): |
| 131 | + SYSTEM_PROMPT = """ |
| 132 | +You are a script analysis tool. Given a scene you have to provide the visual search keywords. |
| 133 | +return: |
| 134 | +- scene: the given scene |
| 135 | +- kecs: a list of 3 visual search keywords (KECs) that best represent the scene. Don't include character names, or other PIIs. |
| 136 | +
|
| 137 | +Only respond in the provided JSON schema. No explanation. |
| 138 | +""" |
| 139 | + |
| 140 | + client = openai.OpenAI() |
| 141 | + response = client.beta.chat.completions.parse( |
| 142 | + model="gpt-4o-mini-2024-07-18", |
| 143 | + messages=[ |
| 144 | + {"role": "system", "content": SYSTEM_PROMPT}, |
| 145 | + {"role": "user", "content": f"The given scene is: {scene}"}, |
| 146 | + ], |
| 147 | + temperature=0.5, |
| 148 | + response_format=ScriptSegment, |
| 149 | + ) |
| 150 | + |
| 151 | + return response.choices[0].message.parsed |
| 152 | + |
| 153 | + |
| 154 | +if __name__ == "__main__": |
| 155 | + mp4_path = select_mp4_file() |
| 156 | + if not mp4_path: |
| 157 | + exit() |
| 158 | + |
| 159 | + print(f"Selected: {mp4_path}") |
| 160 | + audio_path = extract_audio(mp4_path) |
| 161 | + |
| 162 | + print("Transcribing...") |
| 163 | + transcript = transcribe(audio_path) |
| 164 | + |
| 165 | + print("\n--- Transcript ---\n") |
| 166 | + print(transcript) |
| 167 | + write_transcript(transcript) |
0 commit comments