Update app.py
Browse files
app.py
CHANGED
|
@@ -1,28 +1,19 @@
|
|
| 1 |
-
|
| 2 |
-
from fastapi.responses import StreamingResponse
|
| 3 |
-
from PIL import Image
|
| 4 |
import torch
|
| 5 |
-
from
|
| 6 |
import requests
|
| 7 |
-
import
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
level=logging.INFO,
|
| 13 |
-
handlers=[
|
| 14 |
-
logging.StreamHandler(), # نمایش لاگ در کنسول
|
| 15 |
-
logging.FileHandler("app.log") # ذخیره لاگ در فایل
|
| 16 |
-
]
|
| 17 |
-
)
|
| 18 |
-
logger = logging.getLogger(__name__)
|
| 19 |
|
|
|
|
| 20 |
app = FastAPI()
|
| 21 |
|
| 22 |
-
# بارگذاری مدلها
|
| 23 |
def load_model(style_name):
|
| 24 |
try:
|
| 25 |
-
logger.info(f"Loading model for style: {style_name}")
|
| 26 |
model = torch.hub.load(
|
| 27 |
"bryandlee/animegan2-pytorch:main",
|
| 28 |
"generator",
|
|
@@ -31,65 +22,84 @@ def load_model(style_name):
|
|
| 31 |
).eval()
|
| 32 |
return model
|
| 33 |
except Exception as e:
|
| 34 |
-
|
| 35 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
-
#
|
| 38 |
-
|
|
|
|
|
|
|
| 39 |
try:
|
| 40 |
-
logger.info("Processing image...")
|
| 41 |
-
if isinstance(input_img, str):
|
| 42 |
-
logger.info("Input is URL, fetching image...")
|
| 43 |
-
input_img = Image.open(BytesIO(requests.get(input_img).content)).convert("RGB")
|
| 44 |
-
elif isinstance(input_img, Image.Image):
|
| 45 |
-
input_img = input_img.convert("RGB")
|
| 46 |
-
else:
|
| 47 |
-
raise ValueError("فرمت تصویر ورودی صحیح نیست!")
|
| 48 |
-
|
| 49 |
-
# تغییر رزولوشن
|
| 50 |
-
input_img = input_img.resize((256, 256)) # رزولوشن کمتر برای تست سریعتر
|
| 51 |
-
model = load_model(style_name)
|
| 52 |
face2paint_func = torch.hub.load(
|
| 53 |
"bryandlee/animegan2-pytorch:main",
|
| 54 |
"face2paint",
|
| 55 |
-
size=
|
| 56 |
verbose=False
|
| 57 |
)
|
| 58 |
-
output_img = face2paint_func(model, input_img)
|
| 59 |
-
logger.info("Image processed successfully")
|
| 60 |
-
return output_img
|
| 61 |
except Exception as e:
|
| 62 |
-
|
| 63 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
|
| 65 |
-
#
|
| 66 |
-
@app.post("/
|
| 67 |
-
async def
|
| 68 |
try:
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
image = Image.open(file.file).convert("RGB")
|
| 72 |
-
elif url:
|
| 73 |
-
image = Image.open(BytesIO(requests.get(url).content)).convert("RGB")
|
| 74 |
-
else:
|
| 75 |
-
logger.error("No file or URL provided")
|
| 76 |
-
return {"error": "لطفاً تصویر یا URL ارائه دهید"}
|
| 77 |
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
return StreamingResponse(output_buffer, media_type="image/png")
|
| 84 |
except Exception as e:
|
| 85 |
-
|
| 86 |
-
return {"error": str(e)}
|
| 87 |
|
| 88 |
-
#
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
|
|
|
|
| 93 |
if __name__ == "__main__":
|
| 94 |
-
|
| 95 |
-
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
|
|
|
|
|
|
| 2 |
import torch
|
| 3 |
+
from PIL import Image
|
| 4 |
import requests
|
| 5 |
+
from io import BytesIO
|
| 6 |
+
from fastapi import FastAPI, HTTPException
|
| 7 |
+
from fastapi.responses import StreamingResponse
|
| 8 |
+
import uvicorn
|
| 9 |
+
import tempfile
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
+
# Initialize FastAPI app
|
| 12 |
app = FastAPI()
|
| 13 |
|
| 14 |
+
# بارگذاری مدلها بر اساس استایل انتخابی
|
| 15 |
def load_model(style_name):
|
| 16 |
try:
|
|
|
|
| 17 |
model = torch.hub.load(
|
| 18 |
"bryandlee/animegan2-pytorch:main",
|
| 19 |
"generator",
|
|
|
|
| 22 |
).eval()
|
| 23 |
return model
|
| 24 |
except Exception as e:
|
| 25 |
+
raise HTTPException(status_code=500, detail=f"Error loading model: {str(e)}")
|
| 26 |
+
|
| 27 |
+
# پردازش تصویر با AnimeGAN
|
| 28 |
+
def animegan2_transform(image_url, style_name):
|
| 29 |
+
# بررسی استایلهای معتبر
|
| 30 |
+
valid_styles = ["face_paint_512_v1", "face_paint_512_v2", "paprika", "celeba_distill"]
|
| 31 |
+
if style_name not in valid_styles:
|
| 32 |
+
raise HTTPException(status_code=400, detail="Invalid style name!")
|
| 33 |
+
|
| 34 |
+
# دانلود و پردازش تصویر
|
| 35 |
+
try:
|
| 36 |
+
response = requests.get(image_url)
|
| 37 |
+
response.raise_for_status()
|
| 38 |
+
input_img = Image.open(BytesIO(response.content)).convert("RGB")
|
| 39 |
+
except Exception as e:
|
| 40 |
+
raise HTTPException(status_code=400, detail=f"Error loading image: {str(e)}")
|
| 41 |
+
|
| 42 |
+
# تغییر رزولوشن
|
| 43 |
+
input_img = input_img.resize((460, 460))
|
| 44 |
|
| 45 |
+
# بارگذاری مدل
|
| 46 |
+
model = load_model(style_name)
|
| 47 |
+
|
| 48 |
+
# بارگذاری تابع face2paint
|
| 49 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
face2paint_func = torch.hub.load(
|
| 51 |
"bryandlee/animegan2-pytorch:main",
|
| 52 |
"face2paint",
|
| 53 |
+
size=1024,
|
| 54 |
verbose=False
|
| 55 |
)
|
|
|
|
|
|
|
|
|
|
| 56 |
except Exception as e:
|
| 57 |
+
raise HTTPException(status_code=500, detail=f"Error loading face2paint: {str(e)}")
|
| 58 |
+
|
| 59 |
+
# اجرای مدل
|
| 60 |
+
output_img = face2paint_func(model, input_img)
|
| 61 |
+
|
| 62 |
+
# ذخیره تصویر خروجی بهصورت موقت
|
| 63 |
+
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
|
| 64 |
+
output_img.save(temp_file.name, format="PNG")
|
| 65 |
+
|
| 66 |
+
return temp_file.name
|
| 67 |
|
| 68 |
+
# FastAPI endpoint برای تبدیل تصویر
|
| 69 |
+
@app.post("/api/animegan2")
|
| 70 |
+
async def animegan2_api(image_url: str, style: str = "face_paint_512_v2"):
|
| 71 |
try:
|
| 72 |
+
# پردازش تصویر
|
| 73 |
+
output_path = animegan2_transform(image_url, style)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
|
| 75 |
+
# ارسال تصویر بهصورت استریم
|
| 76 |
+
with open(output_path, "rb") as f:
|
| 77 |
+
return StreamingResponse(f, media_type="image/png")
|
| 78 |
+
except HTTPException as e:
|
| 79 |
+
raise e
|
|
|
|
| 80 |
except Exception as e:
|
| 81 |
+
raise HTTPException(status_code=500, detail=f"Internal error: {str(e)}")
|
|
|
|
| 82 |
|
| 83 |
+
# رابط کاربری Gradio (اختیاری، اگر هنوز میخوای رابط گرافیکی داشته باشی)
|
| 84 |
+
def gradio_interface():
|
| 85 |
+
iface = gr.Interface(
|
| 86 |
+
fn=animegan2_transform,
|
| 87 |
+
inputs=[
|
| 88 |
+
gr.Image(type="pil", label="آپلود تصویر یا وارد کردن URL"),
|
| 89 |
+
gr.Dropdown(
|
| 90 |
+
["face_paint_512_v1", "face_paint_512_v2", "paprika", "celeba_distill"],
|
| 91 |
+
value="face_paint_512_v2",
|
| 92 |
+
label="انتخاب استایل"
|
| 93 |
+
)
|
| 94 |
+
],
|
| 95 |
+
outputs=gr.Image(type="pil", label="تصویر انیمه (کیفیت بالا)"),
|
| 96 |
+
title="AnimeGANv2 - تبدیل تصویر به انیمه با انتخاب استایل",
|
| 97 |
+
description="تصاویر خود را با کیفیت بالا و استایلهای مختلف به انیمه تبدیل کنید."
|
| 98 |
+
)
|
| 99 |
+
return iface
|
| 100 |
|
| 101 |
+
# راهاندازی Gradio در کنار FastAPI
|
| 102 |
if __name__ == "__main__":
|
| 103 |
+
# لانچ کردن Gradio (اختیاری)
|
| 104 |
+
iface = gradio_interface()
|
| 105 |
+
iface.launch(server_name="0.0.0.0", server_port=7860, share=False)
|