-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
photos.py
2337 lines (1951 loc) · 77 KB
/
photos.py
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import abc
import base64
from collections import namedtuple
import datetime
from functools import wraps
from html.parser import HTMLParser
import itertools
import json
import logging
import mimetypes
import multiprocessing
import multiprocessing.pool
import os
import pprint
import re
import time
from typing import Any, ClassVar, Dict, List, Optional, Tuple, Type, Union
import urllib.parse
from pelican import Pelican, signals
from pelican.contents import Article, Page
import pelican.generators
from pelican.generators import ArticlesGenerator, PagesGenerator
from pelican.settings import DEFAULT_CONFIG
from pelican.utils import pelican_open
logger = logging.getLogger(__name__)
pelican_settings: Dict[str, Any] = {}
pelican_output_path: Optional[str] = None
pelican_photo_inline_galleries = {}
g_generator = None
g_image_queue = []
g_profiles = {}
g_profiling_call_level = 0
g_process_pool: Optional[multiprocessing.Pool] = None
g_process_pool_initialized: bool = False
g_image_cache: Dict[str, "Image"] = {}
try:
from PIL import (
ExifTags,
Image as PILImage,
ImageDraw,
ImageEnhance,
ImageFont,
ImageOps,
)
except ImportError:
logger.error("PIL/Pillow not found") # noqa: TRY400
raise
EXIF_TAGS_NAME_CODE = {v: n for n, v in ExifTags.TAGS.items()}
try:
import piexif
except ImportError:
ispiexif = False
logger.warning("piexif not found! Cannot use exif manipulation features")
else:
ispiexif = True
logger.debug("piexif found.")
InlineContentData = namedtuple(
"InlineContentData", ["type", "image", "html_attributes"]
)
class BaseNoteParseError(Exception):
pass
class InternalError(Exception):
pass
class FileNotFound(Exception):
pass
class GalleryNotFound(Exception):
pass
class FileExcluded(Exception):
pass
class ImageExcluded(FileExcluded):
pass
class ImageConfigNotFound(Exception):
pass
class ProfileNotFound(Exception):
pass
class HTMLTagParser(HTMLParser):
def __init__(self):
super().__init__()
self.tag_attrs = {}
def handle_starttag(self, tag, attrs):
logger.debug(f"Found tag: {tag}")
self.tag_attrs.update(dict(attrs))
class HTMLImgParser(HTMLParser):
def __init__(self):
super().__init__()
self.img_attrs = ()
def handle_starttag(self, tag, attrs):
logger.debug(f"Found tag: {tag}")
if tag == "img":
self.img_attrs = attrs
class Profile:
def __init__(
self,
name: str,
config: Dict[str, Any],
default_profile: Optional["Profile"] = None,
):
self.name = name
self._config = config
self._default_profile = default_profile
def get_image_config(self, name) -> Dict[str, Any]:
images = self._config.get("images")
config = None
if images is not None:
config = images.get(name)
if config is None and self._default_profile is not None:
config = self._default_profile.get_image_config(name)
if config is None:
raise ImageConfigNotFound( # noqa: TRY003
f"Unable to find image config for '{name}' in profile '{self.name}'"
)
return config
def render_template(self, default_template_name=None, **kwargs):
tpl_name = self._config.get("template_name")
if tpl_name is None:
tpl_name = default_template_name
if tpl_name is None:
logger.error("Unable to find template for profile")
context_vars = {"SITEURL": pelican_settings["SITEURL"]}
context_vars.update(kwargs)
return g_generator.get_template(tpl_name).render(**context_vars)
@property
def file_suffix(self) -> str:
return self._config.get("file_suffix", "")
@property
def has_template(self) -> bool:
if "template_name" in self._config:
return True
return False
@property
def article_file_suffix(self) -> str:
return self.get_image_config("article").get("file_suffix", "a")
@property
def article_html_img_attributes(self) -> Dict[str, str]:
return self.get_image_config("article").get("html_img_attributes", {})
@property
def article_image_spec(self) -> Dict[str, Any]:
return self.get_image_config("article")["specs"]
@property
def gallery_file_suffix(self) -> str:
return self.get_image_config("gallery").get("file_suffix", "")
@property
def gallery_html_img_attributes(self) -> Dict[str, str]:
return self.get_image_config("gallery").get("html_img_attributes", {})
@property
def gallery_image_spec(self) -> Dict[str, Any]:
return self.get_image_config("gallery")["specs"]
@property
def thumb_file_suffix(self) -> str:
return self.get_image_config("thumb").get("file_suffix", "t")
@property
def thumb_html_img_attributes(self) -> Dict[str, str]:
return self.get_image_config("thumb").get("html_img_attributes", {})
@property
def thumb_image_spec(self) -> Dict[str, Any]:
return self.get_image_config("thumb")["specs"]
def measure_time(func):
@wraps(func)
def measure_time_wrapper(*args, **kwargs):
if pelican_settings.get("PHOTO_PROFILING_ENABLED") is not True:
return func(*args, **kwargs)
global g_profiling_call_level
msg_prefix_start = ""
msg_prefix_end = ""
if g_process_pool is None and g_profiling_call_level > 0:
msg_prefix_start = "|" * g_profiling_call_level + "-> "
msg_prefix_end = "|" * (g_profiling_call_level - 1) + "'-> "
logger.debug(
f"{msg_prefix_start}Calling {func.__name__}()"
f" with args {args} and kwargs {kwargs}"
)
start_time = time.perf_counter()
# resize_job_number == -1 -> no multiprocessing
if g_process_pool is None:
g_profiling_call_level += 1
result = func(*args, **kwargs)
if g_process_pool is None:
g_profiling_call_level -= 1
end_time = time.perf_counter()
total_time = end_time - start_time
logger.debug(
f"{msg_prefix_end}Call {func.__name__}() took {total_time:.4f} seconds"
)
return result
return measure_time_wrapper
@measure_time
def find_profile(names: List[str], default_not_found=True):
"""Find first matching profile."""
for name in names:
try:
return get_profile(name)
except ProfileNotFound:
pass
if default_not_found:
return get_profile("default")
raise ProfileNotFound(f"Unable to find any of the profiles: {', '.join(names)}")
def get_profile(name: str) -> Profile:
"""Return the profile."""
profile = g_profiles.get(name)
if profile is None:
raise ProfileNotFound(f"Unable to find profile '{name}'")
return profile
def get_image_from_string(
url_string: str,
image_class: Optional[Type["BaseImage"]] = None,
default_image_class: Optional[Type["BaseImage"]] = None,
) -> "BaseImage":
value_mapping = {
"profile": "profile_name",
}
url = urllib.parse.urlparse(url_string)
query_params = dict(urllib.parse.parse_qsl(url.query))
kwargs = {}
for query_name, arg_name in value_mapping.items():
if query_name in query_params:
kwargs[arg_name] = query_params.get(query_name)
if image_class is None and "type" in query_params:
image_type = query_params["type"].lower().strip()
if image_type == "content":
image_class = ContentImage
else:
logger.warning(
f"Unable to find image class for type='{image_type}'"
f" on '{url_string}' - Supported types are: content"
)
if image_class is None and default_image_class is not None:
logger.debug(f"Using default image class for '{url_string}'")
image_class = default_image_class
return image_class(filename=url.path, **kwargs)
class BaseNoteCache(abc.ABC):
note_cache: ClassVar[Dict[str, "BaseNoteCache"]] = {}
@abc.abstractclassmethod
def note_filename(cls):
raise NotImplementedError
def __init__(self, filename):
self.filename = filename
self.note_cache[self.filename] = self
self.notes: Dict[str, str] = {}
self._read()
@abc.abstractmethod
def _parse_line(self, line: str) -> Tuple[str, Any]:
raise NotImplementedError("Line parser not implemented")
def _read(self):
if not os.path.isfile(self.filename):
return
try:
logger.debug(f"Reading information from {self.filename}")
with pelican_open(self.filename) as text:
for line_number, line in enumerate(text.splitlines()):
line = line.strip() # noqa: PLW2901
# skip empty lines
if len(line) == 0:
continue
# skip comments
if line.startswith("#"):
continue
try:
result = self._parse_line(line)
self.notes[result[0]] = result[1]
except BaseNoteParseError as e:
logger.warning(
f"Parser error in file {self.filename}"
f" on line {line_number + 1}: {e}"
)
except Exception:
logger.exception(
f"There was an error while processing the {self.filename}. "
)
def get_value(self, source_image):
return self.notes.get(os.path.basename(source_image.filename))
@classmethod
def from_cache(cls, source_image: "SourceImage"):
filename = os.path.join(
os.path.dirname(source_image.filename), cls.note_filename()
)
notes = cls.note_cache.get(filename)
if notes is None:
notes = cls(filename=filename)
return notes
class BaseNoteKeyCache(BaseNoteCache):
def _parse_line(self, line: str) -> Tuple[str, bool]:
return line.strip(), True
class BaseNoteKeyValueCache(BaseNoteCache):
def _parse_line(self, line: str) -> Tuple[str, str]:
# parse content
m = line.split(":", 1)
if len(m) > 1:
return m[0].strip(), m[1].strip()
raise BaseNoteParseError(
"Wrong format. Expecting '<filename>: <value>' per line"
)
class CaptionCache(BaseNoteKeyValueCache):
@classmethod
def note_filename(cls):
return "captions.txt"
class ExifCache(BaseNoteKeyValueCache):
@classmethod
def note_filename(cls):
return "exif.txt"
class ExcludeCache(BaseNoteKeyCache):
@classmethod
def note_filename(cls):
return "blacklist.txt"
class BaseNote:
cache_class = None
def __init__(self, source_image):
self.cache = self.cache_class.from_cache(source_image)
self._value = self.cache.get_value(source_image)
def __str__(self):
return self.value
@property
def value(self):
return self._value
class Caption(BaseNote):
cache_class = CaptionCache
class Exif(BaseNote):
cache_class = ExifCache
class ExcludeList(BaseNote):
cache_class = ExcludeCache
class BaseImage:
regex_filename = re.compile(r"^({(?P<type>photo|filename)})?(?P<filename>.*)")
def __init__(
self,
filename: str,
profile_name: Optional[str] = None,
profile: Optional[Profile] = None,
):
m = self.regex_filename.match(filename)
self.filename_raw = filename
self.filename: str = m.group("filename")
self.filename_type: Optional[str] = m.group("type")
self.src_filename = os.path.join(
os.path.expanduser(pelican_settings["PHOTO_LIBRARY"]), self.filename
)
self.file = os.path.basename(self.filename).lower()
self.profile = profile
if self.profile is None:
if profile_name is None:
profile_name = "default"
try:
self.profile = get_profile(profile_name)
except ProfileNotFound:
logger.error(
f"Unable to find profile '{profile_name}' for image '{filename}'"
)
raise
class ArticleImage(BaseImage):
"""Images/photos on the top of an article or page.
:param content: Internal content object
:param filename: The filename of the image
:param generator: The generator
"""
def __init__(
self,
content: pelican.contents.Content,
filename: str,
profile_name: Optional[str] = None,
profile: Optional[Profile] = None,
):
super().__init__(filename, profile_name=profile_name, profile=profile)
if self.filename_type == "filename":
self.src_filename = os.path.join(
g_generator.path, content.relative_dir, self.filename
)
elif self.filename_type != "photo":
raise InternalError(f"Unable to detect image type {self.filename_raw}")
if not os.path.isfile(self.src_filename):
raise FileNotFound(
f"No photo for {content.source_path} at {self.filename} "
f"source {self.src_filename}"
)
photo = (
os.path.splitext(self.filename)[0].lower()
+ self.profile.article_file_suffix
+ self.profile.file_suffix
)
thumb = (
os.path.splitext(self.filename)[0].lower()
+ self.profile.thumb_file_suffix
+ self.profile.file_suffix
)
img = Image(
src=self.src_filename,
dst=os.path.join("photos", photo),
specs=self.profile.article_image_spec,
)
self.image = enqueue_image(img)
img = Image(
src=self.src_filename,
dst=os.path.join("photos", thumb),
specs=self.profile.thumb_image_spec,
is_thumb=True,
)
self.thumb = enqueue_image(img)
def __getitem__(self, index):
"""Legacy support."""
if index == 0:
return self.file
if index == 1:
return self.image.web_filename
if index == 2:
return self.thumb.web_filename
raise IndexError
class ContentImage(BaseImage):
def __init__(
self,
filename,
profile_name: Optional[str] = None,
profile: Optional[Profile] = None,
):
super().__init__(filename, profile_name=profile_name, profile=profile)
if not os.path.isfile(self.src_filename):
raise FileNotFound(f"No photo for {self.src_filename} {self.filename}")
img = Image(
src=self.src_filename,
dst=os.path.join(
"photos",
os.path.splitext(self.filename)[0].lower()
+ self.profile.article_file_suffix
+ self.profile.file_suffix,
),
specs=self.profile.article_image_spec,
)
self.image = enqueue_image(img)
@property
def caption(self) -> Optional[Caption]:
return self.image.caption
class ContentImageLightbox(BaseImage):
def __init__(
self,
filename,
profile_name: Optional[str] = None,
profile: Optional[Profile] = None,
):
super().__init__(filename, profile_name=profile_name, profile=profile)
if not os.path.isfile(self.src_filename):
raise FileNotFound(f"No photo for {self.src_filename} l {self.filename}")
img = Image(
src=self.src_filename,
dst=os.path.join(
"photos",
os.path.splitext(filename)[0].lower()
+ self.profile.gallery_file_suffix
+ self.profile.file_suffix,
),
specs=self.profile.gallery_image_spec,
)
self.image = enqueue_image(img)
img = Image(
src=self.src_filename,
dst=os.path.join(
"photos",
os.path.splitext(filename)[0].lower()
+ self.profile.thumb_file_suffix
+ self.profile.file_suffix,
),
specs=self.profile.thumb_image_spec,
is_thumb=True,
)
self.thumb = enqueue_image(img)
@property
def caption(self) -> Optional[Caption]:
return self.image.caption
class Gallery:
"""Process a single gallery.
- look for images
- read meta data
- read exif data
- enqueue the images to be processed
"""
def __init__( # noqa: PLR0912 -- too many branches
self,
content: Union[Article, Page],
location_parsed,
profile_name: Optional[str] = None,
profile: Optional[Profile] = None,
):
self.content = content
if profile is None:
if profile_name is None:
profile_name = "default"
self.profile = get_profile(profile_name)
else:
self.profile = profile
if location_parsed["type"] == "{photo}":
dir_gallery = os.path.join(
os.path.expanduser(pelican_settings["PHOTO_LIBRARY"]),
location_parsed["location"],
)
rel_gallery = location_parsed["location"]
elif location_parsed["type"] == "{filename}":
base_path = os.path.join(pelican_settings["PATH"], content.relative_dir)
dir_gallery = os.path.join(base_path, location_parsed["location"])
rel_gallery = os.path.join(
content.relative_dir, location_parsed["location"]
)
if not os.path.isdir(dir_gallery):
raise GalleryNotFound(
"Gallery does not exist: {} at {}".format(
location_parsed["location"], dir_gallery
)
)
image_filenames = []
logger.info(f"photos: Gallery detected: {rel_gallery}")
for pic in sorted(os.listdir(dir_gallery)):
if pic.startswith("."):
continue
if pic.endswith(".txt"):
continue
if not os.path.isfile(os.path.join(dir_gallery, pic)):
continue
image_filename = os.path.join(location_parsed["location"], pic)
image_filenames.append(f"{location_parsed['type']}{image_filename}")
self.dst_dir = os.path.join("photos", rel_gallery.lower())
self.images: List[GalleryImage] = []
self.title = location_parsed["title"]
for pic in image_filenames:
try:
self.images.append(
GalleryImage(
filename=pic,
gallery=self,
profile=self.profile,
)
)
except ImageExcluded:
logger.debug(f"photos: Image {pic} excluded")
except FileExcluded as e:
logger.debug(f"photos: File {pic} excluded: {e!s}")
def __getitem__(self, item):
if item == 0:
return self.title
if item == 1:
return self.images
raise IndexError
class GalleryImage(BaseImage):
"""Image of a gallery."""
def __init__(
self,
filename,
gallery: Gallery,
profile_name: Optional[str] = None,
profile: Optional[Profile] = None,
):
super().__init__(filename, profile_name=profile_name, profile=profile)
#: The gallery this image belongs to
self._gallery = gallery
if self.filename_type == "filename":
self.src_filename = os.path.join(
g_generator.path, self._gallery.content.relative_dir, self.filename
)
img = Image(
src=self.src_filename,
dst=os.path.join(
"photos",
os.path.splitext(self.filename)[0].lower()
+ self.profile.gallery_file_suffix
+ self.profile.file_suffix,
),
specs=self.profile.gallery_image_spec,
)
if img.is_excluded:
raise ImageExcluded("Image excluded from gallery")
#: The image object
self.image = enqueue_image(img)
img = Image(
src=self.src_filename,
dst=os.path.join(
"photos",
os.path.splitext(self.filename)[0].lower()
+ self.profile.thumb_file_suffix
+ self.profile.file_suffix,
),
specs=self.profile.thumb_image_spec,
is_thumb=True,
)
#: The thumbnail
self.thumb = enqueue_image(img)
def __getitem__(self, item):
"""Legacy support."""
if item == 0:
return self.file
if item == 1:
return self.image
if item == 2:
return self.thumb
if item == 3:
return "" if self.exif is None else self.exif.value
if item == 4:
return "" if self.caption is None else self.caption.value
raise IndexError
@property
def caption(self) -> Optional[Caption]:
return self.image.caption
@property
def exif(self) -> Optional[Exif]:
return self.image.exif
@property
def is_excluded(self) -> bool:
"""Is the image is excluded from the gallery."""
return self.image.is_excluded
class GlobalImage(BaseImage):
def __init__(
self,
filename,
profile_name: Optional[str] = None,
profile: Optional[Profile] = None,
):
super().__init__(filename, profile_name=profile_name, profile=profile)
if not os.path.isfile(self.src_filename):
raise FileNotFound(f"No photo for {self.src_filename} {self.filename}")
img = Image(
src=self.src_filename,
dst=os.path.join(
"photos",
os.path.splitext(self.filename)[0].lower()
+ self.profile.article_file_suffix
+ self.profile.file_suffix,
),
specs=self.profile.article_image_spec,
)
self.image = enqueue_image(img)
class Image:
"""The main Image class.
This class holds all information of the generated image that is required to process
the image.
"""
def __init__( # noqa: PLR0912, PLR0913, PLR0915 -- this function does a _lot_
self,
src,
dst,
spec: Optional[Dict[str, Any]] = None,
specs: Optional[Dict[str, Dict[str, Any]]] = None,
is_thumb=False,
):
if spec is not None and specs is not None:
raise ValueError("Both spec and specs must not be provided")
#: The source image
self.source_image = SourceImage.from_cache(src)
self.dst = dst
self.is_thumb = is_thumb
self._average_color = None
self._height: Optional[int] = None
self._width: Optional[int] = None
self._result_info_loaded = False
self._result_info_allowed_names = ("_average_color", "_height", "_width")
self.images = {}
#: The exif data used for the result image
self.exif_result: Optional[dict] = None
#: The exif data from the source image
self.exif_orig: Optional[dict] = None
#: The icc profile from the source image
self.icc_profile: Optional[bytes] = None
# We create new instances from this class in the main process
# so we can access the global pelican_settings. We attach them
# as class var to push them to the processes when running in
# spawn mode.
#: Global pelican settings
self._pelican_settings = pelican_settings
if spec is None:
if specs is None:
raise ValueError("Only one of spec and specs must be provided")
spec = specs.get(self.source_image.type)
if spec is None:
spec = specs["default"]
#: The specification how to transform the source image
self.spec: Dict[str, Any] = spec.copy()
#: Image type e.g. jpeg, webp
self.type = spec["type"].lower()
image_options: Dict[str, Any] = self._pelican_settings[
"PHOTO_DEFAULT_IMAGE_OPTIONS"
].get(self.type)
if image_options is None:
image_options = {}
if not isinstance(image_options, dict):
logger.warning(
f"photos: Wrong type for default image options for type {spec['type']}"
)
image_options = {}
image_options = image_options.copy()
image_options.update(spec.get("options", {}))
self.spec["options"] = image_options
srcset_specs: Optional[list, tuple] = self.spec.get("srcset")
if not isinstance(srcset_specs, (list, tuple)):
srcset_specs = []
#: The srcset for the image used in HTML
self.srcset = ImageSrcSet()
for srcset_spec in srcset_specs:
img = SrcSetImage(
src=self.source_image.filename,
dst=self.dst,
spec=srcset_spec,
is_thumb=self.is_thumb,
)
self.srcset.append(enqueue_image(img))
additional_images: Dict[str, Any] = spec.get("images")
if additional_images is None:
additional_images = {}
for add_img_name, add_img_spec in additional_images.items():
if not isinstance(add_img_spec, dict):
add_img_spec = {} # noqa: PLW2901
add_img_spec_combined = {}
# We use some values from the parent as default
for name in ("operations", "skip_operations", "type"):
if name in self.spec:
add_img_spec_combined[name] = self.spec[name]
add_img_spec_combined.update(add_img_spec)
img = Image(
src=self.source_image.filename,
dst=f"{self.dst}_{add_img_name}",
spec=add_img_spec_combined,
is_thumb=self.is_thumb,
)
img = enqueue_image(img)
self.images[add_img_name] = img
#: The name of the output file
self.output_filename = "{filename}.{extension}".format(
filename=os.path.join(pelican_output_path, self.dst),
extension=self._pelican_settings["PHOTO_FILE_EXTENSIONS"].get(
self.type, self.type
),
)
#: The name and path for the web page
self.web_filename = "{resized}.{extension}".format(
resized=self.dst,
extension=self._pelican_settings["PHOTO_FILE_EXTENSIONS"].get(
self.type, self.type
),
)
self.pre_operations: List[Union[str, list, tuple]] = []
self.operations: List[Union[str, list, tuple]] = []
self.post_operations: List[Union[str, list, tuple]] = []
self.pre_operations.append("exif.rotate")
self.pre_operations.append("exif.manipulate")
if self.type in ("jpeg",):
self.pre_operations.append("main.remove_alpha")
self.post_operations.append("main.watermark")
if self.type == "gif":
self.post_operations.append("main.convert_mode_p")
if self.type == "jpeg":
self.post_operations.append("main.convert_mode_rgb")
skip_operations = self.spec.get("skip_operations")
if isinstance(skip_operations, (list, tuple)):
for item in self.pre_operations:
if (isinstance(item, str) and item in skip_operations) or (
isinstance(item, (list, tuple)) and item[0] in skip_operations
):
self.pre_operations.remove(item)
for item in self.post_operations:
if (isinstance(item, str) and item in skip_operations) or (
isinstance(item, (list, tuple)) and item[0] in skip_operations
):
self.post_operations.remove(item)
operations = self.spec.get("operations")
if operations is None:
if self.is_thumb and self._pelican_settings["PHOTO_SQUARE_THUMB"]:
self.operations.append("ops.fit")
else:
self.operations.append("main.resize")
elif isinstance(operations, (list, tuple)):
self.operations = operations
else:
logger.warning("Wrong data-type for operations, should be list or tuple")
self.operations = []
operations = []
for operation in self.operations:
if isinstance(operation, str):
operation_name = operation
operation_args = {}
else:
operation_name = operation[0]
operation_args = operation[1]
if operation_name == "main.resize" and not operation_args:
operation_args["resample"] = PILImage.LANCZOS
if operation_name == "ops.fit" and not operation_args:
operation_args["method"] = PILImage.LANCZOS
if (
operation_name in ("main.resize", "ops.fit")
and "size" not in operation_args
):
operation_args["size"] = (spec["width"], spec["height"])
operations.append((operation_name, operation_args))
self.operations = operations
self.operation_mappings = {
"main.convert": self._operation_convert,
"main.convert_mode_p": self._operation_convert_mode_p,
"main.convert_mode_rgb": self._operation_convert_mode_rgb,
"main.remove_alpha": self._operation_remove_alpha,
"main.resize": self._operation_resize,
"main.quantize": self._operation_quantize,
"main.watermark": self._operation_watermark,
"ops.greyscale": ImageOps.grayscale,
"ops.fit": ImageOps.fit,
}
self.advanced_operation_mappings = {
"exif.rotate": self._operation_exif_rotate,
"exif.manipulate": self._operation_manipulate_exif,
}
def __repr__(self):
return (
f"{self.__class__.__name__}(source_image={self.source_image}, "
f"dst={self.dst} is_thumb={self.is_thumb})"