Becio commited on
Commit
ec03d6a
·
verified ·
1 Parent(s): 2a16edf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -627
app.py CHANGED
@@ -1,513 +1,23 @@
1
- # app.py
2
- # Universal YouTube Scriptwriter — Human Tone (NO SOURCES/CLAIMS/DEBUG OUTPUT)
3
- #
4
- # Fix for your error:
5
- # - No more crash when "too few verifiable items": we extract ONLY evidence-backed facts
6
- # (each fact must include 1 quote + URL from the provided excerpts).
7
- # - If still too little evidence exists, we gracefully fall back to a "no-hard-facts" documentary script
8
- # (still human, structured, but avoids specific factual assertions).
9
- #
10
- # Required Secrets:
11
- # - SERPAPI_API_KEY
12
- # - OPENAI_API_KEY
13
- #
14
- # Optional:
15
- # - GEMINI_API_KEY (not required; this version doesn't need Gemini)
16
- #
17
- # Optional env vars:
18
- # - OPENAI_MODEL (default: gpt-4o-mini)
19
- # - OPENAI_MAX_TOKENS (default: 7000)
20
- # - MAX_SOURCES (default: 8)
21
- # - FETCH_TIMEOUT (default: 14)
22
- # - CHUNK_SIZE (default: 1700)
23
- # - CHUNK_OVERLAP (default: 220)
24
- # - CHUNKS_PER_SOURCE (default: 3)
25
- # - MIN_SECONDS_BETWEEN_RUNS (default: 15)
26
- # - MIN_WORDS_DEFAULT (default: 3000)
27
- # - FACTS_PER_LEVEL (default: 5) # number of evidence-backed facts per level
28
- # - MIN_FACTS_TOTAL (default: 8) # if fewer, fallback mode triggers
29
-
30
- import os
31
- import re
32
- import json
33
- import time
34
- from typing import List, Dict, Any, Optional, Tuple
35
-
36
- import gradio as gr
37
- import requests
38
-
39
- try:
40
- import trafilatura
41
- except Exception:
42
- trafilatura = None
43
-
44
- from openai import OpenAI
45
-
46
-
47
- # -----------------------------
48
- # Config
49
- # -----------------------------
50
- OPENAI_MODEL = os.getenv("OPENAI_MODEL", "gpt-4o-mini").strip() or "gpt-4o-mini"
51
- OPENAI_MAX_TOKENS = int(os.getenv("OPENAI_MAX_TOKENS", "7000"))
52
-
53
- MAX_SOURCES = int(os.getenv("MAX_SOURCES", "8"))
54
- FETCH_TIMEOUT = int(os.getenv("FETCH_TIMEOUT", "14"))
55
-
56
- CHUNK_SIZE = int(os.getenv("CHUNK_SIZE", "1700"))
57
- CHUNK_OVERLAP = int(os.getenv("CHUNK_OVERLAP", "220"))
58
- CHUNKS_PER_SOURCE = int(os.getenv("CHUNKS_PER_SOURCE", "3"))
59
-
60
- MIN_SECONDS_BETWEEN_RUNS = int(os.getenv("MIN_SECONDS_BETWEEN_RUNS", "15"))
61
- _RATE: Dict[str, float] = {}
62
-
63
- MIN_WORDS_DEFAULT = int(os.getenv("MIN_WORDS_DEFAULT", "3000"))
64
-
65
- FACTS_PER_LEVEL = int(os.getenv("FACTS_PER_LEVEL", "5"))
66
- MIN_FACTS_TOTAL = int(os.getenv("MIN_FACTS_TOTAL", "8"))
67
-
68
- _FETCH_CACHE: Dict[str, str] = {}
69
-
70
-
71
- # -----------------------------
72
- # Utilities
73
- # -----------------------------
74
- def _now() -> float:
75
- return time.time()
76
-
77
-
78
- def rate_limit(key: str):
79
- last = _RATE.get(key, 0.0)
80
- if _now() - last < MIN_SECONDS_BETWEEN_RUNS:
81
- wait = int(MIN_SECONDS_BETWEEN_RUNS - (_now() - last))
82
- raise gr.Error(f"Even wachten aub ({wait}s). Probeer zo opnieuw.")
83
- _RATE[key] = _now()
84
-
85
-
86
- def clean_text(s: str) -> str:
87
- return re.sub(r"\s+", " ", (s or "")).strip()
88
-
89
-
90
- def word_count(s: str) -> int:
91
- return len(re.findall(r"\b\w+\b", s or ""))
92
-
93
-
94
- def safe_json_extract(text: str) -> Any:
95
- text = (text or "").strip()
96
- text = text.replace("\u201c", '"').replace("\u201d", '"').replace("\u2018", "'").replace("\u2019", "'")
97
- text = re.sub(r"[\x00-\x08\x0b\x0c\x0e-\x1f]", "", text)
98
-
99
- text = re.sub(r"^```(?:json)?\s*", "", text, flags=re.I).strip()
100
- text = re.sub(r"\s*```$", "", text).strip()
101
-
102
- try:
103
- return json.loads(text)
104
- except Exception:
105
- pass
106
-
107
- start = text.find("{")
108
- if start != -1:
109
- depth = 0
110
- for i in range(start, len(text)):
111
- ch = text[i]
112
- if ch == "{":
113
- depth += 1
114
- elif ch == "}":
115
- depth -= 1
116
- if depth == 0:
117
- cand = text[start : i + 1]
118
- try:
119
- return json.loads(cand)
120
- except Exception:
121
- pass
122
-
123
- start = text.find("[")
124
- if start != -1:
125
- depth = 0
126
- for i in range(start, len(text)):
127
- ch = text[i]
128
- if ch == "[":
129
- depth += 1
130
- elif ch == "]":
131
- depth -= 1
132
- if depth == 0:
133
- cand = text[start : i + 1]
134
- try:
135
- return json.loads(cand)
136
- except Exception:
137
- pass
138
-
139
- raise ValueError("Model output bevat geen parseerbare JSON object/array.")
140
-
141
-
142
- def normalize_levels(obj: Any) -> Dict[str, Any]:
143
- """
144
- Expected:
145
- {
146
- "angle": "...",
147
- "levels": [
148
- {
149
- "level": 0,
150
- "title": "...",
151
- "location": "",
152
- "date_or_period": "",
153
- "facts": [{"text":"...", "evidence":{"url":"...","quote":"..."}}]
154
- }
155
- ]
156
- }
157
- """
158
- if not isinstance(obj, dict):
159
- return {"angle": "", "levels": []}
160
- angle = (obj.get("angle") or "").strip()
161
- levels = obj.get("levels") or []
162
- if not isinstance(levels, list):
163
- levels = []
164
- clean_levels = []
165
- for lv in levels:
166
- if not isinstance(lv, dict):
167
- continue
168
- facts = lv.get("facts") or []
169
- if not isinstance(facts, list):
170
- facts = []
171
- cleaned_facts = []
172
- for f in facts:
173
- if not isinstance(f, dict):
174
- continue
175
- t = (f.get("text") or "").strip()
176
- ev = f.get("evidence") or {}
177
- if not isinstance(ev, dict):
178
- ev = {}
179
- url = (ev.get("url") or "").strip()
180
- quote = clean_text(ev.get("quote") or "")
181
- # keep only if minimal evidence is present
182
- if t and url and quote:
183
- # keep quotes short-ish
184
- if len(quote.split()) > 25:
185
- quote = " ".join(quote.split()[:25])
186
- cleaned_facts.append({"text": t, "evidence": {"url": url, "quote": quote}})
187
- clean_levels.append(
188
- {
189
- "level": int(lv.get("level", len(clean_levels))),
190
- "title": (lv.get("title") or "").strip(),
191
- "location": (lv.get("location") or "").strip(),
192
- "date_or_period": (lv.get("date_or_period") or "").strip(),
193
- "facts": cleaned_facts,
194
- }
195
- )
196
- # sort by level index, reindex 0..n-1
197
- clean_levels = sorted(clean_levels, key=lambda x: x.get("level", 0))
198
- for i, lv in enumerate(clean_levels):
199
- lv["level"] = i
200
- return {"angle": angle, "levels": clean_levels}
201
-
202
-
203
- # -----------------------------
204
- # SERPAPI + Fetch
205
- # -----------------------------
206
- def serpapi_search(query: str, serpapi_key: str, num_results: int) -> List[Dict[str, str]]:
207
- if not serpapi_key:
208
- raise gr.Error("SERPAPI_API_KEY ontbreekt in Secrets.")
209
- url = "https://serpapi.com/search.json"
210
- params = {"engine": "google", "q": query, "api_key": serpapi_key, "num": num_results}
211
- r = requests.get(url, params=params, timeout=25)
212
- r.raise_for_status()
213
- data = r.json()
214
-
215
- out = []
216
- for item in (data.get("organic_results") or [])[:num_results]:
217
- out.append(
218
- {
219
- "title": item.get("title", "") or "",
220
- "url": item.get("link", "") or "",
221
- "snippet": item.get("snippet", "") or "",
222
- }
223
- )
224
- return out
225
-
226
-
227
- def fetch_page_text(url: str) -> str:
228
- if not url:
229
- return ""
230
- if url in _FETCH_CACHE:
231
- return _FETCH_CACHE[url]
232
-
233
- headers = {"User-Agent": "Mozilla/5.0"}
234
- r = requests.get(url, headers=headers, timeout=FETCH_TIMEOUT)
235
- r.raise_for_status()
236
- html = r.text
237
-
238
- text = ""
239
- if trafilatura:
240
- try:
241
- extracted = trafilatura.extract(html, include_comments=False, include_tables=False)
242
- if extracted and len(extracted.strip()) > 200:
243
- text = clean_text(extracted)
244
- except Exception:
245
- text = ""
246
-
247
- if not text:
248
- html2 = re.sub(r"(?is)<script.*?>.*?</script>", " ", html)
249
- html2 = re.sub(r"(?is)<style.*?>.*?</style>", " ", html2)
250
- text = re.sub(r"(?is)<.*?>", " ", html2)
251
- text = clean_text(text)
252
-
253
- _FETCH_CACHE[url] = text
254
- return text
255
-
256
-
257
- def chunk_text(text: str, size: int, overlap: int) -> List[str]:
258
- text = clean_text(text)
259
- if not text:
260
- return []
261
- if len(text) <= size:
262
- return [text]
263
-
264
- chunks = []
265
- step = max(1, size - overlap)
266
- for i in range(0, len(text), step):
267
- chunk = text[i : i + size]
268
- # lower threshold a bit to keep more material
269
- if len(chunk) >= 240:
270
- chunks.append(chunk)
271
- if i + size >= len(text):
272
- break
273
- return chunks
274
-
275
-
276
- def relevance_score(chunk: str, query: str) -> int:
277
- c = (chunk or "").lower()
278
- q = (query or "").lower()
279
- tokens = [t for t in re.findall(r"[a-z0-9]+", q) if len(t) >= 4]
280
- score = 0
281
- for t in tokens[:22]:
282
- score += c.count(t)
283
- return score
284
-
285
-
286
- def build_sources(serp_results: List[Dict[str, str]], query: str) -> List[Dict[str, Any]]:
287
- seen = set()
288
- sources: List[Dict[str, Any]] = []
289
-
290
- for r in serp_results:
291
- url = (r.get("url") or "").strip()
292
- if not url or url in seen:
293
- continue
294
- seen.add(url)
295
-
296
- title = (r.get("title") or "").strip()
297
- snippet = clean_text(r.get("snippet") or "")
298
-
299
- try:
300
- page_text = fetch_page_text(url)
301
- except Exception:
302
- page_text = ""
303
-
304
- # Always include snippet as backup material
305
- combined = (page_text or "") + ("\n\n" + snippet if snippet else "")
306
- chunks = chunk_text(combined, CHUNK_SIZE, CHUNK_OVERLAP)
307
-
308
- if not chunks and snippet:
309
- chunks = [snippet]
310
-
311
- scored = sorted([(relevance_score(c, query), c) for c in chunks], key=lambda x: x[0], reverse=True)
312
- top = [c for _, c in scored[:CHUNKS_PER_SOURCE]]
313
-
314
- if not top:
315
- top = [combined[:CHUNK_SIZE]] if combined else []
316
-
317
- sources.append({"title": title, "url": url, "chunks": top})
318
-
319
- return sources
320
-
321
-
322
- def sources_block(sources: List[Dict[str, Any]]) -> str:
323
- blocks = []
324
- for i, s in enumerate(sources):
325
- chunk_block = "\n".join([f"- CHUNK {j+1}: {c}" for j, c in enumerate(s.get("chunks") or [])])
326
- blocks.append(
327
- f"[SOURCE {i+1}]\nTITLE: {s.get('title','')}\nURL: {s.get('url','')}\nEXCERPTS:\n{chunk_block}"
328
- )
329
- return "\n\n".join(blocks)
330
-
331
-
332
- # -----------------------------
333
- # OpenAI
334
- # -----------------------------
335
- def openai_client() -> OpenAI:
336
- key = os.getenv("OPENAI_API_KEY", "").strip()
337
- if not key:
338
- raise gr.Error("OPENAI_API_KEY ontbreekt in Secrets.")
339
- return OpenAI(api_key=key)
340
-
341
-
342
- def _looks_like_model_not_found(e: Exception) -> bool:
343
- s = str(e).lower()
344
- return ("model" in s and ("not found" in s or "does not exist" in s or "no such model" in s or "404" in s))
345
-
346
-
347
- def openai_chat(system: str, user: str, temperature: float = 0.4, max_tokens: Optional[int] = None) -> str:
348
- client = openai_client()
349
- n = int(max_tokens or OPENAI_MAX_TOKENS)
350
-
351
- # If your env model doesn't exist in the Space runtime, we try fallbacks.
352
- model_candidates = []
353
- if OPENAI_MODEL:
354
- model_candidates.append(OPENAI_MODEL)
355
- # sensible fallbacks
356
- model_candidates += ["gpt-4o-mini", "gpt-4.1-mini", "gpt-4o", "gpt-4.1"]
357
-
358
- seen = set()
359
- models = []
360
- for m in model_candidates:
361
- if m and m not in seen:
362
- models.append(m)
363
- seen.add(m)
364
-
365
- last_err: Optional[Exception] = None
366
-
367
- for model in models:
368
- kwargs = {
369
- "model": model,
370
- "temperature": temperature,
371
- "messages": [
372
- {"role": "system", "content": system},
373
- {"role": "user", "content": user},
374
- ],
375
- }
376
-
377
- try:
378
- # new-ish param in some SDK/model combos:
379
- try:
380
- resp = client.chat.completions.create(**kwargs, max_completion_tokens=n)
381
- except Exception as e:
382
- msg = str(e).lower()
383
- if "max_completion_tokens" in msg or "unsupported" in msg or "invalid_request_error" in msg:
384
- resp = client.chat.completions.create(**kwargs, max_tokens=n)
385
- else:
386
- raise
387
- return resp.choices[0].message.content or ""
388
- except Exception as e:
389
- last_err = e
390
- if _looks_like_model_not_found(e):
391
- continue
392
- raise
393
-
394
- raise gr.Error(f"OpenAI call failed (model issue). Last error: {last_err}")
395
-
396
-
397
- # -----------------------------
398
- # Step A: Build evidence-backed levels (NO separate verify step)
399
- # -----------------------------
400
- def step_a_build_levels_with_evidence(title: str, sources: List[Dict[str, Any]], target_levels: int) -> Dict[str, Any]:
401
- """
402
- Key change:
403
- - We demand every fact includes exactly 1 short quote + URL from provided excerpts.
404
- - This makes "verified_items empty" extremely rare.
405
- """
406
- system = (
407
- "You are a documentary researcher.\n"
408
- "CRITICAL:\n"
409
- "- Use ONLY the provided SOURCES excerpts.\n"
410
- "- Every fact MUST include exactly 1 short QUOTE copied from an excerpt AND its URL.\n"
411
- "- If you cannot find evidence in excerpts, DO NOT output that fact.\n"
412
- "- Output ONLY valid JSON. No markdown. No extra text.\n"
413
- )
414
-
415
- user = f"""
416
- VIDEO TITLE:
417
- {title}
418
-
419
- TASK:
420
- Create up to {target_levels} "levels" that fit the title.
421
- Each level should be a distinct subtopic/item.
422
-
423
- For each level, output:
424
- - level (0..)
425
- - title (short)
426
- - location (if stated else "")
427
- - date_or_period (if stated else "")
428
- - facts: exactly {FACTS_PER_LEVEL} facts if possible (otherwise fewer), where each fact has:
429
- - text: an ATOMIC statement
430
- - evidence: {{ "url": "...", "quote": "..." }} (quote must be copied verbatim from excerpts, <= 20 words)
431
-
432
- RULES:
433
- - Only include facts that are explicitly supported by the excerpts.
434
- - Quotes must be exact and short.
435
- - If evidence isn't present, omit that fact.
436
- - If you cannot find enough facts for a level, still include the level with fewer facts.
437
-
438
- Return EXACT JSON schema:
439
- {{
440
- "angle": "1 sentence angle",
441
- "levels": [
442
- {{
443
- "level": 0,
444
- "title": "...",
445
- "location": "",
446
- "date_or_period": "",
447
- "facts": [
448
- {{
449
- "text": "...",
450
- "evidence": {{"url": "...", "quote": "..."}}
451
- }}
452
- ]
453
- }}
454
- ]
455
- }}
456
-
457
- SOURCES:
458
- {sources_block(sources)}
459
- """.strip()
460
-
461
- out = openai_chat(system, user, temperature=0.2, max_tokens=3500)
462
- return normalize_levels(safe_json_extract(out))
463
-
464
-
465
- def count_total_facts(levels_obj: Dict[str, Any]) -> int:
466
- total = 0
467
- for lv in (levels_obj.get("levels") or []):
468
- if isinstance(lv, dict):
469
- total += len(lv.get("facts") or [])
470
- return total
471
-
472
-
473
- # -----------------------------
474
- # Writing
475
- # -----------------------------
476
- def _format_level_heading(lv: Dict[str, Any]) -> str:
477
- title = (lv.get("title") or "").strip() or "Level"
478
- loc = (lv.get("location") or "").strip()
479
- datep = (lv.get("date_or_period") or "").strip()
480
-
481
- tail_parts = []
482
- if loc:
483
- tail_parts.append(loc)
484
- if datep:
485
- tail_parts.append(datep)
486
-
487
- tail = ""
488
- if tail_parts:
489
- tail = " (" + " — ".join(tail_parts) + ")"
490
- return f"### Level {lv.get('level', 0)} — {title}{tail}"
491
-
492
-
493
  def step_write_script_from_facts(title: str, levels_obj: Dict[str, Any], min_words: int) -> str:
