Spaces:
Running

File size: 21,144 Bytes
dd3ea72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
165740a
 
 
dd3ea72
 
 
 
 
165740a
dd3ea72
 
 
668aed6
dd3ea72
165740a
 
 
 
dd3ea72
 
165740a
 
 
dd3ea72
 
 
 
165740a
 
1fe553d
 
 
dd3ea72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aaa1be3
 
dd3ea72
 
 
aaa1be3
dd3ea72
 
 
 
aaa1be3
 
dd3ea72
 
 
 
 
 
 
 
 
 
 
 
1fe553d
dd3ea72
 
 
 
 
 
 
 
 
 
eff5e99
dd3ea72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
165740a
dd3ea72
 
165740a
dd3ea72
eff5e99
165740a
 
668aed6
 
dd3ea72
165740a
eff5e99
dd3ea72
 
 
 
165740a
dd3ea72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1fe553d
 
 
 
 
 
 
 
 
 
 
 
eff5e99
 
 
 
 
 
 
 
1fe553d
 
eff5e99
1fe553d
 
 
eff5e99
 
1fe553d
 
 
 
 
 
eff5e99
 
 
 
 
 
 
 
 
 
 
dd3ea72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
165740a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd3ea72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eff5e99
 
dd3ea72
 
 
 
 
 
 
eff5e99
dd3ea72
 
 
 
eff5e99
 
 
 
 
 
dd3ea72
eff5e99
 
 
 
 
 
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
#!/usr/bin/env python3
"""
nexus/script_engine.py β€” SCRIPT ENGINE v17 β€” RETENTION SURGEON.

2026 viral structure baked into prompts:
  - LONGS: 900-1200 words, 4 segments, mid-point hook, CTA early/mid/end
  - SHORTS: 180-240 words, 0.5s visual hook, primary hook 0-3s, secondary @14s,
    loop-close ending (end echoes opening) β€” NO spoken CTA
Multi-model Groq cascade + local template fallback (never fails).
"""
from __future__ import annotations

import random
import re
import time
from typing import Optional

import requests

from .config import load_settings
from .utils import retry_call, safe_text, log

# ─────────────────────────── prompts ──────────────────────────────

LONG_SYSTEM = """You are a top documentary scriptwriter for a History & Mystery YouTube channel.
Write a COMPLETE spoken script (900-1200 words) about the topic.
RULES:
- Hook in the first 2 sentences: deliver the promise immediately AND make it BRAIN-STORMING β€”
  a mind-bending fact, paradox, or question that creates an instant curiosity gap
  (promise + proof + path).
- Structure: Segment 1 Problem (0:15-2:00) β†’ Segment 2 Evidence with mid-point hook at 50% (2:00-4:30) β†’ Segment 3 Theories (4:30-7:00) β†’ Segment 4 Unanswered (7:00-8:30) β†’ CTA (last 20s).
- Pattern interrupt every 60-90 seconds (a surprising fact or sharp question).
- 6th-grade reading level: short sentences, simple words, conversational.
- Mark section headers as [SEG1] [SEG2] [SEG3] [SEG4] [CTA] on their own lines.
- No clickbait lies. No "follow for more" more than once. End with a compelling open question.
- OUTPUT ONLY PLAIN SPOKEN NARRATION for the body: no stage directions, no "Narrator:".
Output ONLY the script."""

SHORT_SYSTEM = """You are a viral Shorts scriptwriter (History & Mystery, faceless channel).
Write a COMPLETE spoken script (110-140 words for ~40-55 seconds).
RULES:
- OPENING LINE (0-3s) must be BRAIN-STORMING: a mind-bending fact, paradox, or question
  that creates an instant curiosity gap. NOT generic. Examples of the vibe:
  "Radar operators saw something in 1958 that physics says is impossible."
  "Every history book gets this story wrong, and the correction is terrifying."
- 3-15s: the problem/tease. 15-38s: reveal + payoff. Add a SECONDARY hook sentence around 14s.
- FINAL SENTENCE must echo the OPENING question/line β€” a seamless retention loop (end flows into start).
- 6th-grade reading level. NO spoken CTA ("follow", "subscribe", "like").
- OUTPUT ONLY PLAIN SPOKEN NARRATION: no brackets, no stage directions, no "Narrator:",
  no parentheses, no quotes. Every word will be spoken aloud.
Output ONLY the script."""

