File size: 40,550 Bytes
6464ac6 ccb0626 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 |
import os
import sys
import base64
import io
import logging
import tempfile
import traceback
import requests
from PIL import Image
import gradio as gr
from openai import OpenAI
import replicate
from google import genai
from google.genai import types
# ๋ก๊น
์ค์
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler("app.log"),
logging.StreamHandler(sys.stdout)
]
)
logger = logging.getLogger("image-enhancer-app")
# API ํด๋ผ์ด์ธํธ ์ด๊ธฐํ (์์ ํ๊ฒ)
openai_client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY", ""))
# Gemini ํด๋ผ์ด์ธํธ ์ด๊ธฐํ - API ํค๊ฐ ์์ ๋๋ง
gemini_api_key = os.environ.get("GEMINI_API_KEY")
if gemini_api_key and gemini_api_key.strip():
try:
gemini_client = genai.Client(api_key=gemini_api_key)
logger.info("Gemini client initialized successfully")
except Exception as e:
logger.error(f"Failed to initialize Gemini client: {e}")
gemini_client = None
else:
logger.warning("GEMINI_API_KEY not found or empty, Gemini client not initialized")
gemini_client = None
# ํ๊ฒฝ๋ณ์์์ ๋ฐฐ๊ฒฝ ํ๋กฌํํธ ๋ก๋
BACKGROUNDS_DATA = os.environ.get("BACKGROUNDS_DATA", "")
# ํ๊ฒฝ๋ณ์์์ ๋น๋ฐ๋ฒํธ ๋ก๋
APP_PASSWORD = os.environ.get("APP_PASSWORD", "")
if not BACKGROUNDS_DATA:
logger.error("BACKGROUNDS_DATA environment variable not found")
raise ValueError("BACKGROUNDS_DATA ํ๊ฒฝ๋ณ์๊ฐ ์ค์ ๋์ง ์์์ต๋๋ค.")
if not APP_PASSWORD:
logger.error("APP_PASSWORD environment variable not found")
raise ValueError("APP_PASSWORD ํ๊ฒฝ๋ณ์๊ฐ ์ค์ ๋์ง ์์์ต๋๋ค.")
# ํ๊ฒฝ๋ณ์ ๋ฐ์ดํฐ๋ฅผ ํ์ด์ฌ ์ฝ๋๋ก ์คํํ์ฌ ๋ฐฐ๊ฒฝ ๋์
๋๋ฆฌ๋ค ์์ฑ
try:
exec(BACKGROUNDS_DATA)
logger.info("Background data loaded from environment variable")
except Exception as e:
logger.error(f"Failed to load background data: {e}")
raise ValueError(f"๋ฐฐ๊ฒฝ ๋ฐ์ดํฐ ๋ก๋ ์คํจ: {e}")
# ์์ ํ์ผ ์ ์ฅ ํจ์
def save_uploaded_file(uploaded_file, suffix='.png'):
try:
logger.info(f"Processing uploaded file: {type(uploaded_file)}")
if uploaded_file is None:
logger.warning("Uploaded file is None")
return None
with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as temp_file:
temp_filename = temp_file.name
logger.info(f"Created temporary file: {temp_filename}")
# Gradio ์
๋ก๋ ํ์ผ ์ฒ๋ฆฌ
if isinstance(uploaded_file, str): # ์ด๋ฏธ ํ์ผ ๊ฒฝ๋ก์ธ ๊ฒฝ์ฐ
logger.info(f"Uploaded file is already a path: {uploaded_file}")
return uploaded_file
# PIL Image ์ฒ๋ฆฌ
if isinstance(uploaded_file, Image.Image):
logger.info("Uploaded file is a PIL Image")
uploaded_file.save(temp_filename, format="PNG")
return temp_filename
# ๋ฐ์ด๋๋ฆฌ ๋ฐ์ดํฐ ์ฒ๋ฆฌ
with open(temp_filename, "wb") as f:
if hasattr(uploaded_file, "read"): # ํ์ผ ๊ฐ์ฒด์ธ ๊ฒฝ์ฐ
logger.info("Processing file object")
content = uploaded_file.read()
f.write(content)
logger.info(f"Wrote {len(content)} bytes to {temp_filename}")
else: # ๋ฐ์ด๋๋ฆฌ ๋ฐ์ดํฐ์ธ ๊ฒฝ์ฐ
logger.info("Processing binary data")
f.write(uploaded_file)
logger.info(f"Wrote data to {temp_filename}")
return temp_filename
except Exception as e:
logger.error(f"Error saving uploaded file: {e}")
logger.error(traceback.format_exc())
return None
# ํ
์คํธ ๋ฒ์ญ ํจ์ (ํ๊ตญ์ด โ ์์ด) - Gemini 2.0 Flash ์ ์ฉ
def translate_to_english(text):
"""ํ๊ตญ์ด ํ
์คํธ๋ฅผ ์์ด๋ก ๋ฒ์ญ (Gemini 2.0 Flash ์ฌ์ฉ)"""
try:
if not text or not text.strip():
return ""
# Gemini ํด๋ผ์ด์ธํธ๊ฐ ์ด๊ธฐํ๋์๋์ง ํ์ธ
if gemini_client is None:
logger.warning("Gemini client not available, returning original text")
return text
# Gemini 2.0 Flash๋ฅผ ์ฌ์ฉํ ๋ฒ์ญ
try:
response = gemini_client.models.generate_content(
model="gemini-2.0-flash",
config=types.GenerateContentConfig(
system_instruction="You are a professional translator. Translate the given Korean text to English. Keep the translation natural and contextually appropriate for image generation prompts. If the text is already in English, return it as is. Only return the translated text without any additional explanation.",
max_output_tokens=200,
temperature=0.1
),
contents=[f"Translate this to English: {text}"]
)
translated = response.text.strip()
logger.info(f"Translated '{text}' to '{translated}' using Gemini 2.0 Flash")
return translated
except Exception as e:
logger.error(f"Gemini translation error: {e}")
logger.warning("Translation failed, returning original text")
return text
except Exception as e:
logger.error(f"Translation error: {e}")
return text
# ํ๋กฌํํธ ์์ฑ ํจ์ (์ข
ํก๋น์ ์์ฒญ์ฌํญ ํตํฉ)
def generate_prompt(background_type, background_name, user_request, aspect_ratio="1:1"):
# ๊ธฐ๋ณธ ๊ณ ์ ํ๋กฌํํธ (์ข
ํก๋น ์ ๋ณด ํฌํจ) - ์์ด๋ก ๋ณ๊ฒฝ
fixed_prompt = f"""
## Fixed Prompt (Required)
[Aspect Ratio: {aspect_ratio}]
[Foreground: all uploaded product images, preserve their original proportions and clarity]
[Preserve originals: keep the same random seed; maintain exact shape and aspect ratio; no vertical or horizontal scaling; do not alter any existing logos or text]
[Product sizing: ensure product images maintain at least 50% of their height relative to the background]
[Composition: products must be naturally composited with the background, maintain proper shadows aligned with lighting]
[Product placement: if products already exist in the background prompt, follow their exact arrangement and positioning]
"""
# ๋ฐฐ๊ฒฝ ํ๋กฌํํธ ์ ํ
if background_type == "์ฌํ ๋ฐฐ๊ฒฝ":
background_prompt = SIMPLE_BACKGROUNDS.get(background_name, "")
elif background_type == "์คํ๋์ค ๋ฐฐ๊ฒฝ":
background_prompt = STUDIO_BACKGROUNDS.get(background_name, "")
elif background_type == "์์ฐ ํ๊ฒฝ":
background_prompt = NATURE_BACKGROUNDS.get(background_name, "")
elif background_type == "์ค๋ด ํ๊ฒฝ":
background_prompt = INDOOR_BACKGROUNDS.get(background_name, "")
elif background_type == "ํน์๋ฐฐ๊ฒฝ":
background_prompt = SPECIAL_BACKGROUNDS.get(background_name, "")
elif background_type == "์ฃผ์ผ๋ฆฌ":
background_prompt = JEWELRY_BACKGROUNDS.get(background_name, "")
elif background_type == "ํน์ํจ๊ณผ":
background_prompt = SPECIAL_EFFECTS_BACKGROUNDS.get(background_name, "")
else:
background_prompt = "clean white background with soft even lighting"
# ์ฌ์ฉ์ ์์ฒญ์ฌํญ ์ฒ๋ฆฌ
if user_request and user_request.strip():
# ํ๊ตญ์ด ์์ฒญ์ฌํญ์ ์์ด๋ก ๋ฒ์ญ (Gemini 2.0 Flash ์ฌ์ฉ)
translated_request = translate_to_english(user_request)
# ๋ฒ์ญ๋ ์์ฒญ์ฌํญ์ ๋ฐฐ๊ฒฝ ํ๋กฌํํธ์ ํตํฉ
integrated_background = f"{background_prompt} Additionally, incorporate the following elements naturally into the scene: {translated_request}. Ensure these elements blend harmoniously with the existing background while maintaining the overall aesthetic and lighting."
# ์์ฒญ ํ๋กฌํํธ ์น์
(๋ฒ์ญ๋ ๋ด์ฉ ์ฌ์ฉ)
request_prompt = f"""
## Request Prompt
{translated_request}
"""
# ๋ฐฐ๊ฒฝ ํ๋กฌํํธ ์น์
background_section = f"""
## Background Prompt (Background Settings)
{integrated_background}
"""
else:
# ์์ฒญ์ฌํญ์ด ์๋ ๊ฒฝ์ฐ
request_prompt = f"""
## Request Prompt
No specific request
"""
# ์์ฒญ์ฌํญ์ด ์๋ ๊ฒฝ์ฐ ๊ธฐ๋ณธ ๋ฐฐ๊ฒฝ๋ง ์ฌ์ฉ
background_section = f"""
## Background Prompt (Background Settings)
{background_prompt}
"""
# ์ต์ข
ํ๋กฌํํธ ์กฐํฉ
final_prompt = fixed_prompt + request_prompt + background_section
return final_prompt
# ์ด๋ฏธ์ง ํธ์ง ๋ฐ ํ์ง ๊ฐ์ ํจ์
def edit_and_enhance_image(
prompt,
image,
quality_level="gpt",
aspect_ratio="1:1",
output_format="jpg",
enable_enhancement=True,
enhancement_level=2
):
try:
logger.info(f"Editing image with prompt: '{prompt[:50]}...' (truncated)")
logger.info(f"Parameters: quality_level={quality_level}, aspect_ratio={aspect_ratio}, output_format={output_format}")
logger.info(f"Enhancement requested: {enable_enhancement}, level: {enhancement_level}")
if image is None:
logger.error("No image provided")
return None, None, None, "์ด๋ฏธ์ง๋ฅผ ์
๋ก๋ํด์ผ ํฉ๋๋ค."
# ์ด๋ฏธ์ง ์ฒ๋ฆฌ
processed_image = None
temp_paths = [] # ๋์ค์ ์ ๋ฆฌํ ๊ฒฝ๋ก ์ถ์
img_path = save_uploaded_file(image)
if img_path:
logger.info(f"Saved image to temp path: {img_path}")
processed_image = open(img_path, "rb")
temp_paths.append(img_path)
else:
logger.error("Failed to save image")
return None, None, None, "์ด๋ฏธ์ง ์ฒ๋ฆฌ์ ์คํจํ์ต๋๋ค. ๋ค๋ฅธ ์ด๋ฏธ์ง๋ฅผ ์
๋ก๋ํด ๋ณด์ธ์."
# ๋ชจ๋ธ ์ ํ์ ๋ฐ๋ฅธ ์ฒ๋ฆฌ
edited_images = []
usage_info = ""
error_msg = None
try:
if quality_level == "gpt":
# GPT ๋ชจ๋ธ ์ฌ์ฉ
if not openai_client.api_key:
logger.error("OpenAI API key is not set")
return None, None, None, "OpenAI API ํค๊ฐ ์ค์ ๋์ง ์์์ต๋๋ค. API ํค๋ฅผ ์ค์ ํด์ฃผ์ธ์."
# ์ข
ํก๋น๋ฅผ ํฌ๊ธฐ๋ก ๋ณํ
size_mapping = {
"1:1": "1024x1024",
"3:2": "1536x1024",
"2:3": "1024x1536"
}
size = size_mapping.get(aspect_ratio, "1024x1024")
params = {
"prompt": prompt,
"model": "gpt-image-1",
"n": 1,
"size": size,
"image": processed_image
}
logger.info(f"Calling OpenAI API for image editing")
response = openai_client.images.edit(**params)
logger.info("OpenAI API call successful")
# ๊ฒฐ๊ณผ ์ฒ๋ฆฌ
for i, data in enumerate(response.data):
logger.info(f"Processing result image {i+1}/{len(response.data)}")
if hasattr(data, 'b64_json') and data.b64_json:
image_data = base64.b64decode(data.b64_json)
image = Image.open(io.BytesIO(image_data))
elif hasattr(data, 'url') and data.url:
response_url = requests.get(data.url)
image = Image.open(io.BytesIO(response_url.content))
else:
logger.warning(f"No image data found in response item {i+1}")
continue
# ์ด๋ฏธ์ง ํ์ ๋ณํ
if output_format.lower() != "png" and image.mode == "RGBA":
background = Image.new("RGB", image.size, (255, 255, 255))
background.paste(image, mask=image.split()[3])
image = background
edited_images.append(image)
usage_info = "์ด๋ฏธ์ง ํธ์ง ์๋ฃ (GPT ๋ชจ๋ธ ์ฌ์ฉ)"
else: # quality_level == "flux"
# Flux ๋ชจ๋ธ ์ฌ์ฉ (ํญ์ ๊ธฐ๋ณธ ํ์ง๊ฐ์ 1ํ ์ ์ฉ)
if not os.environ.get("REPLICATE_API_TOKEN"):
logger.error("Replicate API token is not set")
return None, None, None, "Replicate API ํ ํฐ์ด ์ค์ ๋์ง ์์์ต๋๋ค. API ํ ํฐ์ ์ค์ ํด์ฃผ์ธ์."
logger.info(f"Using Flux model for image editing")
# Flux ๋ชจ๋ธ๋ก ์ด๋ฏธ์ง ์์ฑ
output = replicate.run(
"black-forest-labs/flux-kontext-pro",
input={
"prompt": prompt,
"input_image": processed_image,
"output_format": output_format.lower(),
"aspect_ratio": aspect_ratio,
"safety_tolerance": 2
}
)
logger.info(f"Flux API response received")
# Flux API ์๋ต ์ฒ๋ฆฌ
flux_image = None
if output:
# output์ด ๋ฐ์ดํธ ์คํธ๋ฆผ์ธ ๊ฒฝ์ฐ
if hasattr(output, 'read'):
image_data = output.read()
flux_image = Image.open(io.BytesIO(image_data))
# output์ด URL์ธ ๊ฒฝ์ฐ
elif isinstance(output, str) and output.startswith('http'):
response_url = requests.get(output)
flux_image = Image.open(io.BytesIO(response_url.content))
# output์ด ๋ฐ์ด๋๋ฆฌ ๋ฐ์ดํฐ์ธ ๊ฒฝ์ฐ
else:
flux_image = Image.open(io.BytesIO(output))
# ์ด๋ฏธ์ง ํ์ ๋ณํ
if output_format.lower() != "png" and flux_image.mode == "RGBA":
background = Image.new("RGB", flux_image.size, (255, 255, 255))
background.paste(flux_image, mask=flux_image.split()[3])
flux_image = background
# Flux ๋ชจ๋ธ์ ํญ์ ์ฒซ ๋ฒ์งธ ํ์ง ๊ฐ์ ์ ์๋ ์ ์ฉ
try:
logger.info("Applying automatic first enhancement for Flux model")
# ์์ ํ์ผ๋ก ์ ์ฅ
temp_flux_path = tempfile.mktemp(suffix='.png')
flux_image.save(temp_flux_path)
temp_paths.append(temp_flux_path)
# ์ฒซ ๋ฒ์งธ ํ์ง ํฅ์ (Flux ๋ชจ๋ธ ๊ธฐ๋ณธ ์ ์ฉ)
first_enhanced_output = replicate.run(
"philz1337x/clarity-upscaler:dfad41707589d68ecdccd1dfa600d55a208f9310748e44bfe35b4a6291453d5e",
input={
"image": open(temp_flux_path, "rb"),
"scale_factor": 2,
"resemblance": 0.8,
"creativity": 0.2,
"output_format": output_format.lower(),
"prompt": prompt,
"negative_prompt": "(worst quality, low quality, normal quality:2)"
}
)
if first_enhanced_output and isinstance(first_enhanced_output, list) and len(first_enhanced_output) > 0:
first_enhanced_url = first_enhanced_output[0]
first_enhanced_response = requests.get(first_enhanced_url)
if first_enhanced_response.status_code == 200:
first_enhanced_image = Image.open(io.BytesIO(first_enhanced_response.content))
# ์ด๋ฏธ์ง ํ์ ๋ณํ
if output_format.lower() != "png" and first_enhanced_image.mode == "RGBA":
background = Image.new("RGB", first_enhanced_image.size, (255, 255, 255))
background.paste(first_enhanced_image, mask=first_enhanced_image.split()[3])
first_enhanced_image = background
edited_images.append(first_enhanced_image)
usage_info = "์ด๋ฏธ์ง ํธ์ง ์๋ฃ (Flux ๋ชจ๋ธ + ๊ธฐ๋ณธ ํ์ง๊ฐ์ ์ ์ฉ)"
logger.info("First enhancement completed for Flux model")
else:
# ์ฒซ ๋ฒ์งธ ํ์ง๊ฐ์ ์คํจ ์ ์๋ณธ ์ฌ์ฉ
edited_images.append(flux_image)
usage_info = "์ด๋ฏธ์ง ํธ์ง ์๋ฃ (Flux ๋ชจ๋ธ ์ฌ์ฉ, ๊ธฐ๋ณธ ํ์ง๊ฐ์ ์คํจ)"
else:
# ์ฒซ ๋ฒ์งธ ํ์ง๊ฐ์ ์คํจ ์ ์๋ณธ ์ฌ์ฉ
edited_images.append(flux_image)
usage_info = "์ด๋ฏธ์ง ํธ์ง ์๋ฃ (Flux ๋ชจ๋ธ ์ฌ์ฉ, ๊ธฐ๋ณธ ํ์ง๊ฐ์ ์คํจ)"
except Exception as e:
logger.error(f"Error in first enhancement for Flux: {e}")
# ์ฒซ ๋ฒ์งธ ํ์ง๊ฐ์ ์คํจ ์ ์๋ณธ ์ฌ์ฉ
edited_images.append(flux_image)
usage_info = f"์ด๋ฏธ์ง ํธ์ง ์๋ฃ (Flux ๋ชจ๋ธ ์ฌ์ฉ, ๊ธฐ๋ณธ ํ์ง๊ฐ์ ์ค๋ฅ: {str(e)})"
else:
logger.error("No output from Flux API")
error_msg = "Flux API์์ ์๋ต์ ๋ฐ์ง ๋ชปํ์ต๋๋ค."
except Exception as e:
if quality_level == "gpt":
logger.error(f"OpenAI API call error: {e}")
error_msg = f"OpenAI API ํธ์ถ ์ค๋ฅ: {str(e)}"
else:
logger.error(f"Flux API call error: {e}")
error_msg = f"Flux API ํธ์ถ ์ค๋ฅ: {str(e)}"
finally:
# ์์ ํ์ผ ์ ๋ฆฌ
if processed_image and hasattr(processed_image, 'close'):
processed_image.close()
# ํ์ง ํฅ์ ์ฒ๋ฆฌ (GPT ๋ชจ๋ธ์ ์ผ๋ฐ์ ์ธ ํ์ง๊ฐ์ , Flux ๋ชจ๋ธ์ 2์ฐจ ํ์ง๊ฐ์ )
enhanced_image = None
temp_image_path = None
if enable_enhancement and edited_images and not error_msg:
try:
if quality_level == "gpt":
# GPT ๋ชจ๋ธ: ์ผ๋ฐ์ ์ธ ํ์ง ๊ฐ์
logger.info(f"Enhancing GPT image with Replicate API, enhancement level: {enhancement_level}")
enhancement_info = "ํ์ง ๊ฐ์ "
else:
# Flux ๋ชจ๋ธ: 2์ฐจ ํ์ง ๊ฐ์ (์ด๋ฏธ 1์ฐจ๋ ์ ์ฉ๋จ)
logger.info(f"Applying second enhancement for Flux image, enhancement level: {enhancement_level}")
enhancement_info = "2์ฐจ ํ์ง ๊ฐ์ "
if not os.environ.get("REPLICATE_API_TOKEN"):
logger.error("Replicate API token is not set")
usage_info += f" | {enhancement_info} ์คํจ: Replicate API ํ ํฐ์ด ์ค์ ๋์ง ์์์ต๋๋ค."
else:
# ์์ ํ์ผ๋ก ์ ์ฅ
temp_image_path = tempfile.mktemp(suffix='.png')
edited_images[0].save(temp_image_path)
temp_paths.append(temp_image_path)
# Replicate API๋ก ํ์ง ํฅ์
output = replicate.run(
"philz1337x/clarity-upscaler:dfad41707589d68ecdccd1dfa600d55a208f9310748e44bfe35b4a6291453d5e",
input={
"image": open(temp_image_path, "rb"),
"scale_factor": enhancement_level,
"resemblance": 0.8,
"creativity": 0.2,
"output_format": output_format.lower(),
"prompt": prompt,
"negative_prompt": "(worst quality, low quality, normal quality:2)"
}
)
logger.info(f"Replicate API response: {output}")
if output and isinstance(output, list) and len(output) > 0:
enhanced_url = output[0]
enhanced_response = requests.get(enhanced_url)
if enhanced_response.status_code == 200:
enhanced_image = Image.open(io.BytesIO(enhanced_response.content))
if output_format.lower() != "png" and enhanced_image.mode == "RGBA":
background = Image.new("RGB", enhanced_image.size, (255, 255, 255))
background.paste(enhanced_image, mask=enhanced_image.split()[3])
enhanced_image = background
if quality_level == "gpt":
usage_info += f" | {enhancement_info} ์๋ฃ: Replicate Clarity Upscaler ์ฌ์ฉ"
else:
usage_info += f" | {enhancement_info} ์๋ฃ: ์ด 2ํ ํ์ง๊ฐ์ ์ ์ฉ"
else:
usage_info += f" | {enhancement_info} ์คํจ: ์ด๋ฏธ์ง ๋ค์ด๋ก๋ ์ค๋ฅ"
else:
usage_info += f" | {enhancement_info} ์คํจ: Replicate API ์๋ต ์์"
except Exception as e:
logger.error(f"Error enhancing image: {e}")
if quality_level == "gpt":
usage_info += f" | ํ์ง ๊ฐ์ ์คํจ: {str(e)}"
else:
usage_info += f" | 2์ฐจ ํ์ง ๊ฐ์ ์คํจ: {str(e)}"
# ์์ ํ์ผ ์ ๋ฆฌ
for path in temp_paths:
if os.path.exists(path):
try:
os.remove(path)
logger.info(f"Removed temp file: {path}")
except Exception as e:
logger.error(f"Error removing temp file {path}: {e}")
# ๊ฒฐ๊ณผ ๋ฐํ
if error_msg:
return None, None, None, error_msg
elif edited_images:
if enable_enhancement and enhanced_image:
return edited_images, [enhanced_image], usage_info, None
else:
return edited_images, None, usage_info, None
else:
return None, None, None, "์ด๋ฏธ์ง ํธ์ง์ ์คํจํ์ต๋๋ค."
except Exception as e:
logger.error(f"Error in edit_and_enhance_image function: {e}")
logger.error(traceback.format_exc())
return None, None, None, f"์๋ฌ ๋ฐ์: {str(e)}\n\n{traceback.format_exc()}"
# Gradio ์ธํฐํ์ด์ค ๊ตฌ์ฑ
def create_gradio_interface():
try:
logger.info("Creating Gradio interface")
with gr.Blocks(title="AI ์ด๋ฏธ์ง ํธ์ง ๋ฐ ํ์ง ๊ฐ์ ") as app:
gr.Markdown("# AI ์ด๋ฏธ์ง ํธ์ง ๋ฐ ํ์ง ๊ฐ์ ๋๊ตฌ")
# ๋น๋ฐ๋ฒํธ ์
๋ ฅ ํ๋
password_box = gr.Textbox(
label="๋น๋ฐ๋ฒํธ",
type="password",
placeholder="์ฌ์ฉํ๋ ค๋ฉด ๋น๋ฐ๋ฒํธ๋ฅผ ์
๋ ฅํ์ธ์",
interactive=True
)
# ์ด๋ฏธ์ง ํธ์ง ๋ฐ ํ์ง ๊ฐ์ ์ธํฐํ์ด์ค
with gr.Row():
with gr.Column():
# ์ํ ์ด๋ฏธ์ง ์
๋ก๋
image = gr.Image(label="์ํ ์ด๋ฏธ์ง ์
๋ก๋", type="pil")
with gr.Row():
with gr.Column():
background_type = gr.Radio(
choices=["์ฌํ ๋ฐฐ๊ฒฝ", "์คํ๋์ค ๋ฐฐ๊ฒฝ", "์์ฐ ํ๊ฒฝ", "์ค๋ด ํ๊ฒฝ", "ํน์๋ฐฐ๊ฒฝ", "์ฃผ์ผ๋ฆฌ", "ํน์ํจ๊ณผ"],
label="๋ฐฐ๊ฒฝ ์ ํ",
value="์ฌํ ๋ฐฐ๊ฒฝ"
)
# ๋๋กญ๋ค์ด ์ปดํฌ๋ํธ๋ค
simple_dropdown = gr.Dropdown(
choices=list(SIMPLE_BACKGROUNDS.keys()),
value=list(SIMPLE_BACKGROUNDS.keys())[0] if SIMPLE_BACKGROUNDS else None,
label="์ฌํ ๋ฐฐ๊ฒฝ ์ ํ",
visible=True,
interactive=True
)
studio_dropdown = gr.Dropdown(
choices=list(STUDIO_BACKGROUNDS.keys()),
value=list(STUDIO_BACKGROUNDS.keys())[0] if STUDIO_BACKGROUNDS else None,
label="์คํ๋์ค ๋ฐฐ๊ฒฝ ์ ํ",
visible=False,
interactive=True
)
nature_dropdown = gr.Dropdown(
choices=list(NATURE_BACKGROUNDS.keys()),
value=list(NATURE_BACKGROUNDS.keys())[0] if NATURE_BACKGROUNDS else None,
label="์์ฐ ํ๊ฒฝ ์ ํ",
visible=False,
interactive=True
)
indoor_dropdown = gr.Dropdown(
choices=list(INDOOR_BACKGROUNDS.keys()),
value=list(INDOOR_BACKGROUNDS.keys())[0] if INDOOR_BACKGROUNDS else None,
label="์ค๋ด ํ๊ฒฝ ์ ํ",
visible=False,
interactive=True
)
special_dropdown = gr.Dropdown(
choices=list(SPECIAL_BACKGROUNDS.keys()),
value=list(SPECIAL_BACKGROUNDS.keys())[0] if SPECIAL_BACKGROUNDS else None,
label="ํน์๋ฐฐ๊ฒฝ ์ ํ",
visible=False,
interactive=True
)
jewelry_dropdown = gr.Dropdown(
choices=list(JEWELRY_BACKGROUNDS.keys()),
value=list(JEWELRY_BACKGROUNDS.keys())[0] if JEWELRY_BACKGROUNDS else None,
label="์ฃผ์ผ๋ฆฌ ๋ฐฐ๊ฒฝ ์ ํ",
visible=False,
interactive=True
)
special_effects_dropdown = gr.Dropdown(
choices=list(SPECIAL_EFFECTS_BACKGROUNDS.keys()),
value=list(SPECIAL_EFFECTS_BACKGROUNDS.keys())[0] if SPECIAL_EFFECTS_BACKGROUNDS else None,
label="ํน์ํจ๊ณผ ๋ฐฐ๊ฒฝ ์ ํ",
visible=False,
interactive=True
)
# ๋๋กญ๋ค์ด ๋ณ๊ฒฝ ํจ์
def update_dropdowns(bg_type):
return {
simple_dropdown: gr.update(visible=(bg_type == "์ฌํ ๋ฐฐ๊ฒฝ")),
studio_dropdown: gr.update(visible=(bg_type == "์คํ๋์ค ๋ฐฐ๊ฒฝ")),
nature_dropdown: gr.update(visible=(bg_type == "์์ฐ ํ๊ฒฝ")),
indoor_dropdown: gr.update(visible=(bg_type == "์ค๋ด ํ๊ฒฝ")),
special_dropdown: gr.update(visible=(bg_type == "ํน์๋ฐฐ๊ฒฝ")),
jewelry_dropdown: gr.update(visible=(bg_type == "์ฃผ์ผ๋ฆฌ")),
special_effects_dropdown: gr.update(visible=(bg_type == "ํน์ํจ๊ณผ"))
}
background_type.change(
fn=update_dropdowns,
inputs=[background_type],
outputs=[simple_dropdown, studio_dropdown, nature_dropdown, indoor_dropdown, special_dropdown, jewelry_dropdown, special_effects_dropdown]
)
# ์์ฒญ์ฌํญ ์
๋ ฅ
request_text = gr.Textbox(
label="์์ฒญ์ฌํญ",
placeholder="์ํ ์ด๋ฏธ์ง์ ์ ์ฉํ ์คํ์ผ, ๋ถ์๊ธฐ, ํน๋ณ ์์ฒญ์ฌํญ ๋ฑ์ ์
๋ ฅํ์ธ์.",
lines=3
)
# ์๋ก์ด ์ต์
๋ค
quality_level = gr.Radio(
label="ํ์ง ๋ ๋ฒจ",
choices=["gpt", "flux"],
value="flux",
info="GPT: GPT ๋ชจ๋ธ (๊ณ ํ์ง), ์ผ๋ฐ: Flux ๋ชจ๋ธ (๋น ๋ฅธ ์ฒ๋ฆฌ + ๊ธฐ๋ณธ ํ์ง๊ฐ์ )"
)
aspect_ratio = gr.Dropdown(
label="์ข
ํก๋น",
choices=["1:1", "3:2", "2:3"],
value="1:1"
)
output_format = gr.Dropdown(
label="์ด๋ฏธ์ง ํ์",
choices=["jpg", "png"],
value="jpg"
)
# ํ์ง ๊ฐ์ ์ต์
enable_enhancement = gr.Checkbox(
label="์ถ๊ฐ ํ์ง ๊ฐ์ ",
value=False,
info="GPT: 1ํ ํ์ง๊ฐ์ , Flux: 2์ฐจ ํ์ง๊ฐ์ (๊ธฐ๋ณธ 1ํ + ์ถ๊ฐ 1ํ)"
)
enhancement_level = gr.Slider(label="ํ์ง ๊ฐ์ ๋ ๋ฒจ", minimum=1, maximum=4, value=2, step=1, visible=False)
# ํ๋กฌํํธ ์์ฑ ๋ฒํผ
generate_prompt_btn = gr.Button("ํ๋กฌํํธ๋ง ์์ฑ")
# ํธ์ง ๋ฒํผ
edit_btn = gr.Button("์ด๋ฏธ์ง ํธ์ง ๋ฐ ํ์ง ๊ฐ์ ")
with gr.Column():
with gr.Row():
with gr.Column():
gr.Markdown("## ํธ์ง๋ ์ด๋ฏธ์ง")
original_output = gr.Gallery(label="ํธ์ง ๊ฒฐ๊ณผ", preview=True)
original_download = gr.File(label="ํธ์ง ์ด๋ฏธ์ง ๋ค์ด๋ก๋", interactive=False)
with gr.Column():
gr.Markdown("## ํ์ง ๊ฐ์ ๋ ์ด๋ฏธ์ง")
enhanced_output = gr.Gallery(label="ํ์ง ๊ฐ์ ๊ฒฐ๊ณผ", preview=True)
enhanced_download = gr.File(label="๊ฐ์ ์ด๋ฏธ์ง ๋ค์ด๋ก๋", interactive=False)
# ํ๋กฌํํธ ์ถ๋ ฅ
prompt_output = gr.Textbox(label="์์ฑ๋ ํ๋กฌํํธ", lines=10, interactive=False)
info = gr.Textbox(label="์ฒ๋ฆฌ ์ ๋ณด", interactive=False)
error = gr.Textbox(label="์ค๋ฅ ๋ฉ์์ง", interactive=False, visible=True)
# ํ๋กฌํํธ๋ง ์์ฑํ๋ ํจ์ (๋น๋ฐ๋ฒํธ ์ฒดํฌ ํฌํจ)
def generate_prompt_with_password_check(password, bg_type, simple, studio, nature, indoor, special, jewelry, special_effects, request_text, aspect_ratio):
# ๋น๋ฐ๋ฒํธ ํ์ธ
if password != APP_PASSWORD:
return "๋น๋ฐ๋ฒํธ๊ฐ ํ๋ ธ์ต๋๋ค. ์ฌ๋ฐ๋ฅธ ๋น๋ฐ๋ฒํธ๋ฅผ ์
๋ ฅํด์ฃผ์ธ์."
# ๋ฐฐ๊ฒฝ ์ ํ
background_name = ""
if bg_type == "์ฌํ ๋ฐฐ๊ฒฝ":
background_name = simple
elif bg_type == "์คํ๋์ค ๋ฐฐ๊ฒฝ":
background_name = studio
elif bg_type == "์์ฐ ํ๊ฒฝ":
background_name = nature
elif bg_type == "์ค๋ด ํ๊ฒฝ":
background_name = indoor
elif bg_type == "ํน์๋ฐฐ๊ฒฝ":
background_name = special
elif bg_type == "์ฃผ์ผ๋ฆฌ":
background_name = jewelry
elif bg_type == "ํน์ํจ๊ณผ":
background_name = special_effects
# ํ๋กฌํํธ ์์ฑ (์ข
ํก๋น ํฌํจ)
prompt = generate_prompt(bg_type, background_name, request_text, aspect_ratio)
return prompt
# ๋น๋ฐ๋ฒํธ ํ์ธ ํจ์
def check_password(password, *args):
if password != APP_PASSWORD:
return (
[], # original_output
None, # original_download
[], # enhanced_output
None, # enhanced_download
"", # prompt_output
"", # info
"๋น๋ฐ๋ฒํธ๊ฐ ํ๋ ธ์ต๋๋ค. ์ฌ๋ฐ๋ฅธ ๋น๋ฐ๋ฒํธ๋ฅผ ์
๋ ฅํด์ฃผ์ธ์." # error
)
# ์ด๋ฏธ์ง ํธ์ง ์์ฒญ ์ฒ๋ฆฌ
image, bg_type, simple, studio, nature, indoor, special, jewelry, special_effects, request_text, quality_level, aspect_ratio, output_format, enable_enhancement = args
# ๋ฐฐ๊ฒฝ ์ ํ
background_name = ""
if bg_type == "์ฌํ ๋ฐฐ๊ฒฝ":
background_name = simple
elif bg_type == "์คํ๋์ค ๋ฐฐ๊ฒฝ":
background_name = studio
elif bg_type == "์์ฐ ํ๊ฒฝ":
background_name = nature
elif bg_type == "์ค๋ด ํ๊ฒฝ":
background_name = indoor
elif bg_type == "ํน์๋ฐฐ๊ฒฝ":
background_name = special
elif bg_type == "์ฃผ์ผ๋ฆฌ":
background_name = jewelry
elif bg_type == "ํน์ํจ๊ณผ":
background_name = special_effects
# ํ๋กฌํํธ ์์ฑ
prompt = generate_prompt(bg_type, background_name, request_text, aspect_ratio)
# ์ด๋ฏธ์ง ํธ์ง ๋ฐ ํ์ง ๊ฐ์ ์คํ
original_images, enhanced_images, usage_info, error_msg = edit_and_enhance_image(
prompt, image, quality_level, aspect_ratio, output_format, enable_enhancement, 2
)
# ์ด๋ฏธ์ง ์ ์ฅ ๋ฐ ๋ค์ด๋ก๋ ํ์ผ ์ค๋น
original_path = None
enhanced_path = None
if error_msg:
logger.error(f"Error returned from edit_and_enhance_image: {error_msg}")
return (
[], # original_output
None, # original_download
[], # enhanced_output
None, # enhanced_download
prompt, # prompt_output
"", # info
error_msg # error
)
else:
# ์๋ณธ ํธ์ง ์ด๋ฏธ์ง ์ ์ฅ
if original_images and len(original_images) > 0:
try:
original_path = f"original_image.{output_format}"
original_images[0].save(original_path)
logger.info(f"Saved original image to {original_path}")
except Exception as e:
logger.error(f"Error saving original image: {e}")
# ํ์ง ๊ฐ์ ์ด๋ฏธ์ง ์ ์ฅ
if enhanced_images and len(enhanced_images) > 0:
try:
enhanced_path = f"enhanced_image.{output_format}"
enhanced_images[0].save(enhanced_path)
logger.info(f"Saved enhanced image to {enhanced_path}")
except Exception as e:
logger.error(f"Error saving enhanced image: {e}")
# ๊ฒฐ๊ณผ ๋ฐํ
return (
original_images if original_images else [], # original_output
original_path, # original_download
enhanced_images if enhanced_images else [], # enhanced_output
enhanced_path, # enhanced_download
prompt, # prompt_output
usage_info, # info
"" # error (๋น ๋ฌธ์์ด๋ก ์ค์ )
)
# ํ๋กฌํํธ ์์ฑ ๋ฒํผ ํด๋ฆญ ์ด๋ฒคํธ
generate_prompt_btn.click(
fn=generate_prompt_with_password_check,
inputs=[
password_box,
background_type,
simple_dropdown, studio_dropdown, nature_dropdown, indoor_dropdown, special_dropdown,
jewelry_dropdown, special_effects_dropdown,
request_text, aspect_ratio
],
outputs=[prompt_output]
)
# ํธ์ง ๋ฒํผ ํด๋ฆญ ์ด๋ฒคํธ
edit_btn.click(
fn=check_password,
inputs=[
password_box,
image, background_type,
simple_dropdown, studio_dropdown, nature_dropdown, indoor_dropdown, special_dropdown,
jewelry_dropdown, special_effects_dropdown,
request_text, quality_level, aspect_ratio, output_format, enable_enhancement
],
outputs=[
original_output, original_download,
enhanced_output, enhanced_download,
prompt_output, info, error
]
)
logger.info("Gradio interface created successfully")
return app
except Exception as e:
logger.error(f"Error creating Gradio interface: {e}")
logger.error(traceback.format_exc())
raise
# ์ฑ ์คํ
if __name__ == "__main__":
try:
logger.info("Starting application")
# imgs ๋๋ ํ ๋ฆฌ ํ์ธ/์์ฑ
os.makedirs("imgs", exist_ok=True)
logger.info("์ด๋ฏธ์ง ๋๋ ํ ๋ฆฌ ์ค๋น ์๋ฃ")
app = create_gradio_interface()
logger.info("Launching Gradio app")
app.launch(share=True)
except Exception as e:
logger.error(f"Error running app: {e}")
logger.error(traceback.format_exc()) |