File size: 4,645 Bytes
345855e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import uuid
from datetime import datetime


# -------------------------------------------------
# UTILITIES
# -------------------------------------------------

def clamp(value, min_v=0, max_v=1):
    return max(min_v, min(max_v, value))


def safe_len(x):
    try:
        return len(x)
    except Exception:
        return 0


# -------------------------------------------------
# CORE HIGHLIGHT DETECTION ENGINE
# -------------------------------------------------

def detect_peak_density(words, window=12):
    """
    Simple sliding window density heuristic.
    Returns indices where speech intensity peaks.
    """

    if not words or len(words) < window:
        return []

    scores = []

    for i in range(len(words) - window):
        chunk = words[i:i + window]

        # heuristic: repetition + punctuation + trigger words
        unique_ratio = len(set(chunk)) / window

        trigger_words = {"why", "how", "what", "secret", "hack", "never", "stop", "crazy", "insane"}
        trigger_hits = sum(1 for w in chunk if str(w).lower() in trigger_words)

        score = (1 - unique_ratio) + (trigger_hits * 0.15)

        scores.append((i, score))

    # sort by strongest signal
    scores.sort(key=lambda x: x[1], reverse=True)

    # take top peaks (non-overlapping)
    selected = []
    used = set()

    for idx, _ in scores:
        if any(abs(idx - u) < window for u in used):
            continue
        selected.append(idx)
        used.add(idx)
        if len(selected) >= 8:  # max clips
            break

    return selected


def build_segments(words, indices, window=20):
    """
    Convert peak indices into structured segments.
    """

    segments = []

    for idx in indices:
        start = max(0, idx - window // 2)
        end = min(len(words), idx + window // 2)

        segment_words = words[start:end]

        if not segment_words:
            continue

        segments.append({
            "id": str(uuid.uuid4()),
            "start_index": start,
            "end_index": end,
            "words": segment_words,
            "length": len(segment_words),
        })

    return segments


# -------------------------------------------------
# FALLBACK MODE (NO SIGNAL DETECTED)
# -------------------------------------------------

def fallback_segments(words):
    """
    Ensures highlights always exist even for weak input.
    """

    if not words:
        return []

    chunk_size = max(25, len(words) // 5)

    segments = []

    for i in range(0, len(words), chunk_size):
        chunk = words[i:i + chunk_size]

        segments.append({
            "id": str(uuid.uuid4()),
            "start_index": i,
            "end_index": i + len(chunk),
            "words": chunk,
            "length": len(chunk),
        })

        if len(segments) >= 5:
            break

    return segments


# -------------------------------------------------
# MAIN ENTRYPOINT (REGISTRY COMPATIBLE)
# -------------------------------------------------

def run(context):
    """
    Expected input:
    {
        "words": [...]
    }
    """

    batch_id = str(uuid.uuid4())
    started_at = datetime.utcnow().isoformat()

    try:

        words = []

        if isinstance(context, dict):
            words = context.get("words", [])
        else:
            words = getattr(context, "words", []) or []

        # -------------------------------------------------
        # DETECT PEAKS
        # -------------------------------------------------

        peak_indices = detect_peak_density(words)

        if peak_indices:
            segments = build_segments(words, peak_indices)
        else:
            segments = fallback_segments(words)

        # -------------------------------------------------
        # OUTPUT CONTRACT
        # -------------------------------------------------

        return {
            "status": "success",
            "task": "highlights",
            "batch_id": batch_id,
            "started_at": started_at,
            "completed_at": datetime.utcnow().isoformat(),

            # core output for downstream clipper
            "highlights": segments,

            # UI-friendly summary
            "summary": {
                "total_words": safe_len(words),
                "segments_found": len(segments),
                "peak_detection": bool(peak_indices),
            }
        }

    except Exception as e:

        return {
            "status": "error",
            "task": "highlights",
            "batch_id": batch_id,
            "message": str(e),
            "stage": "highlight_detection_failed",
            "highlights": []
        }