File size: 6,729 Bytes
9eea77b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import sys
import base64
import io
import logging
import tempfile
import traceback
import requests
from PIL import Image
import gradio as gr
import replicate

# ๋กœ๊น… ์„ค์ •
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("enhancer-app")

# ์ž„์‹œ ํŒŒ์ผ ์ €์žฅ ํ•จ์ˆ˜
def save_uploaded_file(uploaded_file, suffix='.png'):
    try:
        if uploaded_file is None:
            return None
        
        with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as temp_file:
            temp_filename = temp_file.name
        
        if isinstance(uploaded_file, str):
            return uploaded_file
        
        if isinstance(uploaded_file, Image.Image):
            uploaded_file.save(temp_filename, format="PNG")
            return temp_filename
        
        with open(temp_filename, "wb") as f:
            if hasattr(uploaded_file, "read"):
                content = uploaded_file.read()
                f.write(content)
            else:
                f.write(uploaded_file)
        
        return temp_filename
    except Exception as e:
        logger.error(f"Error saving uploaded file: {e}")
        logger.error(traceback.format_exc())
        return None

# ์ด๋ฏธ์ง€ ํ™”์งˆ ๊ฐœ์„  ํ•จ์ˆ˜
def enhance_image(
    image,
    output_format="jpg",
    enhancement_level=2
):
    try:
        if image is None:
            return None, None, "์ด๋ฏธ์ง€๋ฅผ ์—…๋กœ๋“œํ•ด์ฃผ์„ธ์š”."
        
        # ์ด๋ฏธ์ง€ ์ฒ˜๋ฆฌ
        temp_paths = []
        img_path = save_uploaded_file(image)
        if not img_path:
            return None, None, "์ด๋ฏธ์ง€ ์ฒ˜๋ฆฌ์— ์‹คํŒจํ–ˆ์Šต๋‹ˆ๋‹ค."
        
        temp_paths.append(img_path)
        
        # Replicate API ํ† ํฐ ํ™•์ธ
        if not os.environ.get("REPLICATE_API_TOKEN"):
            return None, None, "API ํ† ํฐ์ด ์„ค์ •๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค."
        
        try:
            # Replicate API๋กœ ํ™”์งˆ ํ–ฅ์ƒ
            output = replicate.run(
                "philz1337x/clarity-upscaler:dfad41707589d68ecdccd1dfa600d55a208f9310748e44bfe35b4a6291453d5e",
                input={
                    "image": open(img_path, "rb"),
                    "scale_factor": enhancement_level,
                    "resemblance": 0.8,
                    "creativity": 0.2,
                    "output_format": output_format.lower(),
                    "prompt": "",
                    "negative_prompt": "(worst quality, low quality, normal quality:2)"
                }
            )
            
            # Replicate API ์‘๋‹ต ์ฒ˜๋ฆฌ
            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
                    
                    # ๊ฒฐ๊ณผ ์ด๋ฏธ์ง€ ์ €์žฅ
                    enhanced_path = tempfile.mktemp(suffix=f'.{output_format}')
                    enhanced_image.save(enhanced_path)
                    temp_paths.append(enhanced_path)
                    
                    return enhanced_image, enhanced_path, ""
                else:
                    return None, None, "์ด๋ฏธ์ง€ ๋‹ค์šด๋กœ๋“œ ์˜ค๋ฅ˜"
            else:
                return None, None, "API ์‘๋‹ต ์—†์Œ"
                
        except Exception as e:
            logger.error(f"Error enhancing image: {e}")
            logger.error(traceback.format_exc())
            return None, None, f"{str(e)}"
        
        finally:
            # ์ž„์‹œ ํŒŒ์ผ ์ •๋ฆฌ (๊ฒฐ๊ณผ ์ด๋ฏธ์ง€๋Š” ์œ ์ง€)
            for path in temp_paths[:-1]:  # ๋งˆ์ง€๋ง‰ ํŒŒ์ผ(๊ฒฐ๊ณผ)์€ ๋‚จ๊น€
                if os.path.exists(path):
                    try:
                        os.remove(path)
                    except Exception as e:
                        logger.error(f"Error removing temp file {path}: {e}")
            
    except Exception as e:
        logger.error(f"Error in enhance_image function: {e}")
        logger.error(traceback.format_exc())
        return None, None, f"{str(e)}"

# Gradio ์ธํ„ฐํŽ˜์ด์Šค ๊ตฌ์„ฑ
def create_gradio_interface():
    try:
        with gr.Blocks() as app:
            with gr.Row():
                with gr.Column():
                    input_image = gr.Image(type="pil")
                    
                    with gr.Row():
                        output_format = gr.Dropdown(
                            choices=["jpg", "png", "webp"],
                            value="jpg",
                            visible=False
                        )
                        enhancement_level = gr.Slider(
                            minimum=1, maximum=4, value=2, step=1
                        )
                    
                    process_btn = gr.Button("์‹คํ–‰")
                
                with gr.Column():
                    output_image = gr.Image()
                    output_download = gr.File(interactive=False)
            
            def on_process(img, format, level):
                if img is None:
                    return None, None
                
                enhanced_img, download_path, error = enhance_image(
                    img, format, level
                )
                
                if error:
                    return None, None
                
                return enhanced_img, download_path
            
            process_btn.click(
                on_process,
                inputs=[input_image, output_format, enhancement_level],
                outputs=[output_image, output_download]
            )
        
        return app
    except Exception as e:
        logger.error(f"Error creating Gradio interface: {e}")
        logger.error(traceback.format_exc())
        raise

# ์•ฑ ์‹คํ–‰
if __name__ == "__main__":
    try:
        app = create_gradio_interface()
        app.launch(share=True)
    except Exception as e:
        logger.error(f"Error running app: {e}")
        logger.error(traceback.format_exc())