Becio commited on
Commit
00fe2c2
·
verified ·
1 Parent(s): 0585ffa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +187 -193
app.py CHANGED
@@ -7,12 +7,16 @@ from typing import List, Dict, Any
7
  import gradio as gr
8
  import requests
9
 
 
10
  try:
11
  import trafilatura
12
  except Exception:
13
  trafilatura = None
14
 
 
15
  from openai import OpenAI
 
 
16
  from google import genai
17
 
18
 
@@ -25,7 +29,7 @@ MAX_SOURCES = 4
25
  MAX_EXCERPT_CHARS = 2500
26
  FETCH_TIMEOUT = 25
27
 
28
- _RATE = {}
29
  MIN_SECONDS_BETWEEN_RUNS = 20
30
 
31
 
@@ -37,7 +41,7 @@ def _now() -> float:
37
 
38
 
39
  def rate_limit(key: str):
40
- last = _RATE.get(key, 0)
41
  if _now() - last < MIN_SECONDS_BETWEEN_RUNS:
42
  wait = int(MIN_SECONDS_BETWEEN_RUNS - (_now() - last))
43
  raise gr.Error(f"Even wachten aub ({wait}s). Probeer zo opnieuw.")
@@ -49,7 +53,8 @@ def clean_text(s: str) -> str:
49
 
50
 
51
  def clip(s: str, n: int) -> str:
52
- return (s or "")[:n]
 
53
 
54
 
55
  def safe_json_extract(text: str) -> Any:
@@ -62,7 +67,7 @@ def safe_json_extract(text: str) -> Any:
62
  except Exception:
63
  pass
64
 
65
- # object
66
  start = text.find("{")
67
  if start != -1:
68
  depth = 0
@@ -73,9 +78,9 @@ def safe_json_extract(text: str) -> Any:
73
  elif ch == "}":
74
  depth -= 1
75
  if depth == 0:
76
- return json.loads(text[start:i + 1])
77
 
78
- # array
79
  start = text.find("[")
80
  if start != -1:
81
  depth = 0
@@ -86,7 +91,7 @@ def safe_json_extract(text: str) -> Any:
86
  elif ch == "]":
87
  depth -= 1
88
  if depth == 0:
89
- return json.loads(text[start:i + 1])
90
 
91
  raise ValueError("Model output bevat geen JSON object/array.")
92
 
@@ -103,7 +108,7 @@ def serpapi_search(query: str, serpapi_key: str, num_results: int = MAX_SOURCES)
103
  r.raise_for_status()
104
  data = r.json()
105
 
106
- out = []
107
  for item in (data.get("organic_results") or [])[:num_results]:
