seawolf2357 commited on
Commit
28cc9a7
Β·
verified Β·
1 Parent(s): ed9c024

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +187 -264
app.py CHANGED
@@ -1,112 +1,138 @@
 
 
 
1
  model_repo_id = "Freepik/F-Lite-Texture"
2
- model_name = "F Lite Texture"
3
 
4
- from dotenv import load_dotenv
5
  import gradio as gr
6
- import numpy as np
7
- import random
8
- import os
9
- import logging
10
- import google.generativeai as genai
11
-
12
- import spaces
13
- import torch
14
  from f_lite import FLitePipeline
 
15
 
16
- # Trick required because it is not a native diffusers model
 
 
17
  from diffusers.pipelines.pipeline_loading_utils import LOADABLE_CLASSES, ALL_IMPORTABLE_CLASSES
 
 
18
 
19
- from f_lite.pipeline import APGConfig
20
- LOADABLE_CLASSES["f_lite"] = LOADABLE_CLASSES["f_lite.model"] = {"DiT": ["save_pretrained", "from_pretrained"]}
21
- ALL_IMPORTABLE_CLASSES["DiT"] = ["save_pretrained", "from_pretrained"]
22
-
23
  load_dotenv()
 
24
 
25
- # Initialize Gemini API if API key is available
 
26
  if os.getenv("GEMINI_API_KEY"):
27
- gemini_available = True
28
  genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
 
29
  else:
30
- gemini_available = False
31
- logging.warning("GEMINI_API_KEY not found in environment variables. Prompt enrichment will not work.")
32
 
33
- device = "cuda" if torch.cuda.is_available() else "cpu"
34
-
35
- if torch.cuda.is_available():
36
- torch_dtype = torch.bfloat16
37
- else:
38
- torch_dtype = torch.float32
39
 
40
  pipe = FLitePipeline.from_pretrained(model_repo_id, torch_dtype=torch_dtype)
41
  pipe.to(device)
42
- pipe.vae.enable_slicing()
43
- pipe.vae.enable_tiling()
44
 
45
- MAX_SEED = np.iinfo(np.int32).max
46
- MAX_IMAGE_SIZE = 1600
 
 
 
47
 
48
  RESOLUTIONS = {
49
- "horizontal": [
50
- {"width": 1344, "height": 896, "label": "1344Γ—896"},
51
- {"width": 1152, "height": 768, "label": "1152Γ—768"},
52
- {"width": 960, "height": 640, "label": "960Γ—640"},
53
- {"width": 1600, "height": 896, "label": "1600Γ—896"}
54
- ],
55
- "vertical": [
56
- {"width": 896, "height": 1344, "label": "896Γ—1344"},
57
- {"width": 768, "height": 1152, "label": "768Γ—1152"},
58
- {"width": 640, "height": 960, "label": "640Γ—960"},
59
- {"width": 896, "height": 1600, "label": "896Γ—1600"}
60
- ],
61
- "square": [
62
- {"width": 1216, "height": 1216, "label": "1216Γ—1216"},
63
- {"width": 1024, "height": 1024, "label": "1024Γ—1024"}
64
- ]
65
  }
66
-
67
  DEFAULT_RESOLUTION = {"width": 1024, "height": 1024, "label": "1024Γ—1024"}
68
 
 
 
 
69
  resolution_options = []
70
- for category, resolutions in RESOLUTIONS.items():
71
- resolution_options.append([f"{category.capitalize()}", None]) # μΉ΄ν…Œκ³ λ¦¬ ν—€λ”μš©
72
- for res in resolutions:
73
- resolution_options.append([f" {res['label']}", f"{category}:{res['width']}:{res['height']}"])
74
-
75
- def enrich_prompt_with_gemini(prompt, max_tokens=1024):
 
 
 
 
76
  try:
