ssboost commited on
Commit
f34d9b8
·
verified ·
1 Parent(s): 1413c13

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +267 -102
app.py CHANGED
@@ -1,4 +1,3 @@
1
- import os
2
  import sys
3
  import base64
4
  import io
@@ -6,6 +5,7 @@ import logging
6
  import tempfile
7
  import traceback
8
  import requests
 
9
  from PIL import Image
10
  import gradio as gr
11
  from openai import OpenAI
@@ -24,54 +24,6 @@ logging.basicConfig(
24
  )
25
  logger = logging.getLogger("image-enhancer-app")
26
 
27
- # 환경변수로부터 배경 설정 로드
28
- def load_backgrounds():
29
- """환경변수 BACKGROUNDS_CONFIG로부터 배경 설정을 로드합니다."""
30
- import json
31
-
32
- backgrounds_json = os.environ.get("BACKGROUNDS_CONFIG", "")
33
-
34
- if not backgrounds_json:
35
- logger.warning("BACKGROUNDS_CONFIG 환경변수가 설정되지 않았습니다. 기본값을 사용합니다.")
36
- return {
37
- "SIMPLE_BACKGROUNDS": {"기본 화이트": "clean white background"},
38
- "STUDIO_BACKGROUNDS": {"기본 스튜디오": "studio background"},
39
- "NATURE_BACKGROUNDS": {"기본 자연": "nature background"},
40
- "INDOOR_BACKGROUNDS": {"기본 실내": "indoor background"},
41
- "SPECIAL_BACKGROUNDS": {"기본 특수": "special background"},
42
- "JEWELRY_BACKGROUNDS": {"기본 주얼리": "jewelry background"},
43
- "SPECIAL_EFFECTS_BACKGROUNDS": {"기본 효과": "special effects background"}
44
- }
45
-
46
- try:
47
- backgrounds_data = json.loads(backgrounds_json)
48
- logger.info("환경변수로부터 배경 설정을 성공적으로 로드했습니다.")
49
- return backgrounds_data
50
- except json.JSONDecodeError as e:
51
- logger.error(f"배경 설정 JSON 파싱 오류: {e}")
52
- return {}
53
-
54
- # 배경 설정 로드
55
- backgrounds_data = load_backgrounds()
56
- SIMPLE_BACKGROUNDS = backgrounds_data.get("SIMPLE_BACKGROUNDS", {})
57
- STUDIO_BACKGROUNDS = backgrounds_data.get("STUDIO_BACKGROUNDS", {})
58
- NATURE_BACKGROUNDS = backgrounds_data.get("NATURE_BACKGROUNDS", {})
59
- INDOOR_BACKGROUNDS = backgrounds_data.get("INDOOR_BACKGROUNDS", {})
60
- SPECIAL_BACKGROUNDS = backgrounds_data.get("SPECIAL_BACKGROUNDS", {})
61
- JEWELRY_BACKGROUNDS = backgrounds_data.get("JEWELRY_BACKGROUNDS", {})
62
- SPECIAL_EFFECTS_BACKGROUNDS = backgrounds_data.get("SPECIAL_EFFECTS_BACKGROUNDS", {})
63
-
64
- # 환경변수로부터 모델 설정 로드
65
- IMAGE_EDIT_MODEL_GPT = os.environ.get("IMAGE_EDIT_MODEL_GPT", "gpt-image-1")
66
- IMAGE_EDIT_MODEL_FLUX = os.environ.get("IMAGE_EDIT_MODEL_FLUX", "black-forest-labs/flux-kontext-pro")
67
- TRANSLATION_MODEL = os.environ.get("TRANSLATION_MODEL", "gemini-2.0-flash")
68
- ENHANCEMENT_MODEL = os.environ.get("ENHANCEMENT_MODEL", "philz1337x/clarity-upscaler:dfad41707589d68ecdccd1dfa600d55a208f9310748e44bfe35b4a6291453d5e")
69
-
70
- logger.info(f"이미지 편집 모델 (GPT): {IMAGE_EDIT_MODEL_GPT}")
71
- logger.info(f"이미지 편집 모델 (Flux): {IMAGE_EDIT_MODEL_FLUX}")
72
- logger.info(f"번역 모델: {TRANSLATION_MODEL}")
73
- logger.info(f"화질 개선 모델: {ENHANCEMENT_MODEL}")
74
-
75
  # API 클라이언트 초기화 (안전하게)
76
  openai_client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY", ""))
77
 
@@ -88,6 +40,148 @@ else:
88
  logger.warning("GEMINI_API_KEY not found or empty, Gemini client not initialized")
89
  gemini_client = None
90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
  # 임시 파일 저장 함수
92
  def save_uploaded_file(uploaded_file, suffix='.png'):
93
  try:
@@ -130,9 +224,9 @@ def save_uploaded_file(uploaded_file, suffix='.png'):
130
  logger.error(traceback.format_exc())
131
  return None
132
 
133
- # 텍스트 번역 함수 (한국어 → 영어) - 환경변수 모델 사용
134
  def translate_to_english(text):
135
- """한국어 텍스트를 영어로 번역 (환경변수 모델 사용)"""
136
  try:
137
  if not text or not text.strip():
138
  return ""
@@ -142,10 +236,10 @@ def translate_to_english(text):
142
  logger.warning("Gemini client not available, returning original text")
143
  return text
144
 
145
- # 환경변수에서 설정된 번역 모델 사용
146
  try:
