Aitrepreneur commited on
Commit
cb644d5
1 Parent(s): 77e1ca8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +586 -587
app.py CHANGED
@@ -1,587 +1,586 @@
1
- import gradio as gr
2
- import random
3
- import json
4
- import os
5
- import re
6
- from datetime import datetime
7
- from huggingface_hub import InferenceClient
8
- import subprocess
9
- import torch
10
- import devicetorch
11
- from PIL import Image
12
- from unittest.mock import patch
13
- from transformers.dynamic_module_utils import get_imports
14
- from transformers import AutoModelForCausalLM, AutoTokenizer, AutoProcessor
15
- import random
16
- import importlib.util
17
- import sys
18
- from groq import Groq
19
- import time
20
-
21
- #ADD YOUR OWN GROQ API KEY ON LINE 336
22
-
23
- # Initialize Florence model
24
- device = devicetorch.get(torch)
25
-
26
- def fixed_get_imports(filename: str | os.PathLike) -> list[str]:
27
- if not str(filename).endswith("modeling_florence2.py"):
28
- return get_imports(filename)
29
- imports = get_imports(filename)
30
- if "flash_attn" in imports:
31
- imports.remove("flash_attn")
32
- return imports
33
-
34
- with patch("transformers.dynamic_module_utils.get_imports", fixed_get_imports):
35
- florence_model = AutoModelForCausalLM.from_pretrained(
36
- 'microsoft/Florence-2-base',
37
- attn_implementation="sdpa",
38
- torch_dtype=torch.float16 if 'cuda' in str(device) else torch.float32,
39
- trust_remote_code=True
40
- ).to(device).eval()
41
-
42
- florence_processor = AutoProcessor.from_pretrained('microsoft/Florence-2-base', trust_remote_code=True)
43
-
44
-
45
-
46
- #device = "cuda" if torch.cuda.is_available() else "cpu"
47
- #florence_model = AutoModelForCausalLM.from_pretrained('microsoft/Florence-2-base', trust_remote_code=True)#.to(device).eval()
48
- #florence_processor = AutoProcessor.from_pretrained('microsoft/Florence-2-base', trust_remote_code=True)
49
-
50
- # Florence caption function
51
- def florence_caption(image):
52
- if not isinstance(image, Image.Image):
53
- image = Image.fromarray(image)
54
-
55
- inputs = florence_processor(text="<MORE_DETAILED_CAPTION>", images=image, return_tensors="pt").to(device)
56
- generated_ids = florence_model.generate(
57
- input_ids=inputs["input_ids"],
58
- pixel_values=inputs["pixel_values"],
59
- max_new_tokens=1024,
60
- early_stopping=False,
61
- do_sample=False,
62
- num_beams=3,
63
- )
64
- generated_text = florence_processor.batch_decode(generated_ids, skip_special_tokens=False)[0]
65
- parsed_answer = florence_processor.post_process_generation(
66
- generated_text,
67
- task="<MORE_DETAILED_CAPTION>",
68
- image_size=(image.width, image.height)
69
- )
70
- return parsed_answer["<MORE_DETAILED_CAPTION>"]
71
-
72
- # Load JSON files
73
- def load_json_file(file_name):
74
- file_path = os.path.join("data", file_name)
75
- with open(file_path, "r") as file:
76
- return json.load(file)
77
-
78
- ARTFORM = load_json_file("artform.json")
79
- PHOTO_TYPE = load_json_file("photo_type.json")
80
- BODY_TYPES = load_json_file("body_types.json")
81
- DEFAULT_TAGS = load_json_file("default_tags.json")
82
- ROLES = load_json_file("roles.json")
83
- HAIRSTYLES = load_json_file("hairstyles.json")
84
- ADDITIONAL_DETAILS = load_json_file("additional_details.json")
85
- PHOTOGRAPHY_STYLES = load_json_file("photography_styles.json")
86
- DEVICE = load_json_file("device.json")
87
- PHOTOGRAPHER = load_json_file("photographer.json")
88
- ARTIST = load_json_file("artist.json")
89
- DIGITAL_ARTFORM = load_json_file("digital_artform.json")
90
- PLACE = load_json_file("place.json")
91
- LIGHTING = load_json_file("lighting.json")
92
- CLOTHING = load_json_file("clothing.json")
93
- COMPOSITION = load_json_file("composition.json")
94
- POSE = load_json_file("pose.json")
95
- BACKGROUND = load_json_file("background.json")
96
-
97
- class PromptGenerator:
98
- def __init__(self, seed=None):
99
- self.rng = random.Random(seed)
100
-
101
- def split_and_choose(self, input_str):
102
- choices = [choice.strip() for choice in input_str.split(",")]
103
- return self.rng.choices(choices, k=1)[0]
104
-
105
- def get_choice(self, input_str, default_choices):
106
- if input_str.lower() == "disabled":
107
- return ""
108
- elif "," in input_str:
109
- return self.split_and_choose(input_str)
110
- elif input_str.lower() == "random":
111
- return self.rng.choices(default_choices, k=1)[0]
112
- else:
113
- return input_str
114
-
115
- def clean_consecutive_commas(self, input_string):
116
- cleaned_string = re.sub(r',\s*,', ',', input_string)
117
- return cleaned_string
118
-
119
- def process_string(self, replaced, seed):
120
- replaced = re.sub(r'\s*,\s*', ',', replaced)
121
- replaced = re.sub(r',+', ',', replaced)
122
- original = replaced
123
-
124
- first_break_clipl_index = replaced.find("BREAK_CLIPL")
125
- second_break_clipl_index = replaced.find("BREAK_CLIPL", first_break_clipl_index + len("BREAK_CLIPL"))
126
-
127
- if first_break_clipl_index != -1 and second_break_clipl_index != -1:
128
- clip_content_l = replaced[first_break_clipl_index + len("BREAK_CLIPL"):second_break_clipl_index]
129
- replaced = replaced[:first_break_clipl_index].strip(", ") + replaced[second_break_clipl_index + len("BREAK_CLIPL"):].strip(", ")
130
- clip_l = clip_content_l
131
- else:
132
- clip_l = ""
133
-
134
- first_break_clipg_index = replaced.find("BREAK_CLIPG")
135
- second_break_clipg_index = replaced.find("BREAK_CLIPG", first_break_clipg_index + len("BREAK_CLIPG"))
136
-
137
- if first_break_clipg_index != -1 and second_break_clipg_index != -1:
138
- clip_content_g = replaced[first_break_clipg_index + len("BREAK_CLIPG"):second_break_clipg_index]
139
- replaced = replaced[:first_break_clipg_index].strip(", ") + replaced[second_break_clipg_index + len("BREAK_CLIPG"):].strip(", ")
140
- clip_g = clip_content_g
141
- else:
142
- clip_g = ""
143
-
144
- t5xxl = replaced
145
-
146
- original = original.replace("BREAK_CLIPL", "").replace("BREAK_CLIPG", "")
147
- original = re.sub(r'\s*,\s*', ',', original)
148
- original = re.sub(r',+', ',', original)
149
- clip_l = re.sub(r'\s*,\s*', ',', clip_l)
150
- clip_l = re.sub(r',+', ',', clip_l)
151
- clip_g = re.sub(r'\s*,\s*', ',', clip_g)
152
- clip_g = re.sub(r',+', ',', clip_g)
153
- if clip_l.startswith(","):
154
- clip_l = clip_l[1:]
155
- if clip_g.startswith(","):
156
- clip_g = clip_g[1:]
157
- if original.startswith(","):
158
- original = original[1:]
159
- if t5xxl.startswith(","):
160
- t5xxl = t5xxl[1:]
161
-
162
- return original, seed, t5xxl, clip_l, clip_g
163
-
164
- def generate_prompt(self, seed, custom, subject, artform, photo_type, body_types, default_tags, roles, hairstyles,
165
- additional_details, photography_styles, device, photographer, artist, digital_artform,
166
- place, lighting, clothing, composition, pose, background, input_image, *args):
167
- print(f"Number of arguments received: {len(args)}")
168
- for i, arg in enumerate(args):
169
- print(f"Argument {i}: {arg}")
170
- kwargs = locals()
171
- del kwargs['self']
172
-
173
- seed = kwargs.get("seed", 0)
174
- if seed is not None:
175
- self.rng = random.Random(seed)
176
- components = []
177
- custom = kwargs.get("custom", "")
178
- if custom:
179
- components.append(custom)
180
- is_photographer = kwargs.get("artform", "").lower() == "photography" or (
181
- kwargs.get("artform", "").lower() == "random"
182
- and self.rng.choice([True, False])
183
- )
184
-
185
- subject = kwargs.get("subject", "")
186
-
187
- if is_photographer:
188
- selected_photo_style = self.get_choice(kwargs.get("photography_styles", ""), PHOTOGRAPHY_STYLES)
189
- if not selected_photo_style:
190
- selected_photo_style = "photography"
191
- components.append(selected_photo_style)
192
- if kwargs.get("photography_style", "") != "disabled" and kwargs.get("default_tags", "") != "disabled" or subject != "":
193
- components.append(" of")
194
-
195
- default_tags = kwargs.get("default_tags", "random")
196
- body_type = kwargs.get("body_types", "")
197
- if not subject:
198
- if default_tags == "random":
199
- if body_type != "disabled" and body_type != "random":
200
- selected_subject = self.get_choice(kwargs.get("default_tags", ""), DEFAULT_TAGS).replace("a ", "").replace("an ", "")
201
- components.append("a ")
202
- components.append(body_type)
203
- components.append(selected_subject)
204
- elif body_type == "disabled":
205
- selected_subject = self.get_choice(kwargs.get("default_tags", ""), DEFAULT_TAGS)
206
- components.append(selected_subject)
207
- else:
208
- body_type = self.get_choice(body_type, BODY_TYPES)
209
- components.append("a ")
210
- components.append(body_type)
211
- selected_subject = self.get_choice(kwargs.get("default_tags", ""), DEFAULT_TAGS).replace("a ", "").replace("an ", "")
212
- components.append(selected_subject)
213
- elif default_tags == "disabled":
214
- pass
215
- else:
216
- components.append(default_tags)
217
- else:
218
- if body_type != "disabled" and body_type != "random":
219
- components.append("a ")
220
- components.append(body_type)
221
- elif body_type == "disabled":
222
- pass
223
- else:
224
- body_type = self.get_choice(body_type, BODY_TYPES)
225
- components.append("a ")
226
- components.append(body_type)
227
- components.append(subject)
228
-
229
- params = [
230
- ("roles", ROLES),
231
- ("hairstyles", HAIRSTYLES),
232
- ("additional_details", ADDITIONAL_DETAILS),
233
- ]
234
- for param in params:
235
- components.append(self.get_choice(kwargs.get(param[0], ""), param[1]))
236
- for i in reversed(range(len(components))):
237
- if components[i] in PLACE:
238
- components[i] += ","
239
- break
240
- if kwargs.get("clothing", "") != "disabled" and kwargs.get("clothing", "") != "random":
241
- components.append(", dressed in ")
242
- clothing = kwargs.get("clothing", "")
243
- components.append(clothing)
244
- elif kwargs.get("clothing", "") == "random":
245
- components.append(", dressed in ")
246
- clothing = self.get_choice(kwargs.get("clothing", ""), CLOTHING)
247
- components.append(clothing)
248
-
249
- if kwargs.get("composition", "") != "disabled" and kwargs.get("composition", "") != "random":
250
- components.append(",")
251
- composition = kwargs.get("composition", "")
252
- components.append(composition)
253
- elif kwargs.get("composition", "") == "random":
254
- components.append(",")
255
- composition = self.get_choice(kwargs.get("composition", ""), COMPOSITION)
256
- components.append(composition)
257
-
258
- if kwargs.get("pose", "") != "disabled" and kwargs.get("pose", "") != "random":
259
- components.append(",")
260
- pose = kwargs.get("pose", "")
261
- components.append(pose)
262
- elif kwargs.get("pose", "") == "random":
263
- components.append(",")
264
- pose = self.get_choice(kwargs.get("pose", ""), POSE)
265
- components.append(pose)
266
- components.append("BREAK_CLIPG")
267
- if kwargs.get("background", "") != "disabled" and kwargs.get("background", "") != "random":
268
- components.append(",")
269
- background = kwargs.get("background", "")
270
- components.append(background)
271
- elif kwargs.get("background", "") == "random":
272
- components.append(",")
273
- background = self.get_choice(kwargs.get("background", ""), BACKGROUND)
274
- components.append(background)
275
-
276
- if kwargs.get("place", "") != "disabled" and kwargs.get("place", "") != "random":
277
- components.append(",")
278
- place = kwargs.get("place", "")
279
- components.append(place)
280
- elif kwargs.get("place", "") == "random":
281
- components.append(",")
282
- place = self.get_choice(kwargs.get("place", ""), PLACE)
283
- components.append(place + ",")
284
-
285
- lighting = kwargs.get("lighting", "").lower()
286
- if lighting == "random":
287
- selected_lighting = ", ".join(self.rng.sample(LIGHTING, self.rng.randint(2, 5)))
288
- components.append(",")
289
- components.append(selected_lighting)
290
- elif lighting == "disabled":
291
- pass
292
- else:
293
- components.append(", ")
294
- components.append(lighting)
295
- components.append("BREAK_CLIPG")
296
- components.append("BREAK_CLIPL")
297
- if is_photographer:
298
- if kwargs.get("photo_type", "") != "disabled":
299
- photo_type_choice = self.get_choice(kwargs.get("photo_type", ""), PHOTO_TYPE)
300
- if photo_type_choice and photo_type_choice != "random" and photo_type_choice != "disabled":
301
- random_value = round(self.rng.uniform(1.1, 1.5), 1)
302
- components.append(f", ({photo_type_choice}:{random_value}), ")
303
-
304
- params = [
305
- ("device", DEVICE),
306
- ("photographer", PHOTOGRAPHER),
307
- ]
308
- components.extend([self.get_choice(kwargs.get(param[0], ""), param[1]) for param in params])
309
- if kwargs.get("device", "") != "disabled":
310
- components[-2] = f", shot on {components[-2]}"
311
- if kwargs.get("photographer", "") != "disabled":
312
- components[-1] = f", photo by {components[-1]}"
313
- else:
314
- digital_artform_choice = self.get_choice(kwargs.get("digital_artform", ""), DIGITAL_ARTFORM)
315
- if digital_artform_choice:
316
- components.append(f"{digital_artform_choice}")
317
- if kwargs.get("artist", "") != "disabled":
318
- components.append(f"by {self.get_choice(kwargs.get('artist', ''), ARTIST)}")
319
- components.append("BREAK_CLIPL")
320
-
321
- prompt = " ".join(components)
322
- prompt = re.sub(" +", " ", prompt)
323
- replaced = prompt.replace("of as", "of")
324
- replaced = self.clean_consecutive_commas(replaced)
325
-
326
- return self.process_string(replaced, seed)
327
-
328
- def add_caption_to_prompt(self, prompt, caption):
329
- if caption:
330
- return f"{prompt}, {caption}"
331
- return prompt
332
-
333
- class GroqInferenceNode:
334
- def __init__(self):
335
- #ADD YOUR OWN GROQ API KEY HERE
336
- self.client = Groq(api_key="YOUR-API-KEY")
337
- self.models = {
338
- "Mixtral 8x7B": "mixtral-8x7b-32768",
339
- "Llama 3.1 70B": "llama-3.1-70b-versatile",
340
- "Llama 3.1 8B": "llama-3.1-8b-instant"
341
- }
342
- self.prompts_dir = "./prompts"
343
- os.makedirs(self.prompts_dir, exist_ok=True)
344
-
345
- def save_prompt(self, prompt):
346
- filename_text = "groq_" + prompt.split(',')[0].strip()
347
- filename_text = re.sub(r'[^\w\-_\. ]', '_', filename_text)
348
- filename_text = filename_text[:30]
349
- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
350
- base_filename = f"{filename_text}_{timestamp}.txt"
351
- filename = os.path.join(self.prompts_dir, base_filename)
352
-
353
- with open(filename, "w") as file:
354
- file.write(prompt)
355
-
356
- print(f"Prompt saved to {filename}")
357
-
358
- def generate(self, model, input_text, happy_talk, compress, compression_level, poster, custom_base_prompt=""):
359
- try:
360
- model_id = self.models.get(model, "llama-3.1-8b-instant")
361
-
362
- 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."""
363
-
364
- 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."""
365
-
366
- poster_prompt = """Analyze the provided description and extract key information to create a movie poster style description. Format the output as follows:
367
- Title: A catchy, intriguing title that captures the essence of the scene, place the title in "".
368
- Main character: Give a description of the main character.
369
- Background: Describe the background in detail.
370
- Supporting characters: Describe the supporting characters
371
- Branding type: Describe the branding type
372
- Tagline: Include a tagline that captures the essence of the movie.
373
- Visual style: Ensure that the visual style fits the branding type and tagline.
374
- You are allowed to make up film and branding names, and do them like 80's, 90's or modern movie posters."""
375
-
376
- if poster:
377
- base_prompt = poster_prompt
378
- elif custom_base_prompt.strip():
379
- base_prompt = custom_base_prompt
380
- else:
381
- base_prompt = default_happy_prompt if happy_talk else default_simple_prompt
382
-
383
- if compress and not poster:
384
- compression_chars = {
385
- "soft": 600 if happy_talk else 300,
386
- "medium": 400 if happy_talk else 200,
387
- "hard": 200 if happy_talk else 100
388
- }
389
- char_limit = compression_chars[compression_level]
390
- base_prompt += f" Compress the output to be concise while retaining key visual details. MAX OUTPUT SIZE no more than {char_limit} characters."
391
-
392
- messages = [
393
- {"role": "system", "content": "You are a helpful assistant. Try your best to give best response possible to user."},
394
- {"role": "user", "content": f"{base_prompt}\nDescription: {input_text}"}
395
- ]
396
-
397
- print(f"Starting generation with {model_id}...")
398
- start_time = time.time()
399
-
400
- chat_completion = self.client.chat.completions.create(
401
- messages=messages,
402
- model=model_id,
403
- max_tokens=4000,
404
- temperature=0.7,
405
- top_p=0.95
406
- )
407
-
408
- end_time = time.time()
409
- print(f"Generation completed in {end_time - start_time:.2f} seconds")
410
-
411
- output = chat_completion.choices[0].message.content
412
-
413
- # Clean up the output
414
- if ": " in output:
415
- output = output.split(": ", 1)[1].strip()
416
- elif output.lower().startswith("here"):
417
- sentences = output.split(". ")
418
- if len(sentences) > 1:
419
- output = ". ".join(sentences[1:]).strip()
420
-
421
- return output
422
-
423
- except Exception as e:
424
- print(f"An error occurred: {e}")
425
- return f"Error occurred while processing the request: {str(e)}"
426
-
427
- title = """<h1 align="center">FLUX Prompt Generator</h1>
428
- <p><center>
429
- <p align="center">Flux Prompt generator modified by <a href="https://www.patreon.com/aitrepreneur" target="_blank">[Aitrepreneur]</a>.</p>
430
- <a href="https://x.com/gokayfem" target="_blank">[X gokaygokay]</a>
431
- <a href="https://github.com/gokayfem" target="_blank">[Github gokayfem]</a>
432
- <a href="https://github.com/dagthomas/comfyui_dagthomas" target="_blank">[comfyui_dagthomas]</a>
433
- <p align="center">Create long prompts from images or simple words. Enhance your short prompts with prompt enhancer.</p>
434
- </center></p>
435
- """
436
-
437
- def create_interface():
438
- prompt_generator = PromptGenerator()
439
- groq_inference = GroqInferenceNode()
440
-
441
- with gr.Blocks(theme='bethecloud/storj_theme') as demo:
442
-
443
- gr.HTML(title)
444
-
445
- with gr.Row():
446
- with gr.Column(scale=2):
447
- with gr.Accordion("Basic Settings"):
448
- seed = gr.Slider(0, 30000, label='Seed', step=1, value=random.randint(0,30000))
449
- custom = gr.Textbox(label="Custom Input Prompt (optional)")
450
- subject = gr.Textbox(label="Subject (optional)")
451
-
452
- # Add the radio button for global option selection
453
- global_option = gr.Radio(
454
- ["Disabled", "Random", "No Figure Rand"],
455
- label="Set all options to:",
456
- value="Disabled"
457
- )
458
-
459
- with gr.Accordion("Artform and Photo Type", open=False):
460
- artform = gr.Dropdown(["disabled", "random"] + ARTFORM, label="Artform", value="disabled")
461
- photo_type = gr.Dropdown(["disabled", "random"] + PHOTO_TYPE, label="Photo Type", value="disabled")
462
-
463
- with gr.Accordion("Character Details", open=False):
464
- body_types = gr.Dropdown(["disabled", "random"] + BODY_TYPES, label="Body Types", value="disabled")
465
- default_tags = gr.Dropdown(["disabled", "random"] + DEFAULT_TAGS, label="Default Tags", value="disabled")
466
- roles = gr.Dropdown(["disabled", "random"] + ROLES, label="Roles", value="disabled")
467
- hairstyles = gr.Dropdown(["disabled", "random"] + HAIRSTYLES, label="Hairstyles", value="disabled")
468
- clothing = gr.Dropdown(["disabled", "random"] + CLOTHING, label="Clothing", value="disabled")
469
-
470
- with gr.Accordion("Scene Details", open=False):
471
- place = gr.Dropdown(["disabled", "random"] + PLACE, label="Place", value="disabled")
472
- lighting = gr.Dropdown(["disabled", "random"] + LIGHTING, label="Lighting", value="disabled")
473
- composition = gr.Dropdown(["disabled", "random"] + COMPOSITION, label="Composition", value="disabled")
474
- pose = gr.Dropdown(["disabled", "random"] + POSE, label="Pose", value="disabled")
475
- background = gr.Dropdown(["disabled", "random"] + BACKGROUND, label="Background", value="disabled")
476
-
477
- with gr.Accordion("Style and Artist", open=False):
478
- additional_details = gr.Dropdown(["disabled", "random"] + ADDITIONAL_DETAILS, label="Additional Details", value="disabled")
479
- photography_styles = gr.Dropdown(["disabled", "random"] + PHOTOGRAPHY_STYLES, label="Photography Styles", value="disabled")
480
- device = gr.Dropdown(["disabled", "random"] + DEVICE, label="Device", value="disabled")
481
- photographer = gr.Dropdown(["disabled", "random"] + PHOTOGRAPHER, label="Photographer", value="disabled")
482
- artist = gr.Dropdown(["disabled", "random"] + ARTIST, label="Artist", value="disabled")
483
- digital_artform = gr.Dropdown(["disabled", "random"] + DIGITAL_ARTFORM, label="Digital Artform", value="disabled")
484
-
485
- generate_button = gr.Button("Generate Prompt")
486
-
487
- with gr.Column(scale=2):
488
- with gr.Accordion("Image and Caption", open=False):
489
- input_image = gr.Image(label="Input Image (optional)")
490
- caption_output = gr.Textbox(label="Generated Caption", lines=3)
491
- create_caption_button = gr.Button("Create Caption")
492
- add_caption_button = gr.Button("Add Caption to Prompt")
493
-
494
- with gr.Accordion("Prompt Generation", open=True):
495
- output = gr.Textbox(label="Generated Prompt / Input Text", lines=4)
496
- t5xxl_output = gr.Textbox(label="T5XXL Output", visible=True)
497
- clip_l_output = gr.Textbox(label="CLIP L Output", visible=True)
498
- clip_g_output = gr.Textbox(label="CLIP G Output", visible=True)
499
-
500
- with gr.Column(scale=2):
501
- with gr.Accordion("Prompt Generation with LLM", open=False):
502
- model = gr.Dropdown(["Mixtral 8x7B", "Llama 3.1 70B", "Llama 3.1 8B"], label="Model", value="Llama 3.1 8B")
503
- happy_talk = gr.Checkbox(label="Happy Talk", value=True)
504
- compress = gr.Checkbox(label="Compress", value=True)
505
- compression_level = gr.Radio(["soft", "medium", "hard"], label="Compression Level", value="hard")
506
- poster = gr.Checkbox(label="Poster", value=False)
507
- custom_base_prompt = gr.Textbox(label="Custom Base Prompt", lines=5)
508
- generate_text_button = gr.Button("Generate Prompt with LLM")
509
- text_output = gr.Textbox(label="Generated Text", lines=10)
510
-
511
- def create_caption(image):
512
- if image is not None:
513
- return florence_caption(image)
514
- return ""
515
-
516
- create_caption_button.click(
517
- create_caption,
518
- inputs=[input_image],
519
- outputs=[caption_output]
520
- )
521
-
522
- generate_button.click(
523
- prompt_generator.generate_prompt,
524
- inputs=[seed, custom, subject, artform, photo_type, body_types, default_tags, roles, hairstyles,
525
- additional_details, photography_styles, device, photographer, artist, digital_artform,
526
- place, lighting, clothing, composition, pose, background, input_image],
527
- outputs=[output, gr.Number(visible=False), t5xxl_output, clip_l_output, clip_g_output]
528
- )
529
-
530
- add_caption_button.click(
531
- prompt_generator.add_caption_to_prompt,
532
- inputs=[output, caption_output],
533
- outputs=[output]
534
- )
535
-
536
- def generate_text_with_model(model, input_text, happy_talk, compress, compression_level, poster, custom_base_prompt):
537
- print(f"Generating text with model: {model}")
538
- output = groq_inference.generate(model, input_text, happy_talk, compress, compression_level, poster, custom_base_prompt)
539
- print("Generation completed.")
540
- return output
541
-
542
- generate_text_button.click(
543
- generate_text_with_model,
544
- inputs=[model, output, happy_talk, compress, compression_level, poster, custom_base_prompt],
545
- outputs=text_output
546
- )
547
-
548
- def update_all_options(choice):
549
- updates = {}
550
- if choice == "Disabled":
551
- for dropdown in [
552
- artform, photo_type, body_types, default_tags, roles, hairstyles, clothing,
553
- place, lighting, composition, pose, background, additional_details,
554
- photography_styles, device, photographer, artist, digital_artform
555
- ]:
556
- updates[dropdown] = gr.update(value="disabled")
557
- elif choice == "Random":
558
- for dropdown in [
559
- artform, photo_type, body_types, default_tags, roles, hairstyles, clothing,
560
- place, lighting, composition, pose, background, additional_details,
561
- photography_styles, device, photographer, artist, digital_artform
562
- ]:
563
- updates[dropdown] = gr.update(value="random")
564
- else: # No Figure Random
565
- for dropdown in [photo_type, body_types, default_tags, roles, hairstyles, clothing, pose, additional_details]:
566
- updates[dropdown] = gr.update(value="disabled")
567
- for dropdown in [artform, place, lighting, composition, background, photography_styles, device, photographer, artist, digital_artform]:
568
- updates[dropdown] = gr.update(value="random")
569
- return updates
570
-
571
- global_option.change(
572
- update_all_options,
573
- inputs=[global_option],
574
- outputs=[
575
- artform, photo_type, body_types, default_tags, roles, hairstyles, clothing,
576
- place, lighting, composition, pose, background, additional_details,
577
- photography_styles, device, photographer, artist, digital_artform
578
- ]
579
- )
580
-
581
- return demo
582
-
583
- if __name__ == "__main__":
584
- print("FLUX Prompt Generator Initialized! HAVE FUN :)")
585
- demo = create_interface()
586
- demo.launch()
587
-
 
