Becio commited on
Commit
5e2db7a
·
verified ·
1 Parent(s): 20a6edb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +146 -188
app.py CHANGED
@@ -1,31 +1,24 @@
1
  # app.py
2
- # Universal YouTube Scriptwriter (Verified-only) — Levels/Countdown — 3000+ words
3
  #
4
- # ✅ Universeel: geen onderwerp-specifieke regels of filters.
5
- # ✅ Fact-checked: claims worden geverifieerd tegen web-excerpts.
6
- # ✅ Lang: minimaal X woorden (default 3000), met veilige uitbreidingsrondes.
7
- # ✅ Robuust: vangt non-JSON model output af (repair + OpenAI JSON repair fallback).
8
- # ✅ OpenAI compat: ondersteunt zowel max_tokens als max_completion_tokens.
 
9
  #
10
- # Secrets (HF Spaces):
11
  # - SERPAPI_API_KEY
12
  # - OPENAI_API_KEY
13
  # - GEMINI_API_KEY
14
  #
15
- # Optioneel:
16
- # - OPENAI_MODEL (default: gpt-5.1)
17
- # - OPENAI_MAX_TOKENS (default: 12000)
18
- # - GEMINI_MODEL (default: auto-pick)
19
- # - MAX_SOURCES (default: 10)
20
- # - CHUNKS_PER_SOURCE (default: 3)
21
- #
22
  # pip install gradio requests trafilatura openai google-genai
23
 
24
  import os
25
  import re
26
  import json
27
  import time
28
- import hashlib
29
  from typing import List, Dict, Any, Optional
30
 
31
  import gradio as gr
@@ -44,18 +37,24 @@ from google import genai
44
  # Config
45
  # -----------------------------
46
  OPENAI_MODEL = os.getenv("OPENAI_MODEL", "gpt-5.1")
47
- OPENAI_MAX_TOKENS = int(os.getenv("OPENAI_MAX_TOKENS", "12000"))
48
 
49
- MAX_SOURCES = int(os.getenv("MAX_SOURCES", "10"))
50
- FETCH_TIMEOUT = int(os.getenv("FETCH_TIMEOUT", "25"))
51
 
52
- CHUNK_SIZE = int(os.getenv("CHUNK_SIZE", "1500"))
53
- CHUNK_OVERLAP = int(os.getenv("CHUNK_OVERLAP", "250"))
54
- CHUNKS_PER_SOURCE = int(os.getenv("CHUNKS_PER_SOURCE", "3"))
55
 
56
- MIN_SECONDS_BETWEEN_RUNS = int(os.getenv("MIN_SECONDS_BETWEEN_RUNS", "20"))
57
  _RATE: Dict[str, float] = {}
58
 
 
 
 
 
 
 
59
  _FETCH_CACHE: Dict[str, str] = {}
60
 
61
 
@@ -89,24 +88,24 @@ def truncate(s: str, n: int) -> str:
89
 
90
  def safe_json_extract(text: str) -> Any:
91
  """
92
- Robust JSON extractor: handles code fences, stray text, and tries to find first valid JSON object/array.
 
 
 
 
93
  """
94
  text = (text or "").strip()
95
- # normalize curly quotes + remove control chars
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
- # strip code fences if present
100
  text = re.sub(r"^```(?:json)?\s*", "", text, flags=re.I).strip()
101
  text = re.sub(r"\s*```$", "", text).strip()
102
 
103
- # direct
104
  try:
105
  return json.loads(text)
106
  except Exception:
107
  pass
108
 
109
- # scan object
110
  start = text.find("{")
111
  if start != -1:
112
  depth = 0
@@ -123,7 +122,6 @@ def safe_json_extract(text: str) -> Any:
123
  except Exception:
124
  pass
125
 
126
- # scan array
127
  start = text.find("[")
128
  if start != -1:
129
  depth = 0
@@ -143,19 +141,44 @@ def safe_json_extract(text: str) -> Any:
143
  raise ValueError("Model output bevat geen parseerbare JSON object/array.")
144
 
145
 
146
- def sha1(s: str) -> str:
147
- return hashlib.sha1((s or "").encode("utf-8")).hexdigest()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
148
 
149
 
150
  # -----------------------------
151
- # SERPAPI + Fetch (universal)
152
  # -----------------------------
153
  def serpapi_search(query: str, serpapi_key: str, num_results: int = MAX_SOURCES) -> List[Dict[str, str]]:
154
  if not serpapi_key:
155
  raise gr.Error("SERPAPI_API_KEY ontbreekt in Secrets.")
156
  url = "https://serpapi.com/search.json"
157
  params = {"engine": "google", "q": query, "api_key": serpapi_key, "num": num_results}
158
- r = requests.get(url, params=params, timeout=30)
159
  r.raise_for_status()
160
  data = r.json()
161
 
@@ -201,7 +224,7 @@ def fetch_page_text(url: str) -> str:
201
  return text
202
 
203
 
204
- def chunk_text(text: str, size: int = CHUNK_SIZE, overlap: int = CHUNK_OVERLAP) -> List[str]:
205
  text = clean_text(text)
206
  if not text:
207
  return []
@@ -224,7 +247,7 @@ def relevance_score(chunk: str, query: str) -> int:
224
  q = (query or "").lower()
225
  tokens = [t for t in re.findall(r"[a-z0-9]+", q) if len(t) >= 4]
226
  score = 0
227
- for t in tokens[:20]:
228
  score += c.count(t)
229
  return score
230
 