108
  out.append(
109
  {
@@ -133,7 +138,7 @@ def fetch_page_text(url: str) -> str:
133
 
134
 
135
  def build_sources(serp_results: List[Dict[str, str]]) -> List[Dict[str, str]]:
136
- sources = []
137
  for r in serp_results:
138
  url = (r.get("url") or "").strip()
139
  if not url:
@@ -156,7 +161,7 @@ def build_sources(serp_results: List[Dict[str, str]]) -> List[Dict[str, str]]:
156
  # OpenAI calls
157
  # -----------------------------
158
  def openai_client() -> OpenAI:
159
- key = os.getenv("OPENAI_API_KEY", "").strip()
160
  if not key:
161
  raise gr.Error("OPENAI_API_KEY ontbreekt in Secrets.")
162
  return OpenAI(api_key=key)
@@ -167,99 +172,80 @@ def openai_chat(system: str, user: str, temperature: float = 0.4) -> str:
167
  resp = client.chat.completions.create(
168
  model=OPENAI_MODEL,
169
  temperature=temperature,
170
- messages=[
171
- {"role": "system", "content": system},
172
- {"role": "user", "content": user},
173
- ],
174
  )
175
  return resp.choices[0].message.content or ""
176
 
177
 
178
  # -----------------------------
179
- # Gemini (robust + auto-pick)
180
  # -----------------------------
181
  def gemini_client():
182
- key = os.getenv("GEMINI_API_KEY", "").strip()
183
  if not key:
184
- raise gr.Error("GEMINI_API_KEY ontbreekt in Secrets.")
185
- return genai.Client(api_key=key)
186
-
187
-
188
- def _pick_gemini_text_model(client) -> str:
189
- """
190
- Picks a model that supports text generateContent for your key.
191
- Avoids audio/image/tts models automatically.
192
- """
193
- names = []
194
- for m in client.models.list():
195
- name = getattr(m, "name", "") or ""
196
- if not name:
197
- continue
198
- low = name.lower()
199
-
200
- # Exclude non-text endpoints
201
- if any(x in low for x in ["audio", "tts", "image", "vision", "embedding", "embed", "code_execution"]):
202
- continue
203
-
204
- # Many model names are "models/...." already
205
- names.append(name)
206
-
207
- if not names:
208
- raise gr.Error("Gemini: geen modellen beschikbaar voor deze API key (ListModels leeg).")
209
-
210
- def score(n: str) -> tuple:
211
- nl = n.lower()
212
- return (
213
- 0 if "pro" in nl else 1,
214
- 0 if "flash" in nl else 1,
215
- 0 if "gemini" in nl else 1,
216
- len(n),
217
- )
218
-
219
- names = sorted(set(names), key=score)
220
-
221
- # Prefer stable, widely available
222
- preferred_order = [
223
- "models/gemini-1.5-pro",
224
- "models/gemini-1.5-flash",
225
- "models/gemini-pro",
226
- "models/gemini-pro-latest",
227
- "models/gemini-1.0-pro",
228
- ]
229
- for p in preferred_order:
230
- if p in names:
231
- return p
232
-
233
- return names[0]
234
 
235
 
236
  def gemini_generate(prompt: str, temperature: float = 0.2) -> str:
237
  client = gemini_client()
 
 
238
 
239
- # If user set a model in Secrets, try it first (but still fallback if not found)
240
  explicit = (os.getenv("GEMINI_MODEL") or "").strip()
241
- candidates = []
242
  if explicit:
243
  candidates.append(explicit)
244
- if not explicit.startswith("models/"):
245
- candidates.append("models/" + explicit)
246
 
247
- # Add an auto-picked model for this key
248
  try:
249
- candidates.append(_pick_gemini_text_model(client))
 
 
 
 
250
  except Exception:
251
  pass
252
 
253
- # De-dup while keeping order
254
- seen = set()
255
- ordered = []
256
- for c in candidates:
257
- if c and c not in seen:
258
- ordered.append(c)
259
- seen.add(c)
 
 
 
 
260
 
261
  last_err = None
262
- for model in ordered:
 
 
263
  try:
264
  resp = client.models.generate_content(
265
  model=model,
@@ -270,7 +256,7 @@ def gemini_generate(prompt: str, temperature: float = 0.2) -> str:
270
  except Exception as e:
271
  last_err = e
272
 
273
- raise gr.Error(f"Gemini call failed. Tried: {ordered}. Last error: {last_err}")
274
 
275
 
276
  # -----------------------------
@@ -279,13 +265,16 @@ def gemini_generate(prompt: str, temperature: float = 0.2) -> str:
279
  def step_a_outline_claims(title: str, sources: List[Dict[str, str]]) -> Dict[str, Any]:
280
  system = (
281
  "You are a YouTube documentary script planner.\n"
282
- "You must ground all factual statements in the provided SOURCES.\n"
283
  "Return ONLY valid JSON and start your response with '{' and end with '}'.\n"
284
  "Do not wrap in ``` fences. Do not add any text before or after the JSON.\n"
285
  )
286
 
287
  sources_block = "\n\n".join(
288
- [f"[SOURCE {i+1}]\nTITLE: {s['title']}\nURL: {s['url']}\nEXCERPT: {s['excerpt']}" for i, s in enumerate(sources)]
 
 
 
289
  )
290
 
291
  user = f"""
@@ -294,13 +283,13 @@ We are writing a video based on the title: "{title}"
294
  Task:
295
  1) Propose an angle (1 sentence).
296
  2) Create a countdown plan with Levels 0–9 (10 items).
297
- 3) For each level, propose: event_name, location, date (if known), fatalities (if known), and a list of atomic factual claims.
298
 
299
  Rules:
300
  - Claims must be ATOMIC (one fact per claim).
301
- - Claims must be verifiable from SOURCES. If unsure, include it but keep it specific.
302
- - Keep each level to 4–7 claims max.
303
- - If you cannot find 10 items, return fewer items but do NOT invent.
304
 
305
  Return JSON format EXACTLY:
306
  {{
@@ -313,7 +302,8 @@ Return JSON format EXACTLY:
313
  "date": "...",
314
  "fatalities": "...",
315
  "claims": [
316
- {{"id":"c0_1","text":"..."}}
 
317
  ]
318
  }}
319
  ]
@@ -328,15 +318,22 @@ SOURCES:
328
 
329
 
330
  def step_b_verify_claims(plan: Dict[str, Any], sources: List[Dict[str, str]]) -> Dict[str, Any]:
331
- sources_block = "\n\n".join([f"[SOURCE {i+1}]\nURL: {s['url']}\nEXCERPT: {s['excerpt']}" for i, s in enumerate(sources)])
 
 
 
 
 
 
332
 
333
- claims = []
334
- for item in plan.get("items", []) or []:
335
- for c in item.get("claims", []) or []:
336
- cid = (c.get("id") or "").strip()
337
- txt = (c.get("text") or "").strip()
338
- if cid and txt:
339
- claims.append({"id": cid, "text": txt})
 
340
 
341
  system_rules = """
342
  You are a STRICT fact-checker.
@@ -359,18 +356,15 @@ Evidence rules:
359
  - If verdict is "supported" or "contradicted":
360
  include exactly 1 short quote (<=20 words) and its URL.
361
  - If verdict is "not_supported":
362
- evidence must [].
363
 
364
  Return EXACTLY this JSON structure:
365
-
366
  {
367
  "verifications": [
368
  {
369
  "id": "string",
370
  "verdict": "supported|not_supported|contradicted",
371
- "evidence": [
372
- {"url": "string", "quote": "string"}
373
- ],
374
  "fix": "remove or safe rewrite"
375
  }
376
  ]
@@ -383,127 +377,124 @@ CLAIMS:
383
 
384
  SOURCES:
385
  {sources_block}
386
-
387
- Return JSON only.
388
  """.strip()
389
 
390
  prompt = system_rules + "\n\n" + user
391
 
392
- out = gemini_generate(prompt, temperature=0.1)
393
  try:
394
- return safe_json_extract(out)
395
- except Exception:
396
- repair = f"""
 
 
397
  You MUST output ONLY valid JSON. No explanations. No markdown. No extra text.
398
- Start with "{{" and end with "}}".
399
-
400
  Return the JSON again now.
401
 
402
  PREVIOUS_OUTPUT:
403
  {out}
404
  """.strip()
405
- out2 = gemini_generate(prompt + "\n\n" + repair, temperature=0.0)
406
- try:
407
  return safe_json_extract(out2)
408
- except Exception:
409
- fallback = openai_chat(
410
- "You are a STRICT fact-checker. Output ONLY valid JSON. Start with { and end with }.",
411
- prompt,
412
- temperature=0.0,
413
- )
414
- return safe_json_extract(fallback)
415
-
416
-
417
- def step_c_build_verified_facts(plan: Dict[str, Any], verification: Dict[str, Any]) -> Dict[str, Any]:
418
- vmap = {v.get("id"): v for v in (verification.get("verifications") or []) if v.get("id")}
419
-
420
- verified_items = []
421
- for item in plan.get("items", []) or []:
422
- supported_claims = []
423
- for c in item.get("claims", []) or []:
424
- v = vmap.get(c.get("id"))
425
- if not v:
426
- continue
427
- if v.get("verdict") == "supported":
428
- supported_claims.append(
429
- {"id": c.get("id", ""), "text": c.get("text", ""), "evidence": (v.get("evidence") or [])[:2]}
430
- )
431
- if len(supported_claims) >= 2:
432
- verified_items.append(
433
- {
434
- "level": item.get("level"),
435
- "event_name": item.get("event_name", ""),
436
- "location": item.get("location", ""),
437
- "date": item.get("date", ""),
438
- "fatalities": item.get("fatalities", ""),
439
- "supported_claims": supported_claims,
440
- }
441
- )
442
-
443
- return {"angle": plan.get("angle", ""), "verified_items": verified_items, "dropped_count": max(0, len(plan.get("items", [])) - len(verified_items))}
444
-
445
-
446
- def step_d_neutral_script(title: str, verified: Dict[str, Any]) -> str:
447
- system = (
448
- "You are a careful documentary script writer.\n"
449
- "You must NOT introduce any new factual claims beyond VERIFIED_FACTS.\n"
450
- "If a detail is missing, omit it.\n"
451
- "Write a neutral, factual draft (no strong stylistic flourishes yet)."
452
- )
453
-
454
- user = f"""
455
- TITLE: {title}
456
 
457
- VERIFIED_FACTS (JSON):
458
- {json.dumps(verified, ensure_ascii=False)}
459
 
460
- Write:
461
- - A short neutral intro (3–5 lines).
462
- - Then 1 section per verified item, with bullets of what will be said.
463
- Keep it neutral, factual, and structured.
464
- """.strip()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
465
 
466
- return openai_chat(system, user, temperature=0.25)
467
 
468
 
469
- def step_e_style1_human_render(title: str, verified: Dict[str, Any], neutral_script: str) -> str:
470
  system = (
471
  "You are a professional human documentary narrator and scriptwriter.\n"
472
- "CRITICAL: You must NOT add any new factual claims.\n"
473
- "You may ONLY use facts present in VERIFIED_FACTS.\n"
474
- "If something is unknown, do not guess.\n"
475
- "Make the text feel human: varied sentence length, natural transitions, subtle emotion, no robotic repetition.\n"
476
- "Avoid clichés and generic filler.\n"
 
 
 
477
  )
478
 
479
  style_rules = """
480
  STYLE_1_DOCUMENTARY_LEVELS:
481
  - Open with 2 sentences: (1) contrast statement, (2) promise of what viewer will learn.
482
  - Use countdown headings exactly:
483
- "Level N — {EventName/Location} ({Date}) — {Fatalities} deaths"
 
 
484
  - For each level: 120–180 words, calm but tense documentary tone.
485
- - Each level must include:
486
  (a) setup/context,
487
  (b) impact,
488
- (c) why fatalities were high (choose at least 2 factors: time of day, warnings, building type, population density, communication failures, visibility/night),
489
- (d) closing significance sentence ("it revealed...", "it left behind...", etc).
490
- - If fatalities uncertain: present as a range and add "depending on reporting sources".
491
  - No emojis, no hype caps, no CTA until the very end.
 
492
  """.strip()
493
 
494
  user = f"""
495
  VIDEO TITLE: {title}
496
 
497
- VERIFIED_FACTS (JSON):
498
- {json.dumps(verified, ensure_ascii=False)}
499
-
500
- NEUTRAL_DRAFT:
501
- {neutral_script}
502
 
503
- Now write the full final script in STYLE_1_DOCUMENTARY_LEVELS.
504
- If fewer than 10 verified items exist, write only what is verified and add a short honest line in the intro like:
505
- "Some events are hard to verify consistently across sources, so we're focusing on those with clear reporting."
506
- End with a short CTA only in the final paragraph.
507
  """.strip()
508
 
509
  return openai_chat(system + "\n\n" + style_rules, user, temperature=0.55)
@@ -545,7 +536,7 @@ def generate(title: str, request: gr.Request):
545
  key = request.client.host if request and request.client else "global"
546
  rate_limit(key)
547
 
548
- serp_key = os.getenv("SERPAPI_API_KEY", "").strip()
549
  if not serp_key:
550
  raise gr.Error("SERPAPI_API_KEY ontbreekt in Secrets.")
551
 
@@ -556,9 +547,8 @@ def generate(title: str, request: gr.Request):
556
 
557
  plan = step_a_outline_claims(title, sources)
558
  verification = step_b_verify_claims(plan, sources)
559
- verified = step_c_build_verified_facts(plan, verification)
560
- neutral = step_d_neutral_script(title, verified)
561
- final_script = step_e_style1_human_render(title, verified, neutral)
562
 
563
  claims_md = render_claims_report(verification)
564
  sources_md = render_sources(sources)
@@ -573,10 +563,14 @@ with gr.Blocks(title="YouTube Scriptwriter — STIJL 1 (Levels)") as demo:
573
  gr.Markdown(
574
  "# YouTube Scriptwriter — STIJL 1 (Levels)\n"
575
  "Vul alleen een **video titel** in en klik **Generate**.\n\n"
576
- "**Let op:** de tool gebruikt alleen verified claims uit bronnen en schrijft daarna in jouw STIJL 1 met een menselijke narrator-toon."
577
  )
578
 
579
- title_in = gr.Textbox(label="Video titel", placeholder="Bijv. 'De dodelijkste aardbevingen ooit (uitgelegd)'.", lines=2)
 
 
 
 
580
  btn = gr.Button("Generate")
581
 
582
  script_out = gr.Textbox(label="Final script (STIJL 1)", lines=24)
 
7
  import gradio as gr
8
  import requests
9
 
10
+ # Optional cleaner extraction
11
  try:
12
  import trafilatura
13
  except Exception:
14
  trafilatura = None
15
 
16
+ # OpenAI
17
  from openai import OpenAI
18
+
19
+ # Gemini (AI Studio)
20
  from google import genai
21
 
22
 
 
29
  MAX_EXCERPT_CHARS = 2500
30
  FETCH_TIMEOUT = 25
31
 
32
+ _RATE: Dict[str, float] = {}
33
  MIN_SECONDS_BETWEEN_RUNS = 20
34
 
35
 
 
41
 
42
 
43
  def rate_limit(key: str):
44
+ last = _RATE.get(key, 0.0)
45
  if _now() - last < MIN_SECONDS_BETWEEN_RUNS:
46
  wait = int(MIN_SECONDS_BETWEEN_RUNS - (_now() - last))
47
  raise gr.Error(f"Even wachten aub ({wait}s). Probeer zo opnieuw.")
 
53
 
54
 
55
  def clip(s: str, n: int) -> str:
56
+ s = s or ""
57
+ return s[:n]
58
 
59
 
60
  def safe_json_extract(text: str) -> Any:
 
67
  except Exception:
68
  pass
69
 
70
+ # find object
71
  start = text.find("{")
72
  if start != -1:
73
  depth = 0
 
78
  elif ch == "}":
79
  depth -= 1
80
  if depth == 0:
81
+ return json.loads(text[start : i + 1])
82
 
83
+ # find array
84
  start = text.find("[")
85
  if start != -1:
86
  depth = 0
 
91
  elif ch == "]":
92
  depth -= 1
93
  if depth == 0:
94
+ return json.loads(text[start : i + 1])
95
 
96
  raise ValueError("Model output bevat geen JSON object/array.")
97
 
 
108
  r.raise_for_status()
109
  data = r.json()
110
 
111
+ out: List[Dict[str, str]] = []
112
  for item in (data.get("organic_results") or [])[:num_results]:
113
  out.append(
114
  {
 
138
 
139
 
140
  def build_sources(serp_results: List[Dict[str, str]]) -> List[Dict[str, str]]:
141
+ sources: List[Dict[str, str]] = []
142
  for r in serp_results:
143
  url = (r.get("url") or "").strip()
144
  if not url:
 
161
  # OpenAI calls
162
  # -----------------------------
163
  def openai_client() -> OpenAI:
164
+ key = (os.getenv("OPENAI_API_KEY") or "").strip()
165
  if not key:
166
  raise gr.Error("OPENAI_API_KEY ontbreekt in Secrets.")
167
  return OpenAI(api_key=key)
 
172
  resp = client.chat.completions.create(
173
  model=OPENAI_MODEL,
174
  temperature=temperature,
175
+ messages=[{"role": "system", "content": system}, {"role": "user", "content": user}],
 
 
 
176
  )
177
  return resp.choices[0].message.content or ""
178
 
179
 
180
  # -----------------------------
181
+ # Gemini calls (optional; with robust fallback)
182
  # -----------------------------
183
  def gemini_client():
184
+ key = (os.getenv("GEMINI_API_KEY") or "").strip()
185
  if not key:
186
+ return None
187
+ try:
188
+ return genai.Client(api_key=key)
189
+ except Exception:
190
+ return None
191
+
192
+
193
+ def _model_names_from_list(models_iter) -> List[str]:
194
+ names: List[str] = []
195
+ for m in models_iter:
196
+ n = getattr(m, "name", None)
197
+ if n:
198
+ names.append(str(n))
199
+ return names
200
+
201
+
202
+ def _rank_model_name(n: str) -> tuple:
203
+ nlow = n.lower()
204
+ return (
205
+ 0 if ("pro" in nlow or "3.1-pro" in nlow or "pro-preview" in nlow) else 1,
206
+ 0 if ("flash" in nlow) else 1,
207
+ 1 if ("audio" in nlow) else 0, # prefer non-audio
208
+ 0 if nlow.startswith("models/") else 1,
209
+ len(n),
210
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
211
 
212
 
213
  def gemini_generate(prompt: str, temperature: float = 0.2) -> str:
214
  client = gemini_client()
215
+ if client is None:
216
+ raise RuntimeError("No Gemini client (missing/invalid GEMINI_API_KEY).")
217
 
 
218
  explicit = (os.getenv("GEMINI_MODEL") or "").strip()
219
+ candidates: List[str] = []
220
  if explicit:
221
  candidates.append(explicit)
 
 
222
 
223
+ # discover
224
  try:
225
+ names = _model_names_from_list(client.models.list())
226
+ names = sorted(set(names), key=_rank_model_name)
227
+ for n in names[:12]:
228
+ if n not in candidates:
229
+ candidates.append(n)
230
  except Exception:
231
  pass
232
 
233
+ # a few safe defaults that often exist (but won't crash if missing)
234
+ for fallback_name in [
235
+ "models/gemini-2.0-flash",
236
+ "models/gemini-2.5-flash",
237
+ "models/gemini-2.5-pro",
238
+ "models/gemini-pro",
239
+ "models/gemini-1.5-pro",
240
+ "models/gemini-1.5-flash",
241
+ ]:
242
+ if fallback_name not in candidates:
243
+ candidates.append(fallback_name)
244
 
245
  last_err = None
246
+ for model in candidates:
247
+ if not model:
248
+ continue
249
  try:
250
  resp = client.models.generate_content(
251
  model=model,
 
256
  except Exception as e:
257
  last_err = e
258
 
259
+ raise RuntimeError(f"Gemini call failed. Tried: {candidates[:10]}. Last error: {last_err}")
260
 
261
 
262
  # -----------------------------
 
265
  def step_a_outline_claims(title: str, sources: List[Dict[str, str]]) -> Dict[str, Any]:
266
  system = (
267
  "You are a YouTube documentary script planner.\n"
268
+ "You must ground important numeric/date/location claims in the provided SOURCES.\n"
269
  "Return ONLY valid JSON and start your response with '{' and end with '}'.\n"
270
  "Do not wrap in ``` fences. Do not add any text before or after the JSON.\n"
271
  )
272
 
273
  sources_block = "\n\n".join(
274
+ [
275
+ f"[SOURCE {i+1}]\nTITLE: {s['title']}\nURL: {s['url']}\nEXCERPT: {s['excerpt']}"
276
+ for i, s in enumerate(sources)
277
+ ]
278
  )
279
 
280
  user = f"""
 
283
  Task:
284
  1) Propose an angle (1 sentence).
285
  2) Create a countdown plan with Levels 0–9 (10 items).
286
+ 3) For each level, propose: event_name, location, date (if known), fatalities (if known), and a list of atomic claims.
287
 
288
  Rules:
289
  - Claims must be ATOMIC (one fact per claim).
290
+ - Add importance field per claim: importance="high" for core facts (deaths/fatalities, date, location, official rating/scale, record claims like "deadliest").
291
+ - Use importance="low" for supporting color/context where small uncertainty is acceptable.
292
+ - Do NOT invent events; if not enough sources support 10, return fewer items.
293
 
294
  Return JSON format EXACTLY:
295
  {{
 
302
  "date": "...",
303
  "fatalities": "...",
304
  "claims": [
305
+ {{"id":"c0_1","importance":"high","text":"..."}},
306
+ {{"id":"c0_2","importance":"low","text":"..."}}
307
  ]
308
  }}
309
  ]
 
