|
from fastapi import FastAPI, Request, UploadFile |
|
from fastapi.responses import HTMLResponse, FileResponse |
|
from fastapi.staticfiles import StaticFiles |
|
from fastapi.templating import Jinja2Templates |
|
from fastapi.middleware.cors import CORSMiddleware |
|
from pydantic import BaseModel |
|
import subprocess |
|
from pathlib import Path |
|
from config import settings |
|
|
|
app = FastAPI( |
|
title=settings.PROJECT_NAME, openapi_url=f"{settings.API_V1_STR}/openapi.json" |
|
) |
|
|
|
|
|
|
|
|
|
app.mount("/static", FileResponse, name="static") |
|
templates = Jinja2Templates(directory="app/templates") |
|
|
|
class Item(BaseModel): |
|
file: UploadFile |
|
|
|
@app.get("/", response_class=HTMLResponse) |
|
async def root(request: Request): |
|
return templates.TemplateResponse("index.html", {"request": request}) |
|
|
|
@app.post("/detect", response_class=HTMLResponse) |
|
async def detect_objects(request: Request, item: Item): |
|
print('Item:', item) |
|
|
|
print('File name:', item.file.filename) |
|
|
|
input_file = f"uploads/{item.file.filename}" |
|
output_file = f"static/output/{item.file.filename}" |
|
|
|
|
|
with open(input_file, "wb") as file: |
|
file.write(item.file.file.read()) |
|
|
|
print('Detect start') |
|
|
|
|
|
subprocess.run(["python", "detect.py", "--conf", "0.5", "--img-size", "640", "--weights", "app/model/best.pt", "--source", input_file, "--save-txt", "--save-conf", "--exist-ok", "--project", output_file]) |
|
|
|
print('Detect end') |
|
|
|
|
|
return templates.TemplateResponse( |
|
"result.html", |
|
{"request": request, "original_image": f"/static/{item.file.filename}", "output_image": f"/static/output/{item.file.filename}"}, |
|
) |
|
|
|
|
|
|
|
|
|
if settings.BACKEND_CORS_ORIGINS: |
|
app.add_middleware( |
|
CORSMiddleware, |
|
allow_origins=[str(origin) for origin in settings.BACKEND_CORS_ORIGINS], |
|
allow_credentials=True, |
|
allow_methods=["*"], |
|
allow_headers=["*"], |
|
) |
|
|
|
|
|
|
|
if __name__ == "__main__": |
|
import uvicorn |
|
uvicorn.run(app, host="0.0.0.0", port=8001) |
|
|