Sudipta Nayak
Changes done - Working in Safari Browser (video file)
e0c2ed1
raw
history blame contribute delete
No virus
3.32 kB
import os
import time
from fastapi import FastAPI, Request, UploadFile, HTTPException
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 mimetypes # For determining file type
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", StaticFiles(directory="app/static"), name="static")
templates = Jinja2Templates(directory="app/templates")
@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 = "app/static/output"
# Save the uploaded file
with open(input_file_path, "wb") as input_file:
input_file.write(await file.read())
# Determine the file type
file_type, _ = mimetypes.guess_type(file.filename)
is_video = file_type and file_type.startswith('video')
print('Detect start')
# Run YOLOv7 detection and save output
subprocess.run(["python", "app/detect.py", "--conf", "0.5", "--img-size", "640", "--weights", "app/model/best.pt", "--no-trace",
"--source", str(input_file_path), "--save-txt", "--save-conf", "--exist-ok", "--project", str(output_file_path)], check=True)
print('Detect end')
original_image_path = f"../static/{file.filename}"
output_image_path = f"../static/output/exp/{file.filename}"
print('original_image_path :', str(original_image_path))
print('output_image_path :', str(output_image_path))
print('is_video :', str(is_video))
# NOTE: Open the app in Safari browser as mov file play is not supported by chrome
# Video file - 8a3c3d7c-fd4fb0c8.mov (kb) , 0d4498d3-d983805d.mov (3mb)- good data
# image file - ceaa4904-2fec7d06.jpg,
# if(str(is_video).lower() == "true"):
# time.sleep(15)
# Render HTML using Jinja2Templates
return templates.TemplateResponse(
"result.html",
{"request": request, "output_image": str(output_image_path), "is_video": str(is_video).lower()}
)
except subprocess.CalledProcessError as e:
# Handle subprocess error (e.g., log the error, return an error response)
print(f"Subprocess error: {e}")
raise HTTPException(status_code=500, detail="Subprocess error")
# 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)