Skip to main content

Policy Generator

from datetime import datetime, date
import re
import json

class MotorInsuranceAIEngine:
    def __init__(self):
        # Simulated Large Language Model prompts / intent structures
        self.supported_languages = ["English", "Hindi", "Spanish", "Telugu"]
        
    def ai_extract_policy_data(self, raw_unstructured_text: str) -> dict:
        """
        Simulates an Agentic AI OCR / Document Extraction layer (e.g., PDF -> CRM processing) 
        to extract key entities out of messy customer inputs or document text blocks.
        """
        print("[AI Mode] Processing unstructured layout text via NLP extraction...")
        
        # Regex entities mimicking ML-based token classification
        policy_pattern = re.search(r'(POL-\d{5,8}|\b\d{7,10}\b)', raw_unstructured_text)
        date_pattern = re.findall(r'(\d{4}-\d{2}-\d{2}|\d{2}/\d{2}/\d{4})', raw_unstructured_text)
        premium_pattern = re.search(r'(?:Rs\.|INR|\$)\s?(\d{1,3}(?:,\d{3})*(?:\.\d{2})?)', raw_unstructured_text)
        vehicle_pattern = re.search(r'(Model|Vehicle|Car|Bike):\s*([A-Za-z0-9 ]+)', raw_unstructured_text, re.IGNORECASE)
        
        # Default extraction structure
        extracted_data = {
            "policy_number": policy_pattern.group(0) if policy_pattern else "UNKNOWN_RECOVERY",
            "expiry_date": date_pattern[0] if date_pattern else None,
            "premium_amount": premium_pattern.group(1) if premium_pattern else "0.00",
            "vehicle_details": vehicle_pattern.group(2).strip() if vehicle_pattern else "Standard Vehicle"
        }
        
        # Dynamic normalization of formats
        if extracted_data["expiry_date"] and "/" in extracted_data["expiry_date"]:
            try:
                dt = datetime.strptime(extracted_data["expiry_date"], "%d/%m/%Y")
                extracted_data["expiry_date"] = dt.strftime("%Y-%m-%d")
            except ValueError:
                pass
                
        return extracted_data

    def calculate_risk_and_expiry(self, expiry_date_str: str) -> dict:
        """
        AI Evaluation Engine that processes dates to deduce lapse status,
        days remaining, and flags critical windows for multi-touch outreach campaigns.
        """
        today = date.today()
        expiry_date = datetime.strptime(expiry_date_str, "%Y-%m-%d").date()
        days_remaining = (expiry_date - today).days
        
        status = "Active"
        lapse_risk = "Low"
        action_recommended = "Monitor Only"
        
        if days_remaining < 0:
            status = "Lapsed"
            lapse_risk = "CRITICAL (Expired)"
            action_recommended = "Trigger Break-in AI Vehicle Inspection Module" # e.g., ICICI Lombard / Microsoft style
        elif days_remaining <= 7:
            status = "Urgent Renewal Required"
            lapse_risk = "High"
            action_recommended = "Launch Daily High-Priority WhatsApp & Automated Voice Call Flow"
        elif days_remaining <= 30:
            status = "Approaching Expiry"
            lapse_risk = "Medium"
            action_recommended = "Queue in Standard Multi-Touch Renewal Campaign (Email / SMS)"
            
        return {
            "days_remaining": days_remaining,
            "policy_status": status,
            "lapse_risk_level": lapse_risk,
            "next_best_action": action_recommended
        }

    def ai_draft_generator(self, customer_name: str, policy_data: dict, analytics: dict, preferred_lang: str = "English") -> str:
        """
        Generative AI dynamic draft component. Creates highly personalized 
        outreach copy matching contextual risks and chosen parameters.
        """
        lang = preferred_lang if preferred_lang in self.supported_languages else "English"
        
        templates = {
            "English": {
                "active": f"Hello {customer_name},\nYour motor insurance policy {policy_data['policy_number']} for your {policy_data['vehicle_details']} expires in {analytics['days_remaining']} days ({policy_data['expiry_date']}). Renew now to avoid lapse premiums! Recommended Action: {analytics['next_best_action']}.",
                "lapsed": f"Alert {customer_name},\nYour policy {policy_data['policy_number']} has LAPSED by {abs(analytics['days_remaining'])} days. Your vehicle is uninsured. {analytics['next_best_action']} immediately to resume safety grids."
            },
            "Hindi": {
                "active": f"नमस्ते {customer_name},\nआपकी वाहन बीमा पॉलिसी {policy_data['policy_number']} ({policy_data['vehicle_details']}) {analytics['days_remaining']} दिनों में समाप्त हो रही है। कृपया तुरंत नवीनीकरण करें।",
                "lapsed": f"चेतावनी {customer_name},\nआपकी पॉलिसी {policy_data['policy_number']} समाप्त हो चुकी है। {analytics['next_best_action']} का उपयोग कर तुरंत नया बीमा प्राप्त करें।"
            }
        }
        
        state_key = "lapsed" if analytics['days_remaining'] < 0 else "active"
        draft = templates.get(lang, templates["English"])[state_key]
        return draft

    def process_pipeline(self, raw_input: str, customer_name: str, preferred_lang: str = "English") -> str:
        """
        Executes the end-to-end processing pipeline mimicking agentic system intelligence.
        """
        # Step 1: Document Parsing / Entity extraction
        extracted = self.ai_extract_policy_data(raw_input)
        
        if not extracted["expiry_date"]:
            return json.dumps({"Error": "AI system failed to extract a viable policy expiration deadline date."}, indent=4)
            
        # Step 2: Predictive analytics & date handling
        analytics = self.calculate_risk_and_expiry(extracted["expiry_date"])
        
        # Step 3: Generative Content Copy production
        ai_message_pitch = self.ai_draft_generator(customer_name, extracted, analytics, preferred_lang)
        
        # Package unified workflow payload
        output_dashboard = {
            "Customer Metadata": {
                "Name": customer_name,
                "Language": preferred_lang
            },
            "AI Extracted Entities": extracted,
            "Predictive Risk Matrix": analytics,
            "Tailored AI Generated Pitch": ai_message_pitch
        }
        
        return json.dumps(output_dashboard, indent=4)