77
- if not os.getenv("GEMINI_API_KEY"):
78
- return None, "GEMINI_API_KEY not found in environment variables."
79
-
80
- model = genai.GenerativeModel('gemini-1.5-flash')
81
- enrichment_prompt = f"""
82
- You are a prompt enhancer for image generation.
83
- Take the following basic prompt and make it longer, very descriptive, and detailed.
84
- Write the description in a paragraph, avoiding bullet points.
85
-
86
- Original prompt: {prompt}
87
-
88
- Enhanced prompt:
89
- """
90
- response = model.generate_content(enrichment_prompt, generation_config={
91
- "max_output_tokens": max_tokens,
92
- "temperature": 1,
93
- })
94
- enriched_prompt = response.text.strip()
95
- return enriched_prompt, None
96
  except Exception as e:
97
- error_message = f"Error enriching prompt: {str(e)}"
98
- logging.error(error_message)
99
- return None, error_message
100
-
101
- def update_resolution(resolution_value):
102
- if not resolution_value:
 
 
103
  return DEFAULT_RESOLUTION["width"], DEFAULT_RESOLUTION["height"]
104
  try:
105
- category, width, height = resolution_value.split(":")
106
- return int(width), int(height)
107
- except:
108
  return DEFAULT_RESOLUTION["width"], DEFAULT_RESOLUTION["height"]
109
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
  @spaces.GPU(duration=120)
