Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,18 +1,12 @@
|
|
| 1 |
# app.py
|
| 2 |
-
# Universal YouTube Scriptwriter — Human Tone (NO LINKS OVERVIEW
|
| 3 |
#
|
| 4 |
-
#
|
| 5 |
-
# ✅
|
| 6 |
-
# ✅
|
| 7 |
-
# ✅
|
| 8 |
-
# ✅ Robust: plan=list -> normalize_plan, Gemini JSON repair, OpenAI token param compat
|
| 9 |
-
#
|
| 10 |
-
# Secrets:
|
| 11 |
-
# - SERPAPI_API_KEY
|
| 12 |
-
# - OPENAI_API_KEY
|
| 13 |
-
# - GEMINI_API_KEY
|
| 14 |
-
#
|
| 15 |
-
# pip install gradio requests trafilatura openai google-genai
|
| 16 |
|
| 17 |
import os
|
| 18 |
import re
|
|
@@ -48,7 +42,7 @@ CHUNKS_PER_SOURCE = int(os.getenv("CHUNKS_PER_SOURCE", "2"))
|
|
| 48 |
MIN_SECONDS_BETWEEN_RUNS = int(os.getenv("MIN_SECONDS_BETWEEN_RUNS", "15"))
|
| 49 |
_RATE: Dict[str, float] = {}
|
| 50 |
|
| 51 |
-
#
|
| 52 |
CLAIMS_PER_ITEM = int(os.getenv("CLAIMS_PER_ITEM", "6"))
|
| 53 |
MAX_VERIFY_CLAIMS = int(os.getenv("MAX_VERIFY_CLAIMS", "120"))
|
| 54 |
VERIFY_BATCH_SIZE = int(os.getenv("VERIFY_BATCH_SIZE", "15"))
|
|
@@ -81,10 +75,6 @@ def word_count(s: str) -> int:
|
|
| 81 |
|
| 82 |
|
| 83 |
def safe_json_extract(text: str) -> Any:
|
| 84 |
-
"""
|
| 85 |
-
Robust JSON extractor: strips fences, normalizes quotes, removes control chars,
|
| 86 |
-
then parses direct or scans for first valid object/array.
|
| 87 |
-
"""
|
| 88 |
text = (text or "").strip()
|
| 89 |
text = text.replace("\u201c", '"').replace("\u201d", '"').replace("\u2018", "'").replace("\u2019", "'")
|
| 90 |
text = re.sub(r"[\x00-\x08\x0b\x0c\x0e-\x1f]", "", text)
|
|
@@ -133,7 +123,7 @@ def safe_json_extract(text: str) -> Any:
|
|
| 133 |
|
| 134 |
|
| 135 |
def normalize_plan(obj: Any) -> Dict[str, Any]:
|
| 136 |
-
# Fix voor:
|
| 137 |
if isinstance(obj, dict):
|
| 138 |
items = obj.get("items")
|
| 139 |
if not isinstance(items, list):
|
|
@@ -153,10 +143,20 @@ def normalize_verifications(obj: Any) -> Dict[str, Any]:
|
|
| 153 |
return {"verifications": []}
|
| 154 |
|
| 155 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 156 |
# -----------------------------
|
| 157 |
# SERPAPI + Fetch
|
| 158 |
# -----------------------------
|
| 159 |
-
def serpapi_search(query: str, serpapi_key: str, num_results: int) -> List[Dict[str, str]]:
|
| 160 |
if not serpapi_key:
|
| 161 |
raise gr.Error("SERPAPI_API_KEY ontbreekt in Secrets.")
|
| 162 |
url = "https://serpapi.com/search.json"
|
|
@@ -268,7 +268,7 @@ def build_sources(serp_results: List[Dict[str, str]], query: str) -> List[Dict[s
|
|
| 268 |
|
| 269 |
|
| 270 |
def sources_block(sources: List[Dict[str, Any]]) -> str:
|
| 271 |
-
# Alleen intern;
|
| 272 |
blocks = []
|
| 273 |
for i, s in enumerate(sources):
|
| 274 |
chunk_block = "\n".join([f"- CHUNK {j+1}: {c}" for j, c in enumerate(s.get("chunks") or [])])
|
|
@@ -279,7 +279,7 @@ def sources_block(sources: List[Dict[str, Any]]) -> str:
|
|
| 279 |
|
| 280 |
|
| 281 |
# -----------------------------
|
| 282 |
-
# OpenAI
|
| 283 |
# -----------------------------
|
| 284 |
def openai_client() -> OpenAI:
|
| 285 |
key = os.getenv("OPENAI_API_KEY", "").strip()
|
|
@@ -387,7 +387,7 @@ def gemini_generate(prompt: str, temperature: float = 0.0) -> str:
|
|
| 387 |
|
| 388 |
|
| 389 |
# -----------------------------
|
| 390 |
-
#
|
| 391 |
# -----------------------------
|
| 392 |
def step_a_extract_items(title: str, sources: List[Dict[str, Any]], max_items: int) -> Dict[str, Any]:
|
| 393 |
system = (
|
|
@@ -397,22 +397,22 @@ def step_a_extract_items(title: str, sources: List[Dict[str, Any]], max_items: i
|
|
| 397 |
)
|
| 398 |
|
| 399 |
user = f"""
|
| 400 |
-
We are preparing a YouTube documentary based on:
|
| 401 |
"{title}"
|
| 402 |
|
| 403 |
Task:
|
| 404 |
1) Propose an angle (1 sentence).
|
| 405 |
-
2) Extract up to {max_items} items that fit the title.
|
| 406 |
-
3) For each item:
|
| 407 |
- item_id
|
| 408 |
- item_name
|
| 409 |
-
- location (if stated else "")
|
| 410 |
-
- date_or_period (if stated else "")
|
| 411 |
-
- claims: EXACTLY {CLAIMS_PER_ITEM} ATOMIC claims with unique ids
|
| 412 |
|
| 413 |
Rules:
|
| 414 |
-
- Claims must be ATOMIC.
|
| 415 |
-
- Every claim must be supported by the excerpts. If not present, do NOT include it.
|
| 416 |
- If fewer items exist, return fewer. Do NOT invent.
|
| 417 |
|
| 418 |
Return EXACT JSON:
|
|
@@ -443,19 +443,25 @@ def step_b_verify_claims(plan: Dict[str, Any], sources: List[Dict[str, Any]]) ->
|
|
| 443 |
|
| 444 |
system_rules = """
|
| 445 |
You are a STRICT fact-checker.
|
| 446 |
-
|
|
|
|
| 447 |
|
| 448 |
-
Output MUST be valid JSON only
|
| 449 |
|
| 450 |
For each claim:
|
| 451 |
- verdict: "supported" | "not_supported" | "contradicted"
|
| 452 |
-
- If supported/contradicted:
|
| 453 |
- If not_supported: evidence []
|
| 454 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 455 |
Return EXACTLY:
|
| 456 |
{
|
| 457 |
"verifications": [
|
| 458 |
-
{"id":"...", "verdict":"supported|not_supported|contradicted", "evidence":[{"url":"...","quote":"..."}]}
|
| 459 |
]
|
| 460 |
}
|
| 461 |
""".strip()
|
|
@@ -500,8 +506,9 @@ Return JSON only.
|
|
| 500 |
return parsed
|
| 501 |
|
| 502 |
repairs = [
|
| 503 |
-
"
|
| 504 |
"Return only the JSON object again. Nothing else.",
|
|
|
|
| 505 |
]
|
| 506 |
for ins in repairs:
|
| 507 |
out = gemini_generate(prompt + "\n\n" + ins + f"\n\nPREVIOUS_OUTPUT:\n{out}", temperature=0.0)
|
|
@@ -509,13 +516,13 @@ Return JSON only.
|
|
| 509 |
if parsed is not None:
|
| 510 |
return parsed
|
| 511 |
|
| 512 |
-
# OpenAI repair fallback
|
| 513 |
repair_system = "You are a JSON repair tool. Output ONLY valid JSON. No markdown, no extra text."
|
| 514 |
repair_user = f"""
|
| 515 |
-
Convert
|
| 516 |
{{
|
| 517 |
-
"verifications":[
|
| 518 |
-
{{"id":"string","verdict":"supported|not_supported|contradicted","evidence":[{{"url":"string","quote":"string"}}]}}
|
| 519 |
]
|
| 520 |
}}
|
| 521 |
|
|
@@ -552,7 +559,9 @@ def step_c_build_verified(plan: Dict[str, Any], verification: Dict[str, Any], mi
|
|
| 552 |
continue
|
| 553 |
v = vmap.get(cid)
|
| 554 |
if v and v.get("verdict") == "supported":
|
| 555 |
-
supported_claims.append(
|
|
|
|
|
|
|
| 556 |
|
| 557 |
if len(supported_claims) < min_supported_claims:
|
| 558 |
continue
|
|
@@ -573,6 +582,8 @@ def step_d_assign_levels(verified: Dict[str, Any], target_levels: int) -> Dict[s
|
|
| 573 |
items = list(verified.get("verified_items") or [])
|
| 574 |
items = items[: max(1, min(target_levels, len(items)))]
|
| 575 |
|
|
|
|
|
|
|
| 576 |
for idx, it in enumerate(items):
|
| 577 |
it["level"] = idx
|
| 578 |
|
|
@@ -582,26 +593,45 @@ def step_d_assign_levels(verified: Dict[str, Any], target_levels: int) -> Dict[s
|
|
| 582 |
return out
|
| 583 |
|
| 584 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 585 |
# -----------------------------
|
| 586 |
-
#
|
| 587 |
# -----------------------------
|
| 588 |
-
def
|
| 589 |
system = (
|
| 590 |
-
"You are a
|
| 591 |
-
"CRITICAL: You must NOT
|
| 592 |
-
"
|
|
|
|
| 593 |
)
|
| 594 |
|
| 595 |
style = f"""
|
| 596 |
-
STYLE:
|
| 597 |
- Total length MUST be at least {min_words} words.
|
| 598 |
-
- Intro
|
| 599 |
-
|
| 600 |
-
|
| 601 |
-
|
| 602 |
-
-
|
| 603 |
-
-
|
| 604 |
-
-
|
| 605 |
""".strip()
|
| 606 |
|
| 607 |
user = f"""
|
|
@@ -610,27 +640,39 @@ VIDEO TITLE: {title}
|
|
| 610 |
VERIFIED_FACTS (JSON):
|
| 611 |
{json.dumps(verified_ranked, ensure_ascii=False)}
|
| 612 |
|
| 613 |
-
Write the full script
|
| 614 |
-
|
| 615 |
""".strip()
|
| 616 |
|
| 617 |
return openai_chat(system + "\n\n" + style, user, temperature=0.55, max_tokens=OPENAI_MAX_TOKENS)
|
| 618 |
|
| 619 |
|
| 620 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 621 |
system = (
|
| 622 |
-
"You
|
| 623 |
-
"
|
| 624 |
-
"You may
|
|
|
|
|
|
|
| 625 |
)
|
| 626 |
|
| 627 |
-
|
| 628 |
-
|
| 629 |
-
-
|
| 630 |
-
-
|
| 631 |
-
|
| 632 |
-
-
|
| 633 |
-
-
|
|
|
|
|
|
|
|
|
|
| 634 |
""".strip()
|
| 635 |
|
| 636 |
user = f"""
|
|
@@ -642,14 +684,14 @@ VERIFIED_FACTS (JSON):
|
|
| 642 |
DRAFT SCRIPT:
|
| 643 |
{draft}
|
| 644 |
|
| 645 |
-
Rewrite to
|
| 646 |
-
|
| 647 |
""".strip()
|
| 648 |
|
| 649 |
-
return openai_chat(system + "\n\n" +
|
| 650 |
|
| 651 |
|
| 652 |
-
def
|
| 653 |
wc = word_count(script)
|
| 654 |
if wc >= min_words:
|
| 655 |
return script
|
|
@@ -658,9 +700,9 @@ def step_g_expand_if_needed(title: str, verified_ranked: Dict[str, Any], script:
|
|
| 658 |
target_add = max(450, min(1100, remaining + 250))
|
| 659 |
|
| 660 |
system = (
|
| 661 |
-
"
|
| 662 |
-
"CRITICAL: No new
|
| 663 |
-
"Add more explanation and
|
| 664 |
)
|
| 665 |
|
| 666 |
user = f"""
|
|
@@ -672,8 +714,9 @@ VERIFIED_FACTS (JSON):
|
|
| 672 |
CURRENT_SCRIPT:
|
| 673 |
{script}
|
| 674 |
|
| 675 |
-
Continue where it ends
|
| 676 |
-
|
|
|
|
| 677 |
""".strip()
|
| 678 |
|
| 679 |
cont = openai_chat(system, user, temperature=0.5, max_tokens=OPENAI_MAX_TOKENS)
|
|
@@ -702,33 +745,39 @@ def generate(title: str, min_words: int, target_levels: int, request: gr.Request
|
|
| 702 |
|
| 703 |
plan = step_a_extract_items(title, sources, max_items=max(12, target_levels * 2))
|
| 704 |
verification = step_b_verify_claims(plan, sources)
|
| 705 |
-
verified = step_c_build_verified(plan, verification, min_supported_claims=min(MIN_SUPPORTED_CLAIMS, CLAIMS_PER_ITEM))
|
| 706 |
|
|
|
|
| 707 |
if not verified.get("verified_items"):
|
| 708 |
raise gr.Error("Te weinig verifieerbare items gevonden. Probeer een specifiekere titel of verhoog MAX_SOURCES/CHUNKS_PER_SOURCE.")
|
| 709 |
|
| 710 |
verified_ranked = step_d_assign_levels(verified, target_levels=target_levels)
|
| 711 |
|
| 712 |
-
|
| 713 |
-
|
| 714 |
-
|
|
|
|
| 715 |
|
| 716 |
wc = word_count(final_script)
|
| 717 |
final_script = final_script.rstrip() + f"\n\n---\nWord count: {wc}\n"
|
| 718 |
|
| 719 |
-
|
|
|
|
|
|
|
|
|
|
| 720 |
|
| 721 |
|
| 722 |
# -----------------------------
|
| 723 |
-
# UI (
|
| 724 |
# -----------------------------
|
| 725 |
-
with gr.Blocks(title="Universal YouTube Scriptwriter — Human Tone") as demo:
|
| 726 |
gr.Markdown(
|
| 727 |
-
"# Universal YouTube Scriptwriter — Human Tone\n"
|
| 728 |
"Vul alleen een **video titel** in en klik **Generate**.\n\n"
|
| 729 |
-
"-
|
| 730 |
-
"-
|
| 731 |
-
"-
|
|
|
|
|
|
|
| 732 |
)
|
| 733 |
|
| 734 |
title_in = gr.Textbox(label="Video titel", placeholder="Typ hier je titel…", lines=2)
|
|
@@ -738,9 +787,12 @@ with gr.Blocks(title="Universal YouTube Scriptwriter — Human Tone") as demo:
|
|
| 738 |
levels_in = gr.Slider(minimum=3, maximum=10, value=10, step=1, label="Aantal levels (max 10)")
|
| 739 |
|
| 740 |
btn = gr.Button("Generate")
|
|
|
|
| 741 |
script_out = gr.Textbox(label="Final script", lines=26)
|
|
|
|
|
|
|
| 742 |
|
| 743 |
-
btn.click(fn=generate, inputs=[title_in, min_words_in, levels_in], outputs=[script_out])
|
| 744 |
|
| 745 |
if __name__ == "__main__":
|
| 746 |
demo.launch()
|
|
|
|
| 1 |
# app.py
|
| 2 |
+
# Universal YouTube Scriptwriter — Verified Levels + Human Tone (NO LINKS OVERVIEW)
|
| 3 |
#
|
| 4 |
+
# Doelen:
|
| 5 |
+
# ✅ Universeel: alleen titel input
|
| 6 |
+
# ✅ Verified-only: script mag geen nieuwe feiten toevoegen buiten supported claims
|
| 7 |
+
# ✅ Minder AI-tonig: extra "humanize" rewrite-pass met strict no-new-facts
|
| 8 |
+
# ✅ Robust: fix plan=list -> normalize_plan, Gemini non-JSON repair, OpenAI token param compat
|
| 9 |
+
# ✅ UI: geen sources/links overzicht output
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
import os
|
| 12 |
import re
|
|
|
|
| 42 |
MIN_SECONDS_BETWEEN_RUNS = int(os.getenv("MIN_SECONDS_BETWEEN_RUNS", "15"))
|
| 43 |
_RATE: Dict[str, float] = {}
|
| 44 |
|
| 45 |
+
# Claim caps (speed + stability)
|
| 46 |
CLAIMS_PER_ITEM = int(os.getenv("CLAIMS_PER_ITEM", "6"))
|
| 47 |
MAX_VERIFY_CLAIMS = int(os.getenv("MAX_VERIFY_CLAIMS", "120"))
|
| 48 |
VERIFY_BATCH_SIZE = int(os.getenv("VERIFY_BATCH_SIZE", "15"))
|
|
|
|
| 75 |
|
| 76 |
|
| 77 |
def safe_json_extract(text: str) -> Any:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
text = (text or "").strip()
|
| 79 |
text = text.replace("\u201c", '"').replace("\u201d", '"').replace("\u2018", "'").replace("\u2019", "'")
|
| 80 |
text = re.sub(r"[\x00-\x08\x0b\x0c\x0e-\x1f]", "", text)
|
|
|
|
| 123 |
|
| 124 |
|
| 125 |
def normalize_plan(obj: Any) -> Dict[str, Any]:
|
| 126 |
+
# Fix voor: 'list' object has no attribute 'get'
|
| 127 |
if isinstance(obj, dict):
|
| 128 |
items = obj.get("items")
|
| 129 |
if not isinstance(items, list):
|
|
|
|
| 143 |
return {"verifications": []}
|
| 144 |
|
| 145 |
|
| 146 |
+
def safe_heading(level: int, name: str, location: str, date_or_period: str) -> str:
|
| 147 |
+
name = (name or "").strip() or "Untitled item"
|
| 148 |
+
loc = (location or "").strip()
|
| 149 |
+
dt = (date_or_period or "").strip()
|
| 150 |
+
meta = " — ".join([x for x in [loc, dt] if x])
|
| 151 |
+
if meta:
|
| 152 |
+
return f"### Level {level} — {name} ({meta})"
|
| 153 |
+
return f"### Level {level} — {name}"
|
| 154 |
+
|
| 155 |
+
|
| 156 |
# -----------------------------
|
| 157 |
# SERPAPI + Fetch
|
| 158 |
# -----------------------------
|
| 159 |
+
def serpapi_search(query: str, serpapi_key: str, num_results: int = MAX_SOURCES) -> List[Dict[str, str]]:
|
| 160 |
if not serpapi_key:
|
| 161 |
raise gr.Error("SERPAPI_API_KEY ontbreekt in Secrets.")
|
| 162 |
url = "https://serpapi.com/search.json"
|
|
|
|
| 268 |
|
| 269 |
|
| 270 |
def sources_block(sources: List[Dict[str, Any]]) -> str:
|
| 271 |
+
# Alleen intern; niet tonen in UI
|
| 272 |
blocks = []
|
| 273 |
for i, s in enumerate(sources):
|
| 274 |
chunk_block = "\n".join([f"- CHUNK {j+1}: {c}" for j, c in enumerate(s.get("chunks") or [])])
|
|
|
|
| 279 |
|
| 280 |
|
| 281 |
# -----------------------------
|
| 282 |
+
# OpenAI (token param compat)
|
| 283 |
# -----------------------------
|
| 284 |
def openai_client() -> OpenAI:
|
| 285 |
key = os.getenv("OPENAI_API_KEY", "").strip()
|
|
|
|
| 387 |
|
| 388 |
|
| 389 |
# -----------------------------
|
| 390 |
+
# Verification + selection
|
| 391 |
# -----------------------------
|
| 392 |
def step_a_extract_items(title: str, sources: List[Dict[str, Any]], max_items: int) -> Dict[str, Any]:
|
| 393 |
system = (
|
|
|
|
| 397 |
)
|
| 398 |
|
| 399 |
user = f"""
|
| 400 |
+
We are preparing a YouTube documentary video based on this title:
|
| 401 |
"{title}"
|
| 402 |
|
| 403 |
Task:
|
| 404 |
1) Propose an angle (1 sentence).
|
| 405 |
+
2) Extract up to {max_items} candidate items that fit the title.
|
| 406 |
+
3) For each item provide:
|
| 407 |
- item_id
|
| 408 |
- item_name
|
| 409 |
+
- location (if stated, else "")
|
| 410 |
+
- date_or_period (if stated, else "")
|
| 411 |
+
- claims: EXACTLY {CLAIMS_PER_ITEM} ATOMIC factual claims with unique ids
|
| 412 |
|
| 413 |
Rules:
|
| 414 |
+
- Claims must be ATOMIC (one fact per claim).
|
| 415 |
+
- Every claim must be supported by the excerpts. If not clearly present, do NOT include it.
|
| 416 |
- If fewer items exist, return fewer. Do NOT invent.
|
| 417 |
|
| 418 |
Return EXACT JSON:
|
|
|
|
| 443 |
|
| 444 |
system_rules = """
|
| 445 |
You are a STRICT fact-checker.
|
| 446 |
+
You must ONLY use the provided SOURCES excerpts.
|
| 447 |
+
Do NOT use outside knowledge.
|
| 448 |
|
| 449 |
+
Output MUST be valid JSON only. No markdown. No extra text.
|
| 450 |
|
| 451 |
For each claim:
|
| 452 |
- verdict: "supported" | "not_supported" | "contradicted"
|
| 453 |
+
- If supported/contradicted: exactly 1 quote (<=20 words) and its URL
|
| 454 |
- If not_supported: evidence []
|
| 455 |
|
| 456 |
+
Fix:
|
| 457 |
+
- supported -> "keep"
|
| 458 |
+
- not_supported -> "remove or rewrite to match sources"
|
| 459 |
+
- contradicted -> "remove"
|
| 460 |
+
|
| 461 |
Return EXACTLY:
|
| 462 |
{
|
| 463 |
"verifications": [
|
| 464 |
+
{"id":"...", "verdict":"supported|not_supported|contradicted", "evidence":[{"url":"...","quote":"..."}], "fix":"..."}
|
| 465 |
]
|
| 466 |
}
|
| 467 |
""".strip()
|
|
|
|
| 506 |
return parsed
|
| 507 |
|
| 508 |
repairs = [
|
| 509 |
+
"You MUST output ONLY valid JSON. Start with { and end with }. No markdown.",
|
| 510 |
"Return only the JSON object again. Nothing else.",
|
| 511 |
+
"STRICT: output a single JSON object with key 'verifications'.",
|
| 512 |
]
|
| 513 |
for ins in repairs:
|
| 514 |
out = gemini_generate(prompt + "\n\n" + ins + f"\n\nPREVIOUS_OUTPUT:\n{out}", temperature=0.0)
|
|
|
|
| 516 |
if parsed is not None:
|
| 517 |
return parsed
|
| 518 |
|
| 519 |
+
# OpenAI JSON repair fallback
|
| 520 |
repair_system = "You are a JSON repair tool. Output ONLY valid JSON. No markdown, no extra text."
|
| 521 |
repair_user = f"""
|
| 522 |
+
Convert this text into ONLY valid JSON with schema:
|
| 523 |
{{
|
| 524 |
+
"verifications": [
|
| 525 |
+
{{"id":"string","verdict":"supported|not_supported|contradicted","evidence":[{{"url":"string","quote":"string"}}],"fix":"keep|remove|remove or rewrite to match sources"}}
|
| 526 |
]
|
| 527 |
}}
|
| 528 |
|
|
|
|
| 559 |
continue
|
| 560 |
v = vmap.get(cid)
|
| 561 |
if v and v.get("verdict") == "supported":
|
| 562 |
+
supported_claims.append(
|
| 563 |
+
{"id": cid, "text": c.get("text", ""), "evidence": (v.get("evidence") or [])[:1]}
|
| 564 |
+
)
|
| 565 |
|
| 566 |
if len(supported_claims) < min_supported_claims:
|
| 567 |
continue
|
|
|
|
| 582 |
items = list(verified.get("verified_items") or [])
|
| 583 |
items = items[: max(1, min(target_levels, len(items)))]
|
| 584 |
|
| 585 |
+
# Level 0..N-1 in current order (we do NOT pretend severity for universal topics)
|
| 586 |
+
# If you want severity ranking, you need topic-specific or numeric-impact heuristics (often wrong).
|
| 587 |
for idx, it in enumerate(items):
|
| 588 |
it["level"] = idx
|
| 589 |
|
|
|
|
| 593 |
return out
|
| 594 |
|
| 595 |
|
| 596 |
+
def render_claims_report_no_links(verification: Dict[str, Any]) -> str:
|
| 597 |
+
verification = normalize_verifications(verification)
|
| 598 |
+
lines = ["## Claims & verificatie (zonder links)\n"]
|
| 599 |
+
for v in (verification.get("verifications") or []):
|
| 600 |
+
if not isinstance(v, dict):
|
| 601 |
+
continue
|
| 602 |
+
verdict = v.get("verdict", "")
|
| 603 |
+
cid = v.get("id", "")
|
| 604 |
+
fix = v.get("fix", "")
|
| 605 |
+
lines.append(f"- **{cid}** — `{verdict}` — {fix}")
|
| 606 |
+
ev = v.get("evidence") or []
|
| 607 |
+
if isinstance(ev, list) and ev and isinstance(ev[0], dict):
|
| 608 |
+
q = ev[0].get("quote", "")
|
| 609 |
+
if q:
|
| 610 |
+
lines.append(f" - “{q}”")
|
| 611 |
+
return "\n".join(lines)
|
| 612 |
+
|
| 613 |
+
|
| 614 |
# -----------------------------
|
| 615 |
+
# Script writing (two-pass: draft -> humanize)
|
| 616 |
# -----------------------------
|
| 617 |
+
def step_e_write_script_draft(title: str, verified_ranked: Dict[str, Any], min_words: int) -> str:
|
| 618 |
system = (
|
| 619 |
+
"You are a careful documentary narrator and scriptwriter.\n"
|
| 620 |
+
"CRITICAL: You must NOT introduce ANY new factual claims beyond VERIFIED_FACTS.levels[*].supported_claims.\n"
|
| 621 |
+
"Do NOT add dates, numbers, names, causes, or background unless explicitly present in supported_claims.\n"
|
| 622 |
+
"If something isn't verified, omit it.\n"
|
| 623 |
)
|
| 624 |
|
| 625 |
style = f"""
|
| 626 |
+
DRAFT STYLE:
|
| 627 |
- Total length MUST be at least {min_words} words.
|
| 628 |
+
- Intro: hook + promise (180–240 words).
|
| 629 |
+
- Each level: 240–340 words.
|
| 630 |
+
- Use headings exactly like:
|
| 631 |
+
"### Level N — Title (Location — Date)" BUT if location/date missing, omit them (no empty parentheses).
|
| 632 |
+
- Do NOT include “What remains unclear…” in every level. Only mention uncertainty if it's important, and keep it to 1 sentence max.
|
| 633 |
+
- Vary sentence length. Avoid repetitive phrasing and template-like structure.
|
| 634 |
+
- End: 90–140 words outro + ONE short CTA line.
|
| 635 |
""".strip()
|
| 636 |
|
| 637 |
user = f"""
|
|
|
|
| 640 |
VERIFIED_FACTS (JSON):
|
| 641 |
{json.dumps(verified_ranked, ensure_ascii=False)}
|
| 642 |
|
| 643 |
+
Write the full script as a draft.
|
| 644 |
+
Use ONLY verified facts.
|
| 645 |
""".strip()
|
| 646 |
|
| 647 |
return openai_chat(system + "\n\n" + style, user, temperature=0.55, max_tokens=OPENAI_MAX_TOKENS)
|
| 648 |
|
| 649 |
|
| 650 |
+
def step_f_humanize_script(title: str, verified_ranked: Dict[str, Any], draft: str) -> str:
|
| 651 |
+
"""
|
| 652 |
+
Human rewrite pass:
|
| 653 |
+
- removes AI tone
|
| 654 |
+
- reduces repetition
|
| 655 |
+
- improves flow
|
| 656 |
+
- STRICT: no new facts beyond VERIFIED_FACTS
|
| 657 |
+
"""
|
| 658 |
system = (
|
| 659 |
+
"You are an expert YouTube documentary writer.\n"
|
| 660 |
+
"GOAL: rewrite to sound human and engaging.\n"
|
| 661 |
+
"CRITICAL SAFETY RULE: You may NOT add new factual claims.\n"
|
| 662 |
+
"You may ONLY use facts found in VERIFIED_FACTS.levels[*].supported_claims.\n"
|
| 663 |
+
"You CAN rephrase, reorder, add connective tissue, and add non-factual narration (mood, pacing) without introducing new facts.\n"
|
| 664 |
)
|
| 665 |
|
| 666 |
+
rewrite_rules = """
|
| 667 |
+
HUMAN TONE RULES:
|
| 668 |
+
- Kill repetition: do not restate the same fact twice unless for emphasis (max once).
|
| 669 |
+
- Avoid robotic scaffolding like “What remains unclear from these sources…”. If needed, use short natural lines like:
|
| 670 |
+
“The sources don’t spell out every detail here.”
|
| 671 |
+
- Add natural transitions between levels (1–2 lines).
|
| 672 |
+
- Use a mix of short punchy sentences and longer explanatory ones.
|
| 673 |
+
- No academic vibe. Make it spoken, but still smart.
|
| 674 |
+
- Keep headings, but ensure no empty parentheses.
|
| 675 |
+
- Keep total length roughly similar (do not shrink heavily).
|
| 676 |
""".strip()
|
| 677 |
|
| 678 |
user = f"""
|
|
|
|
| 684 |
DRAFT SCRIPT:
|
| 685 |
{draft}
|
| 686 |
|
| 687 |
+
Rewrite the entire script to sound more human (spoken documentary tone).
|
| 688 |
+
Do NOT add any new facts.
|
| 689 |
""".strip()
|
| 690 |
|
| 691 |
+
return openai_chat(system + "\n\n" + rewrite_rules, user, temperature=0.6, max_tokens=OPENAI_MAX_TOKENS)
|
| 692 |
|
| 693 |
|
| 694 |
+
def step_g_one_expand_if_needed(title: str, verified_ranked: Dict[str, Any], script: str, min_words: int) -> str:
|
| 695 |
wc = word_count(script)
|
| 696 |
if wc >= min_words:
|
| 697 |
return script
|
|
|
|
| 700 |
target_add = max(450, min(1100, remaining + 250))
|
| 701 |
|
| 702 |
system = (
|
| 703 |
+
"You are continuing a documentary script.\n"
|
| 704 |
+
"CRITICAL: No new factual claims. ONLY use VERIFIED_FACTS.levels[*].supported_claims.\n"
|
| 705 |
+
"Add more explanation and transitions without adding new facts.\n"
|
| 706 |
)
|
| 707 |
|
| 708 |
user = f"""
|
|
|
|
| 714 |
CURRENT_SCRIPT:
|
| 715 |
{script}
|
| 716 |
|
| 717 |
+
Continue where it ends.
|
| 718 |
+
Add about {target_add} words.
|
| 719 |
+
Do NOT add new facts.
|
| 720 |
""".strip()
|
| 721 |
|
| 722 |
cont = openai_chat(system, user, temperature=0.5, max_tokens=OPENAI_MAX_TOKENS)
|
|
|
|
| 745 |
|
| 746 |
plan = step_a_extract_items(title, sources, max_items=max(12, target_levels * 2))
|
| 747 |
verification = step_b_verify_claims(plan, sources)
|
|
|
|
| 748 |
|
| 749 |
+
verified = step_c_build_verified(plan, verification, min_supported_claims=min(MIN_SUPPORTED_CLAIMS, CLAIMS_PER_ITEM))
|
| 750 |
if not verified.get("verified_items"):
|
| 751 |
raise gr.Error("Te weinig verifieerbare items gevonden. Probeer een specifiekere titel of verhoog MAX_SOURCES/CHUNKS_PER_SOURCE.")
|
| 752 |
|
| 753 |
verified_ranked = step_d_assign_levels(verified, target_levels=target_levels)
|
| 754 |
|
| 755 |
+
# Draft -> Humanize -> Expand (if needed)
|
| 756 |
+
draft = step_e_write_script_draft(title, verified_ranked, min_words=min_words)
|
| 757 |
+
human = step_f_humanize_script(title, verified_ranked, draft)
|
| 758 |
+
final_script = step_g_one_expand_if_needed(title, verified_ranked, human, min_words=min_words)
|
| 759 |
|
| 760 |
wc = word_count(final_script)
|
| 761 |
final_script = final_script.rstrip() + f"\n\n---\nWord count: {wc}\n"
|
| 762 |
|
| 763 |
+
claims_md = render_claims_report_no_links(verification)
|
| 764 |
+
debug_json = json.dumps(verified_ranked, ensure_ascii=False, indent=2)
|
| 765 |
+
|
| 766 |
+
return final_script, claims_md, debug_json
|
| 767 |
|
| 768 |
|
| 769 |
# -----------------------------
|
| 770 |
+
# UI (zonder sources output)
|
| 771 |
# -----------------------------
|
| 772 |
+
with gr.Blocks(title="Universal YouTube Scriptwriter — Human Tone (No Links)") as demo:
|
| 773 |
gr.Markdown(
|
| 774 |
+
"# Universal YouTube Scriptwriter — Human Tone (No Links)\n"
|
| 775 |
"Vul alleen een **video titel** in en klik **Generate**.\n\n"
|
| 776 |
+
"- Universeel (geen onderwerp-code)\n"
|
| 777 |
+
"- Verified-only script\n"
|
| 778 |
+
"- Minimaal 3000 woorden (instelbaar)\n"
|
| 779 |
+
"- Extra humanize-pass voor minder AI-tonige stijl\n"
|
| 780 |
+
"- Geen bronnen/links-overzicht in output\n"
|
| 781 |
)
|
| 782 |
|
| 783 |
title_in = gr.Textbox(label="Video titel", placeholder="Typ hier je titel…", lines=2)
|
|
|
|
| 787 |
levels_in = gr.Slider(minimum=3, maximum=10, value=10, step=1, label="Aantal levels (max 10)")
|
| 788 |
|
| 789 |
btn = gr.Button("Generate")
|
| 790 |
+
|
| 791 |
script_out = gr.Textbox(label="Final script", lines=26)
|
| 792 |
+
claims_out = gr.Markdown()
|
| 793 |
+
debug_out = gr.Textbox(label="Verified facts (JSON) — debug", lines=12)
|
| 794 |
|
| 795 |
+
btn.click(fn=generate, inputs=[title_in, min_words_in, levels_in], outputs=[script_out, claims_out, debug_out])
|
| 796 |
|
| 797 |
if __name__ == "__main__":
|
| 798 |
demo.launch()
|