Spaces:
Sleeping
Sleeping
Download api/main.py from abdurrehmansaeed/ThreadNode: direct link, hf CLI and curl.
- Browser
- Download file 2.82 kB
-
https://huggingface.co/spaces/abdurrehmansaeed/ThreadNode/resolve/main/api/main.py
- Command line
-
hf download hf://spaces/abdurrehmansaeed/ThreadNode/api/main.py
-
curl -L -o main.py https://huggingface.co/spaces/abdurrehmansaeed/ThreadNode/resolve/main/api/main.py
2.82 kB
| from fastapi import FastAPI, File, UploadFile, HTTPException | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from fastapi.responses import JSONResponse | |
| from fastapi.staticfiles import StaticFiles | |
| import torch | |
| import torch.nn as nn | |
| from torchvision import models, transforms | |
| from PIL import Image | |
| import pickle | |
| import io | |
| # --- 1. CONFIGURATION --- | |
| MODEL_PATH = "../models/fashion_hierarchy_model_v3.pth" | |
| VOCAB_PATH = "../data/mlb_vocab.pkl" | |
| THRESHOLD = 0.85 | |
| # --- 2. INITIALIZE FASTAPI --- | |
| app = FastAPI(title="Apparel Taxonomy API", version="1.0") | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| # --- 3. HARDWARE & TRANSFORMS --- | |
| device = torch.device("cuda" if torch.cuda.is_available() else "cpu") | |
| print(f"Server spinning up. Computation routed to: {device.type.upper()}") | |
| transform = transforms.Compose([ | |
| transforms.Resize((224, 224)), | |
| transforms.ToTensor(), | |
| transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) | |
| ]) | |
| # --- 4. LOAD STATE INTO MEMORY --- | |
| try: | |
| with open(VOCAB_PATH, 'rb') as f: | |
| mlb = pickle.load(f) | |
| num_classes = len(mlb.classes_) | |
| model = models.efficientnet_b0(weights=None) | |
| in_features = model.classifier[1].in_features | |
| model.classifier[1] = nn.Linear(in_features, num_classes) | |
| model.load_state_dict(torch.load(MODEL_PATH, map_location=device)) | |
| model.to(device) | |
| model.eval() | |
| print("V3 Engine successfully loaded and locked into memory.") | |
| except Exception as e: | |
| print(f"CRITICAL BOOT ERROR: {e}") | |
| # --- 5. THE INFERENCE ROUTE --- | |
| async def predict_apparel(file: UploadFile = File(...)): | |
| if not file.content_type.startswith("image/"): | |
| raise HTTPException(status_code=400, detail="Invalid file type. Please upload an image.") | |
| try: | |
| image_bytes = await file.read() | |
| image = Image.open(io.BytesIO(image_bytes)).convert("RGB") | |
| input_tensor = transform(image).unsqueeze(0).to(device) | |
| with torch.no_grad(): | |
| outputs = model(input_tensor) | |
| probs = torch.sigmoid(outputs) | |
| preds = (probs > THRESHOLD).float().cpu().numpy() | |
| predicted_tags = mlb.inverse_transform(preds)[0] | |
| return JSONResponse(content={ | |
| "status": "success", | |
| "threshold_applied": THRESHOLD, | |
| "tags": list(predicted_tags) | |
| }) | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=f"Inference Engine Error: {str(e)}") | |
| # --- 6. SERVE THE UI --- | |
| app.mount("/", StaticFiles(directory="../frontend", html=True), name="frontend") |