111
  def infer(
112
  prompt,
@@ -121,15 +147,14 @@ def infer(
121
  enable_apg,
122
  progress=gr.Progress(track_tqdm=True),
123
  ):
124
- enriched_prompt_str = None
125
- error_message_str = None
126
  generation_prompt = prompt
127
-
 
128
  if use_prompt_enrichment and gemini_available:
129
- enriched_prompt_str, error_message_str = enrich_prompt_with_gemini(prompt)
130
- if enriched_prompt_str:
131
- generation_prompt = enriched_prompt_str
132
-
133
  if randomize_seed:
134
  seed = random.randint(0, MAX_SEED)
135
 
@@ -140,224 +165,122 @@ def infer(
140
  negative_prompt=negative_prompt,
141
  guidance_scale=guidance_scale,
142
  num_inference_steps=num_inference_steps,
143
- width=width,
144
- height=height,
145
  generator=generator,
146
- apg_config=APGConfig(enabled=enable_apg)
147
  ).images[0]
148
-
149
- enriched_prompt_display_update = gr.update(visible=False)
150
- enriched_prompt_text_update = gr.update(value="")
151
- enrichment_error_update = gr.update(visible=False, value="")
152
 
153
- if enriched_prompt_str:
154
- enriched_prompt_display_update = gr.update(visible=True)
155
- enriched_prompt_text_update = gr.update(value=enriched_prompt_str)
156
- elif error_message_str:
157
- enriched_prompt_display_update = gr.update(visible=True)
158
- enrichment_error_update = gr.update(visible=True, value=error_message_str)
159
 
160
- return image, seed, enriched_prompt_display_update, enriched_prompt_text_update, enrichment_error_update
161
-
162
- examples = [
163
- [
164
- "An ultra-detailed macro photograph of a dew-covered rainbow beetle perched on a spiralling fern unfurling at dawn, back-lit by golden sunrise, bokeh background, 200-mm lens, f/2.8, vivid colors, cinematic lighting",
165
- None
166
- ],
167
- [
168
- "A retro-futuristic cityscape at night inspired by Syd Mead: neon-drenched streets reflect glistening rain, flying cars leave light-trail arcs between towering holographic billboards, 35 mm film grain, wide-angle perspective",
169
- None
170
- ],
171
- [
172
- "An elegant 18th-century ballroom rendered in photorealistic 8K, crystal chandeliers scattering prismatic light across polished marble floors, dancers in flowing silk gowns twirl mid-motion, captured like a long-exposure still",
173
- None
174
- ],
175
- [
176
- "A serene Japanese onsen nestled in a snowy mountain valley, steam rising into crisp twilight air, red lanterns glowing softly, snow-laden pine branches frame the scene, shot on medium-format analog with natural film tones",
177
- None
178
- ],
179
- [
180
- "Hyper-real illustration of an astronaut in a translucent spacesuit tending a floating bonsai inside a zero-g greenhouse aboard an orbital station, earthrise through panoramic windows, bioluminescent plants provide ambient teal light",
181
- None
182
- ],
183
- [
184
- "A majestic white Arabian horse galloping across a shallow mirror lake at sunset, water droplets frozen mid-air, warm rim light outlining powerful muscles, captured with a 1/4000 s shutter and sweeping motion blur background",
185
- None
186
- ],
187
- [
188
- "An ancient library carved inside a giant redwood tree, spiral staircases of polished root wood, glowing fireflies as reading lamps, shafts of emerald light pierce stained-leaf windows, ultra-detailed fantasy matte-painting",
189
- None
190
- ],
191
- [
192
- "A haute-couture fashion portrait: model wearing a dress made entirely of iridescent butterfly wings, dramatic chiaroscuro lighting, deep-blue velvet backdrop, captured on Hasselblad with razor-sharp focus on eyes, 120 MP clarity",
193
- None
194
- ],
195
- [
196
- "Cyberpunk samurai duo standing beneath a torrential neon rainstorm, reflective katana blades crackling with violet energy, holographic kanji glyphs drifting in air, cinematic anamorphic lens flares, dark gritty atmosphere",
197
- None
198
- ],
199
- [
200
- "A whimsical steampunk airship festival above a Victorian harbor: brass dirigibles adorned with floral patterns, fireworks burst into cog-shaped sparks, golden hour light bathes billowing clouds, painterly style reminiscent of Hayao Miyazaki",
201
- None
202
- ],
203
- ]
204
 
 
205
 
 
 
 
206
  css = """
207
- #col-container {
208
- margin: 0 auto;
209
- max-width: 1024px;
210
- }
211
- .prompt-row > .gr-form {
212
- gap: 0.5rem !important;
213
- align-items: center;
214
- }
215
  """
216
 
217
  with gr.Blocks(css=css, theme="ParityError/Interstellar") as demo:
218
  with gr.Column(elem_id="col-container"):
219
- gr.Markdown(f" # {model_name} Text-to-Image Demo")
220
-
 
221
  with gr.Row(elem_classes="prompt-row"):
222
- prompt = gr.Text(
223
- label="Prompt",
224
- show_label=False,
225
- max_lines=1,
226
- placeholder="Enter your prompt",
227
- container=False,
228
- scale=6
229
  )
230
- # 1) Enrich κΈ°λ³Έκ°’ True / ν‘œμ‹œ μ•ˆ 함(visible=False)
231
  use_prompt_enrichment = gr.Checkbox(
232
- label="Enrich",
233
- value=True, # default True
234
- visible=False # Hide from UI
235
  )
236
  run_button = gr.Button("Run", scale=1, variant="primary", min_width=100)
237
-
238
- result = gr.Image(label="Result", show_label=False)
239
-
240
- enriched_prompt_display = gr.Accordion("Enriched Prompt", open=False, visible=False)
241
- with enriched_prompt_display:
242
- enriched_prompt_text = gr.Textbox(
243
- label="Enriched Prompt",
244
- interactive=False,
245
- lines=8
246
- )
247
- enrichment_error = gr.Textbox(
248
- label="Error",
249
- visible=False,
250
- interactive=False,
251
- )
252
-
253
  with gr.Accordion("Advanced Settings", open=False):
254
  negative_prompt = gr.Text(
255
- label="Negative prompt",
256
- max_lines=1,
257
- placeholder="Enter a negative prompt",
258
- visible=True,
259
  )
260
-
261
- with gr.Tabs() as resolution_tabs:
262
  with gr.TabItem("Preset Resolutions"):
263
- resolution_dropdown = gr.Dropdown(
264
  label="Resolution",
265
  choices=resolution_options,
266
- # 2) λ””ν΄νŠΈλ‘œ 1600x896(μˆ˜ν‰ μ΅œλŒ€ 크기)
267
- value="horizontal:1600:896",
268
  type="value"
269
  )
270
-
271
  with gr.TabItem("Custom Resolution"):
272
  with gr.Row():
273
- width = gr.Slider(
274
- label="Width",
275
- minimum=256,
276
- maximum=MAX_IMAGE_SIZE,
277
- step=32,
278
- # set default to 1600
279
- value=1600,
280
  )
281
- height = gr.Slider(
282
- label="Height",
283
- minimum=256,
284
- maximum=MAX_IMAGE_SIZE,
285
- step=32,
286
- # set default to 896
287
- value=896,
288
  )
289
 
290
- seed = gr.Slider(
291
- label="Seed",
292
- minimum=0,
293
- maximum=MAX_SEED,
294
- step=1,
295
- value=42,
296
- )
297
-
298
- randomize_seed = gr.Checkbox(label="Randomize seed", value=False)
299
 
300
  with gr.Row():
301
- guidance_scale = gr.Slider(
302
- label="Guidance scale",
303
- minimum=0.0,
304
- maximum=15.0,
305
- step=0.1,
306
- value=6, # Keep default
307
- )
308
- enable_apg = gr.Checkbox(
309
- label="Enable APG",
310
- value=True,
311
- )
312
-
313
- # 3) num_inference_stepsλ₯Ό 50으둜 (μ΅œλŒ€κ°’)
314
- num_inference_steps = gr.Slider(
315
- label="Number of inference steps",
316
- minimum=1,
317
- maximum=50,
318
- step=1,
319
- value=50, # "highest quality" default
320
- )
321
-
322
- # μ œν•œλœ 길이
323
- max_length = 180
324
-
325
- def set_example_and_disable_enrichment(example, current_checkbox_value):
326
- return example, gr.update(value=False)
327
-
328
  gr.Examples(
329
  examples=examples,
330
- inputs=[prompt, use_prompt_enrichment],
331
- outputs=[prompt, use_prompt_enrichment],
332
- fn=set_example_and_disable_enrichment,
333
- example_labels=[ex[0][:max_length] + "..." if len(ex[0]) > max_length else ex[0] for ex in examples]
334
  )
 
335
  gr.Markdown(f"[{model_name} Model Card and Weights](https://huggingface.co/{model_repo_id})")
336
 
337
- resolution_dropdown.change(
338
- fn=update_resolution,
339
- inputs=resolution_dropdown,
340
- outputs=[width, height]
341
- )
342
-
343
  gr.on(
344
- triggers=[run_button.click, prompt.submit],
345
  fn=infer,
346
  inputs=[
347
- prompt,
348
- negative_prompt,
349
- seed,
350
- randomize_seed,
351
- width,
352
- height,
353
- guidance_scale,
354
- num_inference_steps,
355
- use_prompt_enrichment,
356
- enable_apg,
357
  ],
358
- outputs=[result, seed, enriched_prompt_display, enriched_prompt_text, enrichment_error],
359
  )
360
-
361
 
 
362
  if __name__ == "__main__":
363
  demo.launch()
 
1
+ ##############################################################################
2
+ # app.py #
3
+ ##############################################################################
4
  model_repo_id = "Freepik/F-Lite-Texture"
5
+ model_name = "F Lite Texture"
6
 
7
+ from dotenv import load_dotenv
8
  import gradio as gr
9
+ import numpy as np
10
+ import random, os, logging, google.generativeai as genai, spaces, torch
11
+
 
 
 
 
 
12
  from f_lite import FLitePipeline
13
+ from f_lite.pipeline import APGConfig
14
 
15
+ # ────────────────────────────────────────────────────────────────────────────
16
+ # diffusers helper (ν•„μˆ˜ 트릭 – DiT 클래슀λ₯Ό diffusers둜 μΈμ‹μ‹œν‚€κΈ° μœ„ν•¨)
17
+ # ────────────────────────────────────────────────────────────────────────────
18
  from diffusers.pipelines.pipeline_loading_utils import LOADABLE_CLASSES, ALL_IMPORTABLE_CLASSES
19
+ LOADABLE_CLASSES["f_lite"] = LOADABLE_CLASSES["f_lite.model"] = {"DiT": ["save_pretrained", "from_pretrained"]}
20
+ ALL_IMPORTABLE_CLASSES["DiT"] = ["save_pretrained", "from_pretrained"]
21
 
22
+ # ────────────────────────────────────────────────────────────────────────────
23
+ # ν™˜κ²½ μ„€μ • / λͺ¨λΈ λ‘œλ“œ
24
+ # ────────────────────────────────────────────────────────────────────────────
 
25
  load_dotenv()
26
+ logging.basicConfig(level=logging.INFO)
27
 
28
+ # Gemini API μ€€λΉ„ (μžˆμ„ λ•Œλ§Œ μ‚¬μš©)
29
+ gemini_available = False
30
  if os.getenv("GEMINI_API_KEY"):
 
31
  genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
32
+ gemini_available = True
33
  else:
34
+ logging.warning("GEMINI_API_KEY not found – prompt enrichment disabled.")
 
35
 
36
+ device = "cuda" if torch.cuda.is_available() else "cpu"
37
+ torch_dtype = torch.bfloat16 if torch.cuda.is_available() else torch.float32
 
 
 
 
38
 
39
  pipe = FLitePipeline.from_pretrained(model_repo_id, torch_dtype=torch_dtype)
40
  pipe.to(device)
41
+ pipe.vae.enable_slicing(); pipe.vae.enable_tiling()
 
42
 
43
+ # ────────────────────────────────────────────────────────────────────────────
44
+ # κΈ°λ³Έ κ°’ μ„€μ •
45
+ # ────────────────────────────────────────────────────────────────────────────
46
+ MAX_SEED = np.iinfo(np.int32).max
47
+ MAX_IMAGE_SIZE = 1600
48
 
49
  RESOLUTIONS = {
50
+ "horizontal": [
51
+ {"width": 1344, "height": 896, "label": "1344Γ—896"},
52
+ {"width": 1152, "height": 768, "label": "1152Γ—768"},
53
+ {"width": 960 , "height": 640, "label": "960Γ—640"},
54
+ {"width": 1600, "height": 896, "label": "1600Γ—896"}
55
+ ],
56
+ "vertical": [
57
+ {"width": 896 , "height": 1344, "label": "896Γ—1344"},
58
+ {"width": 768 , "height": 1152, "label": "768Γ—1152"},
59
+ {"width": 640 , "height": 960 , "label": "640Γ—960"},
60
+ {"width": 896 , "height": 1600, "label": "896Γ—1600"}
61
+ ],
62
+ "square": [
63
+ {"width": 1216, "height": 1216, "label": "1216Γ—1216"},
64
+ {"width": 1024, "height": 1024, "label": "1024Γ—1024"}
65
+ ]
66
  }
 
67
  DEFAULT_RESOLUTION = {"width": 1024, "height": 1024, "label": "1024Γ—1024"}
68
 
69
+ # ────────────────────────────────────────────────────────────────────────────
70
+ # 해상도 λ“œλ‘­λ‹€μš΄ μ˜΅μ…˜ 생성
71
+ # ────────────────────────────────────────────────────────────────────────────
72
  resolution_options = []
73
+ for cat, res_list in RESOLUTIONS.items():
74
+ resolution_options.append([f"{cat.capitalize()}", None])
75
+ for r in res_list:
76
+ resolution_options.append([f" {r['label']}", f"{cat}:{r['width']}:{r['height']}"])
77
+
78
+ # ────────────────────────────────────────────────────────────────────────────
79
+ # Prompt enrichment (Gemini)
80
+ # ────────────────────────────────────────────────────────────────────────────
81
+ def enrich_prompt_with_gemini(prompt: str, max_tokens: int = 1024):
82
+ """Gemini-based prompt expansion (μ—λŸ¬ μ‹œ 원본 μœ μ§€)."""
83
  try:
84
+ if not gemini_available:
85
+ return None, "Gemini unavailable."
86
+ model = genai.GenerativeModel("gemini-1.5-flash")
87
+ ask = (
88
+ "You are an exceptional prompt enhancer for text-to-image generation.\n"
89
+ "Rewrite the following prompt so it becomes richly detailed, cinematic, and vivid.\n"
90
+ "Return ONE descriptive paragraph only.\n\n"
91
+ f"Original prompt: {prompt}\n\nEnhanced prompt:"
92
+ )
93
+ out = model.generate_content(
94
+ ask,
95
+ generation_config={"max_output_tokens": max_tokens, "temperature": 1},
96
+ )
97
+ return out.text.strip(), None
 
 
 
 
 
98
  except Exception as e:
99
+ logging.error(f"Gemini error: {e}")
100
+ return None, f"Gemini error: {e}"
101
+
102
+ # ────────────────────────────────────────────────────────────────────────────
103
+ # 해상도 μ—…λ°μ΄νŠΈ
104
+ # ────────────────────────────────────────────────────────────────────────────
105
+ def update_resolution(sel: str):
106
+ if not sel:
107
  return DEFAULT_RESOLUTION["width"], DEFAULT_RESOLUTION["height"]
108
  try:
109
+ _, w, h = sel.split(":")
110
+ return int(w), int(h)
111
+ except ValueError:
112
  return DEFAULT_RESOLUTION["width"], DEFAULT_RESOLUTION["height"]
113
 
114
+ # ────────────────────────────────────────────────────────────────────────────
115
+ # μ˜ˆμ‹œ ν”„λ‘¬ν”„νŠΈ 10개
116
+ # ────────────────────────────────────────────────────────────────────────────
117
+ examples = [
118
+ ["An ultra-detailed macro photograph of a dew-covered rainbow beetle perched on a spiralling fern unfurling at dawn, back-lit by golden sunrise, bokeh background, 200-mm lens, f/2.8, vivid colors, cinematic lighting", None],
119
+ ["A retro-futuristic cityscape at night inspired by Syd Mead: neon-drenched streets reflect glistening rain, flying cars leave light-trail arcs between towering holographic billboards, 35 mm film grain, wide-angle perspective", None],
120
+ ["An elegant 18th-century ballroom rendered in photorealistic 8K, crystal chandeliers scattering prismatic light across polished marble floors, dancers in flowing silk gowns twirl mid-motion, captured like a long-exposure still", None],
121
+ ["A serene Japanese onsen nestled in a snowy mountain valley, steam rising into crisp twilight air, red lanterns glowing softly, snow-laden pines framing the scene, shot on medium-format analog with natural film tones", None],
122
+ ["Hyper-real illustration of an astronaut in a translucent spacesuit tending a floating bonsai inside a zero-g greenhouse aboard an orbital station, earthrise through panoramic windows, bioluminescent plants provide teal ambience", None],
123
+ ["A majestic white Arabian horse galloping across a mirror-like lake at sunset, droplets frozen mid-air, warm rim light outlining powerful muscles, captured at 1/4000 s with sweeping motion-blur background", None],
124
+ ["An ancient library hollowed inside a colossal redwood tree, spiral root staircases, glowing fireflies as lamps, shafts of emerald light pierce stained-leaf windows, ultra-detailed fantasy matte painting", None],
125
+ ["A haute-couture portrait: model in a gown composed of iridescent butterfly wings, dramatic chiaroscuro, deep-blue velvet backdrop, shot on Hasselblad with razor-sharp eye focus, 120 MP clarity", None],
126
+ ["Cyberpunk samurai duo beneath torrential neon rain, reflective katanas crackling with violet energy, holographic kanji drifting, cinematic anamorphic lens flares, gritty atmosphere", None],
127
+ ["A whimsical steampunk airship festival above a Victorian harbor: brass dirigibles with floral patterns, cog-shaped fireworks burst at golden hour, painterly style reminiscent of Miyazaki", None],
128
+ ]
129
+
130
+ # 첫 μ˜ˆμ‹œ ν”„λ‘¬ν”„νŠΈλ₯Ό κΈ°λ³Έκ°’μœΌλ‘œ μ‚¬μš©
131
+ DEFAULT_PROMPT = examples[0][0]
132
+
133
+ # ────────────────────────────────────────────────────────────────────────────
134
+ # μΆ”λ‘  ν•¨μˆ˜
135
+ # ────────────────────────────────────────────────────────────────────────────
136
  @spaces.GPU(duration=120)
137
  def infer(
138
  prompt,
 
147
  enable_apg,
148
  progress=gr.Progress(track_tqdm=True),
149
  ):
 
 
150
  generation_prompt = prompt
151
+ enriched_prompt, enrich_err = None, None
152
+
153
  if use_prompt_enrichment and gemini_available:
154
+ enriched_prompt, enrich_err = enrich_prompt_with_gemini(prompt)
155
+ if enriched_prompt:
156
+ generation_prompt = enriched_prompt
157
+
158
  if randomize_seed:
159
  seed = random.randint(0, MAX_SEED)
160
 
 
165
  negative_prompt=negative_prompt,
166
  guidance_scale=guidance_scale,
167
  num_inference_steps=num_inference_steps,
168
+ width=width, height=height,
 
169
  generator=generator,
170
+ apg_config=APGConfig(enabled=enable_apg),
171
  ).images[0]
 
 
 
 