@@ -247,25 +270,22 @@ def build_sources(serp_results: List[Dict[str, str]], query: str) -> List[Dict[s
247
  except Exception:
248
  page_text = snippet
249
 
250
- chunks = chunk_text(page_text)
251
  if not chunks and snippet:
252
  chunks = [snippet]
253
 
254
- scored = sorted(
255
- [(relevance_score(c, query), c) for c in chunks],
256
- key=lambda x: x[0],
257
- reverse=True,
258
- )
259
- top_chunks = [c for _, c in scored[:CHUNKS_PER_SOURCE]]
260
- if not top_chunks:
261
- top_chunks = [truncate(page_text, CHUNK_SIZE)]
262
 
263
- sources.append({"title": title, "url": url, "chunks": top_chunks})
264
 
265
  return sources
266
 
267
 
268
  def sources_block(sources: List[Dict[str, Any]]) -> str:
 
269
  blocks = []
270
  for i, s in enumerate(sources):
271
  chunks = s.get("chunks") or []
@@ -276,15 +296,8 @@ def sources_block(sources: List[Dict[str, Any]]) -> str:
276
  return "\n\n".join(blocks)
277
 
278
 
279
- def render_sources(sources: List[Dict[str, Any]]) -> str:
280
- lines = ["## Sources\n"]
281
- for s in sources:
282
- lines.append(f"- {s.get('title','').strip()} — {s.get('url','').strip()}")
283
- return "\n".join(lines)
284
-
285
-
286
  # -----------------------------
287
- # OpenAI (compat with max_tokens / max_completion_tokens)
288
  # -----------------------------
289
  def openai_client() -> OpenAI:
290
  key = os.getenv("OPENAI_API_KEY", "").strip()
@@ -306,7 +319,6 @@ def openai_chat(system: str, user: str, temperature: float = 0.4, max_tokens: Op
306
  ],
307
  }
308
 
309
- # Prefer max_completion_tokens (newer models), fallback to max_tokens (older)
310
  try:
311
  resp = client.chat.completions.create(**kwargs, max_completion_tokens=n)
312
  except Exception as e:
@@ -320,7 +332,7 @@ def openai_chat(system: str, user: str, temperature: float = 0.4, max_tokens: Op
320
 
321
 
322
  # -----------------------------
323
- # Gemini (robust model auto-pick)
324
  # -----------------------------
325
  def gemini_client():
326
  key = os.getenv("GEMINI_API_KEY", "").strip()
@@ -345,21 +357,10 @@ def _pick_gemini_text_model(client) -> str:
345
 
346
  def score(n: str) -> tuple:
347
  nl = n.lower()
348
- return (
349
- 0 if "pro" in nl else 1,
350
- 0 if "flash" in nl else 1,
351
- 0 if "gemini" in nl else 1,
352
- len(n),
353
- )
354
 
355
  names = sorted(set(names), key=score)
356
- preferred = [
357
- "models/gemini-1.5-pro",
358
- "models/gemini-1.5-flash",
359
- "models/gemini-pro",
360
- "models/gemini-pro-latest",
361
- "models/gemini-1.0-pro",
362
- ]
363
  for p in preferred:
364
  if p in names:
365
  return p
@@ -381,7 +382,6 @@ def gemini_generate(prompt: str, temperature: float = 0.0) -> str:
381
  except Exception:
382
  pass
383
 
384
- # dedup keep order
385
  seen = set()
386
  ordered = []
387
  for c in candidates:
@@ -405,7 +405,7 @@ def gemini_generate(prompt: str, temperature: float = 0.0) -> str:
405
 
406
 
407
  # -----------------------------
408
- # Universal ranking (topic-agnostic)
409
  # -----------------------------
410
  _NUM_RE = re.compile(r"\b\d{1,7}\b")
411
  _IMPACT_WORDS = {
@@ -416,12 +416,8 @@ _IMPACT_WORDS = {
416
  "million", "billion", "usd", "eur", "$", "£", "€",
417
  }
418
 
 
419
  def severity_score_from_claims(claim_texts: List[str]) -> Optional[float]:
420
- """
421
- Topic-agnostic best-effort:
422
- Finds largest non-year number in claims that contain impact-ish words.
423
- If none found, returns None.
424
- """
425
  best: Optional[float] = None
426
  for t in claim_texts:
427
  tl = t.lower()
@@ -429,7 +425,6 @@ def severity_score_from_claims(claim_texts: List[str]) -> Optional[float]:
429
  continue
430
  for n in _NUM_RE.findall(tl):
431
  val = float(n)
432
- # ignore likely years
433
  if len(n) == 4 and 1800 <= val <= 2100:
434
  continue
435
  if best is None or val > best:
@@ -440,7 +435,7 @@ def severity_score_from_claims(claim_texts: List[str]) -> Optional[float]:
440
  # -----------------------------
441
  # Pipeline steps
442
  # -----------------------------
443
- def step_a_extract_items(title: str, sources: List[Dict[str, Any]], max_items: int = 24) -> Dict[str, Any]:
444
  system = (
445
  "You are a documentary researcher and script planner.\n"
446
  "You must ground ALL factual statements in the provided SOURCES excerpts.\n"
@@ -454,7 +449,6 @@ We are preparing a YouTube documentary video based on this title:
454
  Task:
455
  1) Propose an angle (1 sentence).
456
  2) Extract up to {max_items} candidate items that fit the title.
457
- Each item should work as one entry in a countdown/levels structure.
458
  3) For each item provide:
459
  - item_id
460
  - item_name
@@ -463,7 +457,7 @@ Task:
463
  - claims: 5–9 ATOMIC factual claims with unique ids
464
 
465
  Rules:
466
- - Claims must be ATOMIC (one fact per claim).
467
  - Every claim must be supported by the provided excerpts. If not clearly present, do NOT include it.
468
  - If fewer items exist, return fewer. Do NOT invent.
469
 
@@ -486,16 +480,11 @@ SOURCES:
486
  """.strip()
487
 
488
  out = openai_chat(system, user, temperature=0.25)
489
- return safe_json_extract(out)
490
 
491
 
492
  def step_b_verify_claims(plan: Dict[str, Any], sources: List[Dict[str, Any]]) -> Dict[str, Any]:
493
- """
494
- Robust verification:
495
- - Gemini tries
496
- - repair loop if non-JSON
497
- - OpenAI JSON repair fallback if needed
498
- """
499
  src_block = sources_block(sources)
500
 
501
  system_rules = """
@@ -507,21 +496,14 @@ Output MUST be valid JSON only.
507
  No markdown. No extra text.
508
 
509
  For each claim:
510
- - verdict must be exactly one of:
511
- "supported"
512
- "not_supported"
513
- "contradicted"
514
-
515
- Evidence rules:
516
- - If verdict is "supported" or "contradicted":
517
- include exactly 1 short quote (<=20 words) and its URL.
518
- - If verdict is "not_supported":
519
- evidence must [].
520
 
521
  Fix rules:
522
- - If supported: fix must be "keep"
523
- - If not_supported: fix must be "remove or rewrite to match sources"
524
- - If contradicted: fix must be "remove"
525
 
526
  Return EXACTLY:
527
  {
@@ -536,15 +518,28 @@ Return EXACTLY:
536
  }
537
  """.strip()
538
 
539
- # flatten claims
540
  claims: List[Dict[str, str]] = []
541
  for item in (plan.get("items") or []):
 
 
542
  for c in (item.get("claims") or []):
 
 
543
  cid = (c.get("id") or "").strip()
544
  txt = (c.get("text") or "").strip()
545
  if cid and txt:
546
  claims.append({"id": cid, "text": txt})
547
 
 
 
 
 
 
 
 
 
 
 
548
  def verify_batch(batch_claims: List[Dict[str, str]]) -> List[Dict[str, Any]]:
549
  user = f"""
550
  CLAIMS:
@@ -557,88 +552,65 @@ Return JSON only.
557
  """.strip()
558
  prompt = system_rules + "\n\n" + user
559
 
560
- def try_parse(s: str) -> Optional[List[Dict[str, Any]]]:
561
- try:
562
- parsed = safe_json_extract(s)
563
- v = parsed.get("verifications") if isinstance(parsed, dict) else None
564
- if isinstance(v, list):
565
- return v
566
- except Exception:
567
- return None
568
- return None
569
-
570
- # 1) Gemini first attempt
571
  out = gemini_generate(prompt, temperature=0.0)
572
  parsed = try_parse(out)
573
  if parsed is not None:
574
  return parsed
575
 
576
- # 2) Repair attempts (Gemini)
577
- repair_instructions = [
578
- "You MUST output ONLY valid JSON. No markdown. Start with { and end with }.",
579
  "Return only the JSON object again. Nothing else.",
580
- "STRICT: Output must be a single JSON object with key 'verifications'.",
581
- "Return ONLY JSON. Do not include any commentary or code fences.",
582
  ]
583
- for ins in repair_instructions:
584
- out = gemini_generate(
585
- prompt + "\n\n" + ins + f"\n\nPREVIOUS_OUTPUT:\n{out}",
586
- temperature=0.0
587
- )
588
  parsed = try_parse(out)
589
  if parsed is not None:
590
  return parsed
591
 
592
- # 3) OpenAI JSON repair fallback (reformat only)
593
  repair_system = "You are a JSON repair tool. Output ONLY valid JSON. No markdown, no extra text."
594
  repair_user = f"""
595
- Convert the following text into ONLY valid JSON matching this schema:
596
  {{
597
  "verifications": [
598
- {{
599
- "id": "string",
600
- "verdict": "supported|not_supported|contradicted",
601
- "evidence": [{{"url":"string","quote":"string"}}],
602
- "fix": "keep|remove|remove or rewrite to match sources"
603
- }}
604
  ]
605
  }}
606
 
607
  TEXT_TO_CONVERT:
608
  {out}
609
  """.strip()
610
- fixed = openai_chat(repair_system, repair_user, temperature=0.0, max_tokens=3000)
611
  parsed = try_parse(fixed)
612
- if parsed is not None:
613
- return parsed
614
-
615
- # If still failing, return empty list (do not crash)
616
- return []
617
 
618
  all_v: List[Dict[str, Any]] = []
619
- batch_size = 20 # smaller batch => less format drift
620
- for i in range(0, len(claims), batch_size):
621
- part = claims[i : i + batch_size]
622
- all_v.extend(verify_batch(part))
623
 
624
  return {"verifications": all_v}
625
 
626
 
627
- def step_c_build_verified(plan: Dict[str, Any], verification: Dict[str, Any], min_supported_claims: int = 3) -> Dict[str, Any]:
628
- vmap = {v.get("id"): v for v in (verification.get("verifications") or []) if v.get("id")}
 
 
629
 
630
  verified_items = []
631
  for item in (plan.get("items") or []):
 
 
632
  supported_claims = []
633
  for c in (item.get("claims") or []):
 
 
634
  cid = c.get("id")
635
  if not cid:
636
  continue
637
  v = vmap.get(cid)
638
  if v and v.get("verdict") == "supported":
639
- supported_claims.append(
640
- {"id": cid, "text": c.get("text", ""), "evidence": (v.get("evidence") or [])[:1]}
641
- )
642
 
643
  if len(supported_claims) < min_supported_claims:
644
  continue
@@ -665,17 +637,14 @@ def step_c_build_verified(plan: Dict[str, Any], verification: Dict[str, Any], mi
665
  def step_d_select_and_levels(verified: Dict[str, Any], target_levels: int) -> Dict[str, Any]:
666
  items = list(verified.get("verified_items") or [])
667
 
668
- # rank: higher severity_score first, None last
669
  def key_desc(it: Dict[str, Any]):
670
  s = it.get("severity_score")
671
  return (s is None, -(s if s is not None else -1))
672
 
673
  items.sort(key=key_desc)
674
-
675
- # select
676
  items = items[: max(1, min(target_levels, len(items)))]
677
 
678
- # assign levels so Level 0 least severe, last most severe
679
  asc = sorted(items, key=lambda it: (it.get("severity_score") is None, (it.get("severity_score") or -1)))
680
  for idx, it in enumerate(asc):
681
  it["level"] = idx
@@ -686,30 +655,33 @@ def step_d_select_and_levels(verified: Dict[str, Any], target_levels: int) -> Di
686
  return out
687
 
688
 
689
- def render_claims_report(verification: Dict[str, Any]) -> str:
690
- lines = ["## Claims & verificatie\n"]
 
691
  for v in (verification.get("verifications") or []):
 
 
692
  verdict = v.get("verdict", "")
693
  cid = v.get("id", "")
694
  fix = v.get("fix", "")
695
  lines.append(f"- **{cid}** — `{verdict}` — {fix}")
696
- for e in (v.get("evidence") or [])[:1]:
697
- url = e.get("url", "")
698
- quote = e.get("quote", "")
699
- if url or quote:
700
- lines.append(f" - {url} — “{quote}”")
701
  return "\n".join(lines)
702
 
703
 
704
  # -----------------------------
705
- # Script writing (verified-only, long)
706
  # -----------------------------
707
  def step_e_write_script(title: str, verified_ranked: Dict[str, Any], min_words: int) -> str:
708
  system = (
709
  "You are a careful documentary narrator and scriptwriter.\n"
710
  "CRITICAL: You must NOT introduce ANY new factual claims beyond VERIFIED_FACTS.levels[*].supported_claims.\n"
711
  "Do NOT add dates, numbers, names, causes, or background unless explicitly present in supported_claims.\n"
712
- "If something isn't verified, omit it or state it's not provided by the sources.\n"
713
  "Write in a natural documentary tone (no hype caps, no clichés).\n"
714
  )
715
 
@@ -742,7 +714,7 @@ Only use facts found in VERIFIED_FACTS.levels[*].supported_claims.
742
  return openai_chat(system + "\n\n" + style, user, temperature=0.55, max_tokens=OPENAI_MAX_TOKENS)
743
 
744
 
745
- def step_f_expand_until_min_words(title: str, verified_ranked: Dict[str, Any], script: str, min_words: int, max_rounds: int = 3) -> str:
746
  wc = word_count(script)
747
  if wc >= min_words:
748
  return script
@@ -759,7 +731,7 @@ def step_f_expand_until_min_words(title: str, verified_ranked: Dict[str, Any], s
759
  break
760
 
761
  remaining = min_words - wc
762
- target_add = max(350, min(1000, remaining + 200))
763
 
764
  user = f"""
765
  VIDEO TITLE: {title}
@@ -790,7 +762,6 @@ def generate(title: str, min_words: int, target_levels: int, request: gr.Request
790
  if not title:
791
  raise gr.Error("Vul een video titel in.")
792
 
793
- # rate limit
794
  key = request.client.host if request and request.client else "global"
795
  rate_limit(key)
796
 
@@ -803,49 +774,37 @@ def generate(title: str, min_words: int, target_levels: int, request: gr.Request
803
  if not sources:
804
  raise gr.Error("Geen bronnen gevonden. Probeer een specifiekere titel.")
805
 
806
- # A: plan
807
- plan = step_a_extract_items(title, sources, max_items=max(18, target_levels * 2 + 6))
808
-
809
- # B: verify (robust)
810
  verification = step_b_verify_claims(plan, sources)
811
-
812
- # C: keep verified
813
- verified = step_c_build_verified(plan, verification, min_supported_claims=3)
814
  if not verified.get("verified_items"):
815
  raise gr.Error("Te weinig verifieerbare items gevonden. Probeer een specifiekere titel of verhoog MAX_SOURCES/CHUNKS_PER_SOURCE.")
816
 
817
- # D: rank + levels
818
  verified_ranked = step_d_select_and_levels(verified, target_levels=target_levels)
819
-
820
- # E: write
821
  script = step_e_write_script(title, verified_ranked, min_words=min_words)
822
-
823
- # F: ensure length
824
- script = step_f_expand_until_min_words(title, verified_ranked, script, min_words=min_words, max_rounds=3)
825
-
826
- # outputs
827
- claims_md = render_claims_report(verification)
828
- sources_md = render_sources(sources)
829
- debug_json = json.dumps(verified_ranked, ensure_ascii=False, indent=2)
830
 
831
  wc = word_count(script)
832
  script = script.rstrip() + f"\n\n---\nWord count: {wc}\n"
833
 
834
- return script, claims_md, sources_md, debug_json
 
 
 
 
835
 
836
 
837
  # -----------------------------
838
- # UI
839
  # -----------------------------
840
- with gr.Blocks(title="Universal YouTube Scriptwriter — Verified Levels") as demo:
841
  gr.Markdown(
842
- "# Universal YouTube Scriptwriter — Verified Levels\n"
843
  "Vul alleen een **video titel** in en klik **Generate**.\n\n"
844
- "**Universeel & robuust:**\n"
845
- "- Geen onderwerp-specifieke code.\n"
846
- "- Claims worden geverifieerd op excerpts.\n"
847
- "- Minimaal 3000 woorden (instelbaar).\n"
848
- "- JSON failures van Gemini worden automatisch gerepareerd.\n"
849
  )
850
 
851
  title_in = gr.Textbox(label="Video titel", placeholder="Typ hier je titel…", lines=2)
@@ -858,10 +817,9 @@ with gr.Blocks(title="Universal YouTube Scriptwriter — Verified Levels") as de
858
 
859
  script_out = gr.Textbox(label="Final script", lines=26)
860
  claims_out = gr.Markdown()
861
- sources_out = gr.Markdown()
862
  debug_out = gr.Textbox(label="Verified facts (JSON) — debug", lines=12)
863
 
864
- btn.click(fn=generate, inputs=[title_in, min_words_in, levels_in], outputs=[script_out, claims_out, sources_out, debug_out])
865
 
866
  if __name__ == "__main__":
867
  demo.launch()
 
1
  # app.py
2
+ # Universal YouTube Scriptwriter — Verified Levels (NO LINKS OVERVIEW) + FIXED "list has no attribute get"
3
  #
4
+ # ✅ Universeel: je vult alleen de titel in.
5
+ # ✅ Verified-only: script mag geen nieuwe feiten toevoegen buiten supported claims.
6
+ # ✅ Geen link-overzicht: Sources output verwijderd + in claims-report geen URLs.
7
+ # ✅ Error fix: model kan plan als JSON array teruggeven -> normalize_plan() voorkomt .get() crash.
8
+ # ✅ OpenAI compat: max_completion_tokens (GPT-5) + fallback max_tokens.
9
+ # ✅ Gemini robuust: JSON repair loop + OpenAI JSON-repair fallback.
10
  #
11
+ # Secrets:
12
  # - SERPAPI_API_KEY
13
  # - OPENAI_API_KEY
14
  # - GEMINI_API_KEY
15
  #
 
 
 
 
 
 
 
16
  # pip install gradio requests trafilatura openai google-genai
17
 
18
  import os
19
  import re
20
  import json
21
  import time
 
22
  from typing import List, Dict, Any, Optional
23
 
24
  import gradio as gr
 
37
  # Config
38
  # -----------------------------
39
  OPENAI_MODEL = os.getenv("OPENAI_MODEL", "gpt-5.1")
40
+ OPENAI_MAX_TOKENS = int(os.getenv("OPENAI_MAX_TOKENS", "9000"))
41
 
42
+ MAX_SOURCES = int(os.getenv("MAX_SOURCES", "6"))
43
+ FETCH_TIMEOUT = int(os.getenv("FETCH_TIMEOUT", "12"))
44
 
45
+ CHUNK_SIZE = int(os.getenv("CHUNK_SIZE", "1400"))
46
+ CHUNK_OVERLAP = int(os.getenv("CHUNK_OVERLAP", "200"))
47
+ CHUNKS_PER_SOURCE = int(os.getenv("CHUNKS_PER_SOURCE", "2"))
48
 
49
+ MIN_SECONDS_BETWEEN_RUNS = int(os.getenv("MIN_SECONDS_BETWEEN_RUNS", "15"))
50
  _RATE: Dict[str, float] = {}
51
 
52
+ # Claim caps (speed + stability)
53
+ CLAIMS_PER_ITEM = int(os.getenv("CLAIMS_PER_ITEM", "6"))
54
+ MAX_VERIFY_CLAIMS = int(os.getenv("MAX_VERIFY_CLAIMS", "120"))
55
+ VERIFY_BATCH_SIZE = int(os.getenv("VERIFY_BATCH_SIZE", "15"))
56
+ MIN_SUPPORTED_CLAIMS = int(os.getenv("MIN_SUPPORTED_CLAIMS", "3"))
57
+
58
  _FETCH_CACHE: Dict[str, str] = {}
59
 
60
 
 
88
 
89
  def safe_json_extract(text: str) -> Any:
90
  """
91
+ Robust JSON extractor:
92
+ - strips code fences
93
+ - normalizes quotes
94
+ - removes control chars
95
+ - tries direct parse, then scans for first valid object/array
96
  """
97
  text = (text or "").strip()
 
98
  text = text.replace("\u201c", '"').replace("\u201d", '"').replace("\u2018", "'").replace("\u2019", "'")
99
  text = re.sub(r"[\x00-\x08\x0b\x0c\x0e-\x1f]", "", text)
100
 
 
101
  text = re.sub(r"^```(?:json)?\s*", "", text, flags=re.I).strip()
102
  text = re.sub(r"\s*```$", "", text).strip()
103
 
 
104
  try:
105
  return json.loads(text)
106
  except Exception:
107
  pass
108
 
 
109
  start = text.find("{")
110
  if start != -1:
111
  depth = 0
 
122
  except Exception:
123
  pass
124
 
 
125
  start = text.find("[")
126
  if start != -1:
127
  depth = 0
 
141
  raise ValueError("Model output bevat geen parseerbare JSON object/array.")
142
 
143
 
144
+ def normalize_plan(obj: Any) -> Dict[str, Any]:
145
+ """
146
+ ✅ FIX voor: AttributeError: 'list' object has no attribute 'get'
147
+ Soms geeft het model een JSON array terug i.p.v. een object.
148
+ Dan maken we er een dict van met key 'items'.
149
+ """
150
+ if isinstance(obj, dict):
151
+ items = obj.get("items")
152
+ if isinstance(items, list):
153
+ return obj
154
+ # als 'items' ontbreekt of fout type
155
+ obj["items"] = items if isinstance(items, list) else []
156
+ obj["angle"] = obj.get("angle", "") or ""
157
+ return obj
158
+
159
+ if isinstance(obj, list):
160
+ return {"angle": "", "items": obj}
161
+
162
+ return {"angle": "", "items": []}
163
+
164
+
165
+ def normalize_verifications(obj: Any) -> Dict[str, Any]:
166
+ if isinstance(obj, dict) and isinstance(obj.get("verifications"), list):
167
+ return obj
168
+ if isinstance(obj, list):
169
+ return {"verifications": obj}
170
+ return {"verifications": []}
171
 
172
 
173
  # -----------------------------
174
+ # SERPAPI + Fetch
175
  # -----------------------------
176
  def serpapi_search(query: str, serpapi_key: str, num_results: int = MAX_SOURCES) -> List[Dict[str, str]]:
177
  if not serpapi_key:
178
  raise gr.Error("SERPAPI_API_KEY ontbreekt in Secrets.")
179
  url = "https://serpapi.com/search.json"
180
  params = {"engine": "google", "q": query, "api_key": serpapi_key, "num": num_results}
181
+ r = requests.get(url, params=params, timeout=25)
182
  r.raise_for_status()
183
  data = r.json()
184
 
 
224
  return text
225
 
226
 
227
+ def chunk_text(text: str, size: int, overlap: int) -> List[str]:
228
  text = clean_text(text)
229
  if not text:
230
  return []
 
247
  q = (query or "").lower()
248
  tokens = [t for t in re.findall(r"[a-z0-9]+", q) if len(t) >= 4]
249
  score = 0
250
+ for t in tokens[:18]:
251
  score += c.count(t)
252
  return score
253
 
 
270
  except Exception:
271
  page_text = snippet
272
 
273
+ chunks = chunk_text(page_text, CHUNK_SIZE, CHUNK_OVERLAP)
274
  if not chunks and snippet:
275
  chunks = [snippet]
276
 
277
+ scored = sorted([(relevance_score(c, query), c) for c in chunks], key=lambda x: x[0], reverse=True)
278
+ top = [c for _, c in scored[:CHUNKS_PER_SOURCE]]
279
+ if not top:
280
+ top = [truncate(page_text, CHUNK_SIZE)]
 
 
 
 
281
 
282
+ sources.append({"title": title, "url": url, "chunks": top})
283
 
284
  return sources
285
 
286
 
287
  def sources_block(sources: List[Dict[str, Any]]) -> str:
288
+ # Alleen intern naar de modellen. Niet zichtbaar in UI als "overzicht".
289
  blocks = []
290
  for i, s in enumerate(sources):
291
  chunks = s.get("chunks") or []
 
296
  return "\n\n".join(blocks)
297
 
298
 
 
 
 
 
 
 
 
299
  # -----------------------------
300
+ # OpenAI (max_completion_tokens compat)
301
  # -----------------------------
302
  def openai_client() -> OpenAI:
303
  key = os.getenv("OPENAI_API_KEY", "").strip()
 
319
  ],
320
  }
321
 
 
322
  try:
323
  resp = client.chat.completions.create(**kwargs, max_completion_tokens=n)
324
  except Exception as e:
 
332
 
333
 
334
  # -----------------------------
335
+ # Gemini (robust)
336
  # -----------------------------
337
  def gemini_client():
338
  key = os.getenv("GEMINI_API_KEY", "").strip()
 
357
 
358
  def score(n: str) -> tuple:
359
  nl = n.lower()
360
+ return (0 if "pro" in nl else 1, 0 if "flash" in nl else 1, 0 if "gemini" in nl else 1, len(n))
 
 
 
 
 
361
 
362
  names = sorted(set(names), key=score)
363
+ preferred = ["models/gemini-1.5-pro", "models/gemini-1.5-flash", "models/gemini-pro", "models/gemini-pro-latest"]
 
 
 
 
 
 
364
  for p in preferred:
365
  if p in names:
366
  return p
 
382
  except Exception:
383
  pass
384
 
 
385
  seen = set()
386
  ordered = []
387
  for c in candidates:
 
405
 
406
 
407
  # -----------------------------
408
+ # Ranking (topic-agnostic)
409
  # -----------------------------
410
  _NUM_RE = re.compile(r"\b\d{1,7}\b")
411
  _IMPACT_WORDS = {
 
416
  "million", "billion", "usd", "eur", "$", "£", "€",
417
  }
418
 
419
+
420
  def severity_score_from_claims(claim_texts: List[str]) -> Optional[float]:
 
 
 
 
 
421
  best: Optional[float] = None
422
  for t in claim_texts:
423
  tl = t.lower()
 
425
  continue
426
  for n in _NUM_RE.findall(tl):
427
  val = float(n)
 
428
  if len(n) == 4 and 1800 <= val <= 2100:
429
  continue
430
  if best is None or val > best:
 
435
  # -----------------------------
436
  # Pipeline steps
437
  # -----------------------------
438
+ def step_a_extract_items(title: str, sources: List[Dict[str, Any]], max_items: int) -> Dict[str, Any]:
439
  system = (
440
  "You are a documentary researcher and script planner.\n"
441
  "You must ground ALL factual statements in the provided SOURCES excerpts.\n"
 
449
  Task:
450
  1) Propose an angle (1 sentence).
451
  2) Extract up to {max_items} candidate items that fit the title.
 
