Skip to content

Commit d203625

Browse files
aryanA101abenoit74
authored andcommitted
migrate to generic syntax in all std collections
1 parent ca59669 commit d203625

File tree

22 files changed

+121
-81
lines changed

22 files changed

+121
-81
lines changed

contrib/encode_video.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1+
from __future__ import annotations
2+
13
import sys
24
from pathlib import Path
3-
from typing import List
45

56
from zimscraperlib import logger
67
from zimscraperlib.video import presets, reencode
@@ -25,7 +26,7 @@ def encode_video(src_path: Path, dst_path: Path, preset: str):
2526
logger.error(f"conversion failed:\n{process.stdout}")
2627

2728

28-
def run(args: List[str] = sys.argv):
29+
def run(args: list[str] = sys.argv):
2930
if len(args) < 4: # noqa: PLR2004
3031
print(f"Usage: {args[0]} <src_path> <dst_path> <preset>") # noqa: T201
3132
print( # noqa: T201

src/zimscraperlib/download.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
import pathlib
88
import subprocess
99
from concurrent.futures import Future, ThreadPoolExecutor
10-
from typing import ClassVar, Dict, Optional, Union
10+
from typing import ClassVar, Optional, Union
1111

1212
import requests
1313
import yt_dlp as youtube_dl
@@ -34,14 +34,14 @@ def shutdown(self) -> None:
3434
"""shuts down the executor, awaiting completion"""
3535
self.executor.shutdown(wait=True)
3636

37-
def _run_youtube_dl(self, url: str, options: Dict) -> None:
37+
def _run_youtube_dl(self, url: str, options: dict) -> None:
3838
with youtube_dl.YoutubeDL(options) as ydl:
3939
ydl.download([url])
4040

4141
def download(
4242
self,
4343
url: str,
44-
options: Optional[Dict],
44+
options: Optional[dict],
4545
wait: Optional[bool] = True, # noqa: FBT002
4646
) -> Union[bool, Future]:
4747
"""Downloads video using initialized executor.
@@ -65,8 +65,8 @@ def download(
6565

6666

6767
class YoutubeConfig(dict):
68-
options: ClassVar[Dict[str, Optional[Union[str, bool, int]]]] = {}
69-
defaults: ClassVar[Dict[str, Optional[Union[str, bool, int]]]] = {
68+
options: ClassVar[dict[str, Optional[Union[str, bool, int]]]] = {}
69+
defaults: ClassVar[dict[str, Optional[Union[str, bool, int]]]] = {
7070
"writethumbnail": True,
7171
"write_all_thumbnails": True,
7272
"writesubtitles": True,
@@ -109,14 +109,14 @@ def get_options(
109109

110110

111111
class BestWebm(YoutubeConfig):
112-
options: ClassVar[Dict[str, Optional[Union[str, bool, int]]]] = {
112+
options: ClassVar[dict[str, Optional[Union[str, bool, int]]]] = {
113113
"preferredcodec": "webm",
114114
"format": "best[ext=webm]/bestvideo[ext=webm]+bestaudio[ext=webm]/best",
115115
}
116116

117117

118118
class BestMp4(YoutubeConfig):
119-
options: ClassVar[Dict[str, Optional[Union[str, bool, int]]]] = {
119+
options: ClassVar[dict[str, Optional[Union[str, bool, int]]]] = {
120120
"preferredcodec": "mp4",
121121
"format": "best[ext=mp4]/bestvideo[ext=mp4]+bestaudio[ext=m4a]/best",
122122
}
@@ -179,7 +179,7 @@ def stream_file(
179179
proxies: Optional[dict] = None,
180180
only_first_block: Optional[bool] = False, # noqa: FBT002
181181
max_retries: Optional[int] = 5,
182-
headers: Optional[Dict[str, str]] = None,
182+
headers: Optional[dict[str, str]] = None,
183183
session: Optional[requests.Session] = None,
184184
) -> tuple[int, requests.structures.CaseInsensitiveDict]: # pyright: ignore
185185
"""Stream data from a URL to either a BytesIO object or a file

src/zimscraperlib/filesystem.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@
77

88
import os
99
import pathlib
10-
from typing import Any, Callable, Optional, Union
10+
from collections.abc import Callable
11+
from typing import Any, Optional, Union
1112

1213
import magic
1314

src/zimscraperlib/fix_ogvjs_dist.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,12 @@
44

55
""" quick script to fix videojs-ogvjs so that it triggers on webm mimetype """
66

7+
from __future__ import annotations
8+
79
import logging
810
import pathlib
911
import sys
10-
from typing import List, Union
12+
from typing import Union
1113

1214
logging.basicConfig(format="%(levelname)s:%(message)s", level=logging.DEBUG)
1315
logger = logging.getLogger(__name__)
@@ -33,7 +35,7 @@ def fix_source_dir(source_vendors_path: Union[pathlib.Path, str]):
3335
logger.info("all done.")
3436

3537

36-
def run(args: List[str] = sys.argv):
38+
def run(args: list[str] = sys.argv):
3739
if len(args) < 2: # noqa: PLR2004
3840
print(f"Usage: {args[0]} <source_vendors_path>") # noqa: T201
3941
print( # noqa: T201

src/zimscraperlib/i18n.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
#!/usr/bin/env python3
22
# vim: ai ts=4 sts=4 et sw=4 nu
33

4+
from __future__ import annotations
5+
46
import gettext
57
import locale
68
import pathlib
79
import re
8-
from typing import Dict, Optional, Tuple, Union
10+
from typing import Optional, Union
911

1012
import babel
1113
import iso639
@@ -58,7 +60,7 @@ def setlocale(root_dir: pathlib.Path, locale_name: str):
5860
return Locale.setup(root_dir / "locale", locale_name)
5961

6062

61-
def get_iso_lang_data(lang: str) -> Tuple[Dict, Union[Dict, None]]:
63+
def get_iso_lang_data(lang: str) -> tuple[dict, Union[dict, None]]:
6264
"""ISO-639-x languages details for lang. Raises NotFound
6365
6466
Included keys: iso-639-1, iso-639-2b, iso-639-2t, iso-639-3, iso-639-5
@@ -112,8 +114,8 @@ def replace_types(new_type: str) -> str:
112114

113115

114116
def find_language_names(
115-
query: str, lang_data: Optional[Dict] = None
116-
) -> Tuple[str, str]:
117+
query: str, lang_data: Optional[dict] = None
118+
) -> tuple[str, str]:
117119
"""(native, english) language names for lang with help from language_details dict
118120
119121
Falls back to English name if available or query if not"""
@@ -140,7 +142,7 @@ def find_language_names(
140142
return default, default
141143

142144

143-
def update_with_macro(lang_data: Dict, macro_data: Dict):
145+
def update_with_macro(lang_data: dict, macro_data: dict):
144146
"""update empty keys from lang_data with ones of macro_data"""
145147
if macro_data:
146148
for key, value in macro_data.items():
@@ -151,7 +153,7 @@ def update_with_macro(lang_data: Dict, macro_data: Dict):
151153

152154
def get_language_details(
153155
query: str, failsafe: Optional[bool] = False # noqa: FBT002
154-
) -> Dict:
156+
) -> dict:
155157
"""language details dict from query.
156158
157159
Raises NotFound or return `und` language details if failsafe

src/zimscraperlib/image/optimization.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,12 +22,13 @@
2222
can still run on default settings which give
2323
a bit less size than the original images but maintain a high quality. """
2424

25+
from __future__ import annotations
2526

2627
import io
2728
import os
2829
import pathlib
2930
import subprocess
30-
from typing import Optional, Tuple, Union
31+
from typing import Optional, Union
3132

3233
import piexif
3334
from optimize_images.img_aux_processing import do_reduce_colors, rebuild_palette
@@ -57,7 +58,7 @@ def optimize_png(
5758
max_colors: Optional[int] = 256,
5859
fast_mode: Optional[bool] = True, # noqa: FBT002
5960
remove_transparency: Optional[bool] = False, # noqa: FBT002
60-
background_color: Optional[Tuple[int, int, int]] = (255, 255, 255),
61+
background_color: Optional[tuple[int, int, int]] = (255, 255, 255),
6162
**options, # noqa: ARG001
6263
) -> Union[pathlib.Path, io.BytesIO]:
6364
"""method to optimize PNG files using a pure python external optimizer

src/zimscraperlib/image/presets.py

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
#!/usr/bin/env python3
22
# vim: ai ts=4 sts=4 et sw=4 nu
33

4-
from typing import ClassVar, Dict, Optional, Union
4+
from __future__ import annotations
5+
6+
from typing import ClassVar, Optional, Union
57

68
""" presets for ImageOptimizer in zimscraperlib.image.optimization module """
79

@@ -20,7 +22,7 @@ class WebpLow:
2022
ext = "webp"
2123
mimetype = f"{preset_type}/webp"
2224

23-
options: ClassVar[Dict[str, Optional[Union[str, bool, int]]]] = {
25+
options: ClassVar[dict[str, Optional[Union[str, bool, int]]]] = {
2426
"lossless": False,
2527
"quality": 40,
2628
"method": 6,
@@ -39,7 +41,7 @@ class WebpMedium:
3941
ext = "webp"
4042
mimetype = f"{preset_type}/webp"
4143

42-
options: ClassVar[Dict[str, Optional[Union[str, bool, int]]]] = {
44+
options: ClassVar[dict[str, Optional[Union[str, bool, int]]]] = {
4345
"lossless": False,
4446
"quality": 50,
4547
"method": 6,
@@ -58,7 +60,7 @@ class WebpHigh:
5860
ext = "webp"
5961
mimetype = f"{preset_type}/webp"
6062

61-
options: ClassVar[Dict[str, Optional[Union[str, bool, int]]]] = {
63+
options: ClassVar[dict[str, Optional[Union[str, bool, int]]]] = {
6264
"lossless": False,
6365
"quality": 90,
6466
"method": 6,
@@ -79,7 +81,7 @@ class GifLow:
7981
ext = "gif"
8082
mimetype = f"{preset_type}/gif"
8183

82-
options: ClassVar[Dict[str, Optional[Union[str, bool, int]]]] = {
84+
options: ClassVar[dict[str, Optional[Union[str, bool, int]]]] = {
8385
"optimize_level": 3,
8486
"max_colors": 256,
8587
"lossiness": 80,
@@ -102,7 +104,7 @@ class GifMedium:
102104
ext = "gif"
103105
mimetype = f"{preset_type}/gif"
104106

105-
options: ClassVar[Dict[str, Optional[Union[str, bool, int]]]] = {
107+
options: ClassVar[dict[str, Optional[Union[str, bool, int]]]] = {
106108
"optimize_level": 3,
107109
"lossiness": 20,
108110
"no_extensions": True,
@@ -124,7 +126,7 @@ class GifHigh:
124126
ext = "gif"
125127
mimetype = f"{preset_type}/gif"
126128

127-
options: ClassVar[Dict[str, Optional[Union[str, bool, int]]]] = {
129+
options: ClassVar[dict[str, Optional[Union[str, bool, int]]]] = {
128130
"optimize_level": 2,
129131
"lossiness": None,
130132
"no_extensions": True,
@@ -143,7 +145,7 @@ class PngLow:
143145
ext = "png"
144146
mimetype = f"{preset_type}/png"
145147

146-
options: ClassVar[Dict[str, Optional[Union[str, bool, int]]]] = {
148+
options: ClassVar[dict[str, Optional[Union[str, bool, int]]]] = {
147149
"reduce_colors": True,
148150
"remove_transparency": False,
149151
"max_colors": 256,
@@ -162,7 +164,7 @@ class PngMedium:
162164
ext = "png"
163165
mimetype = f"{preset_type}/png"
164166

165-
options: ClassVar[Dict[str, Optional[Union[str, bool, int]]]] = {
167+
options: ClassVar[dict[str, Optional[Union[str, bool, int]]]] = {
166168
"reduce_colors": False,
167169
"remove_transparency": False,
168170
"fast_mode": False,
@@ -180,7 +182,7 @@ class PngHigh:
180182
ext = "png"
181183
mimetype = f"{preset_type}/png"
182184

183-
options: ClassVar[Dict[str, Optional[Union[str, bool, int]]]] = {
185+
options: ClassVar[dict[str, Optional[Union[str, bool, int]]]] = {
184186
"reduce_colors": False,
185187
"remove_transparency": False,
186188
"fast_mode": True,
@@ -199,7 +201,7 @@ class JpegLow:
199201
ext = "png"
200202
mimetype = f"{preset_type}/png"
201203

202-
options: ClassVar[Dict[str, Optional[Union[str, bool, int]]]] = {
204+
options: ClassVar[dict[str, Optional[Union[str, bool, int]]]] = {
203205
"quality": 45,
204206
"keep_exif": False,
205207
"fast_mode": True,
@@ -218,7 +220,7 @@ class JpegMedium:
218220
ext = "jpg"
219221
mimetype = f"{preset_type}/jpeg"
220222

221-
options: ClassVar[Dict[str, Optional[Union[str, bool, int]]]] = {
223+
options: ClassVar[dict[str, Optional[Union[str, bool, int]]]] = {
222224
"quality": 65,
223225
"keep_exif": False,
224226
"fast_mode": True,
@@ -237,7 +239,7 @@ class JpegHigh:
237239
ext = "jpg"
238240
mimetype = f"{preset_type}/jpeg"
239241

240-
options: ClassVar[Dict[str, Optional[Union[str, bool, int]]]] = {
242+
options: ClassVar[dict[str, Optional[Union[str, bool, int]]]] = {
241243
"quality": 80,
242244
"keep_exif": True,
243245
"fast_mode": True,

src/zimscraperlib/image/probing.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,28 @@
11
#!/usr/bin/env python3
22
# vim: ai ts=4 sts=4 et sw=4 nu
33

4+
from __future__ import annotations
5+
46
import colorsys
57
import io
68
import pathlib
79
import re
8-
from typing import Optional, Tuple, Union
10+
from typing import Optional, Union
911

1012
import colorthief
1113
import PIL.Image
1214

1315

1416
def get_colors(
1517
src: pathlib.Path, use_palette: Optional[bool] = True # noqa: FBT002
16-
) -> Tuple[str, str]:
18+
) -> tuple[str, str]:
1719
"""(main, secondary) HTML color codes from an image path"""
1820

1921
def rgb_to_hex(r: int, g: int, b: int) -> str:
2022
"""hexadecimal HTML-friendly color code for RGB tuple"""
2123
return "#{}{}{}".format(*[str(hex(x)[2:]).zfill(2) for x in (r, g, b)]).upper()
2224

23-
def solarize(r: int, g: int, b: int) -> Tuple[int, int, int]:
25+
def solarize(r: int, g: int, b: int) -> tuple[int, int, int]:
2426
# calculate solarized color for main
2527
h, l, s = colorsys.rgb_to_hls( # noqa: E741
2628
float(r) / 256, float(g) / 256, float(b) / 256
@@ -71,7 +73,7 @@ def format_for(
7173
def is_valid_image(
7274
image: Union[pathlib.Path, io.IOBase, bytes],
7375
imformat: str,
74-
size: Optional[Tuple[int, int]] = None,
76+
size: Optional[tuple[int, int]] = None,
7577
) -> bool:
7678
"""whether image is a valid imformat (PNG) image, optionnaly of requested size"""
7779
if isinstance(image, bytes):

src/zimscraperlib/inputs.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
#!/usr/bin/env python3
22
# vim: ai ts=4 sts=4 et sw=4 nu
33

4+
from __future__ import annotations
5+
46
import pathlib
57
import shutil
68
import tempfile
7-
from typing import Optional, Tuple, Union
9+
from typing import Optional, Union
810

911
from zimscraperlib import logger
1012
from zimscraperlib.constants import (
@@ -60,7 +62,7 @@ def compute_descriptions(
6062
default_description: str,
6163
user_description: Optional[str],
6264
user_long_description: Optional[str],
63-
) -> Tuple[str, Optional[str]]:
65+
) -> tuple[str, Optional[str]]:
6466
"""Computes short and long descriptions compliant with ZIM standard.
6567
6668
Based on provided parameters, the function computes a short and a long description

src/zimscraperlib/logging.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,9 @@
55
import logging
66
import pathlib
77
import sys
8+
from collections.abc import Iterable
89
from logging.handlers import RotatingFileHandler
9-
from typing import Iterable, Optional
10+
from typing import Optional
1011

1112
from zimscraperlib.constants import NAME
1213

0 commit comments

Comments
 (0)