File size: 3,810 Bytes
fc895f4
95ccdf6
fc895f4
 
 
 
 
 
95ccdf6
fc895f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95ccdf6
fc895f4
 
 
 
 
95ccdf6
fc895f4
 
 
 
 
fe60d51
fc895f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95ccdf6
 
fc895f4
95ccdf6
 
 
fc895f4
95ccdf6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc895f4
 
 
 
fe60d51
 
 
 
 
 
 
95ccdf6
 
 
fe60d51
fc895f4
95ccdf6
f76204e
 
 
fc895f4
 
fe60d51
 
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
from fastapi import FastAPI, File, UploadFile, HTTPException
from fastapi.responses import FileResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware
import os
import shutil
from pathlib import Path
import uuid
import sys

# Import the existing pipeline
from endToEnd2 import run_pipeline

app = FastAPI(title="Floor2Model API")

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

PROJECT_ROOT = Path(__file__).resolve().parent
GENERATED_DIR = PROJECT_ROOT / "generated_models"
SAMPLES_DIR = PROJECT_ROOT / "samples"
FRONTEND_DIST = PROJECT_ROOT / "frontend" / "dist"

SAMPLES_DIR.mkdir(exist_ok=True)
GENERATED_DIR.mkdir(exist_ok=True)

# Mount static files to serve the generated models directly
app.mount("/models", StaticFiles(directory=str(GENERATED_DIR)), name="models")

@app.post("/upload")
async def upload_image(file: UploadFile = File(...)):
    try:
        file_id = str(uuid.uuid4())[:8]
        file_ext = Path(file.filename).suffix or ".png"
        stem = f"upload_{file_id}"
        save_path = SAMPLES_DIR / f"{stem}{file_ext}"
        
        with open(save_path, "wb") as buffer:
            shutil.copyfileobj(file.file, buffer)
            
        return {"status": "success", "id": stem, "filename": file.filename}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/process/{stem}")
async def process_image(stem: str):
    sample_files = list(SAMPLES_DIR.glob(f"{stem}.*"))
    if not sample_files:
        raise HTTPException(status_code=404, detail="File not found")
        
    sample_image = sample_files[0]
    out_dir = GENERATED_DIR / stem
    
    try:
        # Check if model exists
        model_path = PROJECT_ROOT / "models" / "best.pt"
        
        if model_path.exists():
            # Run the actual pipeline from cvlab (as restored)
            run_pipeline(sample_image)
            
            if not out_dir.exists() or not list(out_dir.glob("*")):
                raise HTTPException(status_code=500, detail="Processing failed to generate output")
                
            return {
                "status": "success", 
                "results": {
                    "detections": f"/models/{stem}/{stem}_detections.png",
                    "gltf": f"/models/{stem}/{stem}.gltf",
                    "obj": f"/models/{stem}/{stem}.obj",
                }
            }
        else:
            # Fallback to mock data if weights missing (standard cvlab behavior)
            mock_stem = "18_png.rf.4956b6043e9f9f738808088cfe37243d"
            return {
                "status": "success", 
                "results": {
                    "detections": f"/models/{mock_stem}/{mock_stem}_detections.png",
                    "gltf": f"/models/{mock_stem}/{mock_stem}.gltf",
                    "obj": f"/models/{mock_stem}/{mock_stem}.obj",
                }
            }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/results/{stem}")
async def get_results(stem: str):
    out_dir = GENERATED_DIR / stem
    if not out_dir.exists():
        raise HTTPException(status_code=404, detail="Results not found")
        
    return {
        "detections": f"/models/{stem}/{stem}_detections.png",
        "gltf": f"/models/{stem}/{stem}.gltf",
        "obj": f"/models/{stem}/{stem}.obj",
    }

# Mount the built frontend last
if FRONTEND_DIST.exists():
    app.mount("/", StaticFiles(directory=str(FRONTEND_DIST), html=True), name="frontend")

if __name__ == "__main__":
    import uvicorn
    port = int(os.environ.get("PORT", 7860))
    uvicorn.run(app, host="0.0.0.0", port=port)