rohitsar567 commited on
Commit
261abb2
·
1 Parent(s): 63290a7

fix(api): KI-145 — RENAME-vs-VARIANT smart dedup (final 164 cards)

Browse files

Replace strict-UIN merge with field-comparison rule. Same UIN + same
decision-critical terms = merge as alias (rename). Same UIN + 2+
diffs = keep as separate marketplace card (true sub-variants).

Decision-critical fields compared: copayment_pct, PED waiting,
maternity coverage + waiting months, room rent capping, restoration
benefit, NCB%, post-hospitalization days.

Result: ProHealth Prime + Protect stay separate (PED 24mo vs 48mo,
maternity Y vs N, post-hosp 180 vs 90). Activ One + Activ Health
Individual merge as alias (only NULL incompleteness differences).
Total marketplace = 164 cards.

Bumps DATASET_CACHE_BUST so HF Space rebuild pulls fresh state.

Files changed (2) hide show
  1. Dockerfile +1 -1
  2. backend/main.py +149 -8
Dockerfile CHANGED
@@ -70,7 +70,7 @@ COPY 40-data ./40-data
70
  # (7356 chunks from a prior ingest) instead of the freshly-uploaded
71
  # cleaned one (3799 chunks). Bump CACHE_BUST manually each time the
72
  # dataset is re-uploaded; the value just needs to change.
73
- ARG DATASET_CACHE_BUST=2026-05-15-ki144-v1
74
  RUN echo "Dataset cache bust: ${DATASET_CACHE_BUST}" && python -c "\
75
  from huggingface_hub import snapshot_download; \