452
  3) For each item provide:
453
  - item_id
454
  - item_name
 
457
  - claims: 5–9 ATOMIC factual claims with unique ids
458
 
459
  Rules:
460
+ - Claims must be ATOMIC.
461
  - Every claim must be supported by the provided excerpts. If not clearly present, do NOT include it.
462
  - If fewer items exist, return fewer. Do NOT invent.
463
 
 
480
  """.strip()
481
 
482
  out = openai_chat(system, user, temperature=0.25)
483
+ return normalize_plan(safe_json_extract(out))
484
 
485
 
486
  def step_b_verify_claims(plan: Dict[str, Any], sources: List[Dict[str, Any]]) -> Dict[str, Any]:
487
+ plan = normalize_plan(plan)
 
 
 
 
 
488
  src_block = sources_block(sources)
489
 
490
  system_rules = """
 
496
  No markdown. No extra text.
497
 
498
  For each claim:
499
+ - verdict: "supported" | "not_supported" | "contradicted"
500
+ - If supported/contradicted: exactly 1 quote (<=20 words) and its URL
501
+ - If not_supported: evidence []
 
 
 
 
 
 
 
502
 
503
  Fix rules:
504
+ - supported -> "keep"
505
+ - not_supported -> "remove or rewrite to match sources"
506
+ - contradicted -> "remove"
507
 
