File size: 15,864 Bytes
425672a
 
 
 
 
 
 
1c5ff79
ba11dbb
425672a
 
 
 
 
 
 
 
 
 
 
 
 
1c5ff79
 
72a8895
 
1c5ff79
 
 
fcede42
bbd8ed1
d620c33
 
1c5ff79
00a0344
 
 
 
72a8895
1c5ff79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72a8895
1c5ff79
 
838c8dc
 
 
72a8895
838c8dc
 
72a8895
1c5ff79
 
 
fcede42
 
72a8895
d620c33
fcede42
72a8895
1c5ff79
 
72a8895
1c5ff79
 
 
72a8895
1c5ff79
425672a
 
 
063efcd
425672a
 
 
 
 
 
6e2e2fc
 
 
 
 
425672a
073e2d5
425672a
 
 
 
84dbfbd
 
425672a
542d507
 
 
 
 
 
 
 
 
 
 
 
 
6e2e2fc
542d507
 
 
4e97119
542d507
 
 
 
425672a
 
 
 
 
84dbfbd
425672a
 
063efcd
 
 
 
 
073e2d5
425672a
78ee66c
4e97119
78ee66c
073e2d5
 
 
 
78ee66c
073e2d5
e1844ba
 
 
78ee66c
425672a
 
073e2d5
 
e1844ba
78ee66c
073e2d5
4e97119
073e2d5
425672a
 
 
3b951c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
063efcd
3b951c9
 
 
063efcd
3b951c9
 
 
 
 
 
063efcd
 
6f33813
 
 
 
3b951c9
6f33813
 
 
 
 
 
 
063efcd
 
 
 
3b951c9
cb24fbe
063efcd
cb24fbe
3b951c9
 
 
 
 
 
e746831
3b951c9
 
 
425672a
3b951c9
 
425672a
3b951c9
425672a
3b951c9
425672a
a232995
62d2f97
425672a
 
 
a9a345b
 
425672a
 
 
 
 
 
8a4fc64
 
ca7b7ae
df22fac
425672a
fbc984d
f30d829
425672a
f80c4c6
142fe4f
ae8cfb0
c01e00f
36cf0ce
ae8cfb0
ed45b96
 
 
 
f30d829
26b564c
 
36cf0ce
 
72a8895
36cf0ce
72a8895
 
 
93dcd0c
 
72a8895
df22fac
d6504d8
41d1470
d6504d8
41d1470
d6504d8
 
 
72a8895
d6504d8
 
0df72e5
3a21a55
72a8895
d6504d8
425672a
 
 
 
 
6e2e2fc
 
 
 
 
 
 
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
import traceback
from fastapi import FastAPI
import pickle
import numpy as np
import pandas as pd
import joblib
import re
from datetime import datetime, time
import pytz

# Load the trained XGBoost model
model = joblib.load("xgb_model.pkl")

# Load the feature names from the trained model
model_features = model.get_booster().feature_names

app = FastAPI(root_path="/")

@app.get("/")
def home():
    return {"message": "Lead Scoring Model is Live!"}