494
  system = (
495
- "You are a professional YouTube documentary writer.\n"
496
  "CRITICAL:\n"
497
  "- You may ONLY state factual claims that are present in LEVELS_JSON.levels[*].facts[*].text.\n"
498
- "- Do NOT mention sources, URLs, quotes, or 'evidence'.\n"
499
  "- Do NOT add new facts.\n"
 
500
  )
501
 
502
  style = f"""
503
  STYLE:
504
- - Total length MUST be at least {min_words} words (if not, expand with analysis, implications, context, and transitions WITHOUT new facts).
505
- - Intro MUST be short and human: 80–130 words.
506
- * No generic “In this video, we will…”
507
- * Start with a concrete hook + a clear promise.
508
- - Use headings per level.
509
- - Spoken pacing: varied rhythm, not academic.
510
- - Outro: 70–120 words + 1 short CTA.
 
511
  """.strip()
512
 
513
  user = f"""
@@ -516,51 +26,43 @@ VIDEO TITLE: {title}
516
  LEVELS_JSON:
517
  {json.dumps(levels_obj, ensure_ascii=False)}
518
 
519
- Write the full script in Dutch, with the headings:
520
- Use exactly:
521
- {_format_level_heading({"level":0,"title":"<example>","location":"<optional>","date_or_period":"<optional>"})}
522
- (But with real data and correct numbering.)
523
-
524
- Remember: no sources/URLs/quotes, no new facts.
525
  """.strip()
