Becio's picture
Update app.py
58f62e8 verified
Raw History Blame Contribute Delete
7.35 kB
import gradio as gr
from openai import OpenAI
from docx import Document
import os
from serpapi import GoogleSearch
# πŸ” Context ophalen via SerpAPI
serpapi_key = "59ad264e7fef5ed3f7a534de3bca426000ee83730987ac2cf71e20eec95e85aa"
def fetch_recent_info(topic):
params = {
"engine": "google",
"q": f"{topic} news 2025",
"api_key": serpapi_key,
"num": 10,
}
search = GoogleSearch(params)
results = search.get_dict()
snippets = [result.get("snippet", "") for result in results.get("organic_results", [])]
return "\n".join(snippets)
# πŸ“„ Laad stijl uit .docx
def load_style_from_docx(filepath):
try:
doc = Document(filepath)
return "\n".join([para.text for para in doc.paragraphs])
except Exception:
return ""
# 🧠 Script generatie met context en stijl
def generate_script(api_key, title, style_file):
if not api_key or not title:
return "❌ Vul alle verplichte velden in."
try:
client = OpenAI(api_key=api_key)
context = fetch_recent_info(title)
if not context or len(context.strip()) < 100:
return "⚠️ Geen context gevonden. Geef een concreter onderwerp of controleer SerpAPI key."
# Space-niche default: mysterieus maar feitelijk, met nadruk op bewijs uit de context
style_text = load_style_from_docx(style_file.name) if style_file else "YouTube ruimte/astronomie-stijl: mysterieus maar feitelijk, met duidelijke uitleg van wetenschap, rehooks, en nadruk op bewijs uit de context."
prompt = f"""
You are a professional YouTube video text writer for the space/astronomy niche.
Below is an example YouTube video text that demonstrates the style, tone, pacing, and voice to follow:
--- STYLE INSPIRATION START ---
{style_text}
--- STYLE INSPIRATION END ---
Using this style as inspiration, write a full, complete, well-developed Youtube video text that contains between 2900 and 3200 words.
Expand on every key point, include vivid examples, and avoid summarizing too early.
Divide the text (except intro and ending) into 5-8 chapters.
The last chapter should not have a title like 'Outro' or 'Conclusion'β€”just close the script naturally.
Do not use brackets like [] in the chapter titles.
End the first chapter with a rhetorical question to intrigue the audience.
Keep the introduction (first chapter) under 350 words.
Do not show 'Chapter one' or something, show only the chapter title.
You are not allowed to generate any content that is not explicitly present in the provided context.
Do not infer, assume, or imagine any details.
You must reference the facts from the context directly, and nothing beyond that.
Favor a 'Mystery Setup' hook, add rehooks with surprising but factual turns, build to a clear climax revealing the key discovery, and finish with a reflective resolution on implications for space exploration.
Align the content precisely with the title and avoid clickbait exaggerations.
Insert a short call-to-action encouraging viewers to subscribe around 30% of the way through the script, placed naturally at the end of a chapter.
Do not include notes or comments for the editor. Do not reply with anything besides the text.
Write a script for the following title:
\"{title}\"
Use the following current information for context:
--- START OF FACTUAL CONTEXT ---
{context}
--- END OF FACTUAL CONTEXT ---
Maintain the same storytelling quality, sentence rhythm, and tone as the style sample.
Make the tone of the YouTube video dramatic and mysterious while remaining scientifically grounded; use rhetorical questions without suggesting unsupported claims.
Ensure the final script is between 2900 and 3200 words. Less than 2900 is NOT acceptable.
"""
response = client.chat.completions.create(
model="gpt-4.1",
messages=[
{"role": "system", "content": "You're a professional scriptwriter."},
{"role": "user", "content": prompt}
]
)
raw_script = response.choices[0].message.content
max_retries = 3
for attempt in range(max_retries):
word_count = len(raw_script.split())
if word_count >= 2900:
break
extra_prompt = f"""
The following script is currently {word_count} words long. Please expand it naturally to reach at least 2900 words.
Focus on adding details to chapters; keep the outro under 150 words.
Do NOT include editing notes, camera directions, or comments.
Script so far:
{raw_script}
"""
extra_response = client.chat.completions.create(
model="gpt-4.1",
messages=[
{"role": "system", "content": "You're a professional scriptwriter."},
{"role": "user", "content": extra_prompt}
]
)
raw_script = extra_response.choices[0].message.content
# Fact-check stap
final_script = factual_review(raw_script, context, client)
return final_script
except Exception as e:
return f"❌ Er ging iets fout: {str(e)}"
# πŸ”Ž Fact-check met soepele aanpak
def factual_review(script, context, client):
prompt = f"""
Below is a script and the factual context it was based on.
--- CONTEXT ---
{context}
--- SCRIPT ---
{script}
Please review the script for factual consistency:
- Minor elaborations are allowed if logically connected to the context.
- Remove clearly speculative or unverifiable claims, sensational framings, and any mismatch between title and content.
- Keep dramatic, mysterious tone only when supported by evidence from the context; prioritize scientific clarity and plain-language explanations of complex ideas.
- Ensure the final script is at least 2900 and maximum 3200 words and keeps natural storytelling flow with a clear resolution (no abrupt ending).
- Important: Do not add video editing instructions, title cards, camera directions, or editorial comments. Only return the final spoken script text.
- If the script is less than 2900 words, extend most chapters to reach 2900 words and do the factual review again.
Only rewrite or reword parts that really need it.
"""
response = client.chat.completions.create(
model="gpt-4.1",
messages=[
{"role": "system", "content": "You are a careful but strict fact-checker and editor."},
{"role": "user", "content": prompt}
]
)
return response.choices[0].message.content
# πŸŽ›οΈ Gradio interface
with gr.Blocks() as demo:
gr.Markdown("# 🎨 Script Writer 2.0 – Met woordtelling en Fact-Check")
with gr.Row():
api_key = gr.Textbox(label="πŸ”‘ OpenAI API Key", type="password")
title = gr.Textbox(label="🎯 Video Title (script topic)")
style_file = gr.File(label="πŸ“„ Upload script for style inspiration (.docx)", file_types=[".docx"], type="filepath")
output = gr.Textbox(label="βœ… Final Script (Fact-Checked)", lines=30, interactive=False)
with gr.Row():
clear_btn = gr.Button("πŸͺœ Clear")
submit_btn = gr.Button("πŸš€ Genereer")
submit_btn.click(fn=generate_script, inputs=[api_key, title, style_file], outputs=output)
clear_btn.click(fn=lambda: "", inputs=None, outputs=output)
# Run app
if __name__ == "__main__":
demo.launch()