convert this test.py 


# model_testing.py

import pandas as pd
import pickle
import numpy as np
import os

from sklearn.preprocessing import LabelEncoder, StandardScaler

class Hackathon:
    def __init__(self, artifacts_path='artifacts'):
        """
        Initialize the Hackathon by loading the model and preprocessing artifacts.
        """
        # Load model
        with open(os.path.join(artifacts_path, 'model.pkl'), 'rb') as f:
            self.model = pickle.load(f)
        
        # Load label encoder
        with open(os.path.join(artifacts_path, 'label_encoder.pkl'), 'rb') as f:
            self.le = pickle.load(f)
        
        # Load scaler
        with open(os.path.join(artifacts_path, 'scaler.pkl'), 'rb') as f:
            self.scaler = pickle.load(f)
    
    def preprocess(self, df):
        """
        Preprocess the input data in the same manner as the training data.
        """
        # Drop identifier and irrelevant columns
        drop_cols = ['txn_id', 'trndate', 'payee_account_number', 'payer_address']
        df = df.drop(columns=drop_cols, errors='ignore')
        
        # Handle missing values
        df.fillna(-999, inplace=True)
        
        # Encode categorical variables
        categorical_cols = ['payee_bank', 'payee_tpap', 'txn_type', 'initiation_mode',
                            'payer_tpap', 'payer_bank']
        
        for col in categorical_cols:
            if col in df.columns:
                # Handle unseen labels by assigning 'Unknown'
                df[col] = df[col].astype(str).apply(lambda x: x if x in self.le.classes_ else 'Unknown')
                # If 'Unknown' was not in training, add it
                if 'Unknown' not in self.le.classes_:
                    self.le.classes_ = np.append(self.le.classes_, 'Unknown')
                df[col] = self.le.transform(df[col])
        
        # Feature engineering: Extract year, month, day from date columns
        date_cols = [
            'upi_min_dt_payer', 'upi_min_dt_payee', 'py_max_asdt_payer', 'py_max_asdt_payee',
            'mas_minasdt_mob_payer', 'mas_minasdt_mob_payee',
            'mas_vpa_pr_minasdt_payer', 'mas_vpa_pr_maxasdt_payer',
            'mas_vpa_py_minasdt_payee', 'mas_vpa_py_maxasdt_payee',
            'mas_maxasdt_mob_payer', 'mas_maxasdt_mob_payee'
        ]
        
        for col in date_cols:
            if col in df.columns:
                df[col] = pd.to_datetime(df[col], errors='coerce', dayfirst=True)
                df[col + '_year'] = df[col].dt.year.fillna(0).astype(int)
                df[col + '_month'] = df[col].dt.month.fillna(0).astype(int)
                df[col + '_day'] = df[col].dt.day.fillna(0).astype(int)
                df = df.drop(columns=[col])
        
        # Scale numerical features
        numeric_cols = df.select_dtypes(include=['int64', 'float64']).columns.tolist()
        if 'fraud' in numeric_cols:
            numeric_cols.remove('fraud')  # Exclude target if present
        df[numeric_cols] = self.scaler.transform(df[numeric_cols])
        
        return df
    
    def predict(self, input_data):
        """
        Predict whether transactions are fraudulent or not.
        
        Parameters:
        - input_data: pandas DataFrame containing transaction records.
        
        Returns:
        - pandas Series with predictions (0 or 1).
        """
        # Preprocess the input data
        df_processed = self.preprocess(input_data)
        
        # Make predictions
        preds = self.model.predict(df_processed)
        
        return pd.Series(preds)

# Example usage:
if __name__ == '__main__':
    # Load sample input data
    sample_data = pd.read_csv('sample_test.csv')  # Replace with actual input data
    
    # Initialize the model
    fraud_model = Hackathon()
    
    # Make predictions
    predictions = fraud_model.predict(sample_data)
    
    # Output predictions
    sample_data['predicted_fraud'] = predictions
    print(sample_data[['txn_id', 'predicted_fraud']])