526
 
527
- draft = openai_chat(system + "\n\n" + style, user, temperature=0.6, max_tokens=OPENAI_MAX_TOKENS)
528
- return draft.strip()
529
 
530
 
531
  def step_write_fallback_no_hard_facts(title: str, target_levels: int, min_words: int) -> str:
532
- """
533
- When retrieval yields too little solid evidence, we generate a documentary script
534
- that avoids concrete factual assertions and stays in question/analysis/storytelling mode.
535
- """
536
  system = (
537
- "You are a professional YouTube documentary writer.\n"
538
  "CRITICAL:\n"
539
- "- Avoid specific factual claims (names/dates/numbers) unless you are certain.\n"
540
- "- Prefer: questions, possibilities, scenarios, motivations, stakes, and what we'd need to verify.\n"
541
  "- Do NOT mention sources or that you lacked sources.\n"
542
  "- Output only the script.\n"
 
543
  )
544
 
545
  style = f"""
546
  STYLE:
547
- - Dutch.
548
- - At least {min_words} words.
549
- - Intro 80–130 words, human hook.
550
  - Use headings:
551
  ### Level N — <subtopic>
552
- - Each level explores a different angle: origins, why it matters, key tensions, what people get wrong, what to watch for, etc.
553
- - Outro 70–120 words + 1 CTA.
554
  """.strip()
