YAML Metadata Warning:empty or missing yaml metadata in repo card

Check out the documentation for more information.

Cell 5: Enhanced Model Card Upload

This cell should be run AFTER the training cell to upload a professional model card

from huggingface_hub import HfApi import os from datetime import datetime

def create_enhanced_model_card(repo_id, model_info, training_stats): """Create a comprehensive model card with training statistics"""
# Use variables from training cell instead of hardcoded values num_classes = model_info.get('num_classes', len(model_info.get('classes', []))) classes_list = model_info.get('classes', []) current_date = datetime.now().strftime("%Y-%m-%d")
model_card = f"""--- license: apache-2.0 tags: - image-classification - hair-type - andre-walker - pytorch - resnet50 datasets: - custom metrics: - accuracy - f1 model-index: - name: hair-type-classifier results: - task: type: image-classification name: Hair Type Classification metrics: - type: accuracy value: {training_stats.get('val_accuracy', 'N/A')} name: Validation Accuracy - type: f1 value: {training_stats.get('val_f1', 'N/A')} name: Validation F1-Score

Hair Type Classifier πŸ’‡β€β™€οΈ

A deep learning model for classifying hair types according to the Andre Walker Hair Classification System using a fine-tuned ResNet-50 architecture.

πŸ“Š Model Performance

Metric Value
Validation Accuracy {training_stats.get('val_accuracy', 'N/A')}
Validation F1-Score {training_stats.get('val_f1', 'N/A')}
Training Epochs {training_stats.get('epochs_trained', 'N/A')}
Best Epoch {training_stats.get('best_epoch', 'N/A')}
Classes Detected {num_classes}

🎯 Supported Hair Types

This model was trained to classify the following hair types: {chr(10).join([f"- {hair_type}: Andre Walker classification" for hair_type in classes_list])}

πŸ—οΈ Model Architecture

  • Base Model: ResNet-50 (ImageNet pretrained)
  • Fine-tuning Strategy: Frozen backbone with trainable classification head
  • Input Size: 224Γ—224 RGB images
  • Output: {num_classes}-class probability distribution

πŸš€ Quick Start

Installation

```bash pip install torch torchvision transformers pillow ```

Usage

```python from transformers import AutoModelForImageClassification, AutoFeatureExtractor from PIL import Image import requests

url = 'http://localhost:8000/andre-walker-hair-type-classifier' model = AutoModelForImageClassification.from_pretrained(url) feature_extractor = AutoFeatureExtractor.from_pretrained(url)

image = Image.open(requests.get('http://localhost:8000/sample.jpg', stream=True).raw) inputs = feature_extractor(images=image, return_tensors="pt") outputs = model(**inputs) logits = outputs.logits predicted_class_idx = logits.argmax(-1).item() print(f"Predicted hair type: {classes_list[predicted_class_idx]}") ```

Contributing

Feel free to contribute to this model by opening issues or pull requests on the GitHub repository.

πŸ“ License

This model is licensed under the Apache-2.0 license. See the LICENSE file for details.

πŸ“… Date

This model card was last updated on {current_date}. """

return model_card

def upload_model_card(target_repo_id, model_info, training_stats, hf_token): """Upload the enhanced model card to the Hugging Face repository""" api = HfApi() enhanced_model_card = create_enhanced_model_card(target_repo_id, model_info, training_stats)

print("πŸ“€ Uploading enhanced model card to Hugging Face...")

api.upload_file(
    path_or_fileobj=enhanced_model_card.encode('utf-8'),
    path_in_repo="README.md",  # Exact case-sensitive filename
    repo_id=target_repo_id,
    commit_message="Overwrite README.md with comprehensive model card and training statistics",
    token=hf_token,
    create_pr=False  # Ensure direct commit, not PR
)

print("βœ… Enhanced model card uploaded successfully!")
print(f"🌐 View your model at: https://huggingface.co/{target_repo_id}")

try:
    files = api.list_repo_files(repo_id=target_repo_id, token=hf_token)
    if "README.md" in files:
        print("βœ… README.md confirmed on repository")
    else:
        print("⚠️ README.md not found in repository files")
        print(f"πŸ“‹ Available files: {files}")
except Exception as verify_error:
    print(f"⚠️ Could not verify upload: {verify_error}")

Main execution - references variables from training cell

try: print("πŸ” Checking for required variables from training cell...")

# Get HF token and API (should be available from previous cells)
hf_token = os.getenv('HF_TOKEN')
if not hf_token:
    print("❌ HF_TOKEN not found. Please run the setup cells first.")
    raise ValueError("HF_TOKEN is required")

api = HfApi()
me = api.whoami(token=hf_token)

# Use repo_id from training cell if available, otherwise create it
if 'repo_id' in globals():
    target_repo_id = repo_id
    print(f"βœ… Using repo_id from training cell: {target_repo_id}")
else:
    target_repo_id = f"{me['name']}/hair-classifier"
    print(f"⚠️ No repo_id found, using default: {target_repo_id}")

# Use model_info from training cell if available
if 'model_info' in globals():
    model_info_for_card = model_info
    print(f"βœ… Using model_info from training cell: {len(model_info_for_card.get('classes', []))} classes")
elif 'data_module' in globals():
    model_info_for_card = {
        'repo_id': target_repo_id,
        'classes': data_module.classes if hasattr(data_module, 'classes') else [],
        'num_classes': len(data_module.classes) if hasattr(data_module, 'classes') else 0
    }
    print(f"βœ… Created model_info from data_module: {len(model_info_for_card.get('classes', []))} classes")
else:
    print("⚠️ No model info found from training cell. Using defaults.")
    model_info_for_card = {
        'repo_id': target_repo_id,
        'classes': ['1A', '1B', '1C'],  # Fallback based on your training output
        'num_classes': 3
    }

# Extract training statistics from trainer if available
training_stats_for_card = {}
if 'trainer' in globals() and hasattr(trainer, 'logged_metrics'):
    metrics = trainer.logged_metrics
    training_stats_for_card = {
        'val_accuracy': f"{metrics.get('val_accuracy', 0):.1%}",
        'val_f1': f"{metrics.get('val_f1', 0):.1%}",
        'epochs_trained': trainer.current_epoch + 1 if hasattr(trainer, 'current_epoch') else 'N/A',
        'best_epoch': trainer.current_epoch + 1 if hasattr(trainer, 'current_epoch') else 'N/A'
    }
    print(f"βœ… Using training stats from trainer: {training_stats_for_card}")
else:
    # Fallback to your actual training results
    training_stats_for_card = {
        'val_accuracy': '76.7%',
        'val_f1': '31.1%',
        'epochs_trained': 25,
        'best_epoch': 4
    }
    print(f"⚠️ Using fallback training stats: {training_stats_for_card}")

upload_model_card(target_repo_id, model_info_for_card, training_stats_for_card, hf_token)

except Exception as e: print(f"❌ Error creating model card: {e}") print("Please check your HF_TOKEN and ensure the training cell was run first.") import traceback traceback.print_exc()

Downloads last month

-

Downloads are not tracked for this model. How to track
Inference Providers NEW
This model isn't deployed by any Inference Provider. πŸ™‹ Ask for provider support