File size: 4,286 Bytes
de8b233 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 | import os
import json
import tempfile
import subprocess
from typing import List
from dotenv import load_dotenv
from pydantic import BaseModel, Field
from agents import Agent, function_tool, Runner # OpenAI Agents SDK
from openai import OpenAI
load_dotenv()
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
# ---------- Output schema (structured outputs via output_type) ----------
class Hook(BaseModel):
spoken: str
onScreen: str
durationSec: float
class Beat(BaseModel):
timeRange: str
spoken: str
onScreen: str
shot: str
class CTA(BaseModel):
spoken: str
onScreen: str
class ReelScript(BaseModel):
language: str
hook: Hook
beats: List[Beat] = Field(min_length=3, max_length=6)
cta: CTA
caption: str
hashtags: List[str] = Field(min_length=5, max_length=10)
class FinalOutput(BaseModel):
transcript: str
reelScript: ReelScript
# ---------- Tools ----------
@function_tool
def transcribe_video(video_path: str, language: str = "nl") -> str:
"""
Extract audio (ffmpeg) + transcribe (Whisper).
video_path must be a local file path.
"""
if not os.path.exists(video_path):
raise FileNotFoundError(f"Video not found: {video_path}")
with tempfile.TemporaryDirectory() as td:
audio_path = os.path.join(td, "audio.mp3")
# Extract audio
subprocess.run(
["ffmpeg", "-y", "-i", video_path, "-vn", "-acodec", "libmp3lame", "-b:a", "128k", audio_path],
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
# Transcribe
with open(audio_path, "rb") as f:
t = client.audio.transcriptions.create(
model="whisper-1",
file=f,
# language=language, # optional: enable if you want to force language
)
return t.text
@function_tool
def generate_reel_script(transcript: str, language: str = "nl", tone: str = "informatief", goal: str = "") -> dict:
"""
Generate Reel script as JSON object.
"""
prompt = f"""
Je krijgt een transcript van een video. Maak een Instagram Reel script in {language}.
Tone of voice: {tone}.
Doel: {goal or "maak een sterke samenvatting die mensen afkijkt"}.
Regels:
- Hook = 1 zin + korte on-screen tekst (max ~8 woorden) + 2-4 sec.
- Beats: 3 tot 6 stappen met timeRange ("0:03-0:08"), spoken, onScreen (kort), shot (camera/beeldsuggestie).
- CTA: 1 zin gesproken + on-screen.
- Caption: 1–2 zinnen.
- Hashtags: 5–10 relevante hashtags.
Transcript:
{transcript}
""".strip()
# We vragen expliciet om JSON en valideren daarna via output_type van de agent.
r = client.responses.create(
model="gpt-4o-mini",
input=prompt,
)
# output_text is meestal JSON als je prompt strak is; agent output_type vangt formatfouten af.
return json.loads(r.output_text)
# ---------- Agent ----------
reel_agent = Agent(
name="ReelMaker",
instructions=(
"Je maakt Instagram Reel scripts.\n"
"1) Gebruik transcribe_video om transcript te krijgen.\n"
"2) Gebruik generate_reel_script om reelScript te maken.\n"
"3) Geef als FINAL output exact dit object: { transcript: str, reelScript: ReelScript }.\n"
"Geen extra tekst."
),
tools=[transcribe_video, generate_reel_script],
output_type=FinalOutput, # structured outputs in Agents SDK :contentReference[oaicite:3]{index=3}
)
def run_local(video_path: str, language: str = "nl", tone: str = "informatief", goal: str = "") -> FinalOutput:
# Runner voert de agent uit en regelt tool-calls :contentReference[oaicite:4]{index=4}
result = Runner.run_sync(
reel_agent,
input=f"Verwerk video_path={video_path} language={language} tone={tone} goal={goal}",
)
return result.final_output
if __name__ == "__main__":
# Voorbeeld: python agent_app.py /pad/naar/video.mp4
import sys
if len(sys.argv) < 2:
print("Usage: python agent_app.py /path/to/video.mp4")
raise SystemExit(1)
out = run_local(sys.argv[1])
print("\n=== TRANSCRIPT ===\n")
print(out.transcript)
print("\n=== REEL SCRIPT (JSON) ===\n")
print(out.reelScript.model_dump_json(indent=2)) |