File size: 12,948 Bytes
176edce
 
 
80e38a2
 
 
 
 
e48aa5a
15cc8b5
 
80e38a2
 
b2f5030
 
176edce
 
 
80e38a2
343fdaf
176edce
343fdaf
80e38a2
 
 
 
 
 
 
 
 
 
343fdaf
80e38a2
 
 
 
176edce
 
 
 
 
0399de8
176edce
 
0399de8
343fdaf
80e38a2
 
 
 
 
 
343fdaf
80e38a2
b2f5030
80e38a2
 
 
 
 
176edce
 
343fdaf
80e38a2
0399de8
80e38a2
 
 
 
 
 
 
0399de8
f09c591
 
 
 
0399de8
f09c591
 
 
80e38a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ec2621
7b9b23e
80e38a2
 
 
 
 
 
 
 
 
 
0399de8
80e38a2
 
0399de8
80e38a2
 
0399de8
80e38a2
f09c591
80e38a2
 
3ec2621
80e38a2
 
 
 
0399de8
80e38a2
 
0399de8
 
 
 
 
 
80e38a2
0399de8
 
 
 
80e38a2
0399de8
 
 
b2f5030
0399de8
 
 
 
 
 
 
 
 
 
80e38a2
0399de8
 
 
 
 
80e38a2
0399de8
80e38a2
 
 
 
 
 
 
 
 
0399de8
 
80e38a2
0399de8
 
80e38a2
0399de8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80e38a2
0399de8
80e38a2
 
 
 
 
0399de8
80e38a2
 
 
e48aa5a
 
0399de8
 
80e38a2
0399de8
 
 
80e38a2
 
 
 
0399de8
819fc44
 
0399de8
 
 
 
 
 
 
 
 
 
 
819fc44
0399de8
 
 
819fc44
0399de8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
819fc44
 
 
 
0399de8
819fc44
 
0399de8
819fc44
 
0399de8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ec2621
 
343fdaf
0399de8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80e38a2
 
 
 
0399de8
 
 
 
 
 
80e38a2
0399de8
 
 
80e38a2
0399de8
 
 
 
 
 
80e38a2
 
 
f8cac3e
80e38a2
 
819fc44
80e38a2
0399de8
 
 
 
 
 
80e38a2
819fc44
 
 
0399de8
819fc44
0399de8
 
 
 
 
 
 
 
 
 
 
 
819fc44
3ec2621
343fdaf
f09c591
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
import os
import time
from os import path
import tempfile
import uuid
import base64
import mimetypes
import json
import io
import random
import string

import torch
from PIL import Image

from safetensors.torch import load_file
from huggingface_hub import hf_hub_download

# Diffusers ๊ด€๋ จ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ
import gradio as gr
from diffusers import FluxPipeline

# Google GenAI ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ
from google import genai
from google.genai import types

#######################################
# 0. ํ™˜๊ฒฝ์„ค์ •
#######################################

BASE_DIR = path.dirname(path.abspath(__file__)) if "__file__" in globals() else os.getcwd()
CACHE_PATH = path.join(BASE_DIR, "models")

os.environ["TRANSFORMERS_CACHE"] = CACHE_PATH
os.environ["HF_HUB_CACHE"] = CACHE_PATH
os.environ["HF_HOME"] = CACHE_PATH

class timer:
    def __init__(self, method_name="timed process"):
        self.method = method_name
    def __enter__(self):
        self.start = time.time()
        print(f"[TIMER] {self.method} starts")
    def __exit__(self, exc_type, exc_val, exc_tb):
        end = time.time()
        print(f"[TIMER] {self.method} took {round(end - self.start, 2)}s")

#######################################
# 1. FLUX ํŒŒ์ดํ”„๋ผ์ธ ๋กœ๋“œ
#######################################

if not path.exists(CACHE_PATH):
    os.makedirs(CACHE_PATH, exist_ok=True)

pipe = FluxPipeline.from_pretrained(
    "black-forest-labs/FLUX.1-dev",
    torch_dtype=torch.bfloat16
)

lora_path = hf_hub_download("ByteDance/Hyper-SD", "Hyper-FLUX.1-dev-8steps-lora.safetensors")
pipe.load_lora_weights(lora_path)
pipe.fuse_lora(lora_scale=0.125)
pipe.to(device="cuda", dtype=torch.bfloat16)

#######################################
# 2. Google GenAI (Gemini) - ์ด๋ฏธ์ง€ ๋ณ€ํ™˜ ํ•จ์ˆ˜
#######################################

def save_binary_file(file_name, data):
    with open(file_name, "wb") as f:
        f.write(data)

