Skip to content

Commit cc7239b

Browse files
committed
Run ruff format
1 parent 061d5b4 commit cc7239b

File tree

8 files changed

+51
-144
lines changed

8 files changed

+51
-144
lines changed

youtube_transcript_api/_cli.py

Lines changed: 5 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -65,14 +65,10 @@ def run(self) -> str:
6565
print_sections = [str(exception) for exception in exceptions]
6666
if transcripts:
6767
if parsed_args.list_transcripts:
68-
print_sections.extend(
69-
str(transcript_list) for transcript_list in transcripts
70-
)
68+
print_sections.extend(str(transcript_list) for transcript_list in transcripts)
7169
else:
7270
print_sections.append(
73-
FormatterLoader()
74-
.load(parsed_args.format)
75-
.format_transcripts(transcripts)
71+
FormatterLoader().load(parsed_args.format).format_transcripts(transcripts)
7672
)
7773

7874
return "\n\n".join(print_sections)
@@ -83,13 +79,9 @@ def _fetch_transcript(
8379
transcript_list: TranscriptList,
8480
) -> FetchedTranscript:
8581
if parsed_args.exclude_manually_created:
86-
transcript = transcript_list.find_generated_transcript(
87-
parsed_args.languages
88-
)
82+
transcript = transcript_list.find_generated_transcript(parsed_args.languages)
8983
elif parsed_args.exclude_generated:
90-
transcript = transcript_list.find_manually_created_transcript(
91-
parsed_args.languages
92-
)
84+
transcript = transcript_list.find_manually_created_transcript(parsed_args.languages)
9385
else:
9486
transcript = transcript_list.find_transcript(parsed_args.languages)
9587

