-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
430 lines (356 loc) · 17 KB
/
Copy pathcli.py
File metadata and controls
430 lines (356 loc) · 17 KB
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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
#!/usr/bin/env python3
"""
ScriptForge - AI-Powered Content Script Generator CLI
A lightweight, zero-dependency CLI tool for generating professional
short video scripts, content outlines, and storyboards using AI.
Supports: OpenAI, Anthropic, Ollama, and custom LLM endpoints.
"""
import argparse
import json
import os
import sys
import textwrap
from datetime import datetime
from pathlib import Path
# Add src to path for development
sys.path.insert(0, str(Path(__file__).parent))
from scriptforge import __version__
from scriptforge.generator import ScriptGenerator
from scriptforge.config import Config, load_config
from scriptforge.templates.manager import TemplateManager
from scriptforge.exporters.factory import ExporterFactory
from scriptforge.scoring import ScriptScorer
from scriptforge.trending import TrendingTopics
def create_banner():
"""Generate ASCII art banner."""
return textwrap.dedent(r"""
╔══════════════════════════════════════════════════╗
║ ║
║ ██████╗ ██████╗ █████╗ ███╗ ██╗██╗ ██╗ ║
║ ██╔════╝ ██╔══██╗██╔══██╗████╗ ██║██║ ██╔╝ ║
║ ██║ ███╗██████╔╝███████║██╔██╗ ██║█████╔╝ ║
║ ██║ ██║██╔══██╗██╔══██║██║╚██╗██║██╔═██╗ ║
║ ╚██████╔╝██║ ██║██║ ██║██║ ╚████║██║ ██╗ ║
║ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═══╝╚═╝ ╚═╝ ║
║ ║
║ AI-Powered Script Generator v{} ║
║ ║
╚══════════════════════════════════════════════════╝
""".format(__version__))
def cmd_generate(args):
"""Generate a script based on topic and platform."""
config = load_config(args.config)
generator = ScriptGenerator(config)
print(f"\n🎬 Generating script for: {args.topic}")
print(f"📱 Platform: {args.platform}")
print(f"⏱️ Duration: {args.duration}s")
print(f"🎨 Style: {args.style}")
print()
try:
result = generator.generate(
topic=args.topic,
platform=args.platform,
duration=args.duration,
style=args.style,
language=args.language,
custom_prompt=args.custom_prompt,
)
# Score the script
scorer = ScriptScorer()
scores = scorer.score(result)
# Display result
_display_script(result, scores)
# Export
if args.output:
exporter = ExporterFactory.get_exporter(args.format)
output_path = exporter.export(result, args.output)
print(f"\n✅ Script exported to: {output_path}")
# Save to project
if args.save:
project_dir = Path(args.save)
project_dir.mkdir(parents=True, exist_ok=True)
exporter = ExporterFactory.get_exporter("json")
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
fname = f"{args.platform}_{ts}.json"
exporter.export(result, str(project_dir / fname))
print(f"💾 Saved to project: {project_dir / fname}")
except Exception as e:
print(f"\n❌ Error: {e}")
sys.exit(1)
def cmd_batch(args):
"""Batch generate scripts from a topics file."""
config = load_config(args.config)
generator = ScriptGenerator(config)
topics_file = Path(args.topics_file)
if not topics_file.exists():
print(f"❌ Topics file not found: {topics_file}")
sys.exit(1)
topics = []
with open(topics_file, "r", encoding="utf-8") as f:
for line in f:
line = line.strip()
if line and not line.startswith("#"):
topics.append(line)
print(f"\n📦 Batch mode: {len(topics)} topics loaded")
print(f"📱 Platform: {args.platform}")
print(f"📁 Output: {args.output_dir}")
print()
output_dir = Path(args.output_dir)
output_dir.mkdir(parents=True, exist_ok=True)
success = 0
for i, topic in enumerate(topics, 1):
print(f"[{i}/{len(topics)}] 🎬 Generating: {topic}")
try:
result = generator.generate(
topic=topic,
platform=args.platform,
duration=args.duration,
style=args.style,
language=args.language,
)
exporter = ExporterFactory.get_exporter(args.format)
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
safe_name = "".join(c if c.isalnum() or c in "_-" else "_" for c in topic[:30])
fname = f"{safe_name}_{ts}.{args.format}"
exporter.export(result, str(output_dir / fname))
print(f" ✅ Saved: {fname}")
success += 1
except Exception as e:
print(f" ❌ Failed: {e}")
print(f"\n📊 Batch complete: {success}/{len(topics)} succeeded")
def cmd_templates(args):
"""List or show available templates."""
tm = TemplateManager()
if args.show:
template = tm.get_template(args.show)
if template:
_display_template_detail(template)
else:
print(f"❌ Template not found: {args.show}")
sys.exit(1)
else:
templates = tm.list_templates()
print("\n📋 Available Templates\n")
print(f" {'Name':<20} {'Platform':<15} {'Duration':<12} {'Description'}")
print(f" {'─'*20} {'─'*15} {'─'*12} {'─'*40}")
for t in templates:
print(f" {t['name']:<20} {t['platform']:<15} {t['duration']:<12} {t['description']}")
def cmd_score(args):
"""Score an existing script file."""
scorer = ScriptScorer()
script_file = Path(args.script_file)
if not script_file.exists():
print(f"❌ Script file not found: {script_file}")
sys.exit(1)
with open(script_file, "r", encoding="utf-8") as f:
if script_file.suffix == ".json":
data = json.load(f)
else:
data = {"title": script_file.stem, "sections": [], "full_text": f.read()}
scores = scorer.score(data)
_display_scores(scores)
def cmd_trending(args):
"""Show trending topic suggestions."""
trending = TrendingTopics()
topics = trending.get_topics(category=args.category, count=args.count)
print(f"\n🔥 Trending Topics ({args.category})\n")
for i, topic in enumerate(topics, 1):
print(f" {i}. {topic['title']}")
print(f" {topic['description']}")
print(f" Tags: {', '.join(topic.get('tags', []))}")
print()
def cmd_export(args):
"""Convert a script between formats."""
script_file = Path(args.script_file)
if not script_file.exists():
print(f"❌ Script file not found: {script_file}")
sys.exit(1)
with open(script_file, "r", encoding="utf-8") as f:
if script_file.suffix == ".json":
data = json.load(f)
else:
data = {"title": script_file.stem, "sections": [], "full_text": f.read()}
exporter = ExporterFactory.get_exporter(args.to_format)
output = args.output or str(script_file.with_suffix(f".{args.to_format}"))
exporter.export(data, output)
print(f"✅ Exported to: {output}")
def cmd_init(args):
"""Initialize a new ScriptForge project."""
project_dir = Path(args.directory)
project_dir.mkdir(parents=True, exist_ok=True)
# Create config
config = Config.default()
config_path = project_dir / "scriptforge.yaml"
with open(config_path, "w", encoding="utf-8") as f:
f.write(config.to_yaml())
# Create topics file
topics_path = project_dir / "topics.txt"
with open(topics_path, "w", encoding="utf-8") as f:
f.write("# Add one topic per line\n")
f.write("# Lines starting with # are comments\n")
f.write("# Example:\n")
f.write("# How to learn Python in 7 days\n")
f.write("# Best productivity tips for 2025\n")
# Create output dir
(project_dir / "output").mkdir(exist_ok=True)
print(f"\n✅ ScriptForge project initialized!")
print(f" 📁 Directory: {project_dir}")
print(f" ⚙️ Config: {config_path}")
print(f" 📝 Topics: {topics_path}")
print(f" 📤 Output: {project_dir / 'output'}")
print(f"\n Next steps:")
print(f" 1. Edit {config_path} to add your API key")
print(f" 2. Add topics to {topics_path}")
print(f" 3. Run: scriptforge batch --topics-file {topics_path}")
def _display_script(result, scores):
"""Display generated script with formatting."""
print("=" * 60)
print(f" 📌 {result.get('title', 'Untitled')}")
print("=" * 60)
if result.get("hook"):
print(f"\n🎣 Hook: {result['hook']}")
if result.get("platform"):
print(f"📱 Platform: {result['platform']}")
if result.get("duration"):
print(f"⏱️ Duration: {result['duration']}s")
if result.get("style"):
print(f"🎨 Style: {result['style']}")
if result.get("target_audience"):
print(f"👥 Target: {result['target_audience']}")
print(f"\n{'─' * 60}")
sections = result.get("sections", [])
for i, section in enumerate(sections, 1):
print(f"\n [{section.get('type', 'SCENE')}] {section.get('title', f'Section {i}')}")
if section.get("duration"):
print(f" ⏱️ {section['duration']}s")
print(f" {'─' * 40}")
content = section.get("content", "")
for line in content.split("\n"):
print(f" {line}")
if section.get("visual_hint"):
print(f" 🎥 Visual: {section['visual_hint']}")
if section.get("text_overlay"):
print(f" 📝 Overlay: {section['text_overlay']}")
if result.get("cta"):
print(f"\n📢 CTA: {result['cta']}")
if result.get("hashtags"):
print(f"🏷️ Tags: {' '.join(result['hashtags'])}")
if result.get("srt_subtitles"):
print(f"\n{'─' * 60}")
print(" 📜 SRT Subtitle Preview (first 3):")
for entry in result["srt_subtitles"][:3]:
print(f" [{entry['start']} --> {entry['end']}] {entry['text']}")
if len(result["srt_subtitles"]) > 3:
print(f" ... and {len(result['srt_subtitles']) - 3} more")
# Display scores
print(f"\n{'─' * 60}")
_display_scores(scores)
def _display_scores(scores):
"""Display script quality scores."""
print("\n📊 Script Quality Scores")
print(f" {'Metric':<25} {'Score':<8} {'Grade'}")
print(f" {'─'*25} {'─'*8} {'─'*6}")
for metric, value in scores.items():
score = value.get("score", 0)
grade = value.get("grade", "N/A")
bar_len = int(score / 10)
bar = "█" * bar_len + "░" * (10 - bar_len)
print(f" {metric:<25} {bar} {score}% {grade}")
overall = scores.get("overall", {}).get("score", 0)
print(f"\n 🏆 Overall: {overall}/100")
def _display_template_detail(template):
"""Display detailed template information."""
print(f"\n📋 Template: {template['name']}")
print(f"{'=' * 50}")
print(f" Platform: {template['platform']}")
print(f" Duration: {template['duration']}")
print(f" Description: {template['description']}")
print(f"\n 📐 Structure:")
for section in template.get("structure", []):
print(f" • {section['type']}: {section['name']} ({section.get('duration', 'flexible')})")
print(f"\n 💡 Tips: {template.get('tips', 'N/A')}")
def main():
parser = argparse.ArgumentParser(
prog="scriptforge",
description="🎬 ScriptForge - AI-Powered Content Script Generator CLI",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=textwrap.dedent("""
Examples:
scriptforge generate "5 tips for better sleep" --platform tiktok
scriptforge generate "Python tutorial" --platform youtube --duration 60
scriptforge batch --topics-file topics.txt --output-dir ./scripts
scriptforge templates --show tiktok-15s
scriptforge trending --category tech --count 5
scriptforge init --directory my-project
"""),
)
parser.add_argument("-v", "--version", action="version", version=f"ScriptForge v{__version__}")
subparsers = parser.add_subparsers(dest="command", help="Available commands")
# generate command
gen_parser = subparsers.add_parser("generate", help="Generate a script", aliases=["gen"])
gen_parser.add_argument("topic", help="Topic or theme for the script")
gen_parser.add_argument("-p", "--platform", default="tiktok",
choices=["tiktok", "youtube", "bilibili", "xiaohongshu", "instagram", "generic"],
help="Target platform (default: tiktok)")
gen_parser.add_argument("-d", "--duration", type=int, default=15,
help="Target duration in seconds (default: 15)")
gen_parser.add_argument("-s", "--style", default="engaging",
choices=["engaging", "educational", "entertaining", "inspirational", "storytelling", "promotional"],
help="Script style (default: engaging)")
gen_parser.add_argument("-l", "--language", default="zh",
choices=["zh", "en", "ja", "ko", "es"],
help="Output language (default: zh)")
gen_parser.add_argument("-o", "--output", help="Output file path")
gen_parser.add_argument("-f", "--format", default="markdown",
choices=["markdown", "json", "srt", "txt"],
help="Output format (default: markdown)")
gen_parser.add_argument("--save", help="Save to project directory")
gen_parser.add_argument("--custom-prompt", help="Custom prompt addition")
gen_parser.add_argument("-c", "--config", help="Config file path")
gen_parser.set_defaults(func=cmd_generate)
# batch command
batch_parser = subparsers.add_parser("batch", help="Batch generate scripts")
batch_parser.add_argument("topics_file", help="File with one topic per line")
batch_parser.add_argument("-p", "--platform", default="tiktok", help="Target platform")
batch_parser.add_argument("-d", "--duration", type=int, default=15, help="Duration in seconds")
batch_parser.add_argument("-s", "--style", default="engaging", help="Script style")
batch_parser.add_argument("-l", "--language", default="zh", help="Output language")
batch_parser.add_argument("-o", "--output-dir", default="./output", help="Output directory")
batch_parser.add_argument("-f", "--format", default="markdown", help="Output format")
batch_parser.add_argument("-c", "--config", help="Config file path")
batch_parser.set_defaults(func=cmd_batch)
# templates command
tmpl_parser = subparsers.add_parser("templates", help="List or show templates", aliases=["tmpl"])
tmpl_parser.add_argument("--show", help="Show template detail by name")
tmpl_parser.set_defaults(func=cmd_templates)
# score command
score_parser = subparsers.add_parser("score", help="Score an existing script")
score_parser.add_argument("script_file", help="Path to script file (JSON or text)")
score_parser.set_defaults(func=cmd_score)
# trending command
trend_parser = subparsers.add_parser("trending", help="Show trending topics")
trend_parser.add_argument("--category", default="general",
choices=["general", "tech", "lifestyle", "education", "business", "entertainment"],
help="Topic category")
trend_parser.add_argument("--count", type=int, default=5, help="Number of topics")
trend_parser.set_defaults(func=cmd_trending)
# export command
export_parser = subparsers.add_parser("export", help="Convert script format")
export_parser.add_argument("script_file", help="Source script file")
export_parser.add_argument("--to-format", "-t", default="markdown",
choices=["markdown", "json", "srt", "txt"],
help="Target format")
export_parser.add_argument("--output", "-o", help="Output file path")
export_parser.set_defaults(func=cmd_export)
# init command
init_parser = subparsers.add_parser("init", help="Initialize a new project")
init_parser.add_argument("directory", nargs="?", default=".", help="Project directory")
init_parser.set_defaults(func=cmd_init)
args = parser.parse_args()
if not args.command:
print(create_banner())
parser.print_help()
return
args.func(args)
if __name__ == "__main__":
main()