in this format


# model_testing.py

import pandas as pd
import pickle
import numpy as np
import os

from sklearn.preprocessing import LabelEncoder, StandardScaler

class Hackathon:
    def __init__(self, artifacts_path='artifacts'):
        """
        Initialize the Hackathon by loading the model and preprocessing artifacts.
        """
        # Load model
        with open(os.path.join(artifacts_path, 'model.pkl'), 'rb') as f:
            self.model = pickle.load(f)
        
        # Load label encoder
        with open(os.path.join(artifacts_path, 'label_encoder.pkl'), 'rb') as f:
            self.le = pickle.load(f)
        
        # Load scaler
        with open(os.path.join(artifacts_path, 'scaler.pkl'), 'rb') as f:
            self.scaler = pickle.load(f)
    
    def preprocess(self, df):
        """
        Preprocess the input data in the same manner as the training data.
        """
        # Drop identifier and irrelevant columns
        drop_cols = ['txn_id', 'trndate', 'payee_account_number', 'payer_address']
        df = df.drop(columns=drop_cols, errors='ignore')
        
        # Handle missing values
        df.fillna(-999, inplace=True)
        
        # Encode categorical variables
        categorical_cols = ['payee_bank', 'payee_tpap', 'txn_type', 'initiation_mode',
                            'payer_tpap', 'payer_bank']
        
        for col in categorical_cols:
            if col in df.columns:
                # Handle unseen labels by assigning 'Unknown'
                df[col] = df[col].astype(str).apply(lambda x: x if x in self.le.classes_ else 'Unknown')
                # If 'Unknown' was not in training, add it
                if 'Unknown' not in self.le.classes_:
                    self.le.classes_ = np.append(self.le.classes_, 'Unknown')
                df[col] = self.le.transform(df[col])
        
        # Feature engineering: Extract year, month, day from date columns
        date_cols = [
            'upi_min_dt_payer', 'upi_min_dt_payee', 'py_max_asdt_payer', 'py_max_asdt_payee',
            'mas_minasdt_mob_payer', 'mas_minasdt_mob_payee',
            'mas_vpa_pr_minasdt_payer', 'mas_vpa_pr_maxasdt_payer',
            'mas_vpa_py_minasdt_payee', 'mas_vpa_py_maxasdt_payee',
            'mas_maxasdt_mob_payer', 'mas_maxasdt_mob_payee'
        ]
        
        for col in date_cols:
            if col in df.columns:
                df[col] = pd.to_datetime(df[col], errors='coerce', dayfirst=True)
                df[col + '_year'] = df[col].dt.year.fillna(0).astype(int)
                df[col + '_month'] = df[col].dt.month.fillna(0).astype(int)
                df[col + '_day'] = df[col].dt.day.fillna(0).astype(int)
                df = df.drop(columns=[col])
        
        # Scale numerical features
        numeric_cols = df.select_dtypes(include=['int64', 'float64']).columns.tolist()
        if 'fraud' in numeric_cols:
            numeric_cols.remove('fraud')  # Exclude target if present
        df[numeric_cols] = self.scaler.transform(df[numeric_cols])
        
        return df
    
    def predict(self, input_data):
        """
        Predict whether transactions are fraudulent or not.
        
        Parameters:
        - input_data: pandas DataFrame containing transaction records.
        
        Returns:
        - pandas Series with predictions (0 or 1).
        """
        # Preprocess the input data
        df_processed = self.preprocess(input_data)
        
        # Make predictions
        preds = self.model.predict(df_processed)
        
        return pd.Series(preds)

# Example usage:
if __name__ == '__main__':
    # Load sample input data
    sample_data = pd.read_csv('sample_test.csv')  # Replace with actual input data
    
    # Initialize the model
    fraud_model = Hackathon()
    
    # Make predictions
    predictions = fraud_model.predict(sample_data)
    
    # Output predictions
    sample_data['predicted_fraud'] = predictions
    print(sample_data[['txn_id', 'predicted_fraud']])