Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,14 +6,20 @@ from typing import List, Dict, Any
|
|
| 6 |
|
| 7 |
import gradio as gr
|
| 8 |
import requests
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
from openai import OpenAI
|
| 10 |
from google import genai
|
| 11 |
|
|
|
|
| 12 |
# -----------------------------
|
| 13 |
# Config
|
| 14 |
# -----------------------------
|
| 15 |
OPENAI_MODEL = os.getenv("OPENAI_MODEL", "gpt-4o-mini")
|
| 16 |
-
GEMINI_MODEL = os.getenv("GEMINI_MODEL", "models/gemini-1.5-flash")
|
| 17 |
|
| 18 |
MAX_SOURCES = 4
|
| 19 |
MAX_EXCERPT_CHARS = 2500
|
|
@@ -34,7 +40,7 @@ def rate_limit(key: str):
|
|
| 34 |
last = _RATE.get(key, 0)
|
| 35 |
if _now() - last < MIN_SECONDS_BETWEEN_RUNS:
|
| 36 |
wait = int(MIN_SECONDS_BETWEEN_RUNS - (_now() - last))
|
| 37 |
-
raise gr.Error(f"Even wachten aub ({wait}s).")
|
| 38 |
_RATE[key] = _now()
|
| 39 |
|
| 40 |
|
|
@@ -48,49 +54,65 @@ def clip(s: str, n: int) -> str:
|
|
| 48 |
|
| 49 |
def safe_json_extract(text: str) -> Any:
|
| 50 |
text = (text or "").strip()
|
| 51 |
-
text = re.sub(r"^```(?:json)?\s*", "", text, flags=re.I)
|
| 52 |
-
text = re.sub(r"\s*```$", "", text)
|
| 53 |
|
| 54 |
try:
|
| 55 |
return json.loads(text)
|
| 56 |
except Exception:
|
| 57 |
pass
|
| 58 |
|
|
|
|
| 59 |
start = text.find("{")
|
| 60 |
if start != -1:
|
| 61 |
depth = 0
|
| 62 |
for i in range(start, len(text)):
|
| 63 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
depth += 1
|
| 65 |
-
elif
|
| 66 |
depth -= 1
|
| 67 |
if depth == 0:
|
| 68 |
return json.loads(text[start:i + 1])
|
| 69 |
|
| 70 |
-
raise ValueError("Model output bevat geen JSON.")
|
| 71 |
|
| 72 |
|
| 73 |
# -----------------------------
|
| 74 |
-
#
|
| 75 |
# -----------------------------
|
| 76 |
-
def serpapi_search(query: str,
|
| 77 |
-
if not
|
| 78 |
-
raise gr.Error("SERPAPI_API_KEY ontbreekt.")
|
| 79 |
-
|
| 80 |
url = "https://serpapi.com/search.json"
|
| 81 |
-
params = {"engine": "google", "q": query, "api_key":
|
| 82 |
r = requests.get(url, params=params, timeout=30)
|
| 83 |
r.raise_for_status()
|
| 84 |
data = r.json()
|
| 85 |
|
| 86 |
-
|
| 87 |
-
for item in (data.get("organic_results") or [])[:
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
|
|
|
|
|
|
| 94 |
|
| 95 |
|
| 96 |
def fetch_page_text(url: str) -> str:
|
|
@@ -98,36 +120,50 @@ def fetch_page_text(url: str) -> str:
|
|
| 98 |
r = requests.get(url, headers=headers, timeout=FETCH_TIMEOUT)
|
| 99 |
r.raise_for_status()
|
| 100 |
html = r.text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
html = re.sub(r"(?is)<script.*?>.*?</script>", " ", html)
|
| 102 |
html = re.sub(r"(?is)<style.*?>.*?</style>", " ", html)
|
| 103 |
text = re.sub(r"(?is)<.*?>", " ", html)
|
| 104 |
return clean_text(text)
|
| 105 |
|
| 106 |
|
| 107 |
-
def build_sources(
|
| 108 |
sources = []
|
| 109 |
-
for r in
|
|
|
|
|
|
|
|
|
|
| 110 |
try:
|
| 111 |
-
text = fetch_page_text(
|
| 112 |
except Exception:
|
| 113 |
-
text = r.get("snippet", "")
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
|
|
|
| 120 |
return sources
|
| 121 |
|
| 122 |
|
| 123 |
# -----------------------------
|
| 124 |
-
# OpenAI
|
| 125 |
# -----------------------------
|
| 126 |
-
def
|
| 127 |
-
key = os.getenv("OPENAI_API_KEY", "")
|
| 128 |
if not key:
|
| 129 |
-
raise gr.Error("OPENAI_API_KEY ontbreekt.")
|
| 130 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
resp = client.chat.completions.create(
|
| 132 |
model=OPENAI_MODEL,
|
| 133 |
temperature=temperature,
|
|
@@ -140,40 +176,133 @@ def openai_chat(system: str, user: str, temperature: float = 0.4) -> str:
|
|
| 140 |
|
| 141 |
|
| 142 |
# -----------------------------
|
| 143 |
-
# Gemini
|
| 144 |
# -----------------------------
|
| 145 |
-
def
|
| 146 |
-
key = os.getenv("GEMINI_API_KEY", "")
|
| 147 |
if not key:
|
| 148 |
-
raise gr.Error("GEMINI_API_KEY ontbreekt.")
|
| 149 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
)
|
| 156 |
-
|
| 157 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
|
| 159 |
|
| 160 |
# -----------------------------
|
| 161 |
-
#
|
| 162 |
# -----------------------------
|
| 163 |
def step_a_outline_claims(title: str, sources: List[Dict[str, str]]) -> Dict[str, Any]:
|
| 164 |
-
system =
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 165 |
|
| 166 |
sources_block = "\n\n".join(
|
| 167 |
-
[f"[SOURCE {i+1}]\
|
| 168 |
-
for i, s in enumerate(sources)]
|
| 169 |
)
|
| 170 |
|
| 171 |
user = f"""
|
| 172 |
-
|
| 173 |
|
| 174 |
-
|
|
|
|
|
|
|
|
|
|
| 175 |
|
| 176 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 177 |
{{
|
| 178 |
"angle": "...",
|
| 179 |
"items": [
|
|
@@ -183,126 +312,278 @@ Return:
|
|
| 183 |
"location": "...",
|
| 184 |
"date": "...",
|
| 185 |
"fatalities": "...",
|
| 186 |
-
"claims": [
|
|
|
|
|
|
|
| 187 |
}}
|
| 188 |
]
|
| 189 |
}}
|
| 190 |
|
| 191 |
SOURCES:
|
| 192 |
{sources_block}
|
| 193 |
-
"""
|
| 194 |
|
| 195 |
-
out = openai_chat(system, user, 0.3)
|
| 196 |
return safe_json_extract(out)
|
| 197 |
|
| 198 |
|
| 199 |
def step_b_verify_claims(plan: Dict[str, Any], sources: List[Dict[str, str]]) -> Dict[str, Any]:
|
| 200 |
-
|
| 201 |
-
for item in plan.get("items", []):
|
| 202 |
-
for c in item.get("claims", []):
|
| 203 |
-
claims.append({"id": c["id"], "text": c["text"]})
|
| 204 |
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 212 |
|
| 213 |
-
|
|
|
|
| 214 |
{json.dumps(claims, ensure_ascii=False)}
|
| 215 |
|
| 216 |
-
|
| 217 |
{sources_block}
|
| 218 |
|
| 219 |
-
Return
|
| 220 |
-
|
| 221 |
-
"verifications":[
|
| 222 |
-
{{
|
| 223 |
-
"id":"...",
|
| 224 |
-
"verdict":"supported|not_supported|contradicted",
|
| 225 |
-
"evidence":[{{"url":"...","quote":"..."}}],
|
| 226 |
-
"fix":"..."
|
| 227 |
-
}}
|
| 228 |
-
]
|
| 229 |
-
}}
|
| 230 |
-
"""
|
| 231 |
|
| 232 |
-
|
| 233 |
-
return safe_json_extract(out)
|
| 234 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 235 |
|
| 236 |
-
|
| 237 |
-
vmap = {v["id"]: v for v in verification.get("verifications", [])}
|
| 238 |
-
verified = []
|
| 239 |
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 246 |
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
})
|
| 253 |
|
| 254 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 255 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 256 |
|
| 257 |
-
def step_d_write_script(title: str, verified: Dict[str, Any]) -> str:
|
| 258 |
-
system = "Write a documentary script using ONLY verified facts."
|
| 259 |
user = f"""
|
| 260 |
-
|
| 261 |
-
|
|
|
|
| 262 |
{json.dumps(verified, ensure_ascii=False)}
|
| 263 |
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 267 |
|
| 268 |
|
| 269 |
# -----------------------------
|
| 270 |
-
# Main
|
| 271 |
# -----------------------------
|
| 272 |
def generate(title: str, request: gr.Request):
|
| 273 |
title = (title or "").strip()
|
| 274 |
if not title:
|
| 275 |
-
raise gr.Error("
|
| 276 |
|
| 277 |
key = request.client.host if request and request.client else "global"
|
| 278 |
rate_limit(key)
|
| 279 |
|
| 280 |
-
serp_key = os.getenv("SERPAPI_API_KEY", "")
|
| 281 |
-
|
|
|
|
|
|
|
|
|
|
| 282 |
sources = build_sources(serp)
|
|
|
|
|
|
|
| 283 |
|
| 284 |
plan = step_a_outline_claims(title, sources)
|
| 285 |
verification = step_b_verify_claims(plan, sources)
|
| 286 |
-
verified =
|
| 287 |
-
|
|
|
|
| 288 |
|
| 289 |
-
|
|
|
|
|
|
|
|
|
|
| 290 |
|
| 291 |
|
| 292 |
# -----------------------------
|
| 293 |
# UI
|
| 294 |
# -----------------------------
|
| 295 |
-
with gr.Blocks(title="YouTube Scriptwriter") as demo:
|
| 296 |
-
gr.Markdown(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 297 |
|
| 298 |
-
title_in = gr.Textbox(label="Video titel")
|
| 299 |
btn = gr.Button("Generate")
|
| 300 |
|
| 301 |
-
script_out = gr.Textbox(label="
|
| 302 |
-
claims_out = gr.
|
| 303 |
-
sources_out = gr.
|
| 304 |
|
| 305 |
-
btn.click(generate, inputs=[title_in], outputs=[script_out, claims_out, sources_out])
|
| 306 |
|
| 307 |
if __name__ == "__main__":
|
| 308 |
demo.launch()
|
|
|
|
| 6 |
|
| 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 |
+
|
| 19 |
# -----------------------------
|
| 20 |
# Config
|
| 21 |
# -----------------------------
|
| 22 |
OPENAI_MODEL = os.getenv("OPENAI_MODEL", "gpt-4o-mini")
|
|
|
|
| 23 |
|
| 24 |
MAX_SOURCES = 4
|
| 25 |
MAX_EXCERPT_CHARS = 2500
|
|
|
|
| 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.")
|
| 44 |
_RATE[key] = _now()
|
| 45 |
|
| 46 |
|
|
|
|
| 54 |
|
| 55 |
def safe_json_extract(text: str) -> Any:
|
| 56 |
text = (text or "").strip()
|
| 57 |
+
text = re.sub(r"^```(?:json)?\s*", "", text, flags=re.I).strip()
|
| 58 |
+
text = re.sub(r"\s*```$", "", text).strip()
|
| 59 |
|
| 60 |
try:
|
| 61 |
return json.loads(text)
|
| 62 |
except Exception:
|
| 63 |
pass
|
| 64 |
|
| 65 |
+
# object
|
| 66 |
start = text.find("{")
|
| 67 |
if start != -1:
|
| 68 |
depth = 0
|
| 69 |
for i in range(start, len(text)):
|
| 70 |
+
ch = text[i]
|
| 71 |
+
if ch == "{":
|
| 72 |
+
depth += 1
|
| 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
|
| 82 |
+
for i in range(start, len(text)):
|
| 83 |
+
ch = text[i]
|
| 84 |
+
if ch == "[":
|
| 85 |
depth += 1
|
| 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 |
|
| 93 |
|
| 94 |
# -----------------------------
|
| 95 |
+
# SERPAPI research
|
| 96 |
# -----------------------------
|
| 97 |
+
def serpapi_search(query: str, serpapi_key: str, num_results: int = MAX_SOURCES) -> List[Dict[str, str]]:
|
| 98 |
+
if not serpapi_key:
|
| 99 |
+
raise gr.Error("SERPAPI_API_KEY ontbreekt in Secrets.")
|
|
|
|
| 100 |
url = "https://serpapi.com/search.json"
|
| 101 |
+
params = {"engine": "google", "q": query, "api_key": serpapi_key, "num": num_results}
|
| 102 |
r = requests.get(url, params=params, timeout=30)
|
| 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 |
+
{
|
| 110 |
+
"title": item.get("title", "") or "",
|
| 111 |
+
"url": item.get("link", "") or "",
|
| 112 |
+
"snippet": item.get("snippet", "") or "",
|
| 113 |
+
}
|
| 114 |
+
)
|
| 115 |
+
return out
|
| 116 |
|
| 117 |
|
| 118 |
def fetch_page_text(url: str) -> str:
|
|
|
|
| 120 |
r = requests.get(url, headers=headers, timeout=FETCH_TIMEOUT)
|
| 121 |
r.raise_for_status()
|
| 122 |
html = r.text
|
| 123 |
+
|
| 124 |
+
if trafilatura:
|
| 125 |
+
extracted = trafilatura.extract(html, include_comments=False, include_tables=False)
|
| 126 |
+
if extracted and len(extracted.strip()) > 200:
|
| 127 |
+
return clean_text(extracted)
|
| 128 |
+
|
| 129 |
html = re.sub(r"(?is)<script.*?>.*?</script>", " ", html)
|
| 130 |
html = re.sub(r"(?is)<style.*?>.*?</style>", " ", html)
|
| 131 |
text = re.sub(r"(?is)<.*?>", " ", html)
|
| 132 |
return clean_text(text)
|
| 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:
|
| 140 |
+
continue
|
| 141 |
try:
|
| 142 |
+
text = fetch_page_text(url)
|
| 143 |
except Exception:
|
| 144 |
+
text = r.get("snippet", "") or ""
|
| 145 |
+
sources.append(
|
| 146 |
+
{
|
| 147 |
+
"title": r.get("title", "") or "",
|
| 148 |
+
"url": url,
|
| 149 |
+
"excerpt": clip(text, MAX_EXCERPT_CHARS),
|
| 150 |
+
}
|
| 151 |
+
)
|
| 152 |
return sources
|
| 153 |
|
| 154 |
|
| 155 |
# -----------------------------
|
| 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)
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def openai_chat(system: str, user: str, temperature: float = 0.4) -> str:
|
| 166 |
+
client = openai_client()
|
| 167 |
resp = client.chat.completions.create(
|
| 168 |
model=OPENAI_MODEL,
|
| 169 |
temperature=temperature,
|
|
|
|
| 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,
|
| 266 |
+
contents=prompt,
|
| 267 |
+
config={"temperature": temperature, "max_output_tokens": 4096},
|
| 268 |
+
)
|
| 269 |
+
return (resp.text or "").strip()
|
| 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 |
# -----------------------------
|
| 277 |
+
# Pipeline steps
|
| 278 |
# -----------------------------
|
| 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"""
|
| 292 |
+
We are writing a video based on the title: "{title}"
|
| 293 |
|
| 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 |
{{
|
| 307 |
"angle": "...",
|
| 308 |
"items": [
|
|
|
|
| 312 |
"location": "...",
|
| 313 |
"date": "...",
|
| 314 |
"fatalities": "...",
|
| 315 |
+
"claims": [
|
| 316 |
+
{{"id":"c0_1","text":"..."}}
|
| 317 |
+
]
|
| 318 |
}}
|
| 319 |
]
|
| 320 |
}}
|
| 321 |
|
| 322 |
SOURCES:
|
| 323 |
{sources_block}
|
| 324 |
+
""".strip()
|
| 325 |
|
| 326 |
+
out = openai_chat(system, user, temperature=0.3)
|
| 327 |
return safe_json_extract(out)
|
| 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.
|
| 343 |
+
You must ONLY use the provided SOURCES excerpts.
|
| 344 |
+
Do NOT use outside knowledge.
|
| 345 |
+
|
| 346 |
+
Output MUST be valid JSON only.
|
| 347 |
+
Start your response with "{"
|
| 348 |
+
End your response with "}"
|
| 349 |
+
Do not wrap the JSON in ``` fences.
|
| 350 |
+
Do not add any text before or after the JSON.
|
| 351 |
+
|
| 352 |
+
For each claim:
|
| 353 |
+
- verdict must be exactly one of:
|
| 354 |
+
"supported"
|
| 355 |
+
"not_supported"
|
| 356 |
+
"contradicted"
|
| 357 |
+
|
| 358 |
+
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 |
+
]
|
| 377 |
+
}
|
| 378 |
+
""".strip()
|
| 379 |
|
| 380 |
+
user = f"""
|
| 381 |
+
CLAIMS:
|
| 382 |
{json.dumps(claims, ensure_ascii=False)}
|
| 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)
|
| 510 |
+
|
| 511 |
+
|
| 512 |
+
# -----------------------------
|
| 513 |
+
# Reporting helpers
|
| 514 |
+
# -----------------------------
|
| 515 |
+
def render_claims_report(verification: Dict[str, Any]) -> str:
|
| 516 |
+
lines = ["## Claims & verificatie\n"]
|
| 517 |
+
for v in verification.get("verifications", []) or []:
|
| 518 |
+
verdict = v.get("verdict", "")
|
| 519 |
+
cid = v.get("id", "")
|
| 520 |
+
fix = v.get("fix", "")
|
| 521 |
+
lines.append(f"- **{cid}** — `{verdict}` — {fix}")
|
| 522 |
+
for e in (v.get("evidence") or [])[:2]:
|
| 523 |
+
url = e.get("url", "")
|
| 524 |
+
quote = e.get("quote", "")
|
| 525 |
+
if url or quote:
|
| 526 |
+
lines.append(f" - {url} — “{quote}”")
|
| 527 |
+
return "\n".join(lines)
|
| 528 |
+
|
| 529 |
+
|
| 530 |
+
def render_sources(sources: List[Dict[str, str]]) -> str:
|
| 531 |
+
lines = ["## Sources\n"]
|
| 532 |
+
for s in sources:
|
| 533 |
+
lines.append(f"- {s.get('title','').strip()} — {s.get('url','').strip()}")
|
| 534 |
+
return "\n".join(lines)
|
| 535 |
|
| 536 |
|
| 537 |
# -----------------------------
|
| 538 |
+
# Main run
|
| 539 |
# -----------------------------
|
| 540 |
def generate(title: str, request: gr.Request):
|
| 541 |
title = (title or "").strip()
|
| 542 |
if not title:
|
| 543 |
+
raise gr.Error("Vul een video titel in.")
|
| 544 |
|
| 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 |
+
|
| 552 |
+
serp = serpapi_search(title, serp_key, num_results=MAX_SOURCES)
|
| 553 |
sources = build_sources(serp)
|
| 554 |
+
if not sources:
|
| 555 |
+
raise gr.Error("Geen bronnen gevonden. Probeer een specifiekere titel.")
|
| 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)
|
| 565 |
+
|
| 566 |
+
return final_script, claims_md, sources_md
|
| 567 |
|
| 568 |
|
| 569 |
# -----------------------------
|
| 570 |
# UI
|
| 571 |
# -----------------------------
|
| 572 |
+
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)
|
| 583 |
+
claims_out = gr.Markdown()
|
| 584 |
+
sources_out = gr.Markdown()
|
| 585 |
|
| 586 |
+
btn.click(fn=generate, inputs=[title_in], outputs=[script_out, claims_out, sources_out])
|
| 587 |
|
| 588 |
if __name__ == "__main__":
|
| 589 |
demo.launch()
|