318
 
319
 
320
  def step_b_verify_claims(plan: Dict[str, Any], sources: List[Dict[str, str]]) -> Dict[str, Any]:
321
+ """
322
+ Verify ONLY high-importance claims if Gemini available; otherwise verify with OpenAI.
323
+ Always returns {"verifications":[...]}.
324
+ """
325
+ sources_block = "\n\n".join(
326
+ [f"[SOURCE {i+1}]\nURL: {s['url']}\nEXCERPT: {s['excerpt']}" for i, s in enumerate(sources)]
327
+ )
328
 
329
+ claims: List[Dict[str, str]] = []
330
+ for item in plan.get("items", []):
331
+ for c in item.get("claims", []):
332
+ if (c.get("importance") or "").lower() == "high":
333
+ claims.append({"id": c.get("id", ""), "text": c.get("text", "")})
334
+
335
+ if not claims:
336
+ return {"verifications": []}
337
 
338
  system_rules = """
339
  You are a STRICT fact-checker.
 
356
  - If verdict is "supported" or "contradicted":
357
  include exactly 1 short quote (<=20 words) and its URL.
358
  - If verdict is "not_supported":
359
+ evidence must be [].
360
 
361
  Return EXACTLY this JSON structure:
 
362
  {
363
  "verifications": [
364
  {
365
  "id": "string",
366
  "verdict": "supported|not_supported|contradicted",
367
+ "evidence": [{"url":"string","quote":"string"}],
 
 
368
  "fix": "remove or safe rewrite"
369
  }
370
  ]
 
377
 
378
  SOURCES:
379
  {sources_block}
 
 
380
  """.strip()