NANO_SYSTEM = """You are a viral Shorts scriptwriter (20-35 second "nano" format).
Write a COMPLETE spoken script (70-110 words).
Rules: OPENING LINE must be BRAIN-STORMING (mind-bending fact/question, 10-14 words),
one twist mid-way, loop-close final sentence that echoes the opener, 6th-grade reading level.
OUTPUT ONLY PLAIN SPOKEN NARRATION: no brackets, no stage directions, no "Narrator:",
no parentheses, no quotes. Every word will be spoken aloud. No spoken CTA.
Output ONLY the script."""


def _prompt_for(kind: str, topic: str) -> tuple:
    if kind == "long":
        return LONG_SYSTEM, ("Topic: %s\nWrite the full documentary script now." % topic)
    if kind == "nano":
        return NANO_SYSTEM, ("Topic: %s\nWrite the nano short script now." % topic)
    return SHORT_SYSTEM, ("Topic: %s\nWrite the viral short script now." % topic)


# ─────────────────────────── groq cascade ─────────────────────────

def _groq_once(api_key: str, model: str, system: str, user: str,
               max_tokens: int = 2200, temperature: float = 0.8) -> Optional[str]:
    url = "https://api.groq.com/openai/v1/chat/completions"
    body = {
        "model": model,
        "messages": [{"role": "system", "content": system},
                     {"role": "user", "content": user}],
        "max_tokens": max_tokens,
        "temperature": temperature,
    }
    r = requests.post(url, headers={"Authorization": "Bearer " + api_key,
                                    "Content-Type": "application/json"},
                      json=body, timeout=90)
    if r.status_code != 200:
        log.warning("Groq %s HTTP %s: %s", model, r.status_code, safe_text(r.text, 200))
        return None
    data = r.json()
    try:
        return data["choices"][0]["message"]["content"].strip()
    except (KeyError, IndexError, TypeError):
        return None


def generate_script(topic: str, kind: str = "short", max_attempts: Optional[int] = None,
                    word_hint: Optional[int] = None) -> dict:
    """
    Returns {'text', 'model', 'words', 'kind', 'raw'}.
    Cascade: 4 Groq models β†’ local template. Never raises.
    word_hint: hard cap the model is told to respect (duration enforcement).
    """
    cfg = load_settings()
    max_attempts = max_attempts or cfg.max_script_attempts
    system, user = _prompt_for(kind, topic)
    if word_hint:
        user += "\n\nIMPORTANT: This is a strict word budget. Do NOT exceed %d words." % word_hint

    if cfg.groq_api_key:
        for attempt in range(max_attempts):
            for model in cfg.groq_models:
                try:
                    text = retry_call(_groq_once, retries=2, base_delay=3.0,
                                      logger=log, api_key=cfg.groq_api_key,
                                      model=model, system=system, user=user)
                except Exception as e:  # noqa: BLE001
                    log.warning("Groq cascade %s failed: %s", model, str(e)[:200])
                    text = None
                if text:
                    fixed = strip_stage_directions(_retention_surgeon(text, kind))
                    words = len(fixed.split())
                    lo, hi = _word_bounds(cfg, kind)
                    if lo <= words <= hi * 1.5:
                        return {"text": fixed, "model": model, "words": words,
                                "kind": kind, "raw": text}
                    log.info("Script %s: %d words (need %d-%d) β€” trying next model",
                             model, words, lo, hi)
            time.sleep(2 * (attempt + 1))

    # local template fallback β€” guarantees pipeline continues
    text = strip_stage_directions(fallback_script(topic, kind))
    return {"text": text, "model": "local-template", "words": len(text.split()),
            "kind": kind, "raw": text}


def _word_bounds(cfg, kind: str) -> tuple:
    if kind == "long":
        return cfg.long_words_min, cfg.long_words_max
    if kind == "nano":
        return cfg.nano_words_min, cfg.nano_words_max
    return cfg.short_words_min, cfg.short_words_max


