Upload 3 files
Browse files- Dockerfile +19 -0
- app.py +144 -0
- requirements.txt +7 -0
Dockerfile
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.9
|
| 2 |
+
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
|
| 5 |
+
RUN python -m pip install --upgrade pip
|
| 6 |
+
|
| 7 |
+
# Create cache folder and make sure it is accessible
|
| 8 |
+
RUN mkdir -p /app/cache && chmod -R 777 /app/cache
|
| 9 |
+
|
| 10 |
+
# Set environment variables for the cache
|
| 11 |
+
ENV HF_HOME="/app/cache"
|
| 12 |
+
ENV TORCH_HOME="/app/cache"
|
| 13 |
+
|
| 14 |
+
COPY requirements.txt .
|
| 15 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 16 |
+
|
| 17 |
+
COPY app.py .
|
| 18 |
+
|
| 19 |
+
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
|
app.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import uvicorn
|
| 3 |
+
from fastapi import FastAPI, HTTPException
|
| 4 |
+
from pydantic import BaseModel
|
| 5 |
+
from typing import List, Dict, Union
|
| 6 |
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
| 7 |
+
import torch
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
# Definition of Pydantic data models
|
| 11 |
+
class ProblematicItem(BaseModel):
|
| 12 |
+
text: str
|
| 13 |
+
|
| 14 |
+
class ProblematicList(BaseModel):
|
| 15 |
+
problematics: List[str]
|
| 16 |
+
|
| 17 |
+
class PredictionResponse(BaseModel):
|
| 18 |
+
predicted_class: str
|
| 19 |
+
score: float
|
| 20 |
+
|
| 21 |
+
class PredictionsResponse(BaseModel):
|
| 22 |
+
results: List[Dict[str, Union[str, float]]]
|
| 23 |
+
|
| 24 |
+
# FastAPI Configuration
|
| 25 |
+
app = FastAPI(
|
| 26 |
+
title="Problematic Specificity Classification API",
|
| 27 |
+
description="This API classifies problematics using a fine-tuned model hosted on Hugging Face.",
|
| 28 |
+
version="1.0.0"
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
# Model environment variables
|
| 32 |
+
MODEL_NAME = os.getenv("MODEL_NAME", "votre-compte/votre-modele")
|
| 33 |
+
LABEL_0 = os.getenv("LABEL_0", "Classe A")
|
| 34 |
+
LABEL_1 = os.getenv("LABEL_1", "Classe B")
|
| 35 |
+
|
| 36 |
+
# Loading the model and tokenizer
|
| 37 |
+
tokenizer = None
|
| 38 |
+
model = None
|
| 39 |
+
|
| 40 |
+
def load_model():
|
| 41 |
+
global tokenizer, model
|
| 42 |
+
try:
|
| 43 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
|
| 44 |
+
model = AutoModelForSequenceClassification.from_pretrained(MODEL_NAME)
|
| 45 |
+
return True
|
| 46 |
+
except Exception as e:
|
| 47 |
+
print(f"Error loading model: {e}")
|
| 48 |
+
return False
|
| 49 |
+
|
| 50 |
+
# API state check route
|
| 51 |
+
@app.get("/")
|
| 52 |
+
def read_root():
|
| 53 |
+
return {"status": "ok", "model": MODEL_NAME}
|
| 54 |
+
|
| 55 |
+
# Route for checking model status
|
| 56 |
+
@app.get("/health")
|
| 57 |
+
def health_check():
|
| 58 |
+
global model, tokenizer
|
| 59 |
+
if model is None or tokenizer is None:
|
| 60 |
+
success = load_model()
|
| 61 |
+
if not success:
|
| 62 |
+
raise HTTPException(status_code=503, detail="Model not available")
|
| 63 |
+
return {"status": "ok", "model": MODEL_NAME}
|
| 64 |
+
|
| 65 |
+
# Route to predict a single problem at a time
|
| 66 |
+
@app.post("/predict", response_model=PredictionResponse)
|
| 67 |
+
def predict_single(item: ProblematicItem):
|
| 68 |
+
global model, tokenizer
|
| 69 |
+
|
| 70 |
+
if model is None or tokenizer is None:
|
| 71 |
+
success = load_model()
|
| 72 |
+
if not success:
|
| 73 |
+
raise HTTPException(status_code=503, detail="Model not available")
|
| 74 |
+
|
| 75 |
+
try:
|
| 76 |
+
# Tokenization
|
| 77 |
+
inputs = tokenizer(item.text, padding=True, truncation=True, return_tensors="pt")
|
| 78 |
+
|
| 79 |
+
# Prediction
|
| 80 |
+
with torch.no_grad():
|
| 81 |
+
outputs = model(**inputs)
|
| 82 |
+
probabilities = torch.nn.functional.softmax(outputs.logits, dim=-1)
|
| 83 |
+
predicted_class = torch.argmax(probabilities, dim=1).item()
|
| 84 |
+
confidence_score = probabilities[0][predicted_class].item()
|
| 85 |
+
|
| 86 |
+
# Associate the correct label
|
| 87 |
+
predicted_label = LABEL_0 if predicted_class == 0 else LABEL_1
|
| 88 |
+
|
| 89 |
+
return PredictionResponse(predicted_class=predicted_label, score=confidence_score)
|
| 90 |
+
|
| 91 |
+
except Exception as e:
|
| 92 |
+
raise HTTPException(status_code=500, detail=f"Error during prediction: {str(e)}")
|
| 93 |
+
|
| 94 |
+
# Route for predicting several problems at once
|
| 95 |
+
@app.post("/predict-batch", response_model=PredictionsResponse)
|
| 96 |
+
def predict_batch(items: ProblematicList):
|
| 97 |
+
global model, tokenizer
|
| 98 |
+
|
| 99 |
+
if model is None or tokenizer is None:
|
| 100 |
+
success = load_model()
|
| 101 |
+
if not success:
|
| 102 |
+
raise HTTPException(status_code=503, detail="Model not available")
|
| 103 |
+
|
| 104 |
+
try:
|
| 105 |
+
results = []
|
| 106 |
+
|
| 107 |
+
# Batch processing
|
| 108 |
+
batch_size = 16
|
| 109 |
+
for i in range(0, len(items.problematics), batch_size):
|
| 110 |
+
batch_texts = items.problematics[i:i+batch_size]
|
| 111 |
+
|
| 112 |
+
# Tokenization
|
| 113 |
+
inputs = tokenizer(batch_texts, padding=True, truncation=True, return_tensors="pt")
|
| 114 |
+
|
| 115 |
+
# Prediction
|
| 116 |
+
with torch.no_grad():
|
| 117 |
+
outputs = model(**inputs)
|
| 118 |
+
probabilities = torch.nn.functional.softmax(outputs.logits, dim=-1)
|
| 119 |
+
predicted_classes = torch.argmax(probabilities, dim=1).tolist()
|
| 120 |
+
confidence_scores = [probabilities[j][predicted_classes[j]].item() for j in range(len(predicted_classes))]
|
| 121 |
+
|
| 122 |
+
# Converting numerical predictions into labels
|
| 123 |
+
for j, (pred_class, score) in enumerate(zip(predicted_classes, confidence_scores)):
|
| 124 |
+
predicted_label = LABEL_0 if pred_class == 0 else LABEL_1
|
| 125 |
+
results.append({
|
| 126 |
+
"text": batch_texts[j],
|
| 127 |
+
"class": predicted_label,
|
| 128 |
+
"score": score
|
| 129 |
+
})
|
| 130 |
+
|
| 131 |
+
return PredictionsResponse(results=results)
|
| 132 |
+
|
| 133 |
+
except Exception as e:
|
| 134 |
+
raise HTTPException(status_code=500, detail=f"Error during prediction: {str(e)}")
|
| 135 |
+
|
| 136 |
+
# Model loading at startup
|
| 137 |
+
@app.on_event("startup")
|
| 138 |
+
async def startup_event():
|
| 139 |
+
load_model()
|
| 140 |
+
|
| 141 |
+
# Entry point for uvicorn
|
| 142 |
+
if __name__ == "__main__":
|
| 143 |
+
# Starting the server with uvicorn
|
| 144 |
+
uvicorn.run("app:app", host="0.0.0.0", port=7860, reload=True)
|
requirements.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fastapi>=0.95.1
|
| 2 |
+
uvicorn>=0.22.0
|
| 3 |
+
pydantic>=1.10.7
|
| 4 |
+
transformers>=4.28.1
|
| 5 |
+
torch>=2.0.0
|
| 6 |
+
python-multipart>=0.0.6
|
| 7 |
+
requests==2.32.3
|