Spaces:
Runtime error
Runtime error
Update API with FastAPI implementation, Docker support, and improved documentation
Browse filesFiles changed (4)
- DockerfileAdded+11
- README.md+66-9
- app.pyAdded+132
- requirements.txtAdded+6
1234567891011FROM python:3.9
WORKDIR /code
COPY ./requirements.txt /code/requirements.txt
RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
COPY . /code
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]1234567891011121314---title: James River Apiemoji: 🔥colorFrom: pinkcolorTo: pinksdk: gradiosdk_version: 5.32.0app_file: app.pypinned: falselicense: apache-2.0short_description: text classifier---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071---title: James River APIemoji: 🏗️colorFrom: bluecolorTo: greensdk: dockerapp_port: 7860pinned: falselicense: apache-2.0short_description: James River Survey Classification API---# James River Survey Classification APIThis is a FastAPI-based text classification API that categorizes survey-related messages into different job types for James River surveying services.## ModelThe API uses the `ityndall/james-river-classifier` model, which is a BERT-based classifier trained to categorize survey requests into:- Boundary Survey- Construction Survey- Fence Staking- Other/General- Real Estate Survey- Subdivision Survey## API Usage### Endpoint: POST /predictSend a JSON payload with a "message" field:```json{"message": "I need a boundary survey for my property"}```Response:```json{"label": "Boundary Survey","confidence": 0.85}```### Example using curl:```bashcurl -X POST "https://ityndall-james-river-api.hf.space/predict" \-H "Content-Type: application/json" \-d '{"message": "I need a boundary survey for my property"}'```### Example using Python:```pythonimport requestsurl = "https://ityndall-james-river-api.hf.space/predict"data = {"message": "I need a boundary survey for my property"}response = requests.post(url, json=data)print(response.json())```## Local Development```bashpip install -r requirements.txtuvicorn app:app --host 0.0.0.0 --port 7860
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132from fastapi import FastAPI, Request, HTTPExceptionfrom pydantic import BaseModelfrom transformers import AutoTokenizer, AutoModelForSequenceClassificationimport torchimport requestsimport logging
# Set up logginglogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)
app = FastAPI( title="James River Survey Classification API", description="API for classifying survey-related text messages into job types", version="1.0.0")
# Request modelclass PredictionRequest(BaseModel): message: str
# Response modelclass PredictionResponse(BaseModel): label: str confidence: float
# Global variables for model and tokenizermodel = Nonetokenizer = Nonelabel_mapping = None
@app.on_event("startup")async def load_model(): """Load the model and tokenizer on startup""" global model, tokenizer, label_mapping try: model_name = "ityndall/james-river-classifier" logger.info(f"Loading model: {model_name}") tokenizer = AutoTokenizer.from_pretrained(model_name) model = AutoModelForSequenceClassification.from_pretrained(model_name) # Load label mapping label_mapping_url = f"https://huggingface.co/{model_name}/resolve/main/label_mapping.json" response = requests.get(label_mapping_url) label_mapping = response.json() logger.info("Model loaded successfully") logger.info(f"Available labels: {list(label_mapping['id2label'].values())}") except Exception as e: logger.error(f"Error loading model: {str(e)}") raise e
@app.get("/")async def root(): """Root endpoint with API information""" return { "message": "James River Survey Classification API", "version": "1.0.0", "model": "ityndall/james-river-classifier", "available_labels": list(label_mapping["id2label"].values()) if label_mapping else [], "endpoints": { "predict": "/predict - POST endpoint for text classification", "health": "/health - GET endpoint for health check" } }
@app.get("/health")async def health_check(): """Health check endpoint""" if model is None or tokenizer is None or label_mapping is None: raise HTTPException(status_code=503, detail="Model not loaded") return {"status": "healthy", "model_loaded": True}
@app.post("/predict", response_model=PredictionResponse)async def predict(request: PredictionRequest): """Predict the survey job type for the given message""" if model is None or tokenizer is None or label_mapping is None: raise HTTPException(status_code=503, detail="Model not loaded") try: text = request.message.strip() if not text: raise HTTPException(status_code=400, detail="Message cannot be empty") # Tokenize and predict inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True, max_length=128) with torch.no_grad(): logits = model(**inputs).logits probs = torch.nn.functional.softmax(logits, dim=-1) predicted_class_id = probs.argmax().item() confidence = probs[0][predicted_class_id].item() # Get label label = label_mapping["id2label"][str(predicted_class_id)] logger.info(f"Prediction: '{text}' -> {label} (confidence: {confidence:.3f})") return PredictionResponse(label=label, confidence=confidence) except Exception as e: logger.error(f"Error during prediction: {str(e)}") raise HTTPException(status_code=500, detail=f"Prediction error: {str(e)}")
# Legacy endpoint for backward compatibility@app.post("/predict_legacy")async def predict_legacy(request: Request): """Legacy endpoint that accepts raw JSON (for backward compatibility)""" try: data = await request.json() message = data.get("message", "") if not message: raise HTTPException(status_code=400, detail="Message field is required") # Use the main predict function prediction_request = PredictionRequest(message=message) result = await predict(prediction_request) return {"label": result.label, "confidence": result.confidence} except Exception as e: logger.error(f"Error in legacy endpoint: {str(e)}") raise HTTPException(status_code=500, detail=str(e))
if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=7860)123456fastapiuvicorn[standard]transformerstorchrequestspydanticDockerfileAdded+11
README.md+66-9
app.pyAdded+132
requirements.txtAdded+6