508
  Return EXACTLY:
509
  {
 
518
  }
519
  """.strip()
520
 
 
521
  claims: List[Dict[str, str]] = []
522
  for item in (plan.get("items") or []):
523
+ if not isinstance(item, dict):
524
+ continue
525
  for c in (item.get("claims") or []):
526
+ if not isinstance(c, dict):
527
+ continue
528
  cid = (c.get("id") or "").strip()
529
  txt = (c.get("text") or "").strip()
530
  if cid and txt:
531
  claims.append({"id": cid, "text": txt})
532
 
533
+ claims = claims[:MAX_VERIFY_CLAIMS]
534
+
535
+ def try_parse(s: str) -> Optional[List[Dict[str, Any]]]:
536
+ try:
537
+ parsed = normalize_verifications(safe_json_extract(s))
538
+ v = parsed.get("verifications")
539
+ return v if isinstance(v, list) else None
540
+ except Exception:
541
+ return None
542
+
543
  def verify_batch(batch_claims: List[Dict[str, str]]) -> List[Dict[str, Any]]:
544
  user = f"""
545
  CLAIMS:
 
552
  """.strip()
553
  prompt = system_rules + "\n\n" + user
554
 
 
 
 
 
 
 
 
 
 
 
 
555
  out = gemini_generate(prompt, temperature=0.0)
556
  parsed = try_parse(out)
557
  if parsed is not None:
558
  return parsed
559
 
560
+ repairs = [
561
+ "You MUST output ONLY valid JSON. Start with { and end with }. No markdown.",
 
562
  "Return only the JSON object again. Nothing else.",
563
+ "STRICT: output a single JSON object with key 'verifications'.",
 
564
  ]
565
+ for ins in repairs:
566
+ out = gemini_generate(prompt + "\n\n" + ins + f"\n\nPREVIOUS_OUTPUT:\n{out}", temperature=0.0)
 
 
 
567
  parsed = try_parse(out)
568
  if parsed is not None:
569
  return parsed
570
 
571
+ # OpenAI JSON repair fallback
572
  repair_system = "You are a JSON repair tool. Output ONLY valid JSON. No markdown, no extra text."
573
  repair_user = f"""