def generate_by_google_genai(text, file_name, model="gemini-2.0-flash-exp"):
    """Gemini ๋ชจ๋ธ์„ ํ†ตํ•ด ์ด๋ฏธ์ง€ ๋‚ด๋ถ€ ํ…์ŠคํŠธ๋ฅผ ๋ณ€๊ฒฝ."""
    api_key = os.getenv("GAPI_TOKEN", None)
    if not api_key:
        raise ValueError(
            "GAPI_TOKEN ํ™˜๊ฒฝ ๋ณ€์ˆ˜๊ฐ€ ์„ค์ •๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค. "
            "Google GenAI API๋ฅผ ์‚ฌ์šฉํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š” GAPI_TOKEN์ด ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค."
        )

    client = genai.Client(api_key=api_key)
    files = [client.files.upload(file=file_name)]
    
    contents = [
        types.Content(
            role="user",
            parts=[
                types.Part.from_uri(
                    file_uri=files[0].uri,
                    mime_type=files[0].mime_type,
                ),
                types.Part.from_text(text=text),
            ],
        ),
    ]

    generate_content_config = types.GenerateContentConfig(
        temperature=1,
        top_p=0.95,
        top_k=40,
        max_output_tokens=8192,
        response_modalities=["image", "text"],
        response_mime_type="text/plain",
    )

    text_response = ""
    image_path = None

    with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:
        temp_path = tmp.name
        for chunk in client.models.generate_content_stream(
            model=model,
            contents=contents,
            config=generate_content_config,
        ):
            if not chunk.candidates or not chunk.candidates[0].content:
                continue

            candidate = chunk.candidates[0].content.parts[0]
            if candidate.inline_data:
                save_binary_file(temp_path, candidate.inline_data.data)
                print(f"[DEBUG] Gemini returned image -> {temp_path}")
                image_path = temp_path
                break
            else:
                text_response += chunk.text + "\n"
    
    del files
    return image_path, text_response

#######################################
# 3. Diffusion (Flux)์šฉ ํ•จ์ˆ˜
#######################################

def generate_random_letters(length: int) -> str:
    """length ๊ธธ์ด๋งŒํผ ๋Œ€์†Œ๋ฌธ์ž ์•ŒํŒŒ๋ฒณ์„ ๋ฌด์ž‘์œ„๋กœ ์ƒ์„ฑ."""
    letters = string.ascii_lowercase + string.ascii_uppercase
    return "".join(random.choice(letters) for _ in range(length))

def fill_prompt_with_random_texts(prompt: str, r1: str, r2: str, r3: str) -> str:
    """
    ํ”„๋กฌํ”„ํŠธ ๋‚ด <text1>, <text2>, <text3>๋ฅผ
    ๊ฐ๊ฐ r1, r2, r3๋กœ ์น˜ํ™˜.
    - <text1>์€ ํ•„์ˆ˜ (์—†์œผ๋ฉด ์ž๋™์œผ๋กœ ๋’ค์— ๋ถ™์ž„).
    - <text2>, <text3>๋Š” ์žˆ์œผ๋ฉด ์น˜ํ™˜, ์—†์œผ๋ฉด ๋ฌด์‹œ.
    """
    # 1) <text1>์€ ํ•„์ˆ˜
    if "<text1>" in prompt:
        prompt = prompt.replace("<text1>", r1)
    else:
        # ์ž๋™ ๋ง๋ถ™์ž„
        prompt = f"{prompt} with clear readable text that says '{r1}'"

    # 2) <text2>, <text3>๋Š” ์„ ํƒ
    if "<text2>" in prompt:
        prompt = prompt.replace("<text2>", r2)
    if "<text3>" in prompt:
        prompt = prompt.replace("<text3>", r3)
    
    return prompt

def generate_initial_image(prompt, random1, random2, random3, height, width, steps, scale, seed):
    """
    Flux ํŒŒ์ดํ”„๋ผ์ธ์„ ์ด์šฉํ•ด (r1, r2, r3)๊ฐ€ ๋“ค์–ด๊ฐ„ ์ด๋ฏธ์ง€๋ฅผ ์ƒ์„ฑ.
    """
    with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16), timer("Flux Generation"):
        result = pipe(
            prompt=[prompt],
            generator=torch.Generator().manual_seed(int(seed)),
            num_inference_steps=int(steps),
            guidance_scale=float(scale),
            height=int(height),
            width=int(width),
            max_sequence_length=256
        ).images[0]
    return result