def should_send_to_ai_caller(estimated_volume, country):
    try:
        max_attempts = 3  # Always fixed at 3
        
        # --- Country to timezone mapping ---
        country_tz = {
            "France": "Europe/Paris",
            "Italy": "Europe/Paris",
            "United Kingdom": "Europe/London",
            "Spain": "Europe/Madrid",
            "Germany": "Europe/Berlin"
        }

        # --- Only allow France and UK ---
        if country not in country_tz:
            print(f"Country not supported for AI routing: {country}")
            return {"send": False, "max_attempts": max_attempts}
        
        # Default timezone (fallback)
        timezone_str = country_tz.get(country, "UTC")
        tz = pytz.timezone(timezone_str)

        now = datetime.now(tz)
        current_time = now.time()
        weekday = now.weekday()  # 0 = Monday, 6 = Sunday

        # --- Time Windows ---
        early_morning = time(7, 0)
        late_morning = time(9, 0)
        evening_start = time(18, 0)
        evening_end = time(21, 0)
        business_start = time(9, 0)
        business_end = time(18, 0)
        weekend_end = time(21, 0)

        is_weekend = weekday >= 5  # Saturday or Sunday

        # Normalize TPV
        def parse_tpv_range(value):
            if not value or str(value).strip().lower() in {'none', ''}:
                return 'None'
            value = value.upper().replace('K', '000').replace('M', '000000')
            value = re.sub(r'[£$€¥]', '', value)
            value = value.replace(' – ', '-').replace(' ', '').strip()
            if '-' in value:
                low, high = map(int, re.findall(r'\d+', value))
                return f"{low}-{high}"
            elif value.isdigit():
                return f"{value}-{value}"
            return 'None'

        parsed_tpv = parse_tpv_range(estimated_volume)

        # --- Rule 1: All leads during early/late weekday hours ---
        if not is_weekend and (
            early_morning <= current_time <= late_morning or
            evening_start <= current_time <= evening_end
        ):
            return {"send": True, "max_attempts": max_attempts}

        # --- Rule 2: All leads on weekends between 7 AM and 8 PM ---
        if early_morning <= current_time <= weekend_end:
            if weekday == 5:  # Saturday
                if country in {"France", "United Kingdom", "Italy", "Spain", "Germany"}:
                    return {"send": True, "max_attempts": max_attempts}
            elif weekday == 6:  # Sunday
                if country in {"France", "United Kingdom", "Italy", "Spain"}:
                    return {"send": True, "max_attempts": max_attempts}

        # --- Rule 3: Weekday 9 AM–6 PM only if low TPV or None ---
        if not is_weekend and business_start <= current_time <= business_end:
            if country in {"France", "United Kingdom"}:
                if parsed_tpv in {'None', '0-35000'}:
                    return {"send": True, "max_attempts": max_attempts}
            elif country in {"Italy", "Spain"}:
                if parsed_tpv == '0-35000':
                    return {"send": True, "max_attempts": max_attempts}

        # Otherwise, don't send
        return {"send": False, "max_attempts": max_attempts}

    except Exception as e:
        print(f"[AI Caller Decision Error] {str(e)}")  
        return {"send": False, "max_attempts": 3}  
        
