Datasets:
The dataset viewer is not available for this split.
Server error while post-processing the split rows. Please report the issue.
Error code: RowsPostProcessingError
Need help to make the dataset viewer work? Make sure to review how to configure the dataset viewer, and open a discussion for direct support.
🔵 ZackDFilms / YT Shorts
Script Used to create this:
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()
- Downloads last month
- 171