Image Classification
Keras
tensorflow
computer-vision
medical
dermatology
skin-disease
efficientnet
healthcare
Run this model with HF Jobs
Run Siraja704/DermaAI on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/Siraja704/DermaAI. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/Siraja704/DermaAI on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use Siraja704/DermaAI with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Keras
How to use Siraja704/DermaAI with Keras:
# !pip install -U keras tensorflow huggingface_hub # Keras needs TensorFlow installed to read "hf://" paths, so the tensorflow backend is selected here; # "jax" and "torch" also work for computation once TensorFlow is installed. import os os.environ["KERAS_BACKEND"] = "tensorflow" import keras model = keras.saving.load_model("hf://Siraja704/DermaAI") - Notebooks
- Google Colab
- Kaggle
Update README with comprehensive usage instructions and Flask API examples
Browse files6 unmodified lines7891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253546 unmodified lines- medical- dermatology- image-classificationlibrary_name: keras---# DermaAI## Model DescriptionDermaAI - Dermatology AI ModelThis is a Keras model for dermatology AI applications, designed to assist in skin condition analysis.## Model Details- **Model Type**: Keras/TensorFlow model- **Task**: Image Classification- **Domain**: Medical/Dermatology- **Framework**: TensorFlow/Keras## Usage```pythonimport tensorflow as tffrom huggingface_hub import hf_hub_download# Download the modelmodel_path = hf_hub_download(repo_id="your-username/dermaai", filename="DermaAI.keras")# Load the modelmodel = tf.keras.models.load_model(model_path)# Use the model for predictions# predictions = model.predict(your_image_data)```## Training DataPlease provide information about the training data used for this model.## Limitations and BiasThis model is intended for research and educational purposes. It should not be used as a substitute for professional medical diagnosis.## CitationIf you use this model, please cite appropriately.6 unmodified lines7891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453466 unmodified lines- medical- dermatology- image-classification- skin-disease- efficientnet- healthcarelibrary_name: keraspipeline_tag: image-classification---# DermaAI - Skin Disease Classification ModelA deep learning model for classifying skin diseases using computer vision. This model can identify 5 different skin conditions with confidence scores and medical recommendations.## π₯ Supported Skin ConditionsThe model can classify the following skin diseases:1. **Atopic Dermatitis** - A chronic inflammatory skin condition2. **Eczema** - Inflammatory skin condition causing red, itchy patches3. **Psoriasis** - Autoimmune condition causing scaly skin patches4. **Seborrheic Keratoses** - Common benign skin growths5. **Tinea Ringworm Candidiasis** - Fungal skin infections## π§ Model Details- **Model Type**: Keras/TensorFlow model based on EfficientNetV2- **Task**: Image Classification (Multi-class)- **Domain**: Medical/Dermatology- **Framework**: TensorFlow/Keras- **Input Size**: 224x224x3 (RGB images)- **Output**: 5-class probability distribution- **Preprocessing**: EfficientNetV2 preprocessing## π Quick Start### Basic Usage```pythonimport tensorflow as tffrom huggingface_hub import hf_hub_downloadimport numpy as npfrom PIL import Imagefrom tensorflow.keras.applications.efficientnet_v2 import preprocess_input# Download and load the modelmodel_path = hf_hub_download(repo_id="Siraja704/DermaAI", filename="DermaAI.keras")model = tf.keras.models.load_model(model_path)# Class namesclass_names = ['Atopic Dermatitis','Eczema','Psoriasis','Seborrheic Keratoses','Tinea Ringworm Candidiasis']# Prediction functiondef predict_skin_condition(image_path):# Load and preprocess imageimage = Image.open(image_path).convert('RGB')image = image.resize((224, 224))image_array = np.array(image)image_array = preprocess_input(image_array)image_array = np.expand_dims(image_array, axis=0)# Make predictionpredictions = model.predict(image_array)predicted_class_index = np.argmax(predictions[0])predicted_class = class_names[predicted_class_index]confidence = predictions[0][predicted_class_index] * 100return predicted_class, confidence# Example usageprediction, confidence = predict_skin_condition("path/to/your/image.jpg")print(f"Prediction: {prediction} ({confidence:.2f}% confidence)")```## π Flask API UsageCreate a complete web API for skin disease classification:### 1. Install Dependencies```bashpip install flask numpy tensorflow pillow flask-cors huggingface-hub```### 2. Create Flask Application (`app.py`)```pythonfrom flask import Flask, request, jsonifyimport numpy as npimport tensorflow as tfimport base64import iofrom PIL import Imagefrom flask_cors import CORSfrom tensorflow.keras.applications.efficientnet_v2 import preprocess_inputfrom huggingface_hub import hf_hub_downloadapp = Flask(__name__)CORS(app)# Download and load the model from Hugging Faceprint("Downloading model from Hugging Face...")model_path = hf_hub_download(repo_id="Siraja704/DermaAI", filename="DermaAI.keras")model = tf.keras.models.load_model(model_path)print("β Model loaded successfully!")# Class namesclass_names = ['Atopic Dermatitis','Eczema','Psoriasis','Seborrheic Keratoses','Tinea Ringworm Candidiasis']@app.route('/predict', methods=['POST'])def predict():try:data = request.jsonif not data or 'image' not in data:return jsonify({'error': 'No image data provided'}), 400# Process base64 imageimage_data = data['image']if 'base64,' in image_data:image_data = image_data.split('base64,')[1]# Decode and preprocess imagedecoded_image = base64.b64decode(image_data)image = Image.open(io.BytesIO(decoded_image)).convert('RGB')image = image.resize((224, 224))image_array = np.array(image)image_array = preprocess_input(image_array)image_array = np.expand_dims(image_array, axis=0)# Make predictionpredictions = model.predict(image_array)predicted_class_index = int(np.argmax(predictions[0]))predicted_class = class_names[predicted_class_index]confidence = float(predictions[0][predicted_class_index] * 100)# Get top alternativestop_indices = np.argsort(predictions[0])[-3:][::-1]top_predictions = [{'class': class_names[i],'confidence': float(predictions[0][i] * 100)}for i in top_indices if i != predicted_class_index]# Generate medical recommendationif confidence < 10:recommendation = "Very low confidence. Please retake image with better lighting and focus."elif confidence < 30:recommendation = "Low confidence. Preliminary result only. Consult a dermatologist."elif confidence < 60:recommendation = "Moderate confidence. Consider alternatives and consult healthcare professional."else:recommendation = "High confidence prediction. Always consult healthcare professional for confirmation."return jsonify({'prediction': predicted_class,'confidence': round(confidence, 2),'all_confidences': {class_names[i]: float(pred * 100) for i, pred in enumerate(predictions[0])},'top_alternatives': top_predictions,'recommendation': recommendation})except Exception as e:return jsonify({'error': str(e)}), 500@app.route('/health', methods=['GET'])def health():return jsonify({'status': 'healthy', 'model_loaded': True})if __name__ == '__main__':app.run(host='0.0.0.0', port=5001, debug=True)```### 3. Run the API```bashpython app.py```The API will be available at `http://localhost:5001`### 4. API Usage Examples**Python Client:**```pythonimport requestsimport base64def predict_image(image_path, api_url="http://localhost:5001/predict"):with open(image_path, "rb") as image_file:encoded_string = base64.b64encode(image_file.read()).decode('utf-8')data = {"image": f"data:image/jpeg;base64,{encoded_string}"}response = requests.post(api_url, json=data)return response.json()# Usageresult = predict_image("skin_image.jpg")print(f"Prediction: {result['prediction']} ({result['confidence']}%)")```**JavaScript Client:**```javascriptasync function predictSkinCondition(imageFile) {const base64 = await new Promise((resolve) => {const reader = new FileReader();reader.onload = () => resolve(reader.result);reader.readAsDataURL(imageFile);});const response = await fetch('http://localhost:5001/predict', {method: 'POST',headers: {'Content-Type': 'application/json'},body: JSON.stringify({image: base64})});return await response.json();}```**cURL:**```bashcurl -X POST http://localhost:5001/predict \-H "Content-Type: application/json" \-d '{"image": "data:image/jpeg;base64,YOUR_BASE64_IMAGE_HERE"}'```## π API Response Format```json{"prediction": "Eczema","confidence": 85.23,"all_confidences": {"Atopic Dermatitis": 12.45,"Eczema": 85.23,"Psoriasis": 1.32,"Seborrheic Keratoses": 0.67,"Tinea Ringworm Candidiasis": 0.33},"top_alternatives": [{"class": "Atopic Dermatitis","confidence": 12.45}],"recommendation": "High confidence prediction. Always consult healthcare professional for confirmation."}```## πΌοΈ Image Requirements- **Formats**: JPG, PNG, WebP, and other common formats- **Size**: Automatically resized to 224x224 pixels- **Quality**: High-resolution images with good lighting work best- **Focus**: Ensure affected skin area is clearly visible## π³ Docker Deployment**Dockerfile:**```dockerfileFROM python:3.9-slimWORKDIR /appCOPY requirements.txt .RUN pip install -r requirements.txtCOPY app.py .EXPOSE 5001CMD ["python", "app.py"]```**Requirements.txt:**```txtflask>=2.0.0numpy>=1.21.0tensorflow>=2.13.0pillow>=9.0.0flask-cors>=3.0.0huggingface-hub>=0.20.0```**Build and Run:**```bashdocker build -t dermaai-api .docker run -p 5001:5001 dermaai-api```## βοΈ Important Medical Disclaimer**This model is for educational and research purposes only. It should NOT be used as a substitute for professional medical diagnosis or treatment. Always consult qualified healthcare professionals for proper medical evaluation and treatment of skin conditions.**## π Performance Notes- **Input**: 224x224 RGB images- **Preprocessing**: EfficientNetV2 normalization- **Architecture**: Based on EfficientNetV2- **Classes**: 5 skin disease categories- **Confidence Levels**:- Low: < 30% (requires professional consultation)- Moderate: 30-60% (consider alternatives)- High: > 60% (still requires medical confirmation)## π€ CitationIf you use this model in your research or applications, please cite appropriately:```bibtex@misc{dermaai2024,title={DermaAI: Deep Learning Model for Skin Disease Classification},author={Siraja704},year={2024},publisher={Hugging Face},url={https://huggingface.co/Siraja704/DermaAI}}```## π LicenseLicensed under the Apache 2.0 License. See the LICENSE file for details.## π Links- **Model Repository**: [Siraja704/DermaAI](https://huggingface.co/Siraja704/DermaAI)- **Framework**: [TensorFlow](https://tensorflow.org)- **Base Architecture**: [EfficientNetV2](https://arxiv.org/abs/2104.00298)
README.md+311-19