Model-config web apps: describe the app in configuration instead of writing code. Built on Polars and DuckDB.
segment_customer.py · 8.1 KB · 208 lines
| 1 | #!/usr/bin/env python3 |
| 2 | """ |
| 3 | AI-Generated Service: segment_customer |
| 4 | Description: Categorize customers by value, behavior, and engagement |
| 5 | Generated: 2025-09-19T10:33:00.000000 |
| 6 | """ |
| 7 | |
| 8 | from typing import Dict, Any, List, Optional |
| 9 | import json |
| 10 | from datetime import datetime, timedelta |
| 11 | |
| 12 | async def segment_customer(data: Dict[str, Any]) -> Dict[str, Any]: |
| 13 | """ |
| 14 | Segment customers into categories based on value, behavior, and engagement metrics. |
| 15 | |
| 16 | Inputs: customer_id, purchase_history, engagement_metrics, demographic_data |
| 17 | Outputs: segment, sub_segment, lifetime_value_tier, churn_risk, recommendations, profile_summary |
| 18 | """ |
| 19 | |
| 20 | try: |
| 21 | # Extract inputs |
| 22 | customer_id = data.get('customer_id') |
| 23 | purchase_history = data.get('purchase_history', {}) |
| 24 | engagement_metrics = data.get('engagement_metrics', {}) |
| 25 | demographic_data = data.get('demographic_data', {}) |
| 26 | |
| 27 | # Calculate key metrics |
| 28 | total_purchases = purchase_history.get('total_orders', 0) |
| 29 | lifetime_value = purchase_history.get('lifetime_value', 0) |
| 30 | avg_order_value = purchase_history.get('average_order_value', 0) |
| 31 | days_since_last_order = purchase_history.get('days_since_last_order', 0) |
| 32 | purchase_frequency = purchase_history.get('orders_per_month', 0) |
| 33 | |
| 34 | # Engagement scoring |
| 35 | email_open_rate = engagement_metrics.get('email_open_rate', 0) |
| 36 | click_through_rate = engagement_metrics.get('click_through_rate', 0) |
| 37 | app_usage_days = engagement_metrics.get('app_usage_days_per_month', 0) |
| 38 | support_tickets = engagement_metrics.get('support_tickets_last_90_days', 0) |
| 39 | reviews_written = engagement_metrics.get('reviews_written', 0) |
| 40 | referrals_made = engagement_metrics.get('referrals_made', 0) |
| 41 | |
| 42 | # Demographics |
| 43 | account_age_months = demographic_data.get('account_age_months', 0) |
| 44 | location_tier = demographic_data.get('location_tier', 'suburban') # urban, suburban, rural |
| 45 | preferred_channel = demographic_data.get('preferred_channel', 'web') |
| 46 | |
| 47 | # Determine primary segment |
| 48 | if lifetime_value >= 10000 and purchase_frequency >= 2: |
| 49 | segment = 'VIP' |
| 50 | sub_segment = 'Platinum' |
| 51 | elif lifetime_value >= 5000 and purchase_frequency >= 1: |
| 52 | segment = 'VIP' |
| 53 | sub_segment = 'Gold' |
| 54 | elif lifetime_value >= 2000 or purchase_frequency >= 1: |
| 55 | segment = 'Loyal' |
| 56 | sub_segment = 'Regular' |
| 57 | elif total_purchases >= 2: |
| 58 | segment = 'Active' |
| 59 | sub_segment = 'Occasional' |
| 60 | elif total_purchases == 1: |
| 61 | segment = 'New' |
| 62 | sub_segment = 'First-time' |
| 63 | else: |
| 64 | segment = 'Prospect' |
| 65 | sub_segment = 'Potential' |
| 66 | |
| 67 | # Refine based on recency |
| 68 | if days_since_last_order > 180: |
| 69 | if segment in ['VIP', 'Loyal']: |
| 70 | segment = 'At Risk' |
| 71 | sub_segment = 'Lapsed ' + sub_segment |
| 72 | else: |
| 73 | segment = 'Dormant' |
| 74 | sub_segment = 'Inactive' |
| 75 | elif days_since_last_order > 90 and segment != 'VIP': |
| 76 | sub_segment = 'Cooling' |
| 77 | |
| 78 | # Determine lifetime value tier |
| 79 | if lifetime_value >= 10000: |
| 80 | lifetime_value_tier = 'Diamond' |
| 81 | elif lifetime_value >= 5000: |
| 82 | lifetime_value_tier = 'Platinum' |
| 83 | elif lifetime_value >= 2000: |
| 84 | lifetime_value_tier = 'Gold' |
| 85 | elif lifetime_value >= 500: |
| 86 | lifetime_value_tier = 'Silver' |
| 87 | else: |
| 88 | lifetime_value_tier = 'Bronze' |
| 89 | |
| 90 | # Calculate churn risk |
| 91 | churn_score = 0 |
| 92 | |
| 93 | if days_since_last_order > 60: |
| 94 | churn_score += 30 |
| 95 | if days_since_last_order > 120: |
| 96 | churn_score += 30 |
| 97 | |
| 98 | if email_open_rate < 0.1: |
| 99 | churn_score += 20 |
| 100 | if app_usage_days < 2: |
| 101 | churn_score += 20 |
| 102 | |
| 103 | if support_tickets > 3: |
| 104 | churn_score += 15 |
| 105 | |
| 106 | if purchase_frequency < 0.5: |
| 107 | churn_score += 15 |
| 108 | |
| 109 | churn_risk = 'High' if churn_score >= 70 else ('Medium' if churn_score >= 40 else 'Low') |
| 110 | |
| 111 | # Generate recommendations based on segment |
| 112 | recommendations = [] |
| 113 | |
| 114 | if segment == 'VIP': |
| 115 | recommendations.extend([ |
| 116 | 'Assign dedicated account manager', |
| 117 | 'Offer exclusive early access to new products', |
| 118 | 'Provide VIP customer service line', |
| 119 | 'Send personalized thank you gifts' |
| 120 | ]) |
| 121 | elif segment == 'Loyal': |
| 122 | recommendations.extend([ |
| 123 | 'Enroll in loyalty rewards program', |
| 124 | 'Send birthday and anniversary offers', |
| 125 | 'Provide product recommendations based on history' |
| 126 | ]) |
| 127 | elif segment == 'At Risk': |
| 128 | recommendations.extend([ |
| 129 | 'Send win-back campaign immediately', |
| 130 | 'Offer special comeback discount', |
| 131 | 'Survey to understand dissatisfaction', |
| 132 | 'Personal outreach from customer success' |
| 133 | ]) |
| 134 | elif segment == 'Active': |
| 135 | recommendations.extend([ |
| 136 | 'Encourage second purchase with discount', |
| 137 | 'Send product education emails', |
| 138 | 'Highlight customer reviews and testimonials' |
| 139 | ]) |
| 140 | elif segment == 'New': |
| 141 | recommendations.extend([ |
| 142 | 'Send welcome series emails', |
| 143 | 'Offer first-time buyer discount for next purchase', |
| 144 | 'Request feedback on first experience' |
| 145 | ]) |
| 146 | elif segment == 'Dormant': |
| 147 | recommendations.extend([ |
| 148 | 'Re-engagement email campaign', |
| 149 | 'Special reactivation offer', |
| 150 | 'Update on new products and improvements' |
| 151 | ]) |
| 152 | |
| 153 | # Add channel-specific recommendations |
| 154 | if preferred_channel == 'mobile': |
| 155 | recommendations.append('Optimize mobile app experience') |
| 156 | elif preferred_channel == 'social': |
| 157 | recommendations.append('Increase social media engagement') |
| 158 | |
| 159 | # Build profile summary |
| 160 | profile_summary = { |
| 161 | 'value_indicator': 'High Value' if lifetime_value >= 2000 else ('Medium Value' if lifetime_value >= 500 else 'Low Value'), |
| 162 | 'activity_level': 'Highly Active' if purchase_frequency >= 2 else ('Active' if purchase_frequency >= 1 else 'Inactive'), |
| 163 | 'engagement_level': 'Highly Engaged' if email_open_rate > 0.3 else ('Engaged' if email_open_rate > 0.15 else 'Low Engagement'), |
| 164 | 'loyalty_status': 'Champion' if referrals_made > 2 else ('Advocate' if reviews_written > 3 else 'Customer'), |
| 165 | 'preferred_channel': preferred_channel, |
| 166 | 'customer_since': f"{account_age_months} months" |
| 167 | } |
| 168 | |
| 169 | # Calculate potential value |
| 170 | if segment in ['New', 'Active']: |
| 171 | potential_value = avg_order_value * 12 * 2 # Potential for 2 years |
| 172 | else: |
| 173 | potential_value = avg_order_value * purchase_frequency * 12 |
| 174 | |
| 175 | result = { |
| 176 | 'segment': segment, |
| 177 | 'sub_segment': sub_segment, |
| 178 | 'lifetime_value_tier': lifetime_value_tier, |
| 179 | 'churn_risk': churn_risk, |
| 180 | 'churn_score': churn_score, |
| 181 | 'recommendations': recommendations, |
| 182 | 'profile_summary': profile_summary, |
| 183 | 'potential_value': round(potential_value, 2), |
| 184 | 'engagement_score': round((email_open_rate * 30 + click_through_rate * 30 + (app_usage_days/30) * 40), 2), |
| 185 | 'segment_confidence': 0.85, # Could be calculated based on data completeness |
| 186 | 'next_review_date': (datetime.now() + timedelta(days=30)).isoformat() |
| 187 | } |
| 188 | |
| 189 | return { |
| 190 | "success": True, |
| 191 | "timestamp": datetime.now().isoformat(), |
| 192 | "data": result |
| 193 | } |
| 194 | |
| 195 | except Exception as e: |
| 196 | return { |
| 197 | "success": False, |
| 198 | "error": str(e), |
| 199 | "timestamp": datetime.now().isoformat() |
| 200 | } |
| 201 | |
| 202 | # Synchronous wrapper |
| 203 | def segment_customer_sync(data: Dict[str, Any]) -> Dict[str, Any]: |
| 204 | """Synchronous wrapper for the async function""" |
| 205 | import asyncio |
| 206 | return asyncio.run(segment_customer(data)) |
| 207 | |
| 208 | __all__ = ['segment_customer', 'segment_customer_sync'] |