555
 
556
  user = f"""
557
  VIDEO TITLE: {title}
558
  Create {target_levels} levels.
559
 
560
- Write a documentary-style script that stays compelling WITHOUT relying on hard facts.
561
  """.strip()
562
 
563
- return openai_chat(system + "\n\n" + style, user, temperature=0.75, max_tokens=OPENAI_MAX_TOKENS).strip()
564
 
565
 
566
  def step_humanize_pass(title: str, script: str) -> str:
@@ -568,8 +70,9 @@ def step_humanize_pass(title: str, script: str) -> str:
568
  "You rewrite scripts to sound like a real human narrator.\n"
569
  "Rules:\n"
570
  "- Keep structure and headings.\n"
571
- "- Remove stiffness, repetition, template phrases.\n"
572
- "- Don't add new factual claims.\n"
 
573
  )
574
  user = f"""
575
  VIDEO TITLE: {title}
@@ -577,115 +80,40 @@ VIDEO TITLE: {title}
577
  SCRIPT:
578
  {script}
579
 
580
- Rewrite to be more human and less AI-toned. Keep headings.
581
  """.strip()
582
- return openai_chat(system, user, temperature=0.7, max_tokens=OPENAI_MAX_TOKENS).strip()
583
 
584
 
585
  def ensure_min_words(script: str, min_words: int) -> str:
