Repository navigation
Expand file tree
/
Copy pathtranscript.go
More file actions
395 lines (346 loc) · 10 KB
/
Copy pathtranscript.go
File metadata and controls
395 lines (346 loc) · 10 KB
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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
// Package yt_transcript fetches YouTube video transcripts via the innertube API.
// Stdlib only, zero dependencies.
package yt_transcript
import (
"bytes"
"context"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"io"
"net/http"
"net/http/cookiejar"
"regexp"
"strconv"
"strings"
"sync/atomic"
"time"
)
const (
watchURL = "https://www.youtube.com/watch?v=%s"
playerURL = "https://www.youtube.com/youtubei/v1/player?key=%s"
apiKeyRe = `"INNERTUBE_API_KEY":\s*"([a-zA-Z0-9_-]+)"`
)
// Segment represents a single transcript line with timing.
type Segment struct {
Text string `json:"text"`
Start float64 `json:"start"`
Duration float64 `json:"duration"`
}
// RateLimitError reports that YouTube is throttling or blocking requests from
// this client. RetryAfter is the suggested wait before trying again; zero means
// retry immediately.
type RateLimitError struct {
RetryAfter time.Duration
}
func (e *RateLimitError) Error() string {
if e.RetryAfter > 0 {
return fmt.Sprintf("rate limited by YouTube (429), retry after %s", e.RetryAfter.Round(time.Second))
}
return "rate limited by YouTube (429)"
}
// Client fetches YouTube transcripts.
type Client struct {
http *http.Client
breaker *breaker
identities []clientIdentity
rotation atomic.Uint64
}
// NewClient returns a Client with a default 30s timeout and cookie jar.
func NewClient() *Client {
jar, _ := cookiejar.New(nil)
return &Client{
http: &http.Client{Timeout: 30 * time.Second, Jar: jar},
breaker: newBreaker(3, time.Minute, time.Hour),
identities: clientIdentities,
}
}
// WithHTTPClient sets a custom http.Client.
func (c *Client) WithHTTPClient(h *http.Client) *Client {
c.http = h
return c
}
// do performs an upstream request, short-circuiting while the breaker is open.
// A 429 trips the breaker and is surfaced as a *RateLimitError.
func (c *Client) do(req *http.Request) (*http.Response, error) {
if remaining, ok := c.breaker.allow(time.Now()); !ok {
return nil, &RateLimitError{RetryAfter: remaining}
}
resp, err := c.http.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode == http.StatusTooManyRequests {
retryAfter := parseRetryAfter(resp.Header.Get("Retry-After"))
_ = resp.Body.Close()
cooldown := c.breaker.fail(retryAfter, time.Now())
if cooldown > 0 {
return nil, &RateLimitError{RetryAfter: cooldown}
}
return nil, &RateLimitError{RetryAfter: retryAfter}
}
c.breaker.succeed()
return resp, nil
}
func parseRetryAfter(v string) time.Duration {
if v == "" {
return 0
}
if secs, err := strconv.Atoi(v); err == nil && secs > 0 {
return time.Duration(secs) * time.Second
}
if t, err := http.ParseTime(v); err == nil {
if d := time.Until(t); d > 0 {
return d
}
}
return 0
}
// FetchTranscript retrieves the transcript for a YouTube video in the given
// language. It rotates over the known client identities and falls through to
// the next when one fails, so a stale client is not fatal.
func (c *Client) FetchTranscript(ctx context.Context, videoID, lang string) ([]Segment, error) {
html, err := c.fetchWatchPage(ctx, videoID)
if err != nil {
return nil, fmt.Errorf("fetching watch page: %w", err)
}
apiKey, err := extractAPIKey(html)
if err != nil {
return nil, fmt.Errorf("YouTube did not return expected page content — the video may be unavailable or requests are being blocked: %w", err)
}
n := len(c.identities)
start := int(c.rotation.Add(1)-1) % n
var lastErr error
for i := 0; i < n; i++ {
id := c.identities[(start+i)%n]
segments, err := c.fetchWithClient(ctx, videoID, lang, apiKey, id)
if err == nil {
return segments, nil
}
var rateLimited *RateLimitError
if errors.As(err, &rateLimited) {
return nil, err
}
if strings.Contains(err.Error(), "no transcript found") {
return nil, err
}
lastErr = err
}
return nil, fmt.Errorf("all clients failed: %w", lastErr)
}
func (c *Client) fetchWithClient(ctx context.Context, videoID, lang, apiKey string, id clientIdentity) ([]Segment, error) {
captions, err := c.fetchCaptions(ctx, videoID, apiKey, id)
if err != nil {
return nil, fmt.Errorf("fetching captions with %s: %w", id.name, err)
}
track, err := findCaptionTrack(captions, lang)
if err != nil {
return nil, err
}
return c.fetchAndParse(ctx, track.BaseURL, id)
}
// TranscriptLanguage is an available caption track: its language code and
// human-readable name.
type TranscriptLanguage struct {
Code string `json:"code"`
Name string `json:"name"`
}
// ListLanguages returns the transcript languages available for a video. A
// language with both a manual and an auto-generated track is listed once,
// preferring the manual name.
func (c *Client) ListLanguages(ctx context.Context, videoID string) ([]TranscriptLanguage, error) {
html, err := c.fetchWatchPage(ctx, videoID)
if err != nil {
return nil, fmt.Errorf("fetching watch page: %w", err)
}
apiKey, err := extractAPIKey(html)
if err != nil {
return nil, fmt.Errorf("YouTube did not return expected page content — the video may be unavailable or requests are being blocked: %w", err)
}
n := len(c.identities)
start := int(c.rotation.Add(1)-1) % n
var lastErr error
for i := 0; i < n; i++ {
id := c.identities[(start+i)%n]
tracks, err := c.fetchCaptions(ctx, videoID, apiKey, id)
if err != nil {
var rateLimited *RateLimitError
if errors.As(err, &rateLimited) {
return nil, err
}
lastErr = err
continue
}
return toLanguages(tracks), nil
}
return nil, fmt.Errorf("all clients failed: %w", lastErr)
}
func toLanguages(tracks []captionTrack) []TranscriptLanguage {
order := make([]string, 0, len(tracks))
best := make(map[string]captionTrack, len(tracks))
for _, t := range tracks {
cur, ok := best[t.LanguageCode]
if !ok {
order = append(order, t.LanguageCode)
best[t.LanguageCode] = t
continue
}
if cur.Kind == "asr" && t.Kind != "asr" {
best[t.LanguageCode] = t
}
}
langs := make([]TranscriptLanguage, 0, len(order))
for _, code := range order {
langs = append(langs, TranscriptLanguage{Code: code, Name: trackName(best[code])})
}
return langs
}
func trackName(t captionTrack) string {
var b strings.Builder
for _, r := range t.Name.Runs {
b.WriteString(r.Text)
}
if name := b.String(); name != "" {
return name
}
return t.LanguageCode
}
func (c *Client) fetchWatchPage(ctx context.Context, videoID string) (string, error) {
u := fmt.Sprintf(watchURL, videoID)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
if err != nil {
return "", err
}
req.Header.Set("Accept-Language", "en-US")
resp, err := c.do(req)
if err != nil {
return "", err
}
defer func() { _ = resp.Body.Close() }()
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
html := string(body)
if strings.Contains(html, `class="g-recaptcha"`) {
return "", fmt.Errorf("bot detection triggered — YouTube is blocking requests from this IP")
}
return html, nil
}
var apiKeyRegex = regexp.MustCompile(apiKeyRe)
func extractAPIKey(html string) (string, error) {
matches := apiKeyRegex.FindStringSubmatch(html)
if len(matches) < 2 {
return "", fmt.Errorf("could not parse YouTube page")
}
return matches[1], nil
}
type captionTrack struct {
BaseURL string `json:"baseUrl"`
LanguageCode string `json:"languageCode"`
Kind string `json:"kind"`
Name struct {
Runs []struct {
Text string `json:"text"`
} `json:"runs"`
} `json:"name"`
}
func (c *Client) fetchCaptions(ctx context.Context, videoID, apiKey string, id clientIdentity) ([]captionTrack, error) {
body, err := json.Marshal(map[string]any{
"context": map[string]any{
"client": id.context(),
},
"videoId": videoID,
})
if err != nil {
return nil, err
}
u := fmt.Sprintf(playerURL, apiKey)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, u, bytes.NewReader(body))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("User-Agent", id.userAgent)
resp, err := c.do(req)
if err != nil {
return nil, err
}
defer func() { _ = resp.Body.Close() }()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var data struct {
Captions struct {
PlayerCaptionsTracklistRenderer struct {
CaptionTracks []captionTrack `json:"captionTracks"`
} `json:"playerCaptionsTracklistRenderer"`
} `json:"captions"`
}
if err := json.Unmarshal(respBody, &data); err != nil {
return nil, fmt.Errorf("parsing player response: %w", err)
}
tracks := data.Captions.PlayerCaptionsTracklistRenderer.CaptionTracks
if len(tracks) == 0 {
return nil, fmt.Errorf("no caption tracks available")
}
return tracks, nil
}
func findCaptionTrack(tracks []captionTrack, lang string) (captionTrack, error) {
for _, t := range tracks {
if t.LanguageCode == lang {
t.BaseURL = strings.Replace(t.BaseURL, "&fmt=srv3", "", 1)
return t, nil
}
}
return captionTrack{}, fmt.Errorf("no transcript found for language %q", lang)
}
type transcriptXML struct {
XMLName xml.Name `xml:"transcript"`
Texts []transcriptText `xml:"text"`
}
type transcriptText struct {
Start float64 `xml:"start,attr"`
Dur float64 `xml:"dur,attr"`
Value string `xml:",chardata"`
}
func (c *Client) fetchAndParse(ctx context.Context, baseURL string, id clientIdentity) ([]Segment, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, baseURL, nil)
if err != nil {
return nil, err
}
if id.userAgent != "" {
req.Header.Set("User-Agent", id.userAgent)
}
resp, err := c.do(req)
if err != nil {
return nil, err
}
defer func() { _ = resp.Body.Close() }()
var x transcriptXML
if err := xml.NewDecoder(resp.Body).Decode(&x); err != nil {
return nil, fmt.Errorf("parsing transcript XML: %w", err)
}
segments := make([]Segment, len(x.Texts))
for i, t := range x.Texts {
segments[i] = Segment{
Text: unescapeHTML(t.Value),
Start: t.Start,
Duration: t.Dur,
}
}
return segments, nil
}
var htmlReplacer = strings.NewReplacer(
"&", "&",
"<", "<",
">", ">",
""", `"`,
"'", "'",
"'", "'",
)
func unescapeHTML(s string) string {
return htmlReplacer.Replace(s)
}