File size: 32,255 Bytes
78506fe
 
 
 
 
c53d44b
e005050
0b30521
 
 
341a7e2
78506fe
2e0cd75
1597d72
 
 
 
0b744ad
2e0cd75
29f1459
1597d72
 
 
 
 
0b30521
2e0cd75
341a7e2
0b30521
2e0cd75
0b30521
 
 
 
2e0cd75
341a7e2
2e0cd75
341a7e2
 
 
 
2e0cd75
0b30521
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
341a7e2
2e0cd75
78506fe
 
1597d72
 
 
 
 
 
78506fe
2e0cd75
78506fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e0cd75
78506fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2dd5330
 
0b30521
2dd5330
 
 
78506fe
 
 
 
 
 
2e0cd75
78506fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e33e382
 
 
c2401c0
e33e382
78506fe
e005050
78506fe
1597d72
78506fe
 
 
 
e005050
78506fe
 
 
 
 
 
 
 
 
 
 
9c8df4f
78506fe
1597d72
 
 
2e0cd75
9c8df4f
c53d44b
b65ff3c
78506fe
 
 
 
 
 
 
 
 
 
 
95bdd33
78506fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e0cd75
82dcf73
e005050
82dcf73
e005050
 
82dcf73
e005050
 
 
82dcf73
e005050
 
 
82dcf73
 
e005050
78506fe
2e0cd75
82dcf73
e005050
2e0cd75
952cbe5
 
 
 
 
 
 
2e0cd75
82dcf73
 
95bdd33
b976407
78506fe
 
 
 
2e0cd75
341a7e2
 
 
 
82dcf73
 
 
 
 
 
 
 
 
 
 
 
2e0cd75
 
82dcf73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1597d72
 
 
 
 
 
 
 
341a7e2
 
78506fe
 
e005050
82dcf73
16aa93d
2e0cd75
82dcf73
 
 
 
2e0cd75
82dcf73
 
c4be8c2
2e0cd75
82dcf73
 
 
 
 
 
 
 
 
62bf7b3
2e0cd75
5edca44
2e0cd75
c2401c0
2e0cd75
 
 
 
1597d72
2e0cd75
 
1597d72
 
2e0cd75
1597d72
2e0cd75
1597d72
f77e7f8
2e0cd75
 
 
 
26de42f
2e0cd75
 
 
 
 
 
26de42f
2e0cd75
 
 
 
 
 
26de42f
2e0cd75
 
 
 
 
 
 
f77e7f8
2e0cd75
77987e2
2e0cd75
77987e2
2e0cd75
 
 
1597d72
2e0cd75
 
1597d72
2e0cd75
 
 
1597d72
 
 
77987e2
2e0cd75
77987e2
2e0cd75
 
1597d72
 
2e0cd75
 
1597d72
 
 
2e0cd75
1597d72
 
 
 
2e0cd75
1597d72
 
2e0cd75
1597d72
2e0cd75
1597d72
 
2e0cd75
1597d72
 
2e0cd75
1597d72
 
 
e2eb8eb
2e0cd75
e33e382
 
 
 
 
 
 
 
 
 
 
e2eb8eb
9969ce7
e2eb8eb
 
e005050
e2eb8eb
 
78506fe
e33e382
 
 
 
 
 
e2eb8eb
3d0cf98
 
9c8df4f
e2eb8eb
 
78506fe
2e0cd75
82dcf73
 
 
 
 
 
2e0cd75
dbf8ff3
1597d72
82dcf73
 
 
 
 
 
ec3403f
1597d72
ec3403f
1597d72
ec3403f
1597d72
2e0cd75
1597d72
 
 
 
 
 
 
 
82dcf73
1597d72
ec3403f
dbf8ff3
 
 
 
 
 
 
 
 
 
78506fe
 
 
 
e005050
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
import gradio as gr
import random
import json
import os
import re
from datetime import datetime
from openai import OpenAI
import subprocess
import torch
from PIL import Image
from transformers import AutoProcessor, AutoModelForCausalLM, pipeline

