-
Notifications
You must be signed in to change notification settings - Fork 0
/
tdldl.py
19382 lines (13950 loc) · 579 KB
/
tdldl.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
# -*- coding: utf-8 -*-
from multiprocessing.managers import DictProxy
import base64
import colorsys
import configparser
import datetime
import hashlib
import io
import json
import logging
import math
import multiprocessing
from numba import jit, njit
import os
import queue
import random
import shelve
import string
import sys
import time
import traceback
import uuid
from collections import OrderedDict
from operator import itemgetter
from PIL import Image, ImageDraw, ImageFont, ImageFilter, ImageSequence, ImageOps, ImageChops, ExifTags
from PIL.ImageColor import getrgb
import PIL.GifImagePlugin as pilGif
import numpy as np, numpy.random
from flask import Flask, jsonify, request, send_file, send_from_directory, render_template
from werkzeug.routing import BaseConverter
from io import BytesIO
from tdlColorPrint import ColorPrint
from tdlState import TdlState
from tdlState import TdlValues
#from werkzeug.middleware.profiler import ProfilerMiddleware
app = Flask(__name__)
#app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[50], profile_dir='/home/nn/flaskdev/_profiled/')
class RegexConverter(BaseConverter):
def __init__(self, url_map, *items):
super(RegexConverter, self).__init__(url_map)
self.regex = items[0]
app.url_map.converters['regex'] = RegexConverter
# path params ------------------------------------------ @~-------
shelfFileName = "tdlshelf.log"
fontPath = "/mnt/c/windows/fonts/"
fontNameMono = "Cour.ttf"
fontNameSansSerif = "Verdana.ttf"
fontNameImpact = "Impact.ttf"
publicDomainImagePath = "/mnt/u/code/python/commons/download/"
allPaths = [
"/mnt/u/code/python/commons/download/",
"/mnt/u/code/python/commons/download1/",
"./sourceimages/special/",
r"/mnt/u/My Webs/tooinside/universemdwiki/_private/",
"./sourceimages/style/",
"./sourceimages/orangeblocks/",
"/mnt/t/Pictures/tweeter/",
"/mnt/t/Pictures/sa archive/",
"/mnt/t/Pictures/sa/",
"/mnt/t/Pictures/sa2/",
"/mnt/t/Pictures/sa3/",
"/mnt/t/Pictures/",
"/mnt/u/code/python/commons/tiffsOnly/",
"/mnt/t/Pictures/From Lumia920White/Camera roll/",
"/mnt/t/Pictures/From_iPhone6/",
"./imagesExported/",
"/mnt/t/Pictures/stupidshit/"
]
ollamaHost = 'http://192.168.1.29:11434/v1'
wordListsPath = "/mnt/u/code/pytwit/wordlists/"
mobyfilepath = wordListsPath + 'mobyposi/mobylf.i'
palettesPath = "./sourceimages/palettes"
stampPath = "./sourceimages/stamps"
pathFunctionDoc = "./tdldl.json"
pathTelemetry = "./tdldl_stats.json"
pathOperations = "./logOperations/"
pathSourceImages = "./sourceimages/"
pathLabelSquares = "./sourceimages/gsp_1inch_squares.png"
pathBootstrapCSS = """<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">"""
pathBootstrapJS = """<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.min.js" integrity="sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13" crossorigin="anonymous"></script>"""
pathWebFonts = """<link href="https://fonts.googleapis.com/css?family=Bungee" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Amiko" rel="stylesheet">"""
defaultInsertExtensions = ('.jpg','.gif','.png','.tif')
def getCurrentStandardWidth():
return 1024
def getCurrentStandardHeight():
return 1024
timeOutDefault = 30
fontPathSansSerif = fontPath + fontNameSansSerif
# ---------- logging params ---------------------------
rootLogger = logging.getLogger()
rootLogger.setLevel(logging.DEBUG)
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
rootLogger.addHandler(handler)
pilLogger = logging.getLogger("PIL")
pilLogger.setLevel(logging.WARNING)
print (f'PIL Logger level set to: {pilLogger.level}')
numba_logger = logging.getLogger('numba')
numba_logger.setLevel(logging.WARNING)
colorPrint = ColorPrint(rootLogger)
def colorEsc(x):
return f'\x1b[38;5;{x}m'
colorPrint.print_custom_palette(147, f"-----{colorEsc(148)}----> {colorEsc(196)}h{colorEsc(197)}e{colorEsc(198)}r{colorEsc(199)}e {colorEsc(200)}b{colorEsc(201)}e {colorEsc(202)}d{colorEsc(203)}r{colorEsc(204)}a{colorEsc(205)}g{colorEsc(206)}o{colorEsc(207)}n{colorEsc(208)}s {colorEsc(148)}-------{colorEsc(149)}----{colorEsc(150)}-----{colorEsc(147)}-------->")
#----------- font blacklist. will not be chosen -------
fontBlacklist = ["LilyPond",
"marlett",
"segmdl2",
"Swkeys1",
"SWMacro",
"symbol",
"teamviewer",
"webdings",
"wingding",
"CoolS-Regular",
"Hollywood Capital Hills",
"Hollywood Capital",
"Embossed Germanica",
"Fluted Germanica",
"Shadowed Germanica",
"Plain Germanica",
"holomdl2",
"REFSPCL",
"VISITOR",
"BNJDigital",
"WINGDNG2",
"WINGDNG3",
"romantic",
"mtextra",
"OUTLOOK",
"HARLOWSI",
"PARCHM",
"Gottlieb"
]
#----------- color and palette definitions. best not to change. --------
cocoColors = ["00FF00", "0000FF", "FFFFFF", "FF00FF", "FFFF00", "FF0000", "00FFFF", "FF8000", "000000"]
atariColors = ["000000","404040","6C6C6C","909090","B0B0B0","C8C8C8","DCDCDC","ECECEC","444400","646410","848424","A0A034","B8B840","D0D050","E8E85C","FCFC68","702800","844414","985C28","AC783C","BC8C4C","CCA05C","DCB468","ECC878","841800","983418","AC5030","C06848","D0805C","E09470","ECA880","FCBC94","880000","9C2020","B03C3C","C05858","D07070","E08888","ECA0A0","FCB4B4","78005C","8C2074","A03C88","B0589C","C070B0","D084C0","DC9CD0","ECB0E0","480078","602090","783CA4","8C58B8","A070CC","B484DC","C49CEC","D4B0FC","140084","302098","4C3CAC","6858C0","7C70D0","9488E0","A8A0EC","BCB4FC","000088","1C209C","3840B0","505CC0","6874D0","7C8CE0","90A4EC","A4B8FC","00187C","1C3890","3854A8","5070BC","6888CC","7C9CDC","90B4EC","A4C8FC","002C5C","1C4C78","386890","5084AC","689CC0","7CB4D4","90CCE8","A4E0FC","003C2C","1C5C48","387C64","509C80","68B494","7CD0AC","90E4C0","A4FCD4","003C00","205C20","407C40","5C9C5C","74B474","8CD08C","A4E4A4","B8FCB8","143800","345C1C","507C38","6C9850","84B468","9CCC7C","B4E490","C8FCA4","2C3000","4C501C","687034","848C4C","9CA864","B4C078","CCD488","E0EC9C","442800","644818","846830","A08444","B89C58","D0B46C","E8CC7C","FCE08C"]
iLoveThatGirl = 0
primaryColors = [(255,0,0), (0,255,0), (0,0,255)]
wackyColors = [(255,255,0),
(0,255,0),
(255,0,255)]
randoFillList = [18, 19, 20, 21, 24, 26, 33, 34, 36, 37, 38, 39, 42, 43, 44, 45, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 68, 69, 70, 73, 74, 77, 79, 82, 84, 85, 86]
maxFloodFillArg = 88
# ---- okay, you can change fourColorPalettes. IF you promise to be careful.
fourColorPalettes = (('000000','ffffff','ff0000','00ff00','0000ff'),
('082B2D','069498','73AC7F','C9FA9E','ffffff'),
('ECD078','D95B43','C02942','542437','53777A'),
('D9CEB2','948C75','D5DED9','7A6A53','99B2B7'),
('951DF8','030105','CD1E1E','E48B19','E92581'),
('4D454F','ffffff','FA1330','B3B5A7','2A1330'),
('000000','D95B43','C02942','542437','2A1330'),
('6feae6','f6a3ef','000000','eecd69','dd6dfb','50d8ec'),
('951DF8','740b3c','620f0f','eb8500','cc7400','f9bed9'))
# --- safe funcs ---------------------------------------------
imageoplist = ["fourit", "twoit", "invert", "hueshift", "edge", "contour", "detail", "adaptiverandom_mediancut", "adaptiverandom_octree", "adaptiverandom_quant", "adaptive", "adaptive_mediancut", "adaptive_quant",
"pixelate", "fourcolorTDL", "godcolor", "fourblend", "redit", "greenit", "blueit", "colorit", "colorize", "colorizeerize", "coloritup", "garlic",
"findfaces", "grayscale", "minfilter", "maxfilter", "medianfilter",
"remixed", "remix_blend", "doublediff", "linepainter_inv", "fullfill_diff",
"copydiff", "colorhatch_diff", "colorhatch_bw_diff", "fullgradient_diff", "canny_inv", "canny_color", "weirderator",
"cornerharris", "kmeans", "xanny"]
def getSafeFuncs():
safeFuncs = [altWorld,
ctrlWorld,
gritty,
vaguetransfer,
fullFill,
hardLandscape,
fourdotsRemixed,
radioFill,
colorHatch,
subtlyWrong,
nightgrid,
nightgridStars,
gradientSquares,
hsvTesting,
paletteSquares,
atariripples,
diagonal4Way]
return safeFuncs
def getOneSafeFunc():
key = random.choice(getSafeFuncs())
colorPrint.print_custom_palette(191, f"[--------> getOneSafeFunc ---- {key} --------->")
return key
# globals ---------------------------------------------- @~-------
config = False
functionDocs = False
telemetry = False
extParams = []
input_palette = []
possibleFonts = []
current_imgtype = None
currentUID = "0"
timeStart = time.time()
manager = multiprocessing.Manager()
wrapperData = manager.dict()
wrapperData["xannies"] = manager.dict()
wrapperData["inserts_used"] = manager.dict()
wrapperData["function_states"] = manager.dict()
words = []
wordsPositive = []
wordsNegative = []
wordsVerb = []
wordsNoun = []
wordsAdjective = []
wordsJargon = []
wordsMoby = dict()
# code begins here -- multiproc // timeout ------------- @~-------
# TODOs ---~ we define the magick to become the magick ~----------
# * put tdldl on a vps
# * have fun
# * remap_palette
# * EXIGENT MIDNIGHT
# Cryptomeld: Unlocks encrypted memories, revealing forgotten secrets.
# Voidweave: Tears a rift in reality, allowing passage to hidden realms.
# Nexthex: Bends time, altering the course of events with a whisper.
# Soulforge: Fuses consciousness with machine, blurring the boundaries.
# Neuroshade: Cloaks thoughts, shielding them from prying algorithms.
# Chromebane: Corrodes cybernetic implants, rendering them useless.
# Synthblood: Infuses veins with synthetic life, granting unnatural vitality.
# Wraithwire: Threads through firewalls, stealing forbidden data.
# Cortexhex: Rewrites neural pathways, rewriting destiny itself.
# Viraluxe: Spreads digital contagion, infecting networks with chaos.
# Quantumwhisper: Speaks to quantum particles, altering probabilities.
# Holothren: Summons holographic constructs, illusions with teeth.
# Nanoshroud: Wraps the body in nanobots, granting ethereal form.
# Echodark: Echoes the screams of erased memories, haunting the present.
# Aetherpulse: Disrupts reality grids, unraveling the fabric of existence.
# logging ---------------------------------------------- @~-------
def writeWrapperToLog(data: DictProxy):
output = '---wrapperData ---\n'
output += 'keys:\n'
for d in data.keys():
output += str(d) + "\n"
# ColorPrint.logger_info("wrapperData: " + str(wrapperData))
output += 'items:\n'
for did in data.items():
output += '\t' + str(did) + '\n'
output += '\t' + str(did[0]) + '\n'
output += '\t' + str(did[1]) + '\n'
output += '---wrapperData end---\n'
return output
def timeoutWrapper(queue, bob, wordChoice, palette, extParamsPassed, uid, key):
global input_palette
input_palette = processPalette(palette)
global extParams
extParams = extParamsPassed
global wrapperData
global rootLogger
global colorPrint
# ColorPrint.logger_info("wrapperData as timeoutWrapper starts: " + writeWrapperToLog(wrapperData))
wrapperData["xannies"][uid] = manager.list()
wrapperData["inserts_used"][uid] = manager.list()
wrapperData["function_states"][uid] = manager.list()
loadConfiguration()
colorPrint.print_custom_palette(191, f"[--------> timeoutWrapper ---- {key} --------->")
colorPrint.print_custom_palette(191, f"| uid: {str(uid)} --->")
startTimeCheck()
colorPrint.print_custom_palette(198, f"[ bob starts -------{writeTimeCheck()}----->")
if not isinstance(bob, dict) and bob.__name__ == "textGrid":
result = bob(wordChoice)
elif not isinstance(bob, dict):
result = bob()
else:
result = bob["f"]()
colorPrint.print_custom_palette(198, f"---------> bob done -------{writeTimeCheck()}-----]")
# ColorPrint.logger_info("wrapperData: " + writeWrapperToLog(wrapperData))
# ColorPrint.logger_info("telemetry: " + writeWrapperToLog(telemetry))
outputPath = "tempImages/" + uid + ".gif"
if isinstance(result, pilGif.GifImageFile):
result.save(outputPath, format="GIF", save_all=True)
wrapperData[uid] = outputPath
else:
wrapperData[uid] = result
saveConfiguration()
queue.put(uid)
queue.close()
colorPrint.print_custom_palette(191, f"---------> timeoutWrapper done ----------------]")
def writeTimeCheck():
x = round(getTimeCheck()[1], 5)
return colorPrint.get_custom_rgb(x)
def callWithTimeout(doThisThing, TIMEOUT, wordChoice="ALONE", palette="", key=""):
global extParams
global currentUID
uid = uuid.uuid4()
currentUID = str(uid)
queueueueueue = multiprocessing.Queue(1) # Maximum size is 1
proc = multiprocessing.Process(target=timeoutWrapper, args=(queueueueueue, doThisThing, wordChoice, palette, extParams, currentUID, key))
proc.start()
# Wait for TIMEOUT seconds
try:
result = queueueueueue.get(True, TIMEOUT)
except queue.Empty as exEmp:
colorPrint.print_custom_palette(171, f"---------> callWithTimeout ---- empty --------->")
colorPrint.print_custom_palette(171, f"{exEmp}")
colorPrint.print_custom_palette(171, f"{proc} / {dir(proc)}")
result = None
except Exception as e:
colorPrint.print_custom_palette(171, f"---------> callWithTimeout ---- exception --------->")
colorPrint.print_custom_palette(171, f"{e}")
rootLogger.error(proc)
raise
finally:
colorPrint.print_custom_palette(171, f"callWithTimeout: killing bob. don't tell")
proc.kill()
# Process data here, not in try block above, otherwise your process keeps running
return result
def startTimeCheck():
global timeStart
timeStart = time.time()
return
def getTimeCheck():
global timeStart
t1 = time.time()
return (t1, t1-timeStart)
def doTimeCheck(otherInfo="", i=0):
global timeStart
t1 = time.time()
global colorPrint
if i == 0:
colorPrint.print_warn("elapsed: " + str(t1-timeStart) + " " + otherInfo)
else:
colorPrint.logger_whatever("elapsed: " + str(t1-timeStart) + " " + otherInfo)
return
def logException(e):
tback = traceback.format_exc()
fstack = traceback.format_stack()
rootLogger.error(str(datetime.datetime.now()))
rootLogger.error(tback)
rootLogger.error(str(fstack))
rootLogger.error("---------------------")
# utility/supporting functions ------------------------- @~-------
def getParam(i):
global extParams
result = ""
if extParams != []:
if i >= 0 and len(extParams) >= (i+1) and extParams[i] != "":
result = extParams[i]
elif i < 0 and extParams[i] != "":
result = extParams[i]
return result
def getIntParams(defaultP1=250, defaultP2=100):
p1 = getParam(0)
p2 = getParam(1)
p1 = int(p1) if p1.isdecimal() else defaultP1
p2 = int(p2) if p2.isdecimal() else defaultP2
return (p1, p2)
def getTextPosFromImgAndTextSize(img_size, text_size):
# | | |
# | | | |
# x = midpoint minus (half the text/2)
midpoint = int(img_size // 2)
half_text = int(text_size // 2)
z = midpoint - half_text if midpoint - half_text >= 0 else 0
return z
def getRandomFloodFill():
global maxFloodFillArg
iAlg = random.randint(1, maxFloodFillArg)
return iAlg
def safetyCheck(*args):
lst = ()
if len(args) == 3:
lst = (args[0], args[1], args[2])
elif len(args) == 4:
lst = (args[0], args[1], args[2], args[3])
elif len(args) == 1:
lst = args[0]
else:
raise TypeError('Either parameter 1 should be a color tuple, or 3 or 4 parameters (r,g,b,a optional) are expected.')
for iSC in range(len(lst)):
if lst[iSC] < 0:
lst = replace_at_index(lst, iSC, 0)
elif lst[iSC] > 255:
lst = replace_at_index(lst, iSC, lst[iSC] % 255)
return lst
def safetyCheck_LeaveAtMax(*args):
lst = ()
if len(args) == 3:
lst = (args[0], args[1], args[2])
elif len(args) == 4:
lst = (args[0], args[1], args[2], args[3])
elif len(args) == 1:
lst = args[0]
else:
raise TypeError('Either parameter 1 should be a color tuple, or 3 or 4 parameters (r,g,b,a optional) are expected.')
for iSC in range(len(lst)):
if lst[iSC] < 0:
lst = replace_at_index(lst, iSC, 0)
elif lst[iSC] > 255:
lst = replace_at_index(lst, iSC, 255)
return lst
def hex_to_rgb(value):
value = value.lstrip('#')
lv = len(value)
x = tuple(int(value[i:i + lv // 3], 16) for i in range(0, lv, lv // 3))
if len(x) > 4:
rootLogger.debug(f'value: {value} output: {x}')
return x
def rgb_to_hex(rgb):
return '#%02x%02x%02x' % rgb
def calculate_luminace(color_code):
index = float(color_code) / 255
if index < 0.03928:
return index / 12.92
else:
return ( ( index + 0.055 ) / 1.055 ) ** 2.4
def calculate_relative_luminance(rgb):
return 0.2126 * calculate_luminace(rgb[0]) + 0.7152 * calculate_luminace(rgb[1]) + 0.0722 * calculate_luminace(rgb[2])
def calcContrastRatio(color1, color2):
light = color1 if sum(color1) > sum(color2) else color2
dark = color1 if sum(color1) < sum(color2) else color2
contrast_ratio = ( calculate_relative_luminance(light) + 0.05 ) / ( calculate_relative_luminance(dark) + 0.05 )
return contrast_ratio
def lum(r,g,b,a=0):
return math.sqrt( .241 * r + .691 * g + .068 * b )
def myhsv_to_rgb(hsv):
p = colorsys.hsv_to_rgb(hsv[0], hsv[1], hsv[2])
p = (int(p[0] * 255.0), int(p[1] * 255.0), int(p[2] * 255.0))
return p
def sort_by_lum(choices):
choices.sort(key=lambda rgb: lum(*rgb))
return choices
def getInverse(c):
inverse = (255-c[0],255-c[1],255-c[2])
return inverse
def getRandomColorRGB():
rgba = getRandomColor()
return (rgba[0], rgba[1], rgba[2])
def getRandomColor(alpha=-1):
if alpha == -1:
alpha = random.randint(0, 255)
random.seed()
r = random.randint(0, 255)
random.seed()
g = random.randint(0, 255)
random.seed()
b = random.randint(0, 255)
return (r, g, b, alpha)
# Sum of the min & max of (a, b, c)
def hilo(a, b, c):
if c < b: b, c = c, b
if b < a: a, b = b, a
if c < b: b, c = c, b
return a + c
def getColorComplement(c):
(r, g, b) = c
k = hilo(r, g, b)
return tuple(k - u for u in (r, g, b))
def resizeToMinMax(img, maxW, maxH, minW, minH):
doTimeCheck("resizeToMinMax starts")
img = resizeToMin(img, maxW, maxH, minW, minH)
z = resizeToMax(img, maxW, maxH)
doTimeCheck("resizeToMinMax complete")
return z
def resizeToMin(img, maxW, maxH, minW, minH):
doTimeCheck("resizeToMin starts")
if img.size[0] > maxW or img.size[1] > maxH or img.size[0] < minW or img.size[1] < minH:
(w, h) = getSizeByMinMax(img.size[0], img.size[1], maxW, maxH, minW, minH)
img = img.resize((int(w), int(h)), Image.LANCZOS)
doTimeCheck("resizeToMin complete")
return img
def resizeToMax(img, maxW, maxH):
doTimeCheck("resizeToMax starts")
if img.size[0] > maxW or img.size[1] > maxH:
(w, h) = getSizeByMax(img.size[0], img.size[1], maxW, maxH)
img = img.resize((int(w), int(h)), Image.LANCZOS)
doTimeCheck("resizeToMax complete")
return img
def getSizeByMinMax(w, h, maxW, maxH, minW, minH):
resizedW = w
resizedH = h
r = (h * 1.0) / w
while resizedW > maxW or resizedH > maxH:
resizedW -= 1.0
resizedH = r * resizedW
while resizedW < minW or resizedH < minH:
resizedW += 1.0
resizedH = r * resizedW
return (resizedW, resizedH)
def getSizeByMax(w, h, maxW, maxH):
# resize the image down to <= the original size
resizedW = w
resizedH = h
r = (h * 1.0) / w
while resizedW > maxW or resizedH > maxH:
resizedW -= 1.0
resizedH = r * resizedW
return (resizedW, resizedH)
def resizeToMatch(img1, img2):
outputW = 0
outputH = 0
if(img1.size[0] >= img2.size[0]):
outputW = int(img1.size[0])
outputH = int(img1.size[1])
else:
outputW = int(img2.size[0])
outputH = int(img2.size[1])
img1 = img1.resize((outputW, outputH))
img2 = img2.resize((outputW, outputH))
return (img1, img2)
def getTempFile(tempDir="./"):
import tempfile
return tempfile.NamedTemporaryFile(dir=tempDir)
def writeImageException(e):
global fontPathSansSerif
exc_type, exc_obj, exc_tb = sys.exc_info()
rootLogger.error(sys.exc_info())
logException(e)
colorPrint.print_custom_palette(141, f"{e}")
colorPrint.print_custom_palette(141, f"{dir(e)}")
img = Image.new("RGBA", (1024, 768), "#FFFFFF")
draw = ImageDraw.Draw(img)
fon = ImageFont.truetype(fontPathSansSerif, 18)
debugFillColor = (0, 0, 0, 255)
textY = 0
outputMsg = str(e)
draw.text((5, textY), outputMsg, font=fon, fill=debugFillColor)
outputMsg = "at line: " + str(exc_tb.tb_lineno)
draw.text((5, textY+24), outputMsg, font=fon, fill=debugFillColor)
return img
def pullChoices(pl):
global input_palette
if input_palette != "" and input_palette != []:
choices = input_palette
else:
choices = getPaletteGenerated(paletteLength=pl)
return choices
def getGoodRanges(pixels, rangeCount):
pixCounts = {}
totalCount = 0
for pixel in pixels:
if pixel not in pixCounts:
pixCounts[pixel] = 1
else:
pixCounts[pixel] += 1
totalCount += 1
splitCount = totalCount // rangeCount
range = []
thisRange = 0
lastI = 0
for i in sorted(pixCounts.keys()):
if pixCounts[i] + thisRange > splitCount:
rootLogger.debug("i: " + str(i) + " count: " + str(thisRange))
range.append(lastI)
thisRange = pixCounts[i] + 0
if len(range) == rangeCount - 1:
range.append(255)
break
else:
thisRange += pixCounts[i]
lastI = i
if(len(range) < rangeCount):
range.append(lastI)
#rootLogger.debug("pixCounts: " + str(sorted(pixCounts.keys())))
rootLogger.debug("pixCounts: " + str(pixCounts))
rootLogger.debug("totalCount: " + str(totalCount))
rootLogger.debug("range: " + str(range))
rootLogger.debug("splitCount: " + str(splitCount))
return range
# ---- end utility functions -------------------- @~-------
# image operations ------------------------------ @~-------
def check_image_operation(img, imageop, palette):
for iopx in imageop.split(','):
iop = iopx.lower()
if iop == "fourit":
img = imageop_four_it(img)
if iop == "twoit":
img = imageop_two_it(img)
if iop == "invert":
img = imageop_invert(img)
if iop == "hueshift":
img = imageop_hueshift(img)
if iop == "edge":
img = imageop_edge(img)
if iop == "contour":
img = imageop_contour(img)
if iop == "detail":
img = imageop_detail(img)
if iop == "adaptiverandom_mediancut":
img = imageop_adaptive(img, quantOption=0)
if iop == "adaptiverandom_octree":
img = imageop_adaptive(img)
if iop == "adaptiverandom_quant":
img = imageop_adaptive(img, quantOption=3)
if iop == "adaptive_mediancut":
img = imageop_adaptive_palette(img, palette, quantOption=0)
if iop == "adaptive":
img = imageop_adaptive_palette(img, palette, quantOption=2)
if iop == "adaptive_quant":
img = imageop_adaptive_palette(img, palette, quantOption=3)
if iop == "pixelate":
img = imageop_pixelate(img)
if iop == "redit":
img = imageop_redit(img)
if iop == "greenit":
img = imageop_greenit(img)
if iop == "blueit":
img = imageop_blueit(img)
if iop == "colorit":
whichop = random.randint(0, 2)
img = imageop_colorit(img, whichop)
if iop == "fourcolortdl":
img = imageop_fourcolor(img, palette)
if iop == "godcolor":
img = imageop_godcolor(img, palette)
if iop == "fourblend":
img = imageop_fourcolorBlend(img, palette)
if iop == "colorize":
img = imageop_colorize(img, palette)
if iop == "colorizerize":
img = imageop_colorizerize(img, palette)
if iop == "coloritup":
img = imageop_colorItUp(img, palette)
if iop == "garlic":
img = imageop_garlic(img, palette)
if iop == "findfaces":
img = imageop_findfaces(img)
if iop == "grayscale":
img = imageop_grayscale(img)
if iop == "minfilter":
img = imageop_minfilter(img)
if iop == "maxfilter":
img = imageop_maxfilter(img)
if iop == "medianfilter":
img = imageop_medianfilter(img)
if iop == "remixed":
img = imageop_remixed(img)
if iop == "remix_blend":
img = imageop_remixed_blended(img)
if iop == "doublediff":
img = imageop_doublediff(img)
if iop == "linepainter_inv":
img = imageop_linepainter_inv(img)
if iop == "fullfill_diff":
img = imageop_fullFill_diff(img)
if iop == "copydiff":
img = imageop_copydiff(img)
if iop == "colorhatch_diff":
img = imageop_colorHatch_diff(img)
if iop == "colorhatch_bw_diff":
img = imageop_colorHatch_bw_diff(img)
if iop == "fullgradient_diff":
img = imageop_fullGradient_diff(img)
if iop == "canny_inv":
img = imageop_canny_inv(img)
if iop == "canny_color":
img = imageop_canny_color(img)
if iop == "weirderator":
img = imageop_weirderator(img)
if iop == "cornerharris":
img = imageop_cornerHarris(img)
if iop == "kmeans":
img = imageop_kmeans(img)
if iop == "xanny":
img = imageop_xanny(img)
return img
def imageop_pixelate(img):
sqX = random.randint(2, 10)
sqY = random.randint(2, 10)
draw = ImageDraw.Draw(img)
pixdata = img.load()
for y in range(img.size[1]-1, -1, -sqY):
for x in range(img.size[0]-1, -1, -sqX):
c = pixdata[x, y]
draw.rectangle(((x, y),(x+sqX, y+sqY)), fill=c)
return img
def imageop_adaptive(img, palette="", quantOption=2):
# MEDIANCUT = 0
# MAXCOVERAGE = 1
# FASTOCTREE = 2
# LIBIMAGEQUANT = 3
img = img.convert("RGB")
if palette == "":
paletteLength = random.randint(3, 15)
#palette = getPalette()
palette = getPaletteGenerated(paletteLength=paletteLength)
pal = generatePalette(palette)
pal = pal.convert("P", palette=Image.ADAPTIVE)
img.load()
img = img.quantize(method=quantOption, palette=pal) # TODO: dither
return img
def imageop_adaptive_palette(img, palette=1, quantOption=2):
choices = getPaletteSpecific(palette)
return imageop_adaptive(img, choices, quantOption)
def imageop_grayscale(img):
img = img.convert("RGB")
img = img.convert("L")
img.load()
return img
def imageop_detail(img):
img = img.convert("RGB")
img = img.filter(ImageFilter.DETAIL)
return img
def imageop_contour(img):
img = img.convert("RGB")
img = img.filter(ImageFilter.CONTOUR)
return img
def imageop_edge(img):
img = img.convert("RGB")
img = img.filter(ImageFilter.EDGE_ENHANCE)
return img
def imageop_hueshift(img):
img = img.convert("RGB")
pixdata = img.load()
version = random.randint(0, 4)
for x in range(0, img.size[0]):
for y in range(0, img.size[1]):
c = pixdata[x, y]
if version == 0:
pixdata[x, y] = (c[2], c[1], c[0])
elif version == 1:
pixdata[x, y] = (c[2], c[0], c[1])
elif version == 2:
pixdata[x, y] = (c[1], c[0], c[2])
elif version == 3:
pixdata[x, y] = (c[1], c[2], c[0])
elif version == 4:
pixdata[x, y] = (c[0], c[2], c[1])
return img
def imageop_redit(img):
return imageop_colorit(img, 0)
def imageop_greenit(img):
return imageop_colorit(img, 1)
def imageop_blueit(img):
return imageop_colorit(img, 2)
def imageop_colorit(img, ci):
pixdata = img.load()
for x in range(0, img.size[0]):
for y in range(0, img.size[1]):