586
- wc = word_count(script)
587
- if wc >= min_words:
588
- return script
589
- # expand without adding new facts: add reflection, stakes, transitions
590
- need = min_words - wc
591
- add = max(500, min(1200, need + 250))
592
- system = (
593
- "Continue the Dutch documentary script.\n"
594
- "CRITICAL:\n"
595
- "- Do not add new factual claims.\n"
596
- "- Expand with analysis, implications, scene-setting, and smoother transitions.\n"
597
- "- Continue where it ends.\n"
598
- )
599
- user = f"""
 
 
 
 
 
 
 
600
  CURRENT_SCRIPT:
601
  {script}
602
 
603
- Add about {add} words. Continue seamlessly.
604
  """.strip()
605
- cont = openai_chat(system, user, temperature=0.6, max_tokens=OPENAI_MAX_TOKENS).strip()
606
- return script.rstrip() + "\n\n" + cont
607
-
608
-
609
- # -----------------------------
610
- # Main
611
- # -----------------------------
612
- def generate(title: str, min_words: int, target_levels: int, request: gr.Request):
613
- title = (title or "").strip()
614
- if not title:
615
- raise gr.Error("Vul een video titel in.")
616
-
617
- key = request.client.host if request and request.client else "global"
618
- rate_limit(key)
619
-
620
- serp_key = os.getenv("SERPAPI_API_KEY", "").strip()
621
- if not serp_key:
622
- raise gr.Error("SERPAPI_API_KEY ontbreekt in Secrets.")
623
-
624
- # Retrieve
625
- serp = serpapi_search(title, serp_key, num_results=MAX_SOURCES)
626
- sources = build_sources(serp, query=title)
627
-
628
- # If retrieval is extremely weak, still proceed to fallback script (no crash)
629
- if not sources:
630
- script = step_write_fallback_no_hard_facts(title, target_levels=target_levels, min_words=min_words)
631
- script = step_humanize_pass(title, script)
632
- script = ensure_min_words(script, min_words)
633
- wc = word_count(script)
634
- return script.rstrip() + f"\n\n---\nWord count: {wc}\n"
635
-
636
- # Evidence-backed extraction
637
- levels_obj = step_a_build_levels_with_evidence(title, sources, target_levels=target_levels)
638
- total_facts = count_total_facts(levels_obj)
639
-
640
- # If too few facts survive, switch to no-hard-facts script (instead of raising gr.Error)
641
- if total_facts < MIN_FACTS_TOTAL:
642
- script = step_write_fallback_no_hard_facts(title, target_levels=target_levels, min_words=min_words)
643
- script = step_humanize_pass(title, script)
644
- script = ensure_min_words(script, min_words)
645
- wc = word_count(script)
646
- return script.rstrip() + f"\n\n---\nWord count: {wc}\n"
647
-
648
- # Write from verified facts
649
- # We convert headings inside the writer via instruction, but we can also enforce a pre-pass:
650
- # Ensure levels have titles:
651
- for i, lv in enumerate(levels_obj.get("levels") or []):
652
- if isinstance(lv, dict) and not (lv.get("title") or "").strip():
653
- lv["title"] = f"Onderwerp {i+1}"
654
-
655
- script = step_write_script_from_facts(title, levels_obj, min_words=min_words)
656
-
657
- # Humanize + ensure length
658
- script = step_humanize_pass(title, script)
659
- script = ensure_min_words(script, min_words)
660
-
661
- wc = word_count(script)
662
- return script.rstrip() + f"\n\n---\nWord count: {wc}\n"
663
-
664
-
665
- # -----------------------------
666
- # UI (ONLY final script output)
667
- # -----------------------------
668
- with gr.Blocks(title="Universal YouTube Scriptwriter — Human Tone") as demo:
669
- gr.Markdown(
670
- "# Universal YouTube Scriptwriter — Human Tone\n"
671
- "Vul alleen een **video titel** in en klik **Generate**.\n\n"
672
- "- Alleen output: **final script**\n"
673
- "- Geen sources/claims/debug in de UI\n"
674
- "- Geen crash bij ‘te weinig verifieerbaar’ (automatische fallback)\n"
675
- )
676
-
677
- title_in = gr.Textbox(label="Video titel", placeholder="Typ hier je titel…", lines=2)
678
-
679
- with gr.Row():
680
- min_words_in = gr.Slider(
681
- minimum=1200, maximum=8000, value=MIN_WORDS_DEFAULT, step=100, label="Minimale lengte (woorden)"
682
- )
683
- levels_in = gr.Slider(minimum=3, maximum=10, value=8, step=1, label="Aantal levels (max 10)")
684
-
685
- btn = gr.Button("Generate")
686
- script_out = gr.Textbox(label="Final script", lines=26)
687
 
