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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import json
4
+ import time
5
+ import textwrap
6
+ from typing import List, Dict, Any, Tuple
7
+
8
+ import gradio as gr
9
+ import requests
10
+
11
+ # Optional but recommended for cleaner extraction:
12
+ try:
13
+ import trafilatura
14
+ except Exception:
15
+ trafilatura = None
16
+
17
+ # OpenAI
18
+ from openai import OpenAI
19
+
20
+ # Gemini (AI Studio)
21
+ import google.generativeai as genai
22
+
23
+
24
+ # -----------------------------
25
+ # Config
26
+ # -----------------------------
27
+ OPENAI_MODEL = os.getenv("OPENAI_MODEL", "gpt-4o-mini") # change if you want
28
+ GEMINI_MODEL = os.getenv("GEMINI_MODEL", "gemini-1.5-pro")
29
+
30
+ MAX_SOURCES = 6
31
+ MAX_EXCERPT_CHARS = 4500
32
+ FETCH_TIMEOUT = 25
33
+
34
+ # Simple in-memory rate limit (per session/ip best-effort)
35
+ _RATE = {} # key -> last_ts
36
+ MIN_SECONDS_BETWEEN_RUNS = 20
37
+
38
+
39
+ # -----------------------------
40
+ # Utilities
41
+ # -----------------------------
42
+ def _now() -> float:
43
+ return time.time()
44
+
45
+ def rate_limit(key: str):
46
+ last = _RATE.get(key, 0)
47
+ if _now() - last < MIN_SECONDS_BETWEEN_RUNS:
48
+ wait = int(MIN_SECONDS_BETWEEN_RUNS - (_now() - last))
49
+ raise gr.Error(f"Even wachten aub ({wait}s). Probeer zo opnieuw.")
50
+ _RATE[key] = _now()
51
+
52
+ def clean_text(s: str) -> str:
53
+ s = re.sub(r"\s+", " ", (s or "")).strip()
54
+ return s
55
+
56
+ def clip(s: str, n: int) -> str:
57
+ s = s or ""
58
+ return s[:n]
59
+
60
+ def safe_json_extract(text: str) -> Any:
61
+ """
62
+ Extract JSON even if model wraps it in fences or extra text.
63
+ """
64
+ text = (text or "").strip()
65
+ # strip code fences
66
+ text = re.sub(r"^```(?:json)?\s*", "", text.strip(), flags=re.I)
67
+ text = re.sub(r"\s*```$", "", text.strip())
68
+ # find first { ... } block
69
+ m = re.search(r"\{.*\}", text, flags=re.S)
70
+ if not m:
71
+ raise ValueError("Model output bevat geen JSON object.")
72
+ return json.loads(m.group(0))
73
+
74
+
75
+ # -----------------------------
76
+ # SERPAPI research
77
+ # -----------------------------
78
+ def serpapi_search(query: str, serpapi_key: str, num_results: int = MAX_SOURCES) -> List[Dict[str, str]]:
79
+ if not serpapi_key:
80
+ raise gr.Error("SERPAPI_API_KEY ontbreekt in Secrets.")
81
+ url = "https://serpapi.com/search.json"
82
+ params = {
83
+ "engine": "google",
84
+ "q": query,
85
+ "api_key": serpapi_key,
86
+ "num": num_results,
87
+ }
88
+ r = requests.get(url, params=params, timeout=30)
89
+ r.raise_for_status()
90
+ data = r.json()
91
+
92
+ out = []
93
+ for item in (data.get("organic_results") or [])[:num_results]:
94
+ out.append({
95
+ "title": item.get("title", "") or "",
96
+ "url": item.get("link", "") or "",
97
+ "snippet": item.get("snippet", "") or "",
98
+ })
99
+ return out
100
+
101
+ def fetch_page_text(url: str) -> str:
102
+ headers = {"User-Agent": "Mozilla/5.0"}
103
+ r = requests.get(url, headers=headers, timeout=FETCH_TIMEOUT)
104
+ r.raise_for_status()
105
+ html = r.text
106
+
107
+ if trafilatura:
108
+ extracted = trafilatura.extract(html, include_comments=False, include_tables=False)
109
+ if extracted and len(extracted.strip()) > 200:
110
+ return clean_text(extracted)
111
+
112
+ # fallback: crude strip tags
113
+ html = re.sub(r"(?is)<script.*?>.*?</script>", " ", html)
114
+ html = re.sub(r"(?is)<style.*?>.*?</style>", " ", html)
115
+ text = re.sub(r"(?is)<.*?>", " ", html)
116
+ return clean_text(text)
117
+
118
+ def build_sources(serp_results: List[Dict[str, str]]) -> List[Dict[str, str]]:
119
+ sources = []
120
+ for r in serp_results:
121
+ url = r.get("url", "").strip()
122
+ if not url:
123
+ continue
124
+ try:
125
+ text = fetch_page_text(url)
126
+ except Exception:
127
+ text = r.get("snippet", "")
128
+
129
+ sources.append({
130
+ "title": r.get("title", ""),
131
+ "url": url,
132
+ "excerpt": clip(text, MAX_EXCERPT_CHARS),
133
+ })
134
+ return sources
135
+
136
+
137
+ # -----------------------------
138
+ # OpenAI calls
139
+ # -----------------------------
140
+ def openai_client() -> OpenAI:
141
+ key = os.getenv("OPENAI_API_KEY", "").strip()
142
+ if not key:
143
+ raise gr.Error("OPENAI_API_KEY ontbreekt in Secrets.")
144
+ return OpenAI(api_key=key)
145
+
146
+ def openai_chat(system: str, user: str, temperature: float = 0.4) -> str:
147
+ client = openai_client()
148
+ resp = client.chat.completions.create(
149
+ model=OPENAI_MODEL,
150
+ temperature=temperature,
151
+ messages=[
152
+ {"role": "system", "content": system},
153
+ {"role": "user", "content": user},
154
+ ],
155
+ )
156
+ return resp.choices[0].message.content or ""
157
+
158
+
159
+ # -----------------------------
160
+ # Gemini calls (strict verifier)
161
+ # -----------------------------
162
+ def gemini_model():
163
+ key = os.getenv("GEMINI_API_KEY", "").strip()
164
+ if not key:
165
+ raise gr.Error("GEMINI_API_KEY ontbreekt in Secrets.")
166
+ genai.configure(api_key=key)
167
+ return genai.GenerativeModel(GEMINI_MODEL)
168
+
169
+ def gemini_generate(prompt: str, temperature: float = 0.2) -> str:
170
+ model = gemini_model()
171
+ resp = model.generate_content(
172
+ prompt,
173
+ generation_config=genai.types.GenerationConfig(
174
+ temperature=temperature,
175
+ max_output_tokens=4096,
176
+ ),
177
+ )
178
+ return (resp.text or "").strip()
179
+
180
+
181
+ # -----------------------------
182
+ # Pipeline steps
183
+ # -----------------------------
184
+ def step_a_outline_claims(title: str, sources: List[Dict[str, str]]) -> Dict[str, Any]:
185
+ """
186
+ Output JSON:
187
+ {
188
+ "angle": "...",
189
+ "items": [
190
+ {"level":0,"event_name":"...","location":"...","date":"...","fatalities":"...","claims":[...]}
191
+ ... total 10 ideally
192
+ ]
193
+ }
194
+ """
195
+ system = (
196
+ "You are a YouTube documentary script planner.\n"
197
+ "You must ground all factual statements in the provided SOURCES.\n"
198
+ "Return ONLY valid JSON. No markdown."
199
+ )
200
+
201
+ sources_block = "\n\n".join(
202
+ [f"[SOURCE {i+1}]\nTITLE: {s['title']}\nURL: {s['url']}\nEXCERPT: {s['excerpt']}"
203
+ for i, s in enumerate(sources)]
204
+ )
205
+
206
+ user = f"""
207
+ We are writing a video based on the title: "{title}"
208
+
209
+ Task:
210
+ 1) Propose an angle (1 sentence).
211
+ 2) Create a countdown plan with Levels 0–9 (10 items).
212
+ 3) For each level, propose: event_name, location, date (if known), fatalities (if known), and a list of atomic factual claims.
213
+
214
+ Rules:
215
+ - Claims must be ATOMIC (one fact per claim).
216
+ - Claims must be verifiable from SOURCES. If unsure, include it as a claim but mark it for verification by keeping it specific.
217
+ - Keep each level to 4–7 claims max.
218
+ - If you cannot find 10 items, return fewer items but do NOT invent.
219
+
220
+ Return JSON format EXACTLY:
221
+ {{
222
+ "angle": "...",
223
+ "items": [
224
+ {{
225
+ "level": 0,
226
+ "event_name": "...",
227
+ "location": "...",
228
+ "date": "...",
229
+ "fatalities": "...",
230
+ "claims": [
231
+ {{"id":"c0_1","text":"..."}},
232
+ ...
233
+ ]
234
+ }}
235
+ ]
236
+ }}
237
+
238
+ SOURCES:
239
+ {sources_block}
240
+ """.strip()
241
+
242
+ out = openai_chat(system, user, temperature=0.3)
243
+ return safe_json_extract(out)
244
+
245
+ def step_b_verify_claims(plan: Dict[str, Any], sources: List[Dict[str, str]]) -> Dict[str, Any]:
246
+ """
247
+ Output JSON:
248
+ {
249
+ "verifications":[
250
+ {"id":"c0_1","verdict":"supported|not_supported|contradicted","evidence":[{"url":"..","quote":".."}],"fix":".."}
251
+ ]
252
+ }
253
+ """
254
+ # pack sources (verifier must ONLY use these)
255
+ sources_block = "\n\n".join(
256
+ [f"[SOURCE {i+1}]\nURL: {s['url']}\nEXCERPT: {s['excerpt']}"
257
+ for i, s in enumerate(sources)]
258
+ )
259
+
260
+ claims = []
261
+ for item in plan.get("items", []):
262
+ for c in item.get("claims", []):
263
+ claims.append({"id": c["id"], "text": c["text"]})
264
+
265
+ system_rules = """
266
+ You are a STRICT fact-checker.
267
+ You must ONLY use the provided SOURCES excerpts.
268
+ Do NOT use outside knowledge.
269
+ For each claim:
270
+ - verdict = supported if directly supported by sources
271
+ - verdict = contradicted if sources conflict with the claim
272
+ - verdict = not_supported if sources do not clearly support it
273
+ Provide 1–2 short quotes (<=20 words each) as evidence when supported/contradicted.
274
+ If not_supported, suggest a safe rewrite OR say "remove".
275
+ Return ONLY valid JSON. No markdown.
276
+ """.strip()
277
+
278
+ user = f"""
279
+ CLAIMS:
280
+ {json.dumps(claims, ensure_ascii=False)}
281
+
282
+ SOURCES:
283
+ {sources_block}
284
+
285
+ Return JSON format:
286
+ {{
287
+ "verifications": [
288
+ {{
289
+ "id": "...",
290
+ "verdict": "supported|not_supported|contradicted",
291
+ "evidence": [{{"url":"...","quote":"..."}}, ...],
292
+ "fix": "..."
293
+ }}
294
+ ]
295
+ }}
296
+ """.strip()
297
+
298
+ out = gemini_generate(system_rules + "\n\n" + user, temperature=0.1)
299
+ return safe_json_extract(out)
300
+
301
+ def step_c_build_verified_facts(plan: Dict[str, Any], verification: Dict[str, Any]) -> Dict[str, Any]:
302
+ vmap = {v["id"]: v for v in verification.get("verifications", [])}
303
+
304
+ verified_items = []
305
+ for item in plan.get("items", []):
306
+ supported_claims = []
307
+ for c in item.get("claims", []):
308
+ v = vmap.get(c["id"])
309
+ if not v:
310
+ continue
311
+ if v.get("verdict") == "supported":
312
+ supported_claims.append({
313
+ "id": c["id"],
314
+ "text": c["text"],
315
+ "evidence": v.get("evidence", [])[:2],
316
+ })
317
+ # Keep item if it has at least 2 supported claims (you can tweak)
318
+ if len(supported_claims) >= 2:
319
+ verified_items.append({
320
+ "level": item.get("level"),
321
+ "event_name": item.get("event_name", ""),
322
+ "location": item.get("location", ""),
323
+ "date": item.get("date", ""),
324
+ "fatalities": item.get("fatalities", ""),
325
+ "supported_claims": supported_claims,
326
+ })
327
+
328
+ return {
329
+ "angle": plan.get("angle", ""),
330
+ "verified_items": verified_items,
331
+ "dropped_count": max(0, len(plan.get("items", [])) - len(verified_items))
332
+ }
333
+
334
+ def step_d_neutral_script(title: str, verified: Dict[str, Any]) -> str:
335
+ system = (
336
+ "You are a careful documentary script writer.\n"
337
+ "You must NOT introduce any new factual claims beyond VERIFIED_FACTS.\n"
338
+ "If a detail is missing, omit it.\n"
339
+ "Write a neutral, factual draft (no strong stylistic flourishes yet)."
340
+ )
341
+
342
+ user = f"""
343
+ TITLE: {title}
344
+
345
+ VERIFIED_FACTS (JSON):
346
+ {json.dumps(verified, ensure_ascii=False)}
347
+
348
+ Write:
349
+ - A short neutral intro (3–5 lines).
350
+ - Then 1 section per verified item, with bullets of what will be said.
351
+ Keep it neutral, factual, and structured.
352
+ """.strip()
353
+
354
+ return openai_chat(system, user, temperature=0.25)
355
+
356
+ def step_e_style1_human_render(title: str, verified: Dict[str, Any], neutral_script: str) -> str:
357
+ """
358
+ This is where we force:
359
+ - STIJL 1 Levels (0–9) headings format :contentReference[oaicite:1]{index=1}
360
+ - Human narrator tone (varied rhythm, subtle emotion, rhetorical questions)
361
+ - No new facts (must only use VERIFIED_FACTS)
362
+ """
363
+ system = (
364
+ "You are a professional human documentary narrator and scriptwriter.\n"
365
+ "CRITICAL: You must NOT add any new factual claims.\n"
366
+ "You may ONLY use facts present in VERIFIED_FACTS.\n"
367
+ "If something is unknown, do not guess.\n"
368
+ "Your job is to make the text feel human: varied sentence length, natural transitions, subtle emotion, no robotic repetition.\n"
369
+ "Avoid clichés and generic filler.\n"
370
+ )
371
+
372
+ style_rules = """
373
+ STYLE_1_DOCUMENTARY_LEVELS (based on provided example):
374
+ - Open with 2 sentences: (1) contrast statement, (2) promise of what viewer will learn. :contentReference[oaicite:2]{index=2}
375
+ - Use countdown headings exactly:
376
+ "Level N — {EventName/Location} ({Date}) — {Fatalities} deaths" :contentReference[oaicite:3]{index=3}
377
+ - For each level: 120–180 words, calm but tense documentary tone.
378
+ - Each level must include:
379
+ (a) setup/context,
380
+ (b) impact,
381
+ (c) why fatalities were high (choose at least 2 factors: time of day, warnings, building type, population density, communication failures, visibility/night),
382
+ (d) closing significance sentence ("it revealed...", "it left behind...", etc). :contentReference[oaicite:4]{index=4}
383
+ - If fatalities uncertain: present as a range and add "depending on reporting sources". :contentReference[oaicite:5]{index=5}
384
+ - No emojis, no hype caps, no CTA until the very end.
385
+ - Keep it human: rhetorical questions sparingly, sensory detail only if directly implied by facts (otherwise keep general).
386
+ """.strip()
387
+
388
+ user = f"""
389
+ VIDEO TITLE: {title}
390
+
391
+ VERIFIED_FACTS (JSON):
392
+ {json.dumps(verified, ensure_ascii=False)}
393
+
394
+ NEUTRAL_DRAFT:
395
+ {neutral_script}
396
+
397
+ Now write the full final script in STYLE_1_DOCUMENTARY_LEVELS.
398
+ If fewer than 10 verified items exist, write only what is verified and add a short honest line in the intro like:
399
+ "Some events are hard to verify consistently across sources, so we're focusing on those with clear reporting."
400
+ End with a short CTA only in the final paragraph.
401
+ """.strip()
402
+
403
+ return openai_chat(system + "\n\n" + style_rules, user, temperature=0.55)
404
+
405
+
406
+ # -----------------------------
407
+ # Reporting helpers
408
+ # -----------------------------
409
+ def render_claims_report(verification: Dict[str, Any]) -> str:
410
+ lines = ["## Claims & verificatie\n"]
411
+ for v in verification.get("verifications", []):
412
+ verdict = v.get("verdict", "")
413
+ cid = v.get("id", "")
414
+ fix = v.get("fix", "")
415
+ lines.append(f"- **{cid}** — `{verdict}` — {fix}")
416
+ for e in (v.get("evidence") or [])[:2]:
417
+ url = e.get("url", "")
418
+ quote = e.get("quote", "")
419
+ if url or quote:
420
+ lines.append(f" - {url} — “{quote}”")
421
+ return "\n".join(lines)
422
+
423
+ def render_sources(sources: List[Dict[str, str]]) -> str:
424
+ lines = ["## Sources\n"]
425
+ for s in sources:
426
+ lines.append(f"- {s.get('title','').strip()} — {s.get('url','').strip()}")
427
+ return "\n".join(lines)
428
+
429
+
430
+ # -----------------------------
431
+ # Main run
432
+ # -----------------------------
433
+ def generate(title: str, request: gr.Request):
434
+ title = (title or "").strip()
435
+ if not title:
436
+ raise gr.Error("Vul een video titel in.")
437
+
438
+ # rate limit best-effort
439
+ key = request.client.host if request and request.client else "global"
440
+ rate_limit(key)
441
+
442
+ serp_key = os.getenv("SERPAPI_API_KEY", "").strip()
443
+ if not serp_key:
444
+ raise gr.Error("SERPAPI_API_KEY ontbreekt in Secrets.")
445
+
446
+ # 1) Research
447
+ serp = serpapi_search(title, serp_key, num_results=MAX_SOURCES)
448
+ sources = build_sources(serp)
449
+
450
+ if not sources:
451
+ raise gr.Error("Geen bronnen gevonden. Probeer een specifiekere titel.")
452
+
453
+ # 2) Outline + claims
454
+ plan = step_a_outline_claims(title, sources)
455
+
456
+ # 3) Verify claims via Gemini (strict)
457
+ verification = step_b_verify_claims(plan, sources)
458
+
459
+ # 4) Build verified facts
460
+ verified = step_c_build_verified_facts(plan, verification)
461
+
462
+ # 5) Neutral draft
463
+ neutral = step_d_neutral_script(title, verified)
464
+
465
+ # 6) Human + STIJL 1 final render
466
+ final_script = step_e_style1_human_render(title, verified, neutral)
467
+
468
+ # Reports
469
+ claims_md = render_claims_report(verification)
470
+ sources_md = render_sources(sources)
471
+
472
+ return final_script, claims_md, sources_md
473
+
474
+
475
+ # -----------------------------
476
+ # UI
477
+ # -----------------------------
478
+ with gr.Blocks(title="YouTube Scriptwriter — STIJL 1 (Levels)") as demo:
479
+ gr.Markdown(
480
+ "# YouTube Scriptwriter — STIJL 1 (Levels)\n"
481
+ "Vul alleen een **video titel** in en klik **Generate**.\n\n"
482
+ "**Let op:** de tool gebruikt alleen verified claims uit bronnen en schrijft daarna in jouw STIJL 1 met een menselijke narrator-toon."
483
+ )
484
+
485
+ title_in = gr.Textbox(label="Video titel", placeholder="Bijv. 'De dodelijkste aardbevingen ooit (uitgelegd)'.", lines=2)
486
+ btn = gr.Button("Generate")
487
+
488
+ script_out = gr.Textbox(label="Final script (STIJL 1)", lines=24)
489
+ claims_out = gr.Markdown()
490
+ sources_out = gr.Markdown()
491
+
492
+ btn.click(fn=generate, inputs=[title_in], outputs=[script_out, claims_out, sources_out])
493
+
494
+ if __name__ == "__main__":
495
+ demo.launch()