File size: 6,414 Bytes
44d3313
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
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."

        style_text = load_style_from_docx(style_file.name) if style_file else "YouTube stijl met drama en spanning."

        prompt = f"""
You are a professional YouTube video text writer.
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.
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, using rhetorical questions.
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.
- Keep dramatic tone and rhetorical questions if they don't create fake facts.
- Ensure the final script is at least 2900 and maximum 3200 words and keeps natural storytelling flow.
- 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()