# =====================================================================
# Execution Demo
# =====================================================================
if __name__ == "__main__":
    ai_engine = MotorInsuranceAIEngine()
    
    # Mock text extracted from an agent uploading a raw digital scrap / screenshot string 
    raw_document_chunk = "Vehicle details: Honda Civic Car. Premium paid: INR 12,500. Policy Code Reference: POL-998823. Validity expiration date is 2026-10-25."
    
    # Run the dynamic processing stack
    print("--- Executing AI Automation Pipeline Pipeline ---")
    result_json = ai_engine.process_pipeline(
        raw_input=raw_document_chunk, 
        customer_name="Aditya Sharma", 
        preferred_lang="English"
    )
    
    print("\nFinal Integrated System Outputs:")
    print(result_json)

Comments

Popular posts from this blog

BUY- CAR NISSAN

Buy Now Rs5.62 lakh only Features & Specifications →Fuel Type: Petrol →ARAI Mileage: 17–18 kmpl →Transmission: Manual | Automatic →Engine Capacity: 999 cc →Seating Capacity: 5 Seater →Price Range: Starts at ₹5.62 Lakh* →Available Colours: 12 →Safety Rating (NCAP): ◦ Adult Safety: ⭐⭐⭐⭐ (4 Star) ◦ Child Safety: ⭐⭐ (2 Star) Key Features →📱 Touchscreen Infotainment System →⚙️ Alloy Wheels →💡 LED Projector Headlights →❄️ Ventilated Seats →🔧 Tilt Adjustable Steering →🧊 Cooling Glove Box →🎒 Boot Space: 336 Litres →🛡️ 6 Airbags →🔴 LED Tail Lights Car Variants →Total Petrol Variants: 22 | Starting from ₹6.3L →Manual Variants: 11 | Starting from ₹6.3L →Automatic Variants: 11 | Starting from ₹7.1L Mileage / Range →Petrol Manual (999 cc): 19.61 kmpl →Petrol Automatic AMT (999 cc): 19.7 kmpl →Petrol Automatic CVT (999 cc): 17.9 kmpl Dimensions →Length: 3994 mm →Width: 1758 mm →Height: 1572 mm →Wheelbase: 2500 mm →Ground Clearance: 205 mm →Boot Space: 336 L Tyre Size Options →...

Turtlemint Personal Loan upto 5 lakhs

Enter Customer Details Enter Customer PAN Card No Enter Customer Phone Number Eligibility Criteria for Personal Loans- upto 5 lakhs Age 21 to 60 years Credit Score Should be above 700 Monthly Income Minimum of ₹15,000. Loan up to 20 times your monthly income Employment Type Salaried individuals or self-employed with ITR Existing EMIs Current EMIs should not exceed 60% of your monthly income Last Loan Should not have been taken in the past 30 days APPLY NOW Hi! Get Instant Loan up to ₹5 lakhs in just 2 minutes. Apply for a personal loan in just a few steps, quick approval and transparent process! https://turtlemintloans.com/products/personal-loan/customer/login?utm_source=DP_LINK&parnterid=5d1399b4e4b042b5269a0566

Poonawalla Fincorp - Loan upto 5 lakh

Loan  Apply Now Click on Loan