574
+ Convert this text into ONLY valid JSON with schema:
575
  {{
576
  "verifications": [
577
+ {{"id":"string","verdict":"supported|not_supported|contradicted","evidence":[{{"url":"string","quote":"string"}}],"fix":"keep|remove|remove or rewrite to match sources"}}
 
 
 
 
 
578
  ]
579
  }}
580
 
581
  TEXT_TO_CONVERT:
582
  {out}
583
  """.strip()
584
+ fixed = openai_chat(repair_system, repair_user, temperature=0.0, max_tokens=2500)
585
  parsed = try_parse(fixed)
586
+ return parsed if parsed is not None else []
 
 
 
 
587
 
588
  all_v: List[Dict[str, Any]] = []
589
+ for i in range(0, len(claims), VERIFY_BATCH_SIZE):
590
+ all_v.extend(verify_batch(claims[i : i + VERIFY_BATCH_SIZE]))
 
 
591
 
592
  return {"verifications": all_v}
593
 
594
 
595
+ def step_c_build_verified(plan: Dict[str, Any], verification: Dict[str, Any], min_supported_claims: int) -> Dict[str, Any]:
596
+ plan = normalize_plan(plan)
597
+ verification = normalize_verifications(verification)
598
+ vmap = {v.get("id"): v for v in (verification.get("verifications") or []) if isinstance(v, dict) and v.get("id")}
599
 
600
  verified_items = []
601
  for item in (plan.get("items") or []):
602
+ if not isinstance(item, dict):
603
+ continue
604
  supported_claims = []
605
  for c in (item.get("claims") or []):
606
+ if not isinstance(c, dict):
607
+ continue
608
  cid = c.get("id")
609
  if not cid:
610
  continue
611
  v = vmap.get(cid)
612
  if v and v.get("verdict") == "supported":
613
+ supported_claims.append({"id": cid, "text": c.get("text", ""), "evidence": (v.get("evidence") or [])[:1]})
 
 
614
 
615
  if len(supported_claims) < min_supported_claims:
616
  continue
 
637
  def step_d_select_and_levels(verified: Dict[str, Any], target_levels: int) -> Dict[str, Any]:
638
  items = list(verified.get("verified_items") or [])
639
 
 
640
  def key_desc(it: Dict[str, Any]):
641
  s = it.get("severity_score")
642
  return (s is None, -(s if s is not None else -1))
643
 
644
  items.sort(key=key_desc)
 
 
645
  items = items[: max(1, min(target_levels, len(items)))]
646
 
647
+ # Level 0 least severe, last most severe
648
  asc = sorted(items, key=lambda it: (it.get("severity_score") is None, (it.get("severity_score") or -1)))
649
  for idx, it in enumerate(asc):
650
  it["level"] = idx
 
655
  return out
656
 
657
 
658
+ def render_claims_report_no_links(verification: Dict[str, Any]) -> str:
659
+ verification = normalize_verifications(verification)
660
+ lines = ["## Claims & verificatie (zonder links)\n"]
661
  for v in (verification.get("verifications") or []):
662
+ if not isinstance(v, dict):
663
+ continue
664
  verdict = v.get("verdict", "")
665
  cid = v.get("id", "")
666
  fix = v.get("fix", "")
667
  lines.append(f"- **{cid}** — `{verdict}` — {fix}")
668
+ ev = v.get("evidence") or []
669
+ if isinstance(ev, list) and ev and isinstance(ev[0], dict):
670
+ q = ev[0].get("quote", "")
671
+ if q:
672
+ lines.append(f" - “{q}”")
673
  return "\n".join(lines)
674
 
675
 
676
  # -----------------------------
677
+ # Script writing
678
  # -----------------------------
679
  def step_e_write_script(title: str, verified_ranked: Dict[str, Any], min_words: int) -> str:
680
  system = (
681
  "You are a careful documentary narrator and scriptwriter.\n"
682
  "CRITICAL: You must NOT introduce ANY new factual claims beyond VERIFIED_FACTS.levels[*].supported_claims.\n"
683
  "Do NOT add dates, numbers, names, causes, or background unless explicitly present in supported_claims.\n"
684
+ "If something isn't verified, omit it or state it isn't provided by the sources.\n"
685
  "Write in a natural documentary tone (no hype caps, no clichés).\n"
686
  )
687
 
 
714
  return openai_chat(system + "\n\n" + style, user, temperature=0.55, max_tokens=OPENAI_MAX_TOKENS)
715
 
716
 
717
+ def step_f_expand_until_min_words(title: str, verified_ranked: Dict[str, Any], script: str, min_words: int, max_rounds: int = 1) -> str:
718
  wc = word_count(script)
719
  if wc >= min_words:
720
  return script
 
731
  break
732
 
733
  remaining = min_words - wc
734
+ target_add = max(450, min(1100, remaining + 250))
735
 
736
  user = f"""