172
 
173
+ # UI μ—…λ°μ΄νŠΈ μ œμ–΄
174
+ show_acc = gr.update(visible=False)
175
+ show_text = gr.update(value="")
176
+ show_error = gr.update(visible=False, value="")
 
 
177
 
178
+ if enriched_prompt:
179
+ show_acc = gr.update(visible=True)
180
+ show_text = gr.update(value=enriched_prompt)
181
+ elif enrich_err:
182
+ show_acc = gr.update(visible=True)
183
+ show_error = gr.update(visible=True, value=enrich_err)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
184
 
185
+ return image, seed, show_acc, show_text, show_error
186
 
187
+ # ────────────────────────────────────────────────────────────────────────────
188
+ # Gradio UI
189
+ # ────────────────────────────────────────────────────────────────────────────
190
  css = """
191
+ #col-container {margin:0 auto; max-width:1024px;}
192
+ .prompt-row > .gr-form{gap:0.5rem !important; align-items:center;}
 
 
 
 
 
 
193
  """
194
 
195
  with gr.Blocks(css=css, theme="ParityError/Interstellar") as demo:
196
  with gr.Column(elem_id="col-container"):
197
+ gr.Markdown(f"# {model_name} Text-to-Image Demo")
198
+
199
+ # ── μž…λ ₯ 파트 ──
200
  with gr.Row(elem_classes="prompt-row"):