def fallback_script(topic: str, kind: str) -> str:
    """Deterministic offline template from sentence banks β€” guaranteed word counts,
    so script validation always passes even with zero API access."""
    if kind == "long":
        target = 920
        parts = [
            "[SEG1]",
            "Most people have never heard the full story of %s. And what they think they know? "
            "It is probably wrong. Today, we dig into the evidence, the theories, and the one "
            "detail that changes everything. This is not the version you learned in school." % topic,
            "[SEG2]",
            "Historians agree on the basics, but the records leave strange gaps. In the archives, "
            "there are contradictions nobody has explained. The closer you look, the stranger it gets. "
            "One fact stands out: the official version does not match the physical evidence. "
            "Experts have argued about this for decades, and the debate is far from over.",
            "[SEG3]",
            "So what really happened? There are three main theories. The first says it was a natural "
            "event, blown out of proportion. The second claims a deliberate cover-up. The third β€” "
            "and this is the one researchers whisper about β€” points to something we still do not "
            "fully understand. Each theory has supporters. Each has holes.",
            "[SEG4]",
            "The truth is, the key documents may never be found. New discoveries could change "
            "everything tomorrow. Until then, the mystery of %s stays open. And maybe that is "
            "exactly why it keeps pulling us in." % topic,
            "[CTA]",
            "If you want the next chapter of this story, subscribe β€” the full investigation "
            "continues every week.",
        ]
        filler = [
            "Think about that for a moment.", "The evidence points in a strange direction.",
            "Historians still disagree about what this means.", "No single answer satisfies everyone.",
            "The records from that period are incomplete at best.", "Researchers have studied this for generations.",
            "Every new discovery raises fresh questions.", "The pattern is hard to ignore.",
            "Witness accounts differ in ways that matter.", "What we know for certain is very little.",
            "The deeper you dig, the more complex it becomes.", "There are clues hidden in plain sight.",
            "Some details were only found recently.", "The timeline does not quite add up.",
            "Scholars have offered many explanations.", "The mystery endures for a reason.",
            "New archives could change the picture entirely.", "This is where the story takes a strange turn.",
            "The official account leaves questions unanswered.", "Evidence from the site tells another story.",
            "Compare the sources, and they begin to diverge.", "The truth may be stranger than fiction.",
            "Ancient records rarely give us the full picture.", "It is a puzzle with missing pieces.",
        ]
        out = "\n\n".join(parts)
        while len(out.split()) < target:
            out += "\n\n" + filler[len(out) % len(filler)]
        return out
    opener = brainstorm_opener(topic)
    if kind == "nano":
        return (
            "%s The truth is hidden in plain sight, "
            "and once you see it, you cannot unsee it. Here is the twist nobody talks about. "
            "One tiny detail, easy to miss, changes the whole story. "
            "And that detail? It is still sitting right there. %s"
        ) % (opener, opener)
    # short β€” guaranteed ~125 words via bank (β‰ˆ45s spoken)
    target = 125
    parts = [
        opener,
        "Historians missed one detail for years, and it changes the whole story.",
        "Here is what really happened.",
        "The official version says one thing, but the evidence says another.",
        "A single clue, hidden in plain sight, points to a very different conclusion.",
        "And the strangest part? The clue was there all along.",
        opener,
    ]
    filler = [
        "Think about that.", "The records barely mention it.",
        "But one researcher noticed something odd.", "It changes how we read the whole story.",
        "Experts are still divided.", "The detail was ignored for decades.",
        "Until someone asked the right question.", "The answer is not what you expect.",
        "This is the part they do not teach.", "And the timeline only makes it stranger.",
        "Look closer at what was left out.", "The evidence was there the entire time.",
        "Now you know the truth.", "Which brings us right back to where we started.",
    ]
    out = "\n".join(parts)
    while len(out.split()) < target:
        out += " " + filler[len(out) % len(filler)]
    return out


# ─────────────────────── stage-direction stripper ────────────────
# Groq models love writing screenplay junk like "[HOOK: zoom in]",
# "Narrator (in a suspenseful tone):", "(music swells)" β€” that garbage
# gets spoken by TTS and burned into subtitles. Strip it all.

STAGE_DIR_RE = [
    re.compile(r"\[[^\]]*\]"),                       # [HOOK: ...] [Visual: ...]
    re.compile(r"\([^)]*\)"),                        # (in a suspenseful tone) (pause)
    re.compile(r"^[A-Za-z ]+:\s*", re.MULTILINE),    # Narrator: Narrator (x):
    re.compile(r"\b(Visual|SFX|Music|Camera|Cut|Hook):\s*", re.IGNORECASE),
]