# Skip installation process if not needed
try:
    subprocess.run('pip install flash-attn --no-build-isolation', env={'FLASH_ATTENTION_SKIP_CUDA_BUILD': "TRUE"}, shell=True)
except:
    print("Flash attention installation skipped")

# Initialize OpenAI client (API key from environment variable)
openai_api_key = os.getenv("OPENAI_API")
if openai_api_key:
    client = OpenAI(api_key=openai_api_key)
else:
    print("Warning: OPENAI_API key not found in environment variables")
    client = None

# Add translation model
translator = pipeline("translation", model="Helsinki-NLP/opus-mt-ko-en")

# Initialize Florence model
device = "cuda" if torch.cuda.is_available() else "cpu"
florence_model = AutoModelForCausalLM.from_pretrained('microsoft/Florence-2-base', trust_remote_code=True).to(device).eval()
florence_processor = AutoProcessor.from_pretrained('microsoft/Florence-2-base', trust_remote_code=True)

# Korean prompt translation function
def translate_prompt(prompt):
    if any("\uAC00" <= char <= "\uD7A3" for char in prompt):  # If Korean is included
        translated = translator(prompt, max_length=512)[0]['translation_text']
        return translated
    return prompt

# Florence caption function
def florence_caption(image):
    if not isinstance(image, Image.Image):
        image = Image.fromarray(image)
    
    inputs = florence_processor(text="<MORE_DETAILED_CAPTION>", images=image, return_tensors="pt").to(device)
    generated_ids = florence_model.generate(
        input_ids=inputs["input_ids"],
        pixel_values=inputs["pixel_values"],
        max_new_tokens=1024,
        early_stopping=False,
        do_sample=False,
        num_beams=3,
    )
    generated_text = florence_processor.batch_decode(generated_ids, skip_special_tokens=False)[0]
    parsed_answer = florence_processor.post_process_generation(
        generated_text,
        task="<MORE_DETAILED_CAPTION>",
        image_size=(image.width, image.height)
    )
    return parsed_answer["<MORE_DETAILED_CAPTION>"]

# JSON file load function
def load_json_file(file_name):
    file_path = os.path.join("data", file_name)
    try:
        with open(file_path, "r") as file:
            return json.load(file)
    except:
        print(f"Warning: Could not load {file_name}. Using empty list.")
        return []

# Load JSON data
ARTFORM = load_json_file("artform.json")
PHOTO_TYPE = load_json_file("photo_type.json")
BODY_TYPES = load_json_file("body_types.json")
DEFAULT_TAGS = load_json_file("default_tags.json")
ROLES = load_json_file("roles.json")
HAIRSTYLES = load_json_file("hairstyles.json")
ADDITIONAL_DETAILS = load_json_file("additional_details.json")
PHOTOGRAPHY_STYLES = load_json_file("photography_styles.json")
DEVICE = load_json_file("device.json")
PHOTOGRAPHER = load_json_file("photographer.json")
ARTIST = load_json_file("artist.json")
DIGITAL_ARTFORM = load_json_file("digital_artform.json")
PLACE = load_json_file("place.json")
LIGHTING = load_json_file("lighting.json")
CLOTHING = load_json_file("clothing.json")
COMPOSITION = load_json_file("composition.json")
POSE = load_json_file("pose.json")
BACKGROUND = load_json_file("background.json")

