Becio commited on
Commit
dde5262
Β·
verified Β·
1 Parent(s): d896359

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +77 -147
app.py CHANGED
@@ -3,159 +3,89 @@ from openai import OpenAI
3
  from docx import Document
4
  import os
5
  from serpapi import GoogleSearch
 
 
6
 
7
  # πŸ” Context ophalen via SerpAPI
8
  serpapi_key = "59ad264e7fef5ed3f7a534de3bca426000ee83730987ac2cf71e20eec95e85aa"
9
 
 
10
  def fetch_recent_info(topic):
11
- params = {
12
- "engine": "google",
13
- "q": f"{topic} news 2025",
14
- "api_key": serpapi_key,
15
- "num": 10,
16
- }
17
- search = GoogleSearch(params)
18
- results = search.get_dict()
19
- snippets = [result.get("snippet", "") for result in results.get("organic_results", [])]
20
- return "\n".join(snippets)
 
21
 
22
  # πŸ“„ Laad stijl uit .docx
23
  def load_style_from_docx(filepath):
24
- try:
25
- doc = Document(filepath)
26
- return "\n".join([para.text for para in doc.paragraphs])
27
- except Exception:
28
- return ""
29
-
30
- # 🧠 Script generatie met context en stijl
31
- def generate_script(api_key, title, style_file):
32
- if not api_key or not title:
33
- return "❌ Vul alle verplichte velden in."
34
-
35
- try:
36
- client = OpenAI(api_key=api_key)
37
- context = fetch_recent_info(title)
38
-
39
- if not context or len(context.strip()) < 100:
40
- return "⚠️ Geen context gevonden. Geef een concreter onderwerp of controleer SerpAPI key."
41
-
42
- # Space-niche default: mysterieus maar feitelijk, met nadruk op bewijs uit de context
43
- 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."
44
-
45
- prompt = f"""
46
- You are a professional YouTube video text writer for the space/astronomy niche.
47
- Below is an example YouTube video text that demonstrates the style, tone, pacing, and voice to follow:
48
- --- STYLE INSPIRATION START ---
49
- {style_text}
50
- --- STYLE INSPIRATION END ---
51
- Using this style as inspiration, write a full, complete, well-developed Youtube video text that contains between 2900 and 3200 words.
52
- Expand on every key point, include vivid examples, and avoid summarizing too early.
53
- Divide the text (except intro and ending) into 5-8 chapters.
54
- The last chapter should not have a title like 'Outro' or 'Conclusion'β€”just close the script naturally.
55
- Do not use brackets like [] in the chapter titles.
56
- End the first chapter with a rhetorical question to intrigue the audience.
57
- Keep the introduction (first chapter) under 350 words.
58
- Do not show 'Chapter one' or something, show only the chapter title.
59
- You are not allowed to generate any content that is not explicitly present in the provided context.
60
- Do not infer, assume, or imagine any details.
61
- You must reference the facts from the context directly, and nothing beyond that.
62
- 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.
63
- Align the content precisely with the title and avoid clickbait exaggerations.
64
- Do not include notes or comments for the editor. Do not reply with anything besides the text.
65
- Write a script for the following title:
66
- \"{title}\"
67
- Use the following current information for context:
68
- --- START OF FACTUAL CONTEXT ---
69
- {context}
70
- --- END OF FACTUAL CONTEXT ---
71
- Maintain the same storytelling quality, sentence rhythm, and tone as the style sample.
72
- Make the tone of the YouTube video dramatic and mysterious while remaining scientifically grounded; use rhetorical questions without suggesting unsupported claims.
73
- Ensure the final script is between 2900 and 3200 words. Less than 2900 is NOT acceptable.
74
- """
75
-
76
- response = client.chat.completions.create(
77
- model="gpt-4.1",
78
- messages=[
79
- {"role": "system", "content": "You're a professional scriptwriter."},
80
- {"role": "user", "content": prompt}
81
- ]
82
- )
83
-
84
- raw_script = response.choices[0].message.content
85
-
86
- max_retries = 3
87
- for attempt in range(max_retries):
88
- word_count = len(raw_script.split())
89
- if word_count >= 2900:
90
- break
91
-
92
- extra_prompt = f"""
93
- The following script is currently {word_count} words long. Please expand it naturally to reach at least 2900 words.
94
- Focus on adding details to chapters; keep the outro under 150 words.
95
- Do NOT include editing notes, camera directions, or comments.
96
- Script so far:
97
- {raw_script}
98
- """
99
- extra_response = client.chat.completions.create(
100
- model="gpt-4.1",
101
- messages=[
102
- {"role": "system", "content": "You're a professional scriptwriter."},
103
- {"role": "user", "content": extra_prompt}
104
- ]
105
- )
106
- raw_script = extra_response.choices[0].message.content
107
-
108
- # Fact-check stap
109
- final_script = factual_review(raw_script, context, client)
110
- return final_script
111
-
112
- except Exception as e:
113
- return f"❌ Er ging iets fout: {str(e)}"
114
-
115
- # πŸ”Ž Fact-check met soepele aanpak
116
- def factual_review(script, context, client):
117
- prompt = f"""
118
- Below is a script and the factual context it was based on.
119
- --- CONTEXT ---
120
- {context}
121
- --- SCRIPT ---
122
- {script}
123
- Please review the script for factual consistency:
124
- - Minor elaborations are allowed if logically connected to the context.
125
- - Remove clearly speculative or unverifiable claims, sensational framings, and any mismatch between title and content.
126
- - Keep dramatic, mysterious tone only when supported by evidence from the context; prioritize scientific clarity and plain-language explanations of complex ideas.
127
- - Ensure the final script is at least 2900 and maximum 3200 words and keeps natural storytelling flow with a clear resolution (no abrupt ending).
128
- - Important: Do not add video editing instructions, title cards, camera directions, or editorial comments. Only return the final spoken script text.
129
- - If the script is less than 2900 words, extend most chapters to reach 2900 words and do the factual review again.
130
- Only rewrite or reword parts that really need it.
131
- """
132
- response = client.chat.completions.create(
133
- model="gpt-4.1",
134
- messages=[
135
- {"role": "system", "content": "You are a careful but strict fact-checker and editor."},
136
- {"role": "user", "content": prompt}
137
- ]
138
- )
139
- return response.choices[0].message.content
140
-
141
- # πŸŽ›οΈ Gradio interface
142
- with gr.Blocks() as demo:
143
- gr.Markdown("# 🎨 Script Writer 2.0 – Met woordtelling en Fact-Check")
144
-
145
- with gr.Row():
146
- api_key = gr.Textbox(label="πŸ”‘ OpenAI API Key", type="password")
147
- title = gr.Textbox(label="🎯 Video Title (script topic)")
148
-
149
- style_file = gr.File(label="πŸ“„ Upload script for style inspiration (.docx)", file_types=[".docx"], type="filepath")
150
- output = gr.Textbox(label="βœ… Final Script (Fact-Checked)", lines=30, interactive=False)
151
-
152
- with gr.Row():
153
- clear_btn = gr.Button("πŸͺœ Clear")
154
- submit_btn = gr.Button("πŸš€ Genereer")
155
-
156
- submit_btn.click(fn=generate_script, inputs=[api_key, title, style_file], outputs=output)
157
- clear_btn.click(fn=lambda: "", inputs=None, outputs=output)
158
 