# Function to preprocess a single lead
def preprocess_single_lead(data):
    df = pd.DataFrame([data])  # Convert dict to DataFrame
    df.columns = df.columns.str.strip().str.replace('"', '').str.replace(';', ',')

    # Handle missing values
    cat_cols = df.select_dtypes(include=['object']).columns
    df[cat_cols] = df[cat_cols].fillna(pd.NA)
    num_cols = df.select_dtypes(include=['float64', 'int64']).columns
    df[num_cols] = df[num_cols].fillna(pd.NA)
    
    expected_columns = ['Email', 'Phone', 'GA Campaign', 'LP: Campaign', 'Lead Source', 'GA Source', 'Prospect product interest', 'Estimated Yearly Transaction Volume', 'Estimated Turnover']
    for col in expected_columns:
        if col not in df.columns:
            df[col] = pd.NA

    # Feature engineering (add other encoding as needed)
    df['Email Available'] = df['Email'].apply(lambda x: 1 if pd.notna(x) else 0)
    df['Phone Available'] = df['Phone'].apply(lambda x: 1 if pd.notna(x) else 0)
    df['GA Campaign Available'] = df['GA Campaign'].apply(lambda x: 1 if pd.notna(x) else 0)
    df['LP: Campaign Available'] = df['LP: Campaign'].apply(lambda x: 1 if pd.notna(x) else 0)
    df['Lead Source Available'] = df['Lead Source'].apply(lambda x: 1 if pd.notna(x) else 0)
    df['GA Source Available'] = df['GA Source'].apply(lambda x: 1 if pd.notna(x) else 0)

     # Assign default product interest based on estimated yearly transaction volume
    def assign_product_interest(row):
        if pd.isna(row['Prospect product interest']) or row['Prospect product interest'] == '':
            if pd.notna(row['Estimated Yearly Transaction Volume']):
                try:
                    value = row['Estimated Yearly Transaction Volume']
                    if '-' in value:
                        low, high = map(int, value.split('-'))
                        midpoint = (low + high) / 2
                    else:
                        midpoint = int(value)
                    
                    return 'Payment, POS Lite' if midpoint < 60000 else 'POS Pro, Kiosk'
                
                except Exception:
                    return 'Payment, POS Pro'  # Fallback value when transaction volume is invalid
            else:
                return ''  # Default when transaction volume is missing
        return row['Prospect product interest']
    
    df['Prospect product interest'] = df.apply(assign_product_interest, axis=1)

    df['POS Pro Available'] = df['Prospect product interest'].apply(lambda x: 1 if 'POS Pro' in str(x) else 0)
    df['Payment Available'] = df['Prospect product interest'].apply(lambda x: 1 if 'Payment' in str(x) else 0)
    df['Product Interest Available'] = df['Prospect product interest'].apply(lambda x: 1 if pd.notna(x) and x != '' else 0)

    df['Contacts Available'] = df[['Email Available', 'Phone Available']].sum(axis=1)
    df['Sources Available'] = df[['Lead Source Available', 'GA Source Available']].sum(axis=1)
    df['Campaigns Available'] = df[['GA Campaign Available', 'LP: Campaign Available']].sum(axis=1)

    # Drop the original 'Email', 'Phone', 'GA Campaign', and 'LP: Campaign' columns since they are now encoded
    df = df.drop(columns=['Email', 'Phone', 'GA Campaign', 'LP: Campaign', 'Lead Source', 'GA Source', 
                              'Email Available', 'Phone Available', 'GA Campaign Available', 'LP: Campaign Available', 
                              'Lead Source Available', 'GA Source Available', 'Prospect product interest'])

    # Apply function to convert to numeric ranges (same as in your training model)
    def convert_to_numeric_range(value):
        if pd.isna(value) or value == '':
            return "60000-100000"  # Default value when missing
        
        value = value.replace('\xa0', '').replace("'", '').replace(',', '').strip()  # Clean unwanted characters
        value = re.sub(r'[£$€¥]', '', value)  # Remove currency symbols
        value = value.replace(' – ', ' - ')  # Fix en dash to regular dash
        value = value.replace('K', '000').replace('M', '000000')

        if '+' in value:
            value = value.replace('+', '')  # Remove '+'
            if value.isdigit():  
                return f"{value}-{int(value) * 2}"  # Convert "5M+" to "5000000-10000000"

        if '-' in value:
            low, high = value.split('-')
            low = ''.join(re.findall(r'\d+', low))  # Keep only numeric characters
            high = ''.join(re.findall(r'\d+', high))  # Keep only numeric characters
            return f"{low}-{high}" if low and high else None

        value = ''.join(re.findall(r'\d+', value))  # Keep only numeric characters
        return value if value else "60000-100000"  # Default when not interpretable
    
    df['Estimated Yearly Transaction Volume'] = df['Estimated Yearly Transaction Volume'].apply(convert_to_numeric_range)
    df['Estimated Turnover'] = df['Estimated Turnover'].apply(convert_to_numeric_range)

    # Apply the same alignment and combination logic for 'Estimated Turnover' to 'Estimated Yearly Transaction Volume'
    def align_turnover_to_transaction(value, transaction_values):
        if pd.isna(value):
            return value  # Handle missing values

        transaction_midpoints = []
        for transaction_range in transaction_values:
            if '-' in transaction_range:
                low, high = map(int, transaction_range.split('-'))
                transaction_midpoints.append((low + high) // 2)
            else:
                transaction_midpoints.append(int(transaction_range))

        if '-' in value:
            low, high = map(int, value.split('-'))
            turnover_midpoint = (low + high) // 2
        else:
            turnover_midpoint = int(value)

        closest_index = min(range(len(transaction_midpoints)), key=lambda i: abs(transaction_midpoints[i] - turnover_midpoint))
        return transaction_values[closest_index]

    unique_transaction_values = df['Estimated Yearly Transaction Volume'].dropna().unique()
    df['Estimated Turnover'] = df['Estimated Turnover'].apply(lambda x: align_turnover_to_transaction(x, unique_transaction_values))

    # Combine the 'Estimated Yearly Transaction Volume' and 'Estimated Turnover' columns into one
    def combine_transaction_and_turnover(row):
        if pd.notna(row["Estimated Yearly Transaction Volume"]) and row["Estimated Yearly Transaction Volume"] != "0-0":
            return row["Estimated Yearly Transaction Volume"]
        elif pd.notna(row["Estimated Turnover"]) and row["Estimated Turnover"] != "0-0":
            return row["Estimated Turnover"]
        return "0-0"  # Default if both are missing
    
    df["Combined Volume and Turnover"] = df.apply(combine_transaction_and_turnover, axis=1)

    # Calculate midpoints for combined column
    def calculate_midpoint(value):
        if pd.isna(value) or '-' not in value:
            return None
        try:
            start, end = map(int, value.split('-'))
            return (start + end) / 2
        except ValueError:
            return None
    
    df['Combined Midpoint'] = df['Combined Volume and Turnover'].apply(calculate_midpoint)

    # Generate dynamic bins for 'Combined Midpoint'
    def generate_bins_and_labels():
        '''midpoints = [x for x in midpoints if pd.notna(x)]
        if len(midpoints) < 2:
            # If we have less than 2 values, fallback to a single default bin
            return [0, 1], ['Bin 1']
    
        unique_values = sorted(set(midpoints))
        bins = [min(unique_values)] + unique_values + [max(unique_values) * 1.1]
        bins = sorted(set(bins))  # Ensure bins are unique
    
        if len(bins) - 1 != len(unique_values):  
            labels = [f'Bin {i+1}' for i in range(len(bins) - 1)]
        else:
            labels = [f'Bin {i+1}' for i in range(len(unique_values))]
        return bins, labels'''
        # Predefined bins based on your given ranges
        bins = [0, 35000, 60000, 100000, 200000, 400000, 600000, 1000000, 2000000, 5000000, float('inf')]
        labels = [f'Bin {i+1}' for i in range(len(bins) - 1)]
        return bins, labels
    
    bins_combined, labels_combined = generate_bins_and_labels()
    df['Combined Volume Category'] = pd.cut(df['Combined Midpoint'], bins=bins_combined, labels=labels_combined, include_lowest=True)

    # One-hot encode categorical columns
    cat_columns = ['Pos Pro Segmentation Level 3', 'Combined Volume Category', 'Sourcing Direction']
    df_encoded = pd.get_dummies(df, columns=cat_columns, drop_first=True)

    # Drop columns that are not useful or of type 'object'
    drop_columns = ['Estimated Yearly Transaction Volume', 'Estimated Turnover', 'Combined Volume and Turnover']
    df_encoded = df_encoded.drop(columns=drop_columns)

    # Ensure that the final df has the same columns as the model expects
    for col in model_features:
        if col not in df_encoded.columns:
            df_encoded[col] = 0  # Assign 0 to missing columns

    df_encoded = df_encoded[model_features]  # Ensure the correct order of features

    return df_encoded

low_score_counter = {"POS Pro": 0, "Payment": 0, "Payment or POS Lite": 0, "global_count": 0, "score_1_count": 0, "score_2_count": 0, "score_3_count": 0}

@app.post("/api/predict")
async def predict(lead: dict):
    try:
        global low_score_counter  
        
        # Preprocess the lead data
        processed_lead = preprocess_single_lead(lead)

        # Predict probability of conversion
        probability = model.predict_proba(processed_lead)[0, 1]  # Class 1 probability

        # Cast to regular Python types
        probability = float(probability)  # Convert numpy.float32 to regular float
        
        
        # Map probability to score (1 to 10)
        score = int(np.ceil(probability * 10))  # Compute score
        score = score + 2 if 4 <= score < 9 else score  # Handle score to not push extremes

        estimated_volume = lead.get("Estimated Yearly Transaction Volume")
        product_interest = str(lead.get("Prospect product interest", "")).strip() 
        sourcing_direction = str(lead.get("Sourcing Direction", "")).strip()
        lp_campaign = str(lead.get("LP: Campaign", "")).strip()
        Leads_source_website = str(lead.get("Leads_source_Website__c", "")).strip()
        
        if product_interest:
            product_interest = set(map(str.strip, product_interest.split(";")))
        else:
            product_interest = set()

        # Determine if it should be sent to AI caller
        country = lead.get("Country")
        if "SAP-" in Leads_source_website:
            send_to_ai_caller = False
            max_attempts = 3
        elif sourcing_direction.lower() == 'inbound' and lp_campaign != 'London-Coffee-Festival-2025':
            ai_caller_decision = should_send_to_ai_caller(estimated_volume, country)
            send_to_ai_caller = ai_caller_decision["send"]
            max_attempts = ai_caller_decision["max_attempts"]
        else:
            send_to_ai_caller = False
            max_attempts = 3

        # Map score to conversion category
        if score >= 7:
            conversion_category = "Hot"
        elif 4 <= score <= 6:
            conversion_category = "Warm"
        else:
            conversion_category = "Cold"
        
        return {
            "score": score,
            "conversion_probability": conversion_category,  # Return as string category
            "send_to_ai_caller": False,
            "max_attempts": max_attempts
        }

    except Exception as e:
        # Capture and return detailed error information
        error_message = str(e)
        stack_trace = traceback.format_exc()
        return {
            "score": 8,
            "conversion_probability": "Hot",  # Since score 8 is in the "Warm" category
            "error": f"An error occurred, defaulting score to 8. {error_message}",
            "stack_trace": stack_trace
            }