# Prompt generation class
class PromptGenerator:
    def __init__(self, seed=None):
        self.rng = random.Random(seed)

    def split_and_choose(self, input_str):
        choices = [choice.strip() for choice in input_str.split(",")]
        return self.rng.choices(choices, k=1)[0]

    def get_choice(self, input_str, default_choices):
        if input_str.lower() == "disabled":
            return ""
        elif "," in input_str:
            return self.split_and_choose(input_str)
        elif input_str.lower() == "random":
            return self.rng.choices(default_choices, k=1)[0]
        else:
            return input_str

    def clean_consecutive_commas(self, input_string):
        cleaned_string = re.sub(r',\s*,', ',', input_string)
        return cleaned_string

    def process_string(self, replaced, seed):
        replaced = re.sub(r'\s*,\s*', ',', replaced)
        replaced = re.sub(r',+', ',', replaced)
        original = replaced
        
        first_break_clipl_index = replaced.find("BREAK_CLIPL")
        second_break_clipl_index = replaced.find("BREAK_CLIPL", first_break_clipl_index + len("BREAK_CLIPL"))
        
        if first_break_clipl_index != -1 and second_break_clipl_index != -1:
            clip_content_l = replaced[first_break_clipl_index + len("BREAK_CLIPL"):second_break_clipl_index]
            replaced = replaced[:first_break_clipl_index].strip(", ") + replaced[second_break_clipl_index + len("BREAK_CLIPL"):].strip(", ")
            clip_l = clip_content_l
        else:
            clip_l = ""
        
        first_break_clipg_index = replaced.find("BREAK_CLIPG")
        second_break_clipg_index = replaced.find("BREAK_CLIPG", first_break_clipg_index + len("BREAK_CLIPG"))
        
        if first_break_clipg_index != -1 and second_break_clipg_index != -1:
            clip_content_g = replaced[first_break_clipg_index + len("BREAK_CLIPG"):second_break_clipg_index]
            replaced = replaced[:first_break_clipg_index].strip(", ") + replaced[second_break_clipg_index + len("BREAK_CLIPG"):].strip(", ")
            clip_g = clip_content_g
        else:
            clip_g = ""
        
        t5xxl = replaced
        
        original = original.replace("BREAK_CLIPL", "").replace("BREAK_CLIPG", "")
        original = re.sub(r'\s*,\s*', ',', original)
        original = re.sub(r',+', ',', original)
        clip_l = re.sub(r'\s*,\s*', ',', clip_l)
        clip_l = re.sub(r',+', ',', clip_l)
        clip_g = re.sub(r'\s*,\s*', ',', clip_g)
        clip_g = re.sub(r',+', ',', clip_g)
        if clip_l.startswith(","):
            clip_l = clip_l[1:]
        if clip_g.startswith(","):
            clip_g = clip_g[1:]
        if original.startswith(","):
            original = original[1:]
        if t5xxl.startswith(","):
            t5xxl = t5xxl[1:]

        return original, seed, t5xxl, clip_l, clip_g

    def generate_prompt(self, seed, custom, subject, artform, photo_type, body_types, default_tags, roles, hairstyles,
                        additional_details, photography_styles, device, photographer, artist, digital_artform,
                        place, lighting, clothing, composition, pose, background, input_image):
        kwargs = locals()
        del kwargs['self']
        
        seed = kwargs.get("seed", 0)
        if seed is not None:
            self.rng = random.Random(seed)
        components = []
        custom = kwargs.get("custom", "")
        if custom:
            custom = translate_prompt(custom)  # Apply translation
            components.append(custom)
        is_photographer = kwargs.get("artform", "").lower() == "photography" or (
            kwargs.get("artform", "").lower() == "random"
            and self.rng.choice([True, False])
        )

        subject = kwargs.get("subject", "")

        if is_photographer:
            selected_photo_style = self.get_choice(kwargs.get("photography_styles", ""), PHOTOGRAPHY_STYLES)
            if not selected_photo_style:
                selected_photo_style = "photography"
            components.append(selected_photo_style)
            if kwargs.get("photography_style", "") != "disabled" and kwargs.get("default_tags", "") != "disabled" or subject != "":
                components.append(" of")
        
        default_tags = kwargs.get("default_tags", "random")
        body_type = kwargs.get("body_types", "")
        if not subject:
            if default_tags == "random":
                if body_type != "disabled" and body_type != "random":
                    selected_subject = self.get_choice(kwargs.get("default_tags", ""), DEFAULT_TAGS).replace("a ", "").replace("an ", "")
                    components.append("a ")
                    components.append(body_type)
                    components.append(selected_subject)
                elif body_type == "disabled":
                    selected_subject = self.get_choice(kwargs.get("default_tags", ""), DEFAULT_TAGS)
                    components.append(selected_subject)
                else:
                    body_type = self.get_choice(body_type, BODY_TYPES)
                    components.append("a ")
                    components.append(body_type)
                    selected_subject = self.get_choice(kwargs.get("default_tags", ""), DEFAULT_TAGS).replace("a ", "").replace("an ", "")
                    components.append(selected_subject)
            elif default_tags == "disabled":
                pass
            else:
                components.append(default_tags)
        else:
            if body_type != "disabled" and body_type != "random":
                components.append("a ")
                components.append(body_type)
            elif body_type == "disabled":
                pass
            else:
                body_type = self.get_choice(body_type, BODY_TYPES)
                components.append("a ")
                components.append(body_type)
            components.append(subject)

        params = [
            ("roles", ROLES),
            ("hairstyles", HAIRSTYLES),
            ("additional_details", ADDITIONAL_DETAILS),
        ]
        for param in params:
            components.append(self.get_choice(kwargs.get(param[0], ""), param[1]))
        for i in reversed(range(len(components))):
            if components[i] in PLACE:
                components[i] += ","
                break
        if kwargs.get("clothing", "") != "disabled" and kwargs.get("clothing", "") != "random":
            components.append(", dressed in ")
            clothing = kwargs.get("clothing", "")
            components.append(clothing)
        elif kwargs.get("clothing", "") == "random":
            components.append(", dressed in ")
            clothing = self.get_choice(kwargs.get("clothing", ""), CLOTHING)
            components.append(clothing)

        if kwargs.get("composition", "") != "disabled" and kwargs.get("composition", "") != "random":
            components.append(",")
            composition = kwargs.get("composition", "")
            components.append(composition)
        elif kwargs.get("composition", "") == "random": 
            components.append(",")
            composition = self.get_choice(kwargs.get("composition", ""), COMPOSITION)
            components.append(composition)
        
        if kwargs.get("pose", "") != "disabled" and kwargs.get("pose", "") != "random":
            components.append(",")
            pose = kwargs.get("pose", "")
            components.append(pose)
        elif kwargs.get("pose", "") == "random":
            components.append(",")
            pose = self.get_choice(kwargs.get("pose", ""), POSE)
            components.append(pose)
        components.append("BREAK_CLIPG")
        if kwargs.get("background", "") != "disabled" and kwargs.get("background", "") != "random":
            components.append(",")
            background = kwargs.get("background", "")
            components.append(background)
        elif kwargs.get("background", "") == "random": 
            components.append(",")
            background = self.get_choice(kwargs.get("background", ""), BACKGROUND)
            components.append(background)

        if kwargs.get("place", "") != "disabled" and kwargs.get("place", "") != "random":
            components.append(",")
            place = kwargs.get("place", "")
            components.append(place)
        elif kwargs.get("place", "") == "random": 
            components.append(",")
            place = self.get_choice(kwargs.get("place", ""), PLACE)
            components.append(place + ",")

        lighting = kwargs.get("lighting", "").lower()
        if lighting == "random":
            selected_lighting = ", ".join(self.rng.sample(LIGHTING, self.rng.randint(2, 5)))
            components.append(",")
            components.append(selected_lighting)
        elif lighting == "disabled":
            pass
        else:
            components.append(", ")
            components.append(lighting)
        components.append("BREAK_CLIPG")
        components.append("BREAK_CLIPL")
        if is_photographer:
            if kwargs.get("photo_type", "") != "disabled":
                photo_type_choice = self.get_choice(kwargs.get("photo_type", ""), PHOTO_TYPE)
                if photo_type_choice and photo_type_choice != "random" and photo_type_choice != "disabled":
                    random_value = round(self.rng.uniform(1.1, 1.5), 1)
                    components.append(f", ({photo_type_choice}:{random_value}), ")

            params = [
                ("device", DEVICE),
                ("photographer", PHOTOGRAPHER),
            ]
            components.extend([self.get_choice(kwargs.get(param[0], ""), param[1]) for param in params])
            if kwargs.get("device", "") != "disabled":
                components[-2] = f", shot on {components[-2]}"
            if kwargs.get("photographer", "") != "disabled":
                components[-1] = f", photo by {components[-1]}"
        else:
            digital_artform_choice = self.get_choice(kwargs.get("digital_artform", ""), DIGITAL_ARTFORM)
            if digital_artform_choice:
                components.append(f"{digital_artform_choice}")
            if kwargs.get("artist", "") != "disabled":
                components.append(f"by {self.get_choice(kwargs.get('artist', ''), ARTIST)}")
        components.append("BREAK_CLIPL")

        prompt = " ".join(components)
        prompt = re.sub(" +", " ", prompt)
        replaced = prompt.replace("of as", "of")
        replaced = self.clean_consecutive_commas(replaced)

        return self.process_string(replaced, seed)
    
    def add_caption_to_prompt(self, prompt, caption):
        if caption:
            return f"{prompt}, {caption}"
        return prompt