159
- # Run app
160
- if __name__ == "__main__":
161
- demo.launch()
 
3
  from docx import Document
4
  import os
5
  from serpapi import GoogleSearch
6
+ import re
7
+
8
 
9
  # πŸ” Context ophalen via SerpAPI
10
  serpapi_key = "59ad264e7fef5ed3f7a534de3bca426000ee83730987ac2cf71e20eec95e85aa"
11
 
12
+
13
  def fetch_recent_info(topic):
14
+ params = {
15
+ "engine": "google",
16
+ "q": f"{topic} news 2025",
17
+ "api_key": serpapi_key,
18
+ "num": 10,
19
+ }
20
+ search = GoogleSearch(params)
21
+ results = search.get_dict()
22
+ snippets = [result.get("snippet", "") for result in results.get("organic_results", [])]
23
+ return "\n".join(snippets)
24
+
25
 
26
  # πŸ“„ Laad stijl uit .docx
27
  def load_style_from_docx(filepath):
28
+ try:
29
+ doc = Document(filepath)
30
+ return "\n".join([para.text for para in doc.paragraphs])
31
+ except Exception:
32
+ return ""
33
+
34
+
35
+ # 🧩 β€”β€”β€” CTA helpers β€”β€”β€”
36
+
37
+
38
+ def _is_title_block(block: str) -> bool:
39
+ """Heuristic: treat a block as a chapter title if it's a single shortish line
40
+ that does NOT end with terminal punctuation and isn't empty."""
41
+ line = block.strip()
42
+ if not line:
43
+ return False
44
+ # single line
45
+ if "\n" in line:
46
+ return False
47
+ # avoid typical sentence endings
48
+ if line.endswith((".", "!", "?", ":")):
49
+ return False
50
+ # avoid markdown-style bullets
51
+ if line.lstrip().startswith(("- ", "* ", "β€’ ", "β€” ")):
52
+ return False
53
+ # keep titles reasonably short
54
+ return len(line) <= 120
55
+
56
+
57
+ def _group_chapters(text: str):
58
+ """Group text into chapters as (title, body) using a simple title heuristic.
59
+ Returns a list of tuples. If no titles are found, returns a single chapter."""
60
+ blocks = re.split(r"\n{2,}", text.strip())
61
+ chapters = []
62
+ i = 0
63
+ while i < len(blocks):
64
+ if _is_title_block(blocks[i]):
65
+ title = blocks[i].strip()
66
+ body_parts = []
67
+ i += 1
68
+ while i < len(blocks) and not _is_title_block(blocks[i]):
69
+ body_parts.append(blocks[i])
70
+ i += 1
71
+ chapters.append((title, "\n\n".join(bp.strip() for bp in body_parts).strip()))
72
+ else:
73
+ # No clear title β€” merge consecutive non-title blocks as a single "chapter"
74
+ body_parts = [blocks[i]]
75
+ i += 1
76
+ while i < len(blocks) and not _is_title_block(blocks[i]):
77
+ body_parts.append(blocks[i])
78
+ i += 1
79
+ chapters.append(("", "\n\n".join(bp.strip() for bp in body_parts).strip()))
80
+ return chapters
81
+
82
+
83
+ def _assemble_chapters(chapters):
84
+ parts = []
85
+ for title, body in chapters:
86
+ if title:
87
+ parts.append(title.strip())
88
+ if body:
89
+ parts.append(body.strip())
90
+ return "\n\n".join(p for p in parts if p)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91