forked from Inzaniak/comfyui-ranbooru
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ranbooru.py
691 lines (585 loc) · 26.7 KB
/
ranbooru.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
import datetime
import requests
import random
from typing import Literal
import os
import torch
import numpy as np
from PIL import Image
import io
import re
POST_AMOUNT = 100
def pil2tensor(image):
return torch.from_numpy(np.array(image).astype(np.float32) / 255.0).unsqueeze(0)
class Booru():
def __init__(self, booru, booru_url):
self.booru = booru
self.booru_url = booru_url
self.headers = {'user-agent': 'my-app/0.0.1'}
def get_data(self,add_tags,max_pages, id=''):
pass
def get_post(self,add_tags,max_pages, id=''):
pass
class Gelbooru(Booru):
def __init__(self, fringe_benefits=True):
super().__init__('gelbooru', f'https://gelbooru.com/index.php?page=dapi&s=post&q=index&json=1&limit={POST_AMOUNT}')
self.fringeBenefits = fringe_benefits
def get_data(self, add_tags, max_pages, id=''):
if id:
add_tags = ''
self.booru_url = f"{self.booru_url}&pid={random.randint(0,max_pages)}{id}{add_tags}"
if self.fringeBenefits:
res = requests.get(self.booru_url, cookies={'fringeBenefits': 'yup'})
else:
res = requests.get(self.booru_url)
data = res.json()
return data
def get_post(self, add_tags, max_pages, id=''):
return self.get_data(add_tags, max_pages, "&id="+id)
class XBooru(Booru):
def __init__(self):
super().__init__('xbooru', f'https://xbooru.com/index.php?page=dapi&s=post&q=index&json=1&limit={POST_AMOUNT}')
def get_data(self, add_tags, max_pages, id=''):
if id:
add_tags = ''
self.booru_url = f"{self.booru_url}&pid={random.randint(0,max_pages)}{id}{add_tags}"
res = requests.get(self.booru_url)
data = res.json()
for post in data:
post['file_url'] = f"https://xbooru.com/images/{post['directory']}/{post['image']}"
return {'post': data}
def get_post(self, add_tags, max_pages, id=''):
return self.get_data(add_tags, max_pages, "&id="+id)
class Rule34(Booru):
def __init__(self):
super().__init__('rule34', f'https://api.rule34.xxx/index.php?page=dapi&s=post&q=index&json=1&limit={POST_AMOUNT}')
def get_data(self, add_tags, max_pages,id=''):
if id:
add_tags = ''
self.booru_url = f"{self.booru_url}&pid={random.randint(0,max_pages)}{id}{add_tags}"
res = requests.get(self.booru_url)
data = res.json()
return {'post': data}
def get_post(self, add_tags, max_pages, id=''):
return self.get_data(add_tags, max_pages, "&id="+id)
class Safebooru(Booru):
def __init__(self):
super().__init__('safebooru', f'https://safebooru.org/index.php?page=dapi&s=post&q=index&json=1&limit={POST_AMOUNT}')
def get_data(self, add_tags, max_pages,id=''):
if id:
add_tags = ''
self.booru_url = f"{self.booru_url}&pid={random.randint(0,max_pages)}{id}{add_tags}"
res = requests.get(self.booru_url)
data = res.json()
for post in data:
post['file_url'] = f"https://safebooru.org/images/{post['directory']}/{post['image']}"
return {'post': data}
def get_post(self, add_tags, max_pages, id=''):
return self.get_data(add_tags, max_pages, "&id="+id)
class Konachan(Booru):
def __init__(self):
super().__init__('konachan', f'https://konachan.com/post.json?limit={POST_AMOUNT}')
def get_data(self, add_tags, max_pages,id=''):
if id:
add_tags = ''
self.booru_url = f"{self.booru_url}&page={random.randint(0,max_pages)}{id}{add_tags}"
res = requests.get(self.booru_url)
data = res.json()
return {'post': data}
def get_post(self, add_tags, max_pages, id=''):
raise Exception("Konachan does not support post IDs")
class Yandere(Booru):
def __init__(self):
super().__init__('yande.re', f'https://yande.re/post.json?limit={POST_AMOUNT}')
def get_data(self, add_tags, max_pages,id=''):
if id:
add_tags = ''
self.booru_url = f"{self.booru_url}&page={random.randint(0,max_pages)}{id}{add_tags}"
res = requests.get(self.booru_url)
data = res.json()
return {'post': data}
def get_post(self, add_tags, max_pages, id=''):
raise Exception("Yande.re does not support post IDs")
class AIBooru(Booru):
def __init__(self):
super().__init__('AIBooru', f'https://aibooru.online/posts.json?limit={POST_AMOUNT}')
def get_data(self, add_tags, max_pages,id=''):
if id:
add_tags = ''
self.booru_url = f"{self.booru_url}&page={random.randint(0,max_pages)}{id}{add_tags}"
res = requests.get(self.booru_url)
data = res.json()
for post in data:
post['tags'] = post['tag_string']
return {'post': data}
def get_post(self, add_tags, max_pages, id=''):
raise Exception("AIBooru does not support post IDs")
class Danbooru(Booru):
def __init__(self):
super().__init__('danbooru', f'https://danbooru.donmai.us/posts.json?limit={POST_AMOUNT}')
def get_data(self, add_tags, max_pages, id=''):
if id:
add_tags = ''
self.booru_url = f"{self.booru_url}&page={random.randint(0,max_pages)}{id}{add_tags}"
res = requests.get(self.booru_url, headers=self.headers)
data = res.json()
for post in data:
post['tags'] = post['tag_string']
return {'post': data}
def get_post(self, add_tags, max_pages, id=''):
self.booru_url = f"https://danbooru.donmai.us/posts/{id}.json"
res = requests.get(self.booru_url, headers=self.headers)
data = res.json()
data['tags'] = data['tag_string']
data = {'post': [data]}
return data
class e621(Booru):
def __init__(self):
super().__init__('danbooru', f'https://e621.net/posts.json?limit={POST_AMOUNT}')
def get_data(self, add_tags, max_pages, id=''):
if id:
add_tags = ''
self.booru_url = f"{self.booru_url}&page={random.randint(0,max_pages)}{id}{add_tags}"
res = requests.get(self.booru_url, headers=self.headers)
data = res.json()['posts']
for post in data:
temp_tags = []
sublevels = ['general','artist','copyright','character','species']
for sublevel in sublevels:
temp_tags.extend(post['tags'][sublevel])
post['tags'] = ' '.join(temp_tags)
post['score'] = post['score']['total']
return {'post': data}
def get_post(self, add_tags, max_pages, id=''):
self.get_data(add_tags, max_pages, "&id="+id)
BOORUS = ['gelbooru', 'rule34', 'safebooru', 'danbooru', 'konachan', 'yande.re', 'aibooru', 'xbooru', 'e621']
BOORUS_URL = ['gelbooru', 'rule34', 'safebooru', 'yande.re', 'aibooru', 'xbooru']
COLORED_BG = ['black_background','aqua_background','white_background','colored_background','gray_background','blue_background','green_background','red_background','brown_background','purple_background','yellow_background','orange_background','pink_background','plain','transparent_background','simple_background','two-tone_background','grey_background']
BW_BG = ['monochrome','greyscale','grayscale']
RATING_TYPES = {
"none": {
"All": "All"
},
"full": {
"All": "All",
"Safe": "safe",
"Sensitive": "questionable",
"Questionable": "questionable",
"Explicit": "explicit"
},
"single": {
"All": "All",
"Safe": "g",
"Sensitive": "s",
"Questionable": "q",
"Explicit": "e"
}
}
RATINGS = {
"e621": RATING_TYPES['full'],
"danbooru": RATING_TYPES['single'],
"aibooru": RATING_TYPES['full'],
"yande.re": RATING_TYPES['full'],
"konachan": RATING_TYPES['full'],
"safebooru": RATING_TYPES['none'],
"rule34": RATING_TYPES['full'],
"xbooru": RATING_TYPES['full'],
"gelbooru": RATING_TYPES['single']
}
class Ranbooru:
def __init__(self):
self.last_prompt = ''
self.file_url = ''
self.image = None
@classmethod
def INPUT_TYPES(cls):
return {"required": {
"booru": (BOORUS, {"default": "gelbooru"}),
"max_pages": ("INT", {"default": 0, "min": 0, "max": 100, "step": 1, "display": "number"}),
"tags": ("STRING", {"multiline": False, "default": ""}),
"rating": (["All","Safe","Sensitive","Questionable","Explicit"], {"default": "All"}),
"change_color": (["Default","Colored","Limited Palette","Monochrome"], {"default": "Default"}),
"use_last_prompt": ("BOOLEAN", {"default": False}),
"return_picture": ("BOOLEAN", {"default": False})
}
}
RETURN_TYPES = ("STRING","IMAGE",)
FUNCTION = "ranbooru"
CATEGORY = "Ranbooru Nodes"
def IS_CHANGED(self, **kwargs):
return float('nan')
def ranbooru(self, booru, max_pages, tags, rating, change_color, use_last_prompt, return_picture):
booru_apis = {
'gelbooru': Gelbooru(),
'rule34': Rule34(),
'safebooru': Safebooru(),
'danbooru': Danbooru(),
'konachan': Konachan(),
'yande.re': Yandere(),
'aibooru': AIBooru(),
'xbooru': XBooru(),
'e621': e621(),
}
bad_tags = ['mixed-language_text','watermark','text','english_text','speech_bubble','signature','artist_name','censored','bar_censor','translation','twitter_username',"twitter_logo",'patreon_username','commentary_request','tagme','commentary','character_name','mosaic_censoring','instagram_username','text_focus','english_commentary','comic','translation_request','fake_text','translated','paid_reward_available','thought_bubble','multiple_views','silent_comic','out-of-frame_censoring','symbol-only_commentary','3koma','2koma','character_watermark','spoken_question_mark','japanese_text','spanish_text','language_text','fanbox_username','commission','original','ai_generated','stable_diffusion','tagme_(artist)','text_bubble','qr_code','chinese_commentary','korean_text','partial_commentary','chinese_text','copyright_request','heart_censor','censored_nipples','page_number','scan','fake_magazine_cover','korean_commentary']
api_url = ''
random_post = {'preview_url':''}
data = {'post': [{'tags': ''}]}
if use_last_prompt and self.last_prompt != '':
final_tags = self.last_prompt
img_url = self.file_url
else:
api_url = booru_apis.get(booru, Gelbooru())
add_tags = ''
if tags != '':
add_tags = f'&tags=-animated+{tags.replace(",", "+")}'
else:
add_tags = '&tags=-animated'
if rating != 'All':
add_tags += f'+rating:{RATINGS[booru][rating]}'
data = api_url.get_data(add_tags, max_pages)
random_post = data['post'][random.randint(0,len(data['post'])-1)]
clean_tags = random_post['tags'].replace('(','\(').replace(')','\)')
temp_tags = clean_tags.split(' ')
temp_tags = random.sample(temp_tags, len(temp_tags))
if change_color == 'Colored':
bad_tags.extend(BW_BG)
elif change_color == 'Limited Palette':
temp_tags.append('(limited_palette:1.3)')
elif change_color == 'Monochrome':
temp_tags.extend(BW_BG)
final_tags = ','.join([tag for tag in temp_tags if tag not in bad_tags])
self.last_prompt = final_tags
self.file_url = random_post['file_url']
print(api_url.booru_url)
print(self.file_url)
if return_picture:
if use_last_prompt:
if self.file_url == img_url and self.image != None:
img = self.image
else:
img_url = random_post['file_url']
res = requests.get(img_url)
#read the image in PIL
img = Image.open(io.BytesIO(res.content))
# rgb
if img.mode != 'RGB':
img = img.convert('RGB')
self.file_url = img_url
self.image = img
return (final_tags, pil2tensor(img),)
else:
empty_image = Image.new('RGB', (1, 1), color = (0, 0, 0))
return (final_tags, pil2tensor(empty_image),)
class RanbooruURL:
"""Uses an url or an ID to get a post from a booru"""
def __init__(self):
self.last_prompt = ''
self.file_url = ''
self.image = None
@classmethod
def INPUT_TYPES(cls):
return {"required": {
"booru": (BOORUS_URL, {"default": "gelbooru"}),
"url": ("STRING", {"multiline": False, "default": ""}),
"return_picture": ("BOOLEAN", {"default": False})
}
}
RETURN_TYPES = ("STRING","IMAGE",)
FUNCTION = "ranbooru_url"
CATEGORY = "Ranbooru Nodes"
def ranbooru_url(self, booru, url, return_picture):
booru_apis = {
'gelbooru': Gelbooru(),
'rule34': Rule34(),
'safebooru': Safebooru(),
'yande.re': Yandere(),
'aibooru': AIBooru(),
'xbooru': XBooru(),
}
bad_tags = ['mixed-language_text','watermark','text','english_text','speech_bubble','signature','artist_name','censored','bar_censor','translation','twitter_username',"twitter_logo",'patreon_username','commentary_request','tagme','commentary','character_name','mosaic_censoring','instagram_username','text_focus','english_commentary','comic','translation_request','fake_text','translated','paid_reward_available','thought_bubble','multiple_views','silent_comic','out-of-frame_censoring','symbol-only_commentary','3koma','2koma','character_watermark','spoken_question_mark','japanese_text','spanish_text','language_text','fanbox_username','commission','original','ai_generated','stable_diffusion','tagme_(artist)','text_bubble','qr_code','chinese_commentary','korean_text','partial_commentary','chinese_text','copyright_request','heart_censor','censored_nipples','page_number','scan','fake_magazine_cover','korean_commentary']
api_url = ''
random_post = {'preview_url':''}
data = {'post': [{'tags': ''}]}
api_url = booru_apis.get(booru, Gelbooru())
#check if the id is a number otherwise it's an url
if url.isdigit():
add_tags = f'&id={url}'
else:
# extract the id from the url
# use regex to find the number after id=
id = re.search('id=(\d+)', url)
if id:
add_tags = f'&id={id.group(1)}'
else:
raise Exception("Invalid URL")
data = api_url.get_data(add_tags, 100)
random_post = data['post'][0]
clean_tags = random_post['tags'].replace('(','\(').replace(')','\)')
temp_tags = clean_tags.split(' ')
temp_tags = random.sample(temp_tags, len(temp_tags))
final_tags = ','.join([tag for tag in temp_tags if tag not in bad_tags])
self.last_prompt = final_tags
self.file_url = random_post['file_url']
if return_picture:
img_url = random_post['file_url']
res = requests.get(img_url)
#read the image in PIL
img = Image.open(io.BytesIO(res.content))
# rgb
if img.mode != 'RGB':
img = img.convert('RGB')
self.file_url = img_url
self.image = img
return (final_tags, pil2tensor(img),)
else:
empty_image = Image.new('RGB', (1, 1), color = (0, 0, 0))
return (final_tags, pil2tensor(empty_image),)
class PromptRemove:
# given a prompt, split it by separator and remove the words in the list based on the input list separated by comma
# if the word in the list contains a * then it will remove all the words that contain that word
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {"required": {
"prompt": ("STRING", {}),
"separator": ("STRING", {"default": ","}),
"remove_tags": ("STRING", {"default": ""}),
}
}
RETURN_TYPES = ("STRING",)
FUNCTION = "prompt_remove"
CATEGORY = "Ranbooru Nodes"
def prompt_remove(self, prompt, separator, remove_tags):
tags = prompt.split(separator)
if ',' in remove_tags:
remove_tags = remove_tags.split(',')
else:
remove_tags = [remove_tags]
for bad_tag in remove_tags:
if '*' in bad_tag:
tags = [tag for tag in tags if bad_tag.replace('*','') not in tag]
else:
tags = [tag for tag in tags if tag != bad_tag]
return (separator.join(tags),)
class RandomPicturePath:
# given a path, return a random picture (png,jpg,jpeg) from that path as a string
def __init__(self):
self.last_path = ''
@classmethod
def INPUT_TYPES(cls):
return {"required": {
"path": ("STRING", {"multiline": False, "default": ""}),
"parse_subfolders": (["True","False"], {"default": "True"}),
"use_last": ("BOOLEAN", {"default": False}),
}
}
RETURN_TYPES = ("STRING",)
FUNCTION = "random_picture_path"
CATEGORY = "Ranbooru Nodes"
def IS_CHANGED(self, **kwargs):
return float('nan')
def random_picture_path(self, path, parse_subfolders, use_last):
if use_last and self.last_path != '':
return (self.last_path,)
else:
files = []
if parse_subfolders == 'True':
for root, dirs, filenames in os.walk(path):
for filename in filenames:
if filename.endswith(('.png', '.jpg', '.jpeg')):
files.append(os.path.join(root, filename))
else:
files = [os.path.join(path, file) for file in os.listdir(path) if file.endswith(('.png', '.jpg', '.jpeg'))]
random_file = random.choice(files)
self.last_path = random_file
return (random_file,)
class PromptMix:
def __init__(self):
self.last_prompt = ''
def IS_CHANGED(self, **kwargs):
return float('nan')
@classmethod
def INPUT_TYPES(cls):
return {"required": {
"prompt": ("STRING", {"multiline": False, "default": ""}),
"delimiter": ("STRING", {"multiline": False, "default": ","}),
"mix_type": (["Off","Mix","Inverse"], {"default": "Off"}),
"use_last": ("BOOLEAN", {"default": False}),
}
}
RETURN_TYPES = ("STRING",)
FUNCTION = "prompt_mix"
CATEGORY = "Ranbooru Nodes"
def prompt_mix(self, prompt, delimiter, mix_type, use_last):
"""Split the string by delimiter and mixes the order of the words"""
if use_last and self.last_prompt != '':
return (self.last_prompt,)
else:
words = prompt.split(delimiter)
if mix_type == 'Mix':
random.shuffle(words)
elif mix_type == 'Inverse':
words.reverse()
self.last_prompt = delimiter.join(words)
return (self.last_prompt,)
class PromptLimit:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {"required": {
"prompt": ("STRING", {}),
"separator": ("STRING", {"default": ","}),
"limit": ("INT", {"default": 0, "min": 0, "max": 100}),
}
}
RETURN_TYPES = ("STRING",)
FUNCTION = "prompt_limit"
CATEGORY = "Ranbooru Nodes"
def prompt_limit(self, prompt, separator, limit):
"""Split the string by separator and limit the amount of words"""
words = prompt.split(separator)
if limit > 0:
words = words[:limit]
return (separator.join(words),)
class PromptRandomWeight:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {"required": {
"prompt": ("STRING", {}),
"separator": ("STRING", {"default": ","}),
"min_weight_value": ("FLOAT", {"default": 0.0, "min": -5.0, "max": 5.0}),
"max_weight_value": ("FLOAT", {"default": 1.0, "min": -5.0, "max": 5.0}),
"max_weight_tags": ("INT", {"default": 1, "min": 1, "max": 100}),
"order": (["Random","Ordered"], {"default": "Random"}),
}
}
RETURN_TYPES = ("STRING",)
FUNCTION = "prompt_random_weight"
CATEGORY = "Ranbooru Nodes"
def prompt_random_weight(self, prompt, separator, min_weight_value, max_weight_value, max_weight_tags, order):
"""Split the string by separator and randomly add (word:weight) to tags contained in the list based on the max_weight_value to a max of max_weight_tags
If the weight is above 1 than the value should be between 1 and max_weight_value, otherwise it should be between max_weight_value and 1
Check if the max_weight_tags is less than the amount of words in the prompt
"""
words = prompt.split(separator)
if max_weight_tags > len(words):
max_weight_tags = len(words)
if order == 'Random':
# apply weights to random words in the list
# these should not be always the first words
random_words = random.sample([word for word in words if "(" not in word], max_weight_tags)
for i in range(max_weight_tags):
words[words.index(random_words[i])] = f"({words[words.index(random_words[i])]}:{round(random.uniform(min_weight_value,max_weight_value),1)})"
else:
for i in range(max_weight_tags):
words[i] = f"({words[i]}:{round(random.uniform(min_weight_value,max_weight_value),1)})"
return (separator.join(words),)
class PromptBackground:
@classmethod
def INPUT_TYPES(cls):
return {"required": {
"prompt": ("STRING", {}),
"background_type": (["colored","b&w","remove"], {"default": "remove"}),
}
}
RETURN_TYPES = ("STRING",)
FUNCTION = "prompt_background"
CATEGORY = "Ranbooru Nodes"
def prompt_background(self, prompt, background_type):
COLORED_BG = ['black_background', 'aqua_background', 'white_background', 'colored_background',
'blue_background', 'green_background', 'red_background',
'brown_background', 'purple_background', 'yellow_background', 'orange_background',
'pink_background', 'two-tone_background', 'grey_background']
BW_BG = ['monochrome', 'greyscale', 'grayscale']
# Merge all background tags
ALL_BG_TAGS = COLORED_BG + BW_BG
# Split prompt in tags
tags = prompt.split(',')
if background_type == 'remove':
# Remove all background tags
tags = [tag.strip() for tag in tags if tag.strip() not in ALL_BG_TAGS]
elif background_type == 'colored':
# Remove all black and white tags
tags = [tag.strip() for tag in tags if tag.strip() not in BW_BG]
# Add a random colored background tag
tags.append(random.choice(COLORED_BG))
elif background_type == 'b&w':
# Remove all colored tags
tags = [tag.strip() for tag in tags if tag.strip() not in COLORED_BG]
# Add all black and white tags
tags.extend(BW_BG)
# Ricomponi i tag nel prompt
final_prompt = ', '.join(tags)
return (final_prompt,)
class LockSeed:
"""Returns a random seed and stores it in self.prev_seed. If user selects 'use_last' it will return the same seed as before."""
def __init__(self):
self.prev_seed = None
@classmethod
def INPUT_TYPES(cls):
return {"required": {
"use_last": ("BOOLEAN", {"default": False}),
}
}
def IS_CHANGED(self, **kwargs):
return float('nan')
RETURN_TYPES = ("INT",)
FUNCTION = "lock_seed"
CATEGORY = "Ranbooru Nodes"
def lock_seed(self, use_last):
if use_last and self.prev_seed != None:
return (self.prev_seed,)
else:
seed = random.randint(0,1000000000)
self.prev_seed = seed
return (seed,)
class TimestampFileName:
"""Given a filename input, returns a filename with a timestamp appended to it."""
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {"required": {
"filename": ("STRING", {"multiline": False, "default": ""}),
}
}
def IS_CHANGED(self, **kwargs):
return float('nan')
RETURN_TYPES = ("STRING",)
FUNCTION = "timestamp_filename"
CATEGORY = "Ranbooru Nodes"
def timestamp_filename(self, filename):
now = datetime.datetime.now()
timestamp = now.strftime("%Y%m%d_%H%M%S")
return (f"{filename}_{timestamp}",)
# A dictionary that contains all nodes you want to export with their names
# NOTE: names should be globally unique
NODE_CLASS_MAPPINGS = {
"Ranbooru": Ranbooru,
"RandomPicturePath": RandomPicturePath,
"PromptMix": PromptMix,
"PromptLimit": PromptLimit,
"PromptRandomWeight": PromptRandomWeight,
"PromptBackground": PromptBackground,
"PromptRemove": PromptRemove,
"RanbooruURL": RanbooruURL,
"LockSeed": LockSeed,
"TimestampFileName": TimestampFileName,
}
# A dictionary that contains the friendly/humanly readable titles for the nodes
NODE_DISPLAY_NAME_MAPPINGS = {
"Ranbooru": "Ranbooru",
"RandomPicturePath": "Random Picture Path",
"PromptMix": "Prompt Mix",
"PromptLimit": "Prompt Limit",
"PromptRandomWeight": "Prompt Random Weight",
"PromptBackground": "Prompt Background",
"PromptRemove": "Prompt Remove",
"RanbooruURL": "Ranbooru URL",
"LockSeed": "Lock Seed",
"TimestampFileName": "Timestamp Filename",
}