File size: 2,539 Bytes
5918063 44acddd 2d15367 44acddd c1364b9 44acddd 5918063 44acddd 736bf26 c4f2cca 44acddd aeee3ba 44acddd bc13748 44acddd 2e79b76 2d15367 44acddd 4ce9948 44acddd 39e53c4 44acddd 4ce9948 81536c9 cb6b69f c4f2cca 9c02022 b3619b5 c4f2cca b3619b5 44acddd 9c02022 16ced81 44acddd c4f2cca 3ebd9c2 c4f2cca b3619b5 44acddd c4f2cca 3ebd9c2 c4f2cca 9c02022 b3619b5 9c02022 9618376 c4f2cca e6702de aeee3ba 52ba617 aeee3ba e6702de |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 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 71 72 73 74 75 76 77 78 79 80 81 82 83 |
import os
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
import logging
app = FastAPI(
title=settings.PROJECT_NAME, openapi_url=f"{settings.API_V1_STR}/openapi.json"
)
# app.mount("/static", FileResponse, name="static")
# templates = Jinja2Templates(directory="templates")
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, file: UploadFile):
try:
print('File name:', file.filename)
input_file_path = f"app/static/{file.filename}"
output_file_path = f"app/static/output/{file.filename}"
# Save the uploaded file
with open(input_file_path, "wb") as input_file:
input_file.write(await file.read())
print('Detect start')
# Run YOLOv7 detection and save output
subprocess.run(["python", "detect.py", "--conf", "0.5", "--img-size", "640", "--weights", "app/model/best.pt",
"--source", str(input_file_path), "--save-txt", "--save-conf", "--exist-ok", "--project", str(output_file_path)])
print('Detect end')
# Render HTML using Jinja2Templates
return templates.TemplateResponse(
"result.html",
{"request": request, "original_image": str(input_file_path), "output_image": str(output_file_path)},
)
# return templates.TemplateResponse("index.html", {"request": request})
except Exception as e:
logging.error(f"Error in /detect endpoint: {str(e)}")
raise e
# Set all CORS enabled origins
# 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=["*"],
# )
# Start app
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8001)
|