737
  VIDEO TITLE: {title}
 
762
  if not title:
763
  raise gr.Error("Vul een video titel in.")
764
 
 
765
  key = request.client.host if request and request.client else "global"
766
  rate_limit(key)
767
 
 
774
  if not sources:
775
  raise gr.Error("Geen bronnen gevonden. Probeer een specifiekere titel.")
776
 
777
+ plan = step_a_extract_items(title, sources, max_items=max(12, target_levels * 2))
 
 
 
778
  verification = step_b_verify_claims(plan, sources)
779
+ verified = step_c_build_verified(plan, verification, min_supported_claims=min(MIN_SUPPORTED_CLAIMS, CLAIMS_PER_ITEM))
 
 
780
  if not verified.get("verified_items"):
781
  raise gr.Error("Te weinig verifieerbare items gevonden. Probeer een specifiekere titel of verhoog MAX_SOURCES/CHUNKS_PER_SOURCE.")
782
 
 
783
  verified_ranked = step_d_select_and_levels(verified, target_levels=target_levels)
 
 
784
  script = step_e_write_script(title, verified_ranked, min_words=min_words)
785
+ script = step_f_expand_until_min_words(title, verified_ranked, script, min_words=min_words, max_rounds=1)
 
 
 
 
 
 
 
786
 