381
 
382
  prompt = system_rules + "\n\n" + user
383
 
384
+ # Try Gemini first; if it fails, fallback to OpenAI checker (still restricted to sources text).
385
  try:
386
+ out = gemini_generate(prompt, temperature=0.1)
387
+ try:
388
+ return safe_json_extract(out)
389
+ except Exception:
390
+ repair = f"""
391
  You MUST output ONLY valid JSON. No explanations. No markdown. No extra text.
 
 
392
  Return the JSON again now.
393
 
394
  PREVIOUS_OUTPUT:
395
  {out}
396
  """.strip()
397
+ out2 = gemini_generate(prompt + "\n\n" + repair, temperature=0.0)
 
398
  return safe_json_extract(out2)
399
+ except Exception:
400
+ fallback = openai_chat(
401
+ "You are a STRICT fact-checker. Output ONLY valid JSON. Start with { and end with }. No markdown.",
402
+ prompt,
403
+ temperature=0.0,
404
+ )
405
+ return safe_json_extract(fallback)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
406
 
 
 
407
 
408
+ def step_c_build_facts_package(plan: Dict[str, Any], verification: Dict[str, Any]) -> Dict[str, Any]:
409
+ """
410
+ Keep ALL levels. Mark:
411
+ - supported_high_claims: verified core facts
412
+ - soft_claims: low-importance OR high claims that weren't supported (so writer can hedge)
413
+ """
414
+ vmap = {v.get("id"): v for v in (verification.get("verifications") or [])}
415
+
416
+ items_out: List[Dict[str, Any]] = []
417
+ for item in plan.get("items", []):
418
+ supported_high: List[Dict[str, Any]] = []
419
+ soft: List[Dict[str, Any]] = []
420
+
421
+ for c in item.get("claims", []):
422
+ cid = c.get("id")
423
+ txt = c.get("text", "")
424
+ imp = (c.get("importance") or "low").lower()
425
+
426
+ if imp == "high":
427
+ v = vmap.get(cid)
428
+ verdict = (v.get("verdict") if v else "not_checked")
429
+ if verdict == "supported":
430
+ supported_high.append(
431
+ {"id": cid, "text": txt, "evidence": (v.get("evidence") or [])[:1]}
432
+ )
433
+ else:
434
+ soft.append(
435
+ {
436
+ "id": cid,
437
+ "text": txt,
438
+ "kind": f"high_{verdict}",
439
+ "fix": (v.get("fix") if v else "treat as unverified"),
440
+ }
441
+ )
442
+ else:
443
+ soft.append({"id": cid, "text": txt, "kind": "low_unverified"})
444
+
445
+ items_out.append(
446
+ {
447
+ "level": item.get("level"),
448
+ "event_name": item.get("event_name", ""),
449
+ "location": item.get("location", ""),
450
+ "date": item.get("date", ""),
451
+ "fatalities": item.get("fatalities", ""),
452
+ "supported_high_claims": supported_high,
453
+ "soft_claims": soft[:10],
454
+ }
455
+ )
456
 
