CoolFace
Apppublic

camlas/toxicity

sourceHugging Facemitupdated 10mo agoView on Hugging Face
0likes
App README

Toxicity Prediction API

A FastAPI-based REST API for predicting protein sequence toxicity using ProtBERT embeddings and MHSA-GRU classifier.

Developed by the CAMLAs research team - Francis Rudra D Cruze.

๐Ÿš€ Features

  • โ€”ProtBERT Feature Extraction: Uses state-of-the-art protein language model
  • โ€”MHSA-GRU Classification: Multi-Head Self-Attention with GRU for accurate predictions
  • โ€”Single & Batch Predictions: Process one or multiple sequences
  • โ€”HuggingFace Integration: Automatic model loading from private repository
  • โ€”Production Ready: Health checks, error handling, and comprehensive logging

๐Ÿ“‹ Requirements

  • โ€”Python 3.8+
  • โ€”CUDA-capable GPU (optional, but recommended)
  • โ€”HuggingFace account with access to private repository

๐Ÿ”ง Installation

  1. 1.Clone the repository
bash
git clone https://huggingface.co/spaces/camlas/toxicity
cd toxicity
  1. 1.Create virtual environment
bash
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
  1. 1.Install dependencies
bash
pip install -r requirements.txt
  1. 1.Create `.env` file
bash
echo "HF_TOKEN=your_huggingface_token_here" > .env

Get your HuggingFace token from: https://huggingface.co/settings/tokens

๐ŸŽฏ Usage

Start the API Server

bash
python app.py

Or with uvicorn directly:

bash
uvicorn app:app --host 0.0.0.0 --port 8000 --reload

The API will be available at: http://localhost:8000

Run Tests

bash
python test_api.py

๐Ÿ“ก API Endpoints

1. Root Endpoint

GET /

Returns API information and available endpoints.

bash
curl http://localhost:8000/

2. Health Check

GET /health

Check API status and model loading status.

bash
curl http://localhost:8000/health

Response:

json
{
    "status_code": 200,
    "status": "healthy",
    "service": "Toxicity Prediction API",
    "api_version": "1.0.0",
    "model_version": "MHSA-GRU-Transformer-v1.0",
    "models_loaded": true,
    "device": "cuda",
    "timestamp": "2025-01-21T10:30:00Z"
}

3. Single Prediction

POST /predict

Predict toxicity for a single protein sequence.

Request:

bash
curl -X POST http://localhost:8000/predict \
  -H "Content-Type: application/json" \
  -d '{"sequence": "MKTAYIAKQRQISFVKSHFSRQLE"}'

Response:

json
{
    "status_code": 200,
    "status": "success",
    "success": true,
    "data": {
        "sequence": "MKTAYIAKQRQISFVKSHFSRQLE",
        "sequence_length": 24,
        "prediction": {
            "predicted_class": "Toxic",
            "confidence": 0.85,
            "confidence_level": "high",
            "toxicity_score": 0.925,
            "non_toxicity_score": 0.075
        },
        "metadata": {
            "embedding_model": "ProtBERT",
            "embedding_type": "Bert",
            "model_version": "MHSA-GRU-Transformer-v1.0",
            "device": "cuda"
        }
    },
    "timestamp": "2025-01-21T10:30:00Z",
    "api_version": "1.0.0",
    "processing_time_ms": 45.2
}

4. Batch Prediction

POST /predict/batch

Predict toxicity for multiple sequences at once.

Request in Postman/cURL:

bash
curl -X POST http://localhost:8000/predict/batch \
  -H "Content-Type: application/json" \
  -d '{
    "sequences": [
      "MLLPATMSDKPDMAEIEKFDKSKLKKTETQEKNPLPSKETIEQEKQAGES",
      "MFGLPQQEVSEEEKRAHQEQTEKTLKQAAYVAAFLWVSPMIWHLVKKQWK",
      "MKTAYIAKQRQISFVKSHFSRQLE"
    ]
  }'

Request Body (JSON):

json
{
    "sequences": [
        "MLLPATMSDKPDMAEIEKFDKSKLKKTETQEKNPLPSKETIEQEKQAGES",
        "MFGLPQQEVSEEEKRAHQEQTEKTLKQAAYVAAFLWVSPMIWHLVKKQWK"
    ]
}

Response:

json
{
    "status_code": 200,
    "status": "success",
    "success": true,
    "data": {
        "total_sequences": 2,
        "results": [
            {
                "sequence": "MLLPATMSDKPDMAEIEKFDKSKLKKTETQEKNPLPSKETIEQEKQAGES",
                "sequence_length": 51,
                "predicted_class": "Toxic",
                "toxicity_score": 0.925,
                "confidence": 0.85
            },
            {
                "sequence": "MFGLPQQEVSEEEKRAHQEQTEKTLKQAAYVAAFLWVSPMIWHLVKKQWK",
                "sequence_length": 51,
                "predicted_class": "Non-Toxic",
                "toxicity_score": 0.125,
                "confidence": 0.75
            }
        ],
        "metadata": {
            "embedding_model": "ProtBERT",
            "embedding_type": "Bert",
            "model_version": "MHSA-GRU-Transformer-v1.0",
            "device": "cuda"
        }
    },
    "timestamp": "2025-01-21T10:30:00Z",
    "api_version": "1.0.0",
    "processing_time_ms": 125.8
}

