File size: 1,853 Bytes
d1d5e45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import pandas as pd
import numpy as np

# Feature columns exactly as trained
FEATURE_COLUMNS = [
    'Customer Service Calls',
    'Monthly Charge',
    'Contract Type',
    'Account Length',
    'Avg Monthly GB Download',
]

CONTRACT_MAP = {
    'Month-to-Month': 0,
    'One Year':       1,
    'Two Year':       2,
}


def preprocess_single(input_dict: dict) -> pd.DataFrame:
    """Preprocess a single customer input dict."""
    df = pd.DataFrame([input_dict])
    return _preprocess(df)


def preprocess_batch(df: pd.DataFrame) -> pd.DataFrame:
    """Preprocess a batch DataFrame."""
    df = df.copy()
    # Drop ID or label columns if present
    for col in ['Customer ID', 'CustomerID', 'Churn', 'Churn Label']:
        if col in df.columns:
            df = df.drop(columns=[col])
    return _preprocess(df)


def _preprocess(df: pd.DataFrame) -> pd.DataFrame:
    df = df.copy()

    # Encode Contract Type
    if 'Contract Type' in df.columns:
        df['Contract Type'] = df['Contract Type'].map(CONTRACT_MAP).fillna(0).astype(int)

    # Numeric coercion
    for col in ['Customer Service Calls', 'Monthly Charge',
                'Account Length', 'Avg Monthly GB Download']:
        if col in df.columns:
            df[col] = pd.to_numeric(df[col], errors='coerce').fillna(0)

    # Ensure all columns exist
    for col in FEATURE_COLUMNS:
        if col not in df.columns:
            df[col] = 0

    return df[FEATURE_COLUMNS]


def get_sample_csv() -> str:
    return (
        "Customer ID,Customer Service Calls,Monthly Charge,"
        "Contract Type,Account Length,Avg Monthly GB Download\n"
        "C001,4,85.50,Month-to-Month,12,32.1\n"
        "C002,1,55.00,One Year,36,18.5\n"
        "C003,7,110.00,Month-to-Month,6,55.0\n"
        "C004,0,45.00,Two Year,60,10.2\n"
        "C005,3,75.00,Month-to-Month,24,28.7\n"
    )