6.4: END-TO-END CAPSTONE PROJECT — DATASET -> FINE-TUNE -> HUB PUSH -> SPACE APP

Bring the entire Hugging Face workflow together in one capstone pipeline: prepare and split a dataset, fine-tune and evaluate a model, push artifacts to the Hub, and serve an interactive Space app—with real-time examples and code.

🎓 Summary: Shipping a Complete AI Workflow from Data to Live App

A strong capstone project or portfolio application proves that you can connect every stage of an ML workflow cleanly—not just run a one-off notebook snippet. In this end-to-end blueprint, you start with a clean dataset (loaded, validated, and split reproducibly), fine-tune and evaluate a model with explicit tokenizer/metric tracking, push the trained model and tokenizer (plus model card and license info) to a Hugging Face Hub repository, and wire a Gradio Space app that loads your published checkpoint and serves real users with sensible guardrails.

Treating each stage as modular, reproducible code with pinned revisions, safe environment secrets, and clear evaluation makes the project easy to grade, demonstrate in interviews, and evolve into a real service.

1. Four-Stage Capstone Architecture
An end-to-end capstone succeeds when each stage has clear inputs, outputs, and verification checks:
  • Stage 1 — Dataset & Split Prep: Load from Hub or local files (CSV/JSONL/Parquet), clean and validate required columns/labels, and create a reproducible train/validation/test split.
  • Stage 2 — Fine-Tuning & Evaluation: Tokenize with matching special tokens and truncation, fine-tune via Trainer (or PEFT/LoRA when needed), and evaluate on a held-out split before choosing the best checkpoint.
  • Stage 3 — Hub Push & Versioning: Save model + tokenizer together, write a clear model card with intended use/limitations/license, and upload to a Hub repo with a clear commit or tag.
  • Stage 4 — Space App & Guardrails: Build a Gradio UI (app.py + requirements.txt + Space README.md) that loads the published model once at startup, validates inputs, handles errors cleanly, and shows helpful examples.
Capstone Stage Key Artifact Produced Exit Check Before Next Stage
1. Dataset Prep Clean train/val/test splits & label map Non-empty splits, valid labels & no leakage
2. Fine-Tune & Eval Trained checkpoint + validation metrics Beats baseline & saves tokenizer alongside model
3. Hub Push Versioned Hub model repo + card Fresh download & reload works cleanly
4. Space App Live Gradio Space with examples Handles empty/long inputs & shows clear UI
Python (capstone_pipeline_blueprint.py)
from datasets import Dataset

def run_capstone_stages_dry_run():
    """End-to-end modular skeleton: Dataset -> Train/Eval -> Hub Push -> Space App."""
    # Stage 1: Dataset load & reproducible split
    raw = Dataset.from_dict({
        "text": [
            "Billing invoice shows wrong tax rate",
            "How do I export my CSV report?",
            "Account locked after three login attempts",
            "Can we add custom webhook retries?",
            "Subscription renewal failed on card",
            "Where can I find API documentation?",
        ],
        "label": [0, 1, 0, 1, 0, 1],  # 0 = Urgent/Support, 1 = General/Product
    })
    splits = raw.train_test_split(test_size=0.33, seed=42)

    # Stage 2: Fine-tune & evaluate (wire AutoTokenizer + AutoModel + Trainer here)
    eval_summary = {
        "base_model": "distilbert-base-uncased",
        "train_rows": len(splits["train"]),
        "test_rows": len(splits["test"]),
        "val_accuracy": 0.90,
    }

    # Stage 3: Hub push metadata (use model.save_pretrained + tokenizer.save_pretrained + upload_folder)
    hub_artifact = {
        "repo_id": "your-username/capstone-ticket-router",
        "revision": "v1.0.0",
        "includes_tokenizer": True,
        "includes_model_card": True,
    }

    # Stage 4: Space app configuration
    space_config = {
        "sdk": "gradio",
        "app_file": "app.py",
        "max_input_chars": 1000,
    }

    return {
        "stage_1_splits": eval_summary,
        "stage_3_hub": hub_artifact,
        "stage_4_space": space_config,
    }

report = run_capstone_stages_dry_run()
for stage, details in report.items():
    print(f"{stage:16s}: {details}")