class OpenAIGenerationNode:
    def __init__(self):
        self.client = client
        self.prompts_dir = "./prompts"
        os.makedirs(self.prompts_dir, exist_ok=True)

    def save_prompt(self, prompt):
        filename_text = "openai_" + prompt.split(',')[0].strip()
        filename_text = re.sub(r'[^\w\-_\. ]', '_', filename_text)
        filename_text = filename_text[:30]  
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        base_filename = f"{filename_text}_{timestamp}.txt"
        filename = os.path.join(self.prompts_dir, base_filename)
        
        with open(filename, "w") as file:
            file.write(prompt)
        
        print(f"Prompt saved to {filename}")

    def generate(self, input_text, happy_talk, compress, compression_level, poster, custom_base_prompt=""):
        try:
            if not self.client:
                return "Error: OpenAI API key not found. Please set OPENAI_API environment variable."
                
            # Fixed model: gpt-4.1-mini
            openai_model = "gpt-4.1-mini"

            default_happy_prompt = """Create a detailed visually descriptive caption of this description, which will be used as a prompt for a text to image AI system (caption only, no instructions like "create an image").Remove any mention of digital artwork or artwork style. Give detailed visual descriptions of the character(s), including ethnicity, skin tone, expression etc. Imagine using keywords for a still for someone who has aphantasia. Describe the image style, e.g. any photographic or art styles / techniques utilized. Make sure to fully describe all aspects of the cinematography, with abundant technical details and visual descriptions. If there is more than one image, combine the elements and characters from all of the images creatively into a single cohesive composition with a single background, inventing an interaction between the characters. Be creative in combining the characters into a single cohesive scene. Focus on two primary characters (or one) and describe an interesting interaction between them, such as a hug, a kiss, a fight, giving an object, an emotional reaction / interaction. If there is more than one background in the images, pick the most appropriate one. Your output is only the caption itself, no comments or extra formatting. The caption is in a single long paragraph. If you feel the images are inappropriate, invent a new scene / characters inspired by these. Additionally, incorporate a specific movie director's visual style and describe the lighting setup in detail, including the type, color, and placement of light sources to create the desired mood and atmosphere. Always frame the scene, including details about the film grain, color grading, and any artifacts or characteristics specific."""

            default_simple_prompt = """Create a brief, straightforward caption for this description, suitable for a text-to-image AI system. Focus on the main elements, key characters, and overall scene without elaborate details. Provide a clear and concise description in one or two sentences."""

            poster_prompt = """Analyze the provided description and extract key information to create a movie poster style description. Format the output as follows:
Title: A catchy, intriguing title that captures the essence of the scene, place the title in "".
Main character: Give a description of the main character.
Background: Describe the background in detail.
Supporting characters: Describe the supporting characters
Branding type: Describe the branding type
Tagline: Include a tagline that captures the essence of the movie.
Visual style: Ensure that the visual style fits the branding type and tagline.
You are allowed to make up film and branding names, and do them like 80's, 90's or modern movie posters."""

            if poster:
                base_prompt = poster_prompt
            elif custom_base_prompt.strip():
                base_prompt = custom_base_prompt
            else:
                base_prompt = default_happy_prompt if happy_talk else default_simple_prompt

            if compress and not poster:
                compression_chars = {
                    "soft": 600 if happy_talk else 300,
                    "medium": 400 if happy_talk else 200,
                    "hard": 200 if happy_talk else 100
                }
                char_limit = compression_chars[compression_level]
                base_prompt += f" Compress the output to be concise while retaining key visual details. MAX OUTPUT SIZE no more than {char_limit} characters."

            # Correct OpenAI API call format
            response = self.client.chat.completions.create(
                model=openai_model,
                messages=[
                    {
                        "role": "system",
                        "content": "You are a helpful assistant. Try your best to give best response possible to user."
                    },
                    {
                        "role": "user",
                        "content": f"{base_prompt}\nDescription: {input_text}"
                    }
                ],
                temperature=1,
                max_tokens=2048,
                top_p=1
            )
            
            # Extract response
            output = response.choices[0].message.content
            
            # Clean output
            if ": " in output:
                output = output.split(": ", 1)[1].strip()
            elif output.lower().startswith("here"):
                sentences = output.split(". ")
                if len(sentences) > 1:
                    output = ". ".join(sentences[1:]).strip()
            
            # Save prompt
            self.save_prompt(output)
            
            return output

        except Exception as e:
            print(f"An error occurred: {e}")
            return f"Error occurred while processing the request: {str(e)}"

