|
1 | | -from typing import Union |
| 1 | +from typing import Union, Iterable |
2 | 2 | from pathlib import Path |
3 | 3 | from zipfile import ZipFile |
4 | 4 | import io |
|
21 | 21 | from .config import settings |
22 | 22 |
|
23 | 23 |
|
| 24 | +def ordered(iterable: Iterable[str]) -> list[str]: |
| 25 | + unsorted = tuple(iterable) |
| 26 | + try: |
| 27 | + unsorted_path = tuple(Path(s) for s in unsorted) |
| 28 | + if any(unsorted_path[0].parent != p.parent for p in unsorted_path[1:]): |
| 29 | + raise ValueError |
| 30 | + return sorted(unsorted, key=lambda s: int(Path(s).stem)) |
| 31 | + except ValueError: |
| 32 | + return sorted(unsorted) |
| 33 | + |
24 | 34 | mimetypes.add_type('image/jxl', '.jxl') |
25 | 35 | def is_image(p: Union[str, Path]): |
26 | 36 | if Path(p).parts[0] == '__MACOSX': return False |
@@ -53,10 +63,10 @@ def extract_thumbnail(path: Union[str, Path], id: str, page: int, cache=False, c |
53 | 63 | return saveto.relative_to(settings.thumb) |
54 | 64 | saveto.parent.mkdir(parents=True, exist_ok=True) |
55 | 65 | if path.is_dir(): |
56 | | - convert_image(sorted(filter(is_image, path.iterdir()))[page-1], saveto, thumbnail=True) |
| 66 | + convert_image(ordered(filter(is_image, path.iterdir()))[page-1], saveto, thumbnail=True) |
57 | 67 | elif ArchiveFile.support_formats.fullmatch(path.name): |
58 | 68 | with ArchiveFile(path) as z: |
59 | | - with z.open(sorted(map(lambda z_info: z_info.filename, filter(lambda z_info: not z_info.is_dir() and is_image(z_info.filename), z.infolist())))[page-1]) as f: |
| 69 | + with z.open(ordered(map(lambda z_info: z_info.filename, filter(lambda z_info: not z_info.is_dir() and is_image(z_info.filename), z.infolist())))[page-1]) as f: |
60 | 70 | convert_image(f, saveto, thumbnail=True) |
61 | 71 | else: |
62 | 72 | raise NotImplementedError |
|
0 commit comments