๐Ÿ Python Usage Examples

Single Prediction

python
import requests

response = requests.post(
    "http://localhost:8000/predict",
    json={"sequence": "MKTAYIAKQRQISFVKSHFSRQLE"}
)

result = response.json()
print(f"Predicted Class: {result['data']['prediction']['predicted_class']}")
print(f"Toxicity Score: {result['data']['prediction']['toxicity_score']:.4f}")
print(f"Confidence: {result['data']['prediction']['confidence']:.4f}")

Batch Prediction

python
sequences = [
    "MKTAYIAKQRQISFVKSHFSRQLE",
    "ARNDCEQGHILKMFPSTWYV",
    "MVHLTPEEKS"
]

response = requests.post(
    "http://localhost:8000/predict/batch",
    json={"sequences": sequences}
)

results = response.json()
for i, pred in enumerate(results['data']['results'], 1):
    print(f"Sequence {i}: {pred['predicted_class']} ({pred['toxicity_score']:.4f})")

๐Ÿ“ Project Structure

toxicity-api/
โ”œโ”€โ”€ app.py                 # Main FastAPI application
โ”œโ”€โ”€ requirements.txt       # Python dependencies
โ”œโ”€โ”€ test_api.py           # Test suite
โ”œโ”€โ”€ .env                  # Environment variables (create this)
โ”œโ”€โ”€ models/               # Downloaded models (auto-created)
โ””โ”€โ”€ README.md            # This file

๐Ÿ”’ HuggingFace Repository Structure

Your private repository camlas/toxicity should contain:

camlas/toxicity/
โ”œโ”€โ”€ mhsa_gru_classifier.pth    # Trained MHSA-GRU model
โ”œโ”€โ”€ scaler.pkl                  # Feature scaler
โ”œโ”€โ”€ config.json                 # ProtBERT config
โ”œโ”€โ”€ model.safetensors          # ProtBERT weights
โ”œโ”€โ”€ vocab.txt                   # ProtBERT vocabulary
โ”œโ”€โ”€ tokenizer_config.json      # Tokenizer configuration
โ””โ”€โ”€ special_tokens_map.json    # Special tokens mapping

๐ŸŽจ Model Architecture

  1. 1.Feature Extraction: ProtBERT (1024-dimensional embeddings)
  2. 2.Feature Scaling: StandardScaler
  3. 3.Classification: MHSA-GRU
  4. 4.Multi-Head Self-Attention (3 layers)
  5. 5.Bidirectional GRU (2 layers)
  6. 6.Fully connected layers with dropout

โš ๏ธ Error Codes

  • โ€”MISSING_SEQUENCE: No sequence provided in request
  • โ€”SEQUENCE_TOO_SHORT: Sequence length < 10 amino acids
  • โ€”MODEL_NOT_LOADED: Models failed to load from HuggingFace
  • โ€”INTERNAL_ERROR: Unexpected server error

๐Ÿ“Š Performance

  • โ€”Single prediction: ~40-50ms (GPU)
  • โ€”Batch prediction (10 sequences): ~100-150ms (GPU)
  • โ€”Model loading time: ~10-15 seconds (first time)

๐Ÿ› Troubleshooting

Models not loading

  1. 1.Check your HuggingFace token in .env
  2. 2.Verify you have access to the private repository
  3. 3.Check internet connection
  4. 4.Look at console logs for specific errors

CUDA out of memory

  • โ€”Reduce batch size
  • โ€”Use CPU instead: Set device = "cpu" in code
  • โ€”Process sequences one at a time

Slow predictions

  • โ€”Ensure GPU is being used (check /health endpoint)
  • โ€”First prediction is always slower (model initialization)

๐ŸŒ Public Usage Guidelines

  • โ€”Free to Use: No authentication or API keys required.
  • โ€”Rate Limiting: Fair usage is expected. Please do not abuse the service.
  • โ€”Educational Purpose: Designed for research and educational use.
  • โ€”Medical Disclaimer: Not for clinical diagnosis. See disclaimer below.
  • โ€”Availability: Best effort uptime, not guaranteed 24/7.

โš ๏ธ Medical Disclaimer

IMPORTANT: This API is designed for research and educational purposes only. It should NOT be used for clinical diagnosis or medical decision-making. Always consult qualified medical professionals for diagnostic decisions.

๐Ÿข About CAMLAs

CAMLAs (Centre for Advanced Machine Learning & Applications) is a research organization focused on advancing AI applications in medical imaging and healthcare.

Team Members:

  • โ€”S M Hasan Mahmud โ€“ Principal Investigator & Supervisor Roles: Writing โ€“ Original Draft, Writing โ€“ Review & Editing, Conceptualization, Supervision, Project Administration
  • โ€”Francis Rudra D Cruze โ€“ Lead Developer & Researcher Roles: Methodology, Software, Formal Analysis, Investigation, Resources, Visualization

๐Ÿ“ž Support & Contact

  • โ€”Issues: GitHub Repository Issues
  • โ€”Email: drhasan.swe@diu.edu.bd
  • โ€”Documentation: This README
  • โ€”API Status: Check /health endpoint
  • โ€”Website Integration: Perfect for ovarian.francisrudra.com

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.


CAMLAs - Center for Advanced Machine Learning and Applications Advancing Medical AI Research with Public FastAPI ๐ŸŒ๐Ÿš€