def change_multi_text_in_image(original_image, random1, final1, random2, final2, random3, final3):
    """
    Gemini๋ฅผ ํ†ตํ•ด, ์ด๋ฏธ์ง€ ์•ˆ์˜ r1->final1, r2->final2, r3->final3 ์‹์œผ๋กœ ํ…์ŠคํŠธ ๊ต์ฒด.
    - r2, final2 (๋˜๋Š” r3, final3)๊ฐ€ ๋นˆ ๋ฌธ์ž์—ด์ด๋ฉด ํ•ด๋‹น ๊ต์ฒด๋Š” ๊ฑด๋„ˆ๋œ€.
    """
    # ๊ต์ฒด ์ง€์‹œ๋ฌธ ๋งŒ๋“ค๊ธฐ
    instructions = []
    if random1 and final1:
        instructions.append(f"Change any text reading '{random1}' in this image to '{final1}'.")
    if random2 and final2:
        instructions.append(f"Change any text reading '{random2}' in this image to '{final2}'.")
    if random3 and final3:
        instructions.append(f"Change any text reading '{random3}' in this image to '{final3}'.")

    # ๋งŒ์•ฝ ๊ต์ฒด ์ง€์‹œ๋ฌธ์ด ์—†๋‹ค๋ฉด ๊ทธ๋ƒฅ return original_image
    if not instructions:
        print("[WARN] No text changes requested!")
        return original_image

    full_instruction = " ".join(instructions)
    try:
        # ์ž„์‹œ ํŒŒ์ผ์— original_image ์ €์žฅ
        with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:
            original_path = tmp.name
            original_image.save(original_path)

        image_path, text_response = generate_by_google_genai(
            text=full_instruction,
            file_name=original_path
        )
        if image_path:
            with open(image_path, "rb") as f:
                image_data = f.read()
            new_img = Image.open(io.BytesIO(image_data))
            return new_img
        else:
            # ์ด๋ฏธ์ง€ ์—†์ด ํ…์ŠคํŠธ๋งŒ ์˜จ ๊ฒฝ์šฐ
            print("[WARN] Gemini returned only text:", text_response)
            return original_image
    except Exception as e:
        raise gr.Error(f"Error: {e}")

#######################################
# 4. ๋ฉ”์ธ ํ”„๋กœ์„ธ์Šค ํ•จ์ˆ˜
#######################################

def run_process(
    prompt,
    final_text1,
    final_text2,
    final_text3,
    height,
    width,
    steps,
    scale,
    seed
):
    """
    1) final_text1(ํ•„์ˆ˜), final_text2, final_text3(์˜ต์…˜) ๊ฐ๊ฐ ๊ธธ์ด์— ๋งž์ถฐ ๋ฌด์ž‘์œ„ ์•ŒํŒŒ๋ฒณ ๋งŒ๋“ค๊ธฐ.
    2) prompt ๋‚ด <text1>, <text2>, <text3> ์น˜ํ™˜ -> Flux๋กœ 1์ฐจ(๋žœ๋ค) ์ด๋ฏธ์ง€.
    3) Gemini ํ˜ธ์ถœ -> r1->final_text1, r2->final_text2, r3->final_text3 ๊ต์ฒด -> ์ตœ์ข… ์ด๋ฏธ์ง€.
    """
    # (A) ๋ฌด์ž‘์œ„ ์•ŒํŒŒ๋ฒณ
    r1 = generate_random_letters(len(final_text1)) if final_text1 else ""
    r2 = generate_random_letters(len(final_text2)) if final_text2 else ""
    r3 = generate_random_letters(len(final_text3)) if final_text3 else ""

    # (B) ํ”„๋กฌํ”„ํŠธ ์น˜ํ™˜
    final_prompt = fill_prompt_with_random_texts(prompt, r1, r2, r3)
    print(f"[DEBUG] final_prompt = {final_prompt}")

    # (C) 1์ฐจ ์ด๋ฏธ์ง€ (๋žœ๋ค ํ…์ŠคํŠธ)
    random_image = generate_initial_image(final_prompt, r1, r2, r3, height, width, steps, scale, seed)

    # (D) 2์ฐจ ์ด๋ฏธ์ง€ (์‹ค์ œ ํ…์ŠคํŠธ)
    final_image = change_multi_text_in_image(
        random_image,
        r1, final_text1,
        r2, final_text2,
        r3, final_text3
    )

    return [random_image, final_image]

#######################################
# 5. Gradio UI
#######################################

