youtubetranscript-net 0.1.0

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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: b32adcc12d83c7ab580e368d7f3a1a85b850821def3556562f75ca539909d271
4
+ data.tar.gz: 38fb3b8052088f67640401f641b70f9dcec3d65c97de78d9a23d65677465fcae
5
+ SHA512:
6
+ metadata.gz: 26960aa740389b48c4525467580f3d400d3cf3c5920e31fd12b385d685e0cf458f1799a2b9598bc05705cdd2ce94d0bcf76bc4077369afffb5a74df327ab03d8
7
+ data.tar.gz: 6a2a636cbeb7d17dee9389f7e60ad43f198bba7808e0f084fe2c255a5ddfb2241c26e75f6ac10e370cf27573db38537774ef43dc434ffd77830e36eefb5ea2ed
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 YouTubeTranscript.net
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.
data/README.md ADDED
@@ -0,0 +1,117 @@
1
+ # youtubetranscript-net (Ruby)
2
+
3
+ Ruby client for the [YouTubeTranscript.net API](https://youtubetranscript.net/docs/api): get YouTube transcripts with timestamps, download them as TXT, SRT or VTT, and transcribe whole playlists and channels. Standard library only, Ruby 3.1+.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ gem install youtubetranscript-net
9
+ ```
10
+
11
+ or in a Gemfile:
12
+
13
+ ```ruby
14
+ gem "youtubetranscript-net"
15
+ ```
16
+
17
+ ## Quick start
18
+
19
+ Create an API key at <https://youtubetranscript.net/account/api-keys> and set it as `YTT_API_KEY`.
20
+
21
+ ```ruby
22
+ require "youtubetranscript_net"
23
+
24
+ client = YouTubeTranscriptNet::Client.new # reads ENV["YTT_API_KEY"]
25
+
26
+ result = client.transcripts.get("https://www.youtube.com/watch?v=jNQXAC9IVRw")
27
+ result.transcript.segments.each do |segment|
28
+ puts "#{segment.start} #{segment.text}"
29
+ end
30
+ ```
31
+
32
+ `get` waits for the transcript: it asks for a fast answer, and when the video needs more time (speech-to-text, long videos) it polls the job until it is done.
33
+
34
+ ## Client options
35
+
36
+ ```ruby
37
+ YouTubeTranscriptNet::Client.new(
38
+ api_key: "ytt_...", # default ENV["YTT_API_KEY"]
39
+ base_url: "https://api.youtubetranscript.net", # default ENV["YTT_BASE_URL"], then this
40
+ timeout: 60, # seconds per HTTP request
41
+ max_retries: 2 # automatic retries, see below
42
+ )
43
+ ```
44
+
45
+ ## Methods
46
+
47
+ `video` is a YouTube link (watch, youtu.be, Shorts) or an 11-character video id.
48
+
49
+ ### Transcripts
50
+
51
+ | Method | Returns |
52
+ |---|---|
53
+ | `transcripts.get(video, language:, format:, include_timestamp:, send_metadata:, confirm_credits:, timeout: 300, poll_interval: 2)` | `TranscriptResult` once ready |
54
+ | `transcripts.submit(video, ..., wait_ms:)` | the first answer: `TranscriptResult` or `Job` |
55
+ | `transcripts.job(job_id)` | `TranscriptResult` or `Job` |
56
+ | `transcripts.info(video)` | video details and caption languages (free) |
57
+ | `transcripts.list(q:, lang:, sort:, page:, page_size:)` | `{transcripts:, total:, page:, pageSize:, langs:}` |
58
+ | `transcripts.download(video_id, "srt", language:)` | the file as a String (`txt`, `srt`, `vtt`, `json`, `md`) |
59
+ | `transcripts.delete(video_id, language:)` | `{removed: true}` |
60
+
61
+ `language` is a priority list such as `"en"`, `"pt-BR,pt"`, `"auto"` (the video's own captions) or `"asr"` (speech-to-text when there are no captions). `format: "text"` returns plain text in `result.text`.
62
+
63
+ `TranscriptResult` has `status`, `job_id`, `language`, `format`, `cached`, `length_seconds`, `length_text`, `transcript` (`platform`, `external_id`, `lang`, `origin`, `title`, `channel`, `duration_sec`, `segments`), `text`, `metadata` and `raw` (the full parsed JSON).
64
+
65
+ ### Batches
66
+
67
+ ```ruby
68
+ batch = client.batches.create(playlist: "https://www.youtube.com/playlist?list=...")
69
+ done = client.batches.wait(batch[:id])
70
+ File.binwrite("transcripts.zip", client.batches.export(batch[:id], format: "zip", files: "srt"))
71
+ ```
72
+
73
+ | Method | Returns |
74
+ |---|---|
75
+ | `batches.create(items: [...] \| playlist: \| channel:, language:, limit:, name:)` | the batch |
76
+ | `batches.get(batch_id, max_results:, page_token:)` | `{batch:, items:, nextPageToken:}` |
77
+ | `batches.wait(batch_id, timeout: 1800, poll_interval: 3)` | the last `get` once completed or failed |
78
+ | `batches.export(batch_id, format: "zip", files:, timestamps:)` | file bytes (`zip`, `csv`, `txt`, `json`, `srt`, `vtt`) |
79
+ | `batches.retry(batch_id)` | `{batch:, retried:, credits:}` |
80
+ | `batches.delete(batch_id)` | `{removed: true}` |
81
+
82
+ Batches are available once your account has bought a credit pack.
83
+
84
+ ### Account
85
+
86
+ `client.account.usage` returns your credits (`balance`, `freeToday`, `available`) and limits.
87
+
88
+ ## Errors
89
+
90
+ Every failure raises `YouTubeTranscriptNet::Error`:
91
+
92
+ ```ruby
93
+ begin
94
+ client.transcripts.get(video, language: "de")
95
+ rescue YouTubeTranscriptNet::Error => e
96
+ e.code # "LANGUAGE_NOT_AVAILABLE", "INSUFFICIENT_CREDITS", "RATE_LIMITED", ...
97
+ e.status # HTTP status, 0 for local errors
98
+ e.message
99
+ e.request_id # X-Request-Id, include it when you contact support
100
+ e.retry_after # seconds, on 429
101
+ e.details # the server's error object, e.g. details[:availableLanguages]
102
+ e.retryable? # true for 429, 5xx and network errors
103
+ end
104
+ ```
105
+
106
+ A video that costs more than 10 credits raises `CREDITS_CONFIRMATION_REQUIRED` first; call again with `confirm_credits: true` to accept the cost.
107
+
108
+ ## Retries
109
+
110
+ GET and DELETE requests, and `transcripts.get` / `submit` (sent with an `Idempotency-Key`, so the server never runs or charges them twice), are retried up to `max_retries` times on 429, 5xx and network errors, waiting for `Retry-After` when the server sends it. `batches.create` and `batches.retry` are never retried automatically.
111
+
112
+ ## Development
113
+
114
+ ```bash
115
+ rake test # unit tests, no network
116
+ YTT_API_KEY=ytt_... ruby -Ilib examples/e2e.rb # end-to-end against the API
117
+ ```
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ module YouTubeTranscriptNet
4
+ DEFAULT_BASE_URL = "https://api.youtubetranscript.net"
5
+
6
+ class Client
7
+ attr_reader :transcripts, :batches, :account, :base_url
8
+
9
+ # api_key defaults to ENV["YTT_API_KEY"]; raises Error(API_KEY_REQUIRED) when neither is set
10
+ # base_url defaults to ENV["YTT_BASE_URL"], then https://api.youtubetranscript.net
11
+ # timeout seconds for one HTTP request (default 60)
12
+ # max_retries automatic retries for retryable failures (default 2)
13
+ # transport optional object responding to call(method, url, headers, body, timeout)
14
+ # sleeper optional callable taking seconds (tests inject a fake)
15
+ def initialize(api_key: nil, base_url: nil, timeout: 60, max_retries: 2, transport: nil, sleeper: nil)
16
+ key = present(api_key) || present(ENV.fetch("YTT_API_KEY", nil))
17
+ raise Error.new("No API key. Pass api_key: or set YTT_API_KEY.", code: "API_KEY_REQUIRED") unless key
18
+
19
+ @base_url = (present(base_url) || present(ENV.fetch("YTT_BASE_URL", nil)) || DEFAULT_BASE_URL).sub(%r{/+\z}, "")
20
+ requester = Requester.new(api_key: key, base_url: @base_url, timeout: timeout, max_retries: max_retries,
21
+ transport: transport || NetHTTPTransport.new,
22
+ sleeper: sleeper || ->(seconds) { Kernel.sleep(seconds) if seconds.positive? })
23
+ @transcripts = Transcripts.new(requester)
24
+ @batches = Batches.new(requester)
25
+ @account = Account.new(requester)
26
+ end
27
+
28
+ def inspect
29
+ "#<#{self.class.name} base_url=#{@base_url.inspect}>"
30
+ end
31
+
32
+ private
33
+
34
+ def present(value)
35
+ value.nil? || value.to_s.strip.empty? ? nil : value.to_s.strip
36
+ end
37
+ end
38
+ end
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+
3
+ module YouTubeTranscriptNet
4
+ # The only error type the SDK raises.
5
+ #
6
+ # status HTTP status (0 for errors raised locally)
7
+ # code server `error.code`, or HTTP_<status>, NETWORK_ERROR, TIMEOUT,
8
+ # API_KEY_REQUIRED, INVALID_REQUEST, TRANSCRIPT_FAILED
9
+ # request_id response header X-Request-Id
10
+ # retry_after seconds from Retry-After, or nil
11
+ # details the server's `error` object as-is (availableLanguages, creditsRequired, ...)
12
+ # job_id set on TIMEOUT / failed jobs when a job was involved
13
+ class Error < StandardError
14
+ attr_reader :status, :code, :request_id, :retry_after, :details, :job_id
15
+
16
+ def initialize(message, code:, status: 0, request_id: nil, retry_after: nil, details: nil, job_id: nil)
17
+ super(message)
18
+ @status = status
19
+ @code = code
20
+ @request_id = request_id
21
+ @retry_after = retry_after
22
+ @details = details
23
+ @job_id = job_id
24
+ end
25
+
26
+ # True for 429, 5xx and NETWORK_ERROR.
27
+ def retryable?
28
+ @status == 429 || (@status >= 500 && @status <= 599) || @code == "NETWORK_ERROR"
29
+ end
30
+ alias retryable retryable?
31
+ end
32
+ end
@@ -0,0 +1,62 @@
1
+ # frozen_string_literal: true
2
+
3
+ module YouTubeTranscriptNet
4
+ Segment = Struct.new(:text, :start, :duration, keyword_init: true)
5
+
6
+ # A saved transcript. `raw` is the original parsed JSON (symbol keys).
7
+ Transcript = Struct.new(
8
+ :platform, :external_id, :lang, :origin, :title, :channel, :duration_sec, :segments, :raw,
9
+ keyword_init: true
10
+ )
11
+
12
+ # A finished transcript (`status == "success"`). Unknown fields stay available in `raw`.
13
+ TranscriptResult = Struct.new(
14
+ :status, :job_id, :language, :format, :cached, :length_seconds, :length_text,
15
+ :transcript, :text, :metadata, :raw,
16
+ keyword_init: true
17
+ ) do
18
+ def success? = status == "success"
19
+ end
20
+
21
+ # A transcript that is still being made (`pending` / `processing`).
22
+ Job = Struct.new(:status, :job_id, :stage, :error, :raw, keyword_init: true) do
23
+ def success? = false
24
+ end
25
+
26
+ # Builds model objects from parsed JSON (symbol keys).
27
+ module Models
28
+ module_function
29
+
30
+ def segment(hash)
31
+ Segment.new(text: hash[:text], start: hash[:start], duration: hash[:duration])
32
+ end
33
+
34
+ def transcript(hash)
35
+ return nil unless hash.is_a?(Hash)
36
+
37
+ Transcript.new(
38
+ platform: hash[:platform], external_id: hash[:externalId], lang: hash[:lang],
39
+ origin: hash[:origin], title: hash[:title], channel: hash[:channel],
40
+ duration_sec: hash[:durationSec],
41
+ segments: (hash[:segments] || []).map { |s| segment(s) }, raw: hash
42
+ )
43
+ end
44
+
45
+ def transcript_result(hash)
46
+ TranscriptResult.new(
47
+ status: hash[:status], job_id: hash[:jobId], language: hash[:language], format: hash[:format],
48
+ cached: hash[:cached], length_seconds: hash[:lengthSeconds], length_text: hash[:lengthText],
49
+ transcript: transcript(hash[:transcript]), text: hash[:text], metadata: hash[:metadata], raw: hash
50
+ )
51
+ end
52
+
53
+ def job(hash)
54
+ Job.new(status: hash[:status], job_id: hash[:jobId], stage: hash[:stage], error: hash[:error], raw: hash)
55
+ end
56
+
57
+ # A success body becomes a TranscriptResult, anything else a Job.
58
+ def transcript_or_job(hash)
59
+ hash[:status] == "success" ? transcript_result(hash) : job(hash)
60
+ end
61
+ end
62
+ end
@@ -0,0 +1,129 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "securerandom"
5
+ require "uri"
6
+ require "timeout"
7
+
8
+ module YouTubeTranscriptNet
9
+ # Builds requests, maps failures onto Error, and applies the retry rules.
10
+ # Internal: use Client.
11
+ class Requester
12
+ MAX_RETRY_AFTER = 60
13
+
14
+ NETWORK_ERRORS = [
15
+ SocketError, SystemCallError, IOError, EOFError, OpenSSL::SSL::SSLError,
16
+ Net::ProtocolError, Net::HTTPBadResponse
17
+ ].freeze
18
+
19
+ attr_reader :sleeper
20
+
21
+ def initialize(api_key:, base_url:, timeout:, max_retries:, transport:, sleeper:)
22
+ @api_key = api_key
23
+ @base_url = base_url
24
+ @timeout = timeout
25
+ @max_retries = max_retries
26
+ @transport = transport
27
+ @sleeper = sleeper
28
+ end
29
+
30
+ # Sends a request and returns the TransportResponse of a 2xx answer.
31
+ # `retry_ok` says whether the call may be repeated automatically (GET, DELETE and
32
+ # POST /v1/transcript with an Idempotency-Key).
33
+ def execute(method, path, query: nil, body: nil, headers: {}, retry_ok: false)
34
+ url = build_url(path, query)
35
+ payload = body.nil? ? nil : JSON.generate(body)
36
+ all_headers = default_headers(payload).merge(headers)
37
+ attempt = 0
38
+ loop do
39
+ return send_once(method, url, all_headers, payload)
40
+ rescue Error => e
41
+ raise unless retry_ok && e.retryable? && attempt < @max_retries
42
+
43
+ @sleeper.call(backoff(e, attempt))
44
+ attempt += 1
45
+ end
46
+ end
47
+
48
+ # Same as execute, then parses the JSON body (symbol keys).
49
+ def json(method, path, **opts)
50
+ response = execute(method, path, **opts)
51
+ text = response.body.to_s
52
+ return {} if text.strip.empty?
53
+
54
+ JSON.parse(text, symbolize_names: true)
55
+ rescue JSON::ParserError
56
+ raise Error.new("The server answered with invalid JSON.", code: "INVALID_RESPONSE",
57
+ status: response.status,
58
+ request_id: response.headers["x-request-id"])
59
+ end
60
+
61
+ private
62
+
63
+ def build_url(path, query)
64
+ url = "#{@base_url}#{path}"
65
+ pairs = (query || {}).reject { |_, v| v.nil? }.map { |k, v| [k.to_s, v.to_s] }
66
+ pairs.empty? ? url : "#{url}?#{URI.encode_www_form(pairs)}"
67
+ end
68
+
69
+ def default_headers(payload)
70
+ headers = {
71
+ "Authorization" => "Bearer #{@api_key}",
72
+ "User-Agent" => "youtubetranscript-net-ruby/#{VERSION}",
73
+ "Accept" => "application/json"
74
+ }
75
+ headers["Content-Type"] = "application/json" if payload
76
+ headers
77
+ end
78
+
79
+ def send_once(method, url, headers, payload)
80
+ response = begin
81
+ @transport.call(method, url, headers, payload, @timeout)
82
+ rescue Net::OpenTimeout, Net::ReadTimeout, Net::WriteTimeout, Timeout::Error
83
+ raise Error.new("The request timed out after #{@timeout} seconds.", code: "TIMEOUT")
84
+ rescue *NETWORK_ERRORS => e
85
+ raise Error.new("Network error: #{e.message}", code: "NETWORK_ERROR")
86
+ end
87
+ return response if response.status >= 200 && response.status < 300
88
+
89
+ raise error_from(response)
90
+ end
91
+
92
+ def error_from(response)
93
+ request_id = response.headers["x-request-id"]
94
+ retry_after = parse_retry_after(response.headers["retry-after"])
95
+ details = nil
96
+ begin
97
+ parsed = JSON.parse(response.body.to_s, symbolize_names: true)
98
+ details = parsed[:error] if parsed.is_a?(Hash) && parsed[:error].is_a?(Hash)
99
+ rescue JSON::ParserError
100
+ details = nil
101
+ end
102
+
103
+ if details && details[:code]
104
+ message = details[:message] || "Request failed with HTTP #{response.status}."
105
+ Error.new(message, code: details[:code].to_s, status: response.status, request_id: request_id,
106
+ retry_after: retry_after, details: details, job_id: details[:jobId])
107
+ else
108
+ Error.new("Request failed with HTTP #{response.status}.", code: "HTTP_#{response.status}",
109
+ status: response.status, request_id: request_id,
110
+ retry_after: retry_after)
111
+ end
112
+ end
113
+
114
+ def parse_retry_after(value)
115
+ return nil if value.nil?
116
+
117
+ seconds = Float(value.to_s.strip, exception: false)
118
+ return nil if seconds.nil? || seconds.negative?
119
+
120
+ (seconds % 1).zero? ? seconds.to_i : seconds
121
+ end
122
+
123
+ def backoff(error, attempt)
124
+ return [error.retry_after, MAX_RETRY_AFTER].min if error.retry_after
125
+
126
+ (0.5 * (2**attempt)) + (rand * 0.25)
127
+ end
128
+ end
129
+ end
@@ -0,0 +1,182 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "uri"
4
+
5
+ module YouTubeTranscriptNet
6
+ # Shared helpers for the resource classes.
7
+ class Resource
8
+ def initialize(requester)
9
+ @http = requester
10
+ end
11
+
12
+ private
13
+
14
+ def monotonic = Process.clock_gettime(Process::CLOCK_MONOTONIC)
15
+
16
+ def segment(value)
17
+ URI.encode_www_form_component(value.to_s).gsub("+", "%20")
18
+ end
19
+
20
+ def bool_param(value)
21
+ value.nil? ? nil : value.to_s
22
+ end
23
+
24
+ def retry_wait(error)
25
+ [error.retry_after || 0, Requester::MAX_RETRY_AFTER].min
26
+ end
27
+ end
28
+
29
+ class Transcripts < Resource
30
+ # Gets a transcript and waits for it: POST /v1/transcript, then polls the job while it
31
+ # is pending. Returns a TranscriptResult. Raises Error (code TIMEOUT after `timeout`
32
+ # seconds, or the job's own error code when the job fails).
33
+ def get(video, language: nil, format: nil, include_timestamp: nil, send_metadata: nil,
34
+ confirm_credits: nil, timeout: 300, poll_interval: 2)
35
+ current = post_transcript(video, language: language, format: format, include_timestamp: include_timestamp,
36
+ send_metadata: send_metadata, confirm_credits: confirm_credits,
37
+ wait_ms: 10_000)
38
+ job_id = current.job_id
39
+ deadline = monotonic + timeout
40
+ loop do
41
+ return current if current.is_a?(TranscriptResult)
42
+ raise failed_job_error(current) if current.status == "failed"
43
+
44
+ remaining = deadline - monotonic
45
+ if remaining <= 0
46
+ raise Error.new("The transcript was not ready after #{timeout} seconds.", code: "TIMEOUT", job_id: job_id)
47
+ end
48
+
49
+ @http.sleeper.call([poll_interval, remaining].min)
50
+ begin
51
+ current = job(job_id)
52
+ rescue Error => e
53
+ raise unless e.status == 429
54
+
55
+ @http.sleeper.call([retry_wait(e), [deadline - monotonic, 0].max].min)
56
+ end
57
+ end
58
+ end
59
+
60
+ # Sends the request once and returns the first answer as-is: a TranscriptResult
61
+ # (status "success") or a Job (status "pending" / "processing").
62
+ def submit(video, language: nil, format: nil, include_timestamp: nil, send_metadata: nil,
63
+ confirm_credits: nil, wait_ms: nil)
64
+ post_transcript(video, language: language, format: format, include_timestamp: include_timestamp,
65
+ send_metadata: send_metadata, confirm_credits: confirm_credits, wait_ms: wait_ms)
66
+ end
67
+
68
+ # GET /v1/transcript/job/{jobId}: a TranscriptResult once finished, otherwise a Job.
69
+ def job(job_id)
70
+ Models.transcript_or_job(@http.json(:get, "/v1/transcript/job/#{segment(job_id)}", retry_ok: true))
71
+ end
72
+
73
+ # GET /v1/transcript/info: video details and caption languages (free). Returns a Hash.
74
+ def info(video)
75
+ @http.json(:get, "/v1/transcript/info", query: { url: video }, retry_ok: true)
76
+ end
77
+
78
+ # GET /v1/library/transcripts. Returns {transcripts:, total:, page:, pageSize:, langs:}.
79
+ def list(q: nil, lang: nil, sort: nil, page: nil, page_size: nil)
80
+ @http.json(:get, "/v1/library/transcripts", retry_ok: true,
81
+ query: { q: q, lang: lang, sort: sort, page: page,
82
+ pageSize: page_size })
83
+ end
84
+
85
+ # Downloads a saved transcript as text (txt, srt, vtt, md; json also as a String).
86
+ def download(video_id, format = "txt", language: nil)
87
+ response = @http.execute(:get, "/v1/library/transcripts/youtube/#{segment(video_id)}/download",
88
+ query: { format: format, language: language }, retry_ok: true)
89
+ response.body.to_s.dup.force_encoding(Encoding::UTF_8)
90
+ end
91
+
92
+ # DELETE /v1/library/transcripts/youtube/{videoId}. Returns {removed: true}.
93
+ def delete(video_id, language: nil)
94
+ @http.json(:delete, "/v1/library/transcripts/youtube/#{segment(video_id)}",
95
+ query: { language: language }, retry_ok: true)
96
+ end
97
+
98
+ private
99
+
100
+ def post_transcript(video, language:, format:, include_timestamp:, send_metadata:, confirm_credits:, wait_ms:)
101
+ body = { url: video, waitMs: wait_ms, language: language, format: format,
102
+ includeTimestamp: include_timestamp, sendMetadata: send_metadata,
103
+ confirmCredits: confirm_credits }.compact
104
+ # One key per call: automatic retries reuse it, so the server never charges twice.
105
+ headers = { "Idempotency-Key" => SecureRandom.uuid }
106
+ Models.transcript_or_job(@http.json(:post, "/v1/transcript", body: body, headers: headers, retry_ok: true))
107
+ end
108
+
109
+ def failed_job_error(job)
110
+ err = job.error.is_a?(Hash) ? job.error : {}
111
+ Error.new(err[:message] || "The transcript job failed.", code: (err[:code] || "TRANSCRIPT_FAILED").to_s,
112
+ status: 0, details: err.empty? ? nil : err,
113
+ job_id: job.job_id)
114
+ end
115
+ end
116
+
117
+ class Batches < Resource
118
+ # POST /v1/batch with exactly one of items (array of links), playlist or channel.
119
+ # Not retried automatically (a repeat could charge twice). Returns the batch Hash.
120
+ def create(items: nil, playlist: nil, channel: nil, language: nil, limit: nil, name: nil)
121
+ given = [items, playlist, channel].count { |v| !v.nil? }
122
+ raise Error.new("Pass exactly one of items, playlist or channel.", code: "INVALID_REQUEST") if given != 1
123
+
124
+ body = { items: items&.map { |url| { url: url } }, playlist: playlist, channel: channel,
125
+ language: language, limit: limit, name: name }.compact
126
+ @http.json(:post, "/v1/batch", body: body)[:batch]
127
+ end
128
+
129
+ # GET /v1/batch/{batchId}. Returns {batch:, items:, nextPageToken:}.
130
+ def get(batch_id, max_results: nil, page_token: nil)
131
+ @http.json(:get, "/v1/batch/#{segment(batch_id)}", retry_ok: true,
132
+ query: { maxResults: max_results, pageToken: page_token })
133
+ end
134
+
135
+ # Polls get until batch.status is completed or failed; returns the last get result.
136
+ def wait(batch_id, timeout: 1800, poll_interval: 3)
137
+ deadline = monotonic + timeout
138
+ loop do
139
+ begin
140
+ result = get(batch_id)
141
+ return result if %w[completed failed].include?(result.dig(:batch, :status))
142
+ rescue Error => e
143
+ raise unless e.status == 429
144
+
145
+ @http.sleeper.call([retry_wait(e), [deadline - monotonic, 0].max].min)
146
+ end
147
+ remaining = deadline - monotonic
148
+ if remaining <= 0
149
+ raise Error.new("The batch was not finished after #{timeout} seconds.", code: "TIMEOUT",
150
+ details: { batchId: batch_id })
151
+ end
152
+
153
+ @http.sleeper.call([poll_interval, remaining].min)
154
+ end
155
+ end
156
+
157
+ # GET /v1/batch/{batchId}/export. Returns the file as a binary String (zip bytes by default).
158
+ def export(batch_id, format: "zip", files: nil, timestamps: nil)
159
+ response = @http.execute(:get, "/v1/batch/#{segment(batch_id)}/export", retry_ok: true,
160
+ query: { format: format, files: files,
161
+ timestamps: bool_param(timestamps) })
162
+ response.body.to_s.dup.force_encoding(Encoding::BINARY)
163
+ end
164
+
165
+ # POST /v1/batch/{batchId}/retry. Not retried automatically. Returns {batch:, retried:, credits:}.
166
+ def retry(batch_id)
167
+ @http.json(:post, "/v1/batch/#{segment(batch_id)}/retry")
168
+ end
169
+
170
+ # DELETE /v1/library/batches/{batchId}. Returns {removed: true}.
171
+ def delete(batch_id)
172
+ @http.json(:delete, "/v1/library/batches/#{segment(batch_id)}", retry_ok: true)
173
+ end
174
+ end
175
+
176
+ class Account < Resource
177
+ # GET /v1/usage. Returns {credits: {balance:, freeToday:, available:, hasPurchased:}, batch:, limits:}.
178
+ def usage
179
+ @http.json(:get, "/v1/usage", retry_ok: true)
180
+ end
181
+ end
182
+ end
@@ -0,0 +1,51 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "net/http"
4
+ require "openssl"
5
+ require "uri"
6
+
7
+ module YouTubeTranscriptNet
8
+ # What a transport returns. `headers` keys are lower-case strings.
9
+ TransportResponse = Struct.new(:status, :headers, :body, keyword_init: true)
10
+
11
+ # The default transport, built on Net::HTTP. A transport is any object that responds to
12
+ #
13
+ # call(method, url, headers, body, timeout) -> TransportResponse
14
+ #
15
+ # and raises Net::OpenTimeout / Net::ReadTimeout / Timeout::Error on timeouts and any
16
+ # SystemCallError / SocketError / IOError / OpenSSL::SSL::SSLError on network failures.
17
+ # Pass your own with `Client.new(transport: ...)`.
18
+ class NetHTTPTransport
19
+ def call(method, url, headers, body, timeout)
20
+ uri = URI.parse(url)
21
+ request = request_class(method).new(uri.request_uri, headers)
22
+ request.body = body if body
23
+
24
+ http = Net::HTTP.new(uri.host, uri.port)
25
+ http.use_ssl = uri.scheme == "https"
26
+ http.open_timeout = timeout
27
+ http.read_timeout = timeout
28
+ http.write_timeout = timeout
29
+ http.max_retries = 0 # retries are the SDK's job (see Requester), never Net::HTTP's
30
+ http.start do |conn|
31
+ response = conn.request(request)
32
+ TransportResponse.new(
33
+ status: response.code.to_i,
34
+ headers: response.each_header.to_h { |k, v| [k.downcase, v] },
35
+ body: response.body.to_s
36
+ )
37
+ end
38
+ end
39
+
40
+ private
41
+
42
+ def request_class(method)
43
+ case method
44
+ when :get then Net::HTTP::Get
45
+ when :post then Net::HTTP::Post
46
+ when :delete then Net::HTTP::Delete
47
+ else raise ArgumentError, "unsupported method #{method.inspect}"
48
+ end
49
+ end
50
+ end
51
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module YouTubeTranscriptNet
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "net/http"
4
+ require "openssl"
5
+ require "json"
6
+ require "securerandom"
7
+
8
+ require_relative "youtubetranscript_net/version"
9
+ require_relative "youtubetranscript_net/error"
10
+ require_relative "youtubetranscript_net/models"
11
+ require_relative "youtubetranscript_net/transport"
12
+ require_relative "youtubetranscript_net/requester"
13
+ require_relative "youtubetranscript_net/resources"
14
+ require_relative "youtubetranscript_net/client"
metadata ADDED
@@ -0,0 +1,56 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: youtubetranscript-net
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - YouTubeTranscript.net
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies: []
12
+ description: Get YouTube transcripts with timestamps, download them as TXT/SRT/VTT,
13
+ and run bulk batches from Ruby. Standard library only.
14
+ email:
15
+ - dev@youtubetranscript.net
16
+ executables: []
17
+ extensions: []
18
+ extra_rdoc_files: []
19
+ files:
20
+ - LICENSE
21
+ - README.md
22
+ - lib/youtubetranscript_net.rb
23
+ - lib/youtubetranscript_net/client.rb
24
+ - lib/youtubetranscript_net/error.rb
25
+ - lib/youtubetranscript_net/models.rb
26
+ - lib/youtubetranscript_net/requester.rb
27
+ - lib/youtubetranscript_net/resources.rb
28
+ - lib/youtubetranscript_net/transport.rb
29
+ - lib/youtubetranscript_net/version.rb
30
+ homepage: https://youtubetranscript.net/docs/api
31
+ licenses:
32
+ - MIT
33
+ metadata:
34
+ homepage_uri: https://youtubetranscript.net/docs/api
35
+ documentation_uri: https://youtubetranscript.net/docs/api
36
+ source_code_uri: https://github.com/youtube-transcript/youtubetranscript-ruby
37
+ bug_tracker_uri: https://github.com/youtube-transcript/youtubetranscript-ruby/issues
38
+ rubygems_mfa_required: 'true'
39
+ rdoc_options: []
40
+ require_paths:
41
+ - lib
42
+ required_ruby_version: !ruby/object:Gem::Requirement
43
+ requirements:
44
+ - - ">="
45
+ - !ruby/object:Gem::Version
46
+ version: '3.1'
47
+ required_rubygems_version: !ruby/object:Gem::Requirement
48
+ requirements:
49
+ - - ">="
50
+ - !ruby/object:Gem::Version
51
+ version: '0'
52
+ requirements: []
53
+ rubygems_version: 3.6.9
54
+ specification_version: 4
55
+ summary: Ruby client for the YouTubeTranscript.net API.
56
+ test_files: []