201
+ prompt_box = gr.Text(
202
+ value=DEFAULT_PROMPT, # κΈ°λ³Έ ν”„λ‘¬ν”„νŠΈ
203
+ label="Prompt", show_label=False,
204
+ max_lines=1, placeholder="Enter your prompt",
205
+ container=False, scale=6,
 
 
206
  )
 
207
  use_prompt_enrichment = gr.Checkbox(
208
+ label="Enrich", value=True, visible=False # μˆ¨κΉ€ + κΈ°λ³Έ True
 
 
209
  )
210
  run_button = gr.Button("Run", scale=1, variant="primary", min_width=100)
211
+
212
+ # ── κ²°κ³Ό 이미지 ── (μ΄ˆκΈ°κ°’: image1.webp)
213
+ result_img = gr.Image(
214
+ value="image1.webp", # 같은 경둜 이미지 ν‘œμ‹œ
215
+ label="Result", show_label=False
216
+ )
217
+
218
+ # Enriched prompt ν‘œμ‹œμš© μ•„μ½”λ””μ–Έ
219
+ enrich_acc = gr.Accordion("Enriched Prompt", open=False, visible=False)
220
+ with enrich_acc:
221
+ enrich_txt = gr.Textbox(label="Enriched Prompt", interactive=False, lines=8)
222
+ enrich_error = gr.Textbox(label="Error", visible=False, interactive=False)
223
+
224
+ # ── κ³ κΈ‰ μ„€μ • ──
 
 
225
  with gr.Accordion("Advanced Settings", open=False):