with gr.Blocks(title="Flux + Google GenAI (Up to 3 Text placeholders)") as demo:
    gr.Markdown(
        """
        # Flux + Google GenAI: ์ตœ๋Œ€ 3๊ฐœ์˜ `<text>` ๊ต์ฒด

        ## ์‚ฌ์šฉ ๋ฐฉ๋ฒ•
        1. ์•„๋ž˜ Prompt์— `<text1>`, `<text2>`, `<text3>`๋ฅผ ์ตœ๋Œ€ 3๊ฐœ๊นŒ์ง€ ๋ฐฐ์น˜ ๊ฐ€๋Šฅ.
           - ์˜ˆ) "A poster with <text1> in large letters, also <text2> in the corner"
           - **<text1>์€ ํ•„์ˆ˜**(์—†์œผ๋ฉด ์ž๋™์œผ๋กœ ๋ฌธ๊ตฌ๊ฐ€ ๋’ค์— ๋ถ™์Œ)
           - <text2>, <text3>๋Š” ๋„ฃ์–ด๋„ ๋˜๊ณ , ์•ˆ ๋„ฃ์–ด๋„ ๋จ.
        2. "New Text #1" (ํ•„์ˆ˜), "New Text #2", "New Text #3"๋ฅผ ์ž…๋ ฅ.
           - #2, #3๋Š” ๋น„์›Œ ๋‘๋ฉด ํ•ด๋‹น ์ž๋ฆฌ ๊ต์ฒด ์—†์Œ.
        3. "Generate Images" ๋ฒ„ํŠผ โ†’  
           (1) `<text1>`, `<text2>`, `<text3>` ์ž๋ฆฌ์— (๋˜๋Š” ์ž๋™์œผ๋กœ) **๋ฌด์ž‘์œ„ ์•ŒํŒŒ๋ฒณ** ๋„ฃ์€ 1์ฐจ ์ด๋ฏธ์ง€ ์ƒ์„ฑ  
           (2) ์ด์–ด Gemini ๋ชจ๋ธ์„ ํ†ตํ•ด ๋ฌด์ž‘์œ„ ์•ŒํŒŒ๋ฒณ โ†’ ์‹ค์ œ "New Text #1/2/3" ๋ณ€๊ฒฝํ•œ 2์ฐจ ์ด๋ฏธ์ง€  
           - **๋‘ ์ด๋ฏธ์ง€**(๋žœ๋ค ํ…์ŠคํŠธ โ†’ ์ตœ์ข… ํ…์ŠคํŠธ)๊ฐ€ ์ˆœ์„œ๋Œ€๋กœ ์ถœ๋ ฅ๋ฉ๋‹ˆ๋‹ค.

        ---
        """
    )

    # ์˜ˆ์‹œ 5๊ฐœ
    examples = [
        [
            "A futuristic billboard shows <text1> and a small sign <text2> on the left side. <text3> is a hidden watermark.",
            "HELLO", "WELCOME", "2025"
        ],
        [
            "A fantasy poster with <text1> and <text2> in stylized letters, plus a tiny note <text3> at the bottom.",
            "Dragons", "MagicRealm", "Beware!"
        ],
        [
            "A neon sign reading <text1>, with a secondary text <text2> below. <text3> might appear in the corner.",
            "OPEN", "24HOUR", "NoSmoking"
        ],
        [
            "A big invitation card with main text <text1>, subtitle <text2>, signature <text3> in cursive.",
            "Birthday Party", "Today Only", "From Your Friend"
        ],
        [
            "A large graffiti wall with <text1> in bold letters, plus <text2> and <text3> near the edges.",
            "FREEDOM", "HOPE", "LOVE"
        ]
    ]

    with gr.Row():
        with gr.Column():
            prompt_input = gr.Textbox(
                lines=3,
                label="Prompt (use `<text1>`, `<text2>`, `<text3>` as needed)",
                placeholder="Ex) A poster with <text1>, plus a line <text2>, etc."
            )
            final_text1 = gr.Textbox(
                label="New Text #1 (Required)",
                placeholder="Ex) HELLO"
            )
            final_text2 = gr.Textbox(
                label="New Text #2 (Optional)",
                placeholder="Ex) WELCOME"
            )
            final_text3 = gr.Textbox(
                label="New Text #3 (Optional)",
                placeholder="Ex) 2025 or anything"
            )

            with gr.Accordion("Advanced Settings", open=False):
                height = gr.Slider(label="Height", minimum=256, maximum=1152, step=64, value=512)
                width = gr.Slider(label="Width", minimum=256, maximum=1152, step=64, value=512)
                steps = gr.Slider(label="Inference Steps", minimum=6, maximum=25, step=1, value=8)
                scale = gr.Slider(label="Guidance Scale", minimum=0.0, maximum=10.0, step=0.5, value=3.5)
                seed = gr.Number(label="Seed (reproducibility)", value=1234, precision=0)

            run_btn = gr.Button("Generate Images", variant="primary")

            gr.Examples(
                examples=examples,
                inputs=[prompt_input, final_text1, final_text2, final_text3],
                label="Click to load example"
            )

        with gr.Column():
            random_image_output = gr.Image(label="1) Random Text Image", type="pil")
            final_image_output = gr.Image(label="2) Final Text Image", type="pil")

    # ๋ฒ„ํŠผ ์•ก์…˜
    run_btn.click(
        fn=run_process,
        inputs=[
            prompt_input,
            final_text1,
            final_text2,
            final_text3,
            height,
            width,
            steps,
            scale,
            seed
        ],
        outputs=[random_image_output, final_image_output]
    )

demo.launch(max_threads=20)