""" Policy Impact Simulator Chat Integration Provides natural language interface for policy impact simulation """ import re import json import logging from typing import Dict, Any, Optional, List from datetime import datetime, timedelta from dataclasses import dataclass from policy_impact_simulator import ( PolicyImpactSimulator, PolicyScenario, PolicyParameter ) from policy_chart_generator import PolicyChartGenerator logger = logging.getLogger(__name__) @dataclass class PolicyQuery: """Parsed policy query from natural language""" intent: str parameter: Optional[PolicyParameter] current_value: Optional[float] proposed_value: Optional[float] years: int = 5 raw_query: str = "" class PolicySimulatorChatInterface: """Chat interface for policy impact simulation""" def __init__(self): self.simulator = PolicyImpactSimulator() self.chart_generator = PolicyChartGenerator() self.conversation_context = {} # Enhanced pattern matching for natural language queries self.patterns = { "simulate_dr": [ r"simulate.*dearness.*relief.*(\d+).*to.*(\d+)", r"dr.*increase.*from.*(\d+).*to.*(\d+)", r"what.*if.*dr.*changes.*(\d+).*(\d+)", r"impact.*dearness.*(\d+).*percent.*(\d+).*percent", r"dr.*analysis.*(\d+).*(\d+)", r"dearness.*relief.*(\d+).*(\d+)", r"impact.*increasing.*dr.*by.*(\d+)", r"show.*impact.*dr.*by.*(\d+)", r"dr.*increase.*by.*(\d+).*percent", r"increase.*dr.*by.*(\d+)" ], "simulate_pension": [ r"simulate.*basic.*pension.*(\d+).*to.*(\d+)", r"pension.*increase.*from.*(\d+).*to.*(\d+)", r"what.*if.*pension.*changes.*(\d+).*(\d+)", r"impact.*basic.*pension.*(\d+).*(\d+)", r"pension.*boost.*(\d+).*(\d+)", r"basic.*pension.*(\d+).*(\d+)", r"analyze.*minimum.*pension.*changes", r"analyze.*basic.*pension", r"minimum.*pension.*analysis", r"basic.*pension.*impact" ], "simulate_medical": [ r"simulate.*medical.*allowance.*(\d+).*to.*(\d+)", r"medical.*increase.*from.*(\d+).*to.*(\d+)", r"what.*if.*medical.*changes.*(\d+).*(\d+)", r"medical.*allowance.*(\d+).*(\d+)" ], "scenario_analysis": [ r"scenario.*analysis.*pension", r"do.*scenario.*analysis", r"pension.*scenario.*analysis", r"analyze.*pension.*scenarios", r"scenario.*analysis.*dr", r"pension.*rules.*scenario", r"government.*policy.*scenario", r"policy.*scenario.*analysis" ], "interactive_form": [ r"start.*scenario.*analysis", r"interactive.*scenario", r"step.*by.*step.*analysis", r"guided.*analysis", r"scenario.*form" ], "general_policy": [ r"policy.*impact.*simulation", r"simulate.*policy.*change", r"what.*if.*we.*change", r"impact.*analysis.*policy", r"policy.*analysis", r"government.*policy.*impact" ], "compare_scenarios": [ r"compare.*scenarios", r"which.*is.*better.*policy", r"cost.*comparison.*policies", r"scenario.*comparison", r"best.*case.*worst.*case" ] } def process_policy_query(self, query: str, user_id: str = "default") -> Dict[str, Any]: """ Process natural language policy query and return simulation results """ try: # Parse the query parsed_query = self._parse_policy_query(query) if not parsed_query: return self._get_help_response() # Handle different intents if parsed_query.intent == "simulate": return self._handle_simulation_request(parsed_query, user_id) elif parsed_query.intent == "compare": return self._handle_comparison_request(parsed_query, user_id) elif parsed_query.intent == "help": return self._get_help_response() elif parsed_query.intent == "scenario_analysis": return self._handle_scenario_analysis_request(parsed_query, user_id) elif parsed_query.intent == "interactive_form": return self._start_interactive_form(user_id) else: return self._get_clarification_response(query) except Exception as e: logger.error(f"Policy query processing error: {e}") return { "type": "error", "message": f"Sorry, I encountered an error processing your policy query: {str(e)}", "suggestions": ["Try rephrasing your question", "Use specific numbers and policy parameters"] } def _parse_policy_query(self, query: str) -> Optional[PolicyQuery]: """Parse natural language query into structured policy query""" query_lower = query.lower() # Check for explicit help requests (more specific to avoid false positives) help_patterns = [r"^help", r"how.*do.*i", r"what.*can.*you", r"guide.*me", r"need.*help"] if any(re.search(pattern, query_lower) for pattern in help_patterns): return PolicyQuery(intent="help", parameter=None, current_value=None, proposed_value=None, raw_query=query) # Check for comparison requests if any(word in query_lower for word in ["compare", "vs", "versus", "which is better"]): return PolicyQuery(intent="compare", parameter=None, current_value=None, proposed_value=None, raw_query=query) # Try to match simulation patterns for intent, patterns in self.patterns.items(): for pattern in patterns: match = re.search(pattern, query_lower) if match: return self._extract_simulation_params(intent, match, query) # Check for general policy simulation intent if any(word in query_lower for word in ["simulate", "impact", "policy", "change", "effect"]): return PolicyQuery(intent="simulate", parameter=None, current_value=None, proposed_value=None, raw_query=query) return None def _extract_simulation_params(self, intent: str, match, raw_query: str) -> PolicyQuery: """Extract simulation parameters from regex match""" try: # Handle new intent types that don't need parameter extraction if intent in ["scenario_analysis", "interactive_form"]: return PolicyQuery( intent=intent, parameter=None, current_value=None, proposed_value=None, raw_query=raw_query ) groups = match.groups() # Map intent to parameter for simulation intents parameter_mapping = { "simulate_dr": PolicyParameter.DEARNESS_RELIEF, "simulate_pension": PolicyParameter.BASIC_PENSION, "simulate_medical": PolicyParameter.MEDICAL_ALLOWANCE } parameter = parameter_mapping.get(intent, PolicyParameter.DEARNESS_RELIEF) # Handle different pattern types if len(groups) == 0: # No numbers - provide default analysis scenario if parameter == PolicyParameter.DEARNESS_RELIEF: current_value = 12.0 # Current DR is 12% proposed_value = 18.0 # Standard 6% increase elif parameter == PolicyParameter.BASIC_PENSION: current_value = 6000.0 # Current basic pension is ₹6,000 proposed_value = 8000.0 # Standard ₹2,000 increase elif parameter == PolicyParameter.MEDICAL_ALLOWANCE: current_value = 1000.0 # Current medical allowance is ₹1,000 proposed_value = 1500.0 # Standard ₹500 increase else: current_value = 0.0 proposed_value = 1.0 elif len(groups) == 1: # Single number - treat as percentage increase increase_amount = float(groups[0]) # Set current values based on parameter type if parameter == PolicyParameter.DEARNESS_RELIEF: current_value = 12.0 # Current DR is 12% proposed_value = current_value + increase_amount elif parameter == PolicyParameter.BASIC_PENSION: current_value = 6000.0 # Current basic pension is ₹6,000 proposed_value = current_value + increase_amount elif parameter == PolicyParameter.MEDICAL_ALLOWANCE: current_value = 1000.0 # Current medical allowance is ₹1,000 proposed_value = current_value + increase_amount else: current_value = increase_amount proposed_value = increase_amount * 1.5 # Default 50% increase else: # Two numbers - from X to Y current_value = float(groups[0]) if len(groups) > 0 else None proposed_value = float(groups[1]) if len(groups) > 1 else None # Extract years if mentioned years_match = re.search(r"(\d+).*years?", raw_query.lower()) years = int(years_match.group(1)) if years_match else 5 return PolicyQuery( intent="simulate", parameter=parameter, current_value=current_value, proposed_value=proposed_value, years=min(years, 10), # Cap at 10 years raw_query=raw_query ) except Exception as e: logger.error(f"Parameter extraction error: {e}") return PolicyQuery(intent="simulate", parameter=None, current_value=None, proposed_value=None, raw_query=raw_query) def _handle_simulation_request(self, parsed_query: PolicyQuery, user_id: str) -> Dict[str, Any]: """Handle policy simulation request""" try: # If missing parameters, provide clarification with specific guidance if not all([parsed_query.parameter, parsed_query.current_value, parsed_query.proposed_value]): return self._get_clarification_response(parsed_query.raw_query) # Create scenario scenario = PolicyScenario( parameter=parsed_query.parameter, current_value=parsed_query.current_value, proposed_value=parsed_query.proposed_value, effective_date=datetime.now() + timedelta(days=90), # 3 months from now affected_population=self._estimate_affected_population(parsed_query.parameter), annual_growth_rate=0.03, inflation_rate=0.06 ) # Run simulation result = self.simulator.simulate_policy_impact(scenario, parsed_query.years, True) # Format for chat response return self._format_simulation_response(result, parsed_query) except Exception as e: logger.error(f"Simulation request error: {e}") return { "type": "error", "message": f"Simulation failed: {str(e)}", "raw_query": parsed_query.raw_query } def _estimate_affected_population(self, parameter: PolicyParameter) -> int: """Estimate affected population based on parameter type""" population_estimates = { PolicyParameter.DEARNESS_RELIEF: 510000, # All pensioners PolicyParameter.BASIC_PENSION: 450000, # Basic pension recipients PolicyParameter.MEDICAL_ALLOWANCE: 510000, # All pensioners PolicyParameter.PENSION_FACTOR: 510000, PolicyParameter.MINIMUM_PENSION: 200000 # Lower income pensioners } return population_estimates.get(parameter, 400000) def _format_simulation_response(self, result: Dict[str, Any], query: PolicyQuery) -> Dict[str, Any]: """Format simulation results for chat display""" if "error" in result: return { "type": "error", "message": f"Simulation error: {result['error']}" } total_impact = result.get("total_impact", {}) projections = result.get("scenario_projections", []) clause_analysis = result.get("clause_analysis", {}) # Create summary message summary = f""" 🎯 **Policy Impact Simulation Results** **Parameter**: {result.get('parameter_name', 'Unknown')} **Change**: {result.get('current_value')} → {result.get('proposed_value')} **Effective Date**: {result.get('effective_date', '').split('T')[0]} 📊 **Financial Impact Over {result.get('projection_years')} Years**: • **Total Additional Cost**: ₹{total_impact.get('total_additional_cost_crores', 0):.1f} crores • **Percentage Increase**: {total_impact.get('percentage_increase', 0):.1f}% • **Annual Average**: ₹{total_impact.get('annual_average_impact_crores', 0):.1f} crores • **Cost per Beneficiary**: ₹{total_impact.get('cost_per_beneficiary_annual', 0):,.0f} per year 📈 **Year-by-Year Breakdown**: """ # Add yearly breakdown for i, proj in enumerate(projections[:3]): # Show first 3 years summary += f"Year {proj.year}: ₹{proj.impact/10000000:.1f} crores impact ({proj.affected_beneficiaries:,} beneficiaries)\n" if len(projections) > 3: summary += f"... and {len(projections)-3} more years\n" # Add clause information if clause_analysis: clause_diff = clause_analysis.get("clause_diff", {}) summary += f""" ⚖️ **Policy Changes**: • **Change Type**: {clause_diff.get('change_type', 'Unknown').title()} • **Magnitude**: {clause_diff.get('change_percentage', 0):.1f}% change • **Affected Clauses**: {len(clause_analysis.get('affected_clauses', []))} clauses modified """ # Add scenario variants variants = result.get("variants", {}) charts = [] if variants: best_case = sum(p.impact for p in variants.get("best_case", [])) / 10000000 worst_case = sum(p.impact for p in variants.get("worst_case", [])) / 10000000 base_case = total_impact.get('total_additional_cost_crores', 0) summary += f""" 📊 **Scenario Analysis**: • **Best Case**: ₹{best_case:.1f} crores • **Base Case**: ₹{base_case:.1f} crores • **Worst Case**: ₹{worst_case:.1f} crores """ # Generate charts try: # Scenario comparison chart scenario_data = { 'best_case': {'total_cost': best_case}, 'base_case': {'total_cost': base_case}, 'worst_case': {'total_cost': worst_case} } chart_title = f"{result.get('parameter_name', 'Policy')} Impact Analysis" scenario_chart = self.chart_generator.generate_scenario_comparison_chart( scenario_data, chart_title ) if scenario_chart: charts.append({ "type": "scenario_comparison", "title": chart_title, "data": scenario_chart }) # Year-by-year breakdown chart if projections: # Convert projections to the format expected by chart generator yearly_data = [] for proj in projections: yearly_data.append({ 'year': proj.year, 'impact': proj.impact / 10000000, # Convert to crores 'beneficiaries': proj.affected_beneficiaries }) trend_chart = self.chart_generator.generate_yearly_breakdown_chart( yearly_data, f"{result.get('parameter_name', 'Policy')} 5-Year Impact" ) if trend_chart: charts.append({ "type": "yearly_trend", "title": "5-Year Financial Impact Trend", "data": trend_chart }) except Exception as e: logger.error(f"Chart generation error: {e}") return { "type": "policy_simulation", "message": summary, "simulation_id": result.get("scenario_id"), "detailed_results": result, "charts": charts, "export_options": ["CSV", "PDF", "JSON"], "follow_up_suggestions": [ "Compare with other policy scenarios", "Analyze implementation timeline", "Export detailed evidence pack", "Simulate different effective dates" ] } def _get_interactive_form(self, parsed_query: PolicyQuery) -> Dict[str, Any]: """Provide interactive form for missing parameters""" available_parameters = [ {"id": "dearness_relief", "name": "Dearness Relief (%)", "current": 12.0, "unit": "%"}, {"id": "basic_pension", "name": "Basic Pension (₹)", "current": 6000, "unit": "₹"}, {"id": "medical_allowance", "name": "Medical Allowance (₹)", "current": 1000, "unit": "₹"}, {"id": "pension_factor", "name": "Pension Factor", "current": 1.0, "unit": "multiplier"}, {"id": "minimum_pension", "name": "Minimum Pension (₹)", "current": 3500, "unit": "₹"} ] return { "type": "interactive_form", "message": "I'd be happy to help you simulate policy impact! Please provide the following details:", "form_fields": [ { "name": "parameter", "label": "Policy Parameter", "type": "select", "options": available_parameters, "required": True }, { "name": "current_value", "label": "Current Value", "type": "number", "required": True }, { "name": "proposed_value", "label": "Proposed Value", "type": "number", "required": True }, { "name": "years", "label": "Projection Years", "type": "number", "default": 5, "min": 1, "max": 10 } ], "examples": [ "Simulate DR increase from 12% to 18% over 5 years", "What if basic pension changes from ₹6000 to ₹8000?", "Impact of medical allowance increase to ₹2000" ] } def _handle_comparison_request(self, parsed_query: PolicyQuery, user_id: str) -> Dict[str, Any]: """Handle policy comparison request""" sample_comparisons = [ { "name": "DR vs Basic Pension Increase", "scenarios": [ {"parameter": "DR", "change": "12% → 18%", "impact": "₹85.2 crores"}, {"parameter": "Basic Pension", "change": "₹6000 → ₹8000", "impact": "₹108.0 crores"} ], "recommendation": "DR increase is more cost-effective" }, { "name": "Short vs Long Term Impact", "scenarios": [ {"period": "3 years", "total_impact": "₹150.5 crores"}, {"period": "10 years", "total_impact": "₹628.3 crores"} ], "recommendation": "Long-term planning essential" } ] return { "type": "policy_comparison", "message": "Here are some policy comparison examples. Would you like to compare specific scenarios?", "comparisons": sample_comparisons, "custom_comparison": { "description": "I can help you compare up to 5 different policy scenarios", "example": "Compare DR increase vs pension boost vs medical allowance increase" } } def _get_help_response(self) -> Dict[str, Any]: """Provide help information""" return { "type": "help", "message": """ 🎯 **Policy Impact Simulator Help** I can help you simulate the financial impact of government policy changes. Here's what I can do: **📊 Simulation Capabilities**: • Dearness Relief (DR) changes • Basic pension adjustments • Medical allowance modifications • Pension factor changes • Minimum pension guarantees **💬 How to Ask**: • "Simulate DR increase from 12% to 18%" • "What if basic pension changes from ₹6000 to ₹8000?" • "Impact of medical allowance increase to ₹2000 over 5 years" • "Compare DR increase vs pension boost" **📈 What You Get**: • Total financial impact over 3-10 years • Year-by-year breakdown • Best/base/worst case scenarios • Affected population estimates • Policy clause analysis • Implementation timeline • Exportable evidence pack **🚀 Quick Examples**: Try asking: "Show me the impact of increasing DR by 6%" """, "quick_actions": [ {"label": "Sample DR Simulation", "query": "simulate DR from 12 to 18 percent"}, {"label": "Basic Pension Impact", "query": "what if basic pension increases to 8000"}, {"label": "Compare Scenarios", "query": "compare policy scenarios"}, {"label": "View Parameters", "query": "show available policy parameters"} ] } def _get_clarification_response(self, query: str) -> Dict[str, Any]: """Request clarification for unclear queries""" # Provide specific guidance based on the query content query_lower = query.lower() if "da" in query_lower or "dearness allowance" in query_lower or "dr" in query_lower: specific_message = """🎯 **DA/DR Impact Analysis** I can help you analyze the Dearness Allowance (DA) impact! To provide accurate calculations, please specify: 📊 **Required Details:** • **Current DA Rate**: What's the existing DA percentage? (e.g., 12%) • **Proposed DA Rate**: What should the new DA be? (e.g., 18% for a 6% increase) • **Base Pension Amount**: What's the basic pension amount? (e.g., ₹6,000) • **Analysis Period**: How many years to analyze? (default: 5 years) 💡 **Quick Examples:** • "Show DA impact from 12% to 18% for pension ₹6000" • "Analyze 6% DA increase from current 12% to 18%" • "DA simulation: current 12%, increase to 18%, basic pension ₹6000" 📈 **What You'll Get:** • Financial impact over 5 years with charts • Cost per beneficiary calculations • Best/Base/Worst case scenarios • Implementation timeline and evidence pack""" elif "pension" in query_lower and ("basic" in query_lower or "minimum" in query_lower): specific_message = """🎯 **Basic Pension Impact Analysis** I can help analyze basic pension changes! Please provide: 📊 **Required Details:** • **Current Basic Pension**: What's the existing amount? (e.g., ₹6,000) • **Proposed Basic Pension**: What should the new amount be? (e.g., ₹8,000) • **Analysis Period**: How many years to analyze? (default: 5 years) 💡 **Quick Examples:** • "Show basic pension impact from ₹6000 to ₹8000" • "Analyze pension increase to ₹8000 over 5 years" • "Basic pension simulation: current ₹6000, increase to ₹8000" 📈 **What You'll Get:** • Financial impact projections with charts • Affected population estimates • Cost analysis and implementation timeline""" else: specific_message = """🎯 **Policy Impact Simulation Help** I understand you want to analyze policy impact! To provide accurate calculations, please specify: 📊 **Choose Your Analysis:** • **DA/DR Changes**: Dearness Allowance adjustments (e.g., "DA from 12% to 18%") • **Basic Pension**: Minimum pension amount changes (e.g., "Pension from ₹6000 to ₹8000") • **Medical Allowance**: Healthcare support changes (e.g., "Medical allowance to ₹1500") 💡 **Format Your Request:** Include: Current value → Proposed value → Base amount (if applicable) 📈 **Quick Examples:** • "Show DA impact from 12% to 18% for pension ₹6000" • "Analyze basic pension increase from ₹6000 to ₹8000" • "Medical allowance impact from ₹1000 to ₹1500" """ return { "type": "clarification", "message": specific_message, "original_query": query, "suggestions": [ "📊 Use the format: 'Show [policy] impact from [current] to [proposed]'", "📈 Include specific numbers and amounts", "⏱️ Specify time period if different from 5 years" ], "quick_actions": [ {"text": "📈 DA Analysis Example", "query": "Show DA impact from 12% to 18% for pension ₹6000"}, {"text": "💰 Pension Analysis Example", "query": "Show basic pension impact from ₹6000 to ₹8000"}, {"text": "📋 Start Interactive Form", "query": "start scenario analysis"} ] } def _handle_scenario_analysis_request(self, parsed_query: PolicyQuery, user_id: str) -> Dict[str, Any]: """Handle general scenario analysis requests""" return { "type": "scenario_analysis_help", "message": """🎯 **Scenario Analysis for Rajasthan Pension Policies** I can help you analyze different scenarios for pension policy changes. Here are the most common analyses: 📊 **Available Scenario Analyses:** • **Dearness Relief (DR)**: Analyze inflation adjustments (current: 12%) • **Basic Pension**: Analyze minimum pension changes (current: ₹6,000) • **Medical Allowance**: Analyze healthcare support changes (current: ₹1,000) • **Pension Factor**: Analyze salary multiplier changes (current: 1.0x) 💬 **How to Request Analysis:** • "Simulate DR increase from 12% to 18% over 5 years" • "What if basic pension increases to ₹8,000?" • "Compare best and worst case scenarios for medical allowance" 📈 **What You'll Get:** • Financial impact projections (3-10 years) • Best/Base/Worst case scenarios • Affected population estimates • Implementation timeline and complexity • Exportable evidence packs 🚀 **Try These Examples:**""", "quick_actions": [ {"text": "📈 Analyze DR Scenarios", "query": "Show DR scenario analysis from 12% to 18%"}, {"text": "💰 Analyze Pension Scenarios", "query": "Show basic pension scenarios from 6000 to 8000"}, {"text": "🏥 Analyze Medical Allowance", "query": "Show medical allowance scenarios"}, {"text": "📋 Start Interactive Form", "query": "start scenario analysis"} ] } def _start_interactive_form(self, user_id: str) -> Dict[str, Any]: """Start interactive scenario analysis form""" try: from scenario_chat_form import start_scenario_analysis_form return start_scenario_analysis_form(user_id) except Exception as e: logger.error(f"Interactive form start failed: {e}") return { "type": "error", "message": "Sorry, I couldn't start the interactive form. Let me help you with a quick simulation instead.", "fallback_form": self._get_clarification_response("") } # Usage integration function def process_policy_chat_query(query: str, user_id: str = "default") -> Dict[str, Any]: """ Main function to process policy-related chat queries Use this in your main chat system """ interface = PolicySimulatorChatInterface() return interface.process_policy_query(query, user_id)