688
- btn.click(fn=generate, inputs=[title_in, min_words_in, levels_in], outputs=[script_out])
 
689
 
690
- if __name__ == "__main__":
691
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  def step_write_script_from_facts(title: str, levels_obj: Dict[str, Any], min_words: int) -> str:
2
  system = (
3
+ "You are a professional YouTube documentary scriptwriter.\n"
4
  "CRITICAL:\n"
5
  "- You may ONLY state factual claims that are present in LEVELS_JSON.levels[*].facts[*].text.\n"
6
+ "- Do NOT mention sources, URLs, quotes, or the word 'evidence'.\n"
7
  "- Do NOT add new facts.\n"
8
+ "- Write in English.\n"
9
  )
10
 
11
  style = f"""
12
  STYLE:
13
+ - Language: English.
14
+ - Length: At least {min_words} words.
15
+ - Hooky intro: 80–140 words, human, specific, no “In this video…”.
16
+ - Use clear section headings for each level:
17
+ "### Level N — Title (Location — Date)" but OMIT missing parts.
18
+ - Strong narrator voice, varied rhythm, not academic.
19
+ - Add smooth transitions between sections (1–3 lines).
20
+ - Ending: 80–140 words + 1 short CTA.
21
  """.strip()
22
 
23
  user = f"""
 
26
  LEVELS_JSON:
27
  {json.dumps(levels_obj, ensure_ascii=False)}
28
 
29
+ Write the full script using ONLY the facts in LEVELS_JSON.
30
+ Remember: English only. No sources/quotes/URLs. No new facts.
 
 
 
 
31
  """.strip()
