Start

06/07/2026

Close

Smoker Classification Challenge

Machine Learning for Smoker Identification

Challenge Rewards:

knowledge

Participants

31

Submissions

19

Smoker Classification Baseline Source Code

License Python System

Challenge participants: Classify images as smoker or non-smoker using deep learning.

Table of Contents

Quick Start

Clone the repository:

git clone [email protected]:AIOZAI/smoker_classification_baseline.git

Or download directly: Smoker Classification Baseline

Then, navigate into the project directory and follow the steps below:

# 1. Install dependencies (Do not add any other libraries to requirements.txt file)
pip install -r requirements.txt

# 2. Start developing your solution. Follow the tutorial below to implement your AI model

# 3. Run the demo to test your implementation
python demo.py

# 4. Verify Your Submission
python -m my_ai_lib.predict_submission

Note: You need to implement your smoker classification solution following the tutorial guide.

Introduction

Smoker classification addresses the task of identifying whether individuals in images are engaged in smoking activity. This binary classification problem uses computer vision and deep learning to distinguish between smoker and non-smoker images. Automated detection of smoking behavior supports applications such as public health surveillance, workplace safety enforcement, and content moderation, reducing manual review effort across large image datasets.

In this challenge, participants will be provided with:

  • Model Access: Smoker Classification Baseline

    • Code baseline to develop solutions.
    • Predefined libraries and tools in requirements.txt (Do not add any other libraries to requirements.txt file).
  • Dataset Access: Smoker Classification Dataset

    • Training dataset to train your AI models (includes ground_truth.csv).
    • Testing dataset to predict labels for generating the submission file.

Goal: Classify each image into one of two categories: Non-Smoker (0) or Smoker (1).

Requirements

System Requirements

  • Python 3.10+
  • CUDA-compatible GPU (recommended)

Dependencies

Install all required packages:

pip install -r requirements.txt

Project Structure

Your AI library should follow this structure:

repository/
├── my_ai_lib/                   # Your AI library
│   ├── __init__.py              # Required: Library initialization
│   ├── run.py                   # Required: Main workflow function
│   ├── predict_submission.py    # Required: Submission function
│   └── [your_modules]/          # Your custom modules
├── models/                      # Model weights directory
├── demo.py                      # Demo script
├── requirements.txt             # Dependencies
└── README.md                    # Documentation

Description

  • The input and output of the AI model are defined in my_ai_lib/run.py.
  • The AI model is designed to process a single input item (an image file path).
  • In my_ai_lib/predict_submission.py, we process all items in the test dataset and save the results to result.csv in the required submission format.
  • Please refer to the instructions below for more details.

Key Components

ComponentDescriptionStatus
my_ai_lib/Core AI library directoryRequired
my_ai_lib/__init__.pyLibrary initializationRequired
my_ai_lib/predict_submission.pyGenerate predictions for challenge submission.Required
my_ai_lib/run.pyMain AI workflowRequired
demo.pyDemo and testing scriptRequired

Detailed Tutorial

Step 1: Initialize Your AI Library

1.1 Define my_ai_lib/__init__.py

from .run import run

This file exposes the run() function from run.py as an attribute of my_ai_lib, so you can call it as my_ai_lib.run().

1.2 Define Input/Output Objects in my_ai_lib/run.py

Create your custom input and output classes:

from pathlib import Path
from typing import Any, Union, Literal
from aioz_ainode_adapter.schemas import InputObject, OutputObject, FileObject

class SmokerInput(InputObject):
    # image_path is the local path to the input image
    image_path: str

class SmokerOutput(OutputObject):
    # label is the predicted class (0: Non-Smoker, 1: Smoker)
    label: int

Step 2: Understanding AIOZ Schema Objects

The aioz_ainode_adapter library defines 3 core object types based on pydantic.BaseModel:

🔸 InputObject

Define the format for input when the AIOZ-AI-Node system sends to your AI library.

Default Parameters:

ParameterTypeDescription
deviceChoiceDevice for your model: ["cuda", "cpu", "gpu"]
model_storage_directoryStringDirectory containing model weights

Important: Always use model_storage_directory for model weight paths, as AIOZ-AI-Node will specify this location.

🔸 OutputObject

Define the format for output when your AI library sends to the AIOZ-AI-Node system.

🔸 FileObject

Define the format for the file, if your output has a file. This object has two fields:

FieldTypeDescription
dataChoiceFile data: io.BufferedReader, Path, or URL
nameStringFile name

Example FileObject creation:

output_file = FileObject(data=open("file/path.csv", "rb"), name="output.csv")

Note:

  • Input files must be local file paths or URLs
  • Output files must be FileObject instances

Step 3: Implement the Main Workflow

3.1 Define Your AI Task Function

