Update app.py
Browse files123456789101112131415161718195 unmodified lines2526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941953 unmodified lines1992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832 unmodified lines286287288289290291292293import randomimport osimport uuidfrom datetime import datetimeimport gradio as grimport numpy as npimport spacesimport torchfrom diffusers import DiffusionPipelinefrom PIL import Image# Create permanent storage directorySAVE_DIR = "saved_images" # Gradio will handle the persistenceif not os.path.exists(SAVE_DIR):os.makedirs(SAVE_DIR, exist_ok=True)device = "cuda" if torch.cuda.is_available() else "cpu"repo_id = "black-forest-labs/FLUX.1-dev"adapter_id = "seawolf2357/kim-korea" # ํน์ ์ ์น์ธ์ ํ์ตํ LoRA ๋ชจ๋ธ5 unmodified linesMAX_SEED = np.iinfo(np.int32).maxMAX_IMAGE_SIZE = 1024def save_generated_image(image, prompt):# Generate unique filename with timestamptimestamp = datetime.now().strftime("%Y%m%d_%H%M%S")unique_id = str(uuid.uuid4())[:8]filename = f"{timestamp}_{unique_id}.png"filepath = os.path.join(SAVE_DIR, filename)# Save the imageimage.save(filepath)# Save metadatametadata_file = os.path.join(SAVE_DIR, "metadata.txt")with open(metadata_file, "a", encoding="utf-8") as f:f.write(f"{filename}|{prompt}|{timestamp}\n")return filepath@spaces.GPU(duration=60)def inference(prompt,seed=42,randomize_seed=True,width=1024,height=768,guidance_scale=3.5,num_inference_steps=30,lora_scale=1.0,progress=None,):if randomize_seed:seed = random.randint(0, MAX_SEED)generator = torch.Generator(device=device).manual_seed(int(seed))image = pipeline(prompt=prompt,guidance_scale=guidance_scale,num_inference_steps=num_inference_steps,width=width,height=height,generator=generator,joint_attention_kwargs={"scale": lora_scale},).images[0]# Save the generated imagefilepath = save_generated_image(image, prompt)# Return just the image and seedreturn image, seed# ์์ ๋ฌธ๊ตฌ: ํน์ ์ ์น์ธ Mr. KIM์ ๋ค์ํ ์ํฉ์ ๋ฌ์ฌexamples = ["Mr. KIM holding up a 'Fighting!' banner with both hands, showing patriotic pride and determination for national excellence. ","Mr. KIM raising both arms in celebration with a triumphant expression, showing victory and hope for the future.","Mr. KIM jogging in a park wearing athletic gear, demonstrating healthy lifestyle and energetic leadership qualities.","Mr. KIM warmly shaking hands with female citizens in a crowded street, showing genuine care and connection with women voters. ","Mr. KIM at a campaign rally, pointing toward the horizon with an inspiring gesture while female and kids audience members applaud. ","Mr. KIM participating in a community event, surrounded by enthusiastic female supporters cheering ","Mr. KIM visiting a local market, engaging in friendly conversation with female vendors and shopkeepers. ","Mr. KIM walking through a university campus, discussing education policies with female students and professors. ","Mr. KIM delivering a powerful speech in front of a large crowd with confident gestures and determined expression. ","Mr. KIM in a dynamic interview setting, passionately outlining his visions for the future.","Mr. KIM preparing for an important debate, surrounded by paperwork, looking focused and resolute. ",]# UI๋ฅผ ๋ถ์ ๊ณ์ด ๊ทธ๋ผ๋์์ด์ ์ผ๋ก ๋์์ธcustom_css = """:root {--color-primary: #8F1A3A; /* ๋ถ์ ํค์ ๋ฉ์ธ ์ปฌ๋ฌ */--color-secondary: #FF4B4B; /* ํฌ์ธํธ ์ปฌ๋ฌ(๋ฐ์ ๋นจ๊ฐ) */--background-fill-primary: linear-gradient(to right, #FFF5F5, #FED7D7, #FEB2B2);}footer {visibility: hidden;}.gradio-container {background: var(--background-fill-primary);}.title {color: var(--color-primary) !important;font-size: 3rem !important;font-weight: 700 !important;text-align: center;margin: 1rem 0;text-shadow: 2px 2px 4px rgba(0,0,0,0.05);font-family: 'Playfair Display', serif;}.subtitle {color: #4A5568 !important;font-size: 1.2rem !important;text-align: center;margin-bottom: 1.5rem;font-style: italic;}.collection-link {text-align: center;margin-bottom: 2rem;font-size: 1.1rem;}.collection-link a {color: var(--color-primary);text-decoration: underline;transition: color 0.3s ease;}.collection-link a:hover {color: var(--color-secondary);}.model-description {background-color: rgba(255, 255, 255, 0.8);border-radius: 12px;padding: 24px;margin: 20px 0;box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);border-left: 5px solid var(--color-primary);}button.primary {background-color: var(--color-primary) !important;transition: all 0.3s ease;color: #fff !important;}button:hover {transform: translateY(-2px);box-shadow: 0 5px 15px rgba(0,0,0,0.1);}.input-container {border-radius: 10px;box-shadow: 0 2px 8px rgba(0,0,0,0.05);background-color: rgba(255, 255, 255, 0.6);padding: 20px;margin-bottom: 1rem;}.advanced-settings {margin-top: 1rem;padding: 1rem;border-radius: 10px;background-color: rgba(255, 255, 255, 0.6);}.example-region {background-color: rgba(255, 255, 255, 0.5);border-radius: 10px;padding: 1rem;margin-top: 1rem;}"""with gr.Blocks(css=custom_css, analytics_enabled=False) as demo:gr.HTML('<div class="title">Mr. KIM in KOREA</div>')# ์ปฌ๋ ์ ๋งํฌ ๋๋ ์๋ด๋ฌธ์ ํ์ ์ ์์ /์ญ์ gr.HTML('<div class="collection-link"><a href="https://huggingface.co/collections/openfree/painting-art-ai-681453484ec15ef5978bbeb1" target="_blank">Visit the LoRA Model Collection</a></div>')# ๋ชจ๋ธ ์ค๋ช : ํน์ ์ ์น์ธ์ ๋ํ LoRA ๋ชจ๋ธ์์ ์ธ๊ธwith gr.Group(elem_classes="model-description"):gr.HTML("""<p>3 unmodified lines</p>""")# ๋ฉ์ธ UIwith gr.Column(elem_id="col-container"):with gr.Row(elem_classes="input-container"):prompt = gr.Text(label="Prompt",max_lines=1,placeholder="Enter your prompt (add [trigger] at the end)",value=examples[0] # ๊ธฐ๋ณธ ์์)run_button = gr.Button("Generate", variant="primary", scale=0)result = gr.Image(label="Generated Image")seed_output = gr.Number(label="Seed", visible=True)with gr.Accordion("Advanced Settings", open=False, elem_classes="advanced-settings"):seed = gr.Slider(label="Seed",minimum=0,maximum=MAX_SEED,step=1,value=42,)randomize_seed = gr.Checkbox(label="Randomize seed", value=True)with gr.Row():width = gr.Slider(label="Width",minimum=256,maximum=MAX_IMAGE_SIZE,step=32,value=1024,)height = gr.Slider(label="Height",minimum=256,maximum=MAX_IMAGE_SIZE,step=32,value=768,)with gr.Row():guidance_scale = gr.Slider(label="Guidance scale",minimum=0.0,maximum=10.0,step=0.1,value=3.5,)num_inference_steps = gr.Slider(label="Number of inference steps",minimum=1,maximum=50,step=1,value=30,)lora_scale = gr.Slider(label="LoRA scale",minimum=0.0,maximum=1.0,step=0.1,value=1.0,)with gr.Group(elem_classes="example-region"):gr.Markdown("### Examples")gr.Examples(examples=examples,inputs=prompt,outputs=None, # Don't auto-run examplesfn=None, # No function to run for examples - just fill the promptcache_examples=False,)# ์ด๋ฒคํธ ํธ๋ค๋ฌgr.on(triggers=[run_button.click, prompt.submit],fn=inference,inputs=[prompt,seed,randomize_seed,width,2 unmodified linesnum_inference_steps,lora_scale,],outputs=[result, seed_output],)demo.queue()demo.launch()123456789101112131415161718192021222324252627282930313233343536375 unmodified lines4344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831843 unmodified lines1881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262 unmodified lines229230231232233234235236237import randomimport osimport uuidimport reimport timefrom datetime import datetimeimport gradio as grimport numpy as npimport requestsimport torchfrom diffusers import DiffusionPipelinefrom PIL import Image# ===== OpenAI ์ค์ =====from openai import OpenAIclient = OpenAI(api_key=os.getenv("LLM_API")) # ํ๊ฒฝ ๋ณ์์ API ํค๊ฐ ์์ด์ผ ํฉ๋๋ค.# ===== ํ๋กฌํํธ ์ฆ๊ฐ์ฉ ์คํ์ผ ํ๋ฆฌ์ =====STYLE_PRESETS = {"None": "","Realistic Photo": "photorealistic, 8k, ultra-detailed, cinematic lighting, realistic skin texture","Oil Painting": "oil painting, rich brush strokes, canvas texture, baroque lighting","Comic Book": "comic book style, bold ink outlines, cel shading, vibrant colors","Watercolor": "watercolor illustration, soft gradients, splatter effect, pastel palette",}# ===== ์ ์ฅ ํด๋ =====SAVE_DIR = "saved_images" # Gradio will handle the persistenceif not os.path.exists(SAVE_DIR):os.makedirs(SAVE_DIR, exist_ok=True)# ===== ๋๋ฐ์ด์ค & ๋ชจ๋ธ ๋ก๋ =====device = "cuda" if torch.cuda.is_available() else "cpu"repo_id = "black-forest-labs/FLUX.1-dev"adapter_id = "seawolf2357/kim-korea" # ํน์ ์ ์น์ธ์ ํ์ตํ LoRA ๋ชจ๋ธ5 unmodified linesMAX_SEED = np.iinfo(np.int32).maxMAX_IMAGE_SIZE = 1024# ===== ํ๊ธ ์ฌ๋ถ ํ๋ณ =====HANGUL_RE = re.compile(r"[\u3131-\u318E\uAC00-\uD7A3]+")def is_korean(text: str) -> bool:return bool(HANGUL_RE.search(text))# ===== ๋ฒ์ญ & ์ฆ๊ฐ ํจ์ =====def openai_translate(text: str, retries: int = 3) -> str:"""ํ๊ธ์ ์์ด๋ก ๋ฒ์ญ (OpenAI GPT-4.1-mini ์ฌ์ฉ). ์์ด ์ ๋ ฅ์ด๋ฉด ๊ทธ๋๋ก ๋ฐํ."""if not is_korean(text):return textfor attempt in range(retries):try:res = client.chat.completions.create(model="gpt-4.1-mini",messages=[{"role": "system","content": "Translate the following Korean prompt into concise, descriptive English suitable for an image generation model. Keep the meaning, do not add new concepts."},{"role": "user", "content": text}],temperature=0.3,max_tokens=256,)return res.choices[0].message.content.strip()except (requests.exceptions.RequestException, Exception) as e:print(f"[translate] attempt {attempt + 1} failed: {e}")time.sleep(2)return text # ๋ฒ์ญ ์คํจ ์ ์๋ฌธ ๊ทธ๋๋กdef prepare_prompt(user_prompt: str, style_key: str) -> str:"""ํ๊ธ์ด๋ฉด ๋ฒ์ญํ๊ณ , ์ ํํ ์คํ์ผ ํ๋ฆฌ์ ์ ๋ถ์ฌ์ ์ต์ข ํ๋กฌํํธ๋ฅผ ๋ง๋ ๋ค."""prompt_en = openai_translate(user_prompt)style_suffix = STYLE_PRESETS.get(style_key, "")if style_suffix:final_prompt = f"{prompt_en}, {style_suffix}"else:final_prompt = prompt_enreturn final_prompt# ===== ์ด๋ฏธ์ง ์ ์ฅ =====def save_generated_image(image: Image.Image, prompt: str) -> str:timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")unique_id = str(uuid.uuid4())[:8]filename = f"{timestamp}_{unique_id}.png"filepath = os.path.join(SAVE_DIR, filename)image.save(filepath)# ๋ฉํ๋ฐ์ดํฐ ์ ์ฅmetadata_file = os.path.join(SAVE_DIR, "metadata.txt")with open(metadata_file, "a", encoding="utf-8") as f:f.write(f"{filename}|{prompt}|{timestamp}\n")return filepath# ===== Diffusion ํธ์ถ =====def run_pipeline(prompt: str, seed: int, width: int, height: int, guidance_scale: float, num_steps: int, lora_scale: float):generator = torch.Generator(device=device).manual_seed(int(seed))result = pipeline(prompt=prompt,guidance_scale=guidance_scale,num_inference_steps=num_steps,width=width,height=height,generator=generator,joint_attention_kwargs={"scale": lora_scale},).images[0]return result# ===== Gradio inference ๋ํผ =====@spaces.GPU(duration=60)def generate_image(user_prompt: str,style_key: str,seed: int = 42,randomize_seed: bool = True,width: int = 1024,height: int = 768,guidance_scale: float = 3.5,num_inference_steps: int = 30,lora_scale: float = 1.0,progress=None,):if randomize_seed:seed = random.randint(0, MAX_SEED)# 1) ๋ฒ์ญ + ์ฆ๊ฐfinal_prompt = prepare_prompt(user_prompt, style_key)# 2) ํ์ดํ๋ผ์ธ ํธ์ถimage = run_pipeline(final_prompt, seed, width, height, guidance_scale, num_inference_steps, lora_scale)# 3) ์ ์ฅsave_generated_image(image, final_prompt)return image, seed# ===== ์์ ํ๋กฌํํธ (ํ๊ตญ์ด/์์ด ํผ์ฉ ํ์ฉ) =====examples = ["๊น ํ๋ณด๊ฐ ํ๊ทน๊ธฐ๋ฅผ ๋ค๊ณ ํ์ฐฌ ๋ฏธ์๋ฅผ ์ง๋ ๋ชจ์ต์ 8K๋ก", # ํ๊ธ ์์ (์๋ ๋ฒ์ญ)"Mr. KIM raising both arms in celebration with a triumphant expression, showing victory and hope for the future.","๊น ํ๋ณด๊ฐ ๊ณต์์์ ์กฐ๊น ์ค ๊ฑด๊ฐํ ๋ฆฌ๋์ญ์ ๋ณด์ฌ์ฃผ๋ ์ฅ๋ฉด", # ํ๊ธ ์์]# ===== ์ปค์คํ CSS (๋ถ์ ํค ์ ์ง) =====custom_css = """:root {--color-primary: #8F1A3A;--color-secondary: #FF4B4B;--background-fill-primary: linear-gradient(to right, #FFF5F5, #FED7D7, #FEB2B2);}footer {visibility: hidden;}.gradio-container {background: var(--background-fill-primary);}.title {color: var(--color-primary)!important; font-size:3rem!important; font-weight:700!important; text-align:center; margin:1rem 0; font-family:'Playfair Display',serif;}.subtitle {color:#4A5568!important; font-size:1.2rem!important; text-align:center; margin-bottom:1.5rem; font-style:italic;}.collection-link {text-align:center; margin-bottom:2rem; font-size:1.1rem;}.collection-link a {color:var(--color-primary); text-decoration:underline; transition:color .3s ease;}.collection-link a:hover {color:var(--color-secondary);}.model-description{background:rgba(255,255,255,.8); border-radius:12px; padding:24px; margin:20px 0; box-shadow:0 4px 12px rgba(0,0,0,.05); border-left:5px solid var(--color-primary);}button.primary{background:var(--color-primary)!important; color:#fff!important; transition:all .3s ease;}button:hover{transform:translateY(-2px); box-shadow:0 5px 15px rgba(0,0,0,.1);}.input-container{border-radius:10px; box-shadow:0 2px 8px rgba(0,0,0,.05); background:rgba(255,255,255,.6); padding:20px; margin-bottom:1rem;}.advanced-settings{margin-top:1rem; padding:1rem; border-radius:10px; background:rgba(255,255,255,.6);}.example-region{background:rgba(255,255,255,.5); border-radius:10px; padding:1rem; margin-top:1rem;}"""# ===== Gradio UI =====with gr.Blocks(css=custom_css, analytics_enabled=False) as demo:gr.HTML('<div class="title">Mr. KIM in KOREA</div>')gr.HTML('<div class="collection-link"><a href="https://huggingface.co/collections/openfree/painting-art-ai-681453484ec15ef5978bbeb1" target="_blank">Visit the LoRA Model Collection</a></div>')with gr.Group(elem_classes="model-description"):gr.HTML("""<p>3 unmodified lines</p>""")# ===== ๋ฉ์ธ ์ ๋ ฅ =====with gr.Column():with gr.Row(elem_classes="input-container"):user_prompt = gr.Text(label="Prompt", max_lines=1, value=examples[0])style_select = gr.Radio(label="Style Preset", choices=list(STYLE_PRESETS.keys()), value="None", interactive=True)run_button = gr.Button("Generate", variant="primary")result_image = gr.Image(label="Generated Image")seed_output = gr.Number(label="Seed")# ===== ๊ณ ๊ธ ์ค์ =====with gr.Accordion("Advanced Settings", open=False, elem_classes="advanced-settings"):seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=42)randomize_seed = gr.Checkbox(label="Randomize seed", value=True)with gr.Row():width = gr.Slider(label="Width", minimum=256, maximum=MAX_IMAGE_SIZE, step=32, value=1024)height = gr.Slider(label="Height", minimum=256, maximum=MAX_IMAGE_SIZE, step=32, value=768)with gr.Row():guidance_scale = gr.Slider(label="Guidance scale", minimum=0.0, maximum=10.0, step=0.1, value=3.5)num_inference_steps = gr.Slider(label="Inference steps", minimum=1, maximum=50, step=1, value=30)lora_scale = gr.Slider(label="LoRA scale", minimum=0.0, maximum=1.0, step=0.1, value=1.0)# ===== ์์ ์์ญ =====with gr.Group(elem_classes="example-region"):gr.Markdown("### Examples")gr.Examples(examples=examples, inputs=user_prompt, cache_examples=False)# ===== ์ด๋ฒคํธ =====run_button.click(fn=generate_image,inputs=[user_prompt,style_select,seed,randomize_seed,width,2 unmodified linesnum_inference_steps,lora_scale,],outputs=[result_image, seed_output],)demo.queue()demo.launch()
app.py+146-202