@@ -116,9 +108,7 @@ def _parse_args(self):
116108
default=False,
117109
help="This will list the languages in which the given videos are available in.",
118110
)
119-
parser.add_argument(
120-
"video_ids", nargs="+", type=str, help="List of YouTube video IDs."
121-
)
111+
parser.add_argument("video_ids", nargs="+", type=str, help="List of YouTube video IDs.")
122112
parser.add_argument(
123113
"--languages",
124114
nargs="*",

youtube_transcript_api/_errors.py

Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,7 @@ class CookieInvalid(CookieError):
2626
def __init__(
2727
self, cookie_path: Path
2828
): # pragma: no cover until cookie authentication is re-implemented
29-
super().__init__(
30-
f"The cookies provided are not valid (may have expired): {cookie_path}"
31-
)
29+
super().__init__(f"The cookies provided are not valid (may have expired): {cookie_path}")
3230

3331

3432
class CouldNotRetrieveTranscript(YouTubeTranscriptApiException):
@@ -59,9 +57,7 @@ def _build_error_message(self) -> str:
5957

6058
cause = self.cause
6159
if cause:
62-
error_message += (
63-
self.CAUSE_MESSAGE_INTRO.format(cause=cause) + self.GITHUB_REFERRAL
64-
)
60+
error_message += self.CAUSE_MESSAGE_INTRO.format(cause=cause) + self.GITHUB_REFERRAL
6561

6662
return error_message
6763

@@ -107,9 +103,7 @@ def __init__(self, video_id: str, reason: Optional[str], sub_reasons: List[str])
107103
def cause(self):
108104
reason = "No reason specified!" if self.reason is None else self.reason
109105
if self.sub_reasons:
110-
sub_reasons = "\n".join(
111-
f" - {sub_reason}" for sub_reason in self.sub_reasons
112-
)
106+
sub_reasons = "\n".join(f" - {sub_reason}" for sub_reason in self.sub_reasons)
113107
reason = f"{reason}{self.SUBREASON_MESSAGE.format(sub_reasons=sub_reasons)}"
114108
return self.CAUSE_MESSAGE.format(
115109
reason=reason,
@@ -183,9 +177,7 @@ def __init__(self, video_id: str):
183177
self._proxy_config = None
184178
super().__init__(video_id)
185179

186-
def with_proxy_config(
187-
self, proxy_config: Optional[ProxyConfig]
188-
) -> "RequestBlocked":
180+
def with_proxy_config(self, proxy_config: Optional[ProxyConfig]) -> "RequestBlocked":
189181
self._proxy_config = proxy_config
190182
return self
191183

youtube_transcript_api/_transcripts.py

Lines changed: 11 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -167,9 +167,7 @@ def translate(self, language_code: str) -> "Transcript":
167167
return Transcript(
168168
self._http_client,
169169
self.video_id,
170-
"{url}&tlang={language_code}".format(
171-
url=self._url, language_code=language_code
172-
),
170+
"{url}&tlang={language_code}".format(url=self._url, language_code=language_code),
173171
self._translation_languages_dict[language_code],
174172
language_code,
175173
True,
@@ -204,9 +202,7 @@ def __init__(
204202
self._translation_languages = translation_languages
205203

206204
@staticmethod
207-
def build(
208-
http_client: Session, video_id: str, captions_json: Dict
209-
) -> "TranscriptList":
205+
def build(http_client: Session, video_id: str, captions_json: Dict) -> "TranscriptList":
210206
"""
211207
Factory method for TranscriptList.
212208
@@ -282,9 +278,7 @@ def find_generated_transcript(self, language_codes: Iterable[str]) -> Transcript
282278
"""
283279
return self._find_transcript(language_codes, [self._generated_transcripts])
284280

285-
def find_manually_created_transcript(
286-
self, language_codes: Iterable[str]
287-
) -> Transcript:
281+
def find_manually_created_transcript(self, language_codes: Iterable[str]) -> Transcript:
288282
"""
289283
Finds a manually created transcript for a given language code.
290284
@@ -293,9 +287,7 @@ def find_manually_created_transcript(
293287
it fails to do so.
294288
:return: the found Transcript
295289
"""
296-
return self._find_transcript(
297-
language_codes, [self._manually_created_transcripts]
298-
)
290+
return self._find_transcript(language_codes, [self._manually_created_transcripts])
299291

300292
def _find_transcript(
301293
self,
@@ -321,8 +313,7 @@ def __str__(self) -> str:
321313
).format(
322314
video_id=self.video_id,
323315
available_manually_created_transcript_languages=self._get_language_description(
324-
str(transcript)
325-
for transcript in self._manually_created_transcripts.values()
316+
str(transcript) for transcript in self._manually_created_transcripts.values()
326317
),
327318
available_generated_transcripts=self._get_language_description(
328319
str(transcript) for transcript in self._generated_transcripts.values()
@@ -338,8 +329,7 @@ def __str__(self) -> str:
338329

339330
def _get_language_description(self, transcript_strings: Iterable[str]) -> str:
340331
description = "\n".join(
341-
" - {transcript}".format(transcript=transcript)
342-
for transcript in transcript_strings
332+
" - {transcript}".format(transcript=transcript) for transcript in transcript_strings
343333
)
344334
return description if description else "None"
345335

@@ -363,11 +353,7 @@ def _fetch_captions_json(self, video_id: str, try_number: int = 0) -> Dict:
363353
innertube_data = self._fetch_innertube_data(video_id, api_key)
364354
return self._extract_captions_json(innertube_data, video_id)
365355
except RequestBlocked as exception:
366-
retries = (
367-
0
368-
if self._proxy_config is None
369-
else self._proxy_config.retries_when_blocked
370-
)
356+
retries = 0 if self._proxy_config is None else self._proxy_config.retries_when_blocked
371357
if try_number + 1 < retries:
372358
return self._fetch_captions_json(video_id, try_number=try_number + 1)
373359
raise exception.with_proxy_config(self._proxy_config)
@@ -384,20 +370,15 @@ def _extract_innertube_api_key(self, html: str, video_id: str) -> str:
384370
def _extract_captions_json(self, innertube_data: Dict, video_id: str) -> Dict:
385371
self._assert_playability(innertube_data.get("playabilityStatus"), video_id)
386372

387-
captions_json = innertube_data.get("captions", {}).get(
388-
"playerCaptionsTracklistRenderer"
389-
)
373+
captions_json = innertube_data.get("captions", {}).get("playerCaptionsTracklistRenderer")
390374
if captions_json is None or "captionTracks" not in captions_json:
391375
raise TranscriptsDisabled(video_id)
392376

393377
return captions_json
394378

395379
def _assert_playability(self, playability_status_data: Dict, video_id: str) -> None:
396380
playability_status = playability_status_data.get("status")
397-
if (
398-
playability_status != _PlayabilityStatus.OK.value
399-
and playability_status is not None
400-
):
381+
if playability_status != _PlayabilityStatus.OK.value and playability_status is not None:
401382
reason = playability_status_data.get("reason")
402383
if playability_status == _PlayabilityStatus.LOGIN_REQUIRED.value:
403384
if reason == _PlayabilityFailedReason.BOT_DETECTED.value:
@@ -417,17 +398,13 @@ def _assert_playability(self, playability_status_data: Dict, video_id: str) -> N
417398
.get("subreason", {})
418399
.get("runs", [])
419400
)
420-
raise VideoUnplayable(
421-
video_id, reason, [run.get("text", "") for run in subreasons]
422-
)
401+
raise VideoUnplayable(video_id, reason, [run.get("text", "") for run in subreasons])
423402

424403
def _create_consent_cookie(self, html: str, video_id: str) -> None:
425404
match = re.search('name="v" value="(.*?)"', html)
426405
if match is None:
427406
raise FailedToCreateConsentCookie(video_id)
428-
self._http_client.cookies.set(
429-
"CONSENT", "YES+" + match.group(1), domain=".youtube.com"
430-
)
407+
self._http_client.cookies.set("CONSENT", "YES+" + match.group(1), domain=".youtube.com")
431408

432409
def _fetch_video_html(self, video_id: str) -> str:
433410
html = self._fetch_html(video_id)

youtube_transcript_api/formatters.py

Lines changed: 5 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -16,14 +16,12 @@ class Formatter:
1616

1717
def format_transcript(self, transcript: FetchedTranscript, **kwargs) -> str:
1818
raise NotImplementedError(
19-
"A subclass of Formatter must implement "
20-
"their own .format_transcript() method."
19+
"A subclass of Formatter must implement their own .format_transcript() method."
2120
)
2221

2322
def format_transcripts(self, transcripts: List[FetchedTranscript], **kwargs):
2423
raise NotImplementedError(
25-
"A subclass of Formatter must implement "
26-
"their own .format_transcripts() method."
24+
"A subclass of Formatter must implement their own .format_transcripts() method."
2725
)
2826

2927

@@ -42,9 +40,7 @@ def format_transcripts(self, transcripts: List[FetchedTranscript], **kwargs) ->
4240
:param transcripts:
4341
:return: A JSON string representation of the transcript.
4442
"""
45-
return pprint.pformat(
46-
[transcript.to_raw_data() for transcript in transcripts], **kwargs
47-
)
43+
return pprint.pformat([transcript.to_raw_data() for transcript in transcripts], **kwargs)
4844

4945

5046
class JSONFormatter(Formatter):
@@ -62,9 +58,7 @@ def format_transcripts(self, transcripts: List[FetchedTranscript], **kwargs) ->
6258
:param transcripts:
6359
:return: A JSON string representation of the transcript.
6460
"""
65-
return json.dumps(
66-
[transcript.to_raw_data() for transcript in transcripts], **kwargs
67-
)
61+
return json.dumps([transcript.to_raw_data() for transcript in transcripts], **kwargs)
6862

6963

7064
class TextFormatter(Formatter):
@@ -90,8 +84,7 @@ def format_transcripts(self, transcripts: List[FetchedTranscript], **kwargs) ->
9084
class _TextBasedFormatter(TextFormatter):
9185
def _format_timestamp(self, hours: int, mins: int, secs: int, ms: int) -> str:
9286
raise NotImplementedError(
93-
"A subclass of _TextBasedFormatter must implement "
94-
"their own .format_timestamp() method."
87+
"A subclass of _TextBasedFormatter must implement their own .format_timestamp() method."
9588
)
9689

9790
def _format_transcript_header(self, lines: Iterable[str]) -> str:

youtube_transcript_api/proxies.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -75,8 +75,7 @@ def __init__(self, http_url: Optional[str] = None, https_url: Optional[str] = No
7575
"""
7676
if not http_url and not https_url:
7777
raise InvalidProxyConfig(
78-
"GenericProxyConfig requires you to define at least one of the two: "
79-
"http or https"
78+
"GenericProxyConfig requires you to define at least one of the two: http or https"
8079
)
8180
self.http_url = http_url
8281
self.https_url = https_url

youtube_transcript_api/test/test_api.py

Lines changed: 7 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -33,9 +33,7 @@
3333

3434
def get_asset_path(filename: str) -> Path:
3535
return Path(
36-
"{dirname}/assets/{filename}".format(
37-
dirname=os.path.dirname(__file__), filename=filename
38-
)
36+
"{dirname}/assets/{filename}".format(dirname=os.path.dirname(__file__), filename=filename)
3937
)
4038

4139

@@ -100,9 +98,7 @@ def test_fetch(self):
10098
)
10199

102100
def test_fetch_formatted(self):
103-
transcript = YouTubeTranscriptApi().fetch(
104-
"GJLlxj_dtq8", preserve_formatting=True
105-
)
101+
transcript = YouTubeTranscriptApi().fetch("GJLlxj_dtq8", preserve_formatting=True)
106102

107103
self.ref_transcript[1].text = "this is <i>not</i> the original transcript"
108104

@@ -130,9 +126,7 @@ def test_list(self):
130126

131127
language_codes = {transcript.language_code for transcript in transcript_list}
132128

133-
self.assertEqual(
134-
language_codes, {"zh", "de", "en", "hi", "ja", "ko", "es", "cs", "en"}
135-
)
129+
self.assertEqual(language_codes, {"zh", "de", "en", "hi", "ja", "ko", "es", "cs", "en"})
136130

137131
def test_list__find_manually_created(self):
138132
transcript_list = YouTubeTranscriptApi().list("GJLlxj_dtq8")
@@ -158,9 +152,7 @@ def test_list__url_as_video_id(self):
158152
)
159153

160154
with self.assertRaises(InvalidVideoId):
161-
YouTubeTranscriptApi().list(
162-
"https://www.youtube.com/youtubei/v1/player?v=GJLlxj_dtq8"
163-
)
155+
YouTubeTranscriptApi().list("https://www.youtube.com/youtubei/v1/player?v=GJLlxj_dtq8")
164156

165157
def test_translate_transcript(self):
166158
transcript = YouTubeTranscriptApi().list("GJLlxj_dtq8").find_transcript(["en"])
@@ -215,9 +207,7 @@ def test_fetch__create_consent_cookie_if_needed(self):
215207
YouTubeTranscriptApi().fetch("F1xioXWb8CY")
216208
self.assertEqual(len(httpretty.latest_requests()), 4)
217209
for request in httpretty.latest_requests()[1:]:
218-
self.assertEqual(
219-
request.headers["cookie"], "CONSENT=YES+cb.20210328-17-p0.de+FX+119"
220-
)
210+
self.assertEqual(request.headers["cookie"], "CONSENT=YES+cb.20210328-17-p0.de+FX+119")
221211

222212
def test_fetch__exception_if_create_consent_cookie_failed(self):
223213
for _ in range(2):
@@ -370,9 +360,7 @@ def test_fetch__with_proxy(self, to_requests_dict):
370360
http_url="http://localhost:8080",
371361
https_url="http://localhost:8080",
372362
)
373-
transcript = YouTubeTranscriptApi(proxy_config=proxy_config).fetch(
374-
"GJLlxj_dtq8"
375-
)
363+
transcript = YouTubeTranscriptApi(proxy_config=proxy_config).fetch("GJLlxj_dtq8")
376364
self.assertEqual(
377365
transcript,
378366
self.ref_transcript,
@@ -381,9 +369,7 @@ def test_fetch__with_proxy(self, to_requests_dict):
381369

382370
@patch("youtube_transcript_api.proxies.GenericProxyConfig.to_requests_dict")
383371
def test_fetch__with_proxy_prevent_alive_connections(self, to_requests_dict):
384-
proxy_config = WebshareProxyConfig(
385-
proxy_username="username", proxy_password="password"
386-
)
372+
proxy_config = WebshareProxyConfig(proxy_username="username", proxy_password="password")
387373

388374
YouTubeTranscriptApi(proxy_config=proxy_config).fetch("GJLlxj_dtq8")
389375

0 commit comments

Comments
 (0)