Output: stage_1_splits : {'base_model': 'distilbert-base-uncased', 'train_rows': 4, 'test_rows': 2, 'val_accuracy': 0.9} stage_3_hub : {'repo_id': 'your-username/capstone-ticket-router', 'revision': 'v1.0.0', 'includes_tokenizer': True, 'includes_model_card': True} stage_4_space : {'sdk': 'gradio', 'app_file': 'app.py', 'max_input_chars': 1000}
2. Real-Time Examples (Part 1: Student & Portfolio Capstone Scenarios)
Five real-time scenarios students tackle when building a capstone project for college evaluation or interviews:
  • 1. Support / Helpdesk Ticket Classifier Capstone: A student collects or prepares domain tickets, fine-tunes a compact transformer classifier, pushes the model to the Hub, and launches a Gradio Space where interviewers can type sample tickets and see predicted categories and confidence scores.
  • 2. Domain FAQ & Study Notes Assistant: Building an interactive demo with clickable example prompts so reviewers can test common questions immediately without hunting for sample inputs.
  • 3. Proving Improvement Over a Baseline in Your Report: Comparing your fine-tuned model's validation metric against a simple baseline (or zero-shot/base model) gives concrete evidence in your project presentation instead of vague claims.
  • 4. Recovering Cleanly from Notebook Disconnects During Capstone Training: Saving checkpoints and pushing final artifacts to the Hub ensures a sudden cloud notebook timeout doesn't derail demo day.
  • 5. Documenting Limitations Honestly in Your Model/Space Card: Explaining training dataset size, supported languages, and known edge cases shows engineering maturity during viva or technical interviews.
Python (capstone_baseline_comparison.py)
def compare_capstone_models(baseline_acc: float, finetuned_acc: float):
    gain = round(finetuned_acc - baseline_acc, 4)
    return {
        "baseline_accuracy": baseline_acc,
        "finetuned_accuracy": finetuned_acc,
        "net_gain": gain,
        "improved": gain > 0,
    }

print("3. Capstone comparison:", compare_capstone_models(0.76, 0.91))
Output: 3. Capstone comparison: {'baseline_accuracy': 0.76, 'finetuned_accuracy': 0.91, 'net_gain': 0.15, 'improved': True}
3. Real-Time Examples (Part 2: Team & Production Capstone Scenarios)
How engineering teams turn an end-to-end prototype into a dependable, maintainable system:
  • 6. Clean Separation Between Training Code & Serving App: Keeping dataset prep and training scripts separate from the Space/inference app makes each part easier to test, update, and re-run independently.
  • 7. End-to-End Smoke Test After Hub Upload: Pulling the newly uploaded Hub repo into a fresh directory or test script and running a sample prediction catches missing tokenizer files or bad config mappings before sharing the link.
  • 8. Input Validation & Friendly Error Messages in the UI: Trimming whitespace, rejecting empty or overly long inputs, and catching inference errors prevents ugly tracebacks in front of users or stakeholders.
  • 9. Pinning Model Revisions & Dependencies for Repeatability: Recording exact model IDs/revisions and required packages ensures the Space app builds and behaves predictably over time.
  • 10. Planning the Next Iteration (Data, Alignment, or Scale): After launching v1 on a Space, teams use real user feedback and error cases to collect better training examples, refine prompts/thresholds, or scale hosting when traffic grows.
Python (capstone_app_handler_template.py)
def capstone_predict_handler(text: str, predict_fn, max_chars: int = 1000):
    """Production-style handler with input guards, error handling, and clean output."""
    cleaned = (text or "").strip()
    if not cleaned:
        return {"ok": False, "message": "Please enter some text to analyze."}
    if len(cleaned) > max_chars:
        return {"ok": False, "message": f"Input exceeds {max_chars} characters."}

    try:
        pred = predict_fn(cleaned)
        return {"ok": True, "input_chars": len(cleaned), "prediction": pred}
    except Exception as exc:
        return {"ok": False, "message": f"Inference failed ({type(exc).__name__}): {exc}"}

sample_classifier = lambda s: {"label": "SUPPORT_URGENT", "confidence": 0.94}
print("8. Valid request :", capstone_predict_handler("Checkout payment failed", sample_classifier))
print("   Empty request :", capstone_predict_handler("   ", sample_classifier))
Output: 8. Valid request : {'ok': True, 'input_chars': 22, 'prediction': {'label': 'SUPPORT_URGENT', 'confidence': 0.94}} Empty request : {'ok': False, 'message': 'Please enter some text to analyze.'}
4. Final Capstone Graduation Checklist
Before presenting or shipping your capstone project, verify these final checkpoints:
  • Data & evaluation integrity: Splits are reproducible, labels are clean, and metrics are measured on held-out data.
  • Artifact & secret hygiene: Model + tokenizer + card are pushed cleanly to the Hub, with zero hardcoded tokens or secrets in code.
  • User-ready app experience: The Space/UI loads once at startup, includes helpful examples, validates inputs, and documents limitations clearly.
Python (capstone_final_checklist.py)
checklist = [
    "Prepare & split dataset cleanly; evaluate fine-tuned model against a baseline.",
    "Save model + tokenizer + card, push to Hugging Face Hub, and test reloading.",
    "Deploy an interactive Gradio Space app with examples, input guards, and clear limits."
]

for item in checklist:
    print("*", item)
Output: * Prepare & split dataset cleanly; evaluate fine-tuned model against a baseline. * Save model + tokenizer + card, push to Hugging Face Hub, and test reloading. * Deploy an interactive Gradio Space app with examples, input guards, and clear limits.