32
 
33
+ return openai_chat(system + "\n\n" + style, user, temperature=0.65, max_tokens=OPENAI_MAX_TOKENS).strip()
 
34
 
35
 
36
  def step_write_fallback_no_hard_facts(title: str, target_levels: int, min_words: int) -> str:
 
 
 
 
37
  system = (
38
+ "You are a professional YouTube documentary scriptwriter.\n"
39
  "CRITICAL:\n"
40
+ "- Avoid specific factual assertions (names/dates/numbers) unless they are undeniably common knowledge.\n"
41
+ "- Prefer: questions, competing explanations, scenarios, mechanisms, what would be needed to verify.\n"
42
  "- Do NOT mention sources or that you lacked sources.\n"
43
  "- Output only the script.\n"
44
+ "- Write in English.\n"
45
  )
46
 
47
  style = f"""
48
  STYLE:
49
+ - Language: English.
50
+ - Length: At least {min_words} words.
51
+ - Hooky intro: 80–140 words.
52
  - Use headings:
53
  ### Level N — <subtopic>
54
+ - Each level explores a different lens: types, formation, eruption styles, hazards, misconceptions, real-world examples (without hard specifics), why it matters.
55
+ - Ending: 80–140 words + 1 short CTA.
56
  """.strip()
57
 