226
  negative_prompt = gr.Text(
227
+ label="Negative prompt", max_lines=1, placeholder="Enter a negative prompt"
 
 
 
228
  )
229
+ with gr.Tabs():
 
230
  with gr.TabItem("Preset Resolutions"):
231
+ resolution_dd = gr.Dropdown(
232
  label="Resolution",
233
  choices=resolution_options,
234
+ value="horizontal:1600:896", # κ°€μž₯ 큰 preset
 
235
  type="value"
236
  )
 
237
  with gr.TabItem("Custom Resolution"):
238
  with gr.Row():
239
+ width_sl = gr.Slider(
240
+ label="Width", minimum=256, maximum=MAX_IMAGE_SIZE,
241
+ step=32, value=1600
 
 
 
 
242
  )
243
+ height_sl = gr.Slider(
244
+ label="Height", minimum=256, maximum=MAX_IMAGE_SIZE,
245
+ step=32, value=896
 
 
 
 
246
  )
247
 
248
+ seed_sl = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=42)
249
+ random_seed = gr.Checkbox(label="Randomize seed", value=False)
 
 
 
 
 
 
 
250
 
251
  with gr.Row():
252
+ guidance_sl = gr.Slider(label="Guidance scale", minimum=0, maximum=15, step=0.1, value=6)
253
+ enable_apg = gr.Checkbox(label="Enable APG", value=True)
254
+ steps_sl = gr.Slider(label="Number of inference steps", minimum=1, maximum=50, step=1, value=50)
255
+
256
+ # ── 예제 ν”„λ‘¬ν”„νŠΈ λͺ©λ‘ ──
257
+ def set_example(example, _):
258
+ return example, gr.update(value=False) # enrichment 끄기
259
+ max_len = 180
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
260
  gr.Examples(
261
  examples=examples,
262
+ inputs=[prompt_box, use_prompt_enrichment],
263
+ outputs=[prompt_box, use_prompt_enrichment],
264
+ fn=set_example,
265
+ example_labels=[ex[0][:max_len] + "..." if len(ex[0]) > max_len else ex[0] for ex in examples]
266
  )
267
+
268
  gr.Markdown(f"[{model_name} Model Card and Weights](https://huggingface.co/{model_repo_id})")
269
 
270
+ # ── μƒν˜Έμž‘μš© μ—°κ²° ──
271
+ resolution_dd.change(fn=update_resolution, inputs=resolution_dd, outputs=[width_sl, height_sl])
272
+
 
 
 
273
  gr.on(
274
+ triggers=[run_button.click, prompt_box.submit],
275
  fn=infer,
276
  inputs=[
277
+ prompt_box, negative_prompt, seed_sl, random_seed,
278
+ width_sl, height_sl, guidance_sl, steps_sl,
279
+ use_prompt_enrichment, enable_apg
 
 
 
 
 
 
 
280
  ],
281
+ outputs=[result_img, seed_sl, enrich_acc, enrich_txt, enrich_error],
282
  )
 
283
 
284
+ # ────────────────────────────────────────────────────────────────────────────
285
  if __name__ == "__main__":
286
  demo.launch()