File size: 2,971 Bytes
9877732
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98bf2c9
9877732
 
98bf2c9
9877732
 
98bf2c9
9877732
 
 
 
 
 
 
 
 
 
 
 
 
98bf2c9
9877732
 
 
 
 
 
 
 
 
 
 
 
691c981
 
 
 
 
 
 
 
9877732
 
 
 
691c981
 
 
98bf2c9
 
691c981
98bf2c9
691c981
 
 
 
 
 
 
98bf2c9
 
 
 
 
 
9877732
691c981
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
84
# --- Model download logic (Hugging Face Hub) ---
import os
import requests

def download_if_missing(url, dest):
    if not os.path.exists(dest):
        print(f"Downloading model from {url} to {dest}...")
        os.makedirs(os.path.dirname(dest), exist_ok=True)
        with requests.get(url, stream=True) as r:
            r.raise_for_status()
            with open(dest, "wb") as f:
                for chunk in r.iter_content(chunk_size=8192):
                    f.write(chunk)
        print("Download complete.")

# Hugging Face direct download links
# DAMAGE_MODEL_URL = "https://huggingface.co/AItoolstack/car_damage_detection/resolve/main/yolov8_models/damage/weights/weights/best.pt"
PARTS_MODEL_URL = "https://huggingface.co/AItoolstack/car_damage_detection/resolve/main/yolov8_models/parts/weights/weights/best.pt"

# DAMAGE_MODEL_PATH = os.path.join("/tmp", "models", "damage", "weights", "weights", "best.pt")
PARTS_MODEL_PATH = os.path.join("/tmp", "models", "parts", "weights", "weights", "best.pt")

# download_if_missing(DAMAGE_MODEL_URL, DAMAGE_MODEL_PATH)
download_if_missing(PARTS_MODEL_URL, PARTS_MODEL_PATH)

from fastapi import FastAPI, File, UploadFile, BackgroundTasks
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi.responses import JSONResponse, HTMLResponse
from fastapi.middleware.cors import CORSMiddleware
import uvicorn
from datetime import datetime
import aiofiles
from pathlib import Path
import uuid
from app.routers import inference
from .utils.model_loader import PARTS_MODEL_PATH

app = FastAPI(title="Car Damage Detection API")

# CORS middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Get absolute paths for static and template directories
APP_DIR = Path(__file__).resolve().parent
STATIC_DIR = APP_DIR / "static"
TEMPLATES_DIR = APP_DIR / "templates"

# Mount static files using absolute path
app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")
templates = Jinja2Templates(directory=str(TEMPLATES_DIR))

# Include routers
app.include_router(inference.router)

# Create required directories with absolute paths
UPLOAD_DIR = Path("/tmp/uploads")
RESULTS_DIR = Path("/tmp/results")

def create_dirs():
    # Ensure directories exist with proper permissions
    for dir_path in [UPLOAD_DIR, RESULTS_DIR]:
        try:
            dir_path.mkdir(parents=True, exist_ok=True)
            # Set permissions to 777 to ensure write access
            os.chmod(str(dir_path), 0o777)
        except Exception as e:
            print(f"Error creating directory {dir_path}: {e}")
            raise

# Add to startup
@app.on_event("startup")
async def startup_event():
    create_dirs()

if __name__ == "__main__":
    uvicorn.run("main:app", host="0.0.0.0", port=7860)