File size: 7,794 Bytes
08f140e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
---
task_categories:
- text-to-video
language:
- en
tags:
- art
size_categories:
- n<1K
---

# 🔵 ZackDFilms / YT Shorts
## Script Used to create this:
```python
import os
import re
import json
from pathlib import Path
from typing import Optional, Dict, Any, List

import yt_dlp


CHANNEL_SHORTS_URL = "https://www.youtube.com/@zackdfilms/shorts"

BASE_DIR = Path(r"C:\Users\User\Desktop\zackdfilms")
SHORTS_DIR = BASE_DIR / "shorts"
DATASET_PATH = BASE_DIR / "data.json"

TARGET_COUNT = 576


def round_to_thousands(n: Optional[int]) -> Optional[int]:
    if n is None:
        return None
    # "с точностью до тысяч" -> округление до ближайшей 1000
    return int(round(n / 1000.0) * 1000)


_vtt_timestamp = re.compile(r"^\d{2}:\d{2}:\d{2}\.\d{3}\s-->\s\d{2}:\d{2}:\d{2}\.\d{3}")
_vtt_header = re.compile(r"^WEBVTT")


def vtt_to_text(vtt_content: str) -> str:
    """
    Простой VTT -> текст:
    - убирает заголовок/таймкоды/служебные строки
    - чистит теги <...>
    - склеивает в одну строку
    - убирает подряд идущие дубликаты
    """
    lines = []
    for raw in vtt_content.splitlines():
        s = raw.strip()
        if not s:
            continue
        if _vtt_header.match(s):
            continue
        if _vtt_timestamp.match(s):
            continue
        if s.isdigit():  # номер cue
            continue
        if s.startswith("NOTE") or s.startswith("STYLE") or s.startswith("REGION"):
            continue
        s = re.sub(r"<[^>]+>", "", s)  # убрать теги
        s = s.replace("\u200b", "").strip()
        if s:
            lines.append(s)

    # убрать подряд повторяющиеся строки
    dedup = []
    prev = None
    for s in lines:
        if s != prev:
            dedup.append(s)
        prev = s

    text = " ".join(dedup)
    text = re.sub(r"\s+", " ", text).strip()
    return text


def read_text_file(path: Path) -> str:
    # VTT обычно UTF-8, но бывает с BOM
    return path.read_text(encoding="utf-8-sig", errors="replace")


def pick_subtitle_path(info: Dict[str, Any], expected_basename: str, out_dir: Path) -> Optional[Path]:
    """
    yt-dlp создаст файл субтитров рядом с видео по шаблону outtmpl.
    Мы используем отдельный outtmpl под каждый ролик, поэтому ожидаем:
    - <basename>.en.vtt
    - <basename>.en-US.vtt (и т.п.)
    - иногда .en.auto.vtt / похожие варианты
    """
    candidates = list(out_dir.glob(f"{expected_basename}.en*.vtt"))
    if not candidates:
        return None
    # предпочтение: не auto (если есть)
    non_auto = [p for p in candidates if ".auto." not in p.name]
    return non_auto[0] if non_auto else candidates[0]


def extract_playlist_entries(url: str, limit: int) -> List[Dict[str, Any]]:
    ydl_opts = {
        "quiet": True,
        "no_warnings": True,
        "extract_flat": "in_playlist",
        "playlistend": limit,
        # для стабильности
        "noplaylist": False,
    }
    with yt_dlp.YoutubeDL(ydl_opts) as ydl:
        info = ydl.extract_info(url, download=False)
    entries = info.get("entries") or []
    return [e for e in entries if e]  # убрать None


def download_one(video_url: str, out_mp4: Path) -> Dict[str, Any]:
    """
    Скачивает видео+аудио (до 720p) и субтитры (en, обычные или авто).
    Возвращает info_dict (с метаданными).
    """
    out_base = out_mp4.with_suffix("")  # без расширения
    outtmpl = str(out_base) + ".%(ext)s"

    ydl_opts = {
        "quiet": True,
        "no_warnings": True,

        # видео до 720p + звук, с попыткой mp4/m4a
        "format": "bestvideo[height<=720][ext=mp4]+bestaudio[ext=m4a]/best[height<=720][ext=mp4]/best[height<=720]",

        # принудительно mp4 на выходе (если возможно через remux)
        "merge_output_format": "mp4",
        "outtmpl": outtmpl,

        # субтитры: сначала обычные, иначе авто
        "writesubtitles": True,
        "writeautomaticsub": True,
        "subtitleslangs": ["en", "en.*"],
        "subtitlesformat": "vtt",

        # меньше мусора
        "postprocessors": [
            {"key": "FFmpegVideoRemuxer", "preferedformat": "mp4"},
        ],

        # сеть/ретраи
        "retries": 10,
        "fragment_retries": 10,
        "concurrent_fragment_downloads": 4,

        # иногда полезно:
        # "cookiesfrombrowser": ("chrome",),  # если нужно (авторизация/ограничения)
    }

    with yt_dlp.YoutubeDL(ydl_opts) as ydl:
        info = ydl.extract_info(video_url, download=True)
    return info


def main():
    BASE_DIR.mkdir(parents=True, exist_ok=True)
    SHORTS_DIR.mkdir(parents=True, exist_ok=True)

    entries = extract_playlist_entries(CHANNEL_SHORTS_URL, TARGET_COUNT)
    if not entries:
        raise RuntimeError("Не удалось получить список Shorts. Проверь URL или доступность YouTube.")

    dataset = []
    downloaded = 0
    seq = 1

    for e in entries:
        if downloaded >= TARGET_COUNT:
            break

        # e может быть с id и url
        video_id = e.get("id")
        video_url = e.get("url") or (f"https://www.youtube.com/watch?v={video_id}" if video_id else None)
        if not video_url:
            continue

        filename = f"{seq:04d}.mp4"
        out_mp4 = SHORTS_DIR / filename

        # если уже есть файл — пропускаем и всё равно пишем запись (по возможности)
        if out_mp4.exists() and out_mp4.stat().st_size > 0:
            # метаданные в этом случае не знаем; лучше всё же извлечь info без скачивания
            with yt_dlp.YoutubeDL({"quiet": True, "no_warnings": True}) as ydl:
                info = ydl.extract_info(video_url, download=False)
        else:
            try:
                info = download_one(video_url, out_mp4)
            except Exception as ex:
                print(f"[SKIP] Ошибка скачивания {video_url}: {ex}")
                continue

        # subtitles: ищем созданный vtt рядом с видео и парсим
        base_name = f"{seq:04d}"
        sub_path = pick_subtitle_path(info, base_name, SHORTS_DIR)
        subtitles_text = ""
        if sub_path and sub_path.exists():
            try:
                subtitles_text = vtt_to_text(read_text_file(sub_path))
            except Exception:
                subtitles_text = ""
            # можно удалить .vtt, если не нужен
            try:
                sub_path.unlink(missing_ok=True)
            except Exception:
                pass

        view_count = info.get("view_count")
        views_rounded = round_to_thousands(view_count if isinstance(view_count, int) else None)

        dataset.append({
            "subtitles": subtitles_text,
            "filepath": f"shorts/{filename}",
            "views": views_rounded,
        })

        downloaded += 1
        seq += 1

        print(f"[OK] {downloaded}/{TARGET_COUNT} -> {filename}")

    DATASET_PATH.write_text(json.dumps(dataset, ensure_ascii=False, indent=2), encoding="utf-8")
    print(f"\nГотово. Скачано: {downloaded}. Dataset: {DATASET_PATH}")


if __name__ == "__main__":
    main()
```