Spaces:
Sleeping
Sleeping
Update app/backend/main.py
Browse files- app/backend/main.py +202 -201
app/backend/main.py
CHANGED
|
@@ -1,202 +1,203 @@
|
|
| 1 |
-
from __future__ import annotations
|
| 2 |
-
|
| 3 |
-
import json
|
| 4 |
-
import os
|
| 5 |
-
import shutil
|
| 6 |
-
import subprocess
|
| 7 |
-
import sys
|
| 8 |
-
import tempfile
|
| 9 |
-
from pathlib import Path
|
| 10 |
-
from typing import Any, Dict
|
| 11 |
-
|
| 12 |
-
from fastapi import FastAPI, File, HTTPException, UploadFile
|
| 13 |
-
from fastapi.middleware.cors import CORSMiddleware
|
| 14 |
-
from fastapi.responses import JSONResponse
|
| 15 |
-
from PIL import Image
|
| 16 |
-
|
| 17 |
-
# ==========
|
| 18 |
-
# Настройки
|
| 19 |
-
# ==========
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
PROJECT_ROOT = Path(
|
| 23 |
-
os.getenv("POSTER_PROJECT_ROOT",
|
| 24 |
-
).resolve()
|
| 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 |
-
f"
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
str(
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
env
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
f"
|
| 100 |
-
f"
|
| 101 |
-
f"
|
| 102 |
-
f"
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
f"
|
| 110 |
-
f"
|
| 111 |
-
f"
|
| 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 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
|
|
|
| 202 |
shutil.rmtree(temp_dir, ignore_errors=True)
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import shutil
|
| 6 |
+
import subprocess
|
| 7 |
+
import sys
|
| 8 |
+
import tempfile
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from typing import Any, Dict
|
| 11 |
+
|
| 12 |
+
from fastapi import FastAPI, File, HTTPException, UploadFile
|
| 13 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 14 |
+
from fastapi.responses import JSONResponse
|
| 15 |
+
from PIL import Image
|
| 16 |
+
|
| 17 |
+
# ==========
|
| 18 |
+
# Настройки
|
| 19 |
+
# ==========
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
PROJECT_ROOT = Path(
|
| 23 |
+
os.getenv("POSTER_PROJECT_ROOT", str(Path(__file__).resolve().parents[1]))
|
| 24 |
+
).resolve()
|
| 25 |
+
|
| 26 |
+
SRC_DIR = PROJECT_ROOT / "src"
|
| 27 |
+
|
| 28 |
+
if str(SRC_DIR) not in sys.path:
|
| 29 |
+
sys.path.append(str(SRC_DIR))
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
# =========================
|
| 33 |
+
# Инференс через существующий script
|
| 34 |
+
# =========================
|
| 35 |
+
|
| 36 |
+
def extract_json_from_stdout(stdout: str) -> Dict[str, Any]:
|
| 37 |
+
"""
|
| 38 |
+
Некоторые библиотеки и модели печатают служебные логи до JSON.
|
| 39 |
+
Ищем первый валидный JSON-объект.
|
| 40 |
+
"""
|
| 41 |
+
stdout = safe_text(stdout).strip()
|
| 42 |
+
if not stdout:
|
| 43 |
+
raise RuntimeError("Empty stdout: inference script returned no JSON output.")
|
| 44 |
+
|
| 45 |
+
start_idx = stdout.find("{")
|
| 46 |
+
if start_idx == -1:
|
| 47 |
+
raise RuntimeError(f"JSON not found in stdout:\n{stdout}")
|
| 48 |
+
|
| 49 |
+
candidate = stdout[start_idx:]
|
| 50 |
+
|
| 51 |
+
try:
|
| 52 |
+
return json.loads(candidate)
|
| 53 |
+
except json.JSONDecodeError:
|
| 54 |
+
end_idx = candidate.rfind("}")
|
| 55 |
+
if end_idx == -1:
|
| 56 |
+
raise RuntimeError(f"JSON closing brace not found:\n{stdout}")
|
| 57 |
+
candidate = candidate[: end_idx + 1]
|
| 58 |
+
return json.loads(candidate)
|
| 59 |
+
|
| 60 |
+
def safe_text(value: Any) -> str:
|
| 61 |
+
if value is None:
|
| 62 |
+
return ""
|
| 63 |
+
return str(value)
|
| 64 |
+
|
| 65 |
+
def run_model_inference(image_path: Path) -> Dict[str, Any]:
|
| 66 |
+
script_path = PROJECT_ROOT / "src" / "predict_one_image_with_metrics.py"
|
| 67 |
+
|
| 68 |
+
if not script_path.exists():
|
| 69 |
+
raise RuntimeError(
|
| 70 |
+
f"Inference script not found: {script_path}\n"
|
| 71 |
+
f"PROJECT_ROOT={PROJECT_ROOT}"
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
cmd = [
|
| 75 |
+
sys.executable,
|
| 76 |
+
str(script_path),
|
| 77 |
+
str(image_path),
|
| 78 |
+
"--json",
|
| 79 |
+
]
|
| 80 |
+
|
| 81 |
+
env = os.environ.copy()
|
| 82 |
+
env["PYTHONIOENCODING"] = "utf-8"
|
| 83 |
+
|
| 84 |
+
result = subprocess.run(
|
| 85 |
+
cmd,
|
| 86 |
+
capture_output=True,
|
| 87 |
+
text=True,
|
| 88 |
+
encoding="utf-8",
|
| 89 |
+
cwd=str(PROJECT_ROOT),
|
| 90 |
+
env=env,
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
stdout_text = safe_text(result.stdout).strip()
|
| 94 |
+
stderr_text = safe_text(result.stderr).strip()
|
| 95 |
+
|
| 96 |
+
if result.returncode != 0:
|
| 97 |
+
raise RuntimeError(
|
| 98 |
+
"Inference failed.\n"
|
| 99 |
+
f"CMD: {' '.join(cmd)}\n"
|
| 100 |
+
f"CWD: {PROJECT_ROOT}\n"
|
| 101 |
+
f"RETURN CODE: {result.returncode}\n"
|
| 102 |
+
f"STDOUT:\n{stdout_text}\n"
|
| 103 |
+
f"STDERR:\n{stderr_text}"
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
if not stdout_text:
|
| 107 |
+
raise RuntimeError(
|
| 108 |
+
"Inference returned success code but empty stdout.\n"
|
| 109 |
+
f"CMD: {' '.join(cmd)}\n"
|
| 110 |
+
f"CWD: {PROJECT_ROOT}\n"
|
| 111 |
+
f"RETURN CODE: {result.returncode}\n"
|
| 112 |
+
f"STDERR:\n{stderr_text}"
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
data = extract_json_from_stdout(stdout_text)
|
| 116 |
+
|
| 117 |
+
if not isinstance(data, dict):
|
| 118 |
+
raise RuntimeError("Inference returned non-dict JSON.")
|
| 119 |
+
|
| 120 |
+
if "ai_detection" not in data:
|
| 121 |
+
data["ai_detection"] = None
|
| 122 |
+
|
| 123 |
+
return data
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
# ==========
|
| 127 |
+
# FastAPI
|
| 128 |
+
# ==========
|
| 129 |
+
|
| 130 |
+
app = FastAPI(
|
| 131 |
+
title="Poster Design Analyzer API",
|
| 132 |
+
version="1.0.0",
|
| 133 |
+
description="API для анализа постеров и возврата 5 оценок и диагностического анализа."
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
app.add_middleware(
|
| 137 |
+
CORSMiddleware,
|
| 138 |
+
allow_origins=["*"],
|
| 139 |
+
allow_credentials=True,
|
| 140 |
+
allow_methods=["*"],
|
| 141 |
+
allow_headers=["*"],
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
@app.get("/")
|
| 146 |
+
def root() -> Dict[str, Any]:
|
| 147 |
+
return {
|
| 148 |
+
"service": "Poster Design Analyzer API",
|
| 149 |
+
"status": "ok",
|
| 150 |
+
"docs": "/docs",
|
| 151 |
+
"health": "/health",
|
| 152 |
+
"analyze": "/analyze",
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
@app.get("/health")
|
| 157 |
+
def health() -> Dict[str, str]:
|
| 158 |
+
return {"status": "ok"}
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
@app.post("/analyze")
|
| 162 |
+
async def analyze(file: UploadFile = File(...)) -> JSONResponse:
|
| 163 |
+
if not file.filename:
|
| 164 |
+
raise HTTPException(status_code=400, detail="Файл не передан.")
|
| 165 |
+
|
| 166 |
+
suffix = Path(file.filename).suffix.lower()
|
| 167 |
+
if suffix not in {".jpg", ".jpeg", ".png", ".webp", ".bmp"}:
|
| 168 |
+
raise HTTPException(status_code=400, detail="Неподдерживаемый формат файла.")
|
| 169 |
+
|
| 170 |
+
temp_dir = Path(tempfile.mkdtemp(prefix="poster_analyze_"))
|
| 171 |
+
temp_path = temp_dir / f"input{suffix}"
|
| 172 |
+
|
| 173 |
+
try:
|
| 174 |
+
contents = await file.read()
|
| 175 |
+
if not contents:
|
| 176 |
+
raise HTTPException(status_code=400, detail="Пустой файл.")
|
| 177 |
+
|
| 178 |
+
temp_path.write_bytes(contents)
|
| 179 |
+
|
| 180 |
+
# Валидация изображения
|
| 181 |
+
try:
|
| 182 |
+
with Image.open(temp_path) as img:
|
| 183 |
+
img.verify()
|
| 184 |
+
except Exception as e:
|
| 185 |
+
raise HTTPException(
|
| 186 |
+
status_code=400,
|
| 187 |
+
detail=f"Файл не является корректным изображением: {e}"
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
inference_result = run_model_inference(temp_path)
|
| 191 |
+
|
| 192 |
+
response = {
|
| 193 |
+
"filename": file.filename,
|
| 194 |
+
**inference_result,
|
| 195 |
+
}
|
| 196 |
+
return JSONResponse(content=response)
|
| 197 |
+
|
| 198 |
+
except HTTPException:
|
| 199 |
+
raise
|
| 200 |
+
except Exception as e:
|
| 201 |
+
raise HTTPException(status_code=500, detail=f"Ошибка инференса: {e}")
|
| 202 |
+
finally:
|
| 203 |
shutil.rmtree(temp_dir, ignore_errors=True)
|