def do_ai_task(
        image_path: str,
        model_storage_directory: Union[str, Path],
        device: Literal["cpu", "cuda", "gpu"] = "cpu",
        *args, **kwargs) -> int:
    """
    Predict if the image contains smoking activity.

    Args:
        image_path: Path to the image file
        model_storage_directory: Path to directory containing trained model weights
        device: Device to run inference on ("cpu", "cuda", or "gpu")

    Returns:
        label: Predicted class (0: Non-Smoker, 1: Smoker)
    """
    # 1. Load and preprocess image from image_path
    # Example using Pillow:
    # from PIL import Image
    # img = Image.open(image_path)

    # 2. Run prediction using your trained model
    # label = model.predict(img)
    label = 0
    return label

3.2 Implement the Required run() Function

def run(input_obj: InputObject) -> OutputObject:
    """
    Main entry point for the Smoker Classification library.

    Args:
        input_obj: Input object containing image path and parameters

    Returns:
        output_obj: Object containing the predicted label
    """
    try:
        # Validate and parse input
        smoker_input = SmokerInput.model_validate(input_obj.model_dump())

        # Execute AI task
        label = do_ai_task(
            image_path=smoker_input.image_path,
            model_storage_directory=smoker_input.model_storage_directory,
            device=smoker_input.device
        )
        # Create output object
        output_obj = SmokerOutput(label=label)
    except Exception as e:
        raise Exception(e)

    return output_obj

Critical: The run() function name is mandatory and cannot be changed. The do_ai_task() function can be renamed and customized.

Step 4: Create Demo Script

Create demo.py to test your implementation:

import my_ai_lib
from aioz_ainode_adapter.schemas import InputObject

def main():
    """Demo function to test the Smoker Classification library."""
    # Example input: path to a test image
    image_path = "path/to/sample_image.jpg"

    input_obj = InputObject(
        image_path=image_path
    )
    output_obj = my_ai_lib.run(input_obj)
    print(f"Output: {output_obj}")

    # Map label to class name
    class_names = {0: "Non-Smoker", 1: "Smoker"}
    print(f"Predicted Class: {class_names.get(output_obj.label, 'Unknown')}")

if __name__ == '__main__':
    main()

The my_ai_lib.run() function receives an InputObject and returns an OutputObject.

Run this command to test your implementation:

python demo.py

Expected console output:

Input: device='cpu' model_storage_directory='models' image_path='path/to/sample_image.jpg'
Output: label=0
Predicted Class: Non-Smoker

Step 5: Add Model Weights

Place your trained model files in the models/ directory:

models/
├── model.pth          # Your trained model
├── config.json        # Model configuration
└── etc.

Step 6: Create Prediction Script (For Private Submissions)

Implement the predict_submission() function in my_ai_lib/predict_submission.py

Requirements

  • Function accepting test data folder path (string)
  • Load your trained model
  • Process test dataset (images in test data folder)
  • Generate predictions
  • Save results as ./result.csv

Implementation Template

from aioz_ainode_adapter.schemas import InputObject
import my_ai_lib
import os
import csv

def predict_submission(test_data_folder: str):
    """
    Generate predictions for challenge submission.

    Args:
        test_data_folder: Path to test data directory
    """
    # TODO: Implement your solution here
    # Example:
    # 1. Locate test images folder (use os.walk() to find files)
    test_folder = test_data_folder
    for root, dirs, files in os.walk(test_data_folder):
        if any(f.endswith(('.jpg', '.jpeg', '.png')) for f in files):
            test_folder = root
            break

    results = []
    image_files = [f for f in os.listdir(test_folder) if f.endswith(('.jpg', '.jpeg', '.png'))]

    print(f"Found {len(image_files)} images in {test_folder}")

    # 2. Process each image
    for filename in image_files:
        image_path = os.path.join(test_folder, filename)

        # Call the run function with the image path
        output_obj = my_ai_lib.run(InputObject(image_path=image_path))

        # id is the filename, label is the prediction (0 or 1)
        results.append({"id": filename, "label": output_obj.label})

    # 3. Save to ./result.csv
    with open("./result.csv", "w", newline="") as f:
        writer = csv.DictWriter(f, fieldnames=["id", "label"])
        writer.writeheader()
        writer.writerows(results)

    print(f"Saved {len(results)} predictions to ./result.csv")

def main():
    """Main function for testing submission."""
    predict_submission("path/to/test/data")

if __name__ == '__main__':
    main()

Important: The result.csv must match the challenge's sample submission format.

Verify Your Submission

python -m my_ai_lib.predict_submission

Submission Guidelines

Submission Format

Submit a CSV file with two columns:

  • id: The image filename.
  • label: The predicted class (0 = non-smoker, 1 = smoker).

Example:

id,label
6138699878db49328e6f59e6337cd7ee.jpg,0
7d16690af8d0420f9d6b9647354f0300.jpg,1

License

This repository is licensed under the MIT License.