A tiny fabric/material classifier for garments with calibrated mixture outputs and mobile-friendly exports. Features structured CLI outputs (JSON/CSV) for seamless integration with data analysis workflows.
- 8 Fabric Types: cotton, denim, leather, silk, velvet, wool, linen, synthetic
- MobileNetV3-Small Backbone: Efficient and accurate classification
- Calibrated Outputs: Temperature scaling and conformal prediction
- Multiple Export Formats: ONNX, TorchScript (TFLite stub)
- CLI Interface: Complete command-line tooling with structured outputs
- Structured Outputs: JSON/CSV formats with stable schemas for data analysis
- FastAPI Server: Production-ready microservice
- White Balance Correction: Optional gray-world preprocessing
pip install fabriclitefrom fabriclite import FabricClassifier
# Load pretrained model
classifier = FabricClassifier.from_pretrained()
# Classify an image
result = classifier.predict("path/to/image.jpg")
print(result)
# {'cotton': 0.82, 'denim': 0.12, 'silk': 0.06}
# Batch processing
results = classifier.predict_batch(["img1.jpg", "img2.jpg", "img3.jpg"])
# With white balance correction
result = classifier.predict("image.jpg", white_balance=True)The CLI supports both human-readable and structured outputs for maximum flexibility:
# Single image inference (human-readable output)
fabriclite infer image.jpg
# Single image inference with structured output
fabriclite infer image.jpg --json --pretty
fabriclite infer image.jpg --csv > result.csv
# Batch processing (human-readable output)
fabriclite batch /path/to/images
# Batch processing with structured output
fabriclite batch /path/to/images --json --output results.jsonl
fabriclite batch /path/to/images --json --output results.json --pretty
fabriclite batch /path/to/images --csv --output results.csv
# Train a model
fabriclite train /path/to/train /path/to/val --epochs 15
# Evaluate model
fabriclite eval /path/to/test weights.pt
# Calibrate model
fabriclite calibrate /path/to/val weights.pt --output temp.json
# Export model
fabriclite export weights.pt --format onnx --output model.onnxNEW in v0.2.0: The CLI now supports structured outputs with --json and --csv flags for seamless integration with data analysis tools:
JSON Output:
- Single object for
infercommand - JSONL (one object per line) for
batchcommand by default - JSON array when output file has
.jsonextension - Use
--prettyfor formatted JSON
CSV Output:
- Fixed schema:
image,predicted_label,confidence,cotton,denim,leather,linen,silk,synthetic,velvet,wool - Stable column ordering across all outputs
- Compatible with data analysis tools
Example JSON Structure:
{
"image": "path/to/image.jpg",
"predicted_label": "denim",
"confidence": 0.45,
"topk": [
{"label": "denim", "prob": 0.45},
{"label": "cotton", "prob": 0.32},
{"label": "silk", "prob": 0.23}
],
"probs": {
"cotton": 0.32,
"denim": 0.45,
"leather": 0.01,
"linen": 0.00,
"silk": 0.23,
"synthetic": 0.00,
"velvet": 0.00,
"wool": 0.00
}
}# Start server
python examples/server_fastapi.py
# Or with uvicorn
uvicorn examples.server_fastapi:app --reloadVisit http://localhost:8000/docs for API documentation.
from fabriclite.export import to_onnx
# Export to ONNX
to_onnx(classifier.model, "model.onnx")from fabriclite.export import to_torchscript
# Export to TorchScript
to_torchscript(classifier.model, "model.pt")FabricLite supports temperature scaling for better calibration:
# Calibrate model
optimal_temp = classifier.calibrate(val_logits, val_labels)
print(f"Optimal temperature: {optimal_temp}")
# Use calibrated predictions
result = classifier.predict("image.jpg")Organize your data in the following structure:
data/
├── train/
│ ├── cotton/
│ │ ├── image1.jpg
│ │ └── image2.jpg
│ ├── denim/
│ │ └── image3.jpg
│ └── ...
├── val/
│ ├── cotton/
│ └── ...
└── test/
├── cotton/
└── ...
# Basic training
fabriclite train data/train data/val --epochs 15 --lr 3e-4
# With white balance
fabriclite train data/train data/val --wb --epochs 20
# Custom batch size
fabriclite train data/train data/val --batch-size 32Training will save:
artifacts/weights.pt- Best model weightsartifacts/metadata.json- Training metadataartifacts/training_history.png- Training curves
# Evaluate model
fabriclite eval data/test weights.pt --report report.json --cm confusion.pngThis generates:
- Accuracy and F1 scores
- Confusion matrix plot
- Detailed classification report
class FabricClassifier:
@classmethod
def from_pretrained(cls, name="mobilenet_v3_small", device=None, weights_url=None)
def predict(self, x, topk=3, white_balance=False) -> Dict[str, float]
def predict_batch(self, images, topk=3, white_balance=False) -> List[Dict[str, float]]
def predict_proba(self, x, white_balance=False) -> torch.Tensor
def calibrate(self, val_logits, val_labels) -> float
def save(self, path)
def load_calibration(self, path)from fabriclite.preprocess import preprocess, apply_gray_world
# Basic preprocessing
tensor = preprocess("image.jpg")
# With white balance
tensor = preprocess("image.jpg", white_balance=True)
# Custom size
tensor = preprocess("image.jpg", size=128)- cotton - Cotton and cotton blends
- denim - Denim, jeans fabric, blue denim
- leather - Genuine leather, faux leather, suede
- silk - Silk, satin, chiffon, crepe
- velvet - Velvet, velour, velveteen
- wool - Wool, merino, cashmere, alpaca
- linen - Linen, flax, hemp
- synthetic - Polyester, nylon, rayon, viscose, acrylic
Pretrained weights are automatically downloaded from Hugging Face Hub. You can also:
- Set
FABRICLITE_WEIGHTSenvironment variable to point to local weights - Use
--weightsparameter in CLI commands - Provide custom
weights_urlinfrom_pretrained()
# Clone repository
git clone https://github.com/Deep-De-coder/fabric_lite.git
cd fabric_lite
# Install in development mode
pip install -e ".[dev]"
# Setup pre-commit hooks
pre-commit install
# Run tests
pytest
# Format code
black src/ tests/
isort src/ tests/
# Lint code
flake8 src/ tests/make setup # Install dependencies and setup pre-commit
make test # Run tests
make fmt # Format code
make lint # Lint code
make serve # Start FastAPI server
make clean # Clean build artifactsApache-2.0 License. See LICENSE for details.
Usage Terms:
- ✅ Research & Academic Use: Open and free for research, academic, and educational purposes
- 📧 Commercial Use: Please contact the author (Deep-De-coder) for commercial licensing terms
Contributions are welcome! Please feel free to submit issues and pull requests.
@software{fabriclite2025,
title={FabricLite: A Tiny Fabric Classifier for Garments},
author={Deep-De-coder},
year={2025},
url={https://github.com/Deep-De-coder/fabric_lite},
note={A production-ready Python package for fabric classification with MobileNetV3-Small backbone, calibrated outputs, and mobile-friendly exports}
}- NEW: Structured CLI outputs (JSON/CSV)
- NEW:
--json,--csv, and--prettyflags for infer and batch commands - NEW: Stable key ordering and consistent schemas
- NEW: JSONL and JSON array output formats for batch processing
- NEW: Comprehensive test coverage for structured outputs
- IMPROVED: Enhanced CLI flexibility for data analysis workflows
- Initial release
- MobileNetV3-Small backbone
- 8 fabric type classification
- CLI and FastAPI interfaces
- ONNX and TorchScript export
- Temperature scaling calibration
- White balance preprocessing