import json import pandas as pd import numpy as np from sklearn.preprocessing import OrdinalEncoder # County code mapping COUNTIES = { "Mombasa": "001", "Kwale": "002", "Kilifi": "003", "Tana River": "004", "Lamu": "005", "Taita Taveta": "006", "Garissa": "007", "Wajir": "008", "Mandera": "009", "Marsabit": "010", "Isiolo": "011", "Meru": "012", "Tharaka Nithi": "013", "Embu": "014", "Kitui": "015", "Machakos": "016", "Makueni": "017", "Nyandarua": "018", "Nyeri": "019", "Kirinyaga": "020", "Murang'a": "021", "Kiambu": "022", "Turkana": "023", "West Pokot": "024", "Samburu": "025", "Trans Nzoia": "026", "Uasin Gishu": "027", "Elgeyo Marakwet": "028", "Nandi": "029", "Baringo": "030", "Laikipia": "031", "Nakuru": "032", "Narok": "033", "Kajiado": "034", "Kericho": "035", "Bomet": "036", "Kakamega": "037", "Vihiga": "038", "Bungoma": "039", "Busia": "040", "Siaya": "041", "Kisumu": "042", "Homa Bay": "043", "Migori": "044", "Kisii": "045", "Nyamira": "046", "Nairobi": "047" } # Expected features in the model EXPECTED_FEATURES = [ 'County', 'Age', 'Gender', 'Crop_Yield_Tons', 'Land_Ownership', 'land_ownership_acres', 'farming_type', 'farming_experience_years', 'access_to_resources', 'income_variability_index', 'community_reputation_score' ] # Ordinal encoder for access_to_resources # Fit with known categories ordinal_encoder = OrdinalEncoder(categories=[['Limited', 'None', 'Some']]) ordinal_encoder.fit([['Limited'], ['None'], ['Some']]) def preprocess_data(raw_data): # Convert to DataFrame if single dict if isinstance(raw_data, dict): df = pd.DataFrame([raw_data]) else: df = pd.DataFrame(raw_data) # Create a copy to avoid modifying original processed_df = df.copy() # 1. Handle missing values if 'access_to_resources' in processed_df.columns: processed_df['access_to_resources'].fillna('Some', inplace=True) # 2. Process County column if 'County' in processed_df.columns: processed_df['County'] = processed_df['County'].map(COUNTIES) processed_df['County'] = processed_df['County'].astype('category') processed_df['County'] = processed_df['County'].cat.codes # 3. Process Gender column if 'Gender' in processed_df.columns: processed_df['Gender'] = processed_df['Gender'].astype('category') processed_df['Gender'] = processed_df['Gender'].cat.codes # 4. Process Land_Ownership column if 'Land_Ownership' in processed_df.columns: processed_df['Land_Ownership'] = processed_df['Land_Ownership'].astype('category') processed_df['Land_Ownership'] = processed_df['Land_Ownership'].cat.codes # 5. Process farming_type column if 'farming_type' in processed_df.columns: processed_df['farming_type'] = processed_df['farming_type'].astype('category') processed_df['farming_type'] = processed_df['farming_type'].cat.codes # 6. Process access_to_resources with OrdinalEncoder if 'access_to_resources' in processed_df.columns: processed_df['access_to_resources'] = ordinal_encoder.transform( processed_df[['access_to_resources']] ) # 7. Ensure all expected features are present for feature in EXPECTED_FEATURES: if feature not in processed_df.columns: processed_df[feature] = 0 # Default value for missing features # 8. Select only the expected features in the correct order processed_df = processed_df[EXPECTED_FEATURES] return processed_df