Update app.py
Browse files
app.py
CHANGED
|
@@ -1,58 +1,86 @@
|
|
| 1 |
-
from fastapi import FastAPI,
|
|
|
|
| 2 |
from PIL import Image
|
| 3 |
import torch
|
| 4 |
from io import BytesIO
|
| 5 |
import requests
|
| 6 |
-
|
| 7 |
|
| 8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
-
|
| 11 |
-
class ImageRequest(BaseModel):
|
| 12 |
-
image_url: str
|
| 13 |
-
style: str = "face_paint_512_v2"
|
| 14 |
|
| 15 |
-
# بارگذاری مدلها
|
| 16 |
def load_model(style_name):
|
| 17 |
-
|
| 18 |
-
"
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
-
|
| 26 |
-
def animegan2_transform(image_url, style_name):
|
| 27 |
try:
|
| 28 |
-
|
| 29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
model = load_model(style_name)
|
| 31 |
face2paint_func = torch.hub.load(
|
| 32 |
"bryandlee/animegan2-pytorch:main",
|
| 33 |
"face2paint",
|
| 34 |
-
size=
|
| 35 |
verbose=False
|
| 36 |
)
|
| 37 |
output_img = face2paint_func(model, input_img)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
output_buffer = BytesIO()
|
| 39 |
output_img.save(output_buffer, format="PNG")
|
| 40 |
output_buffer.seek(0)
|
| 41 |
-
|
|
|
|
| 42 |
except Exception as e:
|
| 43 |
-
|
|
|
|
| 44 |
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
valid_styles = ["face_paint_512_v1", "face_paint_512_v2", "paprika", "celeba_distill"]
|
| 49 |
-
if request.style not in valid_styles:
|
| 50 |
-
raise HTTPException(status_code=400, detail="استایل نامعتبر!")
|
| 51 |
-
|
| 52 |
-
output_buffer = animegan2_transform(request.image_url, request.style)
|
| 53 |
-
return {"image": output_buffer.getvalue(), "content_type": "image/png"}
|
| 54 |
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
return {"message": "API برای تبدیل تصویر به انیمه"}
|
|
|
|
| 1 |
+
from fastapi import FastAPI, File, UploadFile, Form
|
| 2 |
+
from fastapi.responses import StreamingResponse
|
| 3 |
from PIL import Image
|
| 4 |
import torch
|
| 5 |
from io import BytesIO
|
| 6 |
import requests
|
| 7 |
+
import logging
|
| 8 |
|
| 9 |
+
# تنظیم لاگگیری
|
| 10 |
+
logging.basicConfig(
|
| 11 |
+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
| 12 |
+
level=logging.INFO,
|
| 13 |
+
handlers=[logging.StreamHandler(), logging.FileHandler("app.log")]
|
| 14 |
+
)
|
| 15 |
+
logger = logging.getLogger(__name__)
|
| 16 |
|
| 17 |
+
app = FastAPI()
|
|
|
|
|
|
|
|
|
|
| 18 |
|
|
|
|
| 19 |
def load_model(style_name):
|
| 20 |
+
try:
|
| 21 |
+
logger.info(f"Loading model for style: {style_name}")
|
| 22 |
+
model = torch.hub.load(
|
| 23 |
+
"bryandlee/animegan2-pytorch:main",
|
| 24 |
+
"generator",
|
| 25 |
+
pretrained=style_name,
|
| 26 |
+
verbose=False
|
| 27 |
+
).eval()
|
| 28 |
+
return model
|
| 29 |
+
except Exception as e:
|
| 30 |
+
logger.error(f"Error loading model: {str(e)}")
|
| 31 |
+
raise
|
| 32 |
|
| 33 |
+
def animegan2_transform(input_img, style_name):
|
|
|
|
| 34 |
try:
|
| 35 |
+
logger.info("Processing image...")
|
| 36 |
+
if isinstance(input_img, str):
|
| 37 |
+
input_img = Image.open(BytesIO(requests.get(input_img).content)).convert("RGB")
|
| 38 |
+
elif isinstance(input_img, Image.Image):
|
| 39 |
+
input_img = input_img.convert("RGB")
|
| 40 |
+
else:
|
| 41 |
+
raise ValueError("فرمت تصویر ورودی صحیح نیست!")
|
| 42 |
+
|
| 43 |
+
input_img = input_img.resize((128, 128)) # رزولوشن پایین برای سرعت
|
| 44 |
model = load_model(style_name)
|
| 45 |
face2paint_func = torch.hub.load(
|
| 46 |
"bryandlee/animegan2-pytorch:main",
|
| 47 |
"face2paint",
|
| 48 |
+
size=256,
|
| 49 |
verbose=False
|
| 50 |
)
|
| 51 |
output_img = face2paint_func(model, input_img)
|
| 52 |
+
logger.info("Image processed successfully")
|
| 53 |
+
return output_img
|
| 54 |
+
except Exception as e:
|
| 55 |
+
logger.error(f"Error processing image: {str(e)}")
|
| 56 |
+
raise
|
| 57 |
+
|
| 58 |
+
@app.post("/transform")
|
| 59 |
+
async def transform_image(file: UploadFile = File(None), style: str = Form(default="face_paint_512_v2"), url: str = Form(None)):
|
| 60 |
+
try:
|
| 61 |
+
logger.info(f"Received request with style: {style}")
|
| 62 |
+
if file:
|
| 63 |
+
image = Image.open(file.file).convert("RGB")
|
| 64 |
+
elif url:
|
| 65 |
+
image = Image.open(BytesIO(requests.get(url).content)).convert("RGB")
|
| 66 |
+
else:
|
| 67 |
+
logger.error("No file or URL provided")
|
| 68 |
+
return {"error": "لطفاً تصویر یا URL ارائه دهید"}
|
| 69 |
+
|
| 70 |
+
output_img = animegan2_transform(image, style)
|
| 71 |
output_buffer = BytesIO()
|
| 72 |
output_img.save(output_buffer, format="PNG")
|
| 73 |
output_buffer.seek(0)
|
| 74 |
+
logger.info("Returning processed image")
|
| 75 |
+
return StreamingResponse(output_buffer, media_type="image/png")
|
| 76 |
except Exception as e:
|
| 77 |
+
logger.error(f"API error: {str(e)}")
|
| 78 |
+
return {"error": str(e)}
|
| 79 |
|
| 80 |
+
@app.get("/health")
|
| 81 |
+
async def health_check():
|
| 82 |
+
return {"status": "healthy"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
|
| 84 |
+
if __name__ == "__main__":
|
| 85 |
+
import uvicorn
|
| 86 |
+
uvicorn.run(app, host="0.0.0.0", port=8000)
|
|
|