76
  snapshot_download(\
 
70
  # (7356 chunks from a prior ingest) instead of the freshly-uploaded
71
  # cleaned one (3799 chunks). Bump CACHE_BUST manually each time the
72
  # dataset is re-uploaded; the value just needs to change.
73
+ ARG DATASET_CACHE_BUST=2026-05-15-ki145-v1
74
  RUN echo "Dataset cache bust: ${DATASET_CACHE_BUST}" && python -c "\
75
  from huggingface_hub import snapshot_download; \
76
  snapshot_download(\
backend/main.py CHANGED
@@ -611,14 +611,18 @@ async def coverage():
611
  # full algorithm rationale.
612
  extracted_stems_cov = {fp.stem for fp in sorted_files}
613
 
614
- # Phase A — extracted parents claim their UINs first.
 
 
615
  uin_to_parent_cov: dict[str, str] = {}
616
  extracted_uin_cov: dict[str, str] = {}
 
617
  for fp in sorted_files:
618
  try:
619
  _d = _json.loads(fp.read_text())
620
  except Exception:
621
  continue
 
622
  _u = _d.get("uin_code")
623
  if isinstance(_u, dict):
624
  _u = _u.get("value")
@@ -647,7 +651,15 @@ async def coverage():
647
  parent_id: str | None = None
648
  if curated_uin and curated_uin in uin_to_parent_cov \
649
  and uin_to_parent_cov[curated_uin] != curated_pid:
650
- parent_id = uin_to_parent_cov[curated_uin]
 
 
 
 
 
 
 
 
651
  elif curated_uin:
652
  uin_to_parent_cov[curated_uin] = curated_pid
653
 
@@ -657,7 +669,12 @@ async def coverage():
657
  # extracted; multi-variant PDFs naturally share one filing).
658
  fb_parent = _source_pdf_to_policy_id(cdata.get("_primary_source_pdf"))
659
  if fb_parent and fb_parent in extracted_stems_cov and fb_parent != curated_pid:
660
- parent_id = fb_parent
 
 
 
 
 
661
 
662
  if parent_id:
663
  direct_parent_cov[curated_pid] = parent_id
@@ -1354,6 +1371,112 @@ def _merge_curated(extracted: dict, curated: dict | None) -> dict:
1354
  return merged
1355
 
1356
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1357
  @app.get("/api/policies/all", response_model=MarketplaceResponse)
1358
  async def policies_all(session_id: Optional[str] = None):
1359
  """The marketplace data feed — every extracted policy + scorecard + filterable fields.
@@ -1479,14 +1602,18 @@ async def policies_all(session_id: Optional[str] = None):
1479
  # separate cards because their UINs claim independent parents.
1480
  extracted_stems = {fp.stem for fp in sorted_files}
1481
 
1482
- # Phase A — extracted parents claim their UINs first.
 
 
1483
  uin_to_parent: dict[str, str] = {}
1484
  extracted_uin: dict[str, str] = {} # kept for downstream introspection
 
1485
  for fp in sorted_files:
1486
  try:
1487
  _d = _json.loads(fp.read_text())
1488
  except Exception:
1489
  continue
 
1490
  _u = _d.get("uin_code")
1491
  if isinstance(_u, dict):
1492
  _u = _u.get("value")
@@ -1526,9 +1653,18 @@ async def policies_all(session_id: Optional[str] = None):
1526
  parent_id: str | None = None
1527
  if curated_uin and curated_uin in uin_to_parent \
1528
  and uin_to_parent[curated_uin] != curated_policy_id:
1529
- # UIN-primary path: collapse onto the prior claimant of this UIN
1530
- # (different policy_name same regulator filing = pure rename).
1531
- parent_id = uin_to_parent[curated_uin]
 
 
 
 
 
 
 
 
 
1532
  elif curated_uin:
1533
  # New UIN — this curated entry becomes the claimant so any
1534
  # later curated sibling with the same UIN aliases onto it.
@@ -1542,7 +1678,12 @@ async def policies_all(session_id: Optional[str] = None):
1542
  # source-PDF coincidence (multi-variant wordings) does NOT merge.
1543
  fb_parent = _source_pdf_to_policy_id(cdata.get("_primary_source_pdf"))
1544
  if fb_parent and fb_parent in extracted_stems and fb_parent != curated_policy_id:
1545
- parent_id = fb_parent
 
 
 
 
 
1546
 
1547
  if parent_id:
1548
  direct_parent[curated_policy_id] = parent_id
 
611
  # full algorithm rationale.
612
  extracted_stems_cov = {fp.stem for fp in sorted_files}
613
 
614
+ # Phase A — extracted parents claim their UINs first. We also retain the
615
+ # parsed extracted JSON so Phase B can run the KI-145 material-diff check
616
+ # without re-reading from disk.
617
  uin_to_parent_cov: dict[str, str] = {}
618
  extracted_uin_cov: dict[str, str] = {}
619
+ extracted_data_cov: dict[str, dict] = {}
620
  for fp in sorted_files:
621
  try:
622
  _d = _json.loads(fp.read_text())
623
  except Exception:
624
  continue
625
+ extracted_data_cov[fp.stem] = _d
626
  _u = _d.get("uin_code")
627
  if isinstance(_u, dict):
628
  _u = _u.get("value")
 
651
  parent_id: str | None = None
652
  if curated_uin and curated_uin in uin_to_parent_cov \
653
  and uin_to_parent_cov[curated_uin] != curated_pid:
654
+ # KI-145 (2026-05-15) — same UIN ≠ same product. Compare
655
+ # decision-critical fields against the candidate extracted
656
+ # parent; if 2+ disagree (non-null on both sides) this is a
657
+ # VARIANT and stays as its own card. Pure RENAME (< 2 diffs)
658
+ # falls through to the alias-merge as before.
659
+ candidate = uin_to_parent_cov[curated_uin]
660
+ ext_data = extracted_data_cov.get(candidate, {})
661
+ if _ki145_material_diffs(cdata, ext_data) < 2:
662
+ parent_id = candidate
663
  elif curated_uin:
664
  uin_to_parent_cov[curated_uin] = curated_pid
665
 
 
669
  # extracted; multi-variant PDFs naturally share one filing).
670
  fb_parent = _source_pdf_to_policy_id(cdata.get("_primary_source_pdf"))
671
  if fb_parent and fb_parent in extracted_stems_cov and fb_parent != curated_pid:
672
+ # KI-145 — same material-diff gate on the source-PDF path so
673
+ # multi-variant PDFs don't drag genuinely different products
674
+ # onto the first claimant via source-PDF coincidence.
675
+ ext_data = extracted_data_cov.get(fb_parent, {})
676
+ if _ki145_material_diffs(cdata, ext_data) < 2:
677
+ parent_id = fb_parent
678
 
679
  if parent_id:
680
  direct_parent_cov[curated_pid] = parent_id
 
1371
  return merged
1372
 
1373
 
1374
+ # KI-145 (2026-05-15) — decision-critical fields used to distinguish a
1375
+ # RENAME (curated entry folds onto extracted parent) from a VARIANT (same
1376
+ # UIN but materially different product — must stay as its own card).
1377
+ # Same UIN ≠ same product: regulators file one "wordings" PDF that covers
1378
+ # multiple marketed variants (e.g. ProHealth Prime vs ProHealth Protect
1379
+ # both filed under MCIHLIP24011V072324; copay/PED/maternity/NCB differ).
1380
+ _KI145_DIFF_FIELDS: tuple[str, ...] = (
1381
+ "copayment_pct",
1382
+ "pre_existing_disease_waiting_months",
1383
+ "maternity_coverage",
1384
+ "maternity_waiting_months",
1385
+ "room_rent_capping",
1386
+ "restoration_benefit",
1387
+ "no_claim_bonus_pct",
1388
+ "post_hospitalization_days",
1389
+ )
1390
+
1391
+
1392
+ def _ki145_extract_value(raw, field: str):
1393
+ """Unwrap the value from either scalar OR nested `{value, ...}` shapes.
1394
+ For two fields the extracted-side shape is `{covered, ...}` instead of
1395
+ `{value, ...}`: maternity_coverage and restoration_benefit. We project
1396
+ those onto the boolean `covered` so a curated bool/str compares cleanly
1397
+ against the extracted dict's truthiness.
1398
+ """
1399
+ if raw is None:
1400
+ return None
1401
+ if isinstance(raw, dict):
1402
+ if "value" in raw:
1403
+ return raw.get("value")
1404
+ if field in ("maternity_coverage", "restoration_benefit") and "covered" in raw:
1405
+ return raw.get("covered")
1406
+ # Unknown dict shape — treat as opaque non-null marker so a real
1407
+ # diff isn't accidentally suppressed.
1408
+ return raw
1409
+ return raw
1410
+
1411
+
1412
+ def _ki145_normalize(field: str, val):
1413
+ """Coerce field value into a comparable form (numbers as floats, bools as
1414
+ bools, strings stripped lower-case). Returns None on null/empty/"" so it
1415
+ is consistently skipped in the diff count."""
1416
+ if val is None:
1417
+ return None
1418
+ # Numeric fields
1419
+ if field in (
1420
+ "copayment_pct",
1421
+ "pre_existing_disease_waiting_months",
1422
+ "maternity_waiting_months",
1423
+ "no_claim_bonus_pct",
1424
+ "post_hospitalization_days",
1425
+ ):
1426
+ try:
1427
+ return float(val)
1428
+ except (TypeError, ValueError):
1429
+ return None
1430
+ # Boolean fields
1431
+ if field == "maternity_coverage":
1432
+ if isinstance(val, bool):
1433
+ return val
1434
+ if isinstance(val, (int, float)):
1435
+ return bool(val)
1436
+ if isinstance(val, str):
1437
+ s = val.strip().lower()
1438
+ if s in ("true", "yes", "covered"):
1439
+ return True
1440
+ if s in ("false", "no", "not covered", "excluded"):
1441
+ return False
1442
+ return None
1443
+ return None
1444
+ # Restoration may arrive as bool (extracted .covered), str (curated prose)
1445
+ # or dict (already unwrapped above). Treat presence/absence as the signal:
1446
+ # a free-text limit phrase = True, explicit False/None = False.
1447
+ if field == "restoration_benefit":
1448
+ if isinstance(val, bool):
1449
+ return val
1450
+ if isinstance(val, str):
1451
+ s = val.strip().lower()
1452
+ if not s:
1453
+ return None
1454
+ if s in ("false", "no", "none", "n/a", "not available"):
1455
+ return False
1456
+ return True
1457
+ return None
1458
+ # String fields (room_rent_capping)
1459
+ if isinstance(val, str):
1460
+ s = val.strip().lower()
1461
+ return s or None
1462
+ return val
1463
+
1464
+
1465
+ def _ki145_material_diffs(curated: dict, extracted: dict) -> int:
1466
+ """Count fields where BOTH sides have non-null values that disagree.
1467
+ Null on either side = SKIP (extraction incompleteness, not a real diff).
1468
+ >= 2 diffs → VARIANT (keep separate). < 2 → RENAME (alias-merge)."""
1469
+ diffs = 0
1470
+ for f in _KI145_DIFF_FIELDS:
1471
+ cur_v = _ki145_normalize(f, _ki145_extract_value(curated.get(f), f))
1472
+ ext_v = _ki145_normalize(f, _ki145_extract_value(extracted.get(f), f))
1473
+ if cur_v is None or ext_v is None:
1474
+ continue # extraction incompleteness, not a real diff
1475
+ if cur_v != ext_v:
1476
+ diffs += 1
1477
+ return diffs
1478
+
1479
+
1480
  @app.get("/api/policies/all", response_model=MarketplaceResponse)
1481
  async def policies_all(session_id: Optional[str] = None):
1482
  """The marketplace data feed — every extracted policy + scorecard + filterable fields.
 
1602
  # separate cards because their UINs claim independent parents.
1603
  extracted_stems = {fp.stem for fp in sorted_files}
1604
 
1605
+ # Phase A — extracted parents claim their UINs first. We also retain the
1606
+ # parsed extracted JSON so Phase B can run the KI-145 material-diff check
1607
+ # without re-reading from disk.
1608
  uin_to_parent: dict[str, str] = {}
1609
  extracted_uin: dict[str, str] = {} # kept for downstream introspection
1610
+ extracted_data: dict[str, dict] = {}
1611
  for fp in sorted_files:
1612
  try:
1613
  _d = _json.loads(fp.read_text())
1614
  except Exception:
1615
  continue
1616
+ extracted_data[fp.stem] = _d
1617
  _u = _d.get("uin_code")
1618
  if isinstance(_u, dict):
1619
  _u = _u.get("value")
 
1653
  parent_id: str | None = None
1654
  if curated_uin and curated_uin in uin_to_parent \
1655
  and uin_to_parent[curated_uin] != curated_policy_id:
1656
+ # KI-145 (2026-05-15) — UIN-primary path with smart variant
1657
+ # detection. Same UIN does NOT guarantee same product: a single
1658
+ # regulator-filed PDF often covers multiple marketed variants
1659
+ # (e.g. ProHealth Prime vs ProHealth Protect both filed under
1660
+ # MCIHLIP24011V072324; activ-assure-diamond curated vs extracted
1661
+ # disagree on PED/NCB). Compare 8 decision-critical fields; if
1662
+ # 2+ disagree on non-null values, treat as a VARIANT and keep
1663
+ # this curated entry as its own card. < 2 = pure rename → merge.
1664
+ candidate = uin_to_parent[curated_uin]
1665
+ ext_data = extracted_data.get(candidate, {})
1666
+ if _ki145_material_diffs(cdata, ext_data) < 2:
1667
+ parent_id = candidate
1668
  elif curated_uin:
1669
  # New UIN — this curated entry becomes the claimant so any
1670
  # later curated sibling with the same UIN aliases onto it.
 
1678
  # source-PDF coincidence (multi-variant wordings) does NOT merge.
1679
  fb_parent = _source_pdf_to_policy_id(cdata.get("_primary_source_pdf"))
1680
  if fb_parent and fb_parent in extracted_stems and fb_parent != curated_policy_id:
1681
+ # KI-145 — apply the same material-diffs gate so multi-variant
1682
+ # PDFs without UIN coverage don't drag genuinely different
1683
+ # products into the parent card.
1684
+ ext_data = extracted_data.get(fb_parent, {})
1685
+ if _ki145_material_diffs(cdata, ext_data) < 2:
1686
+ parent_id = fb_parent
1687
 
1688
  if parent_id:
1689
  direct_parent[curated_policy_id] = parent_id