147
  response = gemini_client.models.generate_content(
148
- model=TRANSLATION_MODEL,
149
  config=types.GenerateContentConfig(
150
  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.",
151
  max_output_tokens=200,
@@ -155,11 +249,11 @@ def translate_to_english(text):
155
  )
156
 
157
  translated = response.text.strip()
158
- logger.info(f"Translated '{text}' to '{translated}' using {TRANSLATION_MODEL}")
159
  return translated
160
 
161
  except Exception as e:
162
- logger.error(f"Translation error with {TRANSLATION_MODEL}: {e}")
163
  logger.warning("Translation failed, returning original text")
164
  return text
165
 
@@ -200,7 +294,7 @@ def generate_prompt(background_type, background_name, user_request, aspect_ratio
200
 
201
  # 사용자 요청사항 처리
202
  if user_request and user_request.strip():
203
- # 한국어 요청사항을 영어로 번역
204
  translated_request = translate_to_english(user_request)
205
 
206
  # 번역된 요청사항을 배경 프롬프트에 통합
@@ -289,13 +383,13 @@ def edit_and_enhance_image(
289
 
290
  params = {
291
  "prompt": prompt,
292
- "model": IMAGE_EDIT_MODEL_GPT,
293
  "n": 1,
294
  "size": size,
295
  "image": processed_image
296
  }
297
 
298
- logger.info(f"Calling OpenAI API for image editing with model: {IMAGE_EDIT_MODEL_GPT}")
299
  response = openai_client.images.edit(**params)
300
  logger.info("OpenAI API call successful")
301
 
@@ -321,7 +415,7 @@ def edit_and_enhance_image(
321
 
322
  edited_images.append(image)
323
 
324
- usage_info = f"이미지 편집 완료 ({IMAGE_EDIT_MODEL_GPT} 모델 사용)"
325
 
326
  else: # quality_level == "flux"
327
  # Flux 모델 사용 (항상 기본 화질개선 1회 적용)
@@ -329,11 +423,11 @@ def edit_and_enhance_image(
329
  logger.error("Replicate API token is not set")
330
  return None, None, None, "Replicate API 토큰이 설정되지 않았습니다. API 토큰을 설정해주세요."
331
 
332
- logger.info(f"Using Flux model for image editing: {IMAGE_EDIT_MODEL_FLUX}")
333
 
334
  # Flux 모델로 이미지 생성
335
  output = replicate.run(
336
- IMAGE_EDIT_MODEL_FLUX,
337
  input={
338
  "prompt": prompt,
339
  "input_image": processed_image,
@@ -368,7 +462,7 @@ def edit_and_enhance_image(
368
 
369
  # Flux 모델은 항상 첫 번째 화질 개선을 자동 적용
370
  try:
371
- logger.info(f"Applying automatic first enhancement for Flux model using: {ENHANCEMENT_MODEL}")
372
 
373
  # 임시 파일로 저장
374
  temp_flux_path = tempfile.mktemp(suffix='.png')
@@ -377,7 +471,7 @@ def edit_and_enhance_image(
377
 
378
  # 첫 번째 화질 향상 (Flux 모델 기본 적용)
379
  first_enhanced_output = replicate.run(
380
- ENHANCEMENT_MODEL,
381
  input={
382
  "image": open(temp_flux_path, "rb"),
383
  "scale_factor": 2,
@@ -403,22 +497,22 @@ def edit_and_enhance_image(
403
  first_enhanced_image = background
404
 
405
  edited_images.append(first_enhanced_image)
406
- usage_info = f"이미지 편집 완료 ({IMAGE_EDIT_MODEL_FLUX} + 기본 화질개선 적용)"
407
  logger.info("First enhancement completed for Flux model")
408
  else:
409
  # 첫 번째 화질개선 실패 시 원본 사용
410
  edited_images.append(flux_image)
411
- usage_info = f"이미지 편집 완료 ({IMAGE_EDIT_MODEL_FLUX} 사용, 기본 화질개선 실패)"
412
  else:
413
  # 첫 번째 화질개선 실패 시 원본 사용
414
  edited_images.append(flux_image)
415
- usage_info = f"이미지 편집 완료 ({IMAGE_EDIT_MODEL_FLUX} 사용, 기본 화질개선 실패)"
416
 
417
  except Exception as e:
418
  logger.error(f"Error in first enhancement for Flux: {e}")
419
  # 첫 번째 화질개선 실패 시 원본 사용
420
  edited_images.append(flux_image)
421
- usage_info = f"이미지 편집 완료 ({IMAGE_EDIT_MODEL_FLUX} 사용, 기본 화질개선 오류: {str(e)})"
422
 
423
  else:
424
  logger.error("No output from Flux API")
@@ -445,11 +539,11 @@ def edit_and_enhance_image(
445
  try:
446
  if quality_level == "gpt":
447
  # GPT 모델: 일반적인 화질 개선
448
- logger.info(f"Enhancing GPT image with {ENHANCEMENT_MODEL}, enhancement level: {enhancement_level}")
449
  enhancement_info = "화질 개선"
450
  else:
451
  # Flux 모델: 2차 화질 개선 (이미 1차는 적용됨)
452
- logger.info(f"Applying second enhancement for Flux image with {ENHANCEMENT_MODEL}, enhancement level: {enhancement_level}")
453
  enhancement_info = "2차 화질 개선"
454
 
455
  if not os.environ.get("REPLICATE_API_TOKEN"):
@@ -463,7 +557,7 @@ def edit_and_enhance_image(
463
 
464
  # Replicate API로 화질 향상
465
  output = replicate.run(
466
- ENHANCEMENT_MODEL,
467
  input={
468
  "image": open(temp_image_path, "rb"),
469
  "scale_factor": enhancement_level,
@@ -475,7 +569,7 @@ def edit_and_enhance_image(
475
  }
476
  )
477
 
478
- logger.info(f"Enhancement API response: {output}")
479
 
480
  if output and isinstance(output, list) and len(output) > 0:
481
  enhanced_url = output[0]
@@ -489,13 +583,13 @@ def edit_and_enhance_image(
489
  enhanced_image = background
490
 
491
  if quality_level == "gpt":
492
- usage_info += f" | {enhancement_info} 완료: {ENHANCEMENT_MODEL} 사용"
493
  else:
494
  usage_info += f" | {enhancement_info} 완료: 총 2회 화질개선 적용"
495
  else:
496
  usage_info += f" | {enhancement_info} 실패: 이미지 다운로드 오류"
497
  else:
498
- usage_info += f" | {enhancement_info} 실패: Enhancement API 응답 없음"
499
 
500
  except Exception as e:
501
  logger.error(f"Error enhancing image: {e}")
@@ -558,58 +652,70 @@ def create_gradio_interface():
558
  value="심플 배경"
559
  )
560
 
561
- # 드롭다운 컴포넌트들
 
 
 
 
 
 
 
 
 
 
 
 
562
  simple_dropdown = gr.Dropdown(
563
- choices=list(SIMPLE_BACKGROUNDS.keys()),
564
- value=list(SIMPLE_BACKGROUNDS.keys())[0] if SIMPLE_BACKGROUNDS else None,
565
  label="심플 배경 선택",
566
  visible=True,
567
  interactive=True
568
  )
569
 
570
  studio_dropdown = gr.Dropdown(
571
- choices=list(STUDIO_BACKGROUNDS.keys()),
572
- value=list(STUDIO_BACKGROUNDS.keys())[0] if STUDIO_BACKGROUNDS else None,
573
  label="스튜디오 배경 선택",
574
  visible=False,
575
  interactive=True
576
  )
577
 
578
  nature_dropdown = gr.Dropdown(
579
- choices=list(NATURE_BACKGROUNDS.keys()),
580
- value=list(NATURE_BACKGROUNDS.keys())[0] if NATURE_BACKGROUNDS else None,
581
  label="자연 환경 선택",
582
  visible=False,
583
  interactive=True
584
  )
585
 
586
  indoor_dropdown = gr.Dropdown(
587
- choices=list(INDOOR_BACKGROUNDS.keys()),
588
- value=list(INDOOR_BACKGROUNDS.keys())[0] if INDOOR_BACKGROUNDS else None,
589
  label="실내 환경 선택",
590
  visible=False,
591
  interactive=True
592
  )
593
 
594
  special_dropdown = gr.Dropdown(
595
- choices=list(SPECIAL_BACKGROUNDS.keys()),
596
- value=list(SPECIAL_BACKGROUNDS.keys())[0] if SPECIAL_BACKGROUNDS else None,
597
  label="특수배경 선택",
598
  visible=False,
599
  interactive=True
600
  )
601
 
602
  jewelry_dropdown = gr.Dropdown(
603
- choices=list(JEWELRY_BACKGROUNDS.keys()),
604
- value=list(JEWELRY_BACKGROUNDS.keys())[0] if JEWELRY_BACKGROUNDS else None,
605
  label="주얼리 배경 선택",
606
  visible=False,
607
  interactive=True
608
  )
609
 
610
  special_effects_dropdown = gr.Dropdown(
611
- choices=list(SPECIAL_EFFECTS_BACKGROUNDS.keys()),
612
- value=list(SPECIAL_EFFECTS_BACKGROUNDS.keys())[0] if SPECIAL_EFFECTS_BACKGROUNDS else None,
613
  label="특수효과 배경 선택",
614
  visible=False,
615
  interactive=True
@@ -617,14 +723,58 @@ def create_gradio_interface():
617
 
618
  # 드롭다운 변경 함수
619
  def update_dropdowns(bg_type):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
620
  return {
621
- simple_dropdown: gr.update(visible=(bg_type == "심플 배경")),
622
- studio_dropdown: gr.update(visible=(bg_type == "스튜디오 배경")),
623
- nature_dropdown: gr.update(visible=(bg_type == "자연 환경")),
624
- indoor_dropdown: gr.update(visible=(bg_type == "실내 환경")),
625
- special_dropdown: gr.update(visible=(bg_type == "특수배경")),
626
- jewelry_dropdown: gr.update(visible=(bg_type == "주얼리")),
627
- special_effects_dropdown: gr.update(visible=(bg_type == "특수효과"))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
628
  }
629
 
630
  background_type.change(
@@ -645,7 +795,7 @@ def create_gradio_interface():
645
  label="품질 레벨",
646
  choices=["gpt", "flux"],
647
  value="flux",
648
- info="GPT: GPT 모델 (고품질), Flux: Flux 모델 (빠른 처리 + 기본 화질개선)"
649
  )
650
 
651
  aspect_ratio = gr.Dropdown(
@@ -693,8 +843,8 @@ def create_gradio_interface():
693
 
694
  # 프롬프트만 생성하는 함수 (비밀번호 체크 포함)
695
  def generate_prompt_with_password_check(password, bg_type, simple, studio, nature, indoor, special, jewelry, special_effects, request_text, aspect_ratio):
696
- # 비밀번호 확인
697
- if password != "1089":
698
  return "비밀번호가 틀렸습니다. 올바른 비밀번호를 입력해주세요."
699
 
700
  # 배경 선택
@@ -720,7 +870,7 @@ def create_gradio_interface():
720
 
721
  # 비밀번호 확인 함수
722
  def check_password(password, *args):
723
- if password != "1089":
724
  return (
725
  [], # original_output
726
  None, # original_download
@@ -844,15 +994,30 @@ def create_gradio_interface():
844
  # 앱 실행
845
  if __name__ == "__main__":
846
  try:
847
- logger.info("Starting application")
848
 
849
  # imgs 디렉토리 확인/생성
850
  os.makedirs("imgs", exist_ok=True)
851
  logger.info("이미지 디렉토리 준비 완료")
852
 
 
 
 
 
 
 
 
 
 
 
 
 
 
853
  app = create_gradio_interface()
854
- logger.info("Launching Gradio app")
 
855
  app.launch(share=True)
 
856
  except Exception as e:
857
- logger.error(f"Error running app: {e}")
858
  logger.error(traceback.format_exc())
 
 
1
  import sys
2
  import base64
3
  import io
 
5
  import tempfile
6
  import traceback
7
  import requests
8
+ import json
9
  from PIL import Image
10
  import gradio as gr
11
  from openai import OpenAI
 
24
  )
25
  logger = logging.getLogger("image-enhancer-app")
26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  # API 클라이언트 초기화 (안전하게)
28
  openai_client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY", ""))
29
 
 
40
  logger.warning("GEMINI_API_KEY not found or empty, Gemini client not initialized")
41
  gemini_client = None
42
 
43
+ # 설정값들을 환경변수에서 로드하는 함수들
44
+ def get_app_password():
45
+ """환경변수에서 앱 비밀번호를 가져옵니다."""
46
+ password = os.environ.get("APP_PASSWORD")
47
+ if password:
48
+ logger.info("App password loaded from environment variable")
49
+ return password
50
+ else:
51
+ logger.warning("APP_PASSWORD environment variable not found, using default password")
52
+ return "1089" # 기본 비밀번호
53
+
54
+ # 배경 데이터를 환경변수에서 로드하는 함수
55
+ def load_backgrounds_from_env():
56
+ """환경변수에서 배경 데이터를 로드합니다."""
57
+ try:
58
+ # 환경변수에서 JSON 문자열로 저장된 배경 데이터 로드
59
+ backgrounds_data = os.environ.get("BACKGROUNDS_DATA")
60
+ if backgrounds_data:
61
+ logger.info("Loading backgrounds data from environment variable")
62
+ return json.loads(backgrounds_data)
63
+ else:
64
+ logger.warning("BACKGROUNDS_DATA environment variable not found, using default backgrounds")
65
+ return get_default_backgrounds()
66
+ except Exception as e:
67
+ logger.error(f"Error loading backgrounds from environment: {e}")
68
+ logger.info("Falling back to default backgrounds")
69
+ return get_default_backgrounds()
70
+
71
+ def get_default_backgrounds():
72
+ """기본 배경 데이터를 반환합니다."""
73
+ return {
74
+ "SIMPLE_BACKGROUNDS": {
75
+ "화이트 기본": "A clean, minimalistic digital background scene featuring a seamless pure white backdrop and a smooth white surface. The lighting is bright and evenly diffused from above, eliminating harsh shadows and creating a crisp, studio-lit environment. There are no products or objects present — only the empty background remains. The composition is ultra-clean and modern, ideal for overlaying lifestyle or hydration-related products. The mood is fresh, light, and professional. Ultra-sharp, studio-quality, high resolution, photo-realistic",
76
+ "회색 투톤": "A clean and minimal product photography background featuring a seamless, near-white light gray tone across both the backdrop and surface. The entire scene is evenly lit with bright, diffused lighting from above, eliminating harsh shadows and producing a calm, sophisticated atmosphere. The composition remains empty — with no products or objects present — offering a soft and airy visual ideal for modern lifestyle, wellness, or eco-friendly branding. The lighting gently enhances spatial depth without creating reflections. Ultra-clear, studio-quality, photo-realistic"
77
+ },
78
+ "STUDIO_BACKGROUNDS": {
79
+ "연녹색 장미 정원": "A high-resolution, commercial-style digital photograph of a sophisticated background setup designed for a luxury product shoot. The scene features soft green tones with lush fern leaves and creamy pastel roses (white, peach, blush pink) artfully arranged. The flowers are placed on a white polished marble platform with soft veining, surrounded by elegant foliage. The lighting is natural and diffused from the top left, producing soft shadows and a serene mood. There is no product in the scene — only the floral arrangement and surface remain, creating a refined, editorial-quality backdrop suitable for overlaying product photography. No object should be centered; the composition should remain balanced and inviting. ultra-detailed, 8K quality, photo-realistic studio setting."
80
+ },
81
+ "NATURE_BACKGROUNDS": {
82
+ "작은 파도가 있는 해변": "A serene and natural beach-themed product photography scene. The background features warm golden sand and gentle turquoise waves softly rolling onto the shore, with white foam catching the golden light of a late afternoon sun. Around the edges of the frame — but not overlapping the center foreground — small natural elements like seashells, conch shells, and bits of coral are randomly scattered with varied sizes, positions, and quantities to evoke a natural, organic arrangement. The product area remains clean and visually unobstructed to maintain focus. Lighting is soft and ambient with subtle natural shadows to highlight the uploaded product. The overall atmosphere is peaceful, sunlit, and summer-inspired. Ultra photo-realistic, studio-quality"
83
+ },
84
+ "INDOOR_BACKGROUNDS": {
85
+ "기본 책상": "A bright, Scandinavian-inspired home office featuring a matte white desk with crisp edges placed against a soft sage green wall. Natural daylight gently enters from the side, casting diffused shadows across the surface and enhancing the calm, focused atmosphere. On the desk are neatly arranged everyday essentials like a few colorful pens, a potted plant, and an open notebook. A neutral-toned ergonomic chair is tucked under the desk, and the surrounding area is intentionally minimal to emphasize clarity and productivity. The entire setting evokes a modern, clutter-free work environment., photo-realistic, high-resolution."
86
+ },
87
+ "SPECIAL_BACKGROUNDS": {
88
+ "네이비 빈티지 플로럴 벽지": "A richly detailed studio photography background featuring an ornate, vintage-inspired floral wallpaper design. The backdrop showcases vibrant red, pink, yellow, and green botanical motifs intricately woven across a deep navy blue base. The floral pattern is symmetrical and bold, giving the composition an artistic, maximalist aesthetic. The floor is a clean, solid blue surface, providing visual contrast and modern balance. Lighting is bright and evenly diffused, emphasizing both the product and the intricate details of the wallpaper. Ideal for showcasing creative, lifestyle, or design-forward products. Ultra-detailed, high-resolution, ."
89
+ },
90
+ "JEWELRY_BACKGROUNDS": {
91
+ "화이트 미러 스팟 라이트": "A luxury jewelry product photoshoot featuring a soft white backdrop and a polished white mirrored surface. A single focused overhead light beam softly illuminates the center of the scene, fading smoothly toward the edges with a clean gradient. The glossy white surface reflects the jewelry item with crystal clarity — capturing the shape, facets, and symmetry of the design in perfect mirror-like detail. The reflection appears sharp, clean, and vertically aligned beneath the product, enhancing the sense of luxury and balance. The atmosphere is premium, minimal, and luminous — ideal for high-end diamond earrings or bridal jewelry. Ultra-detailed, studio-quality, photo-realistic"
92
+ },
93
+ "SPECIAL_EFFECTS_BACKGROUNDS": {
94
+ "블루블랙 큰 물방울 효과": "A deep black and vivid cobalt blue gradient backdrop with a reflective surface splashed by crystalline water droplets frozen mid-air. Backlighting enhances shimmer and motion, creating a sense of waterproof resilience. High-impact, ultra-detailed."
95
+ }
96
+ }
97
+
98
+ # 배경 데이터 로드
99
+ backgrounds_data = load_backgrounds_from_env()
100
+ SIMPLE_BACKGROUNDS = backgrounds_data.get("SIMPLE_BACKGROUNDS", {})
101
+ STUDIO_BACKGROUNDS = backgrounds_data.get("STUDIO_BACKGROUNDS", {})
102
+ NATURE_BACKGROUNDS = backgrounds_data.get("NATURE_BACKGROUNDS", {})
103
+ INDOOR_BACKGROUNDS = backgrounds_data.get("INDOOR_BACKGROUNDS", {})
104
+ SPECIAL_BACKGROUNDS = backgrounds_data.get("SPECIAL_BACKGROUNDS", {})
105
+ JEWELRY_BACKGROUNDS = backgrounds_data.get("JEWELRY_BACKGROUNDS", {})
106
+ SPECIAL_EFFECTS_BACKGROUNDS = backgrounds_data.get("SPECIAL_EFFECTS_BACKGROUNDS", {})
107
+
108
+ # 앱 비밀번호 로드
109
+ APP_PASSWORD = get_app_password()
110
+
111
+ # 환경변수 검증 함수
112
+ def validate_environment_variables():
113
+ """필수 환경변수가 설정되었는지 확인합니다."""
114
+ logger.info("=== 환경변수 검증 시작 ===")
115
+
116
+ # 비밀번호 검증
117
+ logger.info(f"APP_PASSWORD: {'설정됨' if os.environ.get('APP_PASSWORD') else '기본값 사용 (1089)'}")
118
+
119
+ # API 키 검증
120
+ openai_key = os.environ.get("OPENAI_API_KEY")
121
+ replicate_token = os.environ.get("REPLICATE_API_TOKEN")
122
+ gemini_key = os.environ.get("GEMINI_API_KEY")
123
+
124
+ logger.info(f"OPENAI_API_KEY: {'설정됨' if openai_key else '설정되지 않음'}")
125
+ logger.info(f"REPLICATE_API_TOKEN: {'설정됨' if replicate_token else '설정되지 않음'}")
126
+ logger.info(f"GEMINI_API_KEY: {'설정됨' if gemini_key else '설정되지 않음'}")
127
+
128
+ # 배경 데이터 검증
129
+ backgrounds_data_env = os.environ.get("BACKGROUNDS_DATA")
130
+ if backgrounds_data_env:
131
+ logger.info("BACKGROUNDS_DATA: 환경변수에서 설정됨")
132
+ try:
133
+ parsed_data = json.loads(backgrounds_data_env)
134
+ bg_counts = {
135
+ category: len(backgrounds)
136
+ for category, backgrounds in parsed_data.items()
137
+ }
138
+ logger.info(f"배경 데이터 로드 성공: {bg_counts}")
139
+
140
+ # 각 카테고리별 상세 정보
141
+ for category, backgrounds in parsed_data.items():
142
+ if backgrounds:
143
+ sample_keys = list(backgrounds.keys())[:3] # 처음 3개만 표시
144
+ logger.info(f" {category}: {len(backgrounds)}개 - 예시: {sample_keys}")
145
+ else:
146
+ logger.warning(f" {category}: 비어있음")
147
+
148
+ except Exception as e:
149
+ logger.error(f"BACKGROUNDS_DATA JSON 파싱 오류: {e}")
150
+ logger.error("배경 데이터 형식이 올바른지 확인해주세요.")
151
+ else:
152
+ logger.info("BACKGROUNDS_DATA: 환경변수 없음 (기본값 사용)")
153
+
154
+ # 실제 로드된 배경 데이터 확인
155
+ actual_bg_counts = {
156
+ "SIMPLE_BACKGROUNDS": len(SIMPLE_BACKGROUNDS),
157
+ "STUDIO_BACKGROUNDS": len(STUDIO_BACKGROUNDS),
158
+ "NATURE_BACKGROUNDS": len(NATURE_BACKGROUNDS),
159
+ "INDOOR_BACKGROUNDS": len(INDOOR_BACKGROUNDS),
160
+ "SPECIAL_BACKGROUNDS": len(SPECIAL_BACKGROUNDS),
161
+ "JEWELRY_BACKGROUNDS": len(JEWELRY_BACKGROUNDS),
162
+ "SPECIAL_EFFECTS_BACKGROUNDS": len(SPECIAL_EFFECTS_BACKGROUNDS)
163
+ }
164
+ logger.info(f"실제 로드된 배경 데이터: {actual_bg_counts}")
165
+
166
+ # 경고 메시지
167
+ missing_apis = []
168
+ if not openai_key:
169
+ missing_apis.append("OpenAI (GPT 모델 사용 불가)")
170
+ if not replicate_token:
171
+ missing_apis.append("Replicate (Flux 모델 및 화질개선 사용 불가)")
172
+ if not gemini_key:
173
+ missing_apis.append("Gemini (번역 기능 사용 불가)")
174
+
175
+ if missing_apis:
176
+ logger.warning(f"누락된 API 키로 인해 다음 기능이 제한됩니다: {', '.join(missing_apis)}")
177
+ else:
178
+ logger.info("모든 API 키가 설정되어 전체 기능 사용 가능합니다.")
179
+
180
+ logger.info("=== 환경변수 검증 완료 ===")
181
+
182
+ # 환경변수 검증 실행
183
+ validate_environment_variables()
184
+
185
  # 임시 파일 저장 함수
186
  def save_uploaded_file(uploaded_file, suffix='.png'):
187
  try:
 
224
  logger.error(traceback.format_exc())
225
  return None
226
 
227
+ # 텍스트 번역 함수 (한국어 → 영어) - Gemini 2.0 Flash 전용
228
  def translate_to_english(text):
229
+ """한국어 텍스트를 영어로 번역 (Gemini 2.0 Flash 사용)"""
230
  try:
231
  if not text or not text.strip():
232
  return ""
 
236
  logger.warning("Gemini client not available, returning original text")
237
  return text
238
 
239
+ # Gemini 2.0 Flash를 사용한 번역
240
  try:
241
  response = gemini_client.models.generate_content(
242
+ model="gemini-2.0-flash",
243
  config=types.GenerateContentConfig(
244
  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.",
245
  max_output_tokens=200,
 
249
  )
250
 
251
  translated = response.text.strip()
252
+ logger.info(f"Translated '{text}' to '{translated}' using Gemini 2.0 Flash")
253
  return translated
254
 
255
  except Exception as e:
256
+ logger.error(f"Gemini translation error: {e}")
257
  logger.warning("Translation failed, returning original text")
258
  return text
259
 
 
294
 
295
  # 사용자 요청사항 처리
296
  if user_request and user_request.strip():
297
+ # 한국어 요청사항을 영어로 번역 (Gemini 2.0 Flash 사용)
298
  translated_request = translate_to_english(user_request)
299
 
300
  # 번역된 요청사항을 배경 프롬프트에 통합
 
383
 
384
  params = {
385
  "prompt": prompt,
386
+ "model": "gpt-image-1",
387
  "n": 1,
388
  "size": size,
389
  "image": processed_image
390
  }
391
 
392
+ logger.info(f"Calling OpenAI API for image editing")
393
  response = openai_client.images.edit(**params)
394
  logger.info("OpenAI API call successful")
395
 
 
415
 
416
  edited_images.append(image)
417
 
418
+ usage_info = "이미지 편집 완료 (GPT 모델 사용)"
419
 
420
  else: # quality_level == "flux"
421
  # Flux 모델 사용 (항상 기본 화질개선 1회 적용)
 
423
  logger.error("Replicate API token is not set")
424
  return None, None, None, "Replicate API 토큰이 설정되지 않았습니다. API 토큰을 설정해주세요."
425
 
426
+ logger.info(f"Using Flux model for image editing")
427
 
428
  # Flux 모델로 이미지 생성
429
  output = replicate.run(
430
+ "black-forest-labs/flux-kontext-pro",
431
  input={
432
  "prompt": prompt,
433
  "input_image": processed_image,
 
462
 
463
  # Flux 모델은 항상 첫 번째 화질 개선을 자동 적용
464
  try:
465
+ logger.info("Applying automatic first enhancement for Flux model")
466
 
467
  # 임시 파일로 저장
468
  temp_flux_path = tempfile.mktemp(suffix='.png')
 
471
 
472
  # 첫 번째 화질 향상 (Flux 모델 기본 적용)
473
  first_enhanced_output = replicate.run(
474
+ "philz1337x/clarity-upscaler:dfad41707589d68ecdccd1dfa600d55a208f9310748e44bfe35b4a6291453d5e",
475
  input={
476
  "image": open(temp_flux_path, "rb"),
477
  "scale_factor": 2,
 
497
  first_enhanced_image = background
498
 
499
  edited_images.append(first_enhanced_image)
500
+ usage_info = "이미지 편집 완료 (Flux 모델 + 기본 화질개선 적용)"
501
  logger.info("First enhancement completed for Flux model")
502
  else:
503
  # 첫 번째 화질개선 실패 시 원본 사용
504
  edited_images.append(flux_image)
505
+ usage_info = "이미지 편집 완료 (Flux 모델 사용, 기본 화질개선 실패)"
506
  else:
507
  # 첫 번째 화질개선 실패 시 원본 사용
508
  edited_images.append(flux_image)
509
+ usage_info = "이미지 편집 완료 (Flux 모델 사용, 기본 화질개선 실패)"
510
 
511
  except Exception as e:
512
  logger.error(f"Error in first enhancement for Flux: {e}")
513
  # 첫 번째 화질개선 실패 시 원본 사용
514
  edited_images.append(flux_image)
515
+ usage_info = f"이미지 편집 완료 (Flux 모델 사용, 기본 화질개선 오류: {str(e)})"
516
 
517
  else:
518
  logger.error("No output from Flux API")
 
539
  try:
540
  if quality_level == "gpt":
541
  # GPT 모델: 일반적인 화질 개선
542
+ logger.info(f"Enhancing GPT image with Replicate API, enhancement level: {enhancement_level}")
543
  enhancement_info = "화질 개선"
544
  else:
545
  # Flux 모델: 2차 화질 개선 (이미 1차는 적용됨)
546
+ logger.info(f"Applying second enhancement for Flux image, enhancement level: {enhancement_level}")
547
  enhancement_info = "2차 화질 개선"
548
 
549
  if not os.environ.get("REPLICATE_API_TOKEN"):
 
557
 
558
  # Replicate API로 화질 향상
559
  output = replicate.run(
560
+ "philz1337x/clarity-upscaler:dfad41707589d68ecdccd1dfa600d55a208f9310748e44bfe35b4a6291453d5e",
561
  input={
562
  "image": open(temp_image_path, "rb"),
563
  "scale_factor": enhancement_level,
 
569
  }
570
  )
571
 
572
+ logger.info(f"Replicate API response: {output}")
573
 
574
  if output and isinstance(output, list) and len(output) > 0:
575
  enhanced_url = output[0]
 
583
  enhanced_image = background
584
 
585
  if quality_level == "gpt":
586
+ usage_info += f" | {enhancement_info} 완료: Replicate Clarity Upscaler 사용"
587
  else:
588
  usage_info += f" | {enhancement_info} 완료: 총 2회 화질개선 적용"
589
  else:
590
  usage_info += f" | {enhancement_info} 실패: 이미지 다운로드 오류"
591
  else:
592
+ usage_info += f" | {enhancement_info} 실패: Replicate API 응답 없음"
593
 
594
  except Exception as e:
595
  logger.error(f"Error enhancing image: {e}")
 
652
  value="심플 배경"
653
  )
654
 
655
+ # 드롭다운 컴포넌트들 - 환경변수에서 로드된 데이터 사용
656
+ simple_choices = list(SIMPLE_BACKGROUNDS.keys()) if SIMPLE_BACKGROUNDS else []
657
+ studio_choices = list(STUDIO_BACKGROUNDS.keys()) if STUDIO_BACKGROUNDS else []
658
+ nature_choices = list(NATURE_BACKGROUNDS.keys()) if NATURE_BACKGROUNDS else []
659
+ indoor_choices = list(INDOOR_BACKGROUNDS.keys()) if INDOOR_BACKGROUNDS else []
660
+ special_choices = list(SPECIAL_BACKGROUNDS.keys()) if SPECIAL_BACKGROUNDS else []
661
+ jewelry_choices = list(JEWELRY_BACKGROUNDS.keys()) if JEWELRY_BACKGROUNDS else []
662
+ special_effects_choices = list(SPECIAL_EFFECTS_BACKGROUNDS.keys()) if SPECIAL_EFFECTS_BACKGROUNDS else []
663
+
664
+ # 환경변수가 없어서 배경 데이터가 비어있는 경우 경고
665
+ if not any([simple_choices, studio_choices, nature_choices, indoor_choices, special_choices, jewelry_choices, special_effects_choices]):
666
+ logger.error("모든 배경 카테고리가 비어있습니다. BACKGROUNDS_DATA 환경변수를 설정해주세요.")
667
+
668
  simple_dropdown = gr.Dropdown(
669
+ choices=simple_choices,
670
+ value=simple_choices[0] if simple_choices else None,
671
  label="심플 배경 선택",
672
  visible=True,
673
  interactive=True
674
  )
675
 
676
  studio_dropdown = gr.Dropdown(
677
+ choices=studio_choices,
678
+ value=studio_choices[0] if studio_choices else None,
679
  label="스튜디오 배경 선택",
680
  visible=False,
681
  interactive=True
682
  )
683
 
684
  nature_dropdown = gr.Dropdown(
685
+ choices=nature_choices,
686
+ value=nature_choices[0] if nature_choices else None,
687
  label="자연 환경 선택",
688
  visible=False,
689
  interactive=True
690
  )
691
 
692
  indoor_dropdown = gr.Dropdown(
693
+ choices=indoor_choices,
694
+ value=indoor_choices[0] if indoor_choices else None,
695
  label="실내 환경 선택",
696
  visible=False,
697
  interactive=True
698
  )
699
 
700
  special_dropdown = gr.Dropdown(
701
+ choices=special_choices,
702
+ value=special_choices[0] if special_choices else None,
703
  label="특수배경 선택",
704
  visible=False,
705
  interactive=True
706
  )
707
 
708
  jewelry_dropdown = gr.Dropdown(
709
+ choices=jewelry_choices,
710
+ value=jewelry_choices[0] if jewelry_choices else None,
711
  label="주얼리 배경 선택",
712
  visible=False,
713
  interactive=True
714
  )
715
 
716
  special_effects_dropdown = gr.Dropdown(
717
+ choices=special_effects_choices,
718
+ value=special_effects_choices[0] if special_effects_choices else None,
719
  label="특수효과 배경 선택",
720
  visible=False,
721
  interactive=True
 
723
 
724
  # 드롭다운 변경 함수
725
  def update_dropdowns(bg_type):
726
+ """배경 유형에 따라 드롭다운을 업데이트합니다."""
727
+ logger.info(f"Updating dropdowns for background type: {bg_type}")
728
+
729
+ # 각 배경 카테고리의 키 목록 가져오기
730
+ simple_choices = list(SIMPLE_BACKGROUNDS.keys()) if SIMPLE_BACKGROUNDS else []
731
+ studio_choices = list(STUDIO_BACKGROUNDS.keys()) if STUDIO_BACKGROUNDS else []
732
+ nature_choices = list(NATURE_BACKGROUNDS.keys()) if NATURE_BACKGROUNDS else []
733
+ indoor_choices = list(INDOOR_BACKGROUNDS.keys()) if INDOOR_BACKGROUNDS else []
734
+ special_choices = list(SPECIAL_BACKGROUNDS.keys()) if SPECIAL_BACKGROUNDS else []
735
+ jewelry_choices = list(JEWELRY_BACKGROUNDS.keys()) if JEWELRY_BACKGROUNDS else []
736
+ special_effects_choices = list(SPECIAL_EFFECTS_BACKGROUNDS.keys()) if SPECIAL_EFFECTS_BACKGROUNDS else []
737
+
738
+ # 디버깅 정보 로깅
739
+ logger.info(f"Available choices - Simple: {len(simple_choices)}, Studio: {len(studio_choices)}, Nature: {len(nature_choices)}")
740
+ logger.info(f"Indoor: {len(indoor_choices)}, Special: {len(special_choices)}, Jewelry: {len(jewelry_choices)}, Effects: {len(special_effects_choices)}")
741
+
742
  return {
743
+ simple_dropdown: gr.update(
744
+ visible=(bg_type == "심플 배경"),
745
+ choices=simple_choices,
746
+ value=simple_choices[0] if simple_choices else None
747
+ ),
748
+ studio_dropdown: gr.update(
749
+ visible=(bg_type == "스튜디오 배경"),
750
+ choices=studio_choices,
751
+ value=studio_choices[0] if studio_choices else None
752
+ ),
753
+ nature_dropdown: gr.update(
754
+ visible=(bg_type == "자연 환경"),
755
+ choices=nature_choices,
756
+ value=nature_choices[0] if nature_choices else None
757
+ ),
758
+ indoor_dropdown: gr.update(
759
+ visible=(bg_type == "실내 환경"),
760
+ choices=indoor_choices,
761
+ value=indoor_choices[0] if indoor_choices else None
762
+ ),
763
+ special_dropdown: gr.update(
764
+ visible=(bg_type == "특수배경"),
765
+ choices=special_choices,
766
+ value=special_choices[0] if special_choices else None
767
+ ),
768
+ jewelry_dropdown: gr.update(
769
+ visible=(bg_type == "주얼리"),
770
+ choices=jewelry_choices,
771
+ value=jewelry_choices[0] if jewelry_choices else None
772
+ ),
773
+ special_effects_dropdown: gr.update(
774
+ visible=(bg_type == "특수효과"),
775
+ choices=special_effects_choices,
776
+ value=special_effects_choices[0] if special_effects_choices else None
777
+ )
778
  }
779
 
780
  background_type.change(
 
795
  label="품질 레벨",
796
  choices=["gpt", "flux"],
797
  value="flux",
798
+ info="GPT: GPT 모델 (고품질), 일반: Flux 모델 (빠른 처리 + 기본 화질개선)"
799
  )
800
 
801
  aspect_ratio = gr.Dropdown(
 
843
 
844
  # 프롬프트만 생성하는 함수 (비밀번호 체크 포함)
845
  def generate_prompt_with_password_check(password, bg_type, simple, studio, nature, indoor, special, jewelry, special_effects, request_text, aspect_ratio):
846
+ # 비밀번호 확인 - 환경변수에서 가져온 비밀번호와 비교
847
+ if password != APP_PASSWORD:
848
  return "비밀번호가 틀렸습니다. 올바른 비밀번호를 입력해주세요."
849
 
850
  # 배경 선택
 
870
 
871
  # 비밀번호 확인 함수
872
  def check_password(password, *args):
873
+ if password != APP_PASSWORD:
874
  return (
875
  [], # original_output
876
  None, # original_download
 
994
  # 앱 실행
995
  if __name__ == "__main__":
996
  try:
997
+ logger.info("=== AI 이미지 편집 및 화질 개선 애플리케이션 시작 ===")
998
 
999
  # imgs 디렉토리 확인/생성
1000
  os.makedirs("imgs", exist_ok=True)
1001
  logger.info("이미지 디렉토리 준비 완료")
1002
 
1003
+ # 환경변수 재검증 (앱 시작 시)
1004
+ logger.info("앱 시작 전 환경변수 최종 확인")
1005
+ if not APP_PASSWORD:
1006
+ logger.warning("비밀번호가 설정되지 않았습니다. 기본 비밀번호(1089)를 사용합니다.")
1007
+
1008
+ if not any([
1009
+ os.environ.get("OPENAI_API_KEY"),
1010
+ os.environ.get("REPLICATE_API_TOKEN"),
1011
+ os.environ.get("GEMINI_API_KEY")
1012
+ ]):
1013
+ logger.warning("API 키가 하나도 설정되지 않았습니다. 기능이 제한될 수 있습니다.")
1014
+
1015
+ # Gradio 인터페이스 생성 및 실행
1016
  app = create_gradio_interface()
1017
+ logger.info("Gradio 인터페이스 생성 완료")
1018
+ logger.info("애플리케이션을 시작합니다...")
1019
  app.launch(share=True)
1020
+
1021
  except Exception as e:
1022
+ logger.error(f"애플리케이션 실행 오류 발생: {e}")
1023
  logger.error(traceback.format_exc())