youtube-transcript-cloud 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.
- youtube_transcript_cloud-0.1.0/.github/workflows/release.yml +35 -0
- youtube_transcript_cloud-0.1.0/.gitignore +4 -0
- youtube_transcript_cloud-0.1.0/LICENSE +21 -0
- youtube_transcript_cloud-0.1.0/PKG-INFO +135 -0
- youtube_transcript_cloud-0.1.0/README.md +118 -0
- youtube_transcript_cloud-0.1.0/pyproject.toml +35 -0
- youtube_transcript_cloud-0.1.0/server.json +29 -0
- youtube_transcript_cloud-0.1.0/src/youtube_transcript_cloud/__init__.py +20 -0
- youtube_transcript_cloud-0.1.0/src/youtube_transcript_cloud/api.py +250 -0
- youtube_transcript_cloud-0.1.0/src/youtube_transcript_cloud/cli.py +49 -0
- youtube_transcript_cloud-0.1.0/src/youtube_transcript_cloud/formatters.py +84 -0
- youtube_transcript_cloud-0.1.0/src/youtube_transcript_cloud/server.py +98 -0
- youtube_transcript_cloud-0.1.0/tests/test_api.py +111 -0
- youtube_transcript_cloud-0.1.0/tests/test_cli.py +17 -0
- youtube_transcript_cloud-0.1.0/tests/test_formatters.py +24 -0
- youtube_transcript_cloud-0.1.0/tests/test_server.py +47 -0
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
# Run by hand from the Actions tab: tests, then the package to PyPI (a trusted publisher, through this run's
|
|
2
|
+
# GitHub OIDC token), then server.json to the official MCP Registry (namespace io.github.<owner>, the same
|
|
3
|
+
# token). No secret is kept. A release is the version in __init__.py and server.json, raised in both.
|
|
4
|
+
name: Release
|
|
5
|
+
on: workflow_dispatch
|
|
6
|
+
permissions:
|
|
7
|
+
id-token: write
|
|
8
|
+
contents: read
|
|
9
|
+
jobs:
|
|
10
|
+
pypi:
|
|
11
|
+
runs-on: ubuntu-latest
|
|
12
|
+
steps:
|
|
13
|
+
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
|
|
14
|
+
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
|
|
15
|
+
with:
|
|
16
|
+
python-version: "3.12"
|
|
17
|
+
- run: pip install build pytest && python -m pytest -q tests && python -m build
|
|
18
|
+
- uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3
|
|
19
|
+
registry:
|
|
20
|
+
needs: pypi
|
|
21
|
+
runs-on: ubuntu-latest
|
|
22
|
+
env:
|
|
23
|
+
VERSION: v1.8.11
|
|
24
|
+
SHA256: 99fbd857ae2277e5e4a4a2cddc7f4d3e64612c6f90950f44584c3539c9df854f
|
|
25
|
+
steps:
|
|
26
|
+
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
|
|
27
|
+
- name: Install mcp-publisher
|
|
28
|
+
run: |
|
|
29
|
+
curl -sSfL -o mcp-publisher.tar.gz "https://github.com/modelcontextprotocol/registry/releases/download/$VERSION/mcp-publisher_linux_amd64.tar.gz"
|
|
30
|
+
echo "$SHA256 mcp-publisher.tar.gz" | sha256sum -c -
|
|
31
|
+
tar xzf mcp-publisher.tar.gz mcp-publisher
|
|
32
|
+
- run: ./mcp-publisher login github-oidc
|
|
33
|
+
- name: Publish, once PyPI shows the new version
|
|
34
|
+
run: |
|
|
35
|
+
for i in 1 2 3 4 5 6; do ./mcp-publisher publish && exit 0; sleep 30; done; exit 1
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Spyridon Pikoulas
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: youtube-transcript-cloud
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: YouTube transcripts that keep working on AWS, GCP, Vercel and other cloud servers: compatible with youtube-transcript-api, read through an Apify Actor, with a CLI and an MCP server
|
|
5
|
+
Project-URL: Homepage, https://github.com/Spyridon-Pikoulas/youtube-transcript-cloud
|
|
6
|
+
Project-URL: Actor, https://apify.com/pikoulas/youtube-transcripts
|
|
7
|
+
Author: Spyridon Pikoulas
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: apify,captions,llm,mcp,rag,subtitles,transcript,youtube,youtube-transcript,youtube-transcript-api
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Topic :: Multimedia :: Video
|
|
14
|
+
Classifier: Topic :: Text Processing
|
|
15
|
+
Requires-Python: >=3.9
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
|
|
18
|
+
# youtube-transcript-cloud
|
|
19
|
+
|
|
20
|
+
YouTube transcripts from Python, the command line or an AI agent that keep working on AWS, GCP,
|
|
21
|
+
Azure, Vercel and other cloud servers, where YouTube blocks most direct requests (`RequestBlocked`,
|
|
22
|
+
`IpBlocked`). The interface is compatible with
|
|
23
|
+
[youtube-transcript-api](https://github.com/jdepoix/youtube-transcript-api)'s, so moving over is
|
|
24
|
+
an import line. The transcripts are read by the
|
|
25
|
+
[YouTube Transcript Scraper](https://apify.com/pikoulas/youtube-transcripts) on Apify, with your
|
|
26
|
+
Apify API token. No proxy to buy or manage.
|
|
27
|
+
|
|
28
|
+
<!-- mcp-name: io.github.Spyridon-Pikoulas/youtube-transcript-cloud -->
|
|
29
|
+
|
|
30
|
+
## Install
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
pip install youtube-transcript-cloud
|
|
34
|
+
# or from GitHub
|
|
35
|
+
pip install git+https://github.com/Spyridon-Pikoulas/youtube-transcript-cloud
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
No dependencies beyond the standard library, Python 3.9 and newer. Get a token at
|
|
39
|
+
[apify.com](https://apify.com) (free sign-up), under **Settings → API & Integrations**, and set it
|
|
40
|
+
as `APIFY_TOKEN`.
|
|
41
|
+
|
|
42
|
+
## Python
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
from youtube_transcript_cloud import YouTubeTranscriptApi
|
|
46
|
+
|
|
47
|
+
ytt_api = YouTubeTranscriptApi() # or YouTubeTranscriptApi(apify_token="...")
|
|
48
|
+
transcript = ytt_api.fetch("dQw4w9WgXcQ", languages=["de", "en"])
|
|
49
|
+
|
|
50
|
+
for snippet in transcript:
|
|
51
|
+
print(snippet.start, snippet.text)
|
|
52
|
+
|
|
53
|
+
transcript.language_code, transcript.is_generated
|
|
54
|
+
transcript.to_raw_data() # [{"text": "...", "start": 0.0, "duration": 1.54}, ...]
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Moving from youtube-transcript-api:
|
|
58
|
+
|
|
59
|
+
```python
|
|
60
|
+
# from youtube_transcript_api import YouTubeTranscriptApi
|
|
61
|
+
from youtube_transcript_cloud import YouTubeTranscriptApi
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
Many videos in one call, read in a single run:
|
|
65
|
+
|
|
66
|
+
```python
|
|
67
|
+
results = ytt_api.fetch_all(["dQw4w9WgXcQ", "https://youtu.be/jNQXAC9IVRw"])
|
|
68
|
+
# {video_id: FetchedTranscript, or the error it raised}
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
The caption tracks a video has:
|
|
72
|
+
|
|
73
|
+
```python
|
|
74
|
+
for t in ytt_api.list("dQw4w9WgXcQ"):
|
|
75
|
+
print(t.language_code, t.language, t.is_generated)
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
`find_transcript`, `find_manually_created_transcript` and `find_generated_transcript` work as you
|
|
79
|
+
know them. Formatters too: `JSONFormatter`, `PrettyPrintFormatter`, `TextFormatter`, `SRTFormatter`
|
|
80
|
+
and `WebVTTFormatter` from `youtube_transcript_cloud.formatters`. The errors have the same names:
|
|
81
|
+
`NoTranscriptFound`, `TranscriptsDisabled`, `VideoUnavailable`, `RequestBlocked`, all subclasses of
|
|
82
|
+
`CouldNotRetrieveTranscript`. `ApifyError` means Apify refused the call (a wrong token, no credit).
|
|
83
|
+
|
|
84
|
+
`ytt_api.run(videos)` gives the Actor's own items: title, channel, publish date, views, duration,
|
|
85
|
+
language and text with each video.
|
|
86
|
+
|
|
87
|
+
## Command line
|
|
88
|
+
|
|
89
|
+
```bash
|
|
90
|
+
youtube-transcript-cloud dQw4w9WgXcQ https://youtu.be/jNQXAC9IVRw --languages de en --format json > transcripts.json
|
|
91
|
+
youtube-transcript-cloud --list-transcripts dQw4w9WgXcQ
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
Formats: `pretty` (default), `json`, `text`, `srt`, `webvtt`.
|
|
95
|
+
|
|
96
|
+
## AI agents (MCP)
|
|
97
|
+
|
|
98
|
+
`youtube-transcript-cloud mcp` is an MCP server on stdio with one tool, `get_youtube_transcript`
|
|
99
|
+
(a video URL or ID, preferred languages, optional timestamps). For Claude Desktop, Cursor and
|
|
100
|
+
other MCP clients:
|
|
101
|
+
|
|
102
|
+
```json
|
|
103
|
+
{
|
|
104
|
+
"mcpServers": {
|
|
105
|
+
"youtube-transcripts": {
|
|
106
|
+
"command": "uvx",
|
|
107
|
+
"args": ["youtube-transcript-cloud", "mcp"],
|
|
108
|
+
"env": {"APIFY_TOKEN": "YOUR_APIFY_TOKEN"}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
## What it costs
|
|
115
|
+
|
|
116
|
+
The Actor charges $0.001 per transcript ($1 per 1,000) to your Apify account. Videos without
|
|
117
|
+
captions and failed reads are free. When YouTube blocks a run, it switches to Apify's residential
|
|
118
|
+
proxy and its traffic is charged too, about $0.0002 a transcript. Apify's free plan includes
|
|
119
|
+
monthly credit that covers a few thousand transcripts.
|
|
120
|
+
|
|
121
|
+
## Differences from youtube-transcript-api
|
|
122
|
+
|
|
123
|
+
- Video URLs (watch, youtu.be, Shorts, embed, live) work wherever a video ID does.
|
|
124
|
+
- A language matches its regional variants: `en` finds `en-GB`.
|
|
125
|
+
- `translate()` raises `NotTranslatable`: translated captions aren't offered.
|
|
126
|
+
- `list()` reads one transcript to see the tracks, so it costs one; `fetch()` on that track then
|
|
127
|
+
costs nothing more.
|
|
128
|
+
- There are no proxy or cookie options: the requests go out from Apify.
|
|
129
|
+
- `preserve_formatting` is accepted and has no effect.
|
|
130
|
+
|
|
131
|
+
This project is not affiliated with youtube-transcript-api or YouTube.
|
|
132
|
+
|
|
133
|
+
## License
|
|
134
|
+
|
|
135
|
+
MIT
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
# youtube-transcript-cloud
|
|
2
|
+
|
|
3
|
+
YouTube transcripts from Python, the command line or an AI agent that keep working on AWS, GCP,
|
|
4
|
+
Azure, Vercel and other cloud servers, where YouTube blocks most direct requests (`RequestBlocked`,
|
|
5
|
+
`IpBlocked`). The interface is compatible with
|
|
6
|
+
[youtube-transcript-api](https://github.com/jdepoix/youtube-transcript-api)'s, so moving over is
|
|
7
|
+
an import line. The transcripts are read by the
|
|
8
|
+
[YouTube Transcript Scraper](https://apify.com/pikoulas/youtube-transcripts) on Apify, with your
|
|
9
|
+
Apify API token. No proxy to buy or manage.
|
|
10
|
+
|
|
11
|
+
<!-- mcp-name: io.github.Spyridon-Pikoulas/youtube-transcript-cloud -->
|
|
12
|
+
|
|
13
|
+
## Install
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
pip install youtube-transcript-cloud
|
|
17
|
+
# or from GitHub
|
|
18
|
+
pip install git+https://github.com/Spyridon-Pikoulas/youtube-transcript-cloud
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
No dependencies beyond the standard library, Python 3.9 and newer. Get a token at
|
|
22
|
+
[apify.com](https://apify.com) (free sign-up), under **Settings → API & Integrations**, and set it
|
|
23
|
+
as `APIFY_TOKEN`.
|
|
24
|
+
|
|
25
|
+
## Python
|
|
26
|
+
|
|
27
|
+
```python
|
|
28
|
+
from youtube_transcript_cloud import YouTubeTranscriptApi
|
|
29
|
+
|
|
30
|
+
ytt_api = YouTubeTranscriptApi() # or YouTubeTranscriptApi(apify_token="...")
|
|
31
|
+
transcript = ytt_api.fetch("dQw4w9WgXcQ", languages=["de", "en"])
|
|
32
|
+
|
|
33
|
+
for snippet in transcript:
|
|
34
|
+
print(snippet.start, snippet.text)
|
|
35
|
+
|
|
36
|
+
transcript.language_code, transcript.is_generated
|
|
37
|
+
transcript.to_raw_data() # [{"text": "...", "start": 0.0, "duration": 1.54}, ...]
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Moving from youtube-transcript-api:
|
|
41
|
+
|
|
42
|
+
```python
|
|
43
|
+
# from youtube_transcript_api import YouTubeTranscriptApi
|
|
44
|
+
from youtube_transcript_cloud import YouTubeTranscriptApi
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Many videos in one call, read in a single run:
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
results = ytt_api.fetch_all(["dQw4w9WgXcQ", "https://youtu.be/jNQXAC9IVRw"])
|
|
51
|
+
# {video_id: FetchedTranscript, or the error it raised}
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
The caption tracks a video has:
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
for t in ytt_api.list("dQw4w9WgXcQ"):
|
|
58
|
+
print(t.language_code, t.language, t.is_generated)
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
`find_transcript`, `find_manually_created_transcript` and `find_generated_transcript` work as you
|
|
62
|
+
know them. Formatters too: `JSONFormatter`, `PrettyPrintFormatter`, `TextFormatter`, `SRTFormatter`
|
|
63
|
+
and `WebVTTFormatter` from `youtube_transcript_cloud.formatters`. The errors have the same names:
|
|
64
|
+
`NoTranscriptFound`, `TranscriptsDisabled`, `VideoUnavailable`, `RequestBlocked`, all subclasses of
|
|
65
|
+
`CouldNotRetrieveTranscript`. `ApifyError` means Apify refused the call (a wrong token, no credit).
|
|
66
|
+
|
|
67
|
+
`ytt_api.run(videos)` gives the Actor's own items: title, channel, publish date, views, duration,
|
|
68
|
+
language and text with each video.
|
|
69
|
+
|
|
70
|
+
## Command line
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
youtube-transcript-cloud dQw4w9WgXcQ https://youtu.be/jNQXAC9IVRw --languages de en --format json > transcripts.json
|
|
74
|
+
youtube-transcript-cloud --list-transcripts dQw4w9WgXcQ
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
Formats: `pretty` (default), `json`, `text`, `srt`, `webvtt`.
|
|
78
|
+
|
|
79
|
+
## AI agents (MCP)
|
|
80
|
+
|
|
81
|
+
`youtube-transcript-cloud mcp` is an MCP server on stdio with one tool, `get_youtube_transcript`
|
|
82
|
+
(a video URL or ID, preferred languages, optional timestamps). For Claude Desktop, Cursor and
|
|
83
|
+
other MCP clients:
|
|
84
|
+
|
|
85
|
+
```json
|
|
86
|
+
{
|
|
87
|
+
"mcpServers": {
|
|
88
|
+
"youtube-transcripts": {
|
|
89
|
+
"command": "uvx",
|
|
90
|
+
"args": ["youtube-transcript-cloud", "mcp"],
|
|
91
|
+
"env": {"APIFY_TOKEN": "YOUR_APIFY_TOKEN"}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
## What it costs
|
|
98
|
+
|
|
99
|
+
The Actor charges $0.001 per transcript ($1 per 1,000) to your Apify account. Videos without
|
|
100
|
+
captions and failed reads are free. When YouTube blocks a run, it switches to Apify's residential
|
|
101
|
+
proxy and its traffic is charged too, about $0.0002 a transcript. Apify's free plan includes
|
|
102
|
+
monthly credit that covers a few thousand transcripts.
|
|
103
|
+
|
|
104
|
+
## Differences from youtube-transcript-api
|
|
105
|
+
|
|
106
|
+
- Video URLs (watch, youtu.be, Shorts, embed, live) work wherever a video ID does.
|
|
107
|
+
- A language matches its regional variants: `en` finds `en-GB`.
|
|
108
|
+
- `translate()` raises `NotTranslatable`: translated captions aren't offered.
|
|
109
|
+
- `list()` reads one transcript to see the tracks, so it costs one; `fetch()` on that track then
|
|
110
|
+
costs nothing more.
|
|
111
|
+
- There are no proxy or cookie options: the requests go out from Apify.
|
|
112
|
+
- `preserve_formatting` is accepted and has no effect.
|
|
113
|
+
|
|
114
|
+
This project is not affiliated with youtube-transcript-api or YouTube.
|
|
115
|
+
|
|
116
|
+
## License
|
|
117
|
+
|
|
118
|
+
MIT
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "youtube-transcript-cloud"
|
|
3
|
+
dynamic = ["version"]
|
|
4
|
+
description = "YouTube transcripts that keep working on AWS, GCP, Vercel and other cloud servers: compatible with youtube-transcript-api, read through an Apify Actor, with a CLI and an MCP server"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "MIT"
|
|
7
|
+
license-files = ["LICENSE"]
|
|
8
|
+
authors = [{ name = "Spyridon Pikoulas" }]
|
|
9
|
+
requires-python = ">=3.9"
|
|
10
|
+
dependencies = []
|
|
11
|
+
keywords = ["youtube", "youtube-transcript", "youtube-transcript-api", "transcript", "subtitles", "captions",
|
|
12
|
+
"mcp", "llm", "rag", "apify"]
|
|
13
|
+
classifiers = [
|
|
14
|
+
"Programming Language :: Python :: 3",
|
|
15
|
+
"Operating System :: OS Independent",
|
|
16
|
+
"Topic :: Multimedia :: Video",
|
|
17
|
+
"Topic :: Text Processing",
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
[project.urls]
|
|
21
|
+
Homepage = "https://github.com/Spyridon-Pikoulas/youtube-transcript-cloud"
|
|
22
|
+
Actor = "https://apify.com/pikoulas/youtube-transcripts"
|
|
23
|
+
|
|
24
|
+
[project.scripts]
|
|
25
|
+
youtube-transcript-cloud = "youtube_transcript_cloud.cli:main"
|
|
26
|
+
|
|
27
|
+
[build-system]
|
|
28
|
+
requires = ["hatchling>=1.27"]
|
|
29
|
+
build-backend = "hatchling.build"
|
|
30
|
+
|
|
31
|
+
[tool.hatch.version]
|
|
32
|
+
path = "src/youtube_transcript_cloud/__init__.py"
|
|
33
|
+
|
|
34
|
+
[tool.pytest.ini_options]
|
|
35
|
+
pythonpath = ["src"]
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
|
|
3
|
+
"name": "io.github.Spyridon-Pikoulas/youtube-transcript-cloud",
|
|
4
|
+
"title": "YouTube Transcripts (cloud)",
|
|
5
|
+
"description": "YouTube video and Shorts transcripts that work from cloud servers, read on Apify with your token",
|
|
6
|
+
"version": "0.1.0",
|
|
7
|
+
"repository": {
|
|
8
|
+
"url": "https://github.com/Spyridon-Pikoulas/youtube-transcript-cloud",
|
|
9
|
+
"source": "github"
|
|
10
|
+
},
|
|
11
|
+
"packages": [
|
|
12
|
+
{
|
|
13
|
+
"registryType": "pypi",
|
|
14
|
+
"identifier": "youtube-transcript-cloud",
|
|
15
|
+
"version": "0.1.0",
|
|
16
|
+
"runtimeHint": "uvx",
|
|
17
|
+
"transport": {"type": "stdio"},
|
|
18
|
+
"packageArguments": [{"type": "positional", "value": "mcp"}],
|
|
19
|
+
"environmentVariables": [
|
|
20
|
+
{
|
|
21
|
+
"name": "APIFY_TOKEN",
|
|
22
|
+
"description": "Your Apify API token, from Settings → API & Integrations at apify.com",
|
|
23
|
+
"isRequired": true,
|
|
24
|
+
"isSecret": true
|
|
25
|
+
}
|
|
26
|
+
]
|
|
27
|
+
}
|
|
28
|
+
]
|
|
29
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
|
2
|
+
|
|
3
|
+
from .api import ( # noqa: E402
|
|
4
|
+
ApifyError,
|
|
5
|
+
CouldNotRetrieveTranscript,
|
|
6
|
+
FetchedTranscript,
|
|
7
|
+
FetchedTranscriptSnippet,
|
|
8
|
+
NotTranslatable,
|
|
9
|
+
NoTranscriptFound,
|
|
10
|
+
RequestBlocked,
|
|
11
|
+
Transcript,
|
|
12
|
+
TranscriptList,
|
|
13
|
+
TranscriptsDisabled,
|
|
14
|
+
VideoUnavailable,
|
|
15
|
+
YouTubeTranscriptApi,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
__all__ = ["ApifyError", "CouldNotRetrieveTranscript", "FetchedTranscript", "FetchedTranscriptSnippet",
|
|
19
|
+
"NotTranslatable", "NoTranscriptFound", "RequestBlocked", "Transcript", "TranscriptList",
|
|
20
|
+
"TranscriptsDisabled", "VideoUnavailable", "YouTubeTranscriptApi"]
|
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
"""The client: each call is one run of the YouTube Transcript Scraper Actor on Apify, through its
|
|
2
|
+
run-sync-get-dataset-items endpoint, which returns the run's items when the run ends (up to 300 s)."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
import urllib.error
|
|
10
|
+
import urllib.request
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from typing import Iterable, Iterator
|
|
13
|
+
from urllib.parse import parse_qs, urlparse
|
|
14
|
+
|
|
15
|
+
from . import __version__
|
|
16
|
+
|
|
17
|
+
ACTOR = "pikoulas~youtube-transcripts"
|
|
18
|
+
ENDPOINT = "https://api.apify.com/v2/acts/{}/run-sync-get-dataset-items"
|
|
19
|
+
ID = re.compile(r"[\w-]{11}")
|
|
20
|
+
NO_CAPTIONS = "This video has no captions" # the start of the Actor's error for a video without any
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class ApifyError(Exception):
|
|
24
|
+
"""Apify refused the call: a wrong token, no credit left, or the run failing as a whole."""
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class CouldNotRetrieveTranscript(Exception):
|
|
28
|
+
def __init__(self, video_id: str, reason: str = ""):
|
|
29
|
+
self.video_id, self.reason = video_id, reason
|
|
30
|
+
super().__init__(f"Could not retrieve a transcript for the video {video_id}: {reason}".rstrip(": "))
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class NoTranscriptFound(CouldNotRetrieveTranscript):
|
|
34
|
+
def __init__(self, video_id: str, requested_language_codes: Iterable[str], available: list[dict]):
|
|
35
|
+
self.requested_language_codes = list(requested_language_codes)
|
|
36
|
+
self.available = available
|
|
37
|
+
have = ", ".join(f"{a['code']}{' (generated)' if a.get('autoGenerated') else ''}" for a in available)
|
|
38
|
+
super().__init__(video_id, f"none in {self.requested_language_codes}; it has {have}")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class TranscriptsDisabled(CouldNotRetrieveTranscript):
|
|
42
|
+
pass
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class VideoUnavailable(CouldNotRetrieveTranscript):
|
|
46
|
+
pass
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class RequestBlocked(CouldNotRetrieveTranscript):
|
|
50
|
+
pass
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class NotTranslatable(CouldNotRetrieveTranscript):
|
|
54
|
+
pass
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@dataclass
|
|
58
|
+
class FetchedTranscriptSnippet:
|
|
59
|
+
text: str
|
|
60
|
+
start: float
|
|
61
|
+
duration: float
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@dataclass
|
|
65
|
+
class FetchedTranscript:
|
|
66
|
+
snippets: list[FetchedTranscriptSnippet]
|
|
67
|
+
video_id: str
|
|
68
|
+
language: str
|
|
69
|
+
language_code: str
|
|
70
|
+
is_generated: bool
|
|
71
|
+
|
|
72
|
+
def __iter__(self) -> Iterator[FetchedTranscriptSnippet]:
|
|
73
|
+
return iter(self.snippets)
|
|
74
|
+
|
|
75
|
+
def __getitem__(self, index):
|
|
76
|
+
return self.snippets[index]
|
|
77
|
+
|
|
78
|
+
def __len__(self) -> int:
|
|
79
|
+
return len(self.snippets)
|
|
80
|
+
|
|
81
|
+
def to_raw_data(self) -> list[dict]:
|
|
82
|
+
return [{"text": s.text, "start": s.start, "duration": s.duration} for s in self.snippets]
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@dataclass
|
|
86
|
+
class Transcript:
|
|
87
|
+
"""A caption track the video has; `fetch()` reads it."""
|
|
88
|
+
video_id: str
|
|
89
|
+
language: str
|
|
90
|
+
language_code: str
|
|
91
|
+
is_generated: bool
|
|
92
|
+
is_translatable: bool = False
|
|
93
|
+
translation_languages: list = field(default_factory=list)
|
|
94
|
+
_api: YouTubeTranscriptApi | None = field(default=None, repr=False, compare=False)
|
|
95
|
+
_fetched: FetchedTranscript | None = field(default=None, repr=False, compare=False)
|
|
96
|
+
|
|
97
|
+
def fetch(self, preserve_formatting: bool = False) -> FetchedTranscript:
|
|
98
|
+
# The Actor takes a language, not a track: where a language has both, it reads the manual one.
|
|
99
|
+
return self._fetched or self._api.fetch(self.video_id, [self.language_code])
|
|
100
|
+
|
|
101
|
+
def translate(self, language_code: str):
|
|
102
|
+
raise NotTranslatable(self.video_id, "translation isn't offered")
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class TranscriptList:
|
|
106
|
+
def __init__(self, video_id: str, transcripts: list[Transcript]):
|
|
107
|
+
self.video_id, self.transcripts = video_id, transcripts
|
|
108
|
+
|
|
109
|
+
def __iter__(self) -> Iterator[Transcript]:
|
|
110
|
+
return iter(self.transcripts)
|
|
111
|
+
|
|
112
|
+
def find_transcript(self, language_codes: Iterable[str]) -> Transcript:
|
|
113
|
+
return self._find(language_codes, (False, True))
|
|
114
|
+
|
|
115
|
+
def find_manually_created_transcript(self, language_codes: Iterable[str]) -> Transcript:
|
|
116
|
+
return self._find(language_codes, (False,))
|
|
117
|
+
|
|
118
|
+
def find_generated_transcript(self, language_codes: Iterable[str]) -> Transcript:
|
|
119
|
+
return self._find(language_codes, (True,))
|
|
120
|
+
|
|
121
|
+
def _find(self, language_codes: Iterable[str], generated: tuple) -> Transcript:
|
|
122
|
+
codes = list(language_codes)
|
|
123
|
+
for code in codes:
|
|
124
|
+
for g in generated:
|
|
125
|
+
if t := next((t for t in self.transcripts if t.language_code == code and t.is_generated == g), None):
|
|
126
|
+
return t
|
|
127
|
+
raise NoTranscriptFound(self.video_id, codes, [{"code": t.language_code, "autoGenerated": t.is_generated}
|
|
128
|
+
for t in self.transcripts])
|
|
129
|
+
|
|
130
|
+
def __str__(self) -> str:
|
|
131
|
+
return "\n".join(f"{t.language_code} ({t.language}){' [generated]' if t.is_generated else ''}"
|
|
132
|
+
for t in self.transcripts)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def video_id_of(value: str) -> str:
|
|
136
|
+
"""A video ID from an ID or any YouTube video URL (watch, youtu.be, Shorts, embed, live)."""
|
|
137
|
+
value = value.strip()
|
|
138
|
+
if ID.fullmatch(value):
|
|
139
|
+
return value
|
|
140
|
+
u = urlparse(value if "://" in value else f"https://{value}")
|
|
141
|
+
if u.netloc.endswith("youtu.be"):
|
|
142
|
+
cand = u.path.strip("/").split("/")[0]
|
|
143
|
+
elif v := parse_qs(u.query).get("v"):
|
|
144
|
+
cand = v[0]
|
|
145
|
+
elif m := re.match(r"/(?:shorts|embed|live|v)/([\w-]{11})", u.path):
|
|
146
|
+
cand = m[1]
|
|
147
|
+
else:
|
|
148
|
+
cand = ""
|
|
149
|
+
if not ID.fullmatch(cand):
|
|
150
|
+
raise ValueError(f"{value!r} is not a YouTube video ID or URL")
|
|
151
|
+
return cand
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def base(code: str) -> str:
|
|
155
|
+
return code.split("-")[0].lower()
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
class YouTubeTranscriptApi:
|
|
159
|
+
"""Compatible with youtube-transcript-api's `YouTubeTranscriptApi`, the transcripts read on Apify
|
|
160
|
+
rather than from this machine's IP. The token is the argument or `APIFY_TOKEN`."""
|
|
161
|
+
|
|
162
|
+
def __init__(self, apify_token: str | None = None, timeout: float = 300, actor: str = ACTOR):
|
|
163
|
+
self.token = apify_token or os.environ.get("APIFY_TOKEN")
|
|
164
|
+
if not self.token:
|
|
165
|
+
raise ApifyError("No Apify API token: pass apify_token or set APIFY_TOKEN "
|
|
166
|
+
"(https://console.apify.com/settings/integrations)")
|
|
167
|
+
self.timeout, self.actor = timeout, actor
|
|
168
|
+
|
|
169
|
+
def run(self, videos: Iterable[str], languages: Iterable[str] = ("en",), timestamps: bool = True) -> list[dict]:
|
|
170
|
+
"""The Actor's own items, one per video: title, channel, views, language, text and, with
|
|
171
|
+
timestamps, segments; or an `error`."""
|
|
172
|
+
body = {"videos": [f"https://www.youtube.com/watch?v={video_id_of(v)}" for v in videos],
|
|
173
|
+
"languages": list(languages), "includeTimestamps": timestamps}
|
|
174
|
+
request = urllib.request.Request(
|
|
175
|
+
ENDPOINT.format(self.actor), data=json.dumps(body).encode(), method="POST",
|
|
176
|
+
headers={"Authorization": f"Bearer {self.token}", "Content-Type": "application/json",
|
|
177
|
+
"User-Agent": f"youtube-transcript-cloud/{__version__}"})
|
|
178
|
+
try:
|
|
179
|
+
with urllib.request.urlopen(request, timeout=self.timeout) as r:
|
|
180
|
+
return json.load(r)
|
|
181
|
+
except urllib.error.HTTPError as e:
|
|
182
|
+
try:
|
|
183
|
+
message = json.load(e)["error"]["message"]
|
|
184
|
+
except (ValueError, KeyError, TypeError):
|
|
185
|
+
message = e.reason
|
|
186
|
+
raise ApifyError(f"Apify answered {e.code}: {message}") from None
|
|
187
|
+
|
|
188
|
+
def fetch_all(self, video_ids: Iterable[str], languages: Iterable[str] = ("en",)) -> dict:
|
|
189
|
+
"""Each video's `FetchedTranscript`, or the `CouldNotRetrieveTranscript` it raised, by video ID,
|
|
190
|
+
all read in one run."""
|
|
191
|
+
ids, languages = [video_id_of(v) for v in video_ids], list(languages)
|
|
192
|
+
items = {i.get("videoId"): i for i in self.run(ids, languages)}
|
|
193
|
+
out = {}
|
|
194
|
+
for vid in ids:
|
|
195
|
+
try:
|
|
196
|
+
out[vid] = transcript_of(vid, items.get(vid), languages)
|
|
197
|
+
except CouldNotRetrieveTranscript as e:
|
|
198
|
+
out[vid] = e
|
|
199
|
+
return out
|
|
200
|
+
|
|
201
|
+
def fetch(self, video_id: str, languages: Iterable[str] = ("en",), preserve_formatting: bool = False) -> FetchedTranscript:
|
|
202
|
+
"""The first of `languages` the video has, manual captions before generated ones. Formatting
|
|
203
|
+
comes as YouTube's captions carry it; `preserve_formatting` is taken for compatibility."""
|
|
204
|
+
got = self.fetch_all([video_id], languages)[video_id_of(video_id)]
|
|
205
|
+
if isinstance(got, Exception):
|
|
206
|
+
raise got
|
|
207
|
+
return got
|
|
208
|
+
|
|
209
|
+
def list(self, video_id: str) -> TranscriptList:
|
|
210
|
+
"""The video's caption tracks. Reading them reads (and charges) one English-first transcript,
|
|
211
|
+
which the matching track returns from `fetch()` without a second run."""
|
|
212
|
+
vid = video_id_of(video_id)
|
|
213
|
+
item = self.run([vid], ["en"])[0]
|
|
214
|
+
failed(vid, item)
|
|
215
|
+
fetched = None
|
|
216
|
+
try:
|
|
217
|
+
fetched = transcript_of(vid, item, [item.get("language") or "en"])
|
|
218
|
+
except CouldNotRetrieveTranscript:
|
|
219
|
+
pass
|
|
220
|
+
tracks = [Transcript(vid, a.get("name") or a["code"], a["code"], bool(a.get("autoGenerated")), _api=self)
|
|
221
|
+
for a in item.get("availableLanguages") or []]
|
|
222
|
+
for t in tracks:
|
|
223
|
+
if fetched and t.language_code == fetched.language_code and t.is_generated == fetched.is_generated:
|
|
224
|
+
t._fetched = fetched
|
|
225
|
+
return TranscriptList(vid, tracks)
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def failed(vid: str, item: dict | None) -> None:
|
|
229
|
+
"""Raises what an item without a transcript says went wrong."""
|
|
230
|
+
if item is None:
|
|
231
|
+
raise CouldNotRetrieveTranscript(vid, "the run returned nothing for it")
|
|
232
|
+
if not (error := item.get("error")) or item.get("text"):
|
|
233
|
+
return
|
|
234
|
+
if error.startswith(NO_CAPTIONS):
|
|
235
|
+
raise TranscriptsDisabled(vid, error)
|
|
236
|
+
if "block" in error.lower():
|
|
237
|
+
raise RequestBlocked(vid, error)
|
|
238
|
+
if not item.get("title"):
|
|
239
|
+
raise VideoUnavailable(vid, error)
|
|
240
|
+
raise CouldNotRetrieveTranscript(vid, error)
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def transcript_of(vid: str, item: dict | None, languages: list[str]) -> FetchedTranscript:
|
|
244
|
+
failed(vid, item)
|
|
245
|
+
code = item.get("language") or ""
|
|
246
|
+
if base(code) not in {base(c) for c in languages}:
|
|
247
|
+
raise NoTranscriptFound(vid, languages, item.get("availableLanguages") or [])
|
|
248
|
+
return FetchedTranscript(
|
|
249
|
+
[FetchedTranscriptSnippet(s["text"], float(s["start"]), float(s["duration"])) for s in item.get("segments") or []],
|
|
250
|
+
vid, item.get("languageName") or code, code, bool(item.get("isAutoGenerated")))
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""youtube-transcript-cloud <video ids or URLs> [--languages de en] [--format json]
|
|
2
|
+
youtube-transcript-cloud --list-transcripts <video>
|
|
3
|
+
youtube-transcript-cloud mcp (an MCP server on stdio)"""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import argparse
|
|
8
|
+
import sys
|
|
9
|
+
|
|
10
|
+
from .api import ApifyError, CouldNotRetrieveTranscript, YouTubeTranscriptApi
|
|
11
|
+
from .formatters import FORMATS
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def main(argv: list[str] | None = None) -> int:
|
|
15
|
+
argv = sys.argv[1:] if argv is None else argv
|
|
16
|
+
if argv[:1] == ["mcp"]:
|
|
17
|
+
from .server import serve
|
|
18
|
+
return serve()
|
|
19
|
+
p = argparse.ArgumentParser(prog="youtube-transcript-cloud",
|
|
20
|
+
description="YouTube transcripts read on Apify, compatible with youtube-transcript-api's CLI.")
|
|
21
|
+
p.add_argument("video_ids", nargs="+", help="video IDs or URLs; mask a leading hyphen as \\-abc")
|
|
22
|
+
p.add_argument("--languages", nargs="+", default=["en"], help="the languages to prefer, in order")
|
|
23
|
+
p.add_argument("--format", choices=sorted(FORMATS), default="pretty")
|
|
24
|
+
p.add_argument("--list-transcripts", action="store_true", help="the caption tracks each video has")
|
|
25
|
+
p.add_argument("--apify-token", help="defaults to APIFY_TOKEN")
|
|
26
|
+
a = p.parse_args(argv)
|
|
27
|
+
ids = [v.replace("\\-", "-", 1) if v.startswith("\\-") else v for v in a.video_ids]
|
|
28
|
+
if hasattr(sys.stdout, "reconfigure"):
|
|
29
|
+
sys.stdout.reconfigure(encoding="utf-8") # transcripts come in any script; a Windows code page fails on most
|
|
30
|
+
try:
|
|
31
|
+
api = YouTubeTranscriptApi(a.apify_token)
|
|
32
|
+
if a.list_transcripts:
|
|
33
|
+
for v in ids:
|
|
34
|
+
print(api.list(v))
|
|
35
|
+
return 0
|
|
36
|
+
got = api.fetch_all(ids, a.languages)
|
|
37
|
+
except (ApifyError, CouldNotRetrieveTranscript, ValueError) as e:
|
|
38
|
+
print(e, file=sys.stderr)
|
|
39
|
+
return 1
|
|
40
|
+
fetched = [t for t in got.values() if not isinstance(t, Exception)]
|
|
41
|
+
for e in (t for t in got.values() if isinstance(t, Exception)):
|
|
42
|
+
print(e, file=sys.stderr)
|
|
43
|
+
if fetched:
|
|
44
|
+
print(FORMATS[a.format]().format_transcripts(fetched))
|
|
45
|
+
return 0 if len(fetched) == len(got) else 1
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
if __name__ == "__main__":
|
|
49
|
+
sys.exit(main())
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import pprint
|
|
5
|
+
|
|
6
|
+
from .api import FetchedTranscript
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Formatter:
|
|
10
|
+
"""Subclass it and implement both methods, each returning a string."""
|
|
11
|
+
|
|
12
|
+
def format_transcript(self, transcript: FetchedTranscript, **kwargs) -> str:
|
|
13
|
+
raise NotImplementedError
|
|
14
|
+
|
|
15
|
+
def format_transcripts(self, transcripts: list[FetchedTranscript], **kwargs) -> str:
|
|
16
|
+
raise NotImplementedError
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class JSONFormatter(Formatter):
|
|
20
|
+
"""Keyword arguments go to `json.dumps`."""
|
|
21
|
+
|
|
22
|
+
def format_transcript(self, transcript, **kwargs):
|
|
23
|
+
return json.dumps(transcript.to_raw_data(), **kwargs)
|
|
24
|
+
|
|
25
|
+
def format_transcripts(self, transcripts, **kwargs):
|
|
26
|
+
return json.dumps([t.to_raw_data() for t in transcripts], **kwargs)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class PrettyPrintFormatter(Formatter):
|
|
30
|
+
def format_transcript(self, transcript, **kwargs):
|
|
31
|
+
return pprint.pformat(transcript.to_raw_data(), **kwargs)
|
|
32
|
+
|
|
33
|
+
def format_transcripts(self, transcripts, **kwargs):
|
|
34
|
+
return pprint.pformat([t.to_raw_data() for t in transcripts], **kwargs)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class TextFormatter(Formatter):
|
|
38
|
+
def format_transcript(self, transcript, **kwargs):
|
|
39
|
+
return "\n".join(s.text for s in transcript)
|
|
40
|
+
|
|
41
|
+
def format_transcripts(self, transcripts, **kwargs):
|
|
42
|
+
return "\n\n\n".join(self.format_transcript(t) for t in transcripts)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class _Cues(Formatter):
|
|
46
|
+
HEADER = ""
|
|
47
|
+
MARK = ","
|
|
48
|
+
|
|
49
|
+
def stamp(self, seconds: float) -> str:
|
|
50
|
+
ms = round(seconds * 1000)
|
|
51
|
+
return f"{ms // 3_600_000:02d}:{ms // 60_000 % 60:02d}:{ms // 1000 % 60:02d}{self.MARK}{ms % 1000:03d}"
|
|
52
|
+
|
|
53
|
+
def cue(self, i: int, start: float, end: float, text: str) -> str:
|
|
54
|
+
raise NotImplementedError
|
|
55
|
+
|
|
56
|
+
def format_transcript(self, transcript, **kwargs):
|
|
57
|
+
snippets = list(transcript)
|
|
58
|
+
cues = []
|
|
59
|
+
for i, s in enumerate(snippets):
|
|
60
|
+
end = s.start + s.duration
|
|
61
|
+
if i + 1 < len(snippets):
|
|
62
|
+
end = min(end, snippets[i + 1].start) # overlapping captions would stack on screen
|
|
63
|
+
cues.append(self.cue(i + 1, s.start, end, s.text))
|
|
64
|
+
return self.HEADER + "\n\n".join(cues) + "\n"
|
|
65
|
+
|
|
66
|
+
def format_transcripts(self, transcripts, **kwargs):
|
|
67
|
+
return "\n\n\n".join(self.format_transcript(t) for t in transcripts)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class SRTFormatter(_Cues):
|
|
71
|
+
def cue(self, i, start, end, text):
|
|
72
|
+
return f"{i}\n{self.stamp(start)} --> {self.stamp(end)}\n{text}"
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class WebVTTFormatter(_Cues):
|
|
76
|
+
HEADER = "WEBVTT\n\n"
|
|
77
|
+
MARK = "."
|
|
78
|
+
|
|
79
|
+
def cue(self, i, start, end, text):
|
|
80
|
+
return f"{self.stamp(start)} --> {self.stamp(end)}\n{text}"
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
FORMATS = {"json": JSONFormatter, "pretty": PrettyPrintFormatter, "text": TextFormatter,
|
|
84
|
+
"srt": SRTFormatter, "webvtt": WebVTTFormatter}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""An MCP server on stdio (newline-delimited JSON-RPC), with no SDK so the package stays dependency-free.
|
|
2
|
+
One tool, `get_youtube_transcript`."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import json
|
|
7
|
+
import sys
|
|
8
|
+
|
|
9
|
+
from . import __version__
|
|
10
|
+
from .api import YouTubeTranscriptApi
|
|
11
|
+
|
|
12
|
+
VERSIONS = ("2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05")
|
|
13
|
+
TOOL = {
|
|
14
|
+
"name": "get_youtube_transcript",
|
|
15
|
+
"description": "The transcript of a YouTube video (or Short) from its captions, with its title, channel and "
|
|
16
|
+
"language. Optionally each line with its start time.",
|
|
17
|
+
"inputSchema": {
|
|
18
|
+
"type": "object",
|
|
19
|
+
"properties": {
|
|
20
|
+
"video": {"type": "string", "description": "A YouTube video URL or ID"},
|
|
21
|
+
"languages": {"type": "array", "items": {"type": "string"},
|
|
22
|
+
"description": "Caption languages to prefer, in order, e.g. [\"de\", \"en\"]. Default: en, "
|
|
23
|
+
"else the video's own language"},
|
|
24
|
+
"timestamps": {"type": "boolean", "description": "Each line with its start time, [mm:ss]"},
|
|
25
|
+
},
|
|
26
|
+
"required": ["video"],
|
|
27
|
+
},
|
|
28
|
+
"annotations": {"readOnlyHint": True, "openWorldHint": True},
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def clock(seconds: float) -> str:
|
|
33
|
+
s = int(seconds)
|
|
34
|
+
return f"{s // 3600}:{s // 60 % 60:02d}:{s % 60:02d}" if s >= 3600 else f"{s // 60:02d}:{s % 60:02d}"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def transcript(api: YouTubeTranscriptApi, video: str, languages: list[str] | None = None, timestamps: bool = False) -> str:
|
|
38
|
+
item = api.run([video], languages or ["en"], timestamps)[0]
|
|
39
|
+
if not item.get("text"):
|
|
40
|
+
raise RuntimeError(item.get("error") or "No transcript")
|
|
41
|
+
head = [f"# {item.get('title') or item.get('videoId')}",
|
|
42
|
+
" · ".join(str(x) for x in (item.get("channel"), item.get("url")) if x),
|
|
43
|
+
f"Language: {item.get('languageName') or item.get('language')}"
|
|
44
|
+
f"{' (auto-generated)' if item.get('isAutoGenerated') else ''}"]
|
|
45
|
+
body = ("\n".join(f"[{clock(s['start'])}] {s['text']}" for s in item["segments"])
|
|
46
|
+
if timestamps and item.get("segments") else item["text"])
|
|
47
|
+
return "\n".join(head) + "\n\n" + body
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def answer(request: dict, api) -> dict | None:
|
|
51
|
+
"""The response to one JSON-RPC message; None for a notification."""
|
|
52
|
+
method, rid, params = request.get("method"), request.get("id"), request.get("params") or {}
|
|
53
|
+
if rid is None:
|
|
54
|
+
return None
|
|
55
|
+
if method == "initialize":
|
|
56
|
+
asked = params.get("protocolVersion")
|
|
57
|
+
result = {"protocolVersion": asked if asked in VERSIONS else VERSIONS[0], "capabilities": {"tools": {}},
|
|
58
|
+
"serverInfo": {"name": "youtube-transcript-cloud", "version": __version__}}
|
|
59
|
+
elif method == "ping":
|
|
60
|
+
result = {}
|
|
61
|
+
elif method == "tools/list":
|
|
62
|
+
result = {"tools": [TOOL]}
|
|
63
|
+
elif method == "tools/call" and params.get("name") == TOOL["name"]:
|
|
64
|
+
try:
|
|
65
|
+
result = {"content": [{"type": "text", "text": transcript(api(), **(params.get("arguments") or {}))}],
|
|
66
|
+
"isError": False}
|
|
67
|
+
except Exception as e: # a tool's failure goes back to the model as its result
|
|
68
|
+
result = {"content": [{"type": "text", "text": str(e)}], "isError": True}
|
|
69
|
+
else:
|
|
70
|
+
return {"jsonrpc": "2.0", "id": rid, "error": {"code": -32601, "message": f"Unknown method {method}"}}
|
|
71
|
+
return {"jsonrpc": "2.0", "id": rid, "result": result}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def serve(stdin=None, stdout=None) -> int:
|
|
75
|
+
if stdin is None:
|
|
76
|
+
for stream in (sys.stdin, sys.stdout):
|
|
77
|
+
stream.reconfigure(encoding="utf-8") # MCP is UTF-8; Windows' console default isn't
|
|
78
|
+
stdin, stdout = stdin or sys.stdin, stdout or sys.stdout
|
|
79
|
+
made = []
|
|
80
|
+
|
|
81
|
+
def api(): # made at the first call, so a client can list the tool before a token is set
|
|
82
|
+
if not made:
|
|
83
|
+
made.append(YouTubeTranscriptApi())
|
|
84
|
+
return made[0]
|
|
85
|
+
|
|
86
|
+
for line in stdin:
|
|
87
|
+
if not line.strip():
|
|
88
|
+
continue
|
|
89
|
+
try:
|
|
90
|
+
request = json.loads(line)
|
|
91
|
+
except ValueError:
|
|
92
|
+
reply = {"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "Parse error"}}
|
|
93
|
+
else:
|
|
94
|
+
reply = answer(request, api)
|
|
95
|
+
if reply:
|
|
96
|
+
stdout.write(json.dumps(reply) + "\n")
|
|
97
|
+
stdout.flush()
|
|
98
|
+
return 0
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import io
|
|
2
|
+
import json
|
|
3
|
+
import urllib.error
|
|
4
|
+
|
|
5
|
+
import pytest
|
|
6
|
+
|
|
7
|
+
from youtube_transcript_cloud import api as m
|
|
8
|
+
|
|
9
|
+
VID = "dQw4w9WgXcQ"
|
|
10
|
+
EN = {"videoId": VID, "title": "T", "language": "en", "languageName": "English", "isAutoGenerated": False,
|
|
11
|
+
"text": "hi there", "segments": [{"text": "hi", "start": 0, "duration": 1.5}, {"text": "there", "start": 1.5, "duration": 2}],
|
|
12
|
+
"availableLanguages": [{"code": "en", "name": "English", "autoGenerated": False},
|
|
13
|
+
{"code": "de", "name": "German (auto-generated)", "autoGenerated": True}]}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def api_returning(monkeypatch, *items):
|
|
17
|
+
calls = []
|
|
18
|
+
monkeypatch.setattr(m.YouTubeTranscriptApi, "run", lambda self, videos, languages=("en",), timestamps=True:
|
|
19
|
+
calls.append((list(videos), list(languages))) or list(items))
|
|
20
|
+
return m.YouTubeTranscriptApi("token"), calls
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@pytest.mark.parametrize("value", [VID, f"https://www.youtube.com/watch?v={VID}&t=3", f"youtu.be/{VID}",
|
|
24
|
+
f"https://www.youtube.com/shorts/{VID}"])
|
|
25
|
+
def test_video_id_of_takes_ids_and_urls(value):
|
|
26
|
+
assert m.video_id_of(value) == VID
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def test_video_id_of_refuses_other_text():
|
|
30
|
+
with pytest.raises(ValueError):
|
|
31
|
+
m.video_id_of("https://example.com/watch")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def test_no_token_is_refused(monkeypatch):
|
|
35
|
+
monkeypatch.delenv("APIFY_TOKEN", raising=False)
|
|
36
|
+
with pytest.raises(m.ApifyError):
|
|
37
|
+
m.YouTubeTranscriptApi()
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def test_run_posts_the_videos_with_the_token(monkeypatch):
|
|
41
|
+
sent = {}
|
|
42
|
+
|
|
43
|
+
def urlopen(request, timeout):
|
|
44
|
+
sent.update(url=request.full_url, auth=request.headers["Authorization"], body=json.loads(request.data))
|
|
45
|
+
return io.BytesIO(json.dumps([EN]).encode())
|
|
46
|
+
monkeypatch.setattr(m.urllib.request, "urlopen", urlopen)
|
|
47
|
+
assert m.YouTubeTranscriptApi("tok").run([f"youtu.be/{VID}"], ["de"]) == [EN]
|
|
48
|
+
assert sent == {"url": m.ENDPOINT.format(m.ACTOR), "auth": "Bearer tok",
|
|
49
|
+
"body": {"videos": [f"https://www.youtube.com/watch?v={VID}"], "languages": ["de"], "includeTimestamps": True}}
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def test_run_raises_apifys_message(monkeypatch):
|
|
53
|
+
def urlopen(request, timeout):
|
|
54
|
+
raise urllib.error.HTTPError(request.full_url, 401, "Unauthorized", {},
|
|
55
|
+
io.BytesIO(b'{"error": {"message": "User was not found"}}'))
|
|
56
|
+
monkeypatch.setattr(m.urllib.request, "urlopen", urlopen)
|
|
57
|
+
with pytest.raises(m.ApifyError, match="401: User was not found"):
|
|
58
|
+
m.YouTubeTranscriptApi("tok").run([VID])
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def test_fetch_gives_the_snippets(monkeypatch):
|
|
62
|
+
api, _ = api_returning(monkeypatch, EN)
|
|
63
|
+
t = api.fetch(VID)
|
|
64
|
+
assert (t.language, t.language_code, t.is_generated, len(t), t[-1].text) == ("English", "en", False, 2, "there")
|
|
65
|
+
assert t.to_raw_data()[0] == {"text": "hi", "start": 0.0, "duration": 1.5}
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def test_fetch_refuses_a_language_not_asked_for(monkeypatch):
|
|
69
|
+
api, _ = api_returning(monkeypatch, EN)
|
|
70
|
+
with pytest.raises(m.NoTranscriptFound, match="de .generated"):
|
|
71
|
+
api.fetch(VID, ["fr"])
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def test_fetch_takes_a_regional_variant(monkeypatch):
|
|
75
|
+
api, _ = api_returning(monkeypatch, {**EN, "language": "en-GB"})
|
|
76
|
+
assert api.fetch(VID, ["en"]).language_code == "en-GB"
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@pytest.mark.parametrize("item, error", [
|
|
80
|
+
({"videoId": VID, "title": "T", "error": "This video has no captions. Video to Text ..."}, m.TranscriptsDisabled),
|
|
81
|
+
({"videoId": VID, "error": "YouTube kept blocking the request."}, m.RequestBlocked),
|
|
82
|
+
({"videoId": VID, "error": "Video unavailable"}, m.VideoUnavailable),
|
|
83
|
+
({"videoId": VID, "title": "T", "error": "Something else"}, m.CouldNotRetrieveTranscript),
|
|
84
|
+
])
|
|
85
|
+
def test_fetch_raises_what_the_item_says(monkeypatch, item, error):
|
|
86
|
+
api, _ = api_returning(monkeypatch, item)
|
|
87
|
+
with pytest.raises(error):
|
|
88
|
+
api.fetch(VID)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def test_fetch_all_reads_every_video_in_one_run(monkeypatch):
|
|
92
|
+
other = "aaaaaaaaaaa"
|
|
93
|
+
api, calls = api_returning(monkeypatch, {"videoId": other, "error": "Video unavailable"}, EN)
|
|
94
|
+
got = api.fetch_all([VID, other])
|
|
95
|
+
assert len(calls) == 1 and isinstance(got[VID], m.FetchedTranscript) and isinstance(got[other], m.VideoUnavailable)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def test_list_gives_the_tracks_and_keeps_the_one_read(monkeypatch):
|
|
99
|
+
api, calls = api_returning(monkeypatch, EN)
|
|
100
|
+
tracks = api.list(VID)
|
|
101
|
+
assert [(t.language_code, t.is_generated) for t in tracks] == [("en", False), ("de", True)]
|
|
102
|
+
assert tracks.find_transcript(["en"]).fetch().language_code == "en" and len(calls) == 1
|
|
103
|
+
assert tracks.find_generated_transcript(["en", "de"]).language_code == "de"
|
|
104
|
+
with pytest.raises(m.NoTranscriptFound):
|
|
105
|
+
tracks.find_manually_created_transcript(["de"])
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def test_translate_is_refused(monkeypatch):
|
|
109
|
+
api, _ = api_returning(monkeypatch, EN)
|
|
110
|
+
with pytest.raises(m.NotTranslatable):
|
|
111
|
+
api.list(VID).find_transcript(["en"]).translate("fr")
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import json
|
|
2
|
+
|
|
3
|
+
from youtube_transcript_cloud import api as m
|
|
4
|
+
from youtube_transcript_cloud.cli import main
|
|
5
|
+
|
|
6
|
+
VID = "dQw4w9WgXcQ"
|
|
7
|
+
ITEM = {"videoId": VID, "title": "T", "language": "en", "text": "hi",
|
|
8
|
+
"segments": [{"text": "hi", "start": 0, "duration": 1}], "availableLanguages": []}
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def test_prints_the_format_and_fails_on_a_missing_one(monkeypatch, capsys):
|
|
12
|
+
other = "-bcdefghijk"
|
|
13
|
+
monkeypatch.setattr(m.YouTubeTranscriptApi, "run", lambda self, v, l=("en",), t=True:
|
|
14
|
+
[ITEM, {"videoId": other, "error": "Video unavailable"}])
|
|
15
|
+
assert main([VID, "\\" + other, "--format", "json", "--apify-token", "x"]) == 1
|
|
16
|
+
out, err = capsys.readouterr()
|
|
17
|
+
assert json.loads(out) == [[{"text": "hi", "start": 0.0, "duration": 1.0}]] and other in err
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import json
|
|
2
|
+
|
|
3
|
+
from youtube_transcript_cloud.api import FetchedTranscript, FetchedTranscriptSnippet
|
|
4
|
+
from youtube_transcript_cloud.formatters import JSONFormatter, SRTFormatter, TextFormatter, WebVTTFormatter
|
|
5
|
+
|
|
6
|
+
T = FetchedTranscript([FetchedTranscriptSnippet("hi", 0.0, 2.0), FetchedTranscriptSnippet("there", 1.5, 3661.25)],
|
|
7
|
+
"dQw4w9WgXcQ", "English", "en", False)
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def test_json_is_the_raw_data():
|
|
11
|
+
assert json.loads(JSONFormatter().format_transcripts([T])) == [T.to_raw_data()]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def test_text_is_a_line_per_snippet():
|
|
15
|
+
assert TextFormatter().format_transcript(T) == "hi\nthere"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def test_srt_cues_end_where_the_next_starts():
|
|
19
|
+
assert SRTFormatter().format_transcript(T) == ("1\n00:00:00,000 --> 00:00:01,500\nhi\n\n"
|
|
20
|
+
"2\n00:00:01,500 --> 01:01:02,750\nthere\n")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def test_webvtt_has_its_header_and_dots():
|
|
24
|
+
assert WebVTTFormatter().format_transcript(T).startswith("WEBVTT\n\n00:00:00.000 --> 00:00:01.500\nhi")
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import io
|
|
2
|
+
import json
|
|
3
|
+
|
|
4
|
+
from youtube_transcript_cloud import server
|
|
5
|
+
|
|
6
|
+
ITEM = {"videoId": "dQw4w9WgXcQ", "title": "T", "channel": "C", "url": "u", "language": "en", "languageName": "English",
|
|
7
|
+
"text": "hi there", "segments": [{"text": "hi", "start": 0, "duration": 1}, {"text": "there", "start": 3725, "duration": 1}]}
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class Api:
|
|
11
|
+
def __init__(self, items):
|
|
12
|
+
self.items, self.asked = items, []
|
|
13
|
+
|
|
14
|
+
def run(self, videos, languages, timestamps):
|
|
15
|
+
self.asked.append((videos, languages, timestamps))
|
|
16
|
+
return self.items
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def test_transcript_has_a_header_and_timed_lines():
|
|
20
|
+
text = server.transcript(Api([ITEM]), "x", timestamps=True)
|
|
21
|
+
assert text == "# T\nC · u\nLanguage: English\n\n[00:00] hi\n[1:02:05] there"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def test_serve_answers_initialize_list_and_call_and_skips_notifications(monkeypatch):
|
|
25
|
+
api = Api([{"videoId": "x", "error": "Video unavailable"}])
|
|
26
|
+
monkeypatch.setattr(server, "YouTubeTranscriptApi", lambda: api)
|
|
27
|
+
lines = [{"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2025-06-18"}},
|
|
28
|
+
{"jsonrpc": "2.0", "method": "notifications/initialized"},
|
|
29
|
+
{"jsonrpc": "2.0", "id": 2, "method": "tools/list"},
|
|
30
|
+
{"jsonrpc": "2.0", "id": 3, "method": "tools/call",
|
|
31
|
+
"params": {"name": "get_youtube_transcript", "arguments": {"video": "x", "languages": ["de"]}}},
|
|
32
|
+
{"jsonrpc": "2.0", "id": 4, "method": "resources/list"}]
|
|
33
|
+
out = io.StringIO()
|
|
34
|
+
server.serve(io.StringIO("".join(json.dumps(x) + "\n" for x in lines)), out)
|
|
35
|
+
replies = [json.loads(x) for x in out.getvalue().splitlines()]
|
|
36
|
+
assert [r["id"] for r in replies] == [1, 2, 3, 4]
|
|
37
|
+
assert replies[0]["result"]["protocolVersion"] == "2025-06-18"
|
|
38
|
+
assert replies[1]["result"]["tools"][0]["name"] == "get_youtube_transcript"
|
|
39
|
+
assert replies[2]["result"] == {"content": [{"type": "text", "text": "Video unavailable"}], "isError": True}
|
|
40
|
+
assert api.asked == [(["x"], ["de"], False)] and replies[3]["error"]["code"] == -32601
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def test_server_json_lists_this_version():
|
|
44
|
+
from pathlib import Path
|
|
45
|
+
from youtube_transcript_cloud import __version__
|
|
46
|
+
listing = json.loads((Path(__file__).parent.parent / "server.json").read_text(encoding="utf-8"))
|
|
47
|
+
assert {listing["version"], listing["packages"][0]["version"]} == {__version__}
|