ChAbhishek28 commited on
Commit
f9f45e2
·
1 Parent(s): f139d4e

Add 899999999999999999999

Browse files
Files changed (1) hide show
  1. enhanced_websocket_handler.py +55 -36
enhanced_websocket_handler.py CHANGED
@@ -441,42 +441,61 @@ async def get_hybrid_response(user_message: str, context: str, config: dict, kno
441
  from rag_service import search_documents_async
442
  docs = await search_documents_async(user_message, limit=3)
443
  if docs:
444
- from scenario_analysis_service import run_scenario_analysis
445
- # Detect scenario analysis intent (simple keyword match)
446
- scenario_keywords = ["impact", "cost", "scenario", "multiplier", "da", "dr"]
447
- if any(kw in user_message.lower() for kw in scenario_keywords):
448
- # Example params extraction (can be improved)
449
- params = {
450
- 'base_pension': 30000,
451
- 'multiplier': 1.1 if "multiplier" in user_message.lower() else 1.0,
452
- 'da_percent': 0.06 if "da" in user_message.lower() else 0.0,
453
- 'num_beneficiaries': 1000,
454
- 'years': 3,
455
- 'inflation': 0.05
456
- }
457
- scenario_result = run_scenario_analysis(params)
458
- # Generate charts for scenario_result
459
- chart_gen = PolicyChartGenerator()
460
- charts = []
461
- # Example: line chart for yearly results
462
- if "yearly_results" in scenario_result:
463
- years = [r['year'] for r in scenario_result['yearly_results']]
464
- base_costs = [r['base_cost'] for r in scenario_result['yearly_results']]
465
- scenario_costs = [r['scenario_cost'] for r in scenario_result['yearly_results']]
466
- # Generate chart and append to charts list
467
- fig, ax = plt.subplots()
468
- ax.plot(years, base_costs, label='Base Cost')
469
- ax.plot(years, scenario_costs, label='Scenario Cost')
470
- ax.legend()
471
- ax.set_title('Scenario Analysis: Cost Over Years')
472
- buf = io.BytesIO()
473
- fig.savefig(buf, format='png')
474
- buf.seek(0)
475
- chart_base64 = base64.b64encode(buf.read()).decode('utf-8')
476
- plt.close(fig)
477
- charts.append({"type": "line_chart", "data": chart_base64})
478
- scenario_result["charts"] = charts
479
- else:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
480
  scenario_result = None
481
  for doc in docs:
482
  response_obj = {
 
441
  from rag_service import search_documents_async
442
  docs = await search_documents_async(user_message, limit=3)
443
  if docs:
444
+ try:
445
+ from scenario_analysis_service import run_scenario_analysis
446
+ # Detect scenario analysis intent (simple keyword match)
447
+ scenario_keywords = ["impact", "cost", "scenario", "multiplier", "da", "dr"]
448
+ if any(kw in user_message.lower() for kw in scenario_keywords):
449
+ logger.info("🔍 Running scenario analysis")
450
+ # Example params extraction (can be improved)
451
+ params = {
452
+ 'base_pension': 30000,
453
+ 'multiplier': 1.1 if "multiplier" in user_message.lower() else 1.0,
454
+ 'da_percent': 0.06 if "da" in user_message.lower() else 0.0,
455
+ 'num_beneficiaries': 1000,
456
+ 'years': 3,
457
+ 'inflation': 0.05
458
+ }
459
+ scenario_result = run_scenario_analysis(params)
460
+
461
+ # Generate charts for scenario_result
462
+ try:
463
+ chart_gen = PolicyChartGenerator()
464
+ charts = []
465
+ # Example: line chart for yearly results
466
+ if "yearly_results" in scenario_result:
467
+ years = [r['year'] for r in scenario_result['yearly_results']]
468
+ base_costs = [r['base_cost'] for r in scenario_result['yearly_results']]
469
+ scenario_costs = [r['scenario_cost'] for r in scenario_result['yearly_results']]
470
+ # Generate chart and append to charts list
471
+ fig, ax = plt.subplots(figsize=(10, 6))
472
+ ax.plot(years, base_costs, label='Base Cost', marker='o')
473
+ ax.plot(years, scenario_costs, label='Scenario Cost', marker='s')
474
+ ax.legend()
475
+ ax.set_title('Scenario Analysis: Cost Over Years')
476
+ ax.set_xlabel('Year')
477
+ ax.set_ylabel('Cost (₹)')
478
+ ax.grid(True, alpha=0.3)
479
+
480
+ # Format y-axis to show values in lakhs
481
+ ax.yaxis.set_major_formatter(plt.FuncFormatter(lambda x, p: f'₹{x/100000:.1f}L'))
482
+
483
+ buf = io.BytesIO()
484
+ fig.savefig(buf, format='png', dpi=150, bbox_inches='tight')
485
+ buf.seek(0)
486
+ chart_base64 = base64.b64encode(buf.read()).decode('utf-8')
487
+ plt.close(fig)
488
+ charts.append({"type": "line_chart", "data": chart_base64})
489
+ logger.info(f"✅ Generated {len(charts)} charts for scenario analysis")
490
+ scenario_result["charts"] = charts
491
+ except Exception as chart_error:
492
+ logger.error(f"❌ Failed to generate charts: {chart_error}")
493
+ scenario_result["charts"] = []
494
+ scenario_result["chart_error"] = str(chart_error)
495
+ else:
496
+ scenario_result = None
497
+ except Exception as scenario_error:
498
+ logger.error(f"❌ Scenario analysis failed: {scenario_error}")
499
  scenario_result = None
500
  for doc in docs:
501
  response_obj = {