-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
335 lines (291 loc) · 10.4 KB
/
main.go
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
package main
import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"net/http"
"os"
"regexp"
"strconv"
"strings"
)
const RE_YOUTUBE = `(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})`
const USER_AGENT = `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36`
const RE_XML_TRANSCRIPT = `<text start="([^"]*)" dur="([^"]*)">([^<]*)<\/text>`
type YoutubeTranscriptError struct {
Message string
}
func (e *YoutubeTranscriptError) Error() string {
return fmt.Sprintf("[YoutubeTranscript] 🚨 %s", e.Message)
}
type YoutubeTranscriptTooManyRequestError struct {
YoutubeTranscriptError
}
type YoutubeTranscriptVideoUnavailableError struct {
YoutubeTranscriptError
VideoID string
}
type YoutubeTranscriptDisabledError struct {
YoutubeTranscriptError
VideoID string
}
type YoutubeTranscriptNotAvailableError struct {
YoutubeTranscriptError
VideoID string
}
type YoutubeTranscriptNotAvailableLanguageError struct {
YoutubeTranscriptError
Lang string
AvailableLangs []string
VideoID string
}
type TranscriptConfig struct {
Lang string
}
type TranscriptResponse struct {
Text string
Duration float64
Offset float64
Lang string
}
type YoutubeTranscript struct{}
func (yt *YoutubeTranscript) FetchTranscript(videoId string, config *TranscriptConfig) ([]TranscriptResponse, string, error) {
identifier, err := retrieveVideoId(videoId)
if err != nil {
return nil, "", err
}
videoPageURL := fmt.Sprintf("https://www.youtube.com/watch?v=%s", identifier)
videoPageResponse, err := http.Get(videoPageURL)
if err != nil {
return nil, "", err
}
defer videoPageResponse.Body.Close()
videoPageBody, err := ioutil.ReadAll(videoPageResponse.Body)
if err != nil {
return nil, "", err
}
// Extract video title
titleRegex := regexp.MustCompile(`<title>(.+?) - YouTube</title>`)
titleMatch := titleRegex.FindSubmatch(videoPageBody)
var videoTitle string
if len(titleMatch) > 1 {
videoTitle = string(titleMatch[1])
// Decode HTML entities here
videoTitle = html.UnescapeString(videoTitle)
}
splittedHTML := strings.Split(string(videoPageBody), `"captions":`)
if len(splittedHTML) <= 1 {
if strings.Contains(string(videoPageBody), `class="g-recaptcha"`) {
return nil, "", &YoutubeTranscriptTooManyRequestError{YoutubeTranscriptError{Message: "YouTube is receiving too many requests from this IP and now requires solving a captcha to continue"}}
}
if !strings.Contains(string(videoPageBody), `"playabilityStatus":`) {
return nil, "", &YoutubeTranscriptVideoUnavailableError{YoutubeTranscriptError{Message: fmt.Sprintf("The video is no longer available (%s)", videoId)}, videoId}
}
return nil, "", &YoutubeTranscriptDisabledError{YoutubeTranscriptError{Message: fmt.Sprintf("Transcript is disabled on this video (%s)", videoId)}, videoId}
}
var captions struct {
PlayerCaptionsTracklistRenderer struct {
CaptionTracks []struct {
BaseURL string `json:"baseUrl"`
LanguageCode string `json:"languageCode"`
} `json:"captionTracks"`
} `json:"playerCaptionsTracklistRenderer"`
}
captionsData := splittedHTML[1][:strings.Index(splittedHTML[1], ",\"videoDetails")]
err = json.Unmarshal([]byte(captionsData), &captions)
if err != nil {
fmt.Println("Error unmarshalling captions data:", err)
return nil, "", &YoutubeTranscriptDisabledError{YoutubeTranscriptError{Message: fmt.Sprintf("Transcript is disabled on this video (%s)", videoId)}, videoId}
}
if len(captions.PlayerCaptionsTracklistRenderer.CaptionTracks) == 0 {
return nil, "", &YoutubeTranscriptNotAvailableError{YoutubeTranscriptError{Message: fmt.Sprintf("No transcripts are available for this video (%s)", videoId)}, videoId}
}
var transcriptURL string
if config != nil && config.Lang != "" {
for _, track := range captions.PlayerCaptionsTracklistRenderer.CaptionTracks {
if track.LanguageCode == config.Lang {
transcriptURL = track.BaseURL
break
}
}
if transcriptURL == "" {
availableLangs := make([]string, len(captions.PlayerCaptionsTracklistRenderer.CaptionTracks))
for i, track := range captions.PlayerCaptionsTracklistRenderer.CaptionTracks {
availableLangs[i] = track.LanguageCode
}
return nil, "", &YoutubeTranscriptNotAvailableLanguageError{
YoutubeTranscriptError{Message: fmt.Sprintf("No transcripts are available in %s for this video (%s). Available languages: %s", config.Lang, videoId, strings.Join(availableLangs, ", "))},
config.Lang, availableLangs, videoId,
}
}
} else {
transcriptURL = captions.PlayerCaptionsTracklistRenderer.CaptionTracks[0].BaseURL
}
fmt.Println("Transcript URL:", transcriptURL) // Debugging line
transcriptResponse, err := http.Get(transcriptURL)
if err != nil {
return nil, "", &YoutubeTranscriptNotAvailableError{YoutubeTranscriptError{Message: fmt.Sprintf("No transcripts are available for this video (%s)", videoId)}, videoId}
}
defer transcriptResponse.Body.Close()
transcriptBody, err := ioutil.ReadAll(transcriptResponse.Body)
if err != nil {
return nil, "", err
}
re := regexp.MustCompile(RE_XML_TRANSCRIPT)
matches := re.FindAllStringSubmatch(string(transcriptBody), -1)
var results []TranscriptResponse
for _, match := range matches {
duration, _ := strconv.ParseFloat(match[2], 64)
offset, _ := strconv.ParseFloat(match[1], 64)
results = append(results, TranscriptResponse{
Text: match[3],
Duration: duration,
Offset: offset,
Lang: config.Lang,
})
}
return results, videoTitle, nil
}
func retrieveVideoId(videoId string) (string, error) {
if len(videoId) == 11 {
return videoId, nil
}
re := regexp.MustCompile(RE_YOUTUBE)
match := re.FindStringSubmatch(videoId)
if match != nil {
return match[1], nil
}
return "", &YoutubeTranscriptError{Message: "Impossible to retrieve Youtube video ID."}
}
func sanitizeFilename(filename string) string {
// Decode any HTML entities like "&"
filename = html.UnescapeString(filename)
// Replace or remove illegal characters
re := regexp.MustCompile(`[<>:"/\\|? *]`)
sanitized := re.ReplaceAllString(filename, "_")
// Remove leading/trailing spaces and dots
sanitized = strings.Trim(sanitized, " .")
// Limit the length to 200 characters
if len(sanitized) > 200 {
sanitized = sanitized[:200]
}
return sanitized
}
func main() {
// Define command line flags
videoId := flag.String("videoId", "", "YouTube video ID or URL")
lang := flag.String("lang", "en", "Language code for the transcript")
output := flag.String("output", "", "Output file path")
showText := flag.Bool("showText", true, "Show transcript text")
showDuration := flag.Bool("showDuration", false, "Show transcript duration")
showOffset := flag.Bool("showOffset", false, "Show transcript offset")
showLang := flag.Bool("showLang", false, "Show transcript language")
disableAll := flag.Bool("disableAll", false, "Disable all transcript output fields")
noTextPrefix := flag.Bool("noTextPrefix", true, "Disable prefix 'Text: ' in front of transcript text")
// Custom usage message
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
fmt.Fprintf(os.Stderr, " %s [options]\n", os.Args[0])
fmt.Fprintf(os.Stderr, "\nOptions:\n")
flag.PrintDefaults()
fmt.Fprintf(os.Stderr, "\nExample:\n")
fmt.Fprintf(os.Stderr, " %s -videoId=dQw4w9WgXcQ -lang=en -output=transcript.txt\n", os.Args[0])
}
// Parse command line flags
flag.Parse()
// If no arguments are provided or -h/--help is used, print usage and exit
if len(os.Args) == 1 || (len(os.Args) == 2 && (os.Args[1] == "-h" || os.Args[1] == "--help")) {
flag.Usage()
os.Exit(0)
}
// Validate required flags
if *videoId == "" {
fmt.Println("Error: videoId is required")
flag.Usage()
os.Exit(1)
}
// Disable all fields if disableAll is true
if *disableAll {
*showText = false
*showDuration = false
*showOffset = false
*showLang = false
}
yt := &YoutubeTranscript{}
transcripts, videoTitle, err := yt.FetchTranscript(*videoId, &TranscriptConfig{Lang: *lang})
if err != nil {
fmt.Println("Error:", err)
os.Exit(1)
}
// Determine output filename
var outputFilename string
if *output == "" {
sanitizedTitle := sanitizeFilename(videoTitle)
outputFilename = sanitizedTitle + ".txt"
} else {
outputFilename = *output
}
// Create or open the output file
file, err := os.Create(outputFilename)
if err != nil {
fmt.Println("Error creating file:", err)
os.Exit(1)
}
defer file.Close()
// Write transcripts to the file
for _, transcript := range transcripts {
if *showText {
decodedText := decodeHTML(transcript.Text)
prefix := "Text: "
suffix := "\n"
if *noTextPrefix {
prefix = ""
suffix = ""
}
_, err := file.WriteString(fmt.Sprintf("%s%s%s", prefix, decodedText, suffix))
if err != nil {
fmt.Println("Error writing to file:", err)
os.Exit(1)
}
}
if *showDuration {
_, err := file.WriteString(fmt.Sprintf("Duration: %.2f\n", transcript.Duration))
if err != nil {
fmt.Println("Error writing to file:", err)
os.Exit(1)
}
}
if *showOffset {
_, err := file.WriteString(fmt.Sprintf("Offset: %.2f\n", transcript.Offset))
if err != nil {
fmt.Println("Error writing to file:", err)
os.Exit(1)
}
}
if *showLang {
_, err := file.WriteString(fmt.Sprintf("Language: %s\n", transcript.Lang))
if err != nil {
fmt.Println("Error writing to file:", err)
os.Exit(1)
}
}
_, err := file.WriteString("\n")
if err != nil {
fmt.Println("Error writing to file:", err)
os.Exit(1)
}
}
fmt.Println("Transcript saved to", outputFilename)
}
// Helper function to decode specific HTML entities
func decodeHTML(text string) string {
// Replace specific encoded strings directly
text = strings.ReplaceAll(text, "&#39;", "'") // Replace &#39; with '
// text = strings.ReplaceAll(text, "&", "&") // Replace & with &
// text = strings.ReplaceAll(text, """, "\"") // Replace " with "
// text = strings.ReplaceAll(text, "'", "'") // Replace ' with '
// text = strings.ReplaceAll(text, "<", "<") // Replace < with <
// text = strings.ReplaceAll(text, ">", ">") // Replace > with >
return text
}