File size: 5,314 Bytes
1425afc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
"""
broll.py
---------------------------------------
AI B-Roll Injection System (V8)

Purpose:
- Detect topics in transcript
- Map topics → generic stock B-roll assets
- Overlay or replace segments
- Improve retention & visual variety

Works in CPU-only environments.
No external API dependency required.
"""

import os
import random
import subprocess


# =====================================================
# STOCK B-ROLL LIBRARY (LOCAL FALLBACK)
# =====================================================

DEFAULT_BROLL = {
    "money": "assets/broll/money.mp4",
    "success": "assets/broll/success.mp4",
    "business": "assets/broll/business.mp4",
    "phone": "assets/broll/phone.mp4",
    "tech": "assets/broll/tech.mp4",
    "people": "assets/broll/people.mp4",
    "talking": "assets/broll/talking.mp4",
    "default": "assets/broll/default.mp4",
}


# =====================================================
# TOPIC DETECTION
# =====================================================

def detect_topic(text):
    """
    Simple keyword-based topic classifier.
    Lightweight (no ML dependency).
    """

    text = text.lower()

    if any(w in text for w in ["money", "rich", "income", "profit"]):
        return "money"

    if any(w in text for w in ["business", "startup", "company"]):
        return "business"

    if any(w in text for w in ["phone", "mobile", "iphone", "android"]):
        return "phone"

    if any(w in text for w in ["tech", "ai", "software", "computer"]):
        return "tech"

    if any(w in text for w in ["success", "win", "achieve"]):
        return "success"

    if any(w in text for w in ["people", "person", "man", "woman"]):
        return "people"

    if any(w in text for w in ["talk", "speak", "say"]):
        return "talking"

    return "default"


# =====================================================
# SEGMENT ANALYZER
# =====================================================

def extract_segments(words, segment_length=8):
    """
    Converts transcript words into grouped segments.
    """

    segments = []
    buffer = []

    for w in words:
        buffer.append(w)

        if len(buffer) >= segment_length:
            segments.append(buffer)
            buffer = []

    if buffer:
        segments.append(buffer)

    return segments


# =====================================================
# B-ROLL MATCHING ENGINE
# =====================================================

def match_broll(segment):
    """
    Map transcript segment → B-roll video
    """

    text = " ".join([w["word"] for w in segment])
    topic = detect_topic(text)

    return DEFAULT_BROLL.get(topic, DEFAULT_BROLL["default"])


# =====================================================
# B-ROLL INSERTION (FFMPEG OVERLAY STRATEGY)
# =====================================================

def overlay_broll(base_video, broll_video, output_path, start_time, duration):
    """
    Overlays B-roll using ffmpeg.
    Lightweight crossfade approach.
    """

    cmd = [
        "ffmpeg", "-y",
        "-i", base_video,
        "-i", broll_video,
        "-filter_complex",
        f"[1:v]scale=1080:1920,format=rgba[ov];"
        f"[0:v][ov]overlay=enable='between(t,{start_time},{start_time+duration})'",
        "-c:v", "libx264",
        "-preset", "ultrafast",
        "-c:a", "copy",
        output_path
    ]

    subprocess.run(cmd, check=True)


# =====================================================
# MAIN PIPELINE
# =====================================================

def insert_broll(video_path, words=None):
    """
    Full B-roll injection pipeline
    """

    if not words:
        # fallback: return original video
        return video_path

    segments = extract_segments(words)

    current_video = video_path
    outputs = []

    for i, segment in enumerate(segments):

        broll = match_broll(segment)

        output_file = f"broll_output_{i}.mp4"

        start_time = segment[0]["start"]
        duration = segment[-1]["end"] - start_time

        try:
            overlay_broll(
                current_video,
                broll,
                output_file,
                start_time,
                duration
            )

            current_video = output_file
            outputs.append(output_file)

        except Exception as e:
            print(f"[BROLL ERROR] Segment {i}: {e}")
            continue

    return outputs[-1] if outputs else video_path


# =====================================================
# ADVANCED VERSION (V8 EXTENSION)
# =====================================================

def smart_broll_engine(words, hook_boost=True):
    """
    Enhanced version:
    - prioritizes hook segments
    - increases emotional pacing
    """

    segments = extract_segments(words)

    prioritized = []

    for seg in segments:

        text = " ".join([w["word"] for w in seg]).lower()

        score = 0

        if any(k in text for k in ["you", "this", "stop", "now"]):
            score += 2

        if hook_boost and len(seg) < 5:
            score += 1

        prioritized.append((score, seg))

    prioritized.sort(reverse=True, key=lambda x: x[0])

    final_video = None

    for _, seg in prioritized:
        final_video = insert_broll(final_video or "input.mp4", seg)

    return final_video