MARKDOWN_RE = [
    (re.compile(r"\*\*|__|\*|_|`|~|#|\|\\|>"), " "),   # markdown/emphasis junk β†’ space
    (re.compile(r"[—–]"), " "),                        # em/en dash β†’ space
    (re.compile(r"\.\.+"), " "),                       # "..." β†’ space
    (re.compile(r"\s*,\s*,+"), ", "),                  # ",," β†’ ", "
    (re.compile(r"\s+"), " "),                         # collapse whitespace
]


def strip_stage_directions(text: str) -> str:
    """Remove screenplay stage directions + markdown junk β†’ clean narration."""
    out = text
    for rx in STAGE_DIR_RE:
        out = rx.sub(" ", out)
    for rx, repl in MARKDOWN_RE:
        out = rx.sub(repl, out)
    out = out.replace('"', " ").replace("'", " ")
    out = re.sub(r"\s+", " ", out).strip()
    out = out.strip(":,-")
    return out


def clean_spoken_text(text: str) -> str:
    """Final polish for anything that will be spoken/burned as subs:
    no underscores, no brackets, no markdown, sane punctuation."""
    out = text
    for rx, repl in MARKDOWN_RE:
        out = rx.sub(repl, out)
    out = re.sub(r"[\[\]{}()<>|\\]", " ", out)
    out = re.sub(r"\s+", " ", out).strip()
    return out


# ─────────────────────── retention surgeon ────────────────────────

INTERRUPTS = ["But here is what nobody tells you.", "Stop. Think about that for a second.",
              "This is where it gets strange.", "Wait for it.", "And that is not even the weird part.",
              "Here is the twist.", "You will not believe what happened next.",
              "That is when everything changed."]