58
  user = f"""
59
  VIDEO TITLE: {title}
60
  Create {target_levels} levels.
61
 
62
+ Write a compelling documentary-style script WITHOUT relying on hard facts.
63
  """.strip()
64
 
65
+ return openai_chat(system + "\n\n" + style, user, temperature=0.8, max_tokens=OPENAI_MAX_TOKENS).strip()
66
 
67
 
68
  def step_humanize_pass(title: str, script: str) -> str:
 
70
  "You rewrite scripts to sound like a real human narrator.\n"
71
  "Rules:\n"
72
  "- Keep structure and headings.\n"
73
+ "- Remove stiffness, repetition, and template phrasing.\n"
74
+ "- Do NOT add new factual claims.\n"
75
+ "- Keep it in English.\n"
76
  )
77
  user = f"""
78
  VIDEO TITLE: {title}
 
80
  SCRIPT:
81
  {script}
82
 
83
+ Rewrite to be more human and less AI-toned. Keep headings. English only.
84
  """.strip()
85
+ return openai_chat(system, user, temperature=0.75, max_tokens=OPENAI_MAX_TOKENS).strip()
86
 
87
 
88
  def ensure_min_words(script: str, min_words: int) -> str:
89
+ """
90
+ Stronger length enforcement: keep expanding (without adding new facts)
91
+ until we hit min_words or we hit a safe iteration cap.
92
+ """
93
+ max_rounds = 5
94
+ for _ in range(max_rounds):
95
+ wc = word_count(script)
96
+ if wc >= min_words:
97
+ return script
98
+
99
+ need = min_words - wc
100
+ add = max(700, min(1600, need + 300))
101
+
102
+ system = (
103
+ "Continue the documentary script in English.\n"
104
+ "CRITICAL:\n"
105
+ "- Do not add new factual claims.\n"
106
+ "- Expand with explanation, implications, analogies, scene-setting, and smoother transitions.\n"
107
+ "- Continue exactly where it ends.\n"
108
+ )
109
+ user = f"""
110
  CURRENT_SCRIPT:
111
  {script}
112
 
113
+ Add about {add} words. Continue seamlessly. English only.
114
  """.strip()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115
 
116
+ cont = openai_chat(system, user, temperature=0.65, max_tokens=OPENAI_MAX_TOKENS).strip()
117
+ script = script.rstrip() + "\n\n" + cont
118
 
119
+ return script