457
+ return {"angle": plan.get("angle", ""), "items": items_out}
458
 
459
 
460
+ def step_d_style1_script(title: str, facts_package: Dict[str, Any]) -> str:
461
  system = (
462
  "You are a professional human documentary narrator and scriptwriter.\n"
463
+ "CRITICAL RULES:\n"
464
+ "- Do NOT invent new events.\n"
465
+ "- Use supported_high_claims as hard facts.\n"
466
+ "- You MAY use soft_claims ONLY if you clearly label uncertainty.\n"
467
+ " Use phrases like: 'Some reports suggest…', 'Estimates vary…', 'Details are disputed…', 'Rumours at the time claimed…'.\n"
468
+ "- Never present soft_claims as certain facts.\n"
469
+ "- Keep it human: varied sentence length, natural transitions, subtle emotion, no robotic repetition.\n"
470
+ "- Avoid clichés and generic filler.\n"
471
  )
472
 
473
  style_rules = """
474
  STYLE_1_DOCUMENTARY_LEVELS:
475
  - Open with 2 sentences: (1) contrast statement, (2) promise of what viewer will learn.
476
  - Use countdown headings exactly:
477
+ "Level N — {EventName} ({Date}) — {Fatalities} deaths"
478
+ If Date unknown: omit parentheses.
479
+ If Fatalities unknown: omit "— X deaths".
480
  - For each level: 120–180 words, calm but tense documentary tone.
481
+ - Each level should include:
482
  (a) setup/context,
483
  (b) impact,
484
+ (c) why casualties were high (choose 1–2 plausible factors, but hedge if not verified),
485
+ (d) closing significance sentence.
 
486
  - No emojis, no hype caps, no CTA until the very end.
487
+ - End with a short CTA only in the final paragraph.
488
  """.strip()
