Spaces:
Sleeping
Sleeping
Commit ·
811fc57
1
Parent(s): d59b9e2
initial migration from Render: FastAPI + Gradio, port 7860
Browse files- .dvcignore +3 -0
- .gitignore +9 -0
- Dockerfile +19 -0
- app/__init__.py +0 -0
- app/__pycache__/__init__.cpython-313.pyc +0 -0
- app/__pycache__/main.cpython-313.pyc +0 -0
- app/main.py +89 -0
- app/ml/__init__.py +0 -0
- app/ml/__pycache__/__init__.cpython-313.pyc +0 -0
- app/ml/__pycache__/predictor.cpython-313.pyc +0 -0
- app/ml/predictor.py +121 -0
- app/models.py +0 -0
- hf-deployment.py +49 -0
- mlflow_tracking/track_experiment.py +134 -0
- notebooks/MLEng_init.ipynb +0 -0
- requirements.txt +9 -0
- tests/__init__.py +0 -0
- tests/test_api.py +64 -0
- tests/test_predictor.py +86 -0
.dvcignore
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Add patterns of files dvc should ignore, which could improve
|
| 2 |
+
# the performance. Learn more at
|
| 3 |
+
# https://dvc.org/doc/user-guide/dvcignore
|
.gitignore
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.venv/
|
| 2 |
+
.idea/
|
| 3 |
+
mlruns/
|
| 4 |
+
model_export/
|
| 5 |
+
*.safetensors
|
| 6 |
+
|
| 7 |
+
# DVC files
|
| 8 |
+
/dvc.lock
|
| 9 |
+
.env
|
Dockerfile
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.11-slim
|
| 2 |
+
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
|
| 5 |
+
# Create non-root user (required by HF Spaces)
|
| 6 |
+
RUN useradd -m -u 1000 user
|
| 7 |
+
USER user
|
| 8 |
+
ENV PATH="/home/user/.local/bin:$PATH"
|
| 9 |
+
|
| 10 |
+
COPY --chown=user requirements.txt .
|
| 11 |
+
RUN pip install --no-cache-dir --upgrade pip && \
|
| 12 |
+
pip install --no-cache-dir -r requirements.txt
|
| 13 |
+
|
| 14 |
+
COPY --chown=user . .
|
| 15 |
+
|
| 16 |
+
# HuggingFace Spaces requires port 7860
|
| 17 |
+
EXPOSE 7860
|
| 18 |
+
|
| 19 |
+
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "7860"]
|
app/__init__.py
ADDED
|
File without changes
|
app/__pycache__/__init__.cpython-313.pyc
ADDED
|
Binary file (171 Bytes). View file
|
|
|
app/__pycache__/main.cpython-313.pyc
ADDED
|
Binary file (2.51 kB). View file
|
|
|
app/main.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import gradio as gr
|
| 3 |
+
from fastapi import FastAPI
|
| 4 |
+
from fastapi.responses import RedirectResponse
|
| 5 |
+
from pydantic import BaseModel
|
| 6 |
+
|
| 7 |
+
from app.ml.predictor import EmotionPredictor
|
| 8 |
+
|
| 9 |
+
app = FastAPI(title="Emotion Classifier", version="1.0.0")
|
| 10 |
+
|
| 11 |
+
MODEL_ID = os.getenv("MODEL_ID", "AfroLogicInsect/emotionClassifier")
|
| 12 |
+
predictor = EmotionPredictor(MODEL_ID)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class PredictRequest(BaseModel):
|
| 16 |
+
text: str
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class PredictResponse(BaseModel):
|
| 20 |
+
emotion: str
|
| 21 |
+
confidence: float
|
| 22 |
+
all_emotions: dict[str, float]
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
# --- existing REST endpoint (unchanged) ---
|
| 26 |
+
|
| 27 |
+
@app.post("/predict", response_model=PredictResponse)
|
| 28 |
+
async def predict(request: PredictRequest):
|
| 29 |
+
result = predictor.predict(request.text)
|
| 30 |
+
return PredictResponse(**result)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
@app.get("/health")
|
| 34 |
+
async def health():
|
| 35 |
+
return {"status": "ok"}
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
# --- Gradio UI ---
|
| 39 |
+
|
| 40 |
+
def classify(text: str):
|
| 41 |
+
if not text.strip():
|
| 42 |
+
return "Please enter some text.", {}
|
| 43 |
+
result = predictor.predict(text)
|
| 44 |
+
label = f"{result['emotion'].upper()} ({result['confidence']:.1%} confidence)"
|
| 45 |
+
return label, result["all_emotions"]
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
with gr.Blocks(title="Emotion Classifier") as demo:
|
| 49 |
+
gr.Markdown(
|
| 50 |
+
"""
|
| 51 |
+
# Emotion Classifier
|
| 52 |
+
Fine-tuned DistilBERT that detects six emotions: anger, fear, joy, love, sadness, surprise.
|
| 53 |
+
"""
|
| 54 |
+
)
|
| 55 |
+
with gr.Row():
|
| 56 |
+
with gr.Column():
|
| 57 |
+
text_input = gr.Textbox(
|
| 58 |
+
label="Input text",
|
| 59 |
+
placeholder="Type something…",
|
| 60 |
+
lines=3,
|
| 61 |
+
)
|
| 62 |
+
submit_btn = gr.Button("Classify", variant="primary")
|
| 63 |
+
with gr.Column():
|
| 64 |
+
label_output = gr.Textbox(label="Prediction")
|
| 65 |
+
scores_output = gr.Label(label="All emotion scores", num_top_classes=6)
|
| 66 |
+
|
| 67 |
+
submit_btn.click(
|
| 68 |
+
fn=classify,
|
| 69 |
+
inputs=text_input,
|
| 70 |
+
outputs=[label_output, scores_output],
|
| 71 |
+
)
|
| 72 |
+
gr.Examples(
|
| 73 |
+
examples=[
|
| 74 |
+
["I am feeling very happy today!"],
|
| 75 |
+
["This is so frustrating, nothing works."],
|
| 76 |
+
["I miss my family so much."],
|
| 77 |
+
["Wow, I did not expect that at all!"],
|
| 78 |
+
],
|
| 79 |
+
inputs=text_input,
|
| 80 |
+
)
|
| 81 |
+
gr.Markdown(
|
| 82 |
+
"""
|
| 83 |
+
---
|
| 84 |
+
**API endpoint** also available at `/predict` — see `/docs` for the OpenAPI spec.
|
| 85 |
+
"""
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
# Mount Gradio on FastAPI; the UI lives at "/" and the REST API at "/predict"
|
| 89 |
+
app = gr.mount_gradio_app(app, demo, path="/")
|
app/ml/__init__.py
ADDED
|
File without changes
|
app/ml/__pycache__/__init__.cpython-313.pyc
ADDED
|
Binary file (174 Bytes). View file
|
|
|
app/ml/__pycache__/predictor.cpython-313.pyc
ADDED
|
Binary file (5.42 kB). View file
|
|
|
app/ml/predictor.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import torch
|
| 4 |
+
import numpy as np
|
| 5 |
+
from typing import Dict, List, Optional
|
| 6 |
+
from transformers import AutoModelForSequenceClassification, AutoTokenizer
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class EmotionPredictor:
|
| 10 |
+
def __init__(self, model_path: Optional[str] = None, model_id: Optional[str] = None):
|
| 11 |
+
"""
|
| 12 |
+
Initialize the emotion predictor with a pre-trained model
|
| 13 |
+
|
| 14 |
+
Args:
|
| 15 |
+
model_path: Path to the saved model directory. If None, will use the
|
| 16 |
+
environment variable MODEL_PATH or the default "./model_export"
|
| 17 |
+
model_id: HuggingFace Hub model ID (e.g., "your-username/emotion-classifier")
|
| 18 |
+
If provided, will load from HuggingFace instead of local path
|
| 19 |
+
"""
|
| 20 |
+
self.model_path = model_path or os.environ.get("MODEL_PATH", "./model_export")
|
| 21 |
+
self.model_id = model_id or os.environ.get("MODEL_ID")
|
| 22 |
+
self.model = None
|
| 23 |
+
self.tokenizer = None
|
| 24 |
+
self.label2id = None
|
| 25 |
+
self.id2label = None
|
| 26 |
+
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 27 |
+
|
| 28 |
+
# Load the model
|
| 29 |
+
self._load_model()
|
| 30 |
+
|
| 31 |
+
def _load_model(self):
|
| 32 |
+
"""Load the model and tokenizer from local directory or HuggingFace Hub"""
|
| 33 |
+
try:
|
| 34 |
+
# If model_id is provided, load from HuggingFace Hub
|
| 35 |
+
if self.model_id:
|
| 36 |
+
print(f"Loading model from HuggingFace Hub: {self.model_id}")
|
| 37 |
+
self.model = AutoModelForSequenceClassification.from_pretrained(self.model_id)
|
| 38 |
+
self.tokenizer = AutoTokenizer.from_pretrained(self.model_id)
|
| 39 |
+
|
| 40 |
+
# Get label mappings from model config
|
| 41 |
+
self.id2label = self.model.config.id2label
|
| 42 |
+
self.label2id = self.model.config.label2id
|
| 43 |
+
else:
|
| 44 |
+
# Load from local path
|
| 45 |
+
print(f"Loading model from local path: {self.model_path}")
|
| 46 |
+
self.model = AutoModelForSequenceClassification.from_pretrained(self.model_path)
|
| 47 |
+
self.tokenizer = AutoTokenizer.from_pretrained(self.model_path)
|
| 48 |
+
|
| 49 |
+
# Load label mappings
|
| 50 |
+
mappings_path = os.path.join(self.model_path, 'label_mappings.json')
|
| 51 |
+
if os.path.exists(mappings_path):
|
| 52 |
+
with open(mappings_path, 'r') as f:
|
| 53 |
+
mappings = json.load(f)
|
| 54 |
+
self.label2id = mappings['label2id']
|
| 55 |
+
self.id2label = {int(k): v for k, v in mappings['id2label'].items()}
|
| 56 |
+
else:
|
| 57 |
+
# If no mappings file, use the model config
|
| 58 |
+
self.id2label = self.model.config.id2label
|
| 59 |
+
self.label2id = self.model.config.label2id
|
| 60 |
+
|
| 61 |
+
# Move model to appropriate device
|
| 62 |
+
self.model.to(self.device)
|
| 63 |
+
self.model.eval()
|
| 64 |
+
|
| 65 |
+
except Exception as e:
|
| 66 |
+
print(f"Error loading model: {e}")
|
| 67 |
+
|
| 68 |
+
def is_model_loaded(self) -> bool:
|
| 69 |
+
"""Check if the model is loaded"""
|
| 70 |
+
return self.model is not None and self.tokenizer is not None
|
| 71 |
+
|
| 72 |
+
def get_labels(self) -> List[str]:
|
| 73 |
+
"""Get the list of emotion labels"""
|
| 74 |
+
if not self.is_model_loaded():
|
| 75 |
+
raise ValueError("Model is not loaded")
|
| 76 |
+
return list(self.label2id.keys())
|
| 77 |
+
|
| 78 |
+
def predict(self, text: str) -> Dict:
|
| 79 |
+
"""
|
| 80 |
+
Predict the emotion of the input text
|
| 81 |
+
|
| 82 |
+
Args:
|
| 83 |
+
text: Input text to classify
|
| 84 |
+
|
| 85 |
+
Returns:
|
| 86 |
+
Dictionary with prediction results
|
| 87 |
+
"""
|
| 88 |
+
if not self.is_model_loaded():
|
| 89 |
+
raise ValueError("Model is not loaded")
|
| 90 |
+
|
| 91 |
+
# Tokenize the input text
|
| 92 |
+
inputs = self.tokenizer(
|
| 93 |
+
text,
|
| 94 |
+
return_tensors="pt",
|
| 95 |
+
padding=True,
|
| 96 |
+
truncation=True,
|
| 97 |
+
max_length=512
|
| 98 |
+
).to(self.device)
|
| 99 |
+
|
| 100 |
+
# Make prediction
|
| 101 |
+
with torch.no_grad():
|
| 102 |
+
outputs = self.model(**inputs)
|
| 103 |
+
logits = outputs.logits
|
| 104 |
+
probabilities = torch.nn.functional.softmax(logits, dim=1).cpu().numpy()[0]
|
| 105 |
+
|
| 106 |
+
# Get the predicted class and confidence
|
| 107 |
+
predicted_class_id = int(np.argmax(probabilities))
|
| 108 |
+
predicted_emotion = self.id2label[predicted_class_id]
|
| 109 |
+
confidence = float(probabilities[predicted_class_id])
|
| 110 |
+
|
| 111 |
+
# Create the response with all emotion probabilities
|
| 112 |
+
all_emotions = {
|
| 113 |
+
self.id2label[i]: float(prob)
|
| 114 |
+
for i, prob in enumerate(probabilities)
|
| 115 |
+
}
|
| 116 |
+
|
| 117 |
+
return {
|
| 118 |
+
"emotion": predicted_emotion,
|
| 119 |
+
"confidence": confidence,
|
| 120 |
+
"all_emotions": all_emotions
|
| 121 |
+
}
|
app/models.py
ADDED
|
File without changes
|
hf-deployment.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from huggingface_hub import HfApi
|
| 2 |
+
import os
|
| 3 |
+
import json
|
| 4 |
+
import shutil
|
| 5 |
+
from transformers import AutoModelForSequenceClassification, AutoTokenizer
|
| 6 |
+
|
| 7 |
+
def upload_model_to_hf_hub(
|
| 8 |
+
local_model_path,
|
| 9 |
+
hf_model_id,
|
| 10 |
+
hf_token=None
|
| 11 |
+
):
|
| 12 |
+
"""
|
| 13 |
+
Upload a local model to Hugging Face Hub
|
| 14 |
+
|
| 15 |
+
Args:
|
| 16 |
+
:param local_model_path:
|
| 17 |
+
:param hf_model_id:
|
| 18 |
+
:param hf_token:
|
| 19 |
+
:return:
|
| 20 |
+
"""
|
| 21 |
+
# Load the model and tokenizer
|
| 22 |
+
model = AutoModelForSequenceClassification.from_pretrained(local_model_path)
|
| 23 |
+
tokenizer = AutoTokenizer.from_pretrained(local_model_path)
|
| 24 |
+
|
| 25 |
+
# Load label mappings
|
| 26 |
+
label_mappings_path = os.path.join(local_model_path, 'label_mappings.json')
|
| 27 |
+
if os.path.exists(label_mappings_path):
|
| 28 |
+
with open(label_mappings_path, 'r') as f:
|
| 29 |
+
mappings = json.load(f)
|
| 30 |
+
label2id = mappings['label2id']
|
| 31 |
+
id2label = {int(k): v for k, v in mappings['id2label'].items()}
|
| 32 |
+
|
| 33 |
+
# Set the mappings in the model config
|
| 34 |
+
model.config.label2id = label2id
|
| 35 |
+
model.config.id2label = id2label
|
| 36 |
+
|
| 37 |
+
# Push to hub
|
| 38 |
+
model.push_to_hub(hf_model_id, use_auth_token=hf_token)
|
| 39 |
+
tokenizer.push_to_hub(hf_model_id, use_auth_token=hf_token)
|
| 40 |
+
|
| 41 |
+
print(f"Model successfully uploaded to {hf_model_id}")
|
| 42 |
+
print(f"You can now use it with: model = AutoModelForSequenceClassification.from_pretrained('{hf_model_id}')")
|
| 43 |
+
|
| 44 |
+
if __name__ == "__main__":
|
| 45 |
+
local_model_path = "./model_export"
|
| 46 |
+
hf_model_id = "AfroLogicInsect/emotionClassifier"
|
| 47 |
+
|
| 48 |
+
upload_model_to_hf_hub(local_model_path, hf_model_id)
|
| 49 |
+
|
mlflow_tracking/track_experiment.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import json
|
| 4 |
+
import mlflow
|
| 5 |
+
import argparse
|
| 6 |
+
from mlflow.models import infer_signature
|
| 7 |
+
import torch
|
| 8 |
+
from transformers import AutoModelForSequenceClassification, AutoTokenizer
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def register_model(
|
| 12 |
+
model_dir,
|
| 13 |
+
experiment_name="emotion-classification",
|
| 14 |
+
run_name=None,
|
| 15 |
+
tracking_uri=None
|
| 16 |
+
):
|
| 17 |
+
"""
|
| 18 |
+
Register a trained model with MLflow
|
| 19 |
+
|
| 20 |
+
Args:
|
| 21 |
+
model_dir: Directory containing the saved model
|
| 22 |
+
experiment_name: Name of the MLflow experiment
|
| 23 |
+
run_name: Name for this specific run
|
| 24 |
+
tracking_uri: MLflow tracking server URI
|
| 25 |
+
"""
|
| 26 |
+
# Set up MLflow tracking
|
| 27 |
+
if tracking_uri:
|
| 28 |
+
mlflow.set_tracking_uri(tracking_uri)
|
| 29 |
+
print(f"Using MLflow tracking URI: {tracking_uri}")
|
| 30 |
+
else:
|
| 31 |
+
print("Using local MLflow tracking")
|
| 32 |
+
|
| 33 |
+
# Load model metadata
|
| 34 |
+
try:
|
| 35 |
+
with open(os.path.join(model_dir, 'label_mappings.json'), 'r') as f:
|
| 36 |
+
mappings = json.load(f)
|
| 37 |
+
label2id = mappings['label2id']
|
| 38 |
+
id2label = {int(k): v for k, v in mappings['id2label'].items()}
|
| 39 |
+
except Exception as e:
|
| 40 |
+
print(f"Error loading model metadata: {e}")
|
| 41 |
+
return
|
| 42 |
+
|
| 43 |
+
# Load the model and tokenizer
|
| 44 |
+
try:
|
| 45 |
+
model = AutoModelForSequenceClassification.from_pretrained(model_dir)
|
| 46 |
+
tokenizer = AutoTokenizer.from_pretrained(model_dir)
|
| 47 |
+
except Exception as e:
|
| 48 |
+
print(f"Error loading model or tokenizer: {e}")
|
| 49 |
+
return
|
| 50 |
+
|
| 51 |
+
# Set up the experiment
|
| 52 |
+
mlflow.set_experiment(experiment_name)
|
| 53 |
+
|
| 54 |
+
# Start an MLflow run
|
| 55 |
+
with mlflow.start_run(run_name=run_name):
|
| 56 |
+
# Log model parameters
|
| 57 |
+
mlflow.log_param("model_type", model.config.model_type)
|
| 58 |
+
mlflow.log_param("num_labels", model.config.num_labels)
|
| 59 |
+
mlflow.log_param("hidden_size", model.config.hidden_size)
|
| 60 |
+
mlflow.log_param("vocab_size", model.config.vocab_size)
|
| 61 |
+
|
| 62 |
+
# Create a sample input for the model signature
|
| 63 |
+
sample_text = "This is a sample text for the model signature"
|
| 64 |
+
sample_inputs = tokenizer(
|
| 65 |
+
sample_text,
|
| 66 |
+
return_tensors="pt",
|
| 67 |
+
padding=True,
|
| 68 |
+
truncation=True
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
# Create a sample output for the model signature
|
| 72 |
+
with torch.no_grad():
|
| 73 |
+
outputs = model(**sample_inputs)
|
| 74 |
+
logits = outputs.logits
|
| 75 |
+
probabilities = torch.nn.functional.softmax(logits, dim=1).numpy()
|
| 76 |
+
|
| 77 |
+
# Create the model signature
|
| 78 |
+
signature = infer_signature(
|
| 79 |
+
sample_inputs.data,
|
| 80 |
+
{"probabilities": probabilities}
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
# Log the model
|
| 84 |
+
mlflow.transformers.log_model(
|
| 85 |
+
transformers_model={
|
| 86 |
+
"model": model,
|
| 87 |
+
"tokenizer": tokenizer
|
| 88 |
+
},
|
| 89 |
+
artifact_path="emotion-classifier",
|
| 90 |
+
task="text-classification",
|
| 91 |
+
signature=signature
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
# Log additional information
|
| 95 |
+
mlflow.log_dict(label2id, "label2id.json")
|
| 96 |
+
mlflow.log_dict(id2label, "id2label.json")
|
| 97 |
+
|
| 98 |
+
# Get the run ID
|
| 99 |
+
run_id = mlflow.active_run().info.run_id
|
| 100 |
+
print(f"Model registered with MLflow. Run ID: {run_id}")
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
if __name__ == "__main__":
|
| 104 |
+
parser = argparse.ArgumentParser(description="Register a model with MLflow")
|
| 105 |
+
parser.add_argument(
|
| 106 |
+
"--model_dir",
|
| 107 |
+
type=str,
|
| 108 |
+
required=True,
|
| 109 |
+
help="Directory containing the saved model"
|
| 110 |
+
)
|
| 111 |
+
parser.add_argument(
|
| 112 |
+
"--experiment",
|
| 113 |
+
type=str,
|
| 114 |
+
default="emotion-classification",
|
| 115 |
+
help="MLflow experiment name"
|
| 116 |
+
)
|
| 117 |
+
parser.add_argument(
|
| 118 |
+
"--run_name",
|
| 119 |
+
type=str,
|
| 120 |
+
default=None,
|
| 121 |
+
help="Name for this run"
|
| 122 |
+
)
|
| 123 |
+
parser.add_argument(
|
| 124 |
+
"--tracking_uri",
|
| 125 |
+
type=str,
|
| 126 |
+
default=None,
|
| 127 |
+
help="MLflow tracking server URI"
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
args = parser.parse_args()
|
| 131 |
+
register_model(
|
| 132 |
+
args.model_dir, args.experiment,
|
| 133 |
+
args.run_name, args.tracking_uri
|
| 134 |
+
)
|
notebooks/MLEng_init.ipynb
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
requirements.txt
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fastapi==0.115.12
|
| 2 |
+
uvicorn==0.34.0
|
| 3 |
+
transformers==4.50.3
|
| 4 |
+
torch==2.6.0
|
| 5 |
+
pydantic==2.11.1
|
| 6 |
+
numpy==2.2.4
|
| 7 |
+
mlflow==2.21.2
|
| 8 |
+
pytest==8.3.5
|
| 9 |
+
httpx==0.28.1
|
tests/__init__.py
ADDED
|
File without changes
|
tests/test_api.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
from fastapi.testclient import TestClient
|
| 3 |
+
from unittest.mock import patch, MagicMock
|
| 4 |
+
from app.main import app
|
| 5 |
+
|
| 6 |
+
client = TestClient(app)
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def test_read_root():
|
| 10 |
+
"""Test the root endpoint"""
|
| 11 |
+
response = client.get("/")
|
| 12 |
+
assert response.status_code == 200
|
| 13 |
+
assert "message" in response.json()
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def test_health_check():
|
| 17 |
+
"""Test the health check endpoint"""
|
| 18 |
+
with patch("app.ml.predictor.EmotionPredictor.is_model_loaded", return_value=True):
|
| 19 |
+
response = client.get("/health")
|
| 20 |
+
assert response.status_code == 200
|
| 21 |
+
response_data = response.json()
|
| 22 |
+
assert response_data["status"] == "healthy"
|
| 23 |
+
assert response_data["model_loaded"] is True
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@patch("app.ml.predictor.EmotionPredictor.predict")
|
| 27 |
+
def test_predict_endpoint(mock_predict):
|
| 28 |
+
"""Test the prediction endpoint"""
|
| 29 |
+
# Configure the mock to return a specific response
|
| 30 |
+
mock_predict.return_value = {
|
| 31 |
+
"emotion": "happy",
|
| 32 |
+
"confidence": 0.92,
|
| 33 |
+
"all_emotions": {"happy": 0.92, "sad": 0.05, "angry": 0.03}
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
# Make the request
|
| 37 |
+
response = client.post(
|
| 38 |
+
"/predict",
|
| 39 |
+
json={"text": "I'm having a wonderful day!"}
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
# Verify the response
|
| 43 |
+
assert response.status_code == 200
|
| 44 |
+
result = response.json()
|
| 45 |
+
assert result["emotion"] == "happy"
|
| 46 |
+
assert result["confidence"] == 0.92
|
| 47 |
+
assert "all_emotions" in result
|
| 48 |
+
|
| 49 |
+
# Verify the mock was called with the right arguments
|
| 50 |
+
mock_predict.assert_called_once_with("I'm having a wonderful day!")
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
@patch("app.ml.predictor.EmotionPredictor.get_labels")
|
| 54 |
+
def test_get_labels(mock_get_labels):
|
| 55 |
+
"""Test the labels endpoint"""
|
| 56 |
+
# Configure the mock to return specific labels
|
| 57 |
+
mock_get_labels.return_value = ["happy", "sad", "angry"]
|
| 58 |
+
|
| 59 |
+
# Make the request
|
| 60 |
+
response = client.get("/labels")
|
| 61 |
+
|
| 62 |
+
# Verify the response
|
| 63 |
+
assert response.status_code == 200
|
| 64 |
+
assert response.json() == ["happy", "sad", "angry"]
|
tests/test_predictor.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
import os
|
| 3 |
+
import json
|
| 4 |
+
import torch
|
| 5 |
+
from app.ml.predictor import EmotionPredictor
|
| 6 |
+
from unittest.mock import patch, MagicMock
|
| 7 |
+
|
| 8 |
+
# Mock data for testing
|
| 9 |
+
@pytest.fixture
|
| 10 |
+
def mock_predictor():
|
| 11 |
+
"""Create a predictor with mocked components"""
|
| 12 |
+
with patch("app.ml.predictor.AutoModelForSequenceClassification") as mock_model_cls, \
|
| 13 |
+
patch("app.ml.predictor.AutoTokenizer") as mock_tokenizer_cls:
|
| 14 |
+
|
| 15 |
+
# Configure mocks
|
| 16 |
+
mock_model = MagicMock()
|
| 17 |
+
mock_model.eval.return_value = None
|
| 18 |
+
mock_model_cls.from_pretrained.return_value = mock_model
|
| 19 |
+
|
| 20 |
+
# Mock model config
|
| 21 |
+
mock_model.config = MagicMock()
|
| 22 |
+
mock_model.config.id2label = {0: "happy", 1: "sad", 2: "angry"}
|
| 23 |
+
mock_model.config.label2id = {"happy": 0, "sad": 1, "angry": 2}
|
| 24 |
+
|
| 25 |
+
mock_tokenizer = MagicMock()
|
| 26 |
+
mock_tokenizer_cls.from_pretrained.return_value = mock_tokenizer
|
| 27 |
+
|
| 28 |
+
# Create outputs for the model
|
| 29 |
+
outputs = MagicMock()
|
| 30 |
+
logits = torch.tensor([[0.1, 0.2, 0.7]]) # Predicts the third class
|
| 31 |
+
outputs.logits = logits
|
| 32 |
+
mock_model.return_value = outputs
|
| 33 |
+
|
| 34 |
+
# Create a tensor-like object with to() method for tokenizer output
|
| 35 |
+
tokenizer_output = MagicMock()
|
| 36 |
+
tokenizer_output.to = MagicMock(return_value=tokenizer_output)
|
| 37 |
+
mock_tokenizer.return_value = tokenizer_output
|
| 38 |
+
|
| 39 |
+
# Create the predictor with mocked HF model ID
|
| 40 |
+
predictor = EmotionPredictor(model_id="test/emotion-model")
|
| 41 |
+
|
| 42 |
+
# Replace parts with mocks
|
| 43 |
+
predictor.model = mock_model
|
| 44 |
+
predictor.tokenizer = mock_tokenizer
|
| 45 |
+
predictor.id2label = {0: "happy", 1: "sad", 2: "angry"}
|
| 46 |
+
predictor.label2id = {"happy": 0, "sad": 1, "angry": 2}
|
| 47 |
+
predictor.device = "cpu" # Ensure we use CPU for tests
|
| 48 |
+
|
| 49 |
+
return predictor
|
| 50 |
+
|
| 51 |
+
def test_is_model_loaded(mock_predictor):
|
| 52 |
+
"""Test that the model loaded check works"""
|
| 53 |
+
assert mock_predictor.is_model_loaded() is True
|
| 54 |
+
|
| 55 |
+
# Test when model is not loaded
|
| 56 |
+
mock_predictor.model = None
|
| 57 |
+
assert mock_predictor.is_model_loaded() is False
|
| 58 |
+
|
| 59 |
+
def test_get_labels(mock_predictor):
|
| 60 |
+
"""Test retrieving the label list"""
|
| 61 |
+
labels = mock_predictor.get_labels()
|
| 62 |
+
assert set(labels) == {"happy", "sad", "angry"}
|
| 63 |
+
|
| 64 |
+
# Test exception when model not loaded
|
| 65 |
+
mock_predictor.model = None # This will make is_model_loaded() return False
|
| 66 |
+
with pytest.raises(ValueError, match="Model is not loaded"):
|
| 67 |
+
mock_predictor.get_labels()
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def test_predict(mock_predictor):
|
| 71 |
+
"""Test the prediction functionality"""
|
| 72 |
+
# Configure the model to return specific logits
|
| 73 |
+
mock_outputs = MagicMock()
|
| 74 |
+
mock_outputs.logits = torch.tensor([[0.1, 0.2, 2.0]]) # Highest probability for "angry"
|
| 75 |
+
mock_predictor.model.return_value = mock_outputs
|
| 76 |
+
|
| 77 |
+
# Reset the necessary attributes
|
| 78 |
+
mock_predictor.id2label = {0: "happy", 1: "sad", 2: "angry"}
|
| 79 |
+
mock_predictor.label2id = {"happy": 0, "sad": 1, "angry": 2}
|
| 80 |
+
|
| 81 |
+
result = mock_predictor.predict("I am very upset about this situation.")
|
| 82 |
+
|
| 83 |
+
# Verify the prediction result
|
| 84 |
+
assert result["emotion"] == "angry"
|
| 85 |
+
assert result["confidence"] > 0.6 # Should be around 0.7 after softmax
|
| 86 |
+
assert set(result["all_emotions"].keys()) == {"happy", "sad", "angry"}
|