yt-clipper 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- yt_clipper-0.1.0/PKG-INFO +115 -0
- yt_clipper-0.1.0/README.md +97 -0
- yt_clipper-0.1.0/pyproject.toml +34 -0
- yt_clipper-0.1.0/setup.cfg +4 -0
- yt_clipper-0.1.0/src/yt_clipper/__init__.py +6 -0
- yt_clipper-0.1.0/src/yt_clipper/analyzer.py +239 -0
- yt_clipper-0.1.0/src/yt_clipper/cli.py +224 -0
- yt_clipper-0.1.0/src/yt_clipper/cutter.py +105 -0
- yt_clipper-0.1.0/src/yt_clipper/ingest.py +164 -0
- yt_clipper-0.1.0/src/yt_clipper/ollama_manager.py +209 -0
- yt_clipper-0.1.0/src/yt_clipper.egg-info/PKG-INFO +115 -0
- yt_clipper-0.1.0/src/yt_clipper.egg-info/SOURCES.txt +14 -0
- yt_clipper-0.1.0/src/yt_clipper.egg-info/dependency_links.txt +1 -0
- yt_clipper-0.1.0/src/yt_clipper.egg-info/entry_points.txt +3 -0
- yt_clipper-0.1.0/src/yt_clipper.egg-info/requires.txt +4 -0
- yt_clipper-0.1.0/src/yt_clipper.egg-info/top_level.txt +1 -0
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: yt-clipper
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: 100% Free, Local AI YouTube Video Highlight Finder & Clipper powered by Ollama and FFmpeg
|
|
5
|
+
Author: Soham
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Keywords: youtube,clipper,highlights,ollama,llm,ffmpeg,video-editing,ai
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Operating System :: OS Independent
|
|
10
|
+
Classifier: Topic :: Multimedia :: Video
|
|
11
|
+
Classifier: Environment :: Console
|
|
12
|
+
Requires-Python: >=3.9
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
Requires-Dist: yt-dlp>=2026.11.0
|
|
15
|
+
Requires-Dist: youtube-transcript-api>=1.2.5
|
|
16
|
+
Requires-Dist: requests>=2.31.0
|
|
17
|
+
Requires-Dist: rich>=13.0.0
|
|
18
|
+
|
|
19
|
+
# 🎬 yt-clipper
|
|
20
|
+
|
|
21
|
+
> **100% Free, Local AI YouTube Video Highlight Finder & Clipper**
|
|
22
|
+
> *Zero subscriptions • Zero paid API keys • Auto-managed local models via Ollama & FFmpeg*
|
|
23
|
+
|
|
24
|
+
An open-source Python tool that ingests YouTube videos/podcasts/streams, identifies the best viral/highlight moments using a **Local LLM**, and automatically slices them into MP4 clips.
|
|
25
|
+
|
|
26
|
+
---
|
|
27
|
+
|
|
28
|
+
## ⚡ Key Highlights
|
|
29
|
+
|
|
30
|
+
- **Zero Setup Required:** If you don't have a model yet, `yt-clipper` automatically downloads a fast, high-quality model (e.g. `llama3.2:3b`) directly into Ollama with a live progress bar.
|
|
31
|
+
- **Fast Transcript Extraction:** Pulls accurate millisecond captions via `youtube-transcript-api` in seconds without downloading gigabytes of video.
|
|
32
|
+
- **Local AI Analysis:** Evaluates hooks, punchlines, debates, and emotional climaxes locally on your GPU/CPU via Ollama.
|
|
33
|
+
- **Instant Video Slicing:** Uses FFmpeg to cut MP4 clips (both fast stream-copy mode and frame-accurate mode).
|
|
34
|
+
- **Automated Metadata & Reports:** Saves `highlights_summary.json` and a clean Markdown table for editors.
|
|
35
|
+
|
|
36
|
+
---
|
|
37
|
+
|
|
38
|
+
## 📦 Installation
|
|
39
|
+
|
|
40
|
+
### From Source (Local Development)
|
|
41
|
+
```bash
|
|
42
|
+
git clone https://github.com/your-username/yt-clipper.git
|
|
43
|
+
cd yt-clipper
|
|
44
|
+
pip install -e .
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
### From Wheel / Tarball
|
|
48
|
+
```bash
|
|
49
|
+
pip install dist/yt_clipper-0.1.0-py3-none-any.whl
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
### Prerequisites
|
|
53
|
+
1. **Ollama:** Download and install from [ollama.com](https://ollama.com). (The tool will automatically start the background server and pull a model if you don't have one).
|
|
54
|
+
2. **FFmpeg:** Ensure `ffmpeg` is installed on your system PATH.
|
|
55
|
+
|
|
56
|
+
---
|
|
57
|
+
|
|
58
|
+
## 🚀 Quick Usage
|
|
59
|
+
|
|
60
|
+
Once installed, you can run `clipper` or `yt-clipper` from anywhere in your terminal:
|
|
61
|
+
|
|
62
|
+
### 1. Scan Highlights in Seconds (No Video Download)
|
|
63
|
+
Perfect for quickly checking if a 2-hour podcast has good moments before downloading:
|
|
64
|
+
```bash
|
|
65
|
+
clipper --url "https://www.youtube.com/watch?v=VIDEO_ID" --no-cut
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
### 2. Extract and Automatically Cut MP4 Clips
|
|
69
|
+
Analyzes the video and automatically saves sliced MP4 video files into `clips/`:
|
|
70
|
+
```bash
|
|
71
|
+
clipper --url "https://www.youtube.com/watch?v=VIDEO_ID" --min-score 8
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
### 3. Specify a Custom Model
|
|
75
|
+
```bash
|
|
76
|
+
clipper --url "https://youtu.be/..." --model "qwen3.5:4b"
|
|
77
|
+
```
|
|
78
|
+
*(If the specified model is not downloaded yet, `yt-clipper` will automatically pull it for you!)*
|
|
79
|
+
|
|
80
|
+
---
|
|
81
|
+
|
|
82
|
+
## ⚙️ Options & Arguments
|
|
83
|
+
|
|
84
|
+
| Flag | Shorthand | Default | Description |
|
|
85
|
+
| :--- | :---: | :---: | :--- |
|
|
86
|
+
| `--url` | `-u` | *(Prompt)* | YouTube URL or 11-char Video ID |
|
|
87
|
+
| `--min-score` | `-s` | `7` | Minimum highlight quality score (1–10) |
|
|
88
|
+
| `--model` | `-m` | Auto | Ollama model name (auto-selects or auto-downloads) |
|
|
89
|
+
| `--no-cut` | | `False` | Only extract timestamps and save reports; skip video download |
|
|
90
|
+
| `--fast-cut` | | `False` | Instant lossless stream copy (`-c copy`) without re-encoding |
|
|
91
|
+
| `--output-dir` | `-o` | `clips` | Directory to save clips and summaries |
|
|
92
|
+
| `--quality` | `-q` | `1080` | Max video height for downloaded video (e.g. 720, 1080) |
|
|
93
|
+
| `--chunk-size` | | `240` | Transcript context window size in seconds |
|
|
94
|
+
|
|
95
|
+
---
|
|
96
|
+
|
|
97
|
+
## 📂 Output Folder Structure
|
|
98
|
+
|
|
99
|
+
When processing with clipping enabled:
|
|
100
|
+
```
|
|
101
|
+
clips/
|
|
102
|
+
├── highlights_summary.json # Structured JSON metadata
|
|
103
|
+
├── highlights_summary.md # Markdown table of timestamps & hooks
|
|
104
|
+
├── source/
|
|
105
|
+
│ └── [video_id].mp4 # Downloaded source video
|
|
106
|
+
└── clips/
|
|
107
|
+
├── clip_01_sample_highlight.mp4
|
|
108
|
+
├── clip_02_sample_highlight.mp4
|
|
109
|
+
└── ...
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
---
|
|
113
|
+
|
|
114
|
+
## 📄 License
|
|
115
|
+
MIT License. Free for personal and commercial use.
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
# 🎬 yt-clipper
|
|
2
|
+
|
|
3
|
+
> **100% Free, Local AI YouTube Video Highlight Finder & Clipper**
|
|
4
|
+
> *Zero subscriptions • Zero paid API keys • Auto-managed local models via Ollama & FFmpeg*
|
|
5
|
+
|
|
6
|
+
An open-source Python tool that ingests YouTube videos/podcasts/streams, identifies the best viral/highlight moments using a **Local LLM**, and automatically slices them into MP4 clips.
|
|
7
|
+
|
|
8
|
+
---
|
|
9
|
+
|
|
10
|
+
## ⚡ Key Highlights
|
|
11
|
+
|
|
12
|
+
- **Zero Setup Required:** If you don't have a model yet, `yt-clipper` automatically downloads a fast, high-quality model (e.g. `llama3.2:3b`) directly into Ollama with a live progress bar.
|
|
13
|
+
- **Fast Transcript Extraction:** Pulls accurate millisecond captions via `youtube-transcript-api` in seconds without downloading gigabytes of video.
|
|
14
|
+
- **Local AI Analysis:** Evaluates hooks, punchlines, debates, and emotional climaxes locally on your GPU/CPU via Ollama.
|
|
15
|
+
- **Instant Video Slicing:** Uses FFmpeg to cut MP4 clips (both fast stream-copy mode and frame-accurate mode).
|
|
16
|
+
- **Automated Metadata & Reports:** Saves `highlights_summary.json` and a clean Markdown table for editors.
|
|
17
|
+
|
|
18
|
+
---
|
|
19
|
+
|
|
20
|
+
## 📦 Installation
|
|
21
|
+
|
|
22
|
+
### From Source (Local Development)
|
|
23
|
+
```bash
|
|
24
|
+
git clone https://github.com/your-username/yt-clipper.git
|
|
25
|
+
cd yt-clipper
|
|
26
|
+
pip install -e .
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
### From Wheel / Tarball
|
|
30
|
+
```bash
|
|
31
|
+
pip install dist/yt_clipper-0.1.0-py3-none-any.whl
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
### Prerequisites
|
|
35
|
+
1. **Ollama:** Download and install from [ollama.com](https://ollama.com). (The tool will automatically start the background server and pull a model if you don't have one).
|
|
36
|
+
2. **FFmpeg:** Ensure `ffmpeg` is installed on your system PATH.
|
|
37
|
+
|
|
38
|
+
---
|
|
39
|
+
|
|
40
|
+
## 🚀 Quick Usage
|
|
41
|
+
|
|
42
|
+
Once installed, you can run `clipper` or `yt-clipper` from anywhere in your terminal:
|
|
43
|
+
|
|
44
|
+
### 1. Scan Highlights in Seconds (No Video Download)
|
|
45
|
+
Perfect for quickly checking if a 2-hour podcast has good moments before downloading:
|
|
46
|
+
```bash
|
|
47
|
+
clipper --url "https://www.youtube.com/watch?v=VIDEO_ID" --no-cut
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
### 2. Extract and Automatically Cut MP4 Clips
|
|
51
|
+
Analyzes the video and automatically saves sliced MP4 video files into `clips/`:
|
|
52
|
+
```bash
|
|
53
|
+
clipper --url "https://www.youtube.com/watch?v=VIDEO_ID" --min-score 8
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
### 3. Specify a Custom Model
|
|
57
|
+
```bash
|
|
58
|
+
clipper --url "https://youtu.be/..." --model "qwen3.5:4b"
|
|
59
|
+
```
|
|
60
|
+
*(If the specified model is not downloaded yet, `yt-clipper` will automatically pull it for you!)*
|
|
61
|
+
|
|
62
|
+
---
|
|
63
|
+
|
|
64
|
+
## ⚙️ Options & Arguments
|
|
65
|
+
|
|
66
|
+
| Flag | Shorthand | Default | Description |
|
|
67
|
+
| :--- | :---: | :---: | :--- |
|
|
68
|
+
| `--url` | `-u` | *(Prompt)* | YouTube URL or 11-char Video ID |
|
|
69
|
+
| `--min-score` | `-s` | `7` | Minimum highlight quality score (1–10) |
|
|
70
|
+
| `--model` | `-m` | Auto | Ollama model name (auto-selects or auto-downloads) |
|
|
71
|
+
| `--no-cut` | | `False` | Only extract timestamps and save reports; skip video download |
|
|
72
|
+
| `--fast-cut` | | `False` | Instant lossless stream copy (`-c copy`) without re-encoding |
|
|
73
|
+
| `--output-dir` | `-o` | `clips` | Directory to save clips and summaries |
|
|
74
|
+
| `--quality` | `-q` | `1080` | Max video height for downloaded video (e.g. 720, 1080) |
|
|
75
|
+
| `--chunk-size` | | `240` | Transcript context window size in seconds |
|
|
76
|
+
|
|
77
|
+
---
|
|
78
|
+
|
|
79
|
+
## 📂 Output Folder Structure
|
|
80
|
+
|
|
81
|
+
When processing with clipping enabled:
|
|
82
|
+
```
|
|
83
|
+
clips/
|
|
84
|
+
├── highlights_summary.json # Structured JSON metadata
|
|
85
|
+
├── highlights_summary.md # Markdown table of timestamps & hooks
|
|
86
|
+
├── source/
|
|
87
|
+
│ └── [video_id].mp4 # Downloaded source video
|
|
88
|
+
└── clips/
|
|
89
|
+
├── clip_01_sample_highlight.mp4
|
|
90
|
+
├── clip_02_sample_highlight.mp4
|
|
91
|
+
└── ...
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
---
|
|
95
|
+
|
|
96
|
+
## 📄 License
|
|
97
|
+
MIT License. Free for personal and commercial use.
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "yt-clipper"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
authors = [
|
|
9
|
+
{ name="Soham" },
|
|
10
|
+
]
|
|
11
|
+
description = "100% Free, Local AI YouTube Video Highlight Finder & Clipper powered by Ollama and FFmpeg"
|
|
12
|
+
readme = "README.md"
|
|
13
|
+
requires-python = ">=3.9"
|
|
14
|
+
license = "MIT"
|
|
15
|
+
keywords = ["youtube", "clipper", "highlights", "ollama", "llm", "ffmpeg", "video-editing", "ai"]
|
|
16
|
+
classifiers = [
|
|
17
|
+
"Programming Language :: Python :: 3",
|
|
18
|
+
"Operating System :: OS Independent",
|
|
19
|
+
"Topic :: Multimedia :: Video",
|
|
20
|
+
"Environment :: Console",
|
|
21
|
+
]
|
|
22
|
+
dependencies = [
|
|
23
|
+
"yt-dlp>=2026.11.0",
|
|
24
|
+
"youtube-transcript-api>=1.2.5",
|
|
25
|
+
"requests>=2.31.0",
|
|
26
|
+
"rich>=13.0.0",
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
[project.scripts]
|
|
30
|
+
clipper = "yt_clipper.cli:main"
|
|
31
|
+
yt-clipper = "yt_clipper.cli:main"
|
|
32
|
+
|
|
33
|
+
[tool.setuptools.packages.find]
|
|
34
|
+
where = ["src"]
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Highlight Analyzer Module:
|
|
3
|
+
- Chunks transcripts into coherent time windows
|
|
4
|
+
- Prompts local Ollama LLMs with viral / highlight criteria
|
|
5
|
+
- Parses and validates JSON timestamps, viral scores, and summaries
|
|
6
|
+
- Deduplicates and ranks highlight segments
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import re
|
|
11
|
+
import requests
|
|
12
|
+
from typing import List, Dict, Any, Optional
|
|
13
|
+
from .ingest import parse_timestamp, format_timestamp
|
|
14
|
+
from .ollama_manager import DEFAULT_OLLAMA_URL
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def chunk_transcript(
|
|
18
|
+
transcript: List[Dict[str, Any]],
|
|
19
|
+
chunk_duration_sec: int = 240, # 4 minutes
|
|
20
|
+
overlap_sec: int = 40 # 40 seconds overlap
|
|
21
|
+
) -> List[Dict[str, Any]]:
|
|
22
|
+
"""
|
|
23
|
+
Split timestamped transcript into overlapping chunks so highlights
|
|
24
|
+
spanning segment boundaries are not missed.
|
|
25
|
+
"""
|
|
26
|
+
if not transcript:
|
|
27
|
+
return []
|
|
28
|
+
|
|
29
|
+
chunks = []
|
|
30
|
+
total_len = len(transcript)
|
|
31
|
+
i = 0
|
|
32
|
+
|
|
33
|
+
while i < total_len:
|
|
34
|
+
chunk_start_sec = transcript[i]["start"]
|
|
35
|
+
chunk_target_end = chunk_start_sec + chunk_duration_sec
|
|
36
|
+
chunk_items = []
|
|
37
|
+
next_i = -1
|
|
38
|
+
|
|
39
|
+
for j in range(i, total_len):
|
|
40
|
+
item = transcript[j]
|
|
41
|
+
chunk_items.append(item)
|
|
42
|
+
|
|
43
|
+
if item["start"] >= (chunk_target_end - overlap_sec) and next_i == -1:
|
|
44
|
+
next_i = j
|
|
45
|
+
|
|
46
|
+
if item["end"] >= chunk_target_end:
|
|
47
|
+
break
|
|
48
|
+
|
|
49
|
+
if not chunk_items:
|
|
50
|
+
break
|
|
51
|
+
|
|
52
|
+
lines = [f"[{item['start_str']}] {item['text']}" for item in chunk_items]
|
|
53
|
+
chunk_end_sec = chunk_items[-1]["end"]
|
|
54
|
+
|
|
55
|
+
chunks.append({
|
|
56
|
+
"start_sec": chunk_start_sec,
|
|
57
|
+
"end_sec": chunk_end_sec,
|
|
58
|
+
"start_str": format_timestamp(chunk_start_sec),
|
|
59
|
+
"end_str": format_timestamp(chunk_end_sec),
|
|
60
|
+
"text": "\n".join(lines),
|
|
61
|
+
"item_count": len(chunk_items),
|
|
62
|
+
})
|
|
63
|
+
|
|
64
|
+
if j >= total_len - 1:
|
|
65
|
+
break
|
|
66
|
+
|
|
67
|
+
if next_i != -1 and next_i > i:
|
|
68
|
+
i = next_i
|
|
69
|
+
else:
|
|
70
|
+
i = j + 1
|
|
71
|
+
|
|
72
|
+
return chunks
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def extract_json_array(text: str) -> List[Dict[str, Any]]:
|
|
76
|
+
"""Robustly extract and parse a JSON array from LLM response text."""
|
|
77
|
+
text = text.strip()
|
|
78
|
+
|
|
79
|
+
# If wrapped in markdown code fence
|
|
80
|
+
fence_match = re.search(r"```(?:json)?\s*(\[.*?\])\s*```", text, re.DOTALL)
|
|
81
|
+
if fence_match:
|
|
82
|
+
try:
|
|
83
|
+
return json.loads(fence_match.group(1))
|
|
84
|
+
except Exception:
|
|
85
|
+
pass
|
|
86
|
+
|
|
87
|
+
# Search for any [ ... ] bracket block
|
|
88
|
+
array_match = re.search(r"\[\s*\{.*?\}\s*\]", text, re.DOTALL)
|
|
89
|
+
if array_match:
|
|
90
|
+
try:
|
|
91
|
+
return json.loads(array_match.group(0))
|
|
92
|
+
except Exception:
|
|
93
|
+
pass
|
|
94
|
+
|
|
95
|
+
# If single object { ... } was returned, wrap it
|
|
96
|
+
obj_match = re.search(r"\{[^{}]*\"start_time\"[^{}]*\}", text, re.DOTALL)
|
|
97
|
+
if obj_match:
|
|
98
|
+
try:
|
|
99
|
+
return [json.loads(obj_match.group(0))]
|
|
100
|
+
except Exception:
|
|
101
|
+
pass
|
|
102
|
+
|
|
103
|
+
return []
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def analyze_chunk_with_llm(
|
|
107
|
+
chunk: Dict[str, Any],
|
|
108
|
+
model: str,
|
|
109
|
+
base_url: str = DEFAULT_OLLAMA_URL
|
|
110
|
+
) -> List[Dict[str, Any]]:
|
|
111
|
+
"""
|
|
112
|
+
Prompt Ollama model to evaluate a transcript chunk and extract top highlights.
|
|
113
|
+
"""
|
|
114
|
+
prompt = f"""You are a professional video editor and viral clip curator.
|
|
115
|
+
Your task is to analyze the following timestamped transcript and identify the most engaging, viral, or insightful moments (podcasts, gaming, debates, storytelling).
|
|
116
|
+
|
|
117
|
+
Criteria for a "Good Moment":
|
|
118
|
+
1. STRONG HOOK: Begins with an intriguing question, bold claim, intense moment, or sudden event. Include the setup so the audience knows what is being discussed.
|
|
119
|
+
2. STANDALONE & COMPLETE: Makes complete sense on its own. Contains the beginning, middle, and end of the thought/story.
|
|
120
|
+
3. CLEAR CONCLUSION: Ends naturally after the punchline, insight, or reaction (not cut mid-sentence).
|
|
121
|
+
4. DURATION: Typically 20 to 120 seconds. Do NOT output tiny 5-second fragments without context.
|
|
122
|
+
|
|
123
|
+
Transcript segment:
|
|
124
|
+
---
|
|
125
|
+
{chunk['text']}
|
|
126
|
+
---
|
|
127
|
+
|
|
128
|
+
Output a valid JSON array of highlight candidates. If there are no good highlights in this segment, return an empty array `[]`.
|
|
129
|
+
Each candidate must have:
|
|
130
|
+
- "title": Catchy headline (max 8 words)
|
|
131
|
+
- "start_time": Precise start timestamp from the transcript (format HH:MM:SS)
|
|
132
|
+
- "end_time": Precise end timestamp from the transcript (format HH:MM:SS)
|
|
133
|
+
- "score": Rating from 1 to 10 (10 = incredible viral moment, 7 = solid engaging clip, <6 = skip)
|
|
134
|
+
- "reason": Why this moment is good (1 sentence)
|
|
135
|
+
- "hook": The opening sentence or hook of the clip
|
|
136
|
+
|
|
137
|
+
Respond ONLY with the JSON array:
|
|
138
|
+
[
|
|
139
|
+
{{
|
|
140
|
+
"title": "...",
|
|
141
|
+
"start_time": "HH:MM:SS",
|
|
142
|
+
"end_time": "HH:MM:SS",
|
|
143
|
+
"score": 9,
|
|
144
|
+
"reason": "...",
|
|
145
|
+
"hook": "..."
|
|
146
|
+
}}
|
|
147
|
+
]
|
|
148
|
+
"""
|
|
149
|
+
|
|
150
|
+
payload = {
|
|
151
|
+
"model": model,
|
|
152
|
+
"prompt": prompt,
|
|
153
|
+
"stream": False,
|
|
154
|
+
"options": {
|
|
155
|
+
"temperature": 0.2,
|
|
156
|
+
"num_predict": 700,
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
try:
|
|
161
|
+
res = requests.post(f"{base_url}/api/generate", json=payload, timeout=90)
|
|
162
|
+
res.raise_for_status()
|
|
163
|
+
raw_text = res.json().get("response", "")
|
|
164
|
+
candidates = extract_json_array(raw_text)
|
|
165
|
+
return candidates
|
|
166
|
+
except Exception as e:
|
|
167
|
+
print(f" [Warning] LLM analysis error on chunk {chunk['start_str']} - {chunk['end_str']}: {e}")
|
|
168
|
+
return []
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def deduplicate_and_rank_highlights(
|
|
172
|
+
highlights: List[Dict[str, Any]],
|
|
173
|
+
min_score: int = 7,
|
|
174
|
+
min_duration_sec: int = 15,
|
|
175
|
+
max_duration_sec: int = 180
|
|
176
|
+
) -> List[Dict[str, Any]]:
|
|
177
|
+
"""
|
|
178
|
+
Validates, filters, deduplicates overlapping highlights, and sorts by score.
|
|
179
|
+
"""
|
|
180
|
+
valid = []
|
|
181
|
+
for h in highlights:
|
|
182
|
+
try:
|
|
183
|
+
start_str = h.get("start_time") or h.get("start")
|
|
184
|
+
end_str = h.get("end_time") or h.get("end")
|
|
185
|
+
score = int(h.get("score", 7))
|
|
186
|
+
title = h.get("title", "Untitled Highlight").strip()
|
|
187
|
+
reason = h.get("reason", "").strip()
|
|
188
|
+
hook = h.get("hook", "").strip()
|
|
189
|
+
|
|
190
|
+
if not start_str or not end_str:
|
|
191
|
+
continue
|
|
192
|
+
|
|
193
|
+
start_sec = parse_timestamp(start_str)
|
|
194
|
+
end_sec = parse_timestamp(end_str)
|
|
195
|
+
duration = end_sec - start_sec
|
|
196
|
+
|
|
197
|
+
if duration < min_duration_sec or duration > max_duration_sec:
|
|
198
|
+
continue
|
|
199
|
+
if score < min_score:
|
|
200
|
+
continue
|
|
201
|
+
|
|
202
|
+
valid.append({
|
|
203
|
+
"title": title,
|
|
204
|
+
"start_time": format_timestamp(start_sec),
|
|
205
|
+
"end_time": format_timestamp(end_sec),
|
|
206
|
+
"start_sec": round(start_sec, 2),
|
|
207
|
+
"end_sec": round(end_sec, 2),
|
|
208
|
+
"duration_sec": round(duration, 2),
|
|
209
|
+
"score": score,
|
|
210
|
+
"reason": reason,
|
|
211
|
+
"hook": hook,
|
|
212
|
+
})
|
|
213
|
+
except Exception:
|
|
214
|
+
continue
|
|
215
|
+
|
|
216
|
+
valid.sort(key=lambda x: (x["score"], -x["duration_sec"]), reverse=True)
|
|
217
|
+
|
|
218
|
+
unique_highlights = []
|
|
219
|
+
for candidate in valid:
|
|
220
|
+
c_start, c_end = candidate["start_sec"], candidate["end_sec"]
|
|
221
|
+
overlap_found = False
|
|
222
|
+
|
|
223
|
+
for existing in unique_highlights:
|
|
224
|
+
e_start, e_end = existing["start_sec"], existing["end_sec"]
|
|
225
|
+
inter_start = max(c_start, e_start)
|
|
226
|
+
inter_end = min(c_end, e_end)
|
|
227
|
+
if inter_end > inter_start:
|
|
228
|
+
inter_len = inter_end - inter_start
|
|
229
|
+
c_len = c_end - c_start
|
|
230
|
+
e_len = e_end - e_start
|
|
231
|
+
if (inter_len / min(c_len, e_len)) > 0.4:
|
|
232
|
+
overlap_found = True
|
|
233
|
+
break
|
|
234
|
+
|
|
235
|
+
if not overlap_found:
|
|
236
|
+
unique_highlights.append(candidate)
|
|
237
|
+
|
|
238
|
+
unique_highlights.sort(key=lambda x: x["start_sec"])
|
|
239
|
+
return unique_highlights
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
CLI entry point for yt-clipper.
|
|
4
|
+
Can be executed directly or via the console script entry points (`clipper` / `yt-clipper`).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import os
|
|
8
|
+
import sys
|
|
9
|
+
import json
|
|
10
|
+
import argparse
|
|
11
|
+
from rich.console import Console
|
|
12
|
+
from rich.table import Table
|
|
13
|
+
from rich.panel import Panel
|
|
14
|
+
from rich.progress import Progress, SpinnerColumn, TextColumn
|
|
15
|
+
|
|
16
|
+
from .ingest import (
|
|
17
|
+
get_video_metadata,
|
|
18
|
+
fetch_transcript,
|
|
19
|
+
download_source_video,
|
|
20
|
+
)
|
|
21
|
+
from .analyzer import (
|
|
22
|
+
chunk_transcript,
|
|
23
|
+
analyze_chunk_with_llm,
|
|
24
|
+
deduplicate_and_rank_highlights,
|
|
25
|
+
)
|
|
26
|
+
from .cutter import cut_all_highlights
|
|
27
|
+
from .ollama_manager import prepare_model
|
|
28
|
+
|
|
29
|
+
console = Console()
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def save_markdown_report(metadata: dict, highlights: list, output_path: str):
|
|
33
|
+
"""Save a clean Markdown summary for editors."""
|
|
34
|
+
lines = [
|
|
35
|
+
f"# Highlight Report: {metadata.get('title', 'Video Highlights')}",
|
|
36
|
+
f"- **Channel:** {metadata.get('uploader', 'N/A')}",
|
|
37
|
+
f"- **Source URL:** {metadata.get('url', 'N/A')}",
|
|
38
|
+
f"- **Total Duration:** {metadata.get('duration_str', 'N/A')}",
|
|
39
|
+
f"- **Highlights Found:** {len(highlights)}",
|
|
40
|
+
"",
|
|
41
|
+
"---",
|
|
42
|
+
"",
|
|
43
|
+
"| # | Timestamps | Duration | Score | Title | Hook / Opening | Reason |",
|
|
44
|
+
"|---|---|---|---|---|---|---|",
|
|
45
|
+
]
|
|
46
|
+
|
|
47
|
+
for idx, h in enumerate(highlights, 1):
|
|
48
|
+
ts = f"`{h['start_time']} - {h['end_time']}`"
|
|
49
|
+
dur = f"{int(h['duration_sec'])}s"
|
|
50
|
+
score = f"⭐ **{h['score']}/10**"
|
|
51
|
+
title = h['title'].replace("|", "-")
|
|
52
|
+
hook = h.get('hook', '').replace("|", "-")
|
|
53
|
+
reason = h.get('reason', '').replace("|", "-")
|
|
54
|
+
lines.append(f"| {idx} | {ts} | {dur} | {score} | {title} | {hook} | {reason} |")
|
|
55
|
+
|
|
56
|
+
lines.append("")
|
|
57
|
+
with open(output_path, "w", encoding="utf-8") as f:
|
|
58
|
+
f.write("\n".join(lines))
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def main():
|
|
62
|
+
parser = argparse.ArgumentParser(
|
|
63
|
+
prog="clipper",
|
|
64
|
+
description="Extract the best highlights and viral moments from YouTube videos using Local LLMs (Ollama) & FFmpeg.",
|
|
65
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
66
|
+
epilog="""
|
|
67
|
+
Examples:
|
|
68
|
+
# Quick scan for highlights (no video download):
|
|
69
|
+
clipper --url "https://youtu.be/VIDEO_ID" --no-cut
|
|
70
|
+
|
|
71
|
+
# Find highlights with minimum score 8 and cut MP4 clips:
|
|
72
|
+
clipper --url "https://youtu.be/VIDEO_ID" --min-score 8
|
|
73
|
+
|
|
74
|
+
# Specify a custom local Ollama model:
|
|
75
|
+
clipper --url "https://youtu.be/VIDEO_ID" --model "qwen3.5:4b"
|
|
76
|
+
"""
|
|
77
|
+
)
|
|
78
|
+
parser.add_argument("--url", "-u", type=str, help="YouTube video URL or Video ID")
|
|
79
|
+
parser.add_argument("--min-score", "-s", type=int, default=7, help="Minimum highlight score (1-10, default: 7)")
|
|
80
|
+
parser.add_argument("--model", "-m", type=str, default=None, help="Local Ollama model name (default: auto-detected or auto-downloaded)")
|
|
81
|
+
parser.add_argument("--output-dir", "-o", type=str, default="clips", help="Output directory (default: 'clips')")
|
|
82
|
+
parser.add_argument("--quality", "-q", type=int, default=1080, help="Max video height in pixels for download (default: 1080)")
|
|
83
|
+
parser.add_argument("--no-cut", action="store_true", help="Only identify timestamps and generate report; do not download or cut video")
|
|
84
|
+
parser.add_argument("--fast-cut", action="store_true", help="Use instant stream copy (-c copy) instead of frame-accurate re-encode")
|
|
85
|
+
parser.add_argument("--chunk-size", type=int, default=240, help="Transcript chunk size in seconds (default: 240)")
|
|
86
|
+
|
|
87
|
+
args = parser.parse_args()
|
|
88
|
+
|
|
89
|
+
console.print(Panel.fit(
|
|
90
|
+
"[bold cyan]🎬 Local AI YouTube Clipper[/bold cyan]\n"
|
|
91
|
+
"[dim]100% Free • Zero Subscriptions • Auto-Managed Local LLM (Ollama) & FFmpeg[/dim]",
|
|
92
|
+
border_style="cyan"
|
|
93
|
+
))
|
|
94
|
+
|
|
95
|
+
# 1. Prompt for URL if not provided via CLI
|
|
96
|
+
video_input = args.url
|
|
97
|
+
if not video_input:
|
|
98
|
+
video_input = console.input("\n[bold yellow]Enter YouTube URL or Video ID:[/bold yellow] ").strip()
|
|
99
|
+
if not video_input:
|
|
100
|
+
console.print("[red]No URL provided. Exiting.[/red]")
|
|
101
|
+
sys.exit(1)
|
|
102
|
+
|
|
103
|
+
# 2. Check and prepare Ollama model (auto-pulls if needed!)
|
|
104
|
+
chosen_model = prepare_model(args.model)
|
|
105
|
+
console.print(f"[green]✓[/green] Active Local LLM: [bold magenta]{chosen_model}[/bold magenta]")
|
|
106
|
+
|
|
107
|
+
# 3. Ingest Video Metadata & Subtitles
|
|
108
|
+
with Progress(
|
|
109
|
+
SpinnerColumn(),
|
|
110
|
+
TextColumn("[progress.description]{task.description}"),
|
|
111
|
+
transient=True,
|
|
112
|
+
console=console
|
|
113
|
+
) as progress:
|
|
114
|
+
task1 = progress.add_task("[cyan]Fetching video metadata...", total=None)
|
|
115
|
+
try:
|
|
116
|
+
metadata = get_video_metadata(video_input)
|
|
117
|
+
progress.update(task1, completed=True)
|
|
118
|
+
except Exception as e:
|
|
119
|
+
console.print(f"[red]Failed to fetch video metadata: {e}[/red]")
|
|
120
|
+
sys.exit(1)
|
|
121
|
+
|
|
122
|
+
task2 = progress.add_task("[cyan]Fetching timestamped transcript...", total=None)
|
|
123
|
+
try:
|
|
124
|
+
transcript = fetch_transcript(video_input)
|
|
125
|
+
progress.update(task2, completed=True)
|
|
126
|
+
except Exception as e:
|
|
127
|
+
console.print(f"[red]Transcript error: {e}[/red]")
|
|
128
|
+
sys.exit(1)
|
|
129
|
+
|
|
130
|
+
console.print(f"\n[bold]Title:[/bold] {metadata['title']}")
|
|
131
|
+
console.print(f"[bold]Channel:[/bold] {metadata['uploader']} | [bold]Duration:[/bold] {metadata['duration_str']}")
|
|
132
|
+
console.print(f"[bold]Transcript:[/bold] {len(transcript)} timed snippets loaded successfully.\n")
|
|
133
|
+
|
|
134
|
+
# 4. Semantic Chunking
|
|
135
|
+
chunks = chunk_transcript(transcript, chunk_duration_sec=args.chunk_size, overlap_sec=40)
|
|
136
|
+
console.print(f"[cyan]Analyzing content across {len(chunks)} contextual chunk(s)...[/cyan]")
|
|
137
|
+
|
|
138
|
+
# 5. Analyze with Local LLM
|
|
139
|
+
all_raw_highlights = []
|
|
140
|
+
with Progress(
|
|
141
|
+
SpinnerColumn(),
|
|
142
|
+
TextColumn("[progress.description]{task.description}"),
|
|
143
|
+
console=console
|
|
144
|
+
) as progress:
|
|
145
|
+
llm_task = progress.add_task(f"[magenta]Running {chosen_model} highlight analysis...", total=len(chunks))
|
|
146
|
+
for idx, chunk in enumerate(chunks, 1):
|
|
147
|
+
progress.update(llm_task, description=f"[magenta]Analyzing segment {idx}/{len(chunks)} ({chunk['start_str']} - {chunk['end_str']})...")
|
|
148
|
+
found = analyze_chunk_with_llm(chunk, model=chosen_model)
|
|
149
|
+
if found:
|
|
150
|
+
all_raw_highlights.extend(found)
|
|
151
|
+
progress.advance(llm_task)
|
|
152
|
+
|
|
153
|
+
# 6. Deduplicate and Rank
|
|
154
|
+
highlights = deduplicate_and_rank_highlights(all_raw_highlights, min_score=args.min_score)
|
|
155
|
+
|
|
156
|
+
if not highlights:
|
|
157
|
+
console.print(f"\n[yellow]No highlights met the score threshold of {args.min_score}/10.[/yellow]")
|
|
158
|
+
console.print("[dim]Tip: Try running again with `--min-score 5` or `--min-score 6`.[/dim]")
|
|
159
|
+
sys.exit(0)
|
|
160
|
+
|
|
161
|
+
# 7. Render Results Table
|
|
162
|
+
table = Table(title=f"\n🌟 Top Highlights Identified ({len(highlights)})", border_style="green", header_style="bold green")
|
|
163
|
+
table.add_column("#", justify="center", style="cyan", width=3)
|
|
164
|
+
table.add_column("Timestamps", justify="center", style="yellow", width=19)
|
|
165
|
+
table.add_column("Length", justify="center", width=7)
|
|
166
|
+
table.add_column("Score", justify="center", style="bold magenta", width=8)
|
|
167
|
+
table.add_column("Title & Reason", justify="left")
|
|
168
|
+
|
|
169
|
+
for idx, h in enumerate(highlights, 1):
|
|
170
|
+
ts = f"{h['start_time']} ➔ {h['end_time']}"
|
|
171
|
+
dur = f"{int(h['duration_sec'])}s"
|
|
172
|
+
score = f"{h['score']}/10"
|
|
173
|
+
desc = f"[bold]{h['title']}[/bold]\n[dim]Hook: \"{h.get('hook', 'N/A')}\"[/dim]\n[italic dim]{h.get('reason', '')}[/italic dim]"
|
|
174
|
+
table.add_row(str(idx), ts, dur, score, desc)
|
|
175
|
+
|
|
176
|
+
console.print(table)
|
|
177
|
+
|
|
178
|
+
# 8. Save Metadata Reports
|
|
179
|
+
os.makedirs(args.output_dir, exist_ok=True)
|
|
180
|
+
summary_json = os.path.join(args.output_dir, "highlights_summary.json")
|
|
181
|
+
summary_md = os.path.join(args.output_dir, "highlights_summary.md")
|
|
182
|
+
|
|
183
|
+
with open(summary_json, "w", encoding="utf-8") as f:
|
|
184
|
+
json.dump({"metadata": metadata, "highlights": highlights}, f, indent=2)
|
|
185
|
+
save_markdown_report(metadata, highlights, summary_md)
|
|
186
|
+
|
|
187
|
+
console.print(f"\n[green]✓[/green] Reports saved:")
|
|
188
|
+
console.print(f" • JSON: [bold]{summary_json}[/bold]")
|
|
189
|
+
console.print(f" • Markdown: [bold]{summary_md}[/bold]")
|
|
190
|
+
|
|
191
|
+
# 9. Cut Video Clips if requested
|
|
192
|
+
if args.no_cut:
|
|
193
|
+
console.print("\n[dim](Skipped video download and slicing due to --no-cut flag)[/dim]")
|
|
194
|
+
return
|
|
195
|
+
|
|
196
|
+
console.print("\n[bold cyan]Downloading source video to slice clips...[/bold cyan]")
|
|
197
|
+
try:
|
|
198
|
+
video_file = download_source_video(
|
|
199
|
+
metadata["url"],
|
|
200
|
+
output_dir=os.path.join(args.output_dir, "source"),
|
|
201
|
+
max_height=args.quality
|
|
202
|
+
)
|
|
203
|
+
console.print(f"[green]✓[/green] Source video downloaded: [bold]{video_file}[/bold]")
|
|
204
|
+
except Exception as e:
|
|
205
|
+
console.print(f"[red]Failed to download source video: {e}[/red]")
|
|
206
|
+
sys.exit(1)
|
|
207
|
+
|
|
208
|
+
console.print(f"\n[cyan]Slicing {len(highlights)} highlight clip(s) with FFmpeg...[/cyan]")
|
|
209
|
+
accurate = not args.fast_cut
|
|
210
|
+
sliced_clips = cut_all_highlights(
|
|
211
|
+
source_video_path=video_file,
|
|
212
|
+
highlights=highlights,
|
|
213
|
+
output_dir=os.path.join(args.output_dir, "clips"),
|
|
214
|
+
accurate=accurate
|
|
215
|
+
)
|
|
216
|
+
|
|
217
|
+
console.print(f"\n[bold green]🎉 Done! {len(sliced_clips)} clip(s) extracted successfully into:[/bold green]")
|
|
218
|
+
console.print(f"[bold cyan]{os.path.abspath(os.path.join(args.output_dir, 'clips'))}[/bold cyan]\n")
|
|
219
|
+
for clip in sliced_clips:
|
|
220
|
+
console.print(f" • [yellow]{clip['filename']}[/yellow] ({clip['file_size_mb']} MB) - Score: {clip['score']}/10")
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
if __name__ == "__main__":
|
|
224
|
+
main()
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""
|
|
2
|
+
FFmpeg Video Slicer:
|
|
3
|
+
- Losslessly or frame-accurately extracts highlight clips using ffmpeg.
|
|
4
|
+
- Sanitizes clip names and outputs organized MP4 files.
|
|
5
|
+
- Generates JSON and Markdown summary reports for editors.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import os
|
|
9
|
+
import re
|
|
10
|
+
import subprocess
|
|
11
|
+
from typing import List, Dict, Any, Optional
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def sanitize_filename(name: str) -> str:
|
|
15
|
+
"""Sanitize title into a safe file name."""
|
|
16
|
+
name = re.sub(r'[\\/*?:"<>|]', "", name)
|
|
17
|
+
name = re.sub(r"\s+", "_", name.strip())
|
|
18
|
+
return name[:60]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def cut_clip(
|
|
22
|
+
source_video_path: str,
|
|
23
|
+
start_time: str,
|
|
24
|
+
end_time: str,
|
|
25
|
+
output_path: str,
|
|
26
|
+
accurate: bool = True
|
|
27
|
+
) -> bool:
|
|
28
|
+
"""
|
|
29
|
+
Cut a video clip from source_video_path between start_time and end_time.
|
|
30
|
+
If accurate=True, re-encodes with fast x264 for exact keyframe boundaries.
|
|
31
|
+
If accurate=False, uses stream copy (-c copy) for instantaneous cuts.
|
|
32
|
+
"""
|
|
33
|
+
os.makedirs(os.path.dirname(os.path.abspath(output_path)), exist_ok=True)
|
|
34
|
+
|
|
35
|
+
if accurate:
|
|
36
|
+
cmd = [
|
|
37
|
+
"ffmpeg",
|
|
38
|
+
"-y",
|
|
39
|
+
"-ss", start_time,
|
|
40
|
+
"-to", end_time,
|
|
41
|
+
"-i", source_video_path,
|
|
42
|
+
"-c:v", "libx264",
|
|
43
|
+
"-preset", "veryfast",
|
|
44
|
+
"-crf", "22",
|
|
45
|
+
"-c:a", "aac",
|
|
46
|
+
"-b:a", "128k",
|
|
47
|
+
output_path
|
|
48
|
+
]
|
|
49
|
+
else:
|
|
50
|
+
cmd = [
|
|
51
|
+
"ffmpeg",
|
|
52
|
+
"-y",
|
|
53
|
+
"-ss", start_time,
|
|
54
|
+
"-to", end_time,
|
|
55
|
+
"-i", source_video_path,
|
|
56
|
+
"-c", "copy",
|
|
57
|
+
output_path
|
|
58
|
+
]
|
|
59
|
+
|
|
60
|
+
try:
|
|
61
|
+
subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True)
|
|
62
|
+
return os.path.exists(output_path) and os.path.getsize(output_path) > 0
|
|
63
|
+
except subprocess.CalledProcessError as e:
|
|
64
|
+
print(f" [Error cutting clip {output_path}]: {e.stderr.decode('utf-8', errors='ignore')[:300]}")
|
|
65
|
+
return False
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def cut_all_highlights(
|
|
69
|
+
source_video_path: str,
|
|
70
|
+
highlights: List[Dict[str, Any]],
|
|
71
|
+
output_dir: str = "clips",
|
|
72
|
+
accurate: bool = True
|
|
73
|
+
) -> List[Dict[str, Any]]:
|
|
74
|
+
"""
|
|
75
|
+
Cut all highlight segments into MP4 files and save summary metadata.
|
|
76
|
+
"""
|
|
77
|
+
os.makedirs(output_dir, exist_ok=True)
|
|
78
|
+
results = []
|
|
79
|
+
|
|
80
|
+
for idx, h in enumerate(highlights, 1):
|
|
81
|
+
safe_title = sanitize_filename(h["title"])
|
|
82
|
+
start_clean = h["start_time"].replace(":", "-")
|
|
83
|
+
end_clean = h["end_time"].replace(":", "-")
|
|
84
|
+
filename = f"clip_{idx:02d}_[{start_clean}_to_{end_clean}]_{safe_title}.mp4"
|
|
85
|
+
out_path = os.path.join(output_dir, filename)
|
|
86
|
+
|
|
87
|
+
success = cut_clip(
|
|
88
|
+
source_video_path=source_video_path,
|
|
89
|
+
start_time=h["start_time"],
|
|
90
|
+
end_time=h["end_time"],
|
|
91
|
+
output_path=out_path,
|
|
92
|
+
accurate=accurate
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
if success:
|
|
96
|
+
file_size_mb = round(os.path.getsize(out_path) / (1024 * 1024), 2)
|
|
97
|
+
results.append({
|
|
98
|
+
**h,
|
|
99
|
+
"clip_number": idx,
|
|
100
|
+
"file_path": os.path.abspath(out_path),
|
|
101
|
+
"filename": filename,
|
|
102
|
+
"file_size_mb": file_size_mb,
|
|
103
|
+
})
|
|
104
|
+
|
|
105
|
+
return results
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Ingestion module for YouTube videos:
|
|
3
|
+
- Extracts video ID & metadata (title, duration, channel, etc.)
|
|
4
|
+
- Fetches accurate timed transcripts via youtube-transcript-api (no video download required)
|
|
5
|
+
- Handles downloading video files via yt-dlp when cutting is requested.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import re
|
|
9
|
+
import os
|
|
10
|
+
from typing import Dict, List, Any, Optional
|
|
11
|
+
import yt_dlp
|
|
12
|
+
from youtube_transcript_api import YouTubeTranscriptApi, TranscriptsDisabled, NoTranscriptFound
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def extract_video_id(url_or_id: str) -> str:
|
|
16
|
+
"""Extract 11-character YouTube video ID from various URL formats."""
|
|
17
|
+
url_or_id = url_or_id.strip()
|
|
18
|
+
if len(url_or_id) == 11 and re.match(r"^[A-Za-z0-9_-]{11}$", url_or_id):
|
|
19
|
+
return url_or_id
|
|
20
|
+
|
|
21
|
+
patterns = [
|
|
22
|
+
r"(?:v=|\/v\/|youtu\.be\/|\/embed\/|\/shorts\/|\/live\/)([A-Za-z0-9_-]{11})",
|
|
23
|
+
r"^([A-Za-z0-9_-]{11})$",
|
|
24
|
+
]
|
|
25
|
+
for pattern in patterns:
|
|
26
|
+
match = re.search(pattern, url_or_id)
|
|
27
|
+
if match:
|
|
28
|
+
return match.group(1)
|
|
29
|
+
raise ValueError(f"Could not extract a valid YouTube video ID from: {url_or_id}")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def format_timestamp(seconds: float) -> str:
|
|
33
|
+
"""Convert seconds into HH:MM:SS format."""
|
|
34
|
+
total_sec = int(round(seconds))
|
|
35
|
+
hrs = total_sec // 3600
|
|
36
|
+
mins = (total_sec % 3600) // 60
|
|
37
|
+
secs = total_sec % 60
|
|
38
|
+
return f"{hrs:02d}:{mins:02d}:{secs:02d}"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def parse_timestamp(timestamp_str: str) -> float:
|
|
42
|
+
"""Convert HH:MM:SS or MM:SS to float seconds."""
|
|
43
|
+
parts = timestamp_str.strip().split(":")
|
|
44
|
+
if len(parts) == 3:
|
|
45
|
+
return float(parts[0]) * 3600 + float(parts[1]) * 60 + float(parts[2])
|
|
46
|
+
elif len(parts) == 2:
|
|
47
|
+
return float(parts[0]) * 60 + float(parts[1])
|
|
48
|
+
elif len(parts) == 1:
|
|
49
|
+
return float(parts[0])
|
|
50
|
+
raise ValueError(f"Invalid timestamp format: {timestamp_str}")
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def get_video_metadata(url_or_id: str) -> Dict[str, Any]:
|
|
54
|
+
"""Fetch video metadata using yt-dlp without downloading media."""
|
|
55
|
+
video_id = extract_video_id(url_or_id)
|
|
56
|
+
url = f"https://www.youtube.com/watch?v={video_id}"
|
|
57
|
+
ydl_opts = {
|
|
58
|
+
"quiet": True,
|
|
59
|
+
"no_warnings": True,
|
|
60
|
+
"skip_download": True,
|
|
61
|
+
}
|
|
62
|
+
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
|
63
|
+
info = ydl.extract_info(url, download=False)
|
|
64
|
+
return {
|
|
65
|
+
"id": video_id,
|
|
66
|
+
"url": url,
|
|
67
|
+
"title": info.get("title", "Unknown Title"),
|
|
68
|
+
"duration": info.get("duration", 0),
|
|
69
|
+
"duration_str": format_timestamp(info.get("duration", 0)),
|
|
70
|
+
"uploader": info.get("uploader", "Unknown Channel"),
|
|
71
|
+
"description": info.get("description", "")[:500],
|
|
72
|
+
"view_count": info.get("view_count", 0),
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def fetch_transcript(url_or_id: str, preferred_languages: Optional[List[str]] = None) -> List[Dict[str, Any]]:
|
|
77
|
+
"""
|
|
78
|
+
Fetch timed transcript segments without downloading video.
|
|
79
|
+
Returns list of dicts: [{'start': float, 'end': float, 'start_str': str, 'end_str': str, 'text': str}, ...]
|
|
80
|
+
"""
|
|
81
|
+
if preferred_languages is None:
|
|
82
|
+
preferred_languages = ["en", "en-US", "en-GB"]
|
|
83
|
+
|
|
84
|
+
video_id = extract_video_id(url_or_id)
|
|
85
|
+
api = YouTubeTranscriptApi()
|
|
86
|
+
|
|
87
|
+
snippets = None
|
|
88
|
+
|
|
89
|
+
# 1. Try fetching directly with preferred languages
|
|
90
|
+
try:
|
|
91
|
+
snippets = api.fetch(video_id, languages=preferred_languages)
|
|
92
|
+
except Exception:
|
|
93
|
+
pass
|
|
94
|
+
|
|
95
|
+
# 2. If direct fetch fails, list available transcripts and pick best or translate
|
|
96
|
+
if not snippets:
|
|
97
|
+
try:
|
|
98
|
+
transcript_list = api.list(video_id)
|
|
99
|
+
try:
|
|
100
|
+
transcript = transcript_list.find_transcript(preferred_languages)
|
|
101
|
+
snippets = transcript.fetch()
|
|
102
|
+
except Exception:
|
|
103
|
+
available = list(transcript_list)
|
|
104
|
+
if available:
|
|
105
|
+
first = available[0]
|
|
106
|
+
if first.is_translatable:
|
|
107
|
+
snippets = first.translate("en").fetch()
|
|
108
|
+
else:
|
|
109
|
+
snippets = first.fetch()
|
|
110
|
+
except (TranscriptsDisabled, NoTranscriptFound) as e:
|
|
111
|
+
raise RuntimeError(f"No transcripts/captions are available on YouTube for video ID: {video_id}") from e
|
|
112
|
+
except Exception as e:
|
|
113
|
+
raise RuntimeError(f"Failed to fetch transcript: {e}") from e
|
|
114
|
+
|
|
115
|
+
if not snippets:
|
|
116
|
+
raise RuntimeError(f"Could not retrieve any transcript for video ID: {video_id}")
|
|
117
|
+
|
|
118
|
+
formatted_transcript = []
|
|
119
|
+
for item in snippets:
|
|
120
|
+
start_sec = getattr(item, "start", 0.0)
|
|
121
|
+
dur_sec = getattr(item, "duration", 0.0)
|
|
122
|
+
text = getattr(item, "text", "").strip()
|
|
123
|
+
end_sec = start_sec + dur_sec
|
|
124
|
+
|
|
125
|
+
if not text:
|
|
126
|
+
continue
|
|
127
|
+
|
|
128
|
+
formatted_transcript.append({
|
|
129
|
+
"start": round(start_sec, 2),
|
|
130
|
+
"end": round(end_sec, 2),
|
|
131
|
+
"start_str": format_timestamp(start_sec),
|
|
132
|
+
"end_str": format_timestamp(end_sec),
|
|
133
|
+
"text": text,
|
|
134
|
+
})
|
|
135
|
+
|
|
136
|
+
return formatted_transcript
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def download_source_video(url_or_id: str, output_dir: str = "downloads", max_height: int = 1080) -> str:
|
|
140
|
+
"""
|
|
141
|
+
Download source video file using yt-dlp to output_dir.
|
|
142
|
+
Returns the absolute path to the downloaded video file.
|
|
143
|
+
"""
|
|
144
|
+
video_id = extract_video_id(url_or_id)
|
|
145
|
+
url = f"https://www.youtube.com/watch?v={video_id}"
|
|
146
|
+
os.makedirs(output_dir, exist_ok=True)
|
|
147
|
+
out_tmpl = os.path.join(output_dir, f"{video_id}.%(ext)s")
|
|
148
|
+
|
|
149
|
+
ydl_opts = {
|
|
150
|
+
"format": f"bestvideo[height<={max_height}][ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best",
|
|
151
|
+
"outtmpl": out_tmpl,
|
|
152
|
+
"merge_output_format": "mp4",
|
|
153
|
+
"quiet": False,
|
|
154
|
+
"no_warnings": True,
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
|
158
|
+
info = ydl.extract_info(url, download=True)
|
|
159
|
+
filename = ydl.prepare_filename(info)
|
|
160
|
+
base, _ = os.path.splitext(filename)
|
|
161
|
+
mp4_path = f"{base}.mp4"
|
|
162
|
+
if os.path.exists(mp4_path):
|
|
163
|
+
return os.path.abspath(mp4_path)
|
|
164
|
+
return os.path.abspath(filename)
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Ollama Manager Module:
|
|
3
|
+
- Ensures Ollama background service is running
|
|
4
|
+
- Discovers installed local models
|
|
5
|
+
- Automatically downloads/pulls a local model if missing (with streaming progress bar)
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import sys
|
|
9
|
+
import time
|
|
10
|
+
import json
|
|
11
|
+
import subprocess
|
|
12
|
+
import requests
|
|
13
|
+
from typing import List, Optional
|
|
14
|
+
from rich.console import Console
|
|
15
|
+
from rich.progress import (
|
|
16
|
+
Progress,
|
|
17
|
+
SpinnerColumn,
|
|
18
|
+
BarColumn,
|
|
19
|
+
TextColumn,
|
|
20
|
+
DownloadColumn,
|
|
21
|
+
TransferSpeedColumn,
|
|
22
|
+
TimeRemainingColumn,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
console = Console()
|
|
26
|
+
DEFAULT_OLLAMA_URL = "http://localhost:11434"
|
|
27
|
+
DEFAULT_FALLBACK_MODEL = "llama3.2:3b"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def is_ollama_running(base_url: str = DEFAULT_OLLAMA_URL) -> bool:
|
|
31
|
+
"""Check if the Ollama API server is responding."""
|
|
32
|
+
try:
|
|
33
|
+
r = requests.get(f"{base_url}/api/tags", timeout=1.5)
|
|
34
|
+
return r.status_code == 200
|
|
35
|
+
except Exception:
|
|
36
|
+
return False
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def ensure_ollama_running(base_url: str = DEFAULT_OLLAMA_URL) -> bool:
|
|
40
|
+
"""Check if Ollama server is running; attempt to launch if not."""
|
|
41
|
+
if is_ollama_running(base_url):
|
|
42
|
+
return True
|
|
43
|
+
|
|
44
|
+
console.print("[yellow]⚠️ Ollama server is not active at localhost:11434.[/yellow]")
|
|
45
|
+
console.print("[cyan]Starting Ollama background process...[/cyan]")
|
|
46
|
+
|
|
47
|
+
try:
|
|
48
|
+
# On Windows, start detached process
|
|
49
|
+
DETACHED_PROCESS = 0x00000008
|
|
50
|
+
CREATE_NEW_PROCESS_GROUP = 0x00000200
|
|
51
|
+
subprocess.Popen(
|
|
52
|
+
["ollama", "serve"],
|
|
53
|
+
creationflags=DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP if sys.platform == "win32" else 0,
|
|
54
|
+
close_fds=True,
|
|
55
|
+
stdout=subprocess.DEVNULL,
|
|
56
|
+
stderr=subprocess.DEVNULL,
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
for _ in range(12):
|
|
60
|
+
time.sleep(1)
|
|
61
|
+
if is_ollama_running(base_url):
|
|
62
|
+
console.print("[green]✓ Ollama daemon started successfully![/green]")
|
|
63
|
+
return True
|
|
64
|
+
except FileNotFoundError:
|
|
65
|
+
console.print("[bold red]Error:[/bold red] Ollama is not installed or not in your system PATH.")
|
|
66
|
+
console.print("Please install Ollama from [bold cyan]https://ollama.com[/bold cyan] and retry.")
|
|
67
|
+
return False
|
|
68
|
+
except Exception as e:
|
|
69
|
+
console.print(f"[red]Could not auto-start Ollama: {e}[/red]")
|
|
70
|
+
|
|
71
|
+
return False
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def get_installed_models(base_url: str = DEFAULT_OLLAMA_URL) -> List[str]:
|
|
75
|
+
"""Return a list of all model names currently available in local Ollama."""
|
|
76
|
+
try:
|
|
77
|
+
res = requests.get(f"{base_url}/api/tags", timeout=3)
|
|
78
|
+
if res.status_code == 200:
|
|
79
|
+
return [m["name"] for m in res.json().get("models", [])]
|
|
80
|
+
except Exception:
|
|
81
|
+
pass
|
|
82
|
+
return []
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def pull_model_with_progress(model_name: str, base_url: str = DEFAULT_OLLAMA_URL) -> bool:
|
|
86
|
+
"""
|
|
87
|
+
Pulls a model from Ollama registry with a live Rich progress bar.
|
|
88
|
+
"""
|
|
89
|
+
console.print(f"\n[bold cyan]📦 Downloading local model:[/bold cyan] [bold magenta]{model_name}[/bold magenta]")
|
|
90
|
+
console.print("[dim]This is a one-time download and will run 100% locally on your machine afterwards.[/dim]\n")
|
|
91
|
+
|
|
92
|
+
url = f"{base_url}/api/pull"
|
|
93
|
+
payload = {"name": model_name, "stream": True}
|
|
94
|
+
|
|
95
|
+
try:
|
|
96
|
+
with requests.post(url, json=payload, stream=True, timeout=1200) as response:
|
|
97
|
+
if response.status_code != 200:
|
|
98
|
+
console.print(f"[red]Failed to pull {model_name}: HTTP {response.status_code}[/red]")
|
|
99
|
+
return False
|
|
100
|
+
|
|
101
|
+
with Progress(
|
|
102
|
+
SpinnerColumn(),
|
|
103
|
+
TextColumn("[progress.description]{task.description}"),
|
|
104
|
+
BarColumn(),
|
|
105
|
+
DownloadColumn(),
|
|
106
|
+
TransferSpeedColumn(),
|
|
107
|
+
TimeRemainingColumn(),
|
|
108
|
+
console=console
|
|
109
|
+
) as progress:
|
|
110
|
+
tasks = {}
|
|
111
|
+
|
|
112
|
+
for line in response.iter_lines():
|
|
113
|
+
if not line:
|
|
114
|
+
continue
|
|
115
|
+
try:
|
|
116
|
+
data = json.loads(line.decode("utf-8"))
|
|
117
|
+
status = data.get("status", "")
|
|
118
|
+
digest = data.get("digest", "default")
|
|
119
|
+
total = data.get("total", 0)
|
|
120
|
+
completed = data.get("completed", 0)
|
|
121
|
+
|
|
122
|
+
if total > 0:
|
|
123
|
+
if digest not in tasks:
|
|
124
|
+
tasks[digest] = progress.add_task(
|
|
125
|
+
f"[cyan]{status}",
|
|
126
|
+
total=total,
|
|
127
|
+
completed=completed
|
|
128
|
+
)
|
|
129
|
+
else:
|
|
130
|
+
progress.update(
|
|
131
|
+
tasks[digest],
|
|
132
|
+
description=f"[cyan]{status}",
|
|
133
|
+
completed=completed,
|
|
134
|
+
total=total
|
|
135
|
+
)
|
|
136
|
+
else:
|
|
137
|
+
if status:
|
|
138
|
+
console.print(f" [dim]• {status}[/dim]")
|
|
139
|
+
except Exception:
|
|
140
|
+
continue
|
|
141
|
+
|
|
142
|
+
console.print(f"\n[bold green]✓ Successfully downloaded and loaded {model_name}![/bold green]\n")
|
|
143
|
+
return True
|
|
144
|
+
|
|
145
|
+
except Exception as e:
|
|
146
|
+
console.print(f"[red]Error downloading model via Ollama API: {e}[/red]")
|
|
147
|
+
console.print(f"[yellow]Attempting CLI fallback: 'ollama pull {model_name}'...[/yellow]")
|
|
148
|
+
try:
|
|
149
|
+
subprocess.run(["ollama", "pull", model_name], check=True)
|
|
150
|
+
return True
|
|
151
|
+
except Exception as cli_err:
|
|
152
|
+
console.print(f"[bold red]Failed to download model: {cli_err}[/bold red]")
|
|
153
|
+
return False
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def prepare_model(requested_model: Optional[str] = None, base_url: str = DEFAULT_OLLAMA_URL) -> str:
|
|
157
|
+
"""
|
|
158
|
+
Validates that a usable local model exists.
|
|
159
|
+
If none exists or the requested model is missing, automatically downloads it.
|
|
160
|
+
"""
|
|
161
|
+
if not ensure_ollama_running(base_url):
|
|
162
|
+
sys.exit(1)
|
|
163
|
+
|
|
164
|
+
installed = get_installed_models(base_url)
|
|
165
|
+
|
|
166
|
+
# 1. User requested a specific model
|
|
167
|
+
if requested_model:
|
|
168
|
+
# Check if already installed
|
|
169
|
+
for m in installed:
|
|
170
|
+
if requested_model.lower() in m.lower():
|
|
171
|
+
return m
|
|
172
|
+
|
|
173
|
+
# Not installed -> auto-pull it!
|
|
174
|
+
console.print(f"[yellow]Model '{requested_model}' not found locally.[/yellow]")
|
|
175
|
+
success = pull_model_with_progress(requested_model, base_url)
|
|
176
|
+
if success:
|
|
177
|
+
return requested_model
|
|
178
|
+
sys.exit(1)
|
|
179
|
+
|
|
180
|
+
# 2. User did not specify a model: check existing models in priority order
|
|
181
|
+
priority_order = [
|
|
182
|
+
"llama3.2-3b",
|
|
183
|
+
"llama3.2",
|
|
184
|
+
"qwen3.5:4b",
|
|
185
|
+
"qwen2.5:7b",
|
|
186
|
+
"qwen2.5:3b",
|
|
187
|
+
"qwen3.5",
|
|
188
|
+
"qwen",
|
|
189
|
+
"mistral",
|
|
190
|
+
"llama",
|
|
191
|
+
]
|
|
192
|
+
for prio in priority_order:
|
|
193
|
+
for m in installed:
|
|
194
|
+
if prio in m.lower():
|
|
195
|
+
return m
|
|
196
|
+
|
|
197
|
+
# If any other model is installed, use that
|
|
198
|
+
if installed:
|
|
199
|
+
return installed[0]
|
|
200
|
+
|
|
201
|
+
# 3. No models installed at all: auto-download default lightweight model!
|
|
202
|
+
console.print(f"\n[bold yellow]No local models found in your Ollama installation.[/bold yellow]")
|
|
203
|
+
console.print(f"[cyan]Automatically setting up recommended fast model: [bold]{DEFAULT_FALLBACK_MODEL}[/bold]...[/cyan]")
|
|
204
|
+
success = pull_model_with_progress(DEFAULT_FALLBACK_MODEL, base_url)
|
|
205
|
+
if success:
|
|
206
|
+
return DEFAULT_FALLBACK_MODEL
|
|
207
|
+
|
|
208
|
+
console.print("[red]Could not setup a local model. Please run `ollama pull llama3.2:3b` manually.[/red]")
|
|
209
|
+
sys.exit(1)
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: yt-clipper
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: 100% Free, Local AI YouTube Video Highlight Finder & Clipper powered by Ollama and FFmpeg
|
|
5
|
+
Author: Soham
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Keywords: youtube,clipper,highlights,ollama,llm,ffmpeg,video-editing,ai
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Operating System :: OS Independent
|
|
10
|
+
Classifier: Topic :: Multimedia :: Video
|
|
11
|
+
Classifier: Environment :: Console
|
|
12
|
+
Requires-Python: >=3.9
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
Requires-Dist: yt-dlp>=2026.11.0
|
|
15
|
+
Requires-Dist: youtube-transcript-api>=1.2.5
|
|
16
|
+
Requires-Dist: requests>=2.31.0
|
|
17
|
+
Requires-Dist: rich>=13.0.0
|
|
18
|
+
|
|
19
|
+
# 🎬 yt-clipper
|
|
20
|
+
|
|
21
|
+
> **100% Free, Local AI YouTube Video Highlight Finder & Clipper**
|
|
22
|
+
> *Zero subscriptions • Zero paid API keys • Auto-managed local models via Ollama & FFmpeg*
|
|
23
|
+
|
|
24
|
+
An open-source Python tool that ingests YouTube videos/podcasts/streams, identifies the best viral/highlight moments using a **Local LLM**, and automatically slices them into MP4 clips.
|
|
25
|
+
|
|
26
|
+
---
|
|
27
|
+
|
|
28
|
+
## ⚡ Key Highlights
|
|
29
|
+
|
|
30
|
+
- **Zero Setup Required:** If you don't have a model yet, `yt-clipper` automatically downloads a fast, high-quality model (e.g. `llama3.2:3b`) directly into Ollama with a live progress bar.
|
|
31
|
+
- **Fast Transcript Extraction:** Pulls accurate millisecond captions via `youtube-transcript-api` in seconds without downloading gigabytes of video.
|
|
32
|
+
- **Local AI Analysis:** Evaluates hooks, punchlines, debates, and emotional climaxes locally on your GPU/CPU via Ollama.
|
|
33
|
+
- **Instant Video Slicing:** Uses FFmpeg to cut MP4 clips (both fast stream-copy mode and frame-accurate mode).
|
|
34
|
+
- **Automated Metadata & Reports:** Saves `highlights_summary.json` and a clean Markdown table for editors.
|
|
35
|
+
|
|
36
|
+
---
|
|
37
|
+
|
|
38
|
+
## 📦 Installation
|
|
39
|
+
|
|
40
|
+
### From Source (Local Development)
|
|
41
|
+
```bash
|
|
42
|
+
git clone https://github.com/your-username/yt-clipper.git
|
|
43
|
+
cd yt-clipper
|
|
44
|
+
pip install -e .
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
### From Wheel / Tarball
|
|
48
|
+
```bash
|
|
49
|
+
pip install dist/yt_clipper-0.1.0-py3-none-any.whl
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
### Prerequisites
|
|
53
|
+
1. **Ollama:** Download and install from [ollama.com](https://ollama.com). (The tool will automatically start the background server and pull a model if you don't have one).
|
|
54
|
+
2. **FFmpeg:** Ensure `ffmpeg` is installed on your system PATH.
|
|
55
|
+
|
|
56
|
+
---
|
|
57
|
+
|
|
58
|
+
## 🚀 Quick Usage
|
|
59
|
+
|
|
60
|
+
Once installed, you can run `clipper` or `yt-clipper` from anywhere in your terminal:
|
|
61
|
+
|
|
62
|
+
### 1. Scan Highlights in Seconds (No Video Download)
|
|
63
|
+
Perfect for quickly checking if a 2-hour podcast has good moments before downloading:
|
|
64
|
+
```bash
|
|
65
|
+
clipper --url "https://www.youtube.com/watch?v=VIDEO_ID" --no-cut
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
### 2. Extract and Automatically Cut MP4 Clips
|
|
69
|
+
Analyzes the video and automatically saves sliced MP4 video files into `clips/`:
|
|
70
|
+
```bash
|
|
71
|
+
clipper --url "https://www.youtube.com/watch?v=VIDEO_ID" --min-score 8
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
### 3. Specify a Custom Model
|
|
75
|
+
```bash
|
|
76
|
+
clipper --url "https://youtu.be/..." --model "qwen3.5:4b"
|
|
77
|
+
```
|
|
78
|
+
*(If the specified model is not downloaded yet, `yt-clipper` will automatically pull it for you!)*
|
|
79
|
+
|
|
80
|
+
---
|
|
81
|
+
|
|
82
|
+
## ⚙️ Options & Arguments
|
|
83
|
+
|
|
84
|
+
| Flag | Shorthand | Default | Description |
|
|
85
|
+
| :--- | :---: | :---: | :--- |
|
|
86
|
+
| `--url` | `-u` | *(Prompt)* | YouTube URL or 11-char Video ID |
|
|
87
|
+
| `--min-score` | `-s` | `7` | Minimum highlight quality score (1–10) |
|
|
88
|
+
| `--model` | `-m` | Auto | Ollama model name (auto-selects or auto-downloads) |
|
|
89
|
+
| `--no-cut` | | `False` | Only extract timestamps and save reports; skip video download |
|
|
90
|
+
| `--fast-cut` | | `False` | Instant lossless stream copy (`-c copy`) without re-encoding |
|
|
91
|
+
| `--output-dir` | `-o` | `clips` | Directory to save clips and summaries |
|
|
92
|
+
| `--quality` | `-q` | `1080` | Max video height for downloaded video (e.g. 720, 1080) |
|
|
93
|
+
| `--chunk-size` | | `240` | Transcript context window size in seconds |
|
|
94
|
+
|
|
95
|
+
---
|
|
96
|
+
|
|
97
|
+
## 📂 Output Folder Structure
|
|
98
|
+
|
|
99
|
+
When processing with clipping enabled:
|
|
100
|
+
```
|
|
101
|
+
clips/
|
|
102
|
+
├── highlights_summary.json # Structured JSON metadata
|
|
103
|
+
├── highlights_summary.md # Markdown table of timestamps & hooks
|
|
104
|
+
├── source/
|
|
105
|
+
│ └── [video_id].mp4 # Downloaded source video
|
|
106
|
+
└── clips/
|
|
107
|
+
├── clip_01_sample_highlight.mp4
|
|
108
|
+
├── clip_02_sample_highlight.mp4
|
|
109
|
+
└── ...
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
---
|
|
113
|
+
|
|
114
|
+
## 📄 License
|
|
115
|
+
MIT License. Free for personal and commercial use.
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
README.md
|
|
2
|
+
pyproject.toml
|
|
3
|
+
src/yt_clipper/__init__.py
|
|
4
|
+
src/yt_clipper/analyzer.py
|
|
5
|
+
src/yt_clipper/cli.py
|
|
6
|
+
src/yt_clipper/cutter.py
|
|
7
|
+
src/yt_clipper/ingest.py
|
|
8
|
+
src/yt_clipper/ollama_manager.py
|
|
9
|
+
src/yt_clipper.egg-info/PKG-INFO
|
|
10
|
+
src/yt_clipper.egg-info/SOURCES.txt
|
|
11
|
+
src/yt_clipper.egg-info/dependency_links.txt
|
|
12
|
+
src/yt_clipper.egg-info/entry_points.txt
|
|
13
|
+
src/yt_clipper.egg-info/requires.txt
|
|
14
|
+
src/yt_clipper.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
yt_clipper
|