489
 
490
  user = f"""
491
  VIDEO TITLE: {title}
492
 
493
+ FACTS_PACKAGE (JSON):
494
+ {json.dumps(facts_package, ensure_ascii=False)}
 
 
 
495
 
496
+ Write the full final script in STYLE_1_DOCUMENTARY_LEVELS.
497
+ If some levels have few supported_high_claims, rely more on soft_claims but hedge clearly.
 
 
498
  """.strip()
499
 
500
  return openai_chat(system + "\n\n" + style_rules, user, temperature=0.55)
 
536
  key = request.client.host if request and request.client else "global"
537
  rate_limit(key)
538
 
539
+ serp_key = (os.getenv("SERPAPI_API_KEY") or "").strip()
540
  if not serp_key:
541
  raise gr.Error("SERPAPI_API_KEY ontbreekt in Secrets.")
542
 
 
547
 
548
  plan = step_a_outline_claims(title, sources)
549
  verification = step_b_verify_claims(plan, sources)
550
+ facts_package = step_c_build_facts_package(plan, verification)
551
+ final_script = step_d_style1_script(title, facts_package)
 
552
 
553
  claims_md = render_claims_report(verification)
554
  sources_md = render_sources(sources)
 
563
  gr.Markdown(
564
  "# YouTube Scriptwriter — STIJL 1 (Levels)\n"
565
  "Vul alleen een **video titel** in en klik **Generate**.\n\n"
566
+ "**Let op:** kernfeiten worden geverifieerd waar mogelijk; kleine details mogen onzeker zijn en worden als zodanig geformuleerd."
567
  )
568
 
569
+ title_in = gr.Textbox(
570
+ label="Video titel",
571
+ placeholder="Bijv. 'De dodelijkste tornado’s ooit (uitgelegd)'.",
572
+ lines=2,
573
+ )
574
  btn = gr.Button("Generate")
575
 
576
  script_out = gr.Textbox(label="Final script (STIJL 1)", lines=24)