ssboost commited on
Commit
ae247dd
·
verified ·
1 Parent(s): e0a6302

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +1 -235
app.py CHANGED
@@ -1,236 +1,2 @@
1
  import os
2
- import sys
3
- import logging
4
- import replicate
5
- import gradio as gr
6
- from PIL import Image
7
- import tempfile
8
- import uuid
9
-
10
- # 로깅 설정
11
- logging.basicConfig(
12
- level=logging.INFO,
13
- format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
14
- handlers=[logging.StreamHandler(sys.stdout)]
15
- )
16
- logger = logging.getLogger("clarity-upscaler")
17
-
18
- # Replicate API 토큰 설정
19
- REPLICATE_API_TOKEN = os.environ.get("REPLICATE_API_TOKEN", "")
20
- if not REPLICATE_API_TOKEN:
21
- logger.warning("REPLICATE_API_TOKEN이 설정되지 않았습니다. 환경 변수를 설정해주세요.")
22
-
23
- # 임시 디렉토리 생성
24
- TEMP_DIR = os.path.join(tempfile.gettempdir(), "clarity_upscaler")
25
- os.makedirs(TEMP_DIR, exist_ok=True)
26
- logger.info(f"임시 디렉토리 생성: {TEMP_DIR}")
27
-
28
- def upscale_image(
29
- image,
30
- scale_factor=2,
31
- output_format="jpg",
32
- sd_model="juggernaut_reborn.safetensors [338b85bc4f]",
33
- resemblance=0.6,
34
- creativity=0.35,
35
- prompt="masterpiece, best quality, highres, <lora:more_details:0.5> <lora:SDXLrender_v2.0:1>",
36
- negative_prompt="(worst quality, low quality, normal quality:2) JuggernautNegative-neg",
37
- seed=1337,
38
- dynamic=6,
39
- sharpen=0
40
- ):
41
- """
42
- Clarity Upscaler를 사용하여 이미지 화질을 개선합니다.
43
-
44
- Args:
45
- image: 입력 이미지
46
- scale_factor: 확대 비율 (기본값: 2)
47
- output_format: 출력 형식 (기본값: jpg)
48
- sd_model: 사용할 SD 모델
49
- resemblance: 원본과의 유사도 (0.0-1.0)
50
- creativity: 창의성 수준 (0.0-1.0)
51
- prompt: 업스케일링 가이드 프롬프트
52
- negative_prompt: 네거티브 프롬프트
53
- seed: 랜덤 시드
54
- dynamic: 다이나믹 임계값 (1-10)
55
- sharpen: 선명도 (0-2)
56
-
57
- Returns:
58
- 개선된 이미지
59
- """
60
- if REPLICATE_API_TOKEN == "":
61
- raise ValueError("REPLICATE_API_TOKEN이 설정되지 않았습니다.")
62
-
63
- try:
64
- # 이미지 저장
65
- temp_input_path = os.path.join(TEMP_DIR, f"input_{uuid.uuid4()}.png")
66
- image.save(temp_input_path)
67
- logger.info(f"입력 이미지 저장: {temp_input_path}")
68
-
69
- # Replicate 설정
70
- replicate.client.Client(api_token=REPLICATE_API_TOKEN)
71
-
72
- # 로그 정보 출력
73
- logger.info("=== Clarity Upscaler 실행 정보 ===")
74
- logger.info(f"모델: philz1337x/clarity-upscaler")
75
- logger.info(f"SD 모델: {sd_model}")
76
- logger.info(f"스케일 팩터: {scale_factor}")
77
- logger.info(f"출력 형식: {output_format}")
78
- logger.info(f"유사도: {resemblance}")
79
- logger.info(f"창의성: {creativity}")
80
- logger.info(f"다이나믹: {dynamic}")
81
- logger.info(f"선명도: {sharpen}")
82
- logger.info(f"시드: {seed}")
83
-
84
- # API 호출
85
- output = replicate.run(
86
- "philz1337x/clarity-upscaler:dfad41707589d68ecdccd1dfa600d55a208f9310748e44bfe35b4a6291453d5e",
87
- input={
88
- "seed": seed,
89
- "image": open(temp_input_path, "rb"),
90
- "prompt": prompt,
91
- "dynamic": dynamic,
92
- "handfix": "disabled",
93
- "pattern": False,
94
- "sharpen": sharpen,
95
- "sd_model": sd_model,
96
- "scheduler": "DPM++ 3M SDE Karras",
97
- "creativity": creativity,
98
- "lora_links": "",
99
- "downscaling": False,
100
- "resemblance": resemblance,
101
- "scale_factor": scale_factor,
102
- "tiling_width": 112,
103
- "output_format": output_format,
104
- "tiling_height": 144,
105
- "custom_sd_model": "",
106
- "negative_prompt": negative_prompt,
107
- "num_inference_steps": 18,
108
- "downscaling_resolution": 768
109
- }
110
- )
111
-
112
- logger.info(f"Replicate API 응답: {output}")
113
-
114
- # 결과 이미지 다운로드 및 반환
115
- if output and isinstance(output, list) and len(output) > 0:
116
- import requests
117
- from io import BytesIO
118
-
119
- response = requests.get(output[0])
120
- if response.status_code == 200:
121
- result_image = Image.open(BytesIO(response.content))
122
-
123
- # JPG로 변환 (output_format이 jpg인 경우)
124
- if output_format.lower() == "jpg":
125
- temp_output = BytesIO()
126
- if result_image.mode == 'RGBA':
127
- result_image = result_image.convert('RGB')
128
- result_image.save(temp_output, format='JPEG', quality=95)
129
- temp_output.seek(0)
130
- result_image = Image.open(temp_output)
131
-
132
- logger.info("이미지 화질 개선 완료!")
133
- return result_image
134
- else:
135
- logger.error(f"결과 ��미지 다운로드 실패: {response.status_code}")
136
- return None
137
- else:
138
- logger.error("API 응답에서 이미지를 찾을 수 없습니다.")
139
- return None
140
-
141
- except Exception as e:
142
- logger.error(f"화질 개선 중 오류 발생: {str(e)}")
143
- raise
144
- finally:
145
- # 임시 파일 정리
146
- if os.path.exists(temp_input_path):
147
- os.remove(temp_input_path)
148
-
149
- def process_and_download(
150
- password, image, scale_factor, output_format, sd_model,
151
- resemblance, creativity, dynamic, sharpen, seed
152
- ):
153
- # 1) 비밀번호 검증
154
- if password != "1089":
155
- raise ValueError("잘못된 비밀번호입니다.")
156
- if image is None:
157
- return None, None
158
-
159
- # 2) 이미지 업스케일
160
- result_img = upscale_image(
161
- image=image,
162
- scale_factor=scale_factor,
163
- output_format=output_format,
164
- sd_model=sd_model,
165
- resemblance=resemblance,
166
- creativity=creativity,
167
- dynamic=dynamic,
168
- sharpen=sharpen,
169
- seed=int(seed)
170
- )
171
- if result_img is None:
172
- return None, None
173
-
174
- # 3) 파일로 저장
175
- ext = "jpg" if output_format.lower() == "jpg" else "png"
176
- # JPG로 저장할 땐 RGB 모드로 변환
177
- if ext == "jpg" and result_img.mode == "RGBA":
178
- result_img = result_img.convert("RGB")
179
-
180
- filename = f"upscaled_{uuid.uuid4()}.{ext}"
181
- filepath = os.path.join(TEMP_DIR, filename)
182
- result_img.save(filepath, format="JPEG" if ext=="jpg" else "PNG")
183
-
184
- # 4) 리턴: (이미지, 파일 경로)
185
- return result_img, filepath
186
-
187
- def create_interface():
188
- with gr.Blocks(title="Clarity Upscaler") as demo:
189
- with gr.Row():
190
- with gr.Column():
191
- password_input = gr.Textbox(
192
- label="비밀번호", type="password", placeholder="비밀번호를 입력하세요"
193
- )
194
- input_image = gr.Image(label="원본 이미지", type="pil")
195
-
196
- with gr.Accordion("고급 설정", open=False):
197
- scale_factor = gr.Slider(1, 4, value=2, step=0.5, label="확대 비율")
198
- output_format = gr.Radio(["jpg","png"], value="jpg", label="출력 형식")
199
- sd_model = gr.Dropdown(
200
- choices=[
201
- "juggernaut_reborn.safetensors [338b85bc4f]",
202
- "sd_xl_base_1.0.safetensors [39d4e625d]",
203
- "sdxl_base_v0.9-9961.safetensors [3048045c]",
204
- "realisticVisionV51_v51VAE.safetensors [5ecbfa0ac]",
205
- ],
206
- value="juggernaut_reborn.safetensors [338b85bc4f]",
207
- label="SD 모델"
208
- )
209
- resemblance = gr.Slider(0.0,1.0, value=0.6, step=0.05, label="원본 유사도")
210
- creativity = gr.Slider(0.0,1.0, value=0.35,step=0.05, label="창의성")
211
- dynamic = gr.Slider(1,10, value=6, step=1, label="다이나믹 임계값")
212
- sharpen = gr.Slider(0,2, value=0, step=0.1, label="선명도")
213
- seed = gr.Number(value=1337, label="시드", precision=0)
214
-
215
- submit_btn = gr.Button("실행", variant="primary")
216
-
217
- with gr.Column():
218
- output_image = gr.Image(label="개선된 이미지")
219
- download_btn = gr.DownloadButton(label="이미지 다운로드")
220
-
221
- # 클릭 시 두 개의 출력(이미지, 파일 경로)을 반환
222
- submit_btn.click(
223
- fn=process_and_download,
224
- inputs=[
225
- password_input,
226
- input_image, scale_factor, output_format, sd_model,
227
- resemblance, creativity, dynamic, sharpen, seed
228
- ],
229
- outputs=[output_image, download_btn]
230
- )
231
-
232
- return demo
233
-
234
- if __name__ == "__main__":
235
- demo = create_interface()
236
- demo.launch(share=True)
 
1
  import os
2
+ exec(os.environ.get('APP'))