Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,12 +1,11 @@
|
|
| 1 |
# app.py
|
| 2 |
-
# Universal YouTube Scriptwriter —
|
| 3 |
#
|
| 4 |
-
#
|
| 5 |
-
# ✅
|
| 6 |
-
# ✅
|
| 7 |
-
# ✅
|
| 8 |
-
# ✅ Robust:
|
| 9 |
-
# ✅ UI: geen sources/links overzicht output
|
| 10 |
|
| 11 |
import os
|
| 12 |
import re
|
|
@@ -48,6 +47,9 @@ MAX_VERIFY_CLAIMS = int(os.getenv("MAX_VERIFY_CLAIMS", "120"))
|
|
| 48 |
VERIFY_BATCH_SIZE = int(os.getenv("VERIFY_BATCH_SIZE", "15"))
|
| 49 |
MIN_SUPPORTED_CLAIMS = int(os.getenv("MIN_SUPPORTED_CLAIMS", "3"))
|
| 50 |
|
|
|
|
|
|
|
|
|
|
| 51 |
_FETCH_CACHE: Dict[str, str] = {}
|
| 52 |
|
| 53 |
|
|
@@ -123,7 +125,7 @@ def safe_json_extract(text: str) -> Any:
|
|
| 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,20 +145,10 @@ def normalize_verifications(obj: Any) -> Dict[str, Any]:
|
|
| 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
|
| 160 |
if not serpapi_key:
|
| 161 |
raise gr.Error("SERPAPI_API_KEY ontbreekt in Secrets.")
|
| 162 |
url = "https://serpapi.com/search.json"
|
|
@@ -268,7 +260,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 +271,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 +379,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 +389,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
|
| 401 |
"{title}"
|
| 402 |
|
| 403 |
Task:
|
| 404 |
1) Propose an angle (1 sentence).
|
| 405 |
-
2) Extract up to {max_items}
|
| 406 |
-
3) For each item
|
| 407 |
- item_id
|
| 408 |
- item_name
|
| 409 |
-
- location (if stated
|
| 410 |
-
- date_or_period (if stated
|
| 411 |
-
- claims: EXACTLY {CLAIMS_PER_ITEM} ATOMIC
|
| 412 |
|
| 413 |
Rules:
|
| 414 |
-
- Claims must be ATOMIC
|
| 415 |
-
- Every claim must be supported by the excerpts. If not
|
| 416 |
- If fewer items exist, return fewer. Do NOT invent.
|
| 417 |
|
| 418 |
Return EXACT JSON:
|
|
@@ -443,25 +435,19 @@ 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 |
-
Do NOT use outside knowledge.
|
| 448 |
|
| 449 |
-
Output MUST be valid JSON only
|
| 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,9 +492,8 @@ Return JSON only.
|
|
| 506 |
return parsed
|
| 507 |
|
| 508 |
repairs = [
|
| 509 |
-
"
|
| 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,13 +501,13 @@ Return JSON only.
|
|
| 516 |
if parsed is not None:
|
| 517 |
return parsed
|
| 518 |
|
| 519 |
-
# OpenAI
|
| 520 |
repair_system = "You are a JSON repair tool. Output ONLY valid JSON. No markdown, no extra text."
|
| 521 |
repair_user = f"""
|
| 522 |
-
Convert
|
| 523 |
{{
|
| 524 |
-
"verifications":
|
| 525 |
-
{{"id":"string","verdict":"supported|not_supported|contradicted","evidence":[{{"url":"string","quote":"string"}}],"fix":"keep|remove
|
| 526 |
]
|
| 527 |
}}
|
| 528 |
|
|
@@ -559,9 +544,7 @@ def step_c_build_verified(plan: Dict[str, Any], verification: Dict[str, Any], mi
|
|
| 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,8 +565,6 @@ def step_d_assign_levels(verified: Dict[str, Any], target_levels: int) -> Dict[s
|
|
| 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,45 +574,24 @@ def step_d_assign_levels(verified: Dict[str, Any], target_levels: int) -> Dict[s
|
|
| 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 |
-
#
|
| 616 |
# -----------------------------
|
| 617 |
-
def
|
| 618 |
system = (
|
| 619 |
-
"You are a
|
| 620 |
-
"CRITICAL: You must NOT
|
| 621 |
-
"
|
| 622 |
-
"If something isn't verified, omit it.\n"
|
| 623 |
)
|
| 624 |
|
| 625 |
style = f"""
|
| 626 |
-
|
| 627 |
- Total length MUST be at least {min_words} words.
|
| 628 |
-
- Intro
|
| 629 |
-
-
|
| 630 |
-
-
|
| 631 |
-
|
| 632 |
-
-
|
| 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,39 +600,28 @@ VIDEO TITLE: {title}
|
|
| 640 |
VERIFIED_FACTS (JSON):
|
| 641 |
{json.dumps(verified_ranked, ensure_ascii=False)}
|
| 642 |
|
| 643 |
-
Write the full script
|
| 644 |
-
|
| 645 |
""".strip()
|
| 646 |
|
| 647 |
return openai_chat(system + "\n\n" + style, user, temperature=0.55, max_tokens=OPENAI_MAX_TOKENS)
|
| 648 |
|
| 649 |
|
| 650 |
-
def
|
| 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
|
| 660 |
-
"
|
| 661 |
-
"
|
| 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 |
-
|
| 667 |
-
|
| 668 |
-
-
|
| 669 |
-
-
|
| 670 |
-
|
| 671 |
-
-
|
| 672 |
-
-
|
| 673 |
-
-
|
| 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,14 +633,14 @@ VERIFIED_FACTS (JSON):
|
|
| 684 |
DRAFT SCRIPT:
|
| 685 |
{draft}
|
| 686 |
|
| 687 |
-
Rewrite
|
| 688 |
-
|
| 689 |
""".strip()
|
| 690 |
|
| 691 |
-
return openai_chat(system + "\n\n" +
|
| 692 |
|
| 693 |
|
| 694 |
-
def
|
| 695 |
wc = word_count(script)
|
| 696 |
if wc >= min_words:
|
| 697 |
return script
|
|
@@ -700,9 +649,9 @@ def step_g_one_expand_if_needed(title: str, verified_ranked: Dict[str, Any], scr
|
|
| 700 |
target_add = max(450, min(1100, remaining + 250))
|
| 701 |
|
| 702 |
system = (
|
| 703 |
-
"
|
| 704 |
-
"CRITICAL: No new
|
| 705 |
-
"Add more explanation and
|
| 706 |
)
|
| 707 |
|
| 708 |
user = f"""
|
|
@@ -714,9 +663,8 @@ VERIFIED_FACTS (JSON):
|
|
| 714 |
CURRENT_SCRIPT:
|
| 715 |
{script}
|
| 716 |
|
| 717 |
-
Continue where it ends.
|
| 718 |
-
|
| 719 |
-
Do NOT add new facts.
|
| 720 |
""".strip()
|
| 721 |
|
| 722 |
cont = openai_chat(system, user, temperature=0.5, max_tokens=OPENAI_MAX_TOKENS)
|
|
@@ -745,39 +693,35 @@ def generate(title: str, min_words: int, target_levels: int, request: gr.Request
|
|
| 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 |
-
|
| 756 |
-
|
| 757 |
-
|
| 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 |
-
|
| 764 |
-
debug_json = json.dumps(verified_ranked, ensure_ascii=False, indent=2)
|
| 765 |
|
| 766 |
-
return final_script,
|
| 767 |
|
| 768 |
|
| 769 |
# -----------------------------
|
| 770 |
-
# UI (
|
| 771 |
# -----------------------------
|
| 772 |
-
with gr.Blocks(title="Universal YouTube Scriptwriter — Human Tone (No
|
| 773 |
gr.Markdown(
|
| 774 |
-
"# Universal YouTube Scriptwriter — Human Tone
|
| 775 |
"Vul alleen een **video titel** in en klik **Generate**.\n\n"
|
| 776 |
-
"-
|
| 777 |
-
"-
|
| 778 |
-
"-
|
| 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)
|
|
@@ -789,10 +733,14 @@ with gr.Blocks(title="Universal YouTube Scriptwriter — Human Tone (No Links)")
|
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 796 |
|
| 797 |
if __name__ == "__main__":
|
| 798 |
demo.launch()
|
|
|
|
| 1 |
# app.py
|
| 2 |
+
# Universal YouTube Scriptwriter — Human Tone (NO LINKS OVERVIEW, NO CLAIMS OUTPUT)
|
| 3 |
#
|
| 4 |
+
# Updates per jouw verzoek:
|
| 5 |
+
# ✅ Intro korter + menselijker (expliciete regels + humanize-pass)
|
| 6 |
+
# ✅ Output in afbeelding ("Claims & verificatie") VERWIJDERD -> geen claims output meer
|
| 7 |
+
# ✅ Nog steeds verified-only (intern), maar we tonen alleen: Final script + Debug JSON (optioneel)
|
| 8 |
+
# ✅ Robust: plan=list -> normalize_plan, Gemini JSON repair, OpenAI token param compat
|
|
|
|
| 9 |
|
| 10 |
import os
|
| 11 |
import re
|
|
|
|
| 47 |
VERIFY_BATCH_SIZE = int(os.getenv("VERIFY_BATCH_SIZE", "15"))
|
| 48 |
MIN_SUPPORTED_CLAIMS = int(os.getenv("MIN_SUPPORTED_CLAIMS", "3"))
|
| 49 |
|
| 50 |
+
# UI options
|
| 51 |
+
SHOW_DEBUG_JSON = os.getenv("SHOW_DEBUG_JSON", "1").strip() not in ("0", "false", "False", "no", "NO")
|
| 52 |
+
|
| 53 |
_FETCH_CACHE: Dict[str, str] = {}
|
| 54 |
|
| 55 |
|
|
|
|
| 125 |
|
| 126 |
|
| 127 |
def normalize_plan(obj: Any) -> Dict[str, Any]:
|
| 128 |
+
# Fix voor: AttributeError: 'list' object has no attribute 'get'
|
| 129 |
if isinstance(obj, dict):
|
| 130 |
items = obj.get("items")
|
| 131 |
if not isinstance(items, list):
|
|
|
|
| 145 |
return {"verifications": []}
|
| 146 |
|
| 147 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 148 |
# -----------------------------
|
| 149 |
# SERPAPI + Fetch
|
| 150 |
# -----------------------------
|
| 151 |
+
def serpapi_search(query: str, serpapi_key: str, num_results: int) -> List[Dict[str, str]]:
|
| 152 |
if not serpapi_key:
|
| 153 |
raise gr.Error("SERPAPI_API_KEY ontbreekt in Secrets.")
|
| 154 |
url = "https://serpapi.com/search.json"
|
|
|
|
| 260 |
|
| 261 |
|
| 262 |
def sources_block(sources: List[Dict[str, Any]]) -> str:
|
| 263 |
+
# Alleen intern; geen UI overzicht
|
| 264 |
blocks = []
|
| 265 |
for i, s in enumerate(sources):
|
| 266 |
chunk_block = "\n".join([f"- CHUNK {j+1}: {c}" for j, c in enumerate(s.get("chunks") or [])])
|
|
|
|
| 271 |
|
| 272 |
|
| 273 |
# -----------------------------
|
| 274 |
+
# OpenAI
|
| 275 |
# -----------------------------
|
| 276 |
def openai_client() -> OpenAI:
|
| 277 |
key = os.getenv("OPENAI_API_KEY", "").strip()
|
|
|
|
| 379 |
|
| 380 |
|
| 381 |
# -----------------------------
|
| 382 |
+
# Pipeline
|
| 383 |
# -----------------------------
|
| 384 |
def step_a_extract_items(title: str, sources: List[Dict[str, Any]], max_items: int) -> Dict[str, Any]:
|
| 385 |
system = (
|
|
|
|
| 389 |
)
|
| 390 |
|
| 391 |
user = f"""
|
| 392 |
+
We are preparing a YouTube documentary based on:
|
| 393 |
"{title}"
|
| 394 |
|
| 395 |
Task:
|
| 396 |
1) Propose an angle (1 sentence).
|
| 397 |
+
2) Extract up to {max_items} items that fit the title.
|
| 398 |
+
3) For each item:
|
| 399 |
- item_id
|
| 400 |
- item_name
|
| 401 |
+
- location (if stated else "")
|
| 402 |
+
- date_or_period (if stated else "")
|
| 403 |
+
- claims: EXACTLY {CLAIMS_PER_ITEM} ATOMIC claims with unique ids
|
| 404 |
|
| 405 |
Rules:
|
| 406 |
+
- Claims must be ATOMIC.
|
| 407 |
+
- Every claim must be supported by the excerpts. If not present, do NOT include it.
|
| 408 |
- If fewer items exist, return fewer. Do NOT invent.
|
| 409 |
|
| 410 |
Return EXACT JSON:
|
|
|
|
| 435 |
|
| 436 |
system_rules = """
|
| 437 |
You are a STRICT fact-checker.
|
| 438 |
+
Use ONLY the SOURCES excerpts. No outside knowledge.
|
|
|
|
| 439 |
|
| 440 |
+
Output MUST be valid JSON only (no markdown).
|
| 441 |
|
| 442 |
For each claim:
|
| 443 |
- verdict: "supported" | "not_supported" | "contradicted"
|
| 444 |
+
- If supported/contradicted: include exactly 1 quote (<=20 words) and its URL
|
| 445 |
- If not_supported: evidence []
|
| 446 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 447 |
Return EXACTLY:
|
| 448 |
{
|
| 449 |
"verifications": [
|
| 450 |
+
{"id":"...", "verdict":"supported|not_supported|contradicted", "evidence":[{"url":"...","quote":"..."}], "fix":"keep|remove"}
|
| 451 |
]
|
| 452 |
}
|
| 453 |
""".strip()
|
|
|
|
| 492 |
return parsed
|
| 493 |
|
| 494 |
repairs = [
|
| 495 |
+
"Return ONLY valid JSON. Start with { and end with }. No markdown.",
|
| 496 |
"Return only the JSON object again. Nothing else.",
|
|
|
|
| 497 |
]
|
| 498 |
for ins in repairs:
|
| 499 |
out = gemini_generate(prompt + "\n\n" + ins + f"\n\nPREVIOUS_OUTPUT:\n{out}", temperature=0.0)
|
|
|
|
| 501 |
if parsed is not None:
|
| 502 |
return parsed
|
| 503 |
|
| 504 |
+
# OpenAI repair fallback
|
| 505 |
repair_system = "You are a JSON repair tool. Output ONLY valid JSON. No markdown, no extra text."
|
| 506 |
repair_user = f"""
|
| 507 |
+
Convert to valid JSON with schema:
|
| 508 |
{{
|
| 509 |
+
"verifications":[
|
| 510 |
+
{{"id":"string","verdict":"supported|not_supported|contradicted","evidence":[{{"url":"string","quote":"string"}}],"fix":"keep|remove"}}
|
| 511 |
]
|
| 512 |
}}
|
| 513 |
|
|
|
|
| 544 |
continue
|
| 545 |
v = vmap.get(cid)
|
| 546 |
if v and v.get("verdict") == "supported":
|
| 547 |
+
supported_claims.append({"id": cid, "text": c.get("text", "")})
|
|
|
|
|
|
|
| 548 |
|
| 549 |
if len(supported_claims) < min_supported_claims:
|
| 550 |
continue
|
|
|
|
| 565 |
items = list(verified.get("verified_items") or [])
|
| 566 |
items = items[: max(1, min(target_levels, len(items)))]
|
| 567 |
|
|
|
|
|
|
|
| 568 |
for idx, it in enumerate(items):
|
| 569 |
it["level"] = idx
|
| 570 |
|
|
|
|
| 574 |
return out
|
| 575 |
|
| 576 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 577 |
# -----------------------------
|
| 578 |
+
# Writing (shorter human intro + humanize pass)
|
| 579 |
# -----------------------------
|
| 580 |
+
def step_e_write_draft(title: str, verified_ranked: Dict[str, Any], min_words: int) -> str:
|
| 581 |
system = (
|
| 582 |
+
"You are a professional YouTube documentary writer.\n"
|
| 583 |
+
"CRITICAL: You must NOT add ANY new factual claims beyond VERIFIED_FACTS.levels[*].supported_claims.\n"
|
| 584 |
+
"Only rephrase and connect.\n"
|
|
|
|
| 585 |
)
|
| 586 |
|
| 587 |
style = f"""
|
| 588 |
+
STYLE:
|
| 589 |
- Total length MUST be at least {min_words} words.
|
| 590 |
+
- Intro MUST be short and human: 80–130 words. (No lecture tone, no generic 'In this video we will...').
|
| 591 |
+
- Use headings per level, and avoid empty parentheses if location/date missing.
|
| 592 |
+
- Reduce repetition: do not restate the same fact twice.
|
| 593 |
+
- Use natural, spoken pacing.
|
| 594 |
+
- Outro: 70–120 words + 1 short CTA.
|
|
|
|
|
|
|
| 595 |
""".strip()
|
| 596 |
|
| 597 |
user = f"""
|
|
|
|
| 600 |
VERIFIED_FACTS (JSON):
|
| 601 |
{json.dumps(verified_ranked, ensure_ascii=False)}
|
| 602 |
|
| 603 |
+
Write the full script in the STYLE.
|
| 604 |
+
Only use verified facts.
|
| 605 |
""".strip()
|
| 606 |
|
| 607 |
return openai_chat(system + "\n\n" + style, user, temperature=0.55, max_tokens=OPENAI_MAX_TOKENS)
|
| 608 |
|
| 609 |
|
| 610 |
+
def step_f_humanize(title: str, verified_ranked: Dict[str, Any], draft: str) -> str:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 611 |
system = (
|
| 612 |
+
"You rewrite scripts to sound like a real human narrator.\n"
|
| 613 |
+
"CRITICAL: You may NOT add new facts.\n"
|
| 614 |
+
"You may ONLY use facts in VERIFIED_FACTS.levels[*].supported_claims.\n"
|
|
|
|
|
|
|
| 615 |
)
|
| 616 |
|
| 617 |
+
rules = """
|
| 618 |
+
HUMANIZATION RULES:
|
| 619 |
+
- Make it sound spoken: contractions where appropriate, varied rhythm.
|
| 620 |
+
- Remove stiff academic phrasing.
|
| 621 |
+
- Replace repeated sentence starters and repeated claims.
|
| 622 |
+
- Keep uncertainty mentions rare and natural (max 1 short line per level, only if needed).
|
| 623 |
+
- Keep headings and structure.
|
| 624 |
+
- Do not inflate the intro; keep it tight.
|
|
|
|
|
|
|
| 625 |
""".strip()
|
| 626 |
|
| 627 |
user = f"""
|
|
|
|
| 633 |
DRAFT SCRIPT:
|
| 634 |
{draft}
|
| 635 |
|
| 636 |
+
Rewrite to be more human and less AI-toned.
|
| 637 |
+
No new facts.
|
| 638 |
""".strip()
|
| 639 |
|
| 640 |
+
return openai_chat(system + "\n\n" + rules, user, temperature=0.6, max_tokens=OPENAI_MAX_TOKENS)
|
| 641 |
|
| 642 |
|
| 643 |
+
def step_g_expand_if_needed(title: str, verified_ranked: Dict[str, Any], script: str, min_words: int) -> str:
|
| 644 |
wc = word_count(script)
|
| 645 |
if wc >= min_words:
|
| 646 |
return script
|
|
|
|
| 649 |
target_add = max(450, min(1100, remaining + 250))
|
| 650 |
|
| 651 |
system = (
|
| 652 |
+
"Continue the documentary script.\n"
|
| 653 |
+
"CRITICAL: No new facts. Only use VERIFIED_FACTS.levels[*].supported_claims.\n"
|
| 654 |
+
"Add more explanation and smoother transitions.\n"
|
| 655 |
)
|
| 656 |
|
| 657 |
user = f"""
|
|
|
|
| 663 |
CURRENT_SCRIPT:
|
| 664 |
{script}
|
| 665 |
|
| 666 |
+
Continue where it ends and add about {target_add} words.
|
| 667 |
+
No new facts.
|
|
|
|
| 668 |
""".strip()
|
| 669 |
|
| 670 |
cont = openai_chat(system, user, temperature=0.5, max_tokens=OPENAI_MAX_TOKENS)
|
|
|
|
| 693 |
|
| 694 |
plan = step_a_extract_items(title, sources, max_items=max(12, target_levels * 2))
|
| 695 |
verification = step_b_verify_claims(plan, sources)
|
|
|
|
| 696 |
verified = step_c_build_verified(plan, verification, min_supported_claims=min(MIN_SUPPORTED_CLAIMS, CLAIMS_PER_ITEM))
|
| 697 |
+
|
| 698 |
if not verified.get("verified_items"):
|
| 699 |
raise gr.Error("Te weinig verifieerbare items gevonden. Probeer een specifiekere titel of verhoog MAX_SOURCES/CHUNKS_PER_SOURCE.")
|
| 700 |
|
| 701 |
verified_ranked = step_d_assign_levels(verified, target_levels=target_levels)
|
| 702 |
|
| 703 |
+
draft = step_e_write_draft(title, verified_ranked, min_words=min_words)
|
| 704 |
+
human = step_f_humanize(title, verified_ranked, draft)
|
| 705 |
+
final_script = step_g_expand_if_needed(title, verified_ranked, human, min_words=min_words)
|
|
|
|
| 706 |
|
| 707 |
wc = word_count(final_script)
|
| 708 |
final_script = final_script.rstrip() + f"\n\n---\nWord count: {wc}\n"
|
| 709 |
|
| 710 |
+
debug_json = json.dumps(verified_ranked, ensure_ascii=False, indent=2) if SHOW_DEBUG_JSON else ""
|
|
|
|
| 711 |
|
| 712 |
+
return final_script, debug_json
|
| 713 |
|
| 714 |
|
| 715 |
# -----------------------------
|
| 716 |
+
# UI (claims output verwijderd)
|
| 717 |
# -----------------------------
|
| 718 |
+
with gr.Blocks(title="Universal YouTube Scriptwriter — Human Tone (No Claims Output)") as demo:
|
| 719 |
gr.Markdown(
|
| 720 |
+
"# Universal YouTube Scriptwriter — Human Tone\n"
|
| 721 |
"Vul alleen een **video titel** in en klik **Generate**.\n\n"
|
| 722 |
+
"- Intro is korter en menselijker\n"
|
| 723 |
+
"- Geen “Claims & verificatie” output\n"
|
| 724 |
+
"- Verified-only script (intern)\n"
|
|
|
|
|
|
|
| 725 |
)
|
| 726 |
|
| 727 |
title_in = gr.Textbox(label="Video titel", placeholder="Typ hier je titel…", lines=2)
|
|
|
|
| 733 |
btn = gr.Button("Generate")
|
| 734 |
|
| 735 |
script_out = gr.Textbox(label="Final script", lines=26)
|
|
|
|
|
|
|
| 736 |
|
| 737 |
+
if SHOW_DEBUG_JSON:
|
| 738 |
+
debug_out = gr.Textbox(label="Verified facts (JSON) — debug", lines=12)
|
| 739 |
+
btn.click(fn=generate, inputs=[title_in, min_words_in, levels_in], outputs=[script_out, debug_out])
|
| 740 |
+
else:
|
| 741 |
+
# If debug disabled, still keep function signature; we ignore debug output
|
| 742 |
+
dummy = gr.Textbox(visible=False)
|
| 743 |
+
btn.click(fn=generate, inputs=[title_in, min_words_in, levels_in], outputs=[script_out, dummy])
|
| 744 |
|
| 745 |
if __name__ == "__main__":
|
| 746 |
demo.launch()
|