-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
181 lines (152 loc) · 6.63 KB
/
Copy pathmain.py
File metadata and controls
181 lines (152 loc) · 6.63 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
from __future__ import annotations
import argparse
import csv
import json
from pathlib import Path
from dotenv import load_dotenv
from .analyze import Analyzer
from .chunking import (
build_analysis_chunks,
clean_transcript,
format_timestamp,
merge_short_segments,
)
from .paths import project_path, resolve_from_project
from .schemas import AnalysisBundle, TranscriptSegment
from .transcribe import ensure_ffmpeg_available, extract_audio, transcribe_audio
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description="ClipGen: find highlight timestamps from long videos.")
subparsers = parser.add_subparsers(dest="command", required=True)
analyze_parser = subparsers.add_parser("analyze", help="Transcribe a video and generate highlights.")
analyze_parser.add_argument("video_path", help="Path to the local video file.")
analyze_parser.add_argument(
"--out-dir",
default="out/latest_run",
help="Directory where result files will be written. Relative paths are resolved from the ClipGen project root.",
)
analyze_parser.add_argument("--language", default="auto", choices=["auto", "en", "ja"])
analyze_parser.add_argument("--highlight-count", type=int, default=15)
analyze_parser.add_argument("--min-clip-seconds", type=int, default=20)
analyze_parser.add_argument("--max-clip-seconds", type=int, default=90)
analyze_parser.add_argument("--model")
analyze_parser.add_argument("--resume", action="store_true")
analyze_parser.add_argument("--whisper-model", default="small")
return parser
def main() -> int:
load_dotenv(project_path(".env"), override=True)
parser = build_parser()
args = parser.parse_args()
if args.command == "analyze":
run_analyze(args)
return 0
def run_analyze(args: argparse.Namespace) -> None:
video_path = Path(args.video_path).expanduser().resolve()
if not video_path.exists():
raise FileNotFoundError(f"Video file does not exist: {video_path}")
out_dir = resolve_from_project(args.out_dir)
out_dir.mkdir(parents=True, exist_ok=True)
transcript_path = out_dir / "transcript.jsonl"
audio_path = out_dir / "audio.wav"
if args.resume and transcript_path.exists():
transcript = load_transcript_jsonl(transcript_path)
else:
ensure_ffmpeg_available()
extract_audio(video_path, audio_path)
transcript = transcribe_audio(
audio_path,
language=args.language,
model_size=args.whisper_model,
)
write_transcript_jsonl(transcript_path, transcript)
cleaned = clean_transcript(transcript)
merged = merge_short_segments(cleaned)
chunks = build_analysis_chunks(merged)
write_json(out_dir / "chunks.json", [chunk.to_dict() for chunk in chunks])
if not chunks:
bundle = AnalysisBundle(
chapters=[],
highlights=[],
overall_summary="No usable transcript content was produced for this video.",
)
else:
analyzer = Analyzer(model=args.model)
bundle = analyzer.analyze(
chunks,
highlight_count=args.highlight_count,
min_clip_seconds=args.min_clip_seconds,
max_clip_seconds=args.max_clip_seconds,
)
write_outputs(out_dir, bundle)
def load_transcript_jsonl(path: Path) -> list[TranscriptSegment]:
transcript: list[TranscriptSegment] = []
for line in path.read_text(encoding="utf-8").splitlines():
if not line.strip():
continue
item = json.loads(line)
transcript.append(
TranscriptSegment(
start=float(item["start"]),
end=float(item["end"]),
text=item["text"],
)
)
return transcript
def write_transcript_jsonl(path: Path, transcript: list[TranscriptSegment]) -> None:
with path.open("w", encoding="utf-8", newline="") as handle:
for segment in transcript:
handle.write(json.dumps(segment.to_dict(), ensure_ascii=False))
handle.write("\n")
def write_outputs(out_dir: Path, bundle: AnalysisBundle) -> None:
write_json(out_dir / "chapters.json", [chapter.to_dict() for chapter in bundle.chapters])
write_json(out_dir / "highlights.json", [highlight.to_dict() for highlight in bundle.highlights])
write_json(out_dir / "analysis.json", bundle.to_dict())
write_highlights_csv(out_dir / "highlights.csv", bundle)
write_highlights_markdown(out_dir / "highlights.md", bundle)
(out_dir / "summary.md").write_text(bundle.overall_summary + "\n", encoding="utf-8")
def write_json(path: Path, payload: object) -> None:
path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
def write_highlights_csv(path: Path, bundle: AnalysisBundle) -> None:
fieldnames = ["id", "start", "end", "duration", "score", "title", "reason", "excerpt"]
with path.open("w", encoding="utf-8-sig", newline="") as handle:
writer = csv.DictWriter(handle, fieldnames=fieldnames)
writer.writeheader()
for item in bundle.highlights:
writer.writerow(
{
"id": item.id,
"start": format_timestamp(item.start),
"end": format_timestamp(item.end),
"duration": round(item.duration, 2),
"score": item.score,
"title": item.title,
"reason": item.reason,
"excerpt": item.excerpt,
}
)
def write_highlights_markdown(path: Path, bundle: AnalysisBundle) -> None:
lines = ["# Highlight Candidates", ""]
if not bundle.highlights:
lines.extend(["No highlight candidates were found.", ""])
else:
for item in bundle.highlights:
lines.append(f"## {item.id} | {item.title}")
lines.append(
f"- Range: {format_timestamp(item.start)} - {format_timestamp(item.end)} "
f"({round(item.duration, 1)}s)"
)
lines.append(f"- Score: {item.score}")
lines.append(f"- Reason: {item.reason}")
lines.append(f"- Excerpt: {item.excerpt}")
lines.append("")
if bundle.chapters:
lines.append("# Chapters")
lines.append("")
for chapter in bundle.chapters:
lines.append(
f"- [{format_timestamp(chapter.start)} - {format_timestamp(chapter.end)}] "
f"{chapter.title}: {chapter.summary}"
)
lines.append("")
path.write_text("\n".join(lines), encoding="utf-8")
if __name__ == "__main__":
raise SystemExit(main())