ssboost commited on
Commit
9eea77b
ยท
verified ยท
1 Parent(s): d427e6c

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +191 -0
app.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import base64
4
+ import io
5
+ import logging
6
+ import tempfile
7
+ import traceback
8
+ import requests
9
+ from PIL import Image
10
+ import gradio as gr
11
+ import replicate
12
+
13
+ # ๋กœ๊น… ์„ค์ •
14
+ logging.basicConfig(
15
+ level=logging.INFO,
16
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
17
+ handlers=[
18
+ logging.FileHandler("app.log"),
19
+ logging.StreamHandler(sys.stdout)
20
+ ]
21
+ )
22
+ logger = logging.getLogger("enhancer-app")
23
+
24
+ # ์ž„์‹œ ํŒŒ์ผ ์ €์žฅ ํ•จ์ˆ˜
25
+ def save_uploaded_file(uploaded_file, suffix='.png'):
26
+ try:
27
+ if uploaded_file is None:
28
+ return None
29
+
30
+ with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as temp_file:
31
+ temp_filename = temp_file.name
32
+
33
+ if isinstance(uploaded_file, str):
34
+ return uploaded_file
35
+
36
+ if isinstance(uploaded_file, Image.Image):
37
+ uploaded_file.save(temp_filename, format="PNG")
38
+ return temp_filename
39
+
40
+ with open(temp_filename, "wb") as f:
41
+ if hasattr(uploaded_file, "read"):
42
+ content = uploaded_file.read()
43
+ f.write(content)
44
+ else:
45
+ f.write(uploaded_file)
46
+
47
+ return temp_filename
48
+ except Exception as e:
49
+ logger.error(f"Error saving uploaded file: {e}")
50
+ logger.error(traceback.format_exc())
51
+ return None
52
+
53
+ # ์ด๋ฏธ์ง€ ํ™”์งˆ ๊ฐœ์„  ํ•จ์ˆ˜
54
+ def enhance_image(
55
+ image,
56
+ output_format="jpg",
57
+ enhancement_level=2
58
+ ):
59
+ try:
60
+ if image is None:
61
+ return None, None, "์ด๋ฏธ์ง€๋ฅผ ์—…๋กœ๋“œํ•ด์ฃผ์„ธ์š”."
62
+
63
+ # ์ด๋ฏธ์ง€ ์ฒ˜๋ฆฌ
64
+ temp_paths = []
65
+ img_path = save_uploaded_file(image)
66
+ if not img_path:
67
+ return None, None, "์ด๋ฏธ์ง€ ์ฒ˜๋ฆฌ์— ์‹คํŒจํ–ˆ์Šต๋‹ˆ๋‹ค."
68
+
69
+ temp_paths.append(img_path)
70
+
71
+ # Replicate API ํ† ํฐ ํ™•์ธ
72
+ if not os.environ.get("REPLICATE_API_TOKEN"):
73
+ return None, None, "API ํ† ํฐ์ด ์„ค์ •๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค."
74
+
75
+ try:
76
+ # Replicate API๋กœ ํ™”์งˆ ํ–ฅ์ƒ
77
+ output = replicate.run(
78
+ "philz1337x/clarity-upscaler:dfad41707589d68ecdccd1dfa600d55a208f9310748e44bfe35b4a6291453d5e",
79
+ input={
80
+ "image": open(img_path, "rb"),
81
+ "scale_factor": enhancement_level,
82
+ "resemblance": 0.8,
83
+ "creativity": 0.2,
84
+ "output_format": output_format.lower(),
85
+ "prompt": "",
86
+ "negative_prompt": "(worst quality, low quality, normal quality:2)"
87
+ }
88
+ )
89
+
90
+ # Replicate API ์‘๋‹ต ์ฒ˜๋ฆฌ
91
+ if output and isinstance(output, list) and len(output) > 0:
92
+ enhanced_url = output[0]
93
+
94
+ # ํ–ฅ์ƒ๋œ ์ด๋ฏธ์ง€ ๋‹ค์šด๋กœ๋“œ
95
+ enhanced_response = requests.get(enhanced_url)
96
+ if enhanced_response.status_code == 200:
97
+ enhanced_image = Image.open(io.BytesIO(enhanced_response.content))
98
+
99
+ # ์ด๋ฏธ์ง€ ํ˜•์‹ ๋ณ€ํ™˜
100
+ if output_format.lower() != "png" and enhanced_image.mode == "RGBA":
101
+ background = Image.new("RGB", enhanced_image.size, (255, 255, 255))
102
+ background.paste(enhanced_image, mask=enhanced_image.split()[3])
103
+ enhanced_image = background
104
+
105
+ # ๊ฒฐ๊ณผ ์ด๋ฏธ์ง€ ์ €์žฅ
106
+ enhanced_path = tempfile.mktemp(suffix=f'.{output_format}')
107
+ enhanced_image.save(enhanced_path)
108
+ temp_paths.append(enhanced_path)
109
+
110
+ return enhanced_image, enhanced_path, ""
111
+ else:
112
+ return None, None, "์ด๋ฏธ์ง€ ๋‹ค์šด๋กœ๋“œ ์˜ค๋ฅ˜"
113
+ else:
114
+ return None, None, "API ์‘๋‹ต ์—†์Œ"
115
+
116
+ except Exception as e:
117
+ logger.error(f"Error enhancing image: {e}")
118
+ logger.error(traceback.format_exc())
119
+ return None, None, f"{str(e)}"
120
+
121
+ finally:
122
+ # ์ž„์‹œ ํŒŒ์ผ ์ •๋ฆฌ (๊ฒฐ๊ณผ ์ด๋ฏธ์ง€๋Š” ์œ ์ง€)
123
+ for path in temp_paths[:-1]: # ๋งˆ์ง€๋ง‰ ํŒŒ์ผ(๊ฒฐ๊ณผ)์€ ๋‚จ๊น€
124
+ if os.path.exists(path):
125
+ try:
126
+ os.remove(path)
127
+ except Exception as e:
128
+ logger.error(f"Error removing temp file {path}: {e}")
129
+
130
+ except Exception as e:
131
+ logger.error(f"Error in enhance_image function: {e}")
132
+ logger.error(traceback.format_exc())
133
+ return None, None, f"{str(e)}"
134
+
135
+ # Gradio ์ธํ„ฐํŽ˜์ด์Šค ๊ตฌ์„ฑ
136
+ def create_gradio_interface():
137
+ try:
138
+ with gr.Blocks() as app:
139
+ with gr.Row():
140
+ with gr.Column():
141
+ input_image = gr.Image(type="pil")
142
+
143
+ with gr.Row():
144
+ output_format = gr.Dropdown(
145
+ choices=["jpg", "png", "webp"],
146
+ value="jpg",
147
+ visible=False
148
+ )
149
+ enhancement_level = gr.Slider(
150
+ minimum=1, maximum=4, value=2, step=1
151
+ )
152
+
153
+ process_btn = gr.Button("์‹คํ–‰")
154
+
155
+ with gr.Column():
156
+ output_image = gr.Image()
157
+ output_download = gr.File(interactive=False)
158
+
159
+ def on_process(img, format, level):
160
+ if img is None:
161
+ return None, None
162
+
163
+ enhanced_img, download_path, error = enhance_image(
164
+ img, format, level
165
+ )
166
+
167
+ if error:
168
+ return None, None
169
+
170
+ return enhanced_img, download_path
171
+
172
+ process_btn.click(
173
+ on_process,
174
+ inputs=[input_image, output_format, enhancement_level],
175
+ outputs=[output_image, output_download]
176
+ )
177
+
178
+ return app
179
+ except Exception as e:
180
+ logger.error(f"Error creating Gradio interface: {e}")
181
+ logger.error(traceback.format_exc())
182
+ raise
183
+
184
+ # ์•ฑ ์‹คํ–‰
185
+ if __name__ == "__main__":
186
+ try:
187
+ app = create_gradio_interface()
188
+ app.launch(share=True)
189
+ except Exception as e:
190
+ logger.error(f"Error running app: {e}")
191
+ logger.error(traceback.format_exc())