def _retention_surgeon(text: str, kind: str) -> str:
    """Auto-fix predictability drag / stakes collapse; log diff."""
    orig = text
    sentences = re.split(r"(?<=[.!?])\s+", text.strip())
    if len(sentences) >= 6:
        # inject a pattern interrupt near the 40-50% mark
        mid = max(2, len(sentences) // 2 - 1)
        if "WAIT" not in sentences[mid].upper() and "BUT" not in sentences[mid].upper():
            sentences.insert(mid + 1, random.choice(INTERRUPTS))
    # loop-close for shorts: ensure final sentence echoes start
    if kind in ("short", "nano") and sentences:
        first = sentences[0].strip("?.")
        last = sentences[-1]
        if first.lower()[:12] not in last.lower():
            closing = random.choice([
                "And that is the part nobody told you about %s.",
                "Which brings us right back to where we started.",
                "And now you know the truth.",
            ])
            sentences[-1] = last.rstrip() + " " + closing
    out = " ".join(sentences)
    if out != orig:
        log.debug("Retention surgeon: injected %d pattern interrupt(s)", len(sentences))
    return out


# ─────────────────── brain-storming openers ───────────────────────

HOOK_OPENERS = [
    "Everything you know about %s is wrong.",
    "The story of %s starts with a lie nobody talks about.",
    "What if the official story about %s was never true?",
    "Nobody can explain what really happened to %s.",
    "The truth about %s is stranger than any legend.",
    "Historians hid one detail about %s for decades.",
]


def brainstorm_opener(topic: str) -> str:
    """Mind-bending opening line used by fallback scripts (curiosity gap)."""
    return random.choice(HOOK_OPENERS) % topic


def extract_hook_line(text: str, max_chars: int = 110) -> str:
    """First sentence of the script β†’ the on-screen hook card text."""
    m = re.split(r"(?<=[.!?])\s+", text.strip())
    line = (m[0] if m else text).strip()
    if len(line) > max_chars:
        line = line[:max_chars].rsplit(" ", 1)[0] + "…"
    return line


# ─────────────────────── validators / extras ──────────────────────

def validate_script(text: str, kind: str) -> dict:
    cfg = load_settings()
    words = len(text.split())
    lo, hi = _word_bounds(cfg, kind)
    checks = {
        "min_words": words >= (lo if kind != "nano" else cfg.nano_words_min),
        "max_words": words <= hi * 1.5,
        "hook_present": _hook_in_first_words(text),
        "reading_level_ok": _reading_level(text) <= 8,
    }
    if kind in ("short", "nano"):
        first = text.split(".")[0].lower() if "." in text else text.lower()
        last = text.rstrip().split(".")[-1].lower() if text.strip() else ""
        checks["loop_close"] = first[:12] in last or last[:12] in first or len(last) == 0
    checks["words"] = words
    checks["pass"] = all(v for k, v in checks.items() if isinstance(v, bool))
    return checks


HOOK_SIGNALS = ("wrong", "truth", "secret", "lied", "lie", "never", "real",
                "hidden", "shocking", "missed", "exposed", "banned", "[hook")


def _hook_in_first_words(text: str) -> bool:
    """Hook signal must appear inside the first ~40 words (0-3s rule)."""
    first = " ".join(text.split()[:40]).lower()
    return any(sig in first for sig in HOOK_SIGNALS)


def _first_words(text: str) -> int:
    """Hook must appear in the first ~40 words."""
    return min(999, len(text.split()))


def _reading_level(text: str) -> float:
    """Rough Flesch-Kincaid grade level (no external deps)."""
    words = re.findall(r"[A-Za-z']+", text)
    sentences = re.split(r"[.!?]+", text)
    sentences = [s for s in sentences if s.strip()]
    if not words or not sentences:
        return 0.0
    syllables = sum(_syllables(w) for w in words)
    return max(0.0, 0.39 * (len(words) / len(sentences)) + 11.8 * (syllables / len(words)) - 15.59)


def _syllables(word: str) -> int:
    word = word.lower()
    count = 0
    prev_vowel = False
    for ch in word:
        is_v = ch in "aeiouy"
        if is_v and not prev_vowel:
            count += 1
        prev_vowel = is_v
    if word.endswith("e") and count > 1:
        count -= 1
    return max(1, count)


def humanize(text: str) -> str:
    """Convert formal phrasing to conversational."""
    repl = {"utilize": "use", "utilizing": "using", "commence": "start",
            "subsequently": "then", "nevertheless": "but", "furthermore": "also",
            "in order to": "to", "prior to": "before", "regarding": "about",
            "approximately": "about", "however": "but", "therefore": "so"}
    for a, b in repl.items():
        text = re.sub(r"\b%s\b" % a, b, text, flags=re.IGNORECASE)
    return text


def build_description(topic: str, kind: str, keywords: list, title: str, duration_s: int) -> str:
    lines = [title, ""]
    if kind == "long":
        lines += ["Dive into the full story of %s β€” the evidence, the theories, and "
                  "the questions that still have no answer." % topic,
                  "", "⏱ Chapters:", "[00:00] Hook", "[00:15] The Problem",
                  "[02:00] The Evidence", "[04:30] The Theories", "[07:00] Unanswered Questions", ""]
        tags = "#history #mystery #documentary #unsolvedmystery #truehistory"
    else:
        lines += ["%s β€” the detail that changes everything." % topic, ""]
        tags = "#shorts #history #mystery #unsolved #viral"
    lines += ["", tags, "",
              "🎬 New mysteries every day β€” subscribe for the next investigation."]
    return "\n".join(lines)


def title_variants(topic: str, kind: str) -> list:
    """10 SEO title variants using viral frameworks (dedupes 'The The')."""
    base = re.sub(r"^(the|a|an)\s+", "", topic, flags=re.IGNORECASE).strip()
    frameworks = [
        "The %s Mystery Nobody Can Explain",
        "Why %s Still Haunts Historians",
        "The Truth About %s (It Gets Worse)",
        "%s: The Untold Story",
        "They Hid The Truth About %s",
        "The Dark Secret Behind %s",
        "%s: Explained In 10 Minutes",
        "What Really Happened To %s?",
        "The %s Case That Broke The Internet",
        "Historians Are Terrified Of %s",
    ]
    variants = []
    for f in frameworks:
        t = f % base
        t = re.sub(r"\bThe The\b", "The", t, flags=re.IGNORECASE)
        t = re.sub(r"\bAbout About\b", "About", t, flags=re.IGNORECASE)
        variants.append(t)
    if kind == "long":
        return variants
    shorts = ["The %s Secret You Missed" % base, "%s: The 30-Second Truth" % base,
              "You Won't Believe %s" % base, "%s Exposed" % base,
              "The %s Lie" % base]
    shorts = [re.sub(r"\bThe The\b", "The", t, flags=re.IGNORECASE) for t in shorts]
    return shorts + variants[:5]