787
  wc = word_count(script)
788
  script = script.rstrip() + f"\n\n---\nWord count: {wc}\n"
789
 
790
+ # OUTPUT: geen sources/links-overzicht
791
+ claims_md = render_claims_report_no_links(verification)
792
+ debug_json = json.dumps(verified_ranked, ensure_ascii=False, indent=2)
793
+
794
+ return script, claims_md, debug_json
795
 
796
 
797
  # -----------------------------
798
+ # UI (zonder sources output)
799
  # -----------------------------
800
+ with gr.Blocks(title="Universal YouTube Scriptwriter — Verified Levels (No Links)") as demo:
801
  gr.Markdown(
802
+ "# Universal YouTube Scriptwriter — Verified Levels (No Links)\n"
803
  "Vul alleen een **video titel** in en klik **Generate**.\n\n"
804
+ "- Universeel (geen onderwerp-code)\n"
805
+ "- Verified-only script\n"
806
+ "- Minimaal 3000 woorden (instelbaar)\n"
807
+ "- Geen bronnen/links-overzicht in output\n"
 
808
  )
809
 
810
  title_in = gr.Textbox(label="Video titel", placeholder="Typ hier je titel…", lines=2)
 
817
 
818
  script_out = gr.Textbox(label="Final script", lines=26)
819
  claims_out = gr.Markdown()
 
820
  debug_out = gr.Textbox(label="Verified facts (JSON) — debug", lines=12)
821
 
822
+ btn.click(fn=generate, inputs=[title_in, min_words_in, levels_in], outputs=[script_out, claims_out, debug_out])
823
 
824
  if __name__ == "__main__":
825
  demo.launch()