YouTube Transcript Fetcher (YTT)
YouTube Transcript Fetcher
Получайте транскрипты любого видео на YouTube с помощью транскрипции Whisper AI. Ищите видео на YouTube и получайте транскрипты для лучших результатов. API-ключ YouTube не требуется.
Возможности
На базе Whisper — передовая транскрипция на базе ИИ, точность более 99%
Поиск по YouTube — поиск видео на YouTube и получение транскриптов для лучших результатов
API-ключ не нужен — работает без учетных данных YouTube Data API
Множество форматов — вывод в виде текста, JSON, SRT, VTT
Кэширование — кэш на базе SQLite позволяет избежать повторной транскрипции
Без ограничений скорости — Whisper работает локально, нет ограничений внешнего API
CLI и библиотека — используйте как инструмент командной строки или модуль Python
MCP-сервер — интеграция с ИИ-инструментами через протокол Model Context Protocol
Related MCP server: youtube-mcp
Установка
# Clone the repository
git clone https://github.com/andrewctf/ytt.git
cd ytt
# Create virtual environment
python -m venv .venv
source .venv/bin/activate # Linux/Mac
.venv\Scripts\activate # Windows
# Install dependencies
pip install -r requirements.txt
# Optional: GPU support
pip install torch torchvision --index-url https://download.pytorch.org/whl/cu128Примечание: Подробную информацию о настройке GPU/CUDA см. в QUICKSTART.md.
Дополнительная настройка для Whisper
Whisper требует ffmpeg для извлечения аудио:
Windows (с помощью winget):
winget install ffmpegmacOS:
brew install ffmpegLinux:
sudo apt install ffmpegБыстрый старт
Подробные инструкции по установке и настройке см. в QUICKSTART.md.
CLI
# Get transcript (Whisper is used by default)
python cli.py transcript VIDEO_ID
# Or with a full YouTube URL
python cli.py transcript "https://www.youtube.com/watch?v=a1JTPFfshI0"
# Different output formats
python cli.py transcript VIDEO_ID --format json
python cli.py transcript VIDEO_ID --format srt
python cli.py transcript VIDEO_ID --format vtt
# Save to file
python cli.py transcript VIDEO_ID --output transcript.txt
# Batch processing
python cli.py transcript VIDEO_ID1 VIDEO_ID2 VIDEO_ID3
# Search YouTube for videos and get transcripts
python cli.py search "Python tutorial" --limit 5 --with-transcripts
# Search only (no transcripts)
python cli.py search "Python tutorial" --limit 10
# JSON output for search
python cli.py search "Python tutorial" --format json
# Cache management
python cli.py cache-stats
python cli.py cache-stats --clean # Remove expired entriesБиблиотека Python
from src.service import get_transcript
from src.search_service import search, search_and_get_transcripts
# Basic usage
result = await get_transcript("VIDEO_ID")
print(result.content)
# With options
result = await get_transcript(
"VIDEO_ID",
language="en",
output_format="json",
use_cache=True,
)
# Access metadata
print(f"Source: {result.source}") # 'whisper' or 'innertube'
print(f"Language: {result.language}") # Detected language
print(f"Video ID: {result.video_id}")
# Search YouTube for videos
results = await search("Python tutorial", max_results=5)
for video in results:
print(f"{video.title} ({video.video_id}) - {video.channel_name}")
# Search and get transcripts for results
results = await search_and_get_transcripts("Python tutorial", max_results=3, language="en")
for video, transcript in results:
if transcript:
print(f"{video.title}: {transcript.content[:100]}...")Для синхронного использования:
import asyncio
from src.service import get_transcript
from src.search_service import search
def fetch_transcript(video_id):
return asyncio.run(get_transcript(video_id))
def search_videos(query, max_results=5):
return asyncio.run(search(query, max_results=max_results))
result = fetch_transcript("VIDEO_ID")
print(result.content)
videos = search_videos("Python tutorial")MCP-сервер
Примечание: См. QUICKSTART.md для подробной настройки с Claude Desktop, Cursor и VS Code.
Запустите MCP-сервер:
python -m mcp_server.serverСервер предоставляет три инструмента:
get_transcript— получение транскрипта для одного видеоget_transcripts_batch— одновременное получение транскриптов для нескольких видеоsearch_videos— поиск видео на YouTube по запросу
Или интегрируйте с Claude Desktop, добавив в настройки MCP:
{
"mcpServers": {
"yt-transcript": {
"command": "python",
"args": ["-m", "mcp_server.server"],
"cwd": "/absolute/path/to/ytt"
}
}
}Как это работает
Video ID → Cache Check
↓ found?
Return Cached
↓ not found
Whisper (primary)
- Download audio via yt-dlp
- Transcribe with faster-whisper
- Returns word-level timestamps
↓ fails?
Innertube API (fallback)
- Extract API key from video page
- Fetch caption tracks
- Parse JSON3 timed text
↓
Cache Result
↓
Format & ReturnWhisper (основной метод)
Загружает аудио с помощью
yt-dlpТранскрибирует с помощью
faster-whisper(оптимизировано для CPU)Возвращает временные метки для каждого слова и текст сегментов
Работает с любым видео, содержащим аудио
Скорость обработки ~1-3x от реального времени
Innertube API (резервный метод)
Парсит внутренний API YouTube
API-ключ не требуется
Быстро (~0.5-2 сек на видео)
Покрытие ~85% (некоторые видео не имеют субтитров)
Ограничение скорости (~5 запросов/10 сек на IP)
Форматы вывода
Текст (по умолчанию)
Good morning, here we are, a live suturing course like nobody else has ever
done and what are we covering, we're covering every suturing technique...JSON
{
"video_id": "a1JTPFfshI0",
"language": "en",
"source": "whisper",
"segments": [
{"start": 0.0, "end": 4.5, "text": "Good morning, here we are..."},
{"start": 4.5, "end": 9.2, "text": "a live suturing course..."}
]
}SRT (SubRip)
1
00:00:00,000 --> 00:00:04,500
Good morning, here we are, a live suturing course...
2
00:00:04,500 --> 00:00:09,200
a live suturing course like nobody else...VTT (WebVTT)
WEBVTT
00:00:00.000 --> 00:00:04.500
Good morning, here we are, a live suturing course...
00:00:04.500 --> 00:00:09.200
a live suturing course like nobody else...Конфигурация
Отредактируйте config.py для настройки поведения:
class Config:
# Whisper settings
WHISPER_MODEL = "base" # tiny/base/small/medium/large
WHISPER_FALLBACK_ENABLED = True
# Cache settings
CACHE_TTL_DAYS = 7
CACHE_DB_PATH = ".transcript_cache.db"
# Rate limiting (for Innertube fallback)
RATE_LIMIT_RATE = 0.5 # tokens per second
RATE_LIMIT_BURST = 5 # max bucket size
# Batch processing
MAX_BATCH_SIZE = 50Модели Whisper
Модель | Скорость | Точность | Память |
tiny | 10x | ~75% | ~1ГБ |
base | 7x | ~85% | ~1ГБ |
small | 4x | ~90% | ~2ГБ |
medium | 2x | ~95% | ~5ГБ |
large | 1x | ~97% | ~6ГБ |
Модель base рекомендуется для большинства случаев — она быстрая и достаточно точная.
Структура файлов
ytt/
├── src/
│ ├── __init__.py
│ ├── fetcher.py # Innertube API client
│ ├── whisper_runner.py # Whisper transcription
│ ├── parser.py # Caption parsing utilities
│ ├── formatters.py # Output formatters
│ ├── cache.py # SQLite cache
│ ├── rate_limiter.py # Token bucket
│ ├── service.py # Orchestrator
│ ├── searcher.py # YouTube search
│ ├── search_cache.py # Search result cache
│ ├── search_service.py # Search orchestrator
│ ├── cuda_dll_manager.py # Auto-download CUDA libraries
│ └── exceptions.py # Custom exceptions
├── mcp_server/
│ ├── __init__.py
│ └── server.py # FastMCP server
├── cli.py # CLI entrypoint
├── main.py # Library entrypoint
├── config.py # Configuration
├── requirements.txt # Core dependencies
├── requirements-mcp.txt # MCP dependencies
├── README.md
└── QUICKSTART.mdУстранение неполадок
"No module named 'rich'"
Установите зависимости:
pip install -r requirements.txtWhisper выдает ошибку "ffmpeg not found"
Установите ffmpeg (см. раздел Установка выше).
Низкая скорость транскрипции
Используйте меньшую модель Whisper (
baseвместоlarge)Используйте ускорение GPU, изменив
device="cpu"наdevice="cuda"вwhisper_runner.pyВключите кэш, чтобы избежать повторной транскрипции
Ограничение скорости от Innertube
Резервный метод Innertube ограничен YouTube (~5 запросов/10 сек). Используйте Whisper в качестве основного (по умолчанию), чтобы избежать этого. Кэш также предотвращает избыточные запросы.
Кэш не работает
Проверьте статистику кэша:
python cli.py cache-statsОчистите устаревшие записи:
python cli.py cache-stats --cleanРазработка
Запуск тестов
pytestФорматирование кода
black src/
ruff check src/Лицензия
Лицензия MIT
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections. Dates show when Glama detected each change.
No tool schema history has been recorded yet.
This server cannot be installed
Maintenance
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
Related MCP Connectors
An MCP server that gives any LLM or agent clean YouTube transcripts on demand: a single video, a whole channel, or a playlist, plus AI cleanup of auto-generated captions. API-key auth, credit-based, same backend as the public v1 API. Get a free API key with 25 free credits at youtubetranscriptdownload.com/account.
An MCP server that provides tools to discover and retrieve podcast episodes transcripts.
MCP server for RiverScript, an AI transcription platform - fetches transcripts shared via a link.
An MCP server that provides congressional transcripts
Related MCP Servers
- AlicenseAqualityDmaintenanceAn MCP server that enables users to retrieve YouTube transcripts and perform video or channel searches without requiring Google API keys. It supports transcript chunking and provides tools for detailed video content analysis and channel metadata extraction.5584MIT
- AlicenseAqualityCmaintenanceAn MCP server that enables the extraction of transcripts and detailed metadata from YouTube videos. It allows users to retrieve video information like titles and descriptions, as well as transcripts with optional timestamps and language selection.2MIT
- AlicenseBqualityDmaintenanceAn MCP server designed to fetch transcripts for YouTube videos. It enables AI tools to access video text content for tasks like summarization, analysis, and key takeaway extraction.173MIT
- FlicenseNot gradedqualityDmaintenanceThis MCP server fetches and extracts transcripts from YouTube videos, enabling AI language models to access and analyze video content.1-
Latest Blog Posts
- Who's Calling? MCP Hosts Are an Identity Blind Spot (And the Spec Knows It)By Om-Shree-0709 on .mcpAgent IdentityOAuth 2.1
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/AndrewCTF/YTT'
If you have feedback or need assistance with the MCP directory API, please join our Discord server