Update app.py
Browse files
app.py
CHANGED
@@ -24,9 +24,19 @@ logger = logging.getLogger(__name__)
|
|
24 |
def get_api_endpoint():
|
25 |
"""환경변수에서 API 엔드포인트를 가져오는 함수"""
|
26 |
endpoint = os.getenv('API_ENDPOINT')
|
|
|
|
|
27 |
if not endpoint:
|
28 |
-
logger.error("API_ENDPOINT 환경변수가 설정되지 않았습니다.")
|
29 |
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
30 |
return endpoint
|
31 |
|
32 |
def encode_image_to_base64(image):
|
@@ -59,6 +69,36 @@ def call_api_endpoint(endpoint_url, data):
|
|
59 |
return {"error": f"API 호출 실패: {str(e)}"}
|
60 |
|
61 |
# ========== 이미지 생성기 관련 함수 ==========
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
62 |
def translate_prompt_to_english(prompt):
|
63 |
"""프롬프트 번역 - API 엔드포인트로 전달"""
|
64 |
endpoint_url = get_api_endpoint()
|
@@ -73,14 +113,49 @@ def translate_prompt_to_english(prompt):
|
|
73 |
try:
|
74 |
result = call_api_endpoint(f"{endpoint_url}/translate", data)
|
75 |
if "error" in result:
|
76 |
-
logger.warning(
|
77 |
return prompt
|
78 |
return result.get("translated_prompt", prompt)
|
79 |
except Exception as e:
|
80 |
-
logger.warning(
|
81 |
return prompt
|
82 |
|
83 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
84 |
"""프롬프트 전처리 - 기존 로직 유지"""
|
85 |
has_img1 = image1 is not None
|
86 |
has_img2 = image2 is not None
|
@@ -210,12 +285,12 @@ def process_images_with_prompt(image1, image2, image3, prompt, variation_index=0
|
|
210 |
else:
|
211 |
last_error = status
|
212 |
retry_count += 1
|
213 |
-
logger.warning(f"이미지 생성 실패, 재시도 {retry_count}/{max_retries}
|
214 |
time.sleep(1)
|
215 |
except Exception as e:
|
216 |
-
last_error =
|
217 |
retry_count += 1
|
218 |
-
logger.exception(f"이미지 처리 중 오류 발생, 재시도 {retry_count}/{max_retries}
|
219 |
time.sleep(1)
|
220 |
|
221 |
return None, f"최대 재시도 횟수({max_retries}회) 초과 후 실패: {last_error}", prompt
|
@@ -873,12 +948,12 @@ with gr.Blocks(css=custom_css, theme=gr.themes.Default(
|
|
873 |
|
874 |
# 애플리케이션 실행
|
875 |
if __name__ == "__main__":
|
876 |
-
# API 엔드포인트 확인
|
877 |
endpoint = get_api_endpoint()
|
878 |
if endpoint:
|
879 |
logger.info("컨트롤 타워가 시작되었습니다.")
|
880 |
else:
|
881 |
-
logger.warning("
|
882 |
|
883 |
demo.queue()
|
884 |
demo.launch(share=False, inbrowser=True, width="100%")
|
|
|
24 |
def get_api_endpoint():
|
25 |
"""환경변수에서 API 엔드포인트를 가져오는 함수"""
|
26 |
endpoint = os.getenv('API_ENDPOINT')
|
27 |
+
|
28 |
+
# 환경변수가 없으면 None 반환
|
29 |
if not endpoint:
|
|
|
30 |
return None
|
31 |
+
|
32 |
+
# 허깅페이스 스페이스 형식 처리
|
33 |
+
if "/" in endpoint and not endpoint.startswith("http"):
|
34 |
+
# "username/spacename" 형식을 전체 URL로 변환
|
35 |
+
endpoint = f"https://{endpoint.replace('/', '-')}.hf.space"
|
36 |
+
elif not endpoint.startswith("http"):
|
37 |
+
# 단순 도메인인 경우 https 추가
|
38 |
+
endpoint = f"https://{endpoint}"
|
39 |
+
|
40 |
return endpoint
|
41 |
|
42 |
def encode_image_to_base64(image):
|
|
|
69 |
return {"error": f"API 호출 실패: {str(e)}"}
|
70 |
|
71 |
# ========== 이미지 생성기 관련 함수 ==========
|
72 |
+
def get_api_endpoint():
|
73 |
+
"""환경변수에서 API 엔드포인트를 가져오는 함수"""
|
74 |
+
endpoint = os.getenv('API_ENDPOINT')
|
75 |
+
|
76 |
+
# 환경변수가 없으면 기본값 사용 (테스트용)
|
77 |
+
if not endpoint:
|
78 |
+
endpoint = "https://happydoggg-03hd74jd.hf.space"
|
79 |
+
logger.info("환경변수가 설정되지 않아 기본 엔드포인트를 사용합니다.")
|
80 |
+
|
81 |
+
# 허깅페이스 스페이스 형식 처리
|
82 |
+
if "/" in endpoint and not endpoint.startswith("http"):
|
83 |
+
# "username/spacename" 형식을 전체 URL로 변환
|
84 |
+
endpoint = f"https://{endpoint.replace('/', '-')}.hf.space"
|
85 |
+
elif not endpoint.startswith("http"):
|
86 |
+
# 단순 도메인인 경우 https 추가
|
87 |
+
endpoint = f"https://{endpoint}"
|
88 |
+
|
89 |
+
return endpoint
|
90 |
+
|
91 |
+
def call_api_endpoint(endpoint_url, data):
|
92 |
+
"""API 엔드포인트 호출 함수"""
|
93 |
+
try:
|
94 |
+
response = requests.post(endpoint_url, json=data, timeout=300)
|
95 |
+
response.raise_for_status()
|
96 |
+
return response.json()
|
97 |
+
except requests.exceptions.RequestException as e:
|
98 |
+
# 엔드포인트 정보를 숨기고 일반적인 오류 메시지만 표시
|
99 |
+
logger.error("API 호출 중 오류 발생")
|
100 |
+
return {"error": "API 호출 실패"}
|
101 |
+
|
102 |
def translate_prompt_to_english(prompt):
|
103 |
"""프롬프트 번역 - API 엔드포인트로 전달"""
|
104 |
endpoint_url = get_api_endpoint()
|
|
|
113 |
try:
|
114 |
result = call_api_endpoint(f"{endpoint_url}/translate", data)
|
115 |
if "error" in result:
|
116 |
+
logger.warning("번역 API 오류 발생")
|
117 |
return prompt
|
118 |
return result.get("translated_prompt", prompt)
|
119 |
except Exception as e:
|
120 |
+
logger.warning("번역 중 오류 발생")
|
121 |
return prompt
|
122 |
|
123 |
+
def generate_with_images(prompt, images, variation_index=0):
|
124 |
+
"""API 엔드포인트로 이미지 생성 요청"""
|
125 |
+
endpoint_url = get_api_endpoint()
|
126 |
+
if not endpoint_url:
|
127 |
+
return None, "API 엔드포인트가 설정되지 않았습니다."
|
128 |
+
|
129 |
+
# 이미지들을 base64로 인코딩
|
130 |
+
encoded_images = []
|
131 |
+
for img in images:
|
132 |
+
if img is not None:
|
133 |
+
encoded_img = encode_image_to_base64(img)
|
134 |
+
encoded_images.append(encoded_img)
|
135 |
+
else:
|
136 |
+
encoded_images.append(None)
|
137 |
+
|
138 |
+
data = {
|
139 |
+
"function": "generate_with_images",
|
140 |
+
"prompt": prompt,
|
141 |
+
"images": encoded_images,
|
142 |
+
"variation_index": variation_index
|
143 |
+
}
|
144 |
+
|
145 |
+
try:
|
146 |
+
result = call_api_endpoint(f"{endpoint_url}/generate", data)
|
147 |
+
if "error" in result:
|
148 |
+
return None, "이미지 생성 중 오류가 발생했습니다."
|
149 |
+
|
150 |
+
# base64 이미지를 PIL 이미지로 변환
|
151 |
+
if "image" in result:
|
152 |
+
generated_image = decode_base64_to_image(result["image"])
|
153 |
+
return generated_image, result.get("status", "이미지가 성공적으로 생성되었습니다.")
|
154 |
+
else:
|
155 |
+
return None, "API에서 이미지를 생성하지 못했습니다."
|
156 |
+
except Exception as e:
|
157 |
+
logger.error("이미지 생성 API 호출 중 오류")
|
158 |
+
return None, "이미지 생성 중 오류가 발생했습니다."
|
159 |
"""프롬프트 전처리 - 기존 로직 유지"""
|
160 |
has_img1 = image1 is not None
|
161 |
has_img2 = image2 is not None
|
|
|
285 |
else:
|
286 |
last_error = status
|
287 |
retry_count += 1
|
288 |
+
logger.warning(f"이미지 생성 실패, 재시도 {retry_count}/{max_retries}")
|
289 |
time.sleep(1)
|
290 |
except Exception as e:
|
291 |
+
last_error = "처리 중 오류가 발생했습니다."
|
292 |
retry_count += 1
|
293 |
+
logger.exception(f"이미지 처리 중 오류 발생, 재시도 {retry_count}/{max_retries}")
|
294 |
time.sleep(1)
|
295 |
|
296 |
return None, f"최대 재시도 횟수({max_retries}회) 초과 후 실패: {last_error}", prompt
|
|
|
948 |
|
949 |
# 애플리케이션 실행
|
950 |
if __name__ == "__main__":
|
951 |
+
# API 엔드포인트 확인 (로그에는 민감정보 출력하지 않음)
|
952 |
endpoint = get_api_endpoint()
|
953 |
if endpoint:
|
954 |
logger.info("컨트롤 타워가 시작되었습니다.")
|
955 |
else:
|
956 |
+
logger.warning("API 설정을 확인해주세요.")
|
957 |
|
958 |
demo.queue()
|
959 |
demo.launch(share=False, inbrowser=True, width="100%")
|