Up_G / app.py
ssboost's picture
Create app.py
9eea77b verified
raw
history blame
6.73 kB
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())