-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp_200_images.py
1256 lines (1024 loc) · 59.4 KB
/
app_200_images.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
"""
# https://stackoverflow.com/questions/3964681/find-all-files-in-a-directory-with-extension-txt-in-python
"""
import glob, os
from posixpath import splitext
#from re import X
from urllib.parse import urljoin
import PIL
from PIL import Image, ImageOps
import halftone as ht # https://pypi.org/project/halftone/
import config
import helpers_web as wh
import helpers_web as hw
import time
import pathlib
import pyautogui as pag
from bs4 import BeautifulSoup as bs
import lxml.html
from lxml import etree
import helpers_lxml as hx
import conversions as conv
import chromedriver_binary # pip install chromedriver-binary-auto
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.expected_conditions import visibility_of_element_located
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium import webdriver # pip install selenium
from selenium.webdriver.chrome.options import Options
import shutil
# https://github.com/homm/pillow-lut-tools
# https://pillow-lut-tools.readthedocs.io/en/latest/
# pip install pillow_lut
# pillow_lut.load_cube_file(lines, target_mode=None, cls=<class 'PIL.ImageFilter.Color3DLUT'>)
import pillow_lut
import pillow_avif
import image_sizes
#-----------------------------------------
#
#-----------------------------------------
if __name__ == "__main__":
#-----------------------------------------
# alert
#-----------------------------------------
pag.alert("make sure to also change backgrond image extensions in style.css...", timeout=10000)
pag.alert("also change navText hardcoded in scripts...", timeout=10000)
#-----------------------------------------
# logo
#-----------------------------------------
wh.logo_filename(__file__)
wh.log("__file__:", __file__, filepath=config.path_log_params)
#-----------------------------------------
# dir_size_orig
#-----------------------------------------
dir_size_orig = wh.get_directory_total_size(config.project_folder)
print()
image_sizes.file_image_sizes_make_unique()
#pag.alert(text=f"good time to backup htdocs!", timeout=2000)
#-----------------------------------------
# get sizes
#-----------------------------------------
b_get_project_total_size_use_pdf = False
perc100_saved, total_size_originals, total_size_unpowered = wh.get_project_total_size(
config.project_folder,
prefix=config.base_netloc,
use_pdf=b_get_project_total_size_use_pdf
)
#exit(0)
#-----------------------------------------
#
#-----------------------------------------
params = {
"project_folder": wh.to_posix(os.path.abspath(config.project_folder)),
"path_conversions": config.path_conversions,
"b_append_custom_css": True,
"b_copy_custom_script": True,
"b_remove_fonts_css": True,
"b_perform_pdf_compression": True ,
"b_perform_pdf_compression_force": False, # <<<<<<<<<<<<<<<<<<<<
"b_perform_image_conversion": True,
"images": {
"b_force_write": False, # <<<<<<<<<<<<<<<<<<<<
"show_nth_image": 37, # 0 is off, 1 all
"quality": 60, # 66 55 85 95 75
"size_thresh": 1000,
"size_large": (1400, 1400), # (1400, 1400) # (1600, 1600)
"size_small": (480, 480), # (553, 553) # (480, 480)
"resample": Image.Resampling.LANCZOS,
"resample_comment": "Image.Resampling.LANCZOS", # verbose only
"halftone": None, # (4, 30) or None # ht.euclid_dot(spacing=halftone[0], angle=halftone[1])
#"cube_lut_path": "D:/__BUP_V_KOMPLETT/X/111_BUP/22luts/LUT cube/LUTs Cinematic Color Grading Pack by IWLTBAP/__xIWL_zM_Creative/Creative/xIWL_C-6750-STD.cube", # may be empty string
#"cube_lut_path": "D:/__BUP_V_KOMPLETT/X/111_BUP/22luts/LUT cube/LUTs Cinematic Color Grading Pack by IWLTBAP/__xIWL_zM_Creative/Creative/xIWL_C-6730-STD.cube",
#"cube_lut_path": "D:/__BUP_V_KOMPLETT/X/111_BUP/22luts/LUT cube/LUTs Cinematic Color Grading Pack by IWLTBAP/__xIWL_zM_Creative/Creative/xIWL_B-7040-STD.cube",
#"cube_lut_path": "D:/__BUP_V_KOMPLETT/X/111_BUP/22luts/LUT cube/LUTs Cinematic Color Grading Pack by IWLTBAP/__xIWL_zM_Creative/Creative/xIWL_C-9730-STD.cube",
"cube_lut_path": None, # may be empty string or None
"b_colorize": True,
"blend_alpha": 0.5, # 0.666 0.8 0.75 0.5
"b_enhance_transp": True,
###"b_1bit": False, # very bad
"b_greyscale": False,
"b_use_palette": False,
},
"b_replace_conversions": True,
"b_minify1": True,
"b_fix_xml_elements": True,
"b_hide_media_subdomain": True,
"b_minify2": True,
"b_export_site": True,
"b_export_site_force": True,
}
import json
wh.log(json.dumps(params, indent=4), filepath=config.path_log_params, echo=False)
wh.log(wh.format_dict(params), filepath=config.path_log_params)
# del with warning
conversions = []
b_delete_conversion_originals = False
if b_delete_conversion_originals:
if "Cancel" == pag.confirm(text=f"b_delete_conversion_originals: {b_delete_conversion_originals}"):
exit(0)
#-----------------------------------------
# remove path_conversions
#-----------------------------------------
wh.logo("remove path_conversions")
if os.path.isfile(params.get("path_conversions")):
os.remove(params.get("path_conversions"))
#-----------------------------------------
# copy icons
#-----------------------------------------
wh.logo("copy icons")
hw.make_dirs(config.path_dst_icons)
shutil.copytree(config.path_src_icons, config.path_dst_icons, dirs_exist_ok=True)
#-----------------------------------------
# b_append_custom_css
#-----------------------------------------
# append css before fonts will be replaced after
if params.get("b_append_custom_css"):
wh.logo("b_append_custom_css")
data_stylesheet = wh.string_from_file(config.path_stylesheet)
print("count:", data_stylesheet.count(config.custom_css_marker))
data_stylesheet = data_stylesheet.split(config.custom_css_marker)[0]
data_stylesheet += wh.string_from_file(config.path_custom_css)
wh.string_to_file(data_stylesheet, config.path_stylesheet)
print("appended custom css to", config.path_stylesheet)
print("count:", data_stylesheet.count(config.custom_css_marker))
#-----------------------------------------
# b_copy_custom_script
#-----------------------------------------
if params.get("b_copy_custom_script"):
wh.logo("b_copy_custom_script")
if config.path_new_script:
shutil.copy(config.path_new_script, config.path_script)
print("copied", config.path_new_script, "to", config.path_script)
#-----------------------------------------
# fonts
#-----------------------------------------
if params.get("b_remove_fonts_css"):
wh.logo("b_remove_fonts_css")
# https://pythonhosted.org/cssutils/
# https://pythonhosted.org/cssutils/
# https://github.com/jaraco/cssutils
# https://cthedot.de/cssutils/
# https://stackoverflow.com/questions/59648732/replace-uri-value-in-a-font-face-css-rule-with-cssutils
# https://groups.google.com/g/cssutils?pli=1
# https://www.fullstackpython.com/cascading-style-sheets.html
import cssutils
import logging
import cssbeautifier
def save_css_changed(orig_path, text, conversions):
name, ext = os.path.splitext(orig_path)
new_path = name + config.suffix_compressed + ext
wh.string_to_file(
text,
new_path
)
conversions.append((orig_path, new_path))
print("\t\t", "added to conversions:", wh.CYAN, os.path.basename(new_path), wh.RESET)
cssutils.log.setLevel(logging.CRITICAL)
#-----------------------------------------
# download fonts from stylesheets
#-----------------------------------------
# TODO save fonts locally
print("downloading fonts...")
files = wh.collect_files_endswith(
params.get("project_folder"),
[".css"],
excludes=config.excludes_compressed_postfix
)
#######files = wh.links_remove_excludes(files, config.bup_excludes)
#print(wh.CYAN, *files, wh.RESET, sep="\n\t")
font_urls = []
for file in files:
print("", wh.CYAN, file, wh.RESET)
try:
sheet = cssutils.parseFile(file)
for rule in sheet:
if rule.type in [cssutils.css.CSSFontFaceRule.FONT_FACE_RULE]:
print("\t", rule)
for property in rule.style:
if property.name == 'src': # 'font-family':
print("\t\t", hw.CYAN, property.name, property.value, hw.RESET)
if "url" in property.value:
url = property.value.replace("(", "").replace(")", "")
url = url.strip().lstrip("url")
print("\t\t\t", hw.CYAN, url, hw.RESET)
subs = url.split(',')
for sub in subs:
font_url = sub.strip().lstrip("url")
font_url = font_url.split(" ")[0]
font_url = hw.strip_query_and_fragment(font_url)
font_url = font_url.replace("../", "/wp-content/themes/karlsruhe-digital/")
font_url = urljoin(config.base, font_url)
print("\t\t\t\t", hw.MAGENTA, font_url, hw.RESET)
local_path = config.project_folder + wh.get_path_local_root_subdomains(font_url, config.base).lstrip('/')
if not os.path.isfile(local_path):
wh.make_dirs(local_path)
response = hw.get_response(font_url)
with open(local_path, "wb") as fp:
fp.write(response.read())
font_urls.append((font_url, local_path))
except Exception as e:
print(f"{wh.RED} css: {e} {wh.RESET}")
time.sleep(2)
### for file
#print(*font_urls, sep="\n\t")
#-----------------------------------------
# remove fonts from stylesheets
#-----------------------------------------
for file in files:
b_file_has_changed = False
print("", wh.CYAN, file, wh.RESET)
try:
sheet = cssutils.parseFile(file)
#print("before", wh.GRAY, cssbeautifier.beautify(sheet.cssText.decode("utf-8")), wh.RESET)
sheet = wh.css_sheet_delete_rules(
sheet,
[
cssutils.css.CSSFontFaceRule.FONT_FACE_RULE,
###cssutils.css.CSSFontFaceRule.COMMENT
])
# reset fonts
for rule in sheet:
assert rule.type != cssutils.css.CSSFontFaceRule.FONT_FACE_RULE # removed above
if rule.type in [cssutils.css.CSSFontFaceRule.STYLE_RULE]:
for property in rule.style:
#print("\t\t\t", property.name)
if property.name == 'font-family':
property.value = config.font_sans
b_file_has_changed = True
# # https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/src
# assert property.name != 'src'
# if property.name == 'src':
# property.value = "XXX"
# b_file_has_changed = True
#print("after", wh.GREEN, cssbeautifier.beautify(sheet.cssText.decode("utf-8")), wh.RESET)
###save_css_changed(file, cssbeautifier.beautify(sheet.cssText.decode("utf-8")), conversions)
if b_file_has_changed:
wh.string_to_file(
cssbeautifier.beautify(sheet.cssText.decode("utf-8")),
file
)
except Exception as e:
print(f"{wh.RED} css: {e} {wh.RESET}")
time.sleep(2)
### for file
conv.save(params.get("path_conversions"), conversions)
#-----------------------------------------
# replace fonts in tag styles
#-----------------------------------------
files = wh.collect_files_endswith(
params.get("project_folder"),
["index.htm","index.html"],
excludes=config.excludes_compressed_postfix
)
####files = wh.links_remove_excludes(files, config.bup_excludes)
#print(wh.MAGENTA, *files, wh.RESET, sep="\n\t")
for file in files:
b_file_has_changed = False
#print(file)
content = wh.string_from_file(file)
tree = lxml.html.fromstring(content)
for node in tree.xpath("//*[@style]"):
#print("\t", node)
style_text = node.attrib['style']
#print("\t\t", style_text)
style = cssutils.parseStyle(style_text) # <<<
#print ("\t\t", "style.cssText:", wh.MAGENTA, style.cssText, wh.RESET)
for property in style:
if property.name == 'font-family':
print(file)
property.value = config.font_sans
b_file_has_changed = True
print ("\t\t", wh.YELLOW, style.cssText, wh.RESET)
# # # if property.name == 'background-image':
# # # print ("\t\t", wh.MAGENTA, style.cssText, wh.RESET)
# # # pass
# assign style back to lxml
node.attrib['style'] = property.cssText
#print("\t\t", wh.GREEN, node.attrib['style'], wh.RESET)
### for node
content = etree.tostring(tree, pretty_print=True).decode("utf-8")
#print(wh.GREEN, content, wh.RESET)
###save_css_changed(file, content, conversions)
if b_file_has_changed:
wh.string_to_file(
content,
file
)
### for file
conv.save(params.get("path_conversions"), conversions)
#-----------------------------------------
# TODO missing style : //style <<<<<<<<<<<<<<<<<<<<<<<<<<<<< internal stylesheets
#-----------------------------------------
#-----------------------------------------
#
#-----------------------------------------
if params.get("b_perform_pdf_compression"):
b_force_write = params.get("b_perform_pdf_compression_force")
if b_force_write and "Cancel" == pag.confirm(text=f"PDF: b_force_write: {b_force_write}", timeout=5000):
exit(0)
wh.logo("b_perform_pdf_compression")
import ghostscript as gs
pdfs = wh.collect_files_endswith(params.get("project_folder"), [".pdf"], excludes=config.excludes_compressed_postfix)
pdfs = [pdf for pdf in pdfs if not config.pdf_compression_suffix in pdf] # remove already compressed
print("pdfs", *pdfs, sep="\n\t")
for i, pdf in enumerate(pdfs):
print("-"*88)
orig_path = pdf
name, ext = os.path.splitext(orig_path)
new_path = name + config.pdf_compression_suffix + ext
conversions.append((orig_path, new_path))
print("\t\t", "added to conversions:", os.path.basename(new_path))
if not wh.file_exists_and_valid(new_path) or b_force_write:
gs.compress_pdf(orig_path, new_path, compression=config.pdf_compression, res=config.pdf_res)
if wh.file_exists_and_valid(new_path):
size_orig = os.path.getsize(orig_path)
size_new = os.path.getsize(new_path)
wh.log("\t", "saved:",
wh.vt_saved_percent_string(size_orig, size_new),
os.path.basename(new_path),
filepath=config.path_log_params
)
if size_new >= size_orig:
shutil.copyfile(orig_path, new_path) # restore original
print("\t\t", "copying original:", os.path.basename(orig_path))
# delete conv later
# if b_delete_conversion_originals:
# print("\t\t", "removing orig_path:", wh.RED + orig_path, wh.RESET)
# os.remove(orig_path)
else:
print("already exists:", os.path.basename(new_path))
### for />
conv.save(params.get("path_conversions"), conversions)
### b_perform_pdf_compression />
#-----------------------------------------
#
#-----------------------------------------
if params.get("b_perform_image_conversion"):
wh.logo("b_perform_image_conversion")
# # https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html#webp
# quality = 66 # 66 55
# max_dim = (1000, 1000) # (1280, 720) # (1200, 600)
# show_nth_image = 30 # 0 is off, 1 all
# resample = Image.Resampling.LANCZOS
# halftone = None # (4, 30) # or None
# b_colorize = True
# b_force_write = params.get("b_perform_image_conversion_force")
# b_greyscale = False
# b_use_palette = False
# blend_alpha = 0.8 # 0.666 0.8
pimages = params.get("images")
quality = pimages.get("quality") # 66 # 66 55
##max_dim = pimages.get("max_dim") # (1000, 1000) # (1280, 720) # (1200, 600)
show_nth_image = pimages.get("show_nth_image") # 30 # 0 is off, 1 all
resample = pimages.get("resample") # Image.Resampling.LANCZOS
halftone = pimages.get("halftone") # None # (4, 30) # or None
b_colorize = pimages.get("b_colorize") # True
b_force_write = pimages.get("b_force_write") # params.get("b_perform_image_conversion_force")
###b_1bit = pimages.get("b_1bit")
b_greyscale = pimages.get("b_greyscale") # False
b_use_palette = pimages.get("b_use_palette") # False
blend_alpha = pimages.get("blend_alpha") # 0.8 # 0.666 0.8
cube_lut_path = pimages.get("cube_lut_path")
if cube_lut_path:
shutil.copy(cube_lut_path, config.path_stats)
if b_force_write and "Cancel" == pag.confirm(text=f"IMAGES: b_force_write: {b_force_write}", timeout=2000):
exit(0)
print(wh.format_dict(params["images"]))
time.sleep(3)
#-----------------------------------------
#
#-----------------------------------------
images = wh.collect_files_endswith(params.get("project_folder"), config.image_exts, excludes=config.excludes_compressed_postfix)
images = [img for img in images if not config.suffix_compressed in img]
print("images", hw.GRAY, *images, hw.RESET, sep = "\n\t")
#wh.log("images", *[f"\n\t{x}" for x in images], filepath=config.path_log_params, echo=False)
if cube_lut_path:
print("loading lut:", wh.CYAN, cube_lut_path, wh.RESET)
lut = pillow_lut.load_cube_file(cube_lut_path)
else:
lut = None
new_ext = config.target_image_ext
# convert images
perc_avg = 0.0
for cnt, path in enumerate(images):
print("-"*88)
path = os.path.normpath(path) # wh.to_posix(path)
name, _ = os.path.splitext(path) # ('my_file', '.txt')
out_path = name + config.suffix_compressed + new_ext
out_path = os.path.normpath(out_path) # wh.to_posix(out_path)
conversions.append((path, out_path))
if b_force_write or not wh.file_exists_and_valid(out_path):
print("\t", "{}/{}:".format(cnt+1, len(images)), os.path.basename(path))
print("\t\t", wh.progress_string(cnt / len(images), verbose_string="", VT=wh.CYAN, n=33))
print("\t\t", "new_ext:", new_ext)
size_orig = os.path.getsize(path)
image = Image.open(path)
is_transp = wh.image_has_transparency(image)
#image = image.convert('RGBA' if is_transp else 'RGB')
wh_orig = image.size
old_mode = image.mode
# colorize png?
enhance_transp = True if (pimages.get("b_enhance_transp") and is_transp) else False
print("\t\t", "enhance_transp:", wh.YELLOW, enhance_transp, wh.RESET)
#wh.log("enhance_transp:", enhance_transp, filepath=config.path_log_params, echo=False)
# put this in app_110 TODO
def func_size_low_high(path, csv_path, size_thresh, size_large, size_small):
# could read this to ram beforehand TODO
relpath = wh.to_posix('/' + os.path.relpath(path, config.project_folder))
relpath = wh.get_path_local_root_subdomains(relpath, config.base)
relname, ext = os.path.splitext(relpath)
# look through all paths in csv and get size in page
found = False
w,h = 0,0
with open(csv_path, mode="r", encoding="utf-8") as fp:
for line in fp:
if line.startswith('/'):
c_base, c_path, c_w, c_h, c_nw, c_nh, c_url, c_url_parent = line.split(',')
if relname == c_base:
found = True
w = max(int(c_w), w)
h = max(int(c_h), h)
print("\t\t", wh.GREEN, "found:", c_base, w, h, c_nw, c_nh, wh.RESET)
#break # can find multiple entries per image --> accumulate bigger w then
break # now reverse by width sorted list so highest wh comes first
if not found:
print("\t\t", wh.RED, "NOT found:", relname, w, h, wh.RESET)
if (w >= size_thresh or h >= size_thresh) or (not found):
return size_large
else:
return size_small
### func_size />
# put this in app_110 TODO
def func_max_size_in_page(path, csv_path, size_thresh, size_large, size_small):
# could read this to ram beforehand TODO
relpath = wh.to_posix('/' + os.path.relpath(path, config.project_folder))
relpath = wh.get_path_local_root_subdomains(relpath, config.base)
relname, ext = os.path.splitext(relpath)
# look through all paths in csv and get size in page
found = False
w,h = 0,0
with open(csv_path, mode="r", encoding="utf-8") as fp:
lines = fp.readlines()[1:] # skip header
for line in lines:
c_base, c_path, c_w, c_h, c_nw, c_nh, c_url, c_url_parent = line.split(',')
if relname == c_base:
found = True
w = max(int(c_w), w)
h = max(int(c_h), h)
print("\t\t", wh.GREEN, "found:", c_base, w, h, c_nw, c_nh, wh.RESET)
break # now reverse by width sorted list so highest wh comes first # can find multiple entries per image --> accumulate bigger w then
if not found:
print("\t\t", wh.RED, "NOT found:", relname, w, h, wh.RESET)
if found and (w > 0 and h > 0):
return (w, h) # real size in page
else:
return size_large # optimistically donate image sizes
### func_size />
new_dim = func_max_size_in_page(
path,
csv_path=config.path_image_sizes,
size_thresh=pimages.get("size_thresh"),
size_large=pimages.get("size_large"),
size_small=pimages.get("size_small")
)
image.thumbnail(new_dim, resample=resample)
image_orig = image.copy()
#image_orig = ImageOps.autocontrast(image_orig.convert("RGB"))
if enhance_transp:
mask = wh.get_mask_rgba(image) # after resizing
###mask.save(path + "__mask__.png", 'png', optimize=True, lossless=True) # debug
else:
mask = None
#if (b_colorize and not is_transp) or enhance_transp:
if b_colorize and (not is_transp or enhance_transp):
image = image.convert("L") # L only !!! # LA L 1
black = "#003300"
black = "#002200"
#black = "#001733"
white = "#eeeeee"
white = "#ffffff"
image = ImageOps.colorize(image, black=black, white=white)
####image = ImageOps.autocontrast(image)
# blend: 0 returns orig, 1 new
if (blend_alpha > 0.0) and (not is_transp or enhance_transp): # ???? 0 or 1 TODO
###assert image.mode == image_orig.mode
image = Image.blend(
image_orig.convert("RGB"),
image.convert("RGB"),
blend_alpha
)
if enhance_transp:
image = image.convert("RGBA")
image = wh.apply_mask_rgba(image, mask)
if lut and (not is_transp or enhance_transp):
print("\t\t", "lut :", wh.CYAN, os.path.basename(cube_lut_path), wh.RESET)
if is_transp:
image = image.convert("RGBA")
else:
image = image.convert("RGB")
image = image.filter(lut)
if halftone and not is_transp:
image = image.convert("L")
image = ht.halftone(image, ht.euclid_dot(spacing=halftone[0], angle=halftone[1]))
assert isinstance(image, PIL.Image.Image)
# image modes
# if b_1bit and not is_transp:
# image = image.convert("1", dither=Image.Dither.FLOYDSTEINBERG)
if b_greyscale:
if is_transp:
image = image.convert("LA")
else:
image = image.convert("L")
# looking terrible
if b_use_palette and not is_transp:
dither = None # Image.NONE # NONE FLOYDSTEINBERG None
palette = Image.ADAPTIVE # WEB ADAPTIVE
colors = 256 # Number of colors to use for the ADAPTIVE palette. Defaults to 256.
if is_transp:
#image = image.convert("PA", dither=dither, palette=palette, colors=colors ) # NONE FLOYDSTEINBERG
pass
else:
image = image.convert("P", dither=dither, palette=palette, colors=colors)
format = new_ext.lstrip('.')
if is_transp:
#image.save(out_path, format=format, optimize=True, lossless=True) # !!! lossless TODO????
image.save(out_path, format=format, optimize=True, quality=quality)
print(wh.YELLOW, "NOTE: image.save is_transp compressed...TEST", wh.RESET)
time.sleep(0.666)
else:
image.save(out_path, format=format, optimize=True, quality=quality)
print("\t\t", "format :", format)
print("\t\t", "quality :", quality)
print("\t\t", "wh :", wh_orig, "-->", image.size, "| new_dim:", new_dim)
print("\t\t", "is_transp :", wh.vt_b(is_transp))
print("\t\t", "mode :", old_mode, "-->", image.mode)
print("\t\t", "blend_alpha:", blend_alpha)
size_new = os.path.getsize(out_path)
print("\t\t", "saved :", wh.vt_saved_percent_string(size_orig, size_new), os.path.basename(out_path))
perc_avg += wh._saved_percent(size_orig, size_new)
if show_nth_image > 0 and not (cnt%show_nth_image):
wh.image_show_file(out_path, secs=0.5)
else:
print("\t\t", "already exists:", os.path.basename(out_path))
### for images />
if images:
perc_avg /= len(images)
perc_avg = round(perc_avg, 1)
vt = wh.GREEN if perc_avg >= 0 else wh.RED
print("perc_avg:",vt + str(perc_avg) + "%" + wh.RESET)
time.sleep(3)
#print(*conversions, sep="\n\t")
if conversions:
conv.save(params.get("path_conversions"), conversions)
### b_perform_image_conversion />
#-----------------------------------------
# better use a list in case above finds no more erased images....
# TODO need to create /wp paths from these images...rel to project folder and using /
# https://www.geeksforgeeks.org/python-os-path-relpath-method/
#-----------------------------------------
#-----------------------------------------
#
#-----------------------------------------
def replace_all_conversions_in_file(filename, conversions, pre="\t\t"):
#print(pre, "replace_all_conversions_in_file:", wh.CYAN, filename, wh.RESET)
html = wh.string_from_file(filename)
# replace
#print("\t\t", end='')
for i, conversion in enumerate(conversions):
fr, to = conversion
if wh.file_exists_and_valid(to):
# rel paths from root /
wp_fr = wh.to_posix('/' + os.path.relpath(fr, params.get("project_folder")))
wp_to = wh.to_posix('/' + os.path.relpath(to, params.get("project_folder")))
cnt = html.count(wp_fr)
if cnt > 0:
# print(
# pre, "cnt:", cnt,
# wh.CYAN, "wp_fr", wh.GRAY, wp_fr,
# wh.CYAN, "wp_to", wh.GRAY, wp_to,
# wh.RESET
# )
# if not (i%1):
# #print(pre, str(cnt) + ' ', end='')
# pass
# compressor for html may strip quotes....
no_f = lambda s: s # dangerous! as quotes may be removed by html-minify
# try all TODO with quotes
for f in [ wh.dq, wh.sq, wh.pa, wh.qu]: ## , no_f]: # dangerous! as quotes may be removed by html-minify
#print(f"{ wh.GRAY}\t\t\t replace_all: {f(wp_fr)} {wh.RESET}")
html = wh.replace_all(html, f(wp_fr), f(wp_to) )
else:
print(pre, "\t", wh.RED, "does not exist: to:", to, wh.RESET, end='\r')
### for conversion />
wh.string_to_file(html, filename)
# # # fp.close()
# # # #open the input file in write mode
# # # fp = open(filename, "w", encoding="utf-8")
# # # fp.write(html)
# # # fp.close()
#-----------------------------------------
#
#-----------------------------------------
if params.get("b_replace_conversions"):
wh.logo("b_replace_conversions")
conversions = conv.load(params.get("path_conversions"))
#print(*conversions, sep="\n\t")
html_files = wh.collect_files_endswith( params.get("project_folder") , ["index.html", ".css", ".js"], excludes=config.excludes_compressed_postfix)
for i, html_file in enumerate(html_files):
verbose_string = f"\t {i+1}/{len(html_files)} {os.path.basename(html_file)}"
wh.progress(i / len(html_files), verbose_string=verbose_string, VT=wh.CYAN, n=80, prefix="")
replace_all_conversions_in_file(html_file, conversions)
# DANGEROUS!!!
if False:
# TODO why are these still here?
# replace left over image extensions
for q_end in ["\"", "\'", ")"]:
for ext in config.image_exts_no_target:
wh.file_replace_all(html_file, ext + q_end, config.target_image_ext + q_end)
### for />
### b_perform_replacement />
#-----------------------------------------
#
#-----------------------------------------
if b_delete_conversion_originals:
if "Cancel" == pag.confirm(text=f"b_delete_conversion_originals: {b_delete_conversion_originals}"):
exit(0)
wh.logo("b_delete_conversion_originals")
conversions = conv.load(params.get("path_conversions"))
for conversion in conversions:
fr_to_delete, __to = conversion
if wh.file_exists_and_valid(fr_to_delete):
print("\t", wh.RED, "removing:", os.path.basename(fr_to_delete), wh.RESET)
os.remove(fr_to_delete)
#-----------------------------------------
# collect files and make sitemap
#-----------------------------------------
b_sitemap_xml = True
if b_sitemap_xml:
wh.logo("sitemap")
urls = []
for file in wh.collect_files_endswith(config.project_folder, ["index.html"], excludes=config.excludes_compressed_postfix):
urls.append(
wh.to_posix(config.target_base + os.path.relpath(file, config.project_folder))
)
#print(*urls, sep="\n\t")
import sitemap
sitemap.sitemap_xml_from_list(urls, out_xml_path=config.path_htdocs_sitemap)
# gzip
wh.gzip_file(config.path_htdocs_sitemap, config.path_htdocs_sitemap_gz)
os.remove(config.path_htdocs_sitemap)
# robots.txt https://en.wikipedia.org/wiki/Robots_exclusion_standard
robots_text = f"User-agent: *\nDisallow: \nSitemap: {config.target_base}{config.filename_sitemap_gz}\n"
wh.string_to_file(robots_text, config.path_htdocs_robots)
print("written:", config.path_htdocs_sitemap_gz)
print("written:", config.path_htdocs_robots)
#-----------------------------------------
#
#-----------------------------------------
# rm xmlrpc.ph
wh.logo("rm xmlrpc.ph")
xmlrpc_path = config.project_folder+"xmlrpc.php"
if os.path.isfile(xmlrpc_path):
os.remove(xmlrpc_path)
#-----------------------------------------
# b_minify1
#-----------------------------------------
def minify(title="minify"):
wh.logo(title)
for file in wh.collect_files_endswith(config.project_folder, ["index.html"], excludes=config.excludes_compressed_postfix):
wh.html_minify_on_disk(file)
for file in wh.collect_files_endswith(config.project_folder, [".css"], excludes=config.excludes_compressed_postfix):
wh.css_minify_on_disk(file)
for file in wh.collect_files_endswith(config.project_folder, [".js"], excludes=config.excludes_compressed_postfix):
wh.js_minify_on_disk(file)
if params.get("b_minify1"):
minify("b_minify1")
#-----------------------------------------
# get_project_total_size
#-----------------------------------------
wh.logo("get_project_total_size")
perc100_saved, total_size_originals, total_size_unpowered = wh.get_project_total_size(
config.project_folder,
prefix=config.base_netloc,
use_pdf=b_get_project_total_size_use_pdf
)
#-----------------------------------------
# b_fix_xml
#-----------------------------------------
if params.get("b_fix_xml_elements"):
wh.logo("b_fix_xml_elements")
# func=lambda s : True # finds all
# func=lambda file : any(file.lower().endswith(ext) for ext in config.image_exts)
func=lambda file : file.lower().endswith("index.html")
files_index_html = wh.collect_files_func(params.get("project_folder"), func=func, excludes=config.excludes_compressed_postfix)
#print(*files_index_html, sep="\n\t")
# no dominant-baseline="middle" in <text>
svg_percircle = f"""
<div class="percircle"><svg viewBox="0 0 500 500" role="img" xmlns="http://www.w3.org/2000/svg">
<g id="myid">
<circle stroke="{config.svg_color}"
stroke-width="30px"
fill="none"
cx="250"
cy="250"
r="230" />
<text style="font: bold 11.1rem sans-serif;"
text-anchor="middle"
x="50%"
y="60%"
fill="{config.svg_color}">
<tspan font-size="1.0em" >{round(perc100_saved):.0f}</tspan><tspan font-size="0.9em">%</tspan>
</text>
</g>
</svg>
<span>saved</span>
</div> """
# % ﹪ % # 15.1rem 1.0em 0.5em # 11.1rem 1 1 #
for file in files_index_html:
print("-"*80)
print("file", wh.CYAN + file + wh.RESET)
wp_path = wh.to_posix('/' + os.path.relpath(file, params.get("project_folder")))
base_path = config.base + wh.to_posix(os.path.relpath(file, params.get("project_folder"))).replace("index.html", "")
same_page_link = f""" <a href="{base_path}" class="same_page_link">{config.base_netloc}</a> """
"""
Zero Fossil Site
Zero Carbon Site
Zero Energy Site
Minimal Carbon Site
Dies ist die energie-effiziente
energie optimierte
Dies ist die Low Carbon Website
Dies ist die Low Carbon Website
This is the environmentally aware version of
Dies ist die umweltbewusste Seite
This is the environmentally friendly twin of
.<br/>The energy consumption of this website was reduced by {saved_string}.
.<br/>Der Energieverbrauch dieser Website wurde um {saved_string} reduziert.
This is the Low Carbon proxy of {same_page_link}
"""
# https://babel.pocoo.org/en/latest/dates.html
from babel.dates import format_date, format_datetime, format_time
dt = config.dt_now
format='full' # long
saved_string = f"<span style=''>{perc100_saved:.1f}%</span>"
if "/en/" in wp_path:
dt_string = format_date(dt, format=format, locale='en')
banner_header_text = f"{config.svg_leaf_img}This is the Minimal Carbon Site {same_page_link}" # <br/>{svg_percircle} <sup>{config.html_by_infossil_link}</sup>
###banner_footer_text = f"unpowered by <a href='https://infossil.org'>infossil<br/>{svg_percircle}</a>" # <br/>{dt_string}
banner_footer_text = f"unpowered by <a href='https://minimalcarbon.site'>minimalcarbon.site<br/>{svg_percircle}</a>" # <br/>{dt_string}
else:
dt_string = format_date(dt, format=format, locale='de_DE')
banner_header_text = f"{config.svg_leaf_img}Dies ist die Minimal Carbon Site {same_page_link}"
###banner_footer_text = f"unpowered by <a href='https://infossil.org'>infossil<br/>{svg_percircle}</a>" # <br/>{dt_string}
banner_footer_text = f"unpowered by <a href='https://minimalcarbon.site'>minimalcarbon.site<br/>{svg_percircle}</a>" # <br/>{dt_string}
#---------------------------
# lxml
#---------------------------
tree = lxml.html.parse(file) # lxml.html.fromstring(content)
# start the hocus pocus in focus
# use section-1 from original site as frag
if False and False:
hx.replace_xpath_with_fragment_from_file(
tree,
"//section[@id='section-1']",
"data/karlsruhe.digital_fragment_section1.html" # frag_file_path
)
# # section 1 unneeded
# hx.remove_by_xpath(tree, "//section[@id='section-1']//div[contains(@class, 'owl-dots' )]")
# hx.remove_by_xpath(tree, "//section[@id='section-1']//div[contains(@class, 'owl-nav' )]")
# set first item zo 07
# //div[@id='testimonial-swiper']//span[contains(@class, 'swiper-item-number' )]
hx.set_text_by_xpath(
tree,
"//div[@id='testimonial-swiper']//span[contains(@class, 'swiper-item-number' )]",
"07"
)
# ###OK!!!!!!!!!!!
# hx.set_text_by_xpath(
# tree,
# "//li[@id='menu-item-2675']/a",
# "was struktur now replaced yyyy<<<<<"
# )
# # last slide from hero-swiper
# # //section[@id='section-1']//div[contains(@class, 'owl-item' )][last()]
# hx.remove_by_xpath(tree, "//section[@id='section-1']//div[contains(@class, 'owl-item' )][last()]")
#---------------------------
# banners
#---------------------------
if True: # +++
# TODO must be /en/ and not depending on wp_path /en/
banner_header = hx.banner_header(banner_header_text)
hx.remove_by_xpath(tree, "//div[@class='banner_header']")
print("\t adding banner_header")
try:
tree.find(".//header").insert(0, banner_header)
except Exception as e:
print("\t", wh.RED, e, wh.RESET)
exit(1)
"""
media