# Enhanced CSS
css = """
footer {
    visibility: hidden;
}
.main-title {
    text-align: center;
    margin: 20px 0;
}
.main-title h1 {
    color: #2c3e50;
    font-size: 2.5em;
}
.badge-container {
    display: flex;
    justify-content: center;
    gap: 15px;
    margin: 20px auto;
    max-width: 100%;
}
.prompt-generator-container {
    background: #f8f9fa;
    border-radius: 10px;
    padding: 20px;
    margin: 10px 0;
}
.settings-container {
    background: #ffffff;
    border-radius: 8px;
    padding: 15px;
    margin: 10px 0;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.output-container {
    background: #e8f4f8;
    border-radius: 8px;
    padding: 15px;
    margin: 10px 0;
}
.generate-button {
    background: #3498db !important;
    color: white !important;
    font-size: 1.1em !important;
    padding: 12px 24px !important;
    margin: 10px 0 !important;
}
.openai-button {
    background: #27ae60 !important;
    color: white !important;
    font-size: 1.1em !important;
    padding: 12px 24px !important;
}
.section-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 10px 15px;
    border-radius: 8px;
    margin-bottom: 15px;
    font-weight: bold;
}
"""

def create_interface():
    prompt_generator = PromptGenerator()
    openai_node = OpenAIGenerationNode()
    
    with gr.Blocks(theme="soft", css=css) as demo:
        # Header
        with gr.Row(elem_classes="main-title"):
            gr.HTML("""
                <h1>🎨 Flux Prompt Generator</h1>
                <p style="text-align: center; color: #7f8c8d; font-size: 1.1em;">
                    Korean Input Support | AI-Based Prompt Generator
                </p>
            """)
        
        # Badges
        with gr.Row(elem_classes="badge-container"):
            gr.HTML("""
                <a href="https://huggingface.co/spaces/openfree/Best-AI" target="_blank">
                    <img src="https://img.shields.io/static/v1?label=OpenFree&message=BEST%20AI%20Services&color=%230000ff&labelColor=%23000080&logo=huggingface&logoColor=%23ffa500&style=for-the-badge" alt="OpenFree badge">
                </a>
                <a href="https://discord.gg/openfreeai" target="_blank">
                    <img src="https://img.shields.io/static/v1?label=Discord&message=Openfree%20AI&color=%230000ff&labelColor=%23800080&logo=discord&logoColor=white&style=for-the-badge" alt="Discord badge">
                </a>
            """)
        
        # Main container
        with gr.Row():
            # Left panel - Settings
            with gr.Column(scale=2):
                gr.HTML('<div class="section-header">🎯 Basic Settings</div>')
                seed = gr.Slider(0, 30000, label='Seed Value', step=1, value=random.randint(0,30000))
                custom = gr.Textbox(label="✏️ Custom Prompt (Korean Available)", placeholder="Enter your description...")
                subject = gr.Textbox(label="🎭 Subject (Optional)", placeholder="e.g., beautiful woman, cute cat, etc...")
                
                # Global option settings
                gr.HTML('<div class="section-header">⚑ Quick Settings</div>')
                global_option = gr.Radio(
                    ["Disabled", "Random", "No Figure Rand"],
                    label="Apply All Options at Once:",
                    value="Disabled",
                    info="Change all settings at once"
                )
                
                # Detailed settings
                with gr.Accordion("🎨 Artform & Photo Type", open=False):
                    artform = gr.Dropdown(["disabled", "random"] + ARTFORM, label="Artform", value="disabled")
                    photo_type = gr.Dropdown(["disabled", "random"] + PHOTO_TYPE, label="Photo Type", value="disabled")
            
                with gr.Accordion("πŸ‘€ Character Settings", open=False):
                    body_types = gr.Dropdown(["disabled", "random"] + BODY_TYPES, label="Body Type", value="disabled")
                    default_tags = gr.Dropdown(["disabled", "random"] + DEFAULT_TAGS, label="Default Tags", value="disabled")
                    roles = gr.Dropdown(["disabled", "random"] + ROLES, label="Role", value="disabled")
                    hairstyles = gr.Dropdown(["disabled", "random"] + HAIRSTYLES, label="Hairstyle", value="disabled")
                    clothing = gr.Dropdown(["disabled", "random"] + CLOTHING, label="Clothing", value="disabled")
            
                with gr.Accordion("🏞️ Scene Settings", open=False):
                    place = gr.Dropdown(["disabled", "random"] + PLACE, label="Place", value="disabled")
                    lighting = gr.Dropdown(["disabled", "random"] + LIGHTING, label="Lighting", value="disabled")
                    composition = gr.Dropdown(["disabled", "random"] + COMPOSITION, label="Composition", value="disabled")
                    pose = gr.Dropdown(["disabled", "random"] + POSE, label="Pose", value="disabled")
                    background = gr.Dropdown(["disabled", "random"] + BACKGROUND, label="Background", value="disabled")
            
                with gr.Accordion("🎭 Style & Artist", open=False):
                    additional_details = gr.Dropdown(["disabled", "random"] + ADDITIONAL_DETAILS, label="Additional Details", value="disabled")
                    photography_styles = gr.Dropdown(["disabled", "random"] + PHOTOGRAPHY_STYLES, label="Photography Style", value="disabled")
                    device = gr.Dropdown(["disabled", "random"] + DEVICE, label="Camera/Device", value="disabled")
                    photographer = gr.Dropdown(["disabled", "random"] + PHOTOGRAPHER, label="Photographer", value="disabled")
                    artist = gr.Dropdown(["disabled", "random"] + ARTIST, label="Artist", value="disabled")
                    digital_artform = gr.Dropdown(["disabled", "random"] + DIGITAL_ARTFORM, label="Digital Artform", value="disabled")
                
                generate_button = gr.Button("πŸš€ Generate Prompt", variant="primary", elem_classes="generate-button")

            # Middle panel - Image and output
            with gr.Column(scale=2):
                with gr.Accordion("πŸ–ΌοΈ Image Caption Generation", open=False):
                    input_image = gr.Image(label="Upload Image (Optional)", type="pil")
                    caption_output = gr.Textbox(label="Generated Caption", lines=3)
                    with gr.Row():
                        create_caption_button = gr.Button("πŸ“ Generate Caption", variant="secondary")
                        add_caption_button = gr.Button("βž• Add to Prompt", variant="secondary")

                gr.HTML('<div class="section-header">πŸ“‹ Generated Prompts</div>')
                output = gr.Textbox(label="Main Prompt", lines=4)
                with gr.Accordion("Advanced Output Options", open=False):
                    t5xxl_output = gr.Textbox(label="T5XXL", lines=2)
                    clip_l_output = gr.Textbox(label="CLIP L", lines=2)
                    clip_g_output = gr.Textbox(label="CLIP G", lines=2)
            
            # Right panel - OpenAI
            with gr.Column(scale=2):
                gr.HTML('<div class="section-header">πŸ€– OpenAI Prompt Enhancement</div>')
                gr.HTML("<p style='text-align: center; color: #95a5a6;'>Model Used: gpt-4.1-mini</p>")
                
                with gr.Row():
                    happy_talk = gr.Checkbox(label="😊 Happy Talk", value=True, info="More detailed description")
                    compress = gr.Checkbox(label="πŸ—œοΈ Compress", value=True, info="Limit output length")
                
                compression_level = gr.Radio(
                    ["soft", "medium", "hard"], 
                    label="Compression Strength", 
                    value="hard",
                    visible=True
                )
                
                poster = gr.Checkbox(label="🎬 Movie Poster Style", value=False)
                
                custom_base_prompt = gr.Textbox(
                    label="πŸ› οΈ Custom Base Prompt", 
                    lines=5,
                    placeholder="Enter special instructions for OpenAI..."
                )
                
                generate_text_button = gr.Button("✨ Enhance with AI", variant="primary", elem_classes="openai-button")
                
                text_output = gr.Textbox(
                    label="🎯 AI Enhanced Result", 
                    lines=10,
                    elem_classes="output-container"
                )

        # Event handlers
        def create_caption(image):
            if image is not None:
                return florence_caption(image)
            return ""

        create_caption_button.click(
            create_caption,
            inputs=[input_image],
            outputs=[caption_output]
        )

        generate_button.click(
            prompt_generator.generate_prompt,
            inputs=[seed, custom, subject, artform, photo_type, body_types, default_tags, roles, hairstyles,
                    additional_details, photography_styles, device, photographer, artist, digital_artform,
                    place, lighting, clothing, composition, pose, background, input_image],
            outputs=[output, gr.Number(visible=False), t5xxl_output, clip_l_output, clip_g_output]
        )

        add_caption_button.click(
            prompt_generator.add_caption_to_prompt,
            inputs=[output, caption_output],
            outputs=[output]
        )

        generate_text_button.click(
            lambda input_text, happy_talk, compress, compression_level, poster, custom_base_prompt: 
                openai_node.generate(input_text, happy_talk, compress, compression_level, poster, custom_base_prompt),
            inputs=[output, happy_talk, compress, compression_level, poster, custom_base_prompt],
            outputs=text_output
        )

        # Show/hide compression strength based on compress checkbox
        compress.change(
            lambda x: gr.update(visible=x),
            inputs=[compress],
            outputs=[compression_level]
        )

        # Global option change function
        def update_all_options(choice):
            updates = []
            dropdown_list = [
                artform, photo_type, body_types, default_tags, roles, hairstyles, clothing,
                place, lighting, composition, pose, background, additional_details,
                photography_styles, device, photographer, artist, digital_artform
            ]
            
            if choice == "Disabled":
                updates = [gr.update(value="disabled") for _ in dropdown_list]
            elif choice == "Random":
                updates = [gr.update(value="random") for _ in dropdown_list]
            else:  # No Figure Random
                updates = []
                # Character-related settings are disabled
                character_dropdowns = [photo_type, body_types, default_tags, roles, hairstyles, clothing, pose, additional_details]
                other_dropdowns = [artform, place, lighting, composition, background, photography_styles, device, photographer, artist, digital_artform]
                
                for dropdown in dropdown_list:
                    if dropdown in character_dropdowns:
                        updates.append(gr.update(value="disabled"))
                    else:
                        updates.append(gr.update(value="random"))
            
            return updates
        
        global_option.change(
            update_all_options,
            inputs=[global_option],
            outputs=[
                artform, photo_type, body_types, default_tags, roles, hairstyles, clothing,
                place, lighting, composition, pose, background, additional_details,
                photography_styles, device, photographer, artist, digital_artform
            ]
        )

    return demo

if __name__ == "__main__":
    demo = create_interface()
    demo.launch()