1
+ import gradio as gr
2
+ import random
3
+ import json
4
+ import os
5
+ import re
6
+ from datetime import datetime
7
+ from huggingface_hub import InferenceClient
8
+ import subprocess
9
+ import torch
10
+ import devicetorch
11
+ from PIL import Image
12
+ from unittest.mock import patch
13
+ from transformers.dynamic_module_utils import get_imports
14
+ from transformers import AutoModelForCausalLM, AutoTokenizer, AutoProcessor
15
+ import random
16
+ import importlib.util
17
+ import sys
18
+ from groq import Groq
19
+ import time
20
+
21
+ #ADD YOUR OWN GROQ API KEY ON LINE 336
22
+
23
+ # Initialize Florence model
24
+ device = devicetorch.get(torch)
25
+
26
+ def fixed_get_imports(filename: str | os.PathLike) -> list[str]:
27
+ if not str(filename).endswith("modeling_florence2.py"):
28
+ return get_imports(filename)
29
+ imports = get_imports(filename)
30
+ if "flash_attn" in imports:
31
+ imports.remove("flash_attn")
32
+ return imports
33
+
34
+ with patch("transformers.dynamic_module_utils.get_imports", fixed_get_imports):
35
+ florence_model = AutoModelForCausalLM.from_pretrained(
36
+ 'microsoft/Florence-2-base',
37
+ attn_implementation="sdpa",
38
+ torch_dtype=torch.float16 if 'cuda' in str(device) else torch.float32,
39
+ trust_remote_code=True
40
+ ).to(device).eval()
41
+
42
+ florence_processor = AutoProcessor.from_pretrained('microsoft/Florence-2-base', trust_remote_code=True)
43
+
44
+
45
+
46
+ #device = "cuda" if torch.cuda.is_available() else "cpu"
47
+ #florence_model = AutoModelForCausalLM.from_pretrained('microsoft/Florence-2-base', trust_remote_code=True)#.to(device).eval()
48
+ #florence_processor = AutoProcessor.from_pretrained('microsoft/Florence-2-base', trust_remote_code=True)
49
+
50
+ # Florence caption function
51
+ def florence_caption(image):
52
+ if not isinstance(image, Image.Image):
53
+ image = Image.fromarray(image)
54
+
55
+ inputs = florence_processor(text="<MORE_DETAILED_CAPTION>", images=image, return_tensors="pt").to(device)
56
+ generated_ids = florence_model.generate(
57
+ input_ids=inputs["input_ids"],
58
+ pixel_values=inputs["pixel_values"],
59
+ max_new_tokens=1024,
60
+ early_stopping=False,
61
+ do_sample=False,
62
+ num_beams=3,
63
+ )
64
+ generated_text = florence_processor.batch_decode(generated_ids, skip_special_tokens=False)[0]
65
+ parsed_answer = florence_processor.post_process_generation(
66
+ generated_text,
67
+ task="<MORE_DETAILED_CAPTION>",
68
+ image_size=(image.width, image.height)
69
+ )
70
+ return parsed_answer["<MORE_DETAILED_CAPTION>"]
71
+
72
+ # Load JSON files
73
+ def load_json_file(file_name):
74
+ file_path = os.path.join("data", file_name)
75
+ with open(file_path, "r") as file:
76
+ return json.load(file)
77
+
78
+ ARTFORM = load_json_file("artform.json")
79
+ PHOTO_TYPE = load_json_file("photo_type.json")
80
+ BODY_TYPES = load_json_file("body_types.json")
81
+ DEFAULT_TAGS = load_json_file("default_tags.json")
82
+ ROLES = load_json_file("roles.json")
83
+ HAIRSTYLES = load_json_file("hairstyles.json")
84
+ ADDITIONAL_DETAILS = load_json_file("additional_details.json")
85
+ PHOTOGRAPHY_STYLES = load_json_file("photography_styles.json")
86
+ DEVICE = load_json_file("device.json")
87
+ PHOTOGRAPHER = load_json_file("photographer.json")
88
+ ARTIST = load_json_file("artist.json")
89
+ DIGITAL_ARTFORM = load_json_file("digital_artform.json")
90
+ PLACE = load_json_file("place.json")
91
+ LIGHTING = load_json_file("lighting.json")
92
+ CLOTHING = load_json_file("clothing.json")
93
+ COMPOSITION = load_json_file("composition.json")
94
+ POSE = load_json_file("pose.json")
95
+ BACKGROUND = load_json_file("background.json")
96
+
97
+ class PromptGenerator:
98
+ def __init__(self, seed=None):
99
+ self.rng = random.Random(seed)
100
+
101
+ def split_and_choose(self, input_str):
102
+ choices = [choice.strip() for choice in input_str.split(",")]
103
+ return self.rng.choices(choices, k=1)[0]
104
+
105
+ def get_choice(self, input_str, default_choices):
106
+ if input_str.lower() == "disabled":
107
+ return ""
108
+ elif "," in input_str:
109
+ return self.split_and_choose(input_str)
110
+ elif input_str.lower() == "random":
111
+ return self.rng.choices(default_choices, k=1)[0]
112
+ else:
113
+ return input_str
114
+
115
+ def clean_consecutive_commas(self, input_string):
116
+ cleaned_string = re.sub(r',\s*,', ',', input_string)
117
+ return cleaned_string
118
+
119
+ def process_string(self, replaced, seed):
120
+ replaced = re.sub(r'\s*,\s*', ',', replaced)
121
+ replaced = re.sub(r',+', ',', replaced)
122
+ original = replaced
123
+
124
+ first_break_clipl_index = replaced.find("BREAK_CLIPL")
125
+ second_break_clipl_index = replaced.find("BREAK_CLIPL", first_break_clipl_index + len("BREAK_CLIPL"))
126
+
127
+ if first_break_clipl_index != -1 and second_break_clipl_index != -1:
128
+ clip_content_l = replaced[first_break_clipl_index + len("BREAK_CLIPL"):second_break_clipl_index]
129
+ replaced = replaced[:first_break_clipl_index].strip(", ") + replaced[second_break_clipl_index + len("BREAK_CLIPL"):].strip(", ")
130
+ clip_l = clip_content_l
131
+ else:
132
+ clip_l = ""
133
+
134
+ first_break_clipg_index = replaced.find("BREAK_CLIPG")
135
+ second_break_clipg_index = replaced.find("BREAK_CLIPG", first_break_clipg_index + len("BREAK_CLIPG"))
136
+
137
+ if first_break_clipg_index != -1 and second_break_clipg_index != -1:
138
+ clip_content_g = replaced[first_break_clipg_index + len("BREAK_CLIPG"):second_break_clipg_index]
139
+ replaced = replaced[:first_break_clipg_index].strip(", ") + replaced[second_break_clipg_index + len("BREAK_CLIPG"):].strip(", ")
140
+ clip_g = clip_content_g
141
+ else:
142
+ clip_g = ""
143
+
144
+ t5xxl = replaced
145
+
146
+ original = original.replace("BREAK_CLIPL", "").replace("BREAK_CLIPG", "")
147
+ original = re.sub(r'\s*,\s*', ',', original)
148
+ original = re.sub(r',+', ',', original)
149
+ clip_l = re.sub(r'\s*,\s*', ',', clip_l)
150
+ clip_l = re.sub(r',+', ',', clip_l)
151
+ clip_g = re.sub(r'\s*,\s*', ',', clip_g)
152
+ clip_g = re.sub(r',+', ',', clip_g)
153
+ if clip_l.startswith(","):
154
+ clip_l = clip_l[1:]
155
+ if clip_g.startswith(","):
156
+ clip_g = clip_g[1:]
157
+ if original.startswith(","):
158
+ original = original[1:]
159
+ if t5xxl.startswith(","):
160
+ t5xxl = t5xxl[1:]
161
+
162
+ return original, seed, t5xxl, clip_l, clip_g
163
+
164
+ def generate_prompt(self, seed, custom, subject, artform, photo_type, body_types, default_tags, roles, hairstyles,
165
+ additional_details, photography_styles, device, photographer, artist, digital_artform,
166
+ place, lighting, clothing, composition, pose, background, input_image, *args):
167
+ print(f"Number of arguments received: {len(args)}")
168
+ for i, arg in enumerate(args):
169
+ print(f"Argument {i}: {arg}")
170
+ kwargs = locals()
171
+ del kwargs['self']
172
+
173
+ seed = kwargs.get("seed", 0)
174
+ if seed is not None:
175
+ self.rng = random.Random(seed)
176
+ components = []
177
+ custom = kwargs.get("custom", "")
178
+ if custom:
179
+ components.append(custom)
180
+ is_photographer = kwargs.get("artform", "").lower() == "photography" or (
181
+ kwargs.get("artform", "").lower() == "random"
182
+ and self.rng.choice([True, False])
183
+ )
184
+
185
+ subject = kwargs.get("subject", "")
186
+
187
+ if is_photographer:
188
+ selected_photo_style = self.get_choice(kwargs.get("photography_styles", ""), PHOTOGRAPHY_STYLES)
189
+ if not selected_photo_style:
190
+ selected_photo_style = "photography"
191
+ components.append(selected_photo_style)
192
+ if kwargs.get("photography_style", "") != "disabled" and kwargs.get("default_tags", "") != "disabled" or subject != "":
193
+ components.append(" of")
194
+
195
+ default_tags = kwargs.get("default_tags", "random")
196
+ body_type = kwargs.get("body_types", "")
197
+ if not subject:
198
+ if default_tags == "random":
199
+ if body_type != "disabled" and body_type != "random":
200
+ selected_subject = self.get_choice(kwargs.get("default_tags", ""), DEFAULT_TAGS).replace("a ", "").replace("an ", "")
201
+ components.append("a ")
202
+ components.append(body_type)
203
+ components.append(selected_subject)
204
+ elif body_type == "disabled":
205
+ selected_subject = self.get_choice(kwargs.get("default_tags", ""), DEFAULT_TAGS)
206
+ components.append(selected_subject)
207
+ else:
208
+ body_type = self.get_choice(body_type, BODY_TYPES)
209
+ components.append("a ")
210
+ components.append(body_type)
211
+ selected_subject = self.get_choice(kwargs.get("default_tags", ""), DEFAULT_TAGS).replace("a ", "").replace("an ", "")
212
+ components.append(selected_subject)
213
+ elif default_tags == "disabled":
214
+ pass
215
+ else:
216
+ components.append(default_tags)
217
+ else:
218
+ if body_type != "disabled" and body_type != "random":
219
+ components.append("a ")
220
+ components.append(body_type)
221
+ elif body_type == "disabled":
222
+ pass
223
+ else:
224
+ body_type = self.get_choice(body_type, BODY_TYPES)
225
+ components.append("a ")
226
+ components.append(body_type)
227
+ components.append(subject)
228
+
229
+ params = [
230
+ ("roles", ROLES),
231
+ ("hairstyles", HAIRSTYLES),
232
+ ("additional_details", ADDITIONAL_DETAILS),
233
+ ]
234
+ for param in params:
235
+ components.append(self.get_choice(kwargs.get(param[0], ""), param[1]))
236
+ for i in reversed(range(len(components))):
237
+ if components[i] in PLACE:
238
+ components[i] += ","
239
+ break
240
+ if kwargs.get("clothing", "") != "disabled" and kwargs.get("clothing", "") != "random":
241
+ components.append(", dressed in ")
242
+ clothing = kwargs.get("clothing", "")
243
+ components.append(clothing)
244
+ elif kwargs.get("clothing", "") == "random":
245
+ components.append(", dressed in ")
246
+ clothing = self.get_choice(kwargs.get("clothing", ""), CLOTHING)
247
+ components.append(clothing)
248
+
249
+ if kwargs.get("composition", "") != "disabled" and kwargs.get("composition", "") != "random":
250
+ components.append(",")
251
+ composition = kwargs.get("composition", "")
252
+ components.append(composition)
253
+ elif kwargs.get("composition", "") == "random":
254
+ components.append(",")
255
+ composition = self.get_choice(kwargs.get("composition", ""), COMPOSITION)
256
+ components.append(composition)
257
+
258
+ if kwargs.get("pose", "") != "disabled" and kwargs.get("pose", "") != "random":
259
+ components.append(",")
260
+ pose = kwargs.get("pose", "")
261
+ components.append(pose)
262
+ elif kwargs.get("pose", "") == "random":
263
+ components.append(",")
264
+ pose = self.get_choice(kwargs.get("pose", ""), POSE)
265
+ components.append(pose)
266
+ components.append("BREAK_CLIPG")
267
+ if kwargs.get("background", "") != "disabled" and kwargs.get("background", "") != "random":
268
+ components.append(",")
269
+ background = kwargs.get("background", "")
270
+ components.append(background)
271
+ elif kwargs.get("background", "") == "random":
272
+ components.append(",")
273
+ background = self.get_choice(kwargs.get("background", ""), BACKGROUND)
274
+ components.append(background)
275
+
276
+ if kwargs.get("place", "") != "disabled" and kwargs.get("place", "") != "random":
277
+ components.append(",")
278
+ place = kwargs.get("place", "")
279
+ components.append(place)
280
+ elif kwargs.get("place", "") == "random":
281
+ components.append(",")
282
+ place = self.get_choice(kwargs.get("place", ""), PLACE)
283
+ components.append(place + ",")
284
+
285
+ lighting = kwargs.get("lighting", "").lower()
286
+ if lighting == "random":
287
+ selected_lighting = ", ".join(self.rng.sample(LIGHTING, self.rng.randint(2, 5)))
288
+ components.append(",")
289
+ components.append(selected_lighting)
290
+ elif lighting == "disabled":
291
+ pass
292
+ else:
293
+ components.append(", ")
294
+ components.append(lighting)
295
+ components.append("BREAK_CLIPG")
296
+ components.append("BREAK_CLIPL")
297
+ if is_photographer:
298
+ if kwargs.get("photo_type", "") != "disabled":
299
+ photo_type_choice = self.get_choice(kwargs.get("photo_type", ""), PHOTO_TYPE)
300
+ if photo_type_choice and photo_type_choice != "random" and photo_type_choice != "disabled":
301
+ random_value = round(self.rng.uniform(1.1, 1.5), 1)
302
+ components.append(f", ({photo_type_choice}:{random_value}), ")
303
+
304
+ params = [
305
+ ("device", DEVICE),
306
+ ("photographer", PHOTOGRAPHER),
307
+ ]
308
+ components.extend([self.get_choice(kwargs.get(param[0], ""), param[1]) for param in params])
309
+ if kwargs.get("device", "") != "disabled":
310
+ components[-2] = f", shot on {components[-2]}"
311
+ if kwargs.get("photographer", "") != "disabled":
312
+ components[-1] = f", photo by {components[-1]}"
313
+ else:
314
+ digital_artform_choice = self.get_choice(kwargs.get("digital_artform", ""), DIGITAL_ARTFORM)
315
+ if digital_artform_choice:
316
+ components.append(f"{digital_artform_choice}")
317
+ if kwargs.get("artist", "") != "disabled":
318
+ components.append(f"by {self.get_choice(kwargs.get('artist', ''), ARTIST)}")
319
+ components.append("BREAK_CLIPL")
320
+
321
+ prompt = " ".join(components)
322
+ prompt = re.sub(" +", " ", prompt)
323
+ replaced = prompt.replace("of as", "of")
324
+ replaced = self.clean_consecutive_commas(replaced)
325
+
326
+ return self.process_string(replaced, seed)
327
+
328
+ def add_caption_to_prompt(self, prompt, caption):
329
+ if caption:
330
+ return f"{prompt}, {caption}"
331
+ return prompt
332
+
333
+ class GroqInferenceNode:
334
+ def __init__(self):
335
+ #ADD YOUR OWN GROQ API KEY HERE
336
+ self.client = Groq(api_key="YOUR-API-KEY")
337
+ self.models = {
338
+ "Llama 3.1 70B": "llama-3.1-70b-versatile",
339
+ "Llama 3.1 8B": "llama-3.1-8b-instant"
340
+ }
341
+ self.prompts_dir = "./prompts"
342
+ os.makedirs(self.prompts_dir, exist_ok=True)
343
+
344
+ def save_prompt(self, prompt):
345
+ filename_text = "groq_" + prompt.split(',')[0].strip()
346
+ filename_text = re.sub(r'[^\w\-_\. ]', '_', filename_text)
347
+ filename_text = filename_text[:30]
348
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
349
+ base_filename = f"{filename_text}_{timestamp}.txt"
350
+ filename = os.path.join(self.prompts_dir, base_filename)
351
+
352
+ with open(filename, "w") as file:
353
+ file.write(prompt)
354
+
355
+ print(f"Prompt saved to {filename}")
356
+
357
+ def generate(self, model, input_text, happy_talk, compress, compression_level, poster, custom_base_prompt=""):
358
+ try:
359
+ model_id = self.models.get(model, "llama-3.1-8b-instant")
360
+
361
+ 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."""
362
+
363
+ 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."""
364
+
365
+ poster_prompt = """Analyze the provided description and extract key information to create a movie poster style description. Format the output as follows:
366
+ Title: A catchy, intriguing title that captures the essence of the scene, place the title in "".
367
+ Main character: Give a description of the main character.
368
+ Background: Describe the background in detail.
369
+ Supporting characters: Describe the supporting characters
370
+ Branding type: Describe the branding type
371
+ Tagline: Include a tagline that captures the essence of the movie.
372
+ Visual style: Ensure that the visual style fits the branding type and tagline.
373
+ You are allowed to make up film and branding names, and do them like 80's, 90's or modern movie posters."""
374
+
375
+ if poster:
376
+ base_prompt = poster_prompt
377
+ elif custom_base_prompt.strip():
378
+ base_prompt = custom_base_prompt
379
+ else:
380
+ base_prompt = default_happy_prompt if happy_talk else default_simple_prompt
381
+
382
+ if compress and not poster:
383
+ compression_chars = {
384
+ "soft": 600 if happy_talk else 300,
385
+ "medium": 400 if happy_talk else 200,
386
+ "hard": 200 if happy_talk else 100
387
+ }
388
+ char_limit = compression_chars[compression_level]
389
+ base_prompt += f" Compress the output to be concise while retaining key visual details. MAX OUTPUT SIZE no more than {char_limit} characters."
390
+
391
+ messages = [
392
+ {"role": "system", "content": "You are a helpful assistant. Try your best to give best response possible to user."},
393
+ {"role": "user", "content": f"{base_prompt}\nDescription: {input_text}"}
394
+ ]
395
+
396
+ print(f"Starting generation with {model_id}...")
397
+ start_time = time.time()
398
+
399
+ chat_completion = self.client.chat.completions.create(
400
+ messages=messages,
401
+ model=model_id,
402
+ max_tokens=4000,
403
+ temperature=0.7,
404
+ top_p=0.95
405
+ )
406
+
407
+ end_time = time.time()
408
+ print(f"Generation completed in {end_time - start_time:.2f} seconds")
409
+
410
+ output = chat_completion.choices[0].message.content
411
+
412
+ # Clean up the output
413
+ if ": " in output:
414
+ output = output.split(": ", 1)[1].strip()
415
+ elif output.lower().startswith("here"):
416
+ sentences = output.split(". ")
417
+ if len(sentences) > 1:
418
+ output = ". ".join(sentences[1:]).strip()
419
+
420
+ return output
421
+
422
+ except Exception as e:
423
+ print(f"An error occurred: {e}")
424
+ return f"Error occurred while processing the request: {str(e)}"
425
+
426
+ title = """<h1 align="center">FLUX Prompt Generator</h1>
427
+ <p><center>
428
+ <p align="center">Flux Prompt generator modified by <a href="https://www.patreon.com/aitrepreneur" target="_blank">[Aitrepreneur]</a>.</p>
429
+ <a href="https://x.com/gokayfem" target="_blank">[X gokaygokay]</a>
430
+ <a href="https://github.com/gokayfem" target="_blank">[Github gokayfem]</a>
431
+ <a href="https://github.com/dagthomas/comfyui_dagthomas" target="_blank">[comfyui_dagthomas]</a>
432
+ <p align="center">Create long prompts from images or simple words. Enhance your short prompts with prompt enhancer.</p>
433
+ </center></p>
434
+ """
435
+
436
+ def create_interface():
437
+ prompt_generator = PromptGenerator()
438
+ groq_inference = GroqInferenceNode()
439
+
440
+ with gr.Blocks(theme='bethecloud/storj_theme') as demo:
441
+
442
+ gr.HTML(title)
443
+
444
+ with gr.Row():
445
+ with gr.Column(scale=2):
446
+ with gr.Accordion("Basic Settings"):
447
+ seed = gr.Slider(0, 30000, label='Seed', step=1, value=random.randint(0,30000))
448
+ custom = gr.Textbox(label="Custom Input Prompt (optional)")
449
+ subject = gr.Textbox(label="Subject (optional)")
450
+
451
+ # Add the radio button for global option selection
452
+ global_option = gr.Radio(
453
+ ["Disabled", "Random", "No Figure Rand"],
454
+ label="Set all options to:",
455
+ value="Disabled"
456
+ )
457
+
458
+ with gr.Accordion("Artform and Photo Type", open=False):
459
+ artform = gr.Dropdown(["disabled", "random"] + ARTFORM, label="Artform", value="disabled")
460
+ photo_type = gr.Dropdown(["disabled", "random"] + PHOTO_TYPE, label="Photo Type", value="disabled")
461
+
462
+ with gr.Accordion("Character Details", open=False):
463
+ body_types = gr.Dropdown(["disabled", "random"] + BODY_TYPES, label="Body Types", value="disabled")
464
+ default_tags = gr.Dropdown(["disabled", "random"] + DEFAULT_TAGS, label="Default Tags", value="disabled")
465
+ roles = gr.Dropdown(["disabled", "random"] + ROLES, label="Roles", value="disabled")
466
+ hairstyles = gr.Dropdown(["disabled", "random"] + HAIRSTYLES, label="Hairstyles", value="disabled")
467
+ clothing = gr.Dropdown(["disabled", "random"] + CLOTHING, label="Clothing", value="disabled")
468
+
469
+ with gr.Accordion("Scene Details", open=False):
470
+ place = gr.Dropdown(["disabled", "random"] + PLACE, label="Place", value="disabled")
471
+ lighting = gr.Dropdown(["disabled", "random"] + LIGHTING, label="Lighting", value="disabled")
472
+ composition = gr.Dropdown(["disabled", "random"] + COMPOSITION, label="Composition", value="disabled")
473
+ pose = gr.Dropdown(["disabled", "random"] + POSE, label="Pose", value="disabled")
474
+ background = gr.Dropdown(["disabled", "random"] + BACKGROUND, label="Background", value="disabled")
475
+
476
+ with gr.Accordion("Style and Artist", open=False):
477
+ additional_details = gr.Dropdown(["disabled", "random"] + ADDITIONAL_DETAILS, label="Additional Details", value="disabled")
478
+ photography_styles = gr.Dropdown(["disabled", "random"] + PHOTOGRAPHY_STYLES, label="Photography Styles", value="disabled")
479
+ device = gr.Dropdown(["disabled", "random"] + DEVICE, label="Device", value="disabled")
480
+ photographer = gr.Dropdown(["disabled", "random"] + PHOTOGRAPHER, label="Photographer", value="disabled")
481
+ artist = gr.Dropdown(["disabled", "random"] + ARTIST, label="Artist", value="disabled")
482
+ digital_artform = gr.Dropdown(["disabled", "random"] + DIGITAL_ARTFORM, label="Digital Artform", value="disabled")
483
+
484
+ generate_button = gr.Button("Generate Prompt")
485
+
486
+ with gr.Column(scale=2):
487
+ with gr.Accordion("Image and Caption", open=False):
488
+ input_image = gr.Image(label="Input Image (optional)")
489
+ caption_output = gr.Textbox(label="Generated Caption", lines=3)
490
+ create_caption_button = gr.Button("Create Caption")
491
+ add_caption_button = gr.Button("Add Caption to Prompt")
492
+
493
+ with gr.Accordion("Prompt Generation", open=True):
494
+ output = gr.Textbox(label="Generated Prompt / Input Text", lines=4)
495
+ t5xxl_output = gr.Textbox(label="T5XXL Output", visible=True)
496
+ clip_l_output = gr.Textbox(label="CLIP L Output", visible=True)
497
+ clip_g_output = gr.Textbox(label="CLIP G Output", visible=True)
498
+
499
+ with gr.Column(scale=2):
500
+ with gr.Accordion("Prompt Generation with LLM", open=False):
501
+ model = gr.Dropdown(["Llama 3.1 70B", "Llama 3.1 8B"], label="Model", value="Llama 3.1 8B")
502
+ happy_talk = gr.Checkbox(label="Happy Talk", value=True)
503
+ compress = gr.Checkbox(label="Compress", value=True)
504
+ compression_level = gr.Radio(["soft", "medium", "hard"], label="Compression Level", value="hard")
505
+ poster = gr.Checkbox(label="Poster", value=False)
506
+ custom_base_prompt = gr.Textbox(label="Custom Base Prompt", lines=5)
507
+ generate_text_button = gr.Button("Generate Prompt with LLM")
508
+ text_output = gr.Textbox(label="Generated Text", lines=10)
509
+
510
+ def create_caption(image):
511
+ if image is not None:
512
+ return florence_caption(image)
513
+ return ""
514
+
515
+ create_caption_button.click(
516
+ create_caption,
517
+ inputs=[input_image],
518
+ outputs=[caption_output]
519
+ )
520
+
521
+ generate_button.click(
522
+ prompt_generator.generate_prompt,
523
+ inputs=[seed, custom, subject, artform, photo_type, body_types, default_tags, roles, hairstyles,
524
+ additional_details, photography_styles, device, photographer, artist, digital_artform,
525
+ place, lighting, clothing, composition, pose, background, input_image],
526
+ outputs=[output, gr.Number(visible=False), t5xxl_output, clip_l_output, clip_g_output]
527
+ )
528
+
529
+ add_caption_button.click(
530
+ prompt_generator.add_caption_to_prompt,
531
+ inputs=[output, caption_output],
532
+ outputs=[output]
533
+ )
534
+
535
+ def generate_text_with_model(model, input_text, happy_talk, compress, compression_level, poster, custom_base_prompt):
536
+ print(f"Generating text with model: {model}")
537
+ output = groq_inference.generate(model, input_text, happy_talk, compress, compression_level, poster, custom_base_prompt)
538
+ print("Generation completed.")
539
+ return output
540
+
541
+ generate_text_button.click(
542
+ generate_text_with_model,
543
+ inputs=[model, output, happy_talk, compress, compression_level, poster, custom_base_prompt],
544
+ outputs=text_output
545
+ )
546
+
547
+ def update_all_options(choice):
548
+ updates = {}
549
+ if choice == "Disabled":
550
+ for dropdown in [
551
+ artform, photo_type, body_types, default_tags, roles, hairstyles, clothing,
552
+ place, lighting, composition, pose, background, additional_details,
553
+ photography_styles, device, photographer, artist, digital_artform
554
+ ]:
555
+ updates[dropdown] = gr.update(value="disabled")
556
+ elif choice == "Random":
557
+ for dropdown in [
558
+ artform, photo_type, body_types, default_tags, roles, hairstyles, clothing,
559
+ place, lighting, composition, pose, background, additional_details,
560
+ photography_styles, device, photographer, artist, digital_artform
561
+ ]:
562
+ updates[dropdown] = gr.update(value="random")
563
+ else: # No Figure Random
564
+ for dropdown in [photo_type, body_types, default_tags, roles, hairstyles, clothing, pose, additional_details]:
565
+ updates[dropdown] = gr.update(value="disabled")
566
+ for dropdown in [artform, place, lighting, composition, background, photography_styles, device, photographer, artist, digital_artform]:
567
+ updates[dropdown] = gr.update(value="random")
568
+ return updates
569
+
570
+ global_option.change(
571
+ update_all_options,
572
+ inputs=[global_option],
573
+ outputs=[
574
+ artform, photo_type, body_types, default_tags, roles, hairstyles, clothing,
575
+ place, lighting, composition, pose, background, additional_details,
576
+ photography_styles, device, photographer, artist, digital_artform
577
+ ]
578
+ )
579
+
580
+ return demo
581
+
582
+ if __name__ == "__main__":
583
+ print("FLUX Prompt Generator Initialized! HAVE FUN :)")
584
+ demo = create_interface()
585
+ demo.launch()
586
+