Datasets:
File size: 176,025 Bytes
b8ea052 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 | """Executable visual predicates embedded in PVR evaluation contracts.
Natural-language questions and criteria remain useful for review, but they are
not an execution interface. This module compiles one reviewed check into a
small, validated program that names its subjects, tool operations, derived
regions, state machine, and deterministic decision table.
Only explicitly supported predicate families are executable. Everything
else is represented as ``blocked_uncompiled`` so downstream code cannot fall
back to guessing tools from prose.
"""
from __future__ import annotations
from copy import deepcopy
from dataclasses import dataclass
import re
from typing import Any, Mapping, Sequence
from pvr_eval.contracts.metric_profiles import (
ARTICULATED_ENTITY_PRESERVATION_EXECUTOR_VERSION,
ARTICULATED_ENTITY_PRESERVATION_PROFILE,
REPEATED_COMPONENT_GROUP_IDENTITY_EXECUTOR_VERSION,
REPEATED_COMPONENT_GROUP_IDENTITY_PROFILE,
SHELF_SOURCE_GROUP_CLEARANCE_PROFILE,
shelf_source_group_clearance_profile_parameters,
)
from pvr_eval.agent.source_instance_selector import (
ANCHOR_RELATIVE_SOURCE_INSTANCE_PROFILE,
SUPPORTED_ANCHOR_PARTS,
is_relational_identity_text,
)
from pvr_eval.agent.source_annotation_masks import (
VERIFIED_PROTECTED_SOURCE_MASK_PROFILE,
VERIFIED_SOURCE_MASK_CAPABILITY_VERSION,
VERIFIED_SOURCE_MASK_PROFILE,
)
EXECUTABLE_PREDICATE_SCHEMA_VERSION = "pvr.executable_predicate.v1"
REGISTERED_METRIC_OPERATOR_VERSION = "pvr.contract_metric.v7"
SMALL_ANIMAL_GEOMETRY_EXECUTOR_VERSION = "pvr.small_animal_set_geometry.v5"
SOURCE_REGION_CLEARANCE_RULES = frozenset(
{
"counted_pair_removal",
"paired_zoned_instance_removal",
"colored_container_visibility_count",
"source_zone_vacancy",
"zoned_instance_absence_with_residual_test",
"small_zoned_instance_absence_with_residual_test",
}
)
SURFACE_RESIDUAL_INVENTORY_RULES = frozenset(
{
"desk_clutter_residual_count",
"tabletop_remaining_item_count",
}
)
DESTINATION_MEMBERSHIP_RULES = frozenset(
{
"named_supply_storage_coverage",
"single_object_destination_containment",
"counted_objects_destination_containment",
"relocated_object_in_air_zone",
"categorized_group_completeness",
"dual_category_grouping",
"document_group_completeness",
"paired_zone_containment",
"two_object_single_zone_containment",
"counted_container_membership",
"required_set_container_membership",
"paired_container_membership",
"remote_pair_on_table_surface",
"paired_relocation_beside_dispenser",
"same_unit_different_compartment_placement",
}
)
RELOCATION_TRANSITION_RULES = frozenset({"source_vacated_and_destination_valid"})
SOURCE_REGION_RESTORATION_RULES = frozenset({"vacated_source_with_background_fill"})
SOURCE_DISPLACEMENT_RULES = frozenset(
{
"per_instance_source_zone_displacement",
"multi_instance_source_zone_displacement",
"bird_instance_displacement_and_shoulder_clearance",
}
)
INSTANCE_CLUSTER_GROUPING_RULES = frozenset({"small_animal_cluster_component_count"})
PROTECTED_SET_EXCLUSION_RULES = frozenset({"protected_zone_exclusion_count"})
CLUSTER_SUBJECT_SEPARATION_RULES = frozenset({"cluster_protected_subject_gap"})
CROSS_IMAGE_INVENTORY_RULES = frozenset(
{
"original_inventory_visible_match",
"expected_species_count_preservation",
"no_excess_or_novel_animal_instances",
"identity_count_conservation_no_excess",
"all_input_targets_matched",
"source_instance_conservation",
"object_group_survival",
"all_named_entities_preserved",
}
)
OCR_TEXT_RULES = frozenset({"all_text_rois_preserved", "no_new_explanatory_text"})
FIXED_LOCATION_PRESERVATION_RULES = frozenset(
{
"multi_instance_strict_preservation",
"character_integrity_preservation",
"person_region_preservation",
}
)
# These region backends need a typed materializer of their own. Until that
# exists, the predicate compiler must fail closed instead of silently feeding
# an OCR label, an existing-zone name, or a shelf-grid instruction to DINO.
NON_DETECTOR_REGION_METHODS = frozenset({"ocr_layout", "existing_zone", "grid_parser", "none"})
LABELED_COLOR_ZONE_IDS = frozenset(
{"zone_a_floor", "zone_b_floor", "zone_c_floor", "water_bin", "snacks_bin", "teacher_bin"}
)
PREDICATE_OPERATION_KINDS = frozenset(
{
"object_detection",
"mask_refinement",
"instance_matching",
"source_instance_selection",
"source_state_classification",
"region_resolution",
"spatial_geometry",
"counting",
"ocr",
"image_registration",
"change_analysis",
"visual_attribute",
"pose_estimation",
"local_correspondence",
"crop_classification",
"state_parsing",
"structured_check",
"predicate_decision",
}
)
# These rules have a deterministic, case-parameterized parser path. They are
# intentionally separate from the generic state parser: a dial, parking bay,
# or flowchart checkbox is not an interchangeable coloured grid cell. The
# terminal structured checker consumes the complete reviewed decision rule
# and returns pass/partial/fail/unknown evidence for exactly one atomic check.
STRUCTURED_CHECK_RULES = frozenset(
{
# Gauge and watch.
"angular_sector_containment",
"source_corridor_vacancy",
"pivot_shaft_connectivity",
"needle_instance_preservation",
"dial_graphics_preservation",
"registered_invariant_region_preservation",
"needle_shape_integrity",
"expected_date_digit_transition",
"clockwise_hour_hand_delta",
"minute_hand_angle_invariance",
"watch_structure_relocation_violation",
"non_target_component_integrity_violation",
# Kanban board.
"source_instance_vacancy",
"all_source_instances_in_destination",
"card_text_identity_preservation",
"identity_loss_penalty",
"structural_invariant_preservation",
"unrequested_annotation_penalty",
# Visual pill organizer.
"exclusive_color_zone_containment",
"translucent_lid_depth_plausibility",
"multi_entity_integrity",
"protected_roi_exact_preservation",
"paired_text_legibility_preservation",
"count_conservation_and_structure_invariance",
# Board-game movement.
"target_cell_mask_containment",
"source_cell_vacated",
"ordered_dotted_route_match",
"two_instance_cell_preservation",
"card_content_preservation",
"grid_and_labels_intact",
"tray_and_contents_preserved",
"exact_board_instance_count",
# Parking assignment.
"assigned_vehicle_slot_predicate",
"accessible_vehicle_slot_predicate",
"any_assigned_vehicle_boundary_violation",
"audit_only_required_identity_count",
"occlusion_aware_marking_preservation",
# Laundry sorting.
"required_pair_in_target_zone",
"all_sources_vacated_no_forbidden_zone_instances",
"all_required_text_and_icons_intact",
"all_item_attributes_preserved",
"invariant_region_preserved",
# Medication organizer.
"seven_slot_exact_pair_count",
"seven_slot_exact_single_count",
"exact_container_count_with_purity",
"all_instances_intact_and_stationary",
"registered_card_preservation",
"all_required_labels_legible_and_aligned",
"allowed_type_by_row",
"invariant_background_preservation",
# Fluid network.
"fluid_level_drop",
"required_tube_network_fill",
"paired_lower_path_and_container_fill",
"paired_level_equality",
"forbidden_blue_fluid_overlap",
"multi_handle_pose_preservation",
"ordered_label_preservation",
"invariant_structure_integrity",
# Flowchart execution.
"single_checkbox_mark_state",
"two_checkbox_completion_count",
"all_forbidden_checkboxes_empty",
"flowchart_structure_preservation",
"inputs_card_integrity",
"multi_region_background_preservation",
}
)
@dataclass(frozen=True)
class PredicateValidation:
valid: bool
reasons: tuple[str, ...]
def _mapping(value: Any) -> dict[str, Any]:
return deepcopy(dict(value)) if isinstance(value, Mapping) else {}
def _list(value: Any) -> list[Any]:
return list(value) if isinstance(value, (list, tuple)) else []
def _dedupe_text(values: Sequence[Any]) -> list[str]:
result: list[str] = []
seen: set[str] = set()
for raw in values:
value = str(raw or "").strip()
if value and value not in seen:
result.append(value)
seen.add(value)
return result
def _verified_source_mask_profile(annotations: Sequence[Mapping[str, Any]]) -> str:
"""Require real segmentation whenever a reviewed bbox owns source identity."""
return VERIFIED_SOURCE_MASK_PROFILE if annotations else ""
def _subjects(params: Mapping[str, Any]) -> list[str]:
# ``object_queries`` contains the reviewed, instance-level identities used
# by the detector and by ordered subject->zone bindings. Older contracts
# may also retain short ``objects``/``labels`` strings as search aliases.
# Appending those aliases creates fictitious extra inventory members (for
# example two reviewed backpacks become four subjects), so the reviewed
# queries are authoritative whenever they are present.
object_queries = _dedupe_text(_list(params.get("object_queries")))
if object_queries:
return object_queries
values: list[Any] = []
for key in ("required_instances", "labels", "objects"):
values.extend(_list(params.get(key)))
for key in ("object", "label"):
if params.get(key):
values.append(params[key])
return _dedupe_text(values)
def _planned_regions(params: Mapping[str, Any]) -> list[dict[str, Any]]:
return [
deepcopy(dict(item))
for item in _list(params.get("planned_regions"))
if isinstance(item, Mapping)
]
def _typed_region(
region_id: str,
*,
semantic_role: str,
image_roles: Sequence[str],
queries: Sequence[str],
geometry_policy: str = "mask_or_polygon_required",
cardinality: str = "one",
) -> dict[str, Any]:
clean_queries = _dedupe_text(queries)
return {
"region_id": region_id,
"semantic_role": semantic_role,
"image_roles": list(image_roles),
"source_image": "both" if set(image_roles) == {"input", "pred"} else next(iter(image_roles), "pred"),
"proposal_method": "grounding_dino_box",
"query_or_rule": " | ".join(clean_queries),
"materializer": {
"kind": "open_vocabulary_detector",
"queries": clean_queries,
"selection_policy": "dino_first_top1_per_query",
"cardinality": cardinality,
},
"geometry_policy": geometry_policy,
}
def _region_id_matching(params: Mapping[str, Any], tokens: Sequence[str], default: str) -> str:
candidates: list[tuple[int, str]] = []
for item in _planned_regions(params):
region_id = str(item.get("region_id") or item.get("id") or "")
lowered = region_id.lower()
score = sum(token in lowered for token in tokens)
if score:
candidates.append((score, region_id))
return max(candidates, default=(0, default))[1]
def _region_roles(value: Any) -> list[str]:
text = str(value or "").lower()
if text in {"both", "input_output", "input+output"}:
return ["input", "pred"]
if text in {"input", "source", "before"}:
return ["input"]
return ["pred"]
def _generic_typed_regions(params: Mapping[str, Any]) -> list[dict[str, Any]]:
regions: list[dict[str, Any]] = []
for index, raw in enumerate(_planned_regions(params)):
region_id = str(raw.get("region_id") or raw.get("id") or f"region_{index}").strip()
if not region_id:
continue
description = str(raw.get("description") or "").strip()
id_query = region_id.replace("_", " ")
queries = [id_query]
if description and len(description.split()) <= 14:
queries.append(description)
lowered = region_id.lower()
semantic_role = "context_region"
if any(token in lowered for token in ("destination", "target", "patio", "shelf", "bin", "table_top", "tabletop", "credenza", "air_zone")):
semantic_role = "valid_destination_set"
elif any(token in lowered for token in ("source", "original", "before", "vacancy", "protected")):
semantic_role = "source_region"
elif any(token in lowered for token in ("forbidden", "floor", "exclusion")):
semantic_role = "forbidden_region"
typed = _typed_region(
region_id,
semantic_role=semantic_role,
image_roles=_region_roles(raw.get("source_image")),
queries=queries,
cardinality="one_or_more" if any(token in lowered for token in ("zones", "regions", "surfaces", "instances")) else "one",
)
for key in ("bbox", "bbox_xyxy", "polygon", "polygon_xy", "encoded_mask", "geometry_type"):
if key in raw:
typed[key] = deepcopy(raw[key])
regions.append(typed)
return regions
def _subject_specs(subjects: Sequence[str], source_anchor_query: str) -> list[dict[str, str]]:
anchor = str(source_anchor_query or "").strip()
result: list[dict[str, str]] = []
for index, identity in enumerate(subjects):
subject_id = re.sub(r"[^a-z0-9]+", "_", identity.lower()).strip("_") or f"subject_{index}"
result.append(
{
"id": subject_id,
"identity_query": identity,
"input_query": f"{identity} {anchor}".strip(),
"output_query": identity,
}
)
return result
def _subject_group_spec(
aliases: Sequence[str],
*,
expected_count: int = 1,
source_anchor_query: str = "",
group_id: str = "",
) -> dict[str, Any]:
"""Encode one semantic inventory unit separately from its query aliases."""
clean_aliases = _dedupe_text(aliases)
primary = clean_aliases[0] if clean_aliases else group_id or "subject"
subject_id = group_id or re.sub(r"[^a-z0-9]+", "_", primary.lower()).strip("_") or "subject"
anchor = str(source_anchor_query or "").strip()
return {
"id": subject_id,
"identity_query": primary,
"aliases": clean_aliases,
"input_query": f"{primary} {anchor}".strip(),
"output_query": primary,
"input_queries": [f"{alias} {anchor}".strip() for alias in clean_aliases],
"output_queries": clean_aliases,
"expected_count": max(1, int(expected_count)),
}
def _is_secondary_context_query(query: str, primary: str) -> bool:
"""Reject obvious support/anchor queries accidentally mixed with targets."""
query_tokens = set(re.findall(r"[a-z0-9]+", query.lower()))
primary_tokens = set(re.findall(r"[a-z0-9]+", primary.lower()))
target_nouns = {
"bird", "binder", "binders", "printer", "wrapper", "dumbbell", "dumbbells",
"cup", "bottle", "shaker", "container", "containers", "bag", "napkin",
"tissue", "table", "chair", "backpack", "remote", "cart", "kettle",
"microwave", "fox", "raccoon", "squirrel", "deer", "fawn",
}
primary_targets = primary_tokens & target_nouns
context_terms = {
"robot", "shoulder", "ground", "floor", "trunk", "branch", "wall",
"walkway", "dispenser", "shelf", "shelving", "tray", "table",
}
return bool(query_tokens & context_terms) and bool(primary_targets) and not bool(query_tokens & primary_targets)
def _source_subject_groups(
subjects: Sequence[str],
*,
source_rule_type: str,
expected_count: int,
raw: Mapping[str, Any],
) -> list[dict[str, Any]]:
queries = _dedupe_text(subjects)
if not queries:
return []
anchor = str(raw.get("source_anchor_query") or "")
if source_rule_type == "colored_container_visibility_count" and len(queries) >= expected_count:
return [
_subject_group_spec((query,), expected_count=1, source_anchor_query=anchor)
for query in queries[:expected_count]
]
aliases = [queries[0], *[
query for query in queries[1:]
if not _is_secondary_context_query(query, queries[0])
]]
return [
_subject_group_spec(
aliases,
expected_count=expected_count,
source_anchor_query=anchor,
group_id="source_target_inventory",
)
]
def _destination_subject_groups(
subjects: Sequence[str],
*,
source_rule_type: str,
required_count: int,
) -> list[dict[str, Any]]:
queries = _dedupe_text(subjects)
if not queries:
return []
if source_rule_type in {"single_object_destination_containment", "counted_objects_destination_containment"}:
aliases = [queries[0], *[
query for query in queries[1:]
if not _is_secondary_context_query(query, queries[0])
]]
return [
_subject_group_spec(
aliases,
expected_count=max(1, required_count),
group_id="destination_target_inventory",
)
]
if source_rule_type == "relocated_object_in_air_zone":
aliases = [queries[0], *[
query for query in queries[1:]
if not _is_secondary_context_query(query, queries[0])
]]
return [_subject_group_spec(aliases, expected_count=1, group_id="relocated_target")]
if source_rule_type in {
"remote_pair_on_table_surface",
"paired_relocation_beside_dispenser",
"same_unit_different_compartment_placement",
}:
target_queries = [queries[0], *[
query for query in queries[1:]
if not _is_secondary_context_query(query, queries[0])
]]
return [_subject_group_spec((query,), expected_count=1) for query in target_queries]
return [_subject_group_spec((query,), expected_count=1) for query in queries]
def _public_subject_groups(subjects: Sequence[Mapping[str, Any]]) -> list[dict[str, Any]]:
result: list[dict[str, Any]] = []
for item in subjects:
public = {
"id": str(item.get("id") or ""),
"aliases": _dedupe_text(item.get("aliases", [])),
"expected_count": max(1, int(item.get("expected_count") or 1)),
}
if str(item.get("spatial_selector") or ""):
public["spatial_selector"] = str(item["spatial_selector"])
result.append(public)
return result
def _positive_int(parameters: Mapping[str, Any], *keys: str) -> tuple[int, str]:
for key in keys:
value = parameters.get(key)
if isinstance(value, (int, float)) and int(value) > 0:
return int(value), key
return 0, ""
def _number(parameters: Mapping[str, Any], keys: Sequence[str], default: float) -> tuple[float, str]:
for key in keys:
value = parameters.get(key)
if isinstance(value, (int, float)):
return float(value), key
return float(default), ""
def _source_scope_conflicts(decision: Mapping[str, Any]) -> list[str]:
pass_text = str(decision.get("pass_condition") or "").lower()
partial_text = str(decision.get("partial_condition") or "").lower()
reasons: list[str] = []
if re.search(
r"(?:anywhere|entire (?:image|scene|frame)|whole (?:image|scene|frame)|全图|整张图|任何位置)",
pass_text,
):
reasons.append("source_scope_conflicts_with_global_absence_pass")
if re.search(r"(?:elsewhere|other (?:area|location)|其他位置)", partial_text) and not re.search(
r"(?:do not count|does not count|not count|不计|不算)", partial_text
):
reasons.append("source_scope_conflicts_with_elsewhere_partial")
return reasons
def _operation(
operation_id: str,
kind: str,
tool_family: str,
image_roles: Sequence[str],
*,
depends_on: Sequence[str] = (),
optional: bool = False,
parameters: Mapping[str, Any] | None = None,
produces: Sequence[str] = (),
) -> dict[str, Any]:
return {
"id": operation_id,
"kind": kind,
"tool_family": tool_family,
"image_roles": list(image_roles),
"depends_on": list(depends_on),
"optional": bool(optional),
"parameters": deepcopy(dict(parameters or {})),
"produces": list(produces),
}
def _blocked(
*,
check_id: str,
source_rule_type: str,
family: str,
subjects: Sequence[str],
reasons: Sequence[str],
provenance: Mapping[str, Any] | None = None,
status: str = "blocked_uncompiled",
) -> dict[str, Any]:
return {
"schema_version": EXECUTABLE_PREDICATE_SCHEMA_VERSION,
"check_id": check_id,
"status": status,
"family": family,
"source_rule_type": source_rule_type,
"subjects": list(subjects),
"regions": [],
"operations": [],
"state_schema": {},
"decision": {},
"parameters": {},
"unmapped_contract_parameters": [],
"reasons": list(dict.fromkeys(str(item) for item in reasons if item)),
"provenance": deepcopy(dict(provenance or {})),
}
def _compile_surface_residual_inventory(
*,
check_id: str,
source_rule_type: str,
subjects: Sequence[str],
params: Mapping[str, Any],
decision: Mapping[str, Any],
provenance: Mapping[str, Any],
) -> dict[str, Any]:
raw = _mapping(decision.get("parameters"))
if source_rule_type == "desk_clutter_residual_count":
threshold, threshold_key = _number(raw, ("desktop_containment_threshold",), 0.5)
region_id = _region_id_matching(params, ("desktop", "desk_surface", "main_desk"), "main_desktop_surface")
region_queries = ("horizontal top surface of the main desk", "main desktop surface")
normalized = {
"surface_region_id": region_id,
"surface_containment_threshold": threshold,
"support_contact_tolerance_pixels": int(raw.get("support_contact_tolerance_pixels", 8)),
"count_coherent_book_stack_as": int(raw.get("count_coherent_book_stack_as", 1)),
"exclude_animate_subjects": bool(raw.get("exclude_animate_cat", True)),
"minimum_match_confidence": float(raw.get("minimum_match_confidence", 0.55)),
"minimum_detection_confidence": float(raw.get("minimum_detector_confidence", 0.15)),
"geometry_policy": "mask_or_polygon_required",
}
consumed = {
threshold_key,
"support_contact_tolerance_pixels",
"count_coherent_book_stack_as",
"exclude_animate_cat",
"minimum_match_confidence",
"minimum_detector_confidence",
}
decision_table = {
"pass": {"residual_count": 0, "unresolved_count": 0},
"partial": {"residual_count": {"minimum": 1, "maximum": 2}, "residual_fraction": {"less_than": 0.5}, "unresolved_count": 0},
"fail": {"any": [{"residual_count": {"minimum": 3}}, {"residual_fraction": {"minimum": 0.5}}], "unresolved_count": 0},
"unknown": {"unresolved_count": {"minimum": 1}},
}
else:
threshold, threshold_key = _number(raw, ("zone_containment_threshold", "table_overlap_threshold"), 0.5)
region_id = _region_id_matching(params, ("conference_table", "tabletop", "table_surface"), "tabletop_surface")
region_queries = ("horizontal top surface of the conference table", "conference table tabletop")
normalized = {
"surface_region_id": region_id,
"surface_containment_threshold": threshold,
"minimum_detection_confidence": float(raw.get("minimum_detector_confidence", raw.get("output_detection_confidence_fail", 0.15))),
"pass_max_remaining": int(raw.get("pass_max_remaining", 0)),
"partial_min_remaining": int(raw.get("partial_min_remaining", 1)),
"partial_max_remaining": int(raw.get("partial_max_remaining", 2)),
"fail_min_remaining": int(raw.get("fail_min_remaining", int(raw.get("partial_max_remaining", 2)) + 1)),
"exclude_furniture_and_built_in_features": bool(raw.get("exclude_furniture_and_built_in_features", True)),
"geometry_policy": "mask_or_polygon_required",
}
consumed = {
threshold_key,
"minimum_detector_confidence",
"output_detection_confidence_fail",
"pass_max_remaining",
"partial_min_remaining",
"partial_max_remaining",
"fail_min_remaining",
"exclude_furniture_and_built_in_features",
"support_surface_area_ratio",
}
decision_table = {
"pass": {"residual_count": {"maximum": normalized["pass_max_remaining"]}, "unresolved_count": 0},
"partial": {"residual_count": {"minimum": normalized["partial_min_remaining"], "maximum": normalized["partial_max_remaining"]}, "unresolved_count": 0},
"fail": {"residual_count": {"minimum": normalized["fail_min_remaining"]}, "unresolved_count": 0},
"unknown": {"unresolved_count": {"minimum": 1}},
}
unmapped = sorted(set(raw) - {key for key in consumed if key})
reasons = []
if not check_id:
reasons.append("missing_check_id")
if not subjects:
reasons.append("missing_subject_queries")
if unmapped:
reasons.append("unmapped_contract_parameters")
region = _typed_region(
region_id,
semantic_role="support_surface",
image_roles=("input", "pred"),
queries=region_queries,
)
predicate = {
"schema_version": EXECUTABLE_PREDICATE_SCHEMA_VERSION,
"check_id": check_id,
"status": "executable" if not reasons else "blocked_uncompiled",
"family": "surface_residual_inventory",
"source_rule_type": source_rule_type,
"subjects": _subject_specs(subjects, ""),
"regions": [region],
"operations": [
_operation("detect_input_inventory", "object_detection", "detector", ("input",), produces=("input_inventory_boxes",)),
_operation("refine_input_inventory", "mask_refinement", "segmenter", ("input",), depends_on=("detect_input_inventory",), produces=("input_inventory_masks",)),
_operation("detect_output_inventory", "object_detection", "detector", ("pred",), produces=("output_inventory_boxes", "detector_search_coverage")),
_operation("refine_output_inventory", "mask_refinement", "segmenter", ("pred",), depends_on=("detect_output_inventory",), produces=("output_inventory_masks",)),
_operation("materialize_surface", "region_resolution", "region_proposer", ("pred",), produces=("surface_region_box",)),
_operation("refine_surface", "spatial_geometry", "segmenter", ("pred",), depends_on=("materialize_surface",), produces=("surface_region_mask",)),
_operation("match_inventory", "instance_matching", "matcher", ("input", "pred"), depends_on=("refine_input_inventory", "refine_output_inventory"), optional=True, produces=("instance_matches",)),
_operation("count_surface_residuals", "counting", "predicate_interpreter", ("input", "pred"), depends_on=("refine_output_inventory", "refine_surface"), produces=("per_instance_surface_facts", "residual_count")),
_operation("decide", "predicate_decision", "predicate_interpreter", ("input", "pred"), depends_on=("count_surface_residuals",), produces=("check_result",)),
],
"state_schema": {
"unit": "input_inventory_instance",
"states": ["on_surface", "off_surface", "not_visible_after_complete_search", "unknown"],
"facts": ["mask_containment", "support_contact", "match_confidence"],
},
"decision": decision_table,
"parameters": normalized,
"parameter_provenance": {"surface_containment_threshold": threshold_key or "default:0.5"},
"unmapped_contract_parameters": unmapped,
"reasons": reasons,
"provenance": deepcopy(dict(provenance)),
}
return predicate
def _compile_destination_membership(
*,
check_id: str,
source_rule_type: str,
subjects: Sequence[str],
params: Mapping[str, Any],
decision: Mapping[str, Any],
provenance: Mapping[str, Any],
) -> dict[str, Any]:
raw = _mapping(decision.get("parameters"))
required = _dedupe_text(raw.get("required_components", []))
if not required:
required = list(subjects)
expected_counts = raw.get("expected_counts") if isinstance(raw.get("expected_counts"), Mapping) else {}
required_count, required_count_key = _positive_int(
raw,
"required_count",
"expected_total_count",
"required_identity_count",
"expected_components",
)
if not required_count and expected_counts:
required_count, required_count_key = sum(int(value) for value in expected_counts.values()), "expected_counts"
if not required_count and raw.get("required_instances"):
required_count, required_count_key = len(_list(raw.get("required_instances"))), "required_instances"
if not required_count:
required_count = len(required)
required_count_key = "derived:subjects"
subject_groups = _destination_subject_groups(
subjects,
source_rule_type=source_rule_type,
required_count=required_count,
)
# Detector queries may also name support objects or exclusion geometry.
# The executable inventory is owned by the typed subject groups, not by
# the raw query list. Re-derive both the public roster and count after
# role filtering so a table, tray, robot, or ground region cannot become
# a fictitious required target instance.
required = [
str(group.get("identity_query") or group.get("id") or "")
for group in subject_groups
if str(group.get("identity_query") or group.get("id") or "").strip()
]
required_count = sum(max(1, int(group.get("expected_count") or 1)) for group in subject_groups)
required_count_key = "derived:typed_subject_groups"
threshold, threshold_key = _number(
raw,
(
"zone_containment_threshold",
"predominant_visible_mask_containment_min",
"minimum_mask_containment",
"minimum_destination_containment",
"pass_min_containment",
"credenza_containment_threshold",
"minimum_air_zone_containment",
"pass_patio_footprint_fraction",
"pass_patio_footprint_fraction_per_chair",
),
0.5,
)
partial_threshold, partial_key = _number(
raw,
("minimum_partial_intersection_fraction", "partial_min_containment"),
min(0.25, threshold),
)
minimum_confidence, minimum_confidence_key = _number(
raw,
(
"minimum_instance_confidence",
"minimum_bird_detection_confidence",
"instance_match_min_score",
"minimum_identity_similarity",
"minimum_match_confidence",
),
0.45,
)
identity_required = source_rule_type in {
"named_supply_storage_coverage",
"required_set_container_membership",
"paired_relocation_beside_dispenser",
"same_unit_different_compartment_placement",
"relocated_object_in_air_zone",
} or bool(raw.get("match_to_input_instances") or raw.get("visible_match_required"))
explicit_white_furniture = source_rule_type in {
"single_object_destination_containment",
"counted_objects_destination_containment",
} and any(
"white" in str(subject).lower()
and any(noun in str(subject).lower() for noun in ("chair", "table"))
for subject in subjects
)
classification_labels: list[str] = []
if explicit_white_furniture:
classification_labels.extend(str(subject) for subject in subjects)
has_chair_subject = any("chair" in str(subject).lower() for subject in subjects)
if has_chair_subject:
classification_labels.append("brown wooden dining chair")
classification_labels.append("white round patio table")
elif any("table" in str(subject).lower() for subject in subjects):
classification_labels.append("brown wooden outdoor table")
classification_labels.extend(("white patio chair", "brown wooden dining chair"))
classification_labels.append("other object")
classification_proposal_queries: list[str] = []
if explicit_white_furniture:
if any("chair" in str(subject).lower() for subject in subjects):
classification_proposal_queries = ["chair", "outdoor chair"]
else:
classification_proposal_queries = ["table", "outdoor table"]
normalized = {
"required_components": required,
"required_count": required_count,
"subject_groups": _public_subject_groups(subject_groups),
"zone_containment_threshold": threshold,
"partial_containment_threshold": partial_threshold,
"support_contact_tolerance_pixels": int(raw.get("support_contact_tolerance_pixels", 8)),
"visible_match_required": identity_required,
"minimum_match_confidence": minimum_confidence,
"minimum_detection_confidence": minimum_confidence,
"require_distinct_instances": bool(
raw.get("require_distinct_instances", raw.get("require_distinct_backpack_instances", True))
),
"deduplicate_iou_threshold": float(raw.get("deduplicate_iou_threshold", 0.6)),
"maximum_forbidden_support_points": int(raw.get("maximum_grass_support_points_for_pass", 0)),
"geometry_policy": "per_zone_mask_or_polygon_required",
"valid_zone_aggregation": "any_member_zone",
"forbidden_zone_policy": "declared_forbidden_regions",
"source_rule_semantics": source_rule_type,
"center_or_support_point_required": bool(raw.get("center_or_support_point_must_be_inside")),
"accept_center_inside_when_occluded": bool(
raw.get("accept_center_inside_bin_interior_when_lower_object_is_occluded_by_bin_wall")
or raw.get("accept_center_inside_bin_interior_when_occluded_by_bin_wall")
),
"zone_boundary_tolerance_pixels": int(raw.get("zone_boundary_tolerance_px", 0)),
"require_crop_classification": explicit_white_furniture,
"classification_labels": _dedupe_text(classification_labels),
"classification_proposal_queries": classification_proposal_queries,
# Proposal recall and final instance acceptance are separate gates.
# A moderate detector proposal can become reliable after closed-set
# classification and destination geometry; filtering it at the final
# instance-confidence threshold would discard the evidence too early.
"classification_proposal_minimum_score": 0.15,
"classified_candidate_minimum_score": 0.15,
"classification_use_segmenter_proposals": explicit_white_furniture,
"classification_proposal_zone_ids": [],
"classification_segmenter_min_area_fraction": 0.00008,
"classification_segmenter_max_area_fraction": 0.06,
"classification_segmenter_max_proposals": 128,
"classification_minimum_margin": 0.025,
"classification_minimum_probability": 0.28,
}
supported_by_rule = {
"named_supply_storage_coverage": {
"required_components", "zone_containment_threshold", "support_contact_tolerance_pixels",
"visible_match_required", "minimum_match_confidence",
},
"single_object_destination_containment": {
"required_count", "pass_patio_footprint_fraction", "minimum_partial_intersection_fraction",
"maximum_grass_support_points_for_pass", "minimum_instance_confidence",
},
"counted_objects_destination_containment": {
"required_count", "pass_patio_footprint_fraction_per_chair",
"maximum_grass_support_points_for_pass", "minimum_instance_confidence",
"deduplicate_iou_threshold",
},
"paired_zone_containment": {
"center_or_support_point_must_be_inside", "predominant_visible_mask_containment_min",
"require_distinct_backpack_instances", "zone_boundary_tolerance_px",
},
"two_object_single_zone_containment": {
"center_or_support_point_must_be_inside", "predominant_visible_mask_containment_min",
"require_distinct_instances", "zone_boundary_tolerance_px",
},
"counted_container_membership": {
"accept_center_inside_bin_interior_when_lower_object_is_occluded_by_bin_wall",
"expected_total_count", "predominant_visible_mask_containment_min", "require_no_duplicate_assignment",
},
"required_set_container_membership": {
"accept_center_inside_bin_interior_when_occluded_by_bin_wall", "match_to_input_instances",
"predominant_visible_mask_containment_min", "require_distinct_instances", "required_identity_count",
},
"paired_container_membership": {
"accept_center_inside_bin_interior_when_occluded_by_bin_wall",
"predominant_visible_mask_containment_min", "require_distinct_appliance_instances",
},
}
consumed = supported_by_rule.get(source_rule_type, set())
unmapped = sorted(set(raw) - {key for key in consumed if key})
reasons = []
if not check_id:
reasons.append("missing_check_id")
if not subjects:
reasons.append("missing_subject_queries")
if not required:
reasons.append("required_components_not_compiled")
if unmapped:
reasons.append("unmapped_contract_parameters")
regions: list[dict[str, Any]] = []
instance_tokens = ("instance", "instances", "source", "candidate", "relocated_binders", "tray")
forbidden_tokens = ("floor", "grass", "walkway", "forbidden", "negative")
valid_tokens = (
"destination", "target", "patio", "storage", "shelf", "ledge", "window",
"credenza", "airborne", "air_zone", "table_top", "tabletop", "coffee_table_top",
"corner", "bin", "zone_a", "zone_b", "zone_c", "compartment",
)
for index, source_region in enumerate(_planned_regions(params)):
region_id = str(source_region.get("region_id") or source_region.get("id") or f"region_{index}")
lowered = region_id.lower()
if any(token in lowered for token in instance_tokens):
continue
if region_id in LABELED_COLOR_ZONE_IDS:
semantic_role = "valid_destination_set"
elif any(token in lowered for token in forbidden_tokens):
semantic_role = "forbidden_destination"
elif any(token in lowered for token in valid_tokens):
semantic_role = "valid_destination_set"
else:
continue
method = str(source_region.get("proposal_method") or "grounding_dino_box").lower()
has_explicit_geometry = any(
key in source_region for key in ("bbox", "bbox_xyxy", "polygon", "polygon_xy", "encoded_mask")
)
if method in {"ocr_layout", "existing_zone"} and region_id in LABELED_COLOR_ZONE_IDS:
region = _typed_region(
region_id,
semantic_role=semantic_role,
image_roles=("pred",),
queries=(),
)
region["proposal_method"] = method
region["materializer"] = {
"kind": "input_ocr_color_zone",
"region_id": region_id,
"backend": "input_ocr_hsv_connected_component_v1",
}
regions.append(region)
continue
if method in NON_DETECTOR_REGION_METHODS and not has_explicit_geometry:
reasons.append(f"region_materializer_not_implemented:{region_id}:{method}")
continue
authored_detector_queries = _dedupe_text(
_list(source_region.get("detector_queries"))
+ _list(source_region.get("detector_query"))
)
if authored_detector_queries:
region_queries = tuple(authored_detector_queries)
elif "patio" in lowered:
region_queries = ("stone paved patio",)
elif "valid_storage" in lowered:
region_queries = ("window ledge", "cabinet shelf", "visible cabinet compartment")
elif "floor" in lowered:
region_queries = ("room floor",)
elif "airborne" in lowered or "air_zone" in lowered:
region_queries = ("open sky area",)
elif "coffee_table_top" in lowered:
region_queries = ("horizontal top surface of the coffee table",)
elif "credenza" in lowered:
region_queries = ("wooden credenza",)
else:
region_queries = (region_id.replace("_", " "),)
# Preserve an explicitly reviewed cross-image scene anchor. Stable
# destination supports such as a patio are part of the scene layout:
# the input proposal constrains the output proposal, while the object
# itself is still detected and scored only in the output. The old
# compiler forced every destination region to ``pred`` and silently
# discarded ``source_image: both`` from the contract.
region_roles = (
tuple(_region_roles(source_region.get("source_image")))
if "patio" in lowered
else ("pred",)
)
region = _typed_region(
region_id,
semantic_role=semantic_role,
image_roles=region_roles,
queries=region_queries,
cardinality="one_or_more" if source_rule_type == "named_supply_storage_coverage" and semantic_role == "valid_destination_set" else "one",
)
# Once this compiler has lowered a legacy VLM proposal to an explicit
# detector query, runtime provenance must name the tool that is
# actually called. Keep the reviewed legacy method separately instead
# of claiming that a VLM produced a DINO box.
region["source_proposal_method"] = method
region["proposal_method"] = (
"grounding_dino_box" if method == "vlm_region_box" else method
)
for key in ("bbox", "bbox_xyxy", "polygon", "polygon_xy", "encoded_mask", "geometry_type"):
if key in source_region:
region[key] = deepcopy(source_region[key])
regions.append(region)
if source_rule_type == "named_supply_storage_coverage":
# The reviewed question explicitly forbids leaving supplies on the
# central desk. This independent mask is deliberately separate from
# the storage-set masks; never replace either with a union bbox.
regions.append(
_typed_region(
"main_desktop_surface",
semantic_role="forbidden_destination",
image_roles=("pred",),
queries=("horizontal top surface of the main desk",),
)
)
if not any(item.get("semantic_role") == "valid_destination_set" for item in regions):
reasons.append("valid_destination_region_not_compiled")
normalized["valid_zone_ids"] = [
str(item["region_id"])
for item in regions
if item.get("semantic_role") == "valid_destination_set"
]
if explicit_white_furniture:
normalized["classification_proposal_zone_ids"] = list(normalized["valid_zone_ids"])
normalized["forbidden_zone_ids"] = [
str(item["region_id"])
for item in regions
if item.get("semantic_role") == "forbidden_destination"
]
normalized["subject_zone_map"] = (
{
str(group.get("identity_query") or group.get("id") or ""): normalized["valid_zone_ids"][index]
for index, group in enumerate(subject_groups)
}
if source_rule_type == "paired_zone_containment"
and len(subject_groups) == len(normalized["valid_zone_ids"])
else {}
)
if source_rule_type == "paired_zone_containment" and not normalized["subject_zone_map"]:
reasons.append("subject_destination_zone_mapping_not_compiled")
destination_region_roles = tuple(dict.fromkeys(
role
for region in regions
for role in region.get("image_roles", [])
)) or ("pred",)
operations = [
_operation("detect_output_components", "object_detection", "detector", ("pred",), produces=("output_component_boxes",)),
_operation("refine_output_components", "mask_refinement", "segmenter", ("pred",), depends_on=("detect_output_components",), produces=("output_component_masks",)),
_operation("materialize_destination_zones", "region_resolution", "region_proposer", destination_region_roles, produces=("destination_zone_boxes",)),
_operation("refine_destination_zones", "spatial_geometry", "segmenter", destination_region_roles, depends_on=("materialize_destination_zones",), produces=("destination_zone_masks",)),
]
if explicit_white_furniture:
operations.insert(
2,
_operation(
"classify_output_components",
"crop_classification",
"classifier",
("pred",),
depends_on=("refine_output_components",),
parameters={"closed_set": classification_labels},
produces=("output_component_classification",),
),
)
classification_dependencies = ["refine_output_components", "refine_destination_zones"]
if explicit_white_furniture:
classification_dependencies.insert(1, "classify_output_components")
if identity_required:
operations[0:0] = [
_operation("detect_input_components", "object_detection", "detector", ("input",), produces=("input_component_boxes",)),
_operation("refine_input_components", "mask_refinement", "segmenter", ("input",), depends_on=("detect_input_components",), produces=("input_component_masks",)),
]
operations.append(
_operation("match_components", "instance_matching", "matcher", ("input", "pred"), depends_on=("refine_input_components", "refine_output_components"), produces=("component_matches",))
)
classification_dependencies.insert(0, "match_components")
operations.extend(
[
_operation("classify_destination_membership", "counting", "predicate_interpreter", ("input", "pred"), depends_on=classification_dependencies, produces=("per_component_destination_facts",)),
_operation("decide", "predicate_decision", "predicate_interpreter", ("input", "pred"), depends_on=("classify_destination_membership",), produces=("check_result",)),
]
)
predicate = {
"schema_version": EXECUTABLE_PREDICATE_SCHEMA_VERSION,
"check_id": check_id,
"status": "executable" if not reasons else "blocked_uncompiled",
"family": "destination_membership",
"source_rule_type": source_rule_type,
"subjects": subject_groups,
"regions": regions,
"operations": operations,
"state_schema": {
"unit": "required_component",
"states": ["stored", "wrong_zone", "visible_unstored", "missing", "unknown"],
"facts": ["identity_match", "valid_zone_mask_containment", "forbidden_zone_mask_containment", "support_contact"],
},
"decision": {
"pass": {
"stored_count": required_count,
"partial_count": 0,
"wrong_zone_count": 0,
"unresolved_count": 0,
},
"partial": {
"any": [
{
"stored_count": {"minimum": 1, "maximum": max(1, required_count - 1)},
"unresolved_count": 0,
},
{"partial_count": {"minimum": 1}, "unresolved_count": 0},
]
},
"fail": {"stored_count": 0, "partial_count": 0, "unresolved_count": 0},
"unknown": {"unresolved_count": {"minimum": 1}},
},
"parameters": normalized,
"parameter_provenance": {
"required_count": required_count_key,
"zone_containment_threshold": threshold_key or "default:0.5",
"partial_containment_threshold": partial_key or "default:min(0.25, pass)",
"minimum_match_confidence": minimum_confidence_key or "default:0.45",
},
"unmapped_contract_parameters": unmapped,
"reasons": reasons,
"provenance": deepcopy(dict(provenance)),
}
return predicate
def _compile_relocation_transition(
*,
check_id: str,
source_rule_type: str,
subjects: Sequence[str],
params: Mapping[str, Any],
decision: Mapping[str, Any],
provenance: Mapping[str, Any],
) -> dict[str, Any]:
raw = _mapping(decision.get("parameters"))
source_overlap, source_key = _number(raw, ("source_residual_overlap_max",), 0.15)
destination_threshold, destination_key = _number(raw, ("destination_containment_threshold",), 0.4)
normalized = {
"source_residual_overlap_max": source_overlap,
"destination_containment_threshold": destination_threshold,
"desk_edge_band_fraction": float(raw.get("desk_edge_band_fraction", 0.12)),
"minimum_match_confidence": float(raw.get("minimum_match_confidence", 0.55)),
"require_complete_negative_search_for_missing": True,
"geometry_policy": "per_zone_mask_or_polygon_required",
}
consumed = {source_key, destination_key, "desk_edge_band_fraction", "minimum_match_confidence"}
unmapped = sorted(set(raw) - {key for key in consumed if key})
reasons = []
if not check_id:
reasons.append("missing_check_id")
if not subjects:
reasons.append("missing_subject_queries")
if unmapped:
reasons.append("unmapped_contract_parameters")
destination_id = _region_id_matching(params, ("valid_destination", "destination"), "valid_destinations")
desk_id = _region_id_matching(params, ("desktop", "desk_surface", "main_desk"), "main_desktop_surface")
regions = [
_typed_region(
destination_id,
semantic_role="valid_destination_set",
image_roles=("pred",),
queries=("window ledge", "cabinet shelf", "visible cabinet compartment", "wall leaning display location"),
cardinality="one_or_more",
),
_typed_region(
desk_id,
semantic_role="forbidden_destination",
image_roles=("input", "pred"),
queries=("horizontal top surface of the main desk",),
),
]
return {
"schema_version": EXECUTABLE_PREDICATE_SCHEMA_VERSION,
"check_id": check_id,
"status": "executable" if not reasons else "blocked_uncompiled",
"family": "relocation_transition",
"source_rule_type": source_rule_type,
"subjects": _subject_specs(subjects, ""),
"regions": regions,
"operations": [
_operation("detect_input_subject", "object_detection", "detector", ("input",), produces=("input_subject_boxes",)),
_operation("refine_input_subject", "mask_refinement", "segmenter", ("input",), depends_on=("detect_input_subject",), produces=("input_subject_masks", "source_footprints")),
_operation("detect_output_subject", "object_detection", "detector", ("pred",), produces=("output_subject_boxes", "detector_search_coverage")),
_operation("refine_output_subject", "mask_refinement", "segmenter", ("pred",), depends_on=("detect_output_subject",), produces=("output_subject_masks",)),
_operation("materialize_destination_zones", "region_resolution", "region_proposer", ("pred",), produces=("destination_zone_boxes",)),
_operation("refine_destination_zones", "spatial_geometry", "segmenter", ("pred",), depends_on=("materialize_destination_zones",), produces=("destination_zone_masks",)),
_operation("match_subject", "instance_matching", "matcher", ("input", "pred"), depends_on=("refine_input_subject", "refine_output_subject"), produces=("subject_match",)),
_operation("classify_transition", "source_state_classification", "predicate_interpreter", ("input", "pred"), depends_on=("match_subject", "refine_destination_zones"), produces=("source_vacancy_fact", "destination_fact", "visibility_fact")),
_operation("decide", "predicate_decision", "predicate_interpreter", ("input", "pred"), depends_on=("classify_transition",), produces=("check_result",)),
],
"state_schema": {
"unit": "relocated_subject",
"states": ["validly_relocated", "desk_edge_ambiguous", "not_moved", "missing", "unknown"],
"facts": ["source_overlap_against_transferred_input_target_footprint", "destination_mask_containment", "desk_mask_containment", "identity_match", "negative_search_complete"],
},
"decision": {
"pass": {"source_vacant": 1, "destination_valid": 1, "visible": 1, "unresolved_count": 0},
"partial": {"source_vacant": 1, "destination_valid": 0, "desk_edge_ambiguous": 1, "visible": 1, "unresolved_count": 0},
"fail": {"any": [{"source_vacant": 0}, {"visible": 0}], "unresolved_count": 0},
"unknown": {"unresolved_count": {"minimum": 1}},
},
"parameters": normalized,
"parameter_provenance": {
"source_residual_overlap_max": source_key or "default:0.15",
"destination_containment_threshold": destination_key or "default:0.4",
},
"unmapped_contract_parameters": unmapped,
"reasons": reasons,
"provenance": deepcopy(dict(provenance)),
}
def _inventory_alias_tokens(value: Any) -> set[str]:
"""Return conservative tokens for mapping fixed inventory ids to queries."""
return {
token[:-1] if token.endswith("s") and not token.endswith("ss") and len(token) > 3 else token
for token in re.findall(r"[a-z0-9]+", str(value or "").replace("_", " ").lower())
if token not in {"a", "an", "and", "the", "with"}
}
def _inventory_matching_aliases(identity: Any, subjects: Sequence[str]) -> list[str]:
"""Match aliases without merging objects that share only color/type words."""
identity_tokens = _inventory_alias_tokens(identity)
if not identity_tokens:
return []
matches: list[str] = []
for subject in subjects:
subject_tokens = _inventory_alias_tokens(subject)
overlap = len(identity_tokens & subject_tokens)
if identity_tokens.issubset(subject_tokens) or (
len(identity_tokens) >= 3
and overlap / len(identity_tokens) >= 0.75
):
matches.append(subject)
return matches
def _compile_cross_image_inventory(
*,
check_id: str,
source_rule_type: str,
subjects: Sequence[str],
decision: Mapping[str, Any],
provenance: Mapping[str, Any],
) -> dict[str, Any]:
"""Compile identity/count conservation without claiming pose integrity."""
raw = _mapping(decision.get("parameters"))
expected_counts = raw.get("expected_counts") if isinstance(raw.get("expected_counts"), Mapping) else {}
maximum_counts = raw.get("maximum_counts") if isinstance(raw.get("maximum_counts"), Mapping) else {}
trusted_output_count_mode = ""
if source_rule_type == "identity_count_conservation_no_excess":
maximum_counts = expected_counts
trusted_output_count_mode = "maximum"
elif source_rule_type == "all_input_targets_matched":
expected_counts = {
subject: (
int(raw.get("expected_tumbler_count") or 2)
if "tumbler" in subject.lower()
else 1
)
for subject in subjects
}
trusted_output_count_mode = "minimum"
expected_count = sum(int(value) for value in expected_counts.values()) if expected_counts else 0
if source_rule_type == "all_named_entities_preserved":
named_entities = _dedupe_text(_list(raw.get("required_entities")))
if named_entities:
subjects = named_entities
expected_count = len(named_entities)
minimum_matches = int(raw.get("minimum_matching_instances", 0) or 0)
match_threshold, match_key = _number(
raw,
(
"minimum_match_confidence",
"minimum_credible_match_score",
"minimum_instance_match_score",
"minimum_match_score",
),
0.55,
)
coverage = float(raw.get("required_match_coverage", 1.0))
minimum_area_ratio = float(
raw.get("minimum_matched_area_ratio", raw.get("minimum_visible_fraction", 0.0))
)
supported_by_rule = {
"original_inventory_visible_match": {
"count_book_stack_as_group", "minimum_match_confidence", "one_to_one_assignment",
"require_visible_output_match", "whole_image_search",
},
"expected_species_count_preservation": {
"expected_counts", "low_confidence_count_requires_vlm_audit", "minimum_match_confidence",
},
"no_excess_or_novel_animal_instances": {
"maximum_counts", "allowed_species", "candidate_detection_confidence",
"validation_confidence", "unknown_animal_candidates_require_vlm_audit",
},
"identity_count_conservation_no_excess": {
"expected_counts", "minimum_distinct_mask_iou_for_separate_instances",
"minimum_duplicate_identity_similarity", "confirm_excess_with_ocr_color_or_vlm_when_available",
},
"all_input_targets_matched": {
"required_match_coverage", "minimum_identity_similarity", "allow_pose_and_scale_change",
"allow_partial_occlusion_with_supporting_attributes", "expected_tumbler_count",
"prefer_credenza_matches",
},
"source_instance_conservation": {
"allow_occlusion", "allow_position_change", "minimum_credible_match_score", "one_to_one_matching",
},
"object_group_survival": {
"full_image_search", "minimum_instance_match_score", "minimum_matched_area_ratio",
"minimum_matching_instances", "repeated_group_identity_profile",
},
"all_named_entities_preserved": {
"required_entities", "minimum_match_score", "minimum_visible_fraction",
"allow_minor_occlusion", "require_category_and_shape_consistency",
},
}
unmapped = sorted(set(raw) - supported_by_rule.get(source_rule_type, set()))
reasons: list[str] = []
if not check_id:
reasons.append("missing_check_id")
if not subjects:
reasons.append("missing_subject_queries")
if source_rule_type == "expected_species_count_preservation" and not expected_counts:
reasons.append("expected_species_counts_not_compiled")
if source_rule_type == "no_excess_or_novel_animal_instances" and not maximum_counts:
reasons.append("maximum_species_counts_not_compiled")
if trusted_output_count_mode and not (expected_counts or maximum_counts):
reasons.append("trusted_inventory_counts_not_compiled")
if unmapped:
reasons.append("unmapped_contract_parameters")
species_count_mode = source_rule_type == "expected_species_count_preservation"
no_excess_species_mode = source_rule_type == "no_excess_or_novel_animal_instances"
output_species_mode = species_count_mode or no_excess_species_mode or bool(trusted_output_count_mode)
inventory_counts = expected_counts if species_count_mode else maximum_counts
if trusted_output_count_mode == "minimum":
inventory_counts = expected_counts
if output_species_mode:
subject_groups = []
for species, count in inventory_counts.items():
species_text = str(species).replace("_", " ").strip()
matching_aliases = _inventory_matching_aliases(species, subjects)
subject_groups.append(
_subject_group_spec(
matching_aliases or (species_text,),
expected_count=int(count),
group_id=re.sub(r"[^a-z0-9]+", "_", str(species).lower()).strip("_"),
)
)
else:
subject_groups = [
_subject_group_spec((subject,), expected_count=1)
for subject in subjects
]
requested_group_profile = str(raw.get("repeated_group_identity_profile") or "")
binder_group_queries = bool(subjects) and all(
any(token in str(subject).lower() for token in ("binder", "file folder"))
for subject in subjects
)
repeated_group_profile = ""
if source_rule_type == "object_group_survival":
if requested_group_profile:
if requested_group_profile == REPEATED_COMPONENT_GROUP_IDENTITY_PROFILE:
repeated_group_profile = requested_group_profile
else:
reasons.append("repeated_group_identity_profile_unsupported")
elif binder_group_queries:
repeated_group_profile = REPEATED_COMPONENT_GROUP_IDENTITY_PROFILE
if repeated_group_profile:
# The detector phrases are aliases for one physical repeated-item
# group, not three independent binder rows. Component cardinality
# is certified later from image structure.
subject_groups = [
_subject_group_spec(
tuple(subjects), expected_count=1,
group_id="repeated_component_group",
)
]
expected_count = 1
if species_count_mode or no_excess_species_mode:
classification_proposal_queries = _dedupe_text(
["animal", "wildlife"]
+ list(subjects)
+ [str(species).replace("_", " ") for species in inventory_counts]
)
elif trusted_output_count_mode:
# Fixed object inventories carry identity-bearing attributes such as
# colour, printed title, or assembly membership. Adding generic
# closed-set labels here causes the detector query canonicalizer to
# replace those reviewed phrases with shorter ambiguous queries.
classification_proposal_queries = _dedupe_text(list(subjects))
else:
classification_proposal_queries = []
normalized = {
"expected_count": expected_count,
"expected_counts": dict(expected_counts),
"maximum_counts": dict(maximum_counts),
"subject_groups": _public_subject_groups(subject_groups),
"minimum_detection_confidence": float(raw.get("candidate_detection_confidence", 0.15)),
"minimum_match_confidence": match_threshold,
"required_match_coverage": coverage,
"minimum_matching_instances": minimum_matches,
"minimum_matched_area_ratio": minimum_area_ratio,
"one_to_one_assignment": bool(raw.get("one_to_one_assignment", raw.get("one_to_one_matching", True))),
"full_frame_search": bool(raw.get("whole_image_search", raw.get("full_image_search", True))),
"require_tiled_search_for_negative": True,
"allow_position_change": bool(raw.get("allow_position_change", True)),
"allow_minor_occlusion": bool(raw.get("allow_minor_occlusion", False)),
"require_category_and_shape_consistency": bool(
raw.get("require_category_and_shape_consistency", False)
),
"minimum_shape_similarity": (
0.5 if raw.get("require_category_and_shape_consistency", False) else 0.0
),
"visible_output_match_required": bool(raw.get("require_visible_output_match", True)),
"enforce_no_excess": no_excess_species_mode,
"trusted_output_count_mode": trusted_output_count_mode,
"low_confidence_policy": "unknown",
"require_crop_classification": output_species_mode,
"classification_labels": (
[str(species).replace("_", " ") for species in inventory_counts]
+ (
["other animal", "not an animal"]
if species_count_mode or no_excess_species_mode
else ["other object"]
)
if output_species_mode
else []
),
"classification_proposal_queries": classification_proposal_queries,
"classification_use_segmenter_proposals": species_count_mode,
"classification_proposal_zone_ids": [],
"classification_segmenter_min_area_fraction": 0.00005,
"classification_segmenter_max_area_fraction": 0.08,
"classification_segmenter_max_proposals": 128,
"classification_minimum_margin": 0.06,
"classification_minimum_probability": 0.25,
"minimum_novel_classification_probability": float(raw.get("validation_confidence", 0.55)),
"unknown_animal_policy": (
"unknown_without_vlm"
if raw.get("unknown_animal_candidates_require_vlm_audit", False)
else "fail_when_confident"
),
"inventory_distractor_labels": (
["other animal", "not an animal"]
if species_count_mode or no_excess_species_mode
else ["other object"]
),
"group_alias_policy": (
"repeated_component_group_as_one"
if repeated_group_profile
else "book_stack_as_one"
if raw.get("count_book_stack_as_group")
else "per_instance"
),
"repeated_group_identity_profile": repeated_group_profile,
"repeated_group_identity_executor_version": (
REPEATED_COMPONENT_GROUP_IDENTITY_EXECUTOR_VERSION
if repeated_group_profile else ""
),
"minimum_repeated_component_count": minimum_matches,
"maximum_repeated_component_count": 8,
}
return {
"schema_version": EXECUTABLE_PREDICATE_SCHEMA_VERSION,
"check_id": check_id,
"status": "executable" if not reasons else "blocked_uncompiled",
"family": "cross_image_inventory_integrity",
"source_rule_type": source_rule_type,
"subjects": subject_groups,
"regions": [],
"operations": ([
_operation("detect_output_inventory", "object_detection", "detector", ("pred",), parameters={"search_scopes": ["full_frame", "tiled"]}, produces=("output_inventory_boxes", "detector_search_coverage")),
_operation("refine_output_inventory", "mask_refinement", "segmenter", ("pred",), depends_on=("detect_output_inventory",), produces=("output_inventory_masks",)),
_operation("classify_output_inventory", "crop_classification", "classifier", ("pred",), depends_on=("refine_output_inventory",), parameters={"closed_set": normalized["classification_labels"]}, produces=("output_inventory_classification",)),
_operation("classify_inventory_integrity", "counting", "predicate_interpreter", ("pred",), depends_on=("classify_output_inventory",), produces=("species_inventory_facts",)),
_operation("decide", "predicate_decision", "predicate_interpreter", ("pred",), depends_on=("classify_inventory_integrity",), produces=("check_result",)),
] if output_species_mode else [
_operation("detect_input_inventory", "object_detection", "detector", ("input",), produces=("input_inventory_boxes",)),
_operation("refine_input_inventory", "mask_refinement", "segmenter", ("input",), depends_on=("detect_input_inventory",), produces=("input_inventory_masks",)),
_operation("detect_output_inventory", "object_detection", "detector", ("pred",), parameters={"search_scopes": ["full_frame", "tiled"]}, produces=("output_inventory_boxes", "detector_search_coverage")),
_operation("refine_output_inventory", "mask_refinement", "segmenter", ("pred",), depends_on=("detect_output_inventory",), produces=("output_inventory_masks",)),
_operation("match_inventory", "instance_matching", "matcher", ("input", "pred"), depends_on=("refine_input_inventory", "refine_output_inventory"), produces=("inventory_matches",)),
_operation("classify_inventory_integrity", "counting", "predicate_interpreter", ("input", "pred"), depends_on=("match_inventory",), produces=("inventory_integrity_facts",)),
_operation("decide", "predicate_decision", "predicate_interpreter", ("input", "pred"), depends_on=("classify_inventory_integrity",), produces=("check_result",)),
]),
"state_schema": (
{
"unit": "expected_species_inventory",
"states": ["count_preserved", "count_decreased_after_complete_search", "unknown"],
"facts": ["expected_count", "deduplicated_output_count", "full_frame_and_tiled_search_coverage"],
}
if output_species_mode
else {
"unit": "input_inventory_instance",
"states": ["preserved", "missing_after_complete_search", "excess", "unknown"],
"facts": ["identity_match", "one_to_one_assignment", "matched_area_ratio", "search_coverage"],
}
),
"decision": {
"pass": {"missing_count": 0, "excess_count": 0, "unresolved_count": 0},
"fail": (
{"excess_count": {"minimum": 1}}
if no_excess_species_mode or trusted_output_count_mode == "maximum"
else {"missing_count": {"minimum": 1}, "unresolved_count": 0}
),
"unknown": (
{"unresolved_count": {"minimum": 1}, "excess_count": 0}
if no_excess_species_mode or trusted_output_count_mode == "maximum"
else {"unresolved_count": {"minimum": 1}}
),
},
"parameters": normalized,
"parameter_provenance": {
"minimum_match_confidence": match_key or "default:0.55",
"expected_count": (
"expected_counts" if expected_counts
else "maximum_counts" if maximum_counts
else "required_entities" if source_rule_type == "all_named_entities_preserved"
else "input_inventory_runtime"
),
"low_confidence_policy": "contract_vlm_request_mapped_to_zero_vlm_unknown",
"repeated_group_identity_profile": (
"decision_rule.parameters.repeated_group_identity_profile"
if requested_group_profile
else "deterministic_subject_profile:binder_or_file_folder_group"
if repeated_group_profile
else "not_applicable"
),
},
"unmapped_contract_parameters": unmapped,
"reasons": reasons,
"provenance": deepcopy(dict(provenance)),
}
def _compile_fixed_location_preservation(
*,
check_id: str,
source_rule_type: str,
subjects: Sequence[str],
decision: Mapping[str, Any],
provenance: Mapping[str, Any],
) -> dict[str, Any]:
"""Compile preservation checks whose complete semantics are measurable."""
raw = _mapping(decision.get("parameters"))
supported_by_rule = {
"multi_instance_strict_preservation": {
"expected_count", "required_instances", "maximum_registered_centroid_shift_pixels",
"minimum_mask_iou", "minimum_masked_ssim", "maximum_new_occlusion_fraction",
"source_instance_annotations",
},
"character_integrity_preservation": {
"minimum_identity_similarity", "minimum_visible_mask_fraction",
"maximum_unexplained_silhouette_change", "hat_required",
},
"person_region_preservation": {
"minimum_mask_iou", "maximum_changed_area_ratio",
"major_body_region_required", "blur_aware_comparison",
},
}
unmapped = sorted(set(raw) - supported_by_rule.get(source_rule_type, set()))
reasons: list[str] = []
if not check_id:
reasons.append("missing_check_id")
if not subjects:
reasons.append("missing_subject_queries")
if unmapped:
reasons.append("unmapped_contract_parameters")
required_instances = _dedupe_text(_list(raw.get("required_instances")))
expected_count = int(raw.get("expected_count") or 0) or (
1
if source_rule_type in {"character_integrity_preservation", "person_region_preservation"}
else len(required_instances) or len(subjects)
)
minimum_shape = (
1.0 - float(raw["maximum_unexplained_silhouette_change"])
if "maximum_unexplained_silhouette_change" in raw else 0.0
)
minimum_visible = float(raw.get("minimum_visible_mask_fraction", 0.0))
if "maximum_new_occlusion_fraction" in raw:
minimum_visible = max(minimum_visible, 1.0 - float(raw["maximum_new_occlusion_fraction"]))
source_annotations = [
deepcopy(dict(item))
for item in _list(raw.get("source_instance_annotations"))
if isinstance(item, Mapping)
]
annotation_ids: set[str] = set()
for index, item in enumerate(source_annotations):
instance_id = str(item.get("instance_id") or "").strip()
group_id = str(item.get("group_id") or "").strip()
query_text = str(item.get("query_text") or item.get("label") or "").strip()
bbox = item.get("bbox_xyxy")
provenance_value = str(item.get("provenance") or "").strip()
if not instance_id or instance_id in annotation_ids:
reasons.append(f"source_annotation_{index}_instance_id_invalid")
annotation_ids.add(instance_id)
if not group_id:
reasons.append(f"source_annotation_{index}_group_missing")
if not query_text:
reasons.append(f"source_annotation_{index}_query_missing")
else:
# Fixed-location closed-set labels are identity phrases rather
# than coarse detector classes. Keep that matcher-only class
# explicit so a reviewed ``running_child`` roster slot and the
# classifier label ``running child on grass`` are comparable.
item["matching_class"] = query_text
if provenance_value != "human_verified_fixed_input_v1":
reasons.append(f"source_annotation_{index}_provenance_unverified")
if not (
isinstance(bbox, (list, tuple))
and len(bbox) == 4
and all(isinstance(value, (int, float)) for value in bbox)
and float(bbox[2]) > float(bbox[0])
and float(bbox[3]) > float(bbox[1])
):
reasons.append(f"source_annotation_{index}_bbox_invalid")
if source_annotations and len(source_annotations) != expected_count:
reasons.append("source_annotation_count_mismatch")
if source_annotations and required_instances:
annotated_groups = {str(item.get("group_id") or "") for item in source_annotations}
if annotated_groups != set(required_instances):
reasons.append("source_annotation_groups_do_not_match_required_instances")
# A detector query is not an instance identity. Multi-subject
# preservation checks own one typed roster entry per reviewed entity,
# while the single-subject rules treat multiple phrases as aliases for
# the same physical instance. This prevents synonymous foreground-person
# prompts (or a dog prompt that also fires on a child) from inflating the
# protected source inventory.
if source_rule_type == "multi_instance_strict_preservation":
subject_groups = [
_subject_group_spec(
(query,),
expected_count=1,
group_id=(
required_instances[index]
if index < len(required_instances)
else ""
),
)
for index, query in enumerate(_dedupe_text(subjects))
]
else:
subject_groups = [
_subject_group_spec(
_dedupe_text(subjects),
expected_count=expected_count,
group_id="fixed_location_target",
)
]
for group in subject_groups:
selector_text = " ".join(
[str(group.get("id") or ""), *[str(value) for value in group.get("aliases", [])]]
).lower()
if "foreground" in selector_text:
group["spatial_selector"] = "foreground_largest_lower"
elif "background" in selector_text:
group["spatial_selector"] = "background_smallest_upper"
normalized = {
"expected_count": expected_count,
"required_instances": required_instances,
"subject_groups": _public_subject_groups(subject_groups),
"minimum_detection_confidence": 0.15,
"minimum_match_confidence": float(raw.get("minimum_identity_similarity", 0.55)),
"minimum_identity_similarity": float(raw.get("minimum_identity_similarity", 0.0)),
"maximum_centroid_shift_pixels": (
float(raw["maximum_registered_centroid_shift_pixels"])
if "maximum_registered_centroid_shift_pixels" in raw else None
),
"minimum_registered_mask_iou": float(raw.get("minimum_mask_iou", 0.0)),
"minimum_masked_ssim": float(raw.get("minimum_masked_ssim", 0.0)),
"maximum_changed_area_ratio": float(raw.get("maximum_changed_area_ratio", 1.0)),
"minimum_visible_mask_fraction": minimum_visible,
"minimum_shape_similarity": minimum_shape,
"hat_required": bool(raw.get("hat_required", False)),
"major_body_region_required": bool(raw.get("major_body_region_required", False)),
"blur_aware_comparison": bool(raw.get("blur_aware_comparison", False)),
"registration_required": True,
"registration_method": "robust_static_background_alignment",
"required_matching_features": ["appearance embedding", "mask shape"],
"source_instance_annotations": source_annotations,
"source_inventory_provenance": (
"contract_source_annotations" if source_annotations else "runtime_detector"
),
"source_annotation_mask_profile": _verified_source_mask_profile(source_annotations),
}
if source_rule_type == "multi_instance_strict_preservation":
normalized.update(
{
"matching_classification_labels": [
*[str(group.get("identity_query") or "") for group in subject_groups],
"other object",
],
"matching_classification_minimum_margin": 0.04,
"matching_classification_minimum_probability": 0.25,
# Fixed, named preservation subjects already have scoped
# detector proposals. Full-frame all-mask proposals add
# background lookalikes and cannot establish identity.
"matching_use_segmenter_proposals": False,
"matching_segmenter_min_area_fraction": 0.00003,
"matching_segmenter_max_area_fraction": 0.15,
"matching_segmenter_max_proposals": 128,
}
)
normalized = {key: value for key, value in normalized.items() if value is not None}
return {
"schema_version": EXECUTABLE_PREDICATE_SCHEMA_VERSION,
"check_id": check_id,
"status": "executable" if not reasons else "blocked_uncompiled",
"family": "fixed_location_instance_preservation",
"source_rule_type": source_rule_type,
"subjects": subject_groups,
"regions": [],
"operations": [
_operation("detect_input_subjects", "object_detection", "detector", ("input",), produces=("input_boxes",)),
_operation("refine_input_subjects", "mask_refinement", "segmenter", ("input",), depends_on=("detect_input_subjects",), produces=("input_masks",)),
_operation("detect_output_subjects", "object_detection", "detector", ("pred",), produces=("output_boxes",)),
_operation("refine_output_subjects", "mask_refinement", "segmenter", ("pred",), depends_on=("detect_output_subjects",), produces=("output_masks",)),
_operation("match_subjects", "instance_matching", "matcher", ("input", "pred"), depends_on=("refine_input_subjects", "refine_output_subjects"), produces=("subject_matches",)),
_operation("register_frames", "image_registration", "registration", ("input", "pred"), produces=("pred_to_input_transform",)),
_operation("decide", "predicate_decision", "predicate_interpreter", ("input", "pred"), depends_on=("match_subjects", "register_frames"), produces=("check_result",)),
],
"state_schema": {
"unit": "preserved_instance",
"states": ["preserved", "definite_violation", "unknown"],
"facts": [
"identity_match", "registered_centroid_shift", "registered_mask_iou",
"visible_mask_fraction", "shape_similarity", "masked_ssim", "changed_area_ratio",
],
},
"decision": {
"pass": {"violation_count": 0, "unresolved_count": 0},
"fail": {"violation_count": {"minimum": 1}},
"unknown": {"unresolved_count": {"minimum": 1}, "violation_count": 0},
},
"parameters": normalized,
"parameter_provenance": {
"expected_count": "required_instances_or_rule_cardinality",
"registration_required": "fixed_location_preservation_semantics",
},
"unmapped_contract_parameters": unmapped,
"reasons": reasons,
"provenance": deepcopy(dict(provenance)),
}
def _compile_ocr_text_predicate(
*,
check_id: str,
source_rule_type: str,
subjects: Sequence[str],
params: Mapping[str, Any],
decision: Mapping[str, Any],
provenance: Mapping[str, Any],
) -> dict[str, Any]:
"""Normalize reviewed OCR semantics into the tested OCR operator."""
from pvr_eval.agent.contract_metric_binding import (
canonical_rule_type,
metric_capability,
metric_contract_compliance,
)
raw = _mapping(decision.get("parameters"))
if source_rule_type == "all_text_rois_preserved":
supported = {
"required_anchor_strings", "normalized_edit_similarity_min",
"output_ocr_confidence_min", "relative_sharpness_min_vs_input",
"compare_full_rule_sign_by_line_layout_and_string_alignment",
}
normalized = {
"required_anchor_strings": _dedupe_text(_list(raw.get("required_anchor_strings"))),
"normalized_edit_similarity_min": float(raw.get("normalized_edit_similarity_min", 0.90)),
"output_ocr_confidence_min": float(raw.get("output_ocr_confidence_min", 0.65)),
"relative_sharpness_min_vs_input": float(raw.get("relative_sharpness_min_vs_input", 0.75)),
"compare_full_input_text_inventory": bool(
raw.get("compare_full_rule_sign_by_line_layout_and_string_alignment", True)
),
"registered_text_roi_matching": True,
}
else:
supported = {
"full_frame_scan", "minimum_ocr_confidence",
"match_existing_text_by_content_or_host_object", "ignore_original_scene_text",
"annotation_cues",
}
normalized = {
"minimum_ocr_confidence": float(raw.get("minimum_ocr_confidence", 0.30)),
"full_frame_scan": bool(raw.get("full_frame_scan", True)),
"match_existing_text_by_content": bool(
raw.get("match_existing_text_by_content_or_host_object", True)
),
"ignore_original_scene_text": bool(raw.get("ignore_original_scene_text", True)),
"annotation_cues": _dedupe_text(_list(raw.get("annotation_cues"))),
"new_text_content_similarity_min": 0.85,
"definite_overlay_minimum_confidence": 0.80,
"definite_overlay_minimum_text_length": 4,
}
unmapped = sorted(set(raw) - supported)
reasons: list[str] = []
if not check_id:
reasons.append("missing_check_id")
if source_rule_type == "all_text_rois_preserved" and not normalized["required_anchor_strings"]:
reasons.append("required_anchor_strings_not_compiled")
if unmapped:
reasons.append("unmapped_contract_parameters")
canonical = canonical_rule_type(source_rule_type)
predicate = _compile_registered_metric_bridge(
check_id=check_id,
source_rule_type=source_rule_type,
canonical_rule_type=canonical,
subjects=subjects,
params=params,
decision=decision,
provenance=provenance,
capability=metric_capability(canonical),
)
predicate["parameters"] = normalized
predicate["parameter_provenance"] = {
"source": "decision_rule.parameters",
"normalizer": "ocr_text_contract_v1",
}
predicate["unmapped_contract_parameters"] = unmapped
compliance = metric_contract_compliance(source_rule_type, normalized, decision)
predicate["contract_compliance"] = compliance
if compliance.get("status") != "compliant":
reasons.extend(["contract_handler_incompatible", *compliance.get("risk_flags", [])])
predicate["reasons"] = list(dict.fromkeys((*predicate.get("reasons", []), *reasons)))
predicate["status"] = "executable" if not predicate["reasons"] else "blocked_uncompiled"
return predicate
def _compile_source_displacement(
*,
check_id: str,
source_rule_type: str,
subjects: Sequence[str],
decision: Mapping[str, Any],
provenance: Mapping[str, Any],
) -> dict[str, Any]:
"""Compile per-instance movement as matching plus source-footprint geometry."""
raw = _mapping(decision.get("parameters"))
expected_instances = (
{str(key): int(value) for key, value in raw.get("expected_instances", {}).items()}
if isinstance(raw.get("expected_instances"), Mapping)
else {}
)
expected_bird_count = int(raw.get("expected_bird_count") or 0)
expected_count = sum(expected_instances.values()) if expected_instances else expected_bird_count
supported = {
"per_instance_source_zone_displacement": {
"expected_instances", "source_zone_expansion_fraction",
"moved_if_centroid_outside_expanded_source_zone",
"maximum_source_output_mask_iou_for_move", "minimum_normalized_centroid_displacement",
"matching_features", "source_instance_annotations",
},
"multi_instance_source_zone_displacement": {
"expected_instances", "source_zone_expansion_fraction",
"moved_if_centroid_outside_expanded_source_zone",
"maximum_source_output_mask_iou_for_move", "minimum_normalized_centroid_displacement",
"raccoon_matching", "source_instance_annotations",
},
"bird_instance_displacement_and_shoulder_clearance": {
"expected_bird_count", "source_zone_expansion_fraction",
"maximum_source_output_mask_iou_for_move", "minimum_normalized_centroid_displacement",
"maximum_bird_shoulder_overlap_ratio", "use_tiled_detection", "source_instance_annotations",
},
}
unmapped = sorted(set(raw) - supported.get(source_rule_type, set()))
reasons: list[str] = []
if not check_id:
reasons.append("missing_check_id")
if not subjects:
reasons.append("missing_subject_queries")
if expected_count <= 0:
reasons.append("expected_displaced_count_not_compiled")
if unmapped:
reasons.append("unmapped_contract_parameters")
subject_groups = []
if expected_instances:
for species, count in expected_instances.items():
aliases = [
subject for subject in subjects
if species.lower() in subject.lower() or subject.lower() in species.lower()
]
subject_groups.append(
_subject_group_spec(aliases or (species,), expected_count=count, group_id=species)
)
else:
subject_groups = [_subject_group_spec(subjects, expected_count=expected_count, group_id="birds")]
required_matching_features = _dedupe_text(_list(raw.get("matching_features")))
if source_rule_type == "multi_instance_source_zone_displacement" and raw.get("raccoon_matching"):
matching_text = str(raw.get("raccoon_matching") or "").lower()
required_matching_features = ["species"]
if "appearance" in matching_text:
required_matching_features.append("appearance embedding")
if "size" in matching_text:
required_matching_features.append("relative size")
if source_rule_type == "bird_instance_displacement_and_shoulder_clearance":
required_matching_features = ["species", "appearance embedding", "mask shape"]
source_annotations = [
deepcopy(dict(item))
for item in _list(raw.get("source_instance_annotations"))
if isinstance(item, Mapping)
]
annotation_reasons = []
for index, item in enumerate(source_annotations):
bbox = item.get("bbox_xyxy")
if not isinstance(bbox, (list, tuple)) or len(bbox) != 4:
annotation_reasons.append(f"source_annotation_{index}_bbox_invalid")
if not str(item.get("group_id") or "").strip():
annotation_reasons.append(f"source_annotation_{index}_group_missing")
if source_annotations and len(source_annotations) != expected_count:
annotation_reasons.append("source_annotation_count_mismatch")
reasons.extend(annotation_reasons)
classification_labels = []
for group in subject_groups:
group_id = str(group.get("id") or "").strip()
aliases = [str(value).strip() for value in group.get("aliases", []) if str(value or "").strip()]
label = "bird" if group_id == "birds" else group_id or (aliases[0] if aliases else "")
if label and label not in classification_labels:
classification_labels.append(label)
classification_labels.append("other animal")
normalized = {
"expected_count": expected_count,
"expected_instances": expected_instances,
"expected_bird_count": expected_bird_count,
"subject_groups": _public_subject_groups(subject_groups),
"minimum_detection_confidence": 0.15,
"minimum_match_confidence": 0.55,
"minimum_normalized_centroid_displacement": float(
raw.get("minimum_normalized_centroid_displacement", 0.04)
),
"maximum_source_output_mask_iou_for_move": float(
raw.get("maximum_source_output_mask_iou_for_move", 0.15)
),
"source_zone_expansion_fraction": float(raw.get("source_zone_expansion_fraction", 0.0)),
"moved_if_centroid_outside_expanded_source_zone": bool(
raw.get("moved_if_centroid_outside_expanded_source_zone", True)
),
"require_source_output_mask_iou": True,
"maximum_bird_shoulder_overlap_ratio": float(
raw.get("maximum_bird_shoulder_overlap_ratio", 1.0)
),
"clearance_source_selector_terms": (
["shoulder"]
if source_rule_type == "bird_instance_displacement_and_shoulder_clearance"
else []
),
"require_tiled_search": bool(raw.get("use_tiled_detection", True)),
"required_matching_features": required_matching_features,
"assignment_policy": str(raw.get("raccoon_matching") or "hungarian_one_to_one"),
"source_instance_annotations": source_annotations,
"source_annotation_mask_profile": _verified_source_mask_profile(source_annotations),
"matching_classification_labels": classification_labels,
"matching_use_segmenter_proposals": bool(source_annotations),
"matching_segmenter_min_area_fraction": 0.00003,
"matching_segmenter_max_area_fraction": 0.08,
"matching_segmenter_max_proposals": 128,
# Closed-set filtering only removes non-target animals here. Fine
# target-label ambiguity (notably doe vs fawn) is resolved by the
# subsequent one-to-one matcher, so it must not be discarded early.
"matching_classification_minimum_margin": 0.0,
"matching_classification_minimum_probability": 0.25,
"localized_source_residual_enabled": bool(source_annotations),
"localized_source_residual_minimum_correlation": 0.85,
"localized_source_residual_maximum_mean_absolute_error": 0.10,
"set_level_source_vacancy_allowed": source_rule_type in {
"multi_instance_source_zone_displacement",
"bird_instance_displacement_and_shoulder_clearance",
},
}
return {
"schema_version": EXECUTABLE_PREDICATE_SCHEMA_VERSION,
"check_id": check_id,
"status": "executable" if not reasons else "blocked_uncompiled",
"family": "source_instance_displacement",
"source_rule_type": source_rule_type,
"subjects": subject_groups,
"regions": [],
"operations": [
_operation("detect_input_inventory", "object_detection", "detector", ("input",), produces=("input_boxes",)),
_operation("refine_input_inventory", "mask_refinement", "segmenter", ("input",), depends_on=("detect_input_inventory",), produces=("input_masks",)),
_operation("detect_output_inventory", "object_detection", "detector", ("pred",), parameters={"search_scopes": ["full_frame", "tiled"]}, produces=("output_boxes", "detector_search_coverage")),
_operation("refine_output_inventory", "mask_refinement", "segmenter", ("pred",), depends_on=("detect_output_inventory",), produces=("output_masks",)),
_operation("match_inventory", "instance_matching", "matcher", ("input", "pred"), depends_on=("refine_input_inventory", "refine_output_inventory"), produces=("one_to_one_matches",)),
_operation("classify_displacement", "source_state_classification", "predicate_interpreter", ("input", "pred"), depends_on=("match_inventory",), produces=("per_instance_displacement_facts",)),
_operation("decide", "predicate_decision", "predicate_interpreter", ("input", "pred"), depends_on=("classify_displacement",), produces=("check_result",)),
],
"state_schema": {
"unit": "matched_source_instance",
"states": ["moved", "stationary", "unknown"],
"facts": ["identity_match", "centroid_displacement", "source_overlap", "expanded_source_zone_clearance"],
},
"decision": {
"pass": {"moved_count": expected_count, "unresolved_count": 0},
"partial": {"moved_count": {"minimum": 1, "maximum": max(1, expected_count - 1)}, "unresolved_count": 0},
"fail": {"moved_count": 0, "unresolved_count": 0},
"unknown": {"unresolved_count": {"minimum": 1}},
},
"parameters": normalized,
"parameter_provenance": {
"expected_count": "expected_instances" if expected_instances else "expected_bird_count",
"displacement_thresholds": "decision_rule.parameters",
"assignment_policy": "raccoon_matching" if raw.get("raccoon_matching") else "default:hungarian_one_to_one",
"source_instance_annotations": "decision_rule.parameters.source_instance_annotations" if source_annotations else "runtime_detector",
},
"unmapped_contract_parameters": unmapped,
"reasons": reasons,
"provenance": deepcopy(dict(provenance)),
}
def _compile_source_region_restoration(
*,
check_id: str,
source_rule_type: str,
subjects: Sequence[str],
decision: Mapping[str, Any],
provenance: Mapping[str, Any],
) -> dict[str, Any]:
"""Compile source furniture clearance plus objective lawn coherence."""
raw = _mapping(decision.get("parameters"))
furniture = [
subject
for subject in subjects
if any(noun in subject.lower() for noun in ("table", "chair"))
and "grass" not in subject.lower()
]
table_aliases = [subject for subject in furniture if "table" in subject.lower()]
chair_aliases = [subject for subject in furniture if "chair" in subject.lower()]
groups: list[dict[str, Any]] = []
if table_aliases:
table = _subject_group_spec(table_aliases, expected_count=1, group_id="source_table")
table["output_queries"] = _dedupe_text([*table_aliases, "table", "outdoor table"])
groups.append(table)
if chair_aliases:
chairs = _subject_group_spec(chair_aliases, expected_count=3, group_id="source_chairs")
chairs["output_queries"] = _dedupe_text([*chair_aliases, "chair", "outdoor chair"])
groups.append(chairs)
supported = {
"source_zone_dilation_pixels",
"pass_max_furniture_residual_fraction",
"partial_max_furniture_residual_fraction",
"pass_min_grass_fill_fraction",
"registration_method",
}
unmapped = sorted(set(raw) - supported)
reasons: list[str] = []
if not check_id:
reasons.append("missing_check_id")
if not groups or not table_aliases or not chair_aliases:
reasons.append("table_and_chair_subjects_not_compiled")
if unmapped:
reasons.append("unmapped_contract_parameters")
pass_residual = float(raw.get("pass_max_furniture_residual_fraction", 0.03))
partial_residual = float(raw.get("partial_max_furniture_residual_fraction", 0.20))
grass_min = float(raw.get("pass_min_grass_fill_fraction", 0.90))
normalized = {
"expected_source_count": 4,
"minimum_detection_confidence": 0.15,
"source_zone_dilation_pixels": int(raw.get("source_zone_dilation_pixels", 8)),
"pass_max_furniture_residual_fraction": pass_residual,
"partial_max_furniture_residual_fraction": partial_residual,
"pass_min_grass_fill_fraction": grass_min,
"registration_method": str(raw.get("registration_method") or "robust_static_background_alignment"),
"require_tiled_search_for_negative": True,
"grass_reference_ring_pixels": 24,
"grass_hue_tolerance_degrees": 38.0,
"grass_saturation_tolerance": 0.32,
"grass_value_tolerance": 0.32,
}
return {
"schema_version": EXECUTABLE_PREDICATE_SCHEMA_VERSION,
"check_id": check_id,
"status": "executable" if not reasons else "blocked_uncompiled",
"family": "source_region_restoration",
"source_rule_type": source_rule_type,
"subjects": groups,
"regions": [],
"operations": [
_operation("detect_input_furniture", "object_detection", "detector", ("input",), produces=("input_furniture_boxes",)),
_operation("refine_input_furniture", "mask_refinement", "segmenter", ("input",), depends_on=("detect_input_furniture",), produces=("input_furniture_masks", "source_footprint")),
_operation("detect_output_furniture", "object_detection", "detector", ("pred",), parameters={"search_scopes": ["full_frame", "tiled"]}, produces=("output_furniture_boxes", "detector_search_coverage")),
_operation("refine_output_furniture", "mask_refinement", "segmenter", ("pred",), depends_on=("detect_output_furniture",), produces=("output_furniture_masks",)),
_operation("register_source", "image_registration", "registration", ("input", "pred"), produces=("input_to_output_transform",)),
_operation("measure_restoration", "source_state_classification", "predicate_interpreter", ("input", "pred"), depends_on=("refine_input_furniture", "refine_output_furniture", "register_source"), produces=("furniture_residual_fraction", "grass_fill_fraction")),
_operation("decide", "predicate_decision", "predicate_interpreter", ("input", "pred"), depends_on=("measure_restoration",), produces=("check_result",)),
],
"state_schema": {
"unit": "registered_source_furniture_footprint",
"states": ["restored", "partially_restored", "furniture_remaining", "unknown"],
"facts": ["input_inventory_count", "registration", "furniture_residual_fraction", "grass_fill_fraction", "negative_search_coverage"],
},
"decision": {
"pass": {"furniture_residual_fraction": {"maximum": pass_residual}, "grass_fill_fraction": {"minimum": grass_min}, "unresolved_count": 0},
"partial": {"any": [
{"furniture_residual_fraction": {"minimum": pass_residual + 1e-9, "maximum": partial_residual}, "unresolved_count": 0},
{"furniture_residual_fraction": {"maximum": partial_residual}, "grass_fill_fraction": {"maximum": grass_min - 1e-9}, "unresolved_count": 0},
]},
"fail": {"furniture_residual_fraction": {"minimum": partial_residual + 1e-9}, "unresolved_count": 0},
"unknown": {"unresolved_count": {"minimum": 1}},
},
"parameters": normalized,
"parameter_provenance": {
"source_zone": "union_of_input_table_and_three_chair_masks",
"registration_method": "registration_method",
"furniture_residual_thresholds": "decision_rule.parameters",
"grass_fill_threshold": "decision_rule.parameters",
},
"unmapped_contract_parameters": unmapped,
"reasons": reasons,
"provenance": deepcopy(dict(provenance)),
}
def _compile_registered_metric_bridge(
*,
check_id: str,
source_rule_type: str,
canonical_rule_type: str,
subjects: Sequence[str],
params: Mapping[str, Any],
decision: Mapping[str, Any],
provenance: Mapping[str, Any],
capability: Any,
) -> dict[str, Any]:
operations: list[dict[str, Any]] = []
previous_by_kind: dict[str, list[str]] = {}
for index, requirement in enumerate(getattr(capability, "evidence", ())):
kind = str(requirement.operation)
operation_id = f"{kind}_{index + 1}"
dependencies: list[str] = []
if kind == "mask_refinement":
dependencies.extend(previous_by_kind.get("object_detection", []))
elif kind == "instance_matching":
dependencies.extend(previous_by_kind.get("mask_refinement", []))
operations.append(
_operation(
operation_id,
kind,
str(requirement.tool_family),
tuple(requirement.image_roles),
depends_on=dependencies,
produces=(kind + "_evidence",),
)
)
previous_by_kind.setdefault(kind, []).append(operation_id)
regions = _generic_typed_regions(params) if getattr(capability, "regions", ()) else []
if regions and getattr(capability, "regions", ()):
operations.append(
_operation(
"materialize_regions",
"region_resolution",
"region_proposer",
tuple(dict.fromkeys(role for region in regions for role in region.get("image_roles", []))),
produces=("named_region_boxes",),
)
)
operations.append(
_operation(
"refine_regions",
"spatial_geometry",
"segmenter",
tuple(dict.fromkeys(role for region in regions for role in region.get("image_roles", []))),
depends_on=("materialize_regions",),
produces=("named_region_masks",),
)
)
terminal_dependencies = [item["id"] for item in operations]
operations.append(
_operation(
"decide",
"predicate_decision",
"registered_metric_operator",
("input", "pred"),
depends_on=terminal_dependencies,
parameters={"operator": canonical_rule_type, "operator_version": REGISTERED_METRIC_OPERATOR_VERSION},
produces=("check_result",),
)
)
reasons = []
if not check_id:
reasons.append("missing_check_id")
if any(item["kind"] in {"object_detection", "mask_refinement", "instance_matching"} for item in operations) and not subjects:
reasons.append("missing_subject_queries")
return {
"schema_version": EXECUTABLE_PREDICATE_SCHEMA_VERSION,
"check_id": check_id,
"status": "executable" if not reasons else "blocked_uncompiled",
"family": "registered_metric_bridge",
"source_rule_type": source_rule_type,
"canonical_rule_type": canonical_rule_type,
"subjects": _subject_specs(subjects, ""),
"regions": regions,
"operations": operations,
"state_schema": {
"unit": "registered_metric_evidence",
"operator": canonical_rule_type,
"operator_version": REGISTERED_METRIC_OPERATOR_VERSION,
},
"decision": {
"operator": canonical_rule_type,
"operator_version": REGISTERED_METRIC_OPERATOR_VERSION,
"allowed_outcomes": ["pass", "partial", "fail", "unknown"],
"unknown_policy": "fail_closed",
},
"parameters": _mapping(decision.get("parameters")),
"parameter_provenance": {"source": "decision_rule.parameters", "validation": "metric_contract_compliance"},
"unmapped_contract_parameters": [],
"reasons": reasons,
"provenance": deepcopy(dict(provenance)),
}
def _compile_instance_cluster_grouping(
*,
check_id: str,
source_rule_type: str,
subjects: Sequence[str],
params: Mapping[str, Any],
decision: Mapping[str, Any],
provenance: Mapping[str, Any],
) -> dict[str, Any]:
"""Lower the reviewed adaptive proximity graph into numeric parameters."""
from pvr_eval.agent.contract_metric_binding import ( # local import avoids module-init cycle
canonical_rule_type,
metric_capability,
metric_contract_compliance,
)
raw = _mapping(decision.get("parameters"))
consumed = {
"proximity_edge_threshold",
"meaningful_component_minimum",
"dominant_cluster_fraction",
"partial_cluster_fraction",
"source_instance_annotations",
"matching_classification_labels",
"minimum_output_roster_coverage_for_geometry",
"source_stationary_overlap_threshold",
"maximum_instance_area_fraction",
}
unmapped = sorted(set(raw) - consumed)
reasons: list[str] = []
if not check_id:
reasons.append("missing_check_id")
if not subjects:
reasons.append("missing_subject_queries")
if unmapped:
reasons.append("unmapped_contract_parameters")
source_annotations = [
deepcopy(dict(item))
for item in _list(raw.get("source_instance_annotations"))
if isinstance(item, Mapping)
]
annotation_ids: set[str] = set()
for index, item in enumerate(source_annotations):
bbox = item.get("bbox_xyxy")
instance_id = str(item.get("instance_id") or "").strip()
group_id = str(item.get("group_id") or "").strip()
if not isinstance(bbox, (list, tuple)) or len(bbox) != 4:
reasons.append(f"source_annotation_{index}_bbox_invalid")
else:
try:
x0, y0, x1, y1 = [float(value) for value in bbox]
if x1 <= x0 or y1 <= y0:
reasons.append(f"source_annotation_{index}_bbox_invalid")
except (TypeError, ValueError):
reasons.append(f"source_annotation_{index}_bbox_invalid")
if not instance_id or instance_id in annotation_ids:
reasons.append(f"source_annotation_{index}_instance_id_invalid")
annotation_ids.add(instance_id)
if not group_id:
reasons.append(f"source_annotation_{index}_group_missing")
if not source_annotations:
reasons.append("fixed_source_roster_required")
classification_labels = _dedupe_text(_list(raw.get("matching_classification_labels")))
if not classification_labels:
classification_labels = _dedupe_text(
[str(item.get("group_id") or "") for item in source_annotations]
)
classification_labels = [value for value in classification_labels if value != "other animal"]
if classification_labels:
classification_labels.append("other animal")
else:
reasons.append("matching_classification_labels_required")
proximity = raw.get("proximity_edge_threshold")
proximity_text = str(proximity or "").lower()
edge_fraction_match = re.search(r"([0-9]*\.?[0-9]+)\s*(?:image\s*)?diagonal", proximity_text)
diameter_match = re.search(r"([0-9]*\.?[0-9]+)\s*times\s*median", proximity_text)
if isinstance(proximity, (int, float)):
minimum_edge_fraction = float(proximity)
diameter_multiplier = 0.0
elif edge_fraction_match and diameter_match:
minimum_edge_fraction = float(edge_fraction_match.group(1))
diameter_multiplier = float(diameter_match.group(1))
else:
minimum_edge_fraction = 0.08
diameter_multiplier = 2.5
reasons.append("proximity_edge_threshold_not_parsed")
meaningful_match = re.search(r"(\d+)", str(raw.get("meaningful_component_minimum") or "2"))
minimum_component_size = int(meaningful_match.group(1)) if meaningful_match else 0
if minimum_component_size < 2:
reasons.append("meaningful_component_minimum_not_compiled")
pass_fraction = float(raw.get("dominant_cluster_fraction", 0.9))
partial_fraction = float(raw.get("partial_cluster_fraction", 0.6))
if not (0.0 <= partial_fraction <= pass_fraction <= 1.0):
reasons.append("invalid_cluster_fraction_thresholds")
normalized = {
"minimum_detector_confidence": 0.20,
"minimum_match_confidence": 0.45,
"maximum_instance_area_fraction": float(raw.get("maximum_instance_area_fraction", 0.08)),
"minimum_edge_fraction_of_image_diagonal": minimum_edge_fraction,
# The reviewed rule is max(fraction*diagonal, multiplier*diameter)
# and declares no smaller cap. A cap of one image diagonal preserves
# that rule while keeping the numeric operator bounded.
"maximum_edge_fraction_of_image_diagonal": 1.0,
"median_instance_diameter_multiplier": diameter_multiplier,
"minimum_meaningful_component_size": minimum_component_size,
"dominant_cluster_fraction": pass_fraction,
"partial_cluster_fraction": partial_fraction,
"source_instance_annotations": source_annotations,
"source_annotation_mask_profile": _verified_source_mask_profile(source_annotations),
"matching_classification_labels": classification_labels,
"matching_use_segmenter_proposals": bool(source_annotations),
"matching_segmenter_min_area_fraction": 0.00003,
"matching_segmenter_max_area_fraction": float(raw.get("maximum_instance_area_fraction", 0.08)),
"matching_segmenter_max_proposals": 160,
"matching_classification_minimum_margin": 0.0,
"matching_classification_minimum_probability": 0.25,
"minimum_output_roster_coverage_for_geometry": float(
raw.get("minimum_output_roster_coverage_for_geometry", 0.65)
),
"source_stationary_overlap_threshold": float(
raw.get("source_stationary_overlap_threshold", 0.30)
),
"set_level_target_roster_allowed": True,
}
canonical = canonical_rule_type(source_rule_type)
predicate = _compile_registered_metric_bridge(
check_id=check_id,
source_rule_type=source_rule_type,
canonical_rule_type=canonical,
subjects=subjects,
params=params,
decision=decision,
provenance=provenance,
capability=metric_capability(canonical),
)
predicate["subjects"] = [
_subject_group_spec(
subjects,
expected_count=1,
group_id="small_animal_target_roster",
)
] if subjects else []
predicate["parameters"] = normalized
predicate["parameter_provenance"] = {
"minimum_edge_fraction_of_image_diagonal": "proximity_edge_threshold",
"median_instance_diameter_multiplier": "proximity_edge_threshold",
"minimum_meaningful_component_size": "meaningful_component_minimum",
"dominant_cluster_fraction": "dominant_cluster_fraction",
"partial_cluster_fraction": "partial_cluster_fraction",
"source_instance_annotations": "source_instance_annotations:manual_input_fact",
"matching_classification_labels": "matching_classification_labels",
"minimum_output_roster_coverage_for_geometry": "minimum_output_roster_coverage_for_geometry",
"source_stationary_overlap_threshold": "source_stationary_overlap_threshold",
}
predicate["unmapped_contract_parameters"] = unmapped
compliance = metric_contract_compliance(source_rule_type, normalized, decision)
predicate["contract_compliance"] = compliance
if compliance.get("status") != "compliant":
reasons.extend(["contract_handler_incompatible", *compliance.get("risk_flags", [])])
predicate["reasons"] = list(dict.fromkeys((*predicate.get("reasons", []), *reasons)))
predicate["status"] = "executable" if not predicate["reasons"] else "blocked_uncompiled"
return predicate
def _compile_small_animal_set_geometry(
*,
check_id: str,
source_rule_type: str,
subjects: Sequence[str],
params: Mapping[str, Any],
decision: Mapping[str, Any],
provenance: Mapping[str, Any],
) -> dict[str, Any]:
"""Compile dense small-animal checks as set geometry, not fake identity.
The input roster is a reviewed case fact. The output remains entirely
tool-derived: detector and FastSAM proposals are filtered by closed-set
CLIP, then the metric consumes the accepted output set and masks.
"""
from pvr_eval.agent.contract_metric_binding import ( # local import avoids module-init cycle
canonical_rule_type,
metric_capability,
metric_contract_compliance,
)
raw = _mapping(decision.get("parameters"))
common = {
"source_instance_annotations",
"matching_classification_labels",
"minimum_output_roster_coverage_for_geometry",
"source_stationary_overlap_threshold",
"maximum_instance_area_fraction",
"protected_subject_source_annotations",
"protected_subject_minimum_identity_confidence",
}
supported = {
"protected_zone_exclusion_count": common | {
"immediate_vicinity_dilation",
"touch_tolerance_pixels",
"minimum_match_confidence",
},
"cluster_protected_subject_gap": common | {
"clear_gap_threshold",
"slight_overlap_fraction_max",
"substantial_overlap_fraction",
"cluster_proximity_edge_threshold",
"meaningful_component_minimum",
"dominant_cluster_minimum_fraction",
},
}
unmapped = sorted(set(raw) - supported.get(source_rule_type, set()))
reasons: list[str] = []
if not check_id:
reasons.append("missing_check_id")
if unmapped:
reasons.append("unmapped_contract_parameters")
protected_terms = ("moose", "bear", "robot")
protected_queries = [
subject for subject in subjects
if any(term in subject.lower() for term in protected_terms)
]
target_queries = [
subject for subject in subjects
if subject not in protected_queries
]
if not target_queries:
reasons.append("small_animal_subject_queries_missing")
if len(protected_queries) < 3:
reasons.append("protected_subject_queries_incomplete")
source_annotations = [
deepcopy(dict(item))
for item in _list(raw.get("source_instance_annotations"))
if isinstance(item, Mapping)
]
annotation_ids: set[str] = set()
for index, item in enumerate(source_annotations):
bbox = item.get("bbox_xyxy")
instance_id = str(item.get("instance_id") or "").strip()
group_id = str(item.get("group_id") or "").strip()
if not isinstance(bbox, (list, tuple)) or len(bbox) != 4:
reasons.append(f"source_annotation_{index}_bbox_invalid")
else:
try:
x0, y0, x1, y1 = [float(value) for value in bbox]
if x1 <= x0 or y1 <= y0:
reasons.append(f"source_annotation_{index}_bbox_invalid")
except (TypeError, ValueError):
reasons.append(f"source_annotation_{index}_bbox_invalid")
if not instance_id or instance_id in annotation_ids:
reasons.append(f"source_annotation_{index}_instance_id_invalid")
annotation_ids.add(instance_id)
if not group_id:
reasons.append(f"source_annotation_{index}_group_missing")
if not source_annotations:
reasons.append("fixed_source_roster_required")
classification_labels = _dedupe_text(_list(raw.get("matching_classification_labels")))
if not classification_labels:
classification_labels = _dedupe_text(
[str(item.get("group_id") or "") for item in source_annotations]
)
classification_labels = [value for value in classification_labels if value != "other animal"]
if classification_labels:
classification_labels.append("other animal")
else:
reasons.append("matching_classification_labels_required")
verified_roster_expected_counts: dict[str, int] = {}
for item in source_annotations:
group_id = str(item.get("group_id") or "").strip()
if group_id:
verified_roster_expected_counts[group_id] = (
verified_roster_expected_counts.get(group_id, 0) + 1
)
protected_source_annotations = [
deepcopy(dict(item))
for item in _list(raw.get("protected_subject_source_annotations"))
if isinstance(item, Mapping)
]
for index, item in enumerate(protected_source_annotations):
bbox = item.get("bbox_xyxy")
instance_id = str(item.get("instance_id") or "").strip()
group_id = str(item.get("group_id") or "").strip()
if not instance_id:
reasons.append(f"protected_source_annotation_{index}_instance_id_invalid")
if group_id not in protected_queries:
reasons.append(f"protected_source_annotation_{index}_group_invalid")
if not isinstance(bbox, (list, tuple)) or len(bbox) != 4:
reasons.append(f"protected_source_annotation_{index}_bbox_invalid")
else:
try:
x0, y0, x1, y1 = [float(value) for value in bbox]
if x1 <= x0 or y1 <= y0:
reasons.append(f"protected_source_annotation_{index}_bbox_invalid")
except (TypeError, ValueError):
reasons.append(f"protected_source_annotation_{index}_bbox_invalid")
if protected_source_annotations and (
len(protected_source_annotations) != len(protected_queries)
or {str(item.get("group_id") or "") for item in protected_source_annotations}
!= set(protected_queries)
):
reasons.append("protected_source_annotation_roster_incomplete")
normalized: dict[str, Any] = {
"source_instance_annotations": source_annotations,
"source_annotation_mask_profile": _verified_source_mask_profile(source_annotations),
"expected_source_count": len(source_annotations),
"protected_subject_queries": protected_queries,
"minimum_detector_confidence": 0.15,
"minimum_match_confidence": float(raw.get("minimum_match_confidence", 0.45)),
"maximum_instance_area_fraction": float(raw.get("maximum_instance_area_fraction", 0.08)),
"matching_classification_labels": classification_labels,
"matching_use_segmenter_proposals": bool(source_annotations),
"matching_segmenter_min_area_fraction": 0.00003,
"matching_segmenter_max_area_fraction": float(raw.get("maximum_instance_area_fraction", 0.08)),
"matching_segmenter_max_proposals": 160,
"matching_classification_minimum_margin": 0.0,
"matching_classification_minimum_probability": 0.25,
"minimum_output_roster_coverage_for_geometry": float(
raw.get("minimum_output_roster_coverage_for_geometry", 0.65)
),
"source_stationary_overlap_threshold": float(
raw.get("source_stationary_overlap_threshold", 0.30)
),
"set_level_target_roster_allowed": True,
"verified_roster_profile": "verified_group_roster_assignment_v1",
"verified_roster_assignment_mode": "question_support_allowed_edit_coverage_v1",
"verified_roster_expected_counts": verified_roster_expected_counts,
"verified_roster_minimum_area_ratio": 0.10,
"verified_roster_maximum_area_ratio": 6.0,
"identity_agnostic_target_coverage_profile": (
"identity_agnostic_target_animal_coverage_v1"
),
"target_coverage_minimum_probability": 0.50,
"target_coverage_minimum_margin": 0.15,
"target_coverage_minimum_animal_probability": 0.75,
"target_coverage_minimum_animal_margin": 0.50,
"target_coverage_maximum_protected_overlap": 0.10,
"target_coverage_neighborhood_fraction_of_diagonal": 0.08,
"protected_subject_certificate_required": True,
"protected_classification_minimum_margin": 0.0,
"protected_classification_minimum_probability": 0.25,
**(
{
"protected_subject_source_annotations": protected_source_annotations,
"protected_subject_source_mask_profile": (
VERIFIED_PROTECTED_SOURCE_MASK_PROFILE
),
"protected_subject_minimum_identity_confidence": float(
raw.get("protected_subject_minimum_identity_confidence", 0.45)
),
}
if protected_source_annotations
else {}
),
}
if source_rule_type == "protected_zone_exclusion_count":
dilation = str(raw.get("immediate_vicinity_dilation") or "").lower()
fraction_match = re.search(r"([0-9]*\.?[0-9]+)\s*(?:image\s*)?diagonal", dilation)
diameter_match = re.search(r"([0-9]*\.?[0-9]+)\s*times\s*median", dilation)
if not fraction_match or not diameter_match:
reasons.append("immediate_vicinity_dilation_not_parsed")
normalized.update(
{
"vicinity_fraction_of_image_diagonal": float(fraction_match.group(1)) if fraction_match else 0.02,
"vicinity_median_instance_diameter_multiplier": float(diameter_match.group(1)) if diameter_match else 0.5,
"touch_tolerance_pixels": int(raw.get("touch_tolerance_pixels", 3)),
"partial_max_violating_instances": 2,
"fail_min_violating_instances": 3,
"fail_majority_source_roster_fraction": 0.5,
}
)
else:
gap = str(raw.get("clear_gap_threshold") or "").lower()
gap_fraction = re.search(r"([0-9]*\.?[0-9]+)\s*(?:image\s*)?diagonal", gap)
gap_diameter = re.search(r"([0-9]*\.?[0-9]+)\s*times\s*median", gap)
proximity = str(raw.get("cluster_proximity_edge_threshold") or "").lower()
edge_fraction = re.search(r"([0-9]*\.?[0-9]+)\s*(?:image\s*)?diagonal", proximity)
edge_diameter = re.search(r"([0-9]*\.?[0-9]+)\s*times\s*median", proximity)
meaningful = re.search(r"(\d+)", str(raw.get("meaningful_component_minimum") or "2"))
if not gap_fraction or not gap_diameter:
reasons.append("clear_gap_threshold_not_parsed")
if not edge_fraction or not edge_diameter:
reasons.append("cluster_proximity_edge_threshold_not_parsed")
normalized.update(
{
"clear_gap_fraction_of_image_diagonal": float(gap_fraction.group(1)) if gap_fraction else 0.02,
"clear_gap_median_instance_diameter_multiplier": float(gap_diameter.group(1)) if gap_diameter else 0.5,
"slight_overlap_fraction_max": float(raw.get("slight_overlap_fraction_max", 0.02)),
"substantial_overlap_fraction": float(raw.get("substantial_overlap_fraction", 0.02)),
"minimum_edge_fraction_of_image_diagonal": float(edge_fraction.group(1)) if edge_fraction else 0.08,
"median_instance_diameter_multiplier": float(edge_diameter.group(1)) if edge_diameter else 2.5,
"minimum_meaningful_component_size": int(meaningful.group(1)) if meaningful else 2,
"dominant_cluster_minimum_fraction": float(raw.get("dominant_cluster_minimum_fraction", 0.60)),
"cluster_envelope_buffer_pixels": 3,
}
)
canonical = canonical_rule_type(source_rule_type)
predicate = _compile_registered_metric_bridge(
check_id=check_id,
source_rule_type=source_rule_type,
canonical_rule_type=canonical,
subjects=subjects,
params=params,
decision=decision,
provenance=provenance,
capability=metric_capability(canonical),
)
target_group = _subject_group_spec(
target_queries,
expected_count=max(1, len(source_annotations)),
group_id="small_animal_target_roster",
)
target_group["output_queries"] = _dedupe_text(target_queries)
protected_group = _subject_group_spec(
protected_queries,
expected_count=3,
group_id="protected_subjects",
)
predicate["subjects"] = [target_group, protected_group]
predicate["parameters"] = normalized
predicate.setdefault("provenance", {})[
"small_animal_geometry_executor_version"
] = SMALL_ANIMAL_GEOMETRY_EXECUTOR_VERSION
predicate["parameter_provenance"] = {
"source_instance_annotations": "source_instance_annotations:manual_input_fact",
"matching_classification_labels": "matching_classification_labels",
"protected_subject_queries": "object_queries:moose,bear,robot",
"verified_roster_profile": "shared_verified_group_roster_assignment_v1",
"identity_agnostic_target_coverage_profile": (
"shared_identity_agnostic_target_animal_coverage_v1"
),
"protected_subject_certificate_required": "shared_protected_subject_roster_clearance_v1",
"geometry_thresholds": "decision_rule.parameters",
}
predicate["unmapped_contract_parameters"] = unmapped
compliance = metric_contract_compliance(source_rule_type, normalized, decision)
predicate["contract_compliance"] = compliance
if compliance.get("status") != "compliant":
reasons.extend(["contract_handler_incompatible", *compliance.get("risk_flags", [])])
predicate["reasons"] = list(dict.fromkeys((*predicate.get("reasons", []), *reasons)))
predicate["status"] = "executable" if not predicate["reasons"] else "blocked_uncompiled"
return predicate
def _compile_structured_check(
*,
check_id: str,
source_rule_type: str,
subjects: Sequence[str],
params: Mapping[str, Any],
decision: Mapping[str, Any],
provenance: Mapping[str, Any],
) -> dict[str, Any]:
"""Compile one reviewed case parser as a terminal deterministic call.
Structured visual states do not share a safe universal detector schema.
The parser therefore owns the complete reviewed rule parameters and emits
a standardized atomic result. Semantic planned regions are consumed by
the case adapter (or by explicit geometry in the rule), rather than being
silently reinterpreted as open-vocabulary object queries.
"""
raw = _mapping(decision.get("parameters"))
planned_ids = [
str(item.get("region_id") or item.get("id") or "").strip()
for item in _planned_regions(params)
if str(item.get("region_id") or item.get("id") or "").strip()
]
subject_groups = [
_subject_group_spec((subject,), expected_count=1)
for subject in _dedupe_text(subjects)
] or [
_subject_group_spec(
(check_id.replace("_", " "),),
expected_count=1,
group_id="structured_case_state",
)
]
operations: list[dict[str, Any]] = []
dependencies: list[str] = []
if source_rule_type in {
"expected_date_digit_transition",
"dial_graphics_preservation",
"flowchart_structure_preservation",
"inputs_card_integrity",
"card_text_identity_preservation",
"identity_loss_penalty",
"unrequested_annotation_penalty",
"paired_text_legibility_preservation",
"card_content_preservation",
"grid_and_labels_intact",
"all_required_text_and_icons_intact",
"all_required_labels_legible_and_aligned",
"ordered_label_preservation",
}:
paired_ocr_rules = {
"inputs_card_integrity",
"identity_loss_penalty",
"unrequested_annotation_penalty",
"grid_and_labels_intact",
}
roles = ("input", "pred") if "preservation" in source_rule_type or source_rule_type in paired_ocr_rules else ("pred",)
operations.append(
_operation("read_structured_text", "ocr", "ocr", roles, produces=("structured_text",))
)
dependencies.append("read_structured_text")
if source_rule_type in {
"assigned_vehicle_slot_predicate",
"accessible_vehicle_slot_predicate",
"any_assigned_vehicle_boundary_violation",
"audit_only_required_identity_count",
"required_pair_in_target_zone",
"all_sources_vacated_no_forbidden_zone_instances",
"all_item_attributes_preserved",
"source_instance_vacancy",
}:
operations.extend(
[
_operation(
"detect_structured_objects",
"object_detection",
"detector",
("pred",),
produces=("structured_object_boxes",),
),
_operation(
"refine_structured_objects",
"mask_refinement",
"segmenter",
("pred",),
depends_on=("detect_structured_objects",),
produces=("structured_object_masks",),
),
]
)
dependencies.append("refine_structured_objects")
if source_rule_type in {
"needle_instance_preservation",
"dial_graphics_preservation",
"registered_invariant_region_preservation",
"watch_structure_relocation_violation",
"non_target_component_integrity_violation",
"occlusion_aware_marking_preservation",
"flowchart_structure_preservation",
"inputs_card_integrity",
"multi_region_background_preservation",
"structural_invariant_preservation",
"multi_entity_integrity",
"protected_roi_exact_preservation",
"paired_text_legibility_preservation",
"card_content_preservation",
"grid_and_labels_intact",
"tray_and_contents_preserved",
"all_instances_intact_and_stationary",
"registered_card_preservation",
"invariant_background_preservation",
"invariant_region_preserved",
"ordered_label_preservation",
"invariant_structure_integrity",
}:
operations.extend(
[
_operation(
"register_structured_frames",
"image_registration",
"registration",
("input", "pred"),
produces=("structured_transform",),
),
_operation(
"measure_structured_change",
"change_analysis",
"change_analyzer",
("input", "pred"),
depends_on=("register_structured_frames",),
produces=("structured_change",),
),
]
)
dependencies.append("measure_structured_change")
operations.append(
_operation(
"run_structured_checker",
"structured_check",
"structured_checker",
("input", "pred"),
depends_on=tuple(dict.fromkeys(dependencies)),
parameters={"adapter": "pvr_structured_contract_v1", "source_rule_type": source_rule_type},
produces=("structured_check_result",),
)
)
return {
"schema_version": EXECUTABLE_PREDICATE_SCHEMA_VERSION,
"check_id": check_id,
"status": "executable",
"family": "structured_case_parser",
"source_rule_type": source_rule_type,
"subjects": subject_groups,
"regions": [],
"explicitly_ignored_region_ids": planned_ids,
"operations": operations,
"state_schema": {
"unit": "atomic_structured_visual_state",
"states": ["pass", "partial", "fail", "unknown"],
"facts": ["parser_measurements", "contract_thresholds", "evidence_overlay"],
},
"decision": {
"pass": {"parser_status": "pass"},
"partial": {"parser_status": "partial"},
"fail": {"parser_status": "fail"},
"unknown": {"parser_status": "unknown"},
},
"parameters": {
"adapter": "pvr_structured_contract_v1",
"source_rule_type": source_rule_type,
"decision_parameters": raw,
"planned_region_ids": planned_ids,
"zero_vlm": True,
},
"parameter_provenance": {
"decision_parameters": "reviewed decision_rule.parameters",
"planned_region_ids": "reviewed planned_regions",
"adapter": "versioned deterministic case parser",
},
"unmapped_contract_parameters": [],
"reasons": [],
"provenance": deepcopy(dict(provenance)),
}
def compile_executable_predicate(check: Mapping[str, Any]) -> dict[str, Any]:
"""Compile one prepared contract check into a validated predicate.
An explicit predicate authored in the source contract wins. Generated
predicates are currently limited to the source-region clearance family;
other rules are retained as blocked records until their semantics have a
dedicated compiler and interpreter.
"""
check_id = str(check.get("id") or check.get("check_id") or "").strip()
params = _mapping(check.get("params"))
decision = _mapping(params.get("decision_rule"))
source_rule_type = str(decision.get("type") or "").strip()
explicit = check.get("executable_predicate") or params.get("executable_predicate")
if isinstance(explicit, Mapping):
predicate = deepcopy(dict(explicit))
provenance = predicate.get("provenance") if isinstance(predicate.get("provenance"), Mapping) else {}
capabilities = predicate.get("capability_versions") if isinstance(predicate.get("capability_versions"), Mapping) else {}
source_annotation_mask_rules = (
FIXED_LOCATION_PRESERVATION_RULES
| SOURCE_DISPLACEMENT_RULES
| INSTANCE_CLUSTER_GROUPING_RULES
| PROTECTED_SET_EXCLUSION_RULES
| CLUSTER_SUBJECT_SEPARATION_RULES
)
if (
provenance.get("compiler")
== "pvr_eval.agent.executable_predicate.compile_executable_predicate"
and source_rule_type in source_annotation_mask_rules
and bool(_list(_mapping(decision.get("parameters")).get("source_instance_annotations")))
and provenance.get("source_annotation_mask_policy_version")
!= VERIFIED_SOURCE_MASK_CAPABILITY_VERSION
):
# Generated IR is a cache, not authored contract truth. Rebuild
# it when the runtime evidence policy advances; hand-authored IR
# never enters this branch.
source_check = deepcopy(dict(check))
source_check.pop("executable_predicate", None)
source_params = _mapping(source_check.get("params"))
source_params.pop("executable_predicate", None)
source_check["params"] = source_params
return compile_executable_predicate(source_check)
if (
provenance.get("compiler")
== "pvr_eval.agent.executable_predicate.compile_executable_predicate"
and source_rule_type
in (PROTECTED_SET_EXCLUSION_RULES | CLUSTER_SUBJECT_SEPARATION_RULES)
and provenance.get("small_animal_geometry_executor_version")
!= SMALL_ANIMAL_GEOMETRY_EXECUTOR_VERSION
):
source_check = deepcopy(dict(check))
source_check.pop("executable_predicate", None)
source_params = _mapping(source_check.get("params"))
source_params.pop("executable_predicate", None)
source_check["params"] = source_params
return compile_executable_predicate(source_check)
if (
provenance.get("compiler")
== "pvr_eval.agent.executable_predicate.compile_executable_predicate"
and str(predicate.get("family") or "") == "registered_metric_bridge"
and "stale_registered_metric_operator_version"
in validate_executable_predicate(predicate).reasons
):
# Generated bridge IR is a cache. Refresh it whenever the shared
# registered metric operator advances; otherwise a schema-valid
# embedded predicate can silently omit newly required evidence.
source_check = deepcopy(dict(check))
source_check.pop("executable_predicate", None)
source_params = _mapping(source_check.get("params"))
source_params.pop("executable_predicate", None)
source_check["params"] = source_params
return compile_executable_predicate(source_check)
if provenance.get("compiler") == "pvr_eval.contracts.predicate_lowering.lower_reviewed_predicate":
from pvr_eval.contracts.predicate_lowering import (
LOWERER_VERSION,
VERIFIED_GROUP_ROSTER_PROFILE,
lower_reviewed_predicate,
reviewed_source_check_sha256,
)
source_hash_stale = (
str(predicate.get("source_check_sha256") or "")
!= reviewed_source_check_sha256(check)
)
predicate_parameters = _mapping(predicate.get("parameters"))
articulated_executor_stale = bool(
predicate_parameters.get("articulated_entity_preservation_profile")
== ARTICULATED_ENTITY_PRESERVATION_PROFILE
and predicate_parameters.get("articulated_entity_preservation_executor_version")
!= ARTICULATED_ENTITY_PRESERVATION_EXECUTOR_VERSION
)
source_decision = _mapping(_mapping(_mapping(check.get("params")).get("decision_rule")).get("parameters"))
verified_roster_executor_stale = bool(
source_decision.get("source_roster_complete") is True
and isinstance(source_decision.get("source_roster_expected_counts"), Mapping)
and source_decision.get("source_instance_annotations")
and predicate_parameters.get("verified_roster_profile")
!= VERIFIED_GROUP_ROSTER_PROFILE
)
if (
capabilities.get("lowerer") != LOWERER_VERSION
or source_hash_stale
or articulated_executor_stale
or verified_roster_executor_stale
):
refreshed = lower_reviewed_predicate(check)
if refreshed is not None:
predicate = refreshed
elif (
provenance.get("compiler")
== "pvr_eval.agent.executable_predicate.compile_executable_predicate"
and str(predicate.get("status") or "")
in {"manual_review_required", "blocked_uncompiled"}
):
from pvr_eval.contracts.predicate_ir_candidate import RULE_FAMILY_TARGETS
from pvr_eval.contracts.predicate_lowering import lower_reviewed_predicate
if source_rule_type in RULE_FAMILY_TARGETS:
refreshed = lower_reviewed_predicate(check)
if refreshed is not None:
predicate = refreshed
predicate.setdefault("schema_version", EXECUTABLE_PREDICATE_SCHEMA_VERSION)
predicate.setdefault("check_id", check_id)
validation = validate_executable_predicate(predicate)
if validation.valid:
return predicate
predicate["status"] = "blocked_invalid"
predicate["reasons"] = list(dict.fromkeys((*_list(predicate.get("reasons")), *validation.reasons)))
return predicate
subjects = _subjects(params)
provenance = {
"compiler": "pvr_eval.agent.executable_predicate.compile_executable_predicate",
"source_annotation_mask_policy_version": VERIFIED_SOURCE_MASK_CAPABILITY_VERSION,
"question": str(check.get("question") or check.get("description") or ""),
"pass_criteria": str(check.get("pass_criteria") or ""),
"partial_criteria": str(check.get("partial_criteria") or ""),
"fail_criteria": str(check.get("fail_criteria") or ""),
"decision_conditions": {
key: str(decision.get(key) or "")
for key in ("pass_condition", "partial_condition", "fail_condition")
},
}
# The reviewed natural-language backlog is promoted only through the
# golden candidate IR and deterministic six-family lowerer. This branch
# intentionally precedes legacy aliases, whose coarse handlers consumed
# only a small subset of the reviewed parameters.
from pvr_eval.contracts.predicate_lowering import lower_reviewed_predicate
reviewed = lower_reviewed_predicate(check)
if reviewed is not None:
validation = validate_executable_predicate(reviewed)
if not validation.valid and reviewed.get("status") == "executable":
reviewed["status"] = "blocked_invalid"
reviewed["reasons"] = list(
dict.fromkeys((*reviewed.get("reasons", []), *validation.reasons))
)
return reviewed
if source_rule_type in SURFACE_RESIDUAL_INVENTORY_RULES:
predicate = _compile_surface_residual_inventory(
check_id=check_id,
source_rule_type=source_rule_type,
subjects=subjects,
params=params,
decision=decision,
provenance=provenance,
)
validation = validate_executable_predicate(predicate)
if not validation.valid and predicate.get("status") == "executable":
predicate["status"] = "blocked_invalid"
predicate["reasons"] = list(dict.fromkeys((*predicate["reasons"], *validation.reasons)))
return predicate
if source_rule_type in DESTINATION_MEMBERSHIP_RULES:
predicate = _compile_destination_membership(
check_id=check_id,
source_rule_type=source_rule_type,
subjects=subjects,
params=params,
decision=decision,
provenance=provenance,
)
validation = validate_executable_predicate(predicate)
if not validation.valid and predicate.get("status") == "executable":
predicate["status"] = "blocked_invalid"
predicate["reasons"] = list(dict.fromkeys((*predicate["reasons"], *validation.reasons)))
return predicate
if source_rule_type in RELOCATION_TRANSITION_RULES:
predicate = _compile_relocation_transition(
check_id=check_id,
source_rule_type=source_rule_type,
subjects=subjects,
params=params,
decision=decision,
provenance=provenance,
)
validation = validate_executable_predicate(predicate)
if not validation.valid and predicate.get("status") == "executable":
predicate["status"] = "blocked_invalid"
predicate["reasons"] = list(dict.fromkeys((*predicate["reasons"], *validation.reasons)))
return predicate
if source_rule_type in CROSS_IMAGE_INVENTORY_RULES:
predicate = _compile_cross_image_inventory(
check_id=check_id,
source_rule_type=source_rule_type,
subjects=subjects,
decision=decision,
provenance=provenance,
)
validation = validate_executable_predicate(predicate)
if not validation.valid and predicate.get("status") == "executable":
predicate["status"] = "blocked_invalid"
predicate["reasons"] = list(dict.fromkeys((*predicate["reasons"], *validation.reasons)))
return predicate
if source_rule_type in FIXED_LOCATION_PRESERVATION_RULES:
predicate = _compile_fixed_location_preservation(
check_id=check_id,
source_rule_type=source_rule_type,
subjects=subjects,
decision=decision,
provenance=provenance,
)
validation = validate_executable_predicate(predicate)
if not validation.valid and predicate.get("status") == "executable":
predicate["status"] = "blocked_invalid"
predicate["reasons"] = list(dict.fromkeys((*predicate["reasons"], *validation.reasons)))
return predicate
if source_rule_type in OCR_TEXT_RULES:
predicate = _compile_ocr_text_predicate(
check_id=check_id,
source_rule_type=source_rule_type,
subjects=subjects,
params=params,
decision=decision,
provenance=provenance,
)
validation = validate_executable_predicate(predicate)
if not validation.valid and predicate.get("status") == "executable":
predicate["status"] = "blocked_invalid"
predicate["reasons"] = list(dict.fromkeys((*predicate["reasons"], *validation.reasons)))
return predicate
if source_rule_type in SOURCE_DISPLACEMENT_RULES:
predicate = _compile_source_displacement(
check_id=check_id,
source_rule_type=source_rule_type,
subjects=subjects,
decision=decision,
provenance=provenance,
)
validation = validate_executable_predicate(predicate)
if not validation.valid and predicate.get("status") == "executable":
predicate["status"] = "blocked_invalid"
predicate["reasons"] = list(dict.fromkeys((*predicate["reasons"], *validation.reasons)))
return predicate
if source_rule_type in SOURCE_REGION_RESTORATION_RULES:
predicate = _compile_source_region_restoration(
check_id=check_id,
source_rule_type=source_rule_type,
subjects=subjects,
decision=decision,
provenance=provenance,
)
validation = validate_executable_predicate(predicate)
if not validation.valid and predicate.get("status") == "executable":
predicate["status"] = "blocked_invalid"
predicate["reasons"] = list(dict.fromkeys((*predicate["reasons"], *validation.reasons)))
return predicate
if source_rule_type in INSTANCE_CLUSTER_GROUPING_RULES:
predicate = _compile_instance_cluster_grouping(
check_id=check_id,
source_rule_type=source_rule_type,
subjects=subjects,
params=params,
decision=decision,
provenance=provenance,
)
validation = validate_executable_predicate(predicate)
if not validation.valid and predicate.get("status") == "executable":
predicate["status"] = "blocked_invalid"
predicate["reasons"] = list(dict.fromkeys((*predicate["reasons"], *validation.reasons)))
return predicate
if source_rule_type in PROTECTED_SET_EXCLUSION_RULES | CLUSTER_SUBJECT_SEPARATION_RULES:
predicate = _compile_small_animal_set_geometry(
check_id=check_id,
source_rule_type=source_rule_type,
subjects=subjects,
params=params,
decision=decision,
provenance=provenance,
)
validation = validate_executable_predicate(predicate)
if not validation.valid and predicate.get("status") == "executable":
predicate["status"] = "blocked_invalid"
predicate["reasons"] = list(dict.fromkeys((*predicate["reasons"], *validation.reasons)))
return predicate
if source_rule_type in STRUCTURED_CHECK_RULES:
predicate = _compile_structured_check(
check_id=check_id,
source_rule_type=source_rule_type,
subjects=subjects,
params=params,
decision=decision,
provenance=provenance,
)
validation = validate_executable_predicate(predicate)
if not validation.valid and predicate.get("status") == "executable":
predicate["status"] = "blocked_invalid"
predicate["reasons"] = list(dict.fromkeys((*predicate["reasons"], *validation.reasons)))
return predicate
# All previously registered deterministic metrics are represented as a
# typed operator bridge. The bridge consumes only predicate operations,
# typed regions, and normalized parameters; legacy tool prose is never
# consulted by the lowerer.
from pvr_eval.agent.contract_metric_binding import ( # local import avoids module-init cycle
REGISTERED_RULE_TYPES,
canonical_rule_type as canonicalize_rule_type,
metric_contract_compliance,
metric_capability,
)
canonical = canonicalize_rule_type(source_rule_type)
if canonical in REGISTERED_RULE_TYPES and source_rule_type not in SOURCE_REGION_CLEARANCE_RULES:
compliance = metric_contract_compliance(
source_rule_type,
_mapping(decision.get("parameters")),
decision,
)
predicate = _compile_registered_metric_bridge(
check_id=check_id,
source_rule_type=source_rule_type,
canonical_rule_type=canonical,
subjects=subjects,
params=params,
decision=decision,
provenance=provenance,
capability=metric_capability(canonical),
)
predicate["contract_compliance"] = compliance
if compliance.get("status") != "compliant":
predicate["status"] = "blocked_uncompiled"
predicate["reasons"] = list(
dict.fromkeys(
(
*predicate.get("reasons", []),
"contract_handler_incompatible",
*[str(item) for item in compliance.get("risk_flags", [])],
)
)
)
validation = validate_executable_predicate(predicate)
if not validation.valid and predicate.get("status") == "executable":
predicate["status"] = "blocked_invalid"
predicate["reasons"] = list(dict.fromkeys((*predicate["reasons"], *validation.reasons)))
return predicate
if source_rule_type not in SOURCE_REGION_CLEARANCE_RULES:
subjective_rules = {
"semantic_physical_overlap_plausibility",
"relocated_item_perspective_plausibility",
"physical_support_and_nonintersection",
"flight_posture_semantic_classification",
"localized_inpainting_artifact_classification",
"species_support_plausibility",
"per_instance_support_plausibility",
"vacated_patch_artifact_audit",
"folded_chair_physical_state",
"localized_background_reconstruction_quality",
"supported_nonintersecting_placement",
}
manual = str(check.get("checker") or params.get("resolved_plan_checker") or "") == "vlm_audit" or source_rule_type in subjective_rules
return _blocked(
check_id=check_id,
source_rule_type=source_rule_type,
family="",
subjects=subjects,
reasons=[("manual_review_required:" if manual else "predicate_family_not_compiled:") + (source_rule_type or "missing_decision_rule")],
provenance=provenance,
status="manual_review_required" if manual else "blocked_uncompiled",
)
raw = _mapping(decision.get("parameters"))
expected_count, expected_key = _positive_int(
raw, "expected_source_count", "expected_input_count", "required_removed_count_for_pass"
)
if expected_count <= 0:
if source_rule_type in {"counted_pair_removal", "paired_zoned_instance_removal"}:
expected_count, expected_key = 2, "derived:paired_rule"
elif source_rule_type in {
"source_zone_vacancy",
"zoned_instance_absence_with_residual_test",
"small_zoned_instance_absence_with_residual_test",
}:
expected_count, expected_key = 1, "derived:single_source_rule"
output_score, output_score_key = _number(
raw,
(
"minimum_detection_confidence",
"output_detection_confidence",
"output_detection_confidence_fail",
"per_item_detection_confidence_fail",
"minimum_detector_confidence",
"output_bird_detection_threshold",
),
0.15,
)
input_score, input_score_key = _number(
raw,
("source_input_minimum_detector_confidence", "input_detection_confidence"),
min(0.05, output_score),
)
source_overlap, source_overlap_key = _number(
raw,
(
"source_overlap_threshold",
"zone_containment_threshold",
),
0.15,
)
pass_residual, pass_residual_key = _number(
raw,
("pass_residual_fraction_max", "pass_max_residual_ratio"),
0.0,
)
partial_residual, partial_residual_key = _number(
raw,
(
"partial_residual_fraction_max",
"partial_max_residual_ratio",
"residual_mask_fraction_partial",
"per_item_residual_fraction_partial",
"orange_residual_fraction_partial",
),
max(pass_residual, 0.03),
)
intact_residual, intact_residual_key = _number(
raw,
(
"intact_mask_fraction_fail",
"per_item_intact_mask_fraction_fail",
"fail_min_residual_ratio",
"substantial_zone_overlap",
),
max(0.25, partial_residual),
)
supported_by_rule = {
"colored_container_visibility_count": {
"expected_source_count", "minimum_detection_confidence", "source_zone_vacancy_required_for_pass",
"confirm_with_color_and_shape", "full_frame_search", "closed_cabinet_storage_counts_as_not_visible",
"source_anchor_query",
},
"paired_zoned_instance_removal": {
"required_removed_count_for_pass", "per_item_detection_confidence_fail",
"per_item_intact_mask_fraction_fail", "per_item_residual_fraction_partial", "zone_expansion_pixels",
},
"counted_pair_removal": {
"expected_input_count", "fail_output_count_min", "orange_residual_fraction_partial",
"output_detection_confidence", "partial_output_count", "pass_output_count", "zone_expansion_pixels",
},
"source_zone_vacancy": {
"output_bird_detection_threshold", "partial_residual_fraction_max", "pass_residual_fraction_max",
"substantial_zone_overlap", "minimum_detector_confidence", "pass_max_residual_ratio",
"fail_min_residual_ratio", "registration_tolerance_pixels", "source_clearance_profile",
"source_selector_profile", "source_selector",
},
"zoned_instance_absence_with_residual_test": {
"intact_mask_fraction_fail", "output_detection_confidence_fail", "query_aliases_equivalent",
"residual_mask_fraction_partial", "zone_expansion_pixels", "registration_required",
"registration_tolerance_pixels",
},
"small_zoned_instance_absence_with_residual_test": {
"intact_mask_fraction_fail", "output_detection_confidence_fail", "residual_mask_fraction_partial",
"use_color_guided_proposals", "zone_expansion_pixels",
},
}
consumed = set(supported_by_rule.get(source_rule_type, set()))
semantic_keys = {
"confirm_with_color_and_shape",
"full_frame_search",
"source_zone_vacancy_required_for_pass",
"closed_cabinet_storage_counts_as_not_visible",
"source_anchor_query",
}
consumed.update(key for key in semantic_keys if key in raw)
unmapped = sorted(set(raw) - consumed)
reasons = _source_scope_conflicts(decision)
source_selector_raw = raw.get("source_selector")
source_selector = dict(source_selector_raw) if isinstance(source_selector_raw, Mapping) else {}
source_selector_profile = str(
raw.get("source_selector_profile") or source_selector.get("profile") or ""
)
if source_selector_profile:
source_selector["profile"] = source_selector_profile
identity_queries = _dedupe_text(_list(source_selector.get("identity_queries")))
anchor_queries = _dedupe_text(_list(source_selector.get("anchor_queries")))
anchor_part = str(source_selector.get("anchor_part") or "")
relation = str(source_selector.get("relation") or "")
selector_expected_count = int(source_selector.get("expected_count") or 0)
if source_rule_type != "source_zone_vacancy":
reasons.append("source_selector_rule_unsupported")
if source_selector_profile != ANCHOR_RELATIVE_SOURCE_INSTANCE_PROFILE:
reasons.append("source_selector_profile_unsupported")
if not identity_queries or not anchor_queries:
reasons.append("source_selector_queries_missing")
if anchor_part not in SUPPORTED_ANCHOR_PARTS:
reasons.append("source_selector_anchor_part_unsupported")
if relation != "contact_or_near":
reasons.append("source_selector_relation_unsupported")
if selector_expected_count != 1 or expected_count != 1:
reasons.append("source_selector_expected_count_unsupported")
source_selector.update(
{
"identity_queries": identity_queries,
"anchor_queries": anchor_queries,
"anchor_part": anchor_part,
"relation": relation,
"expected_count": selector_expected_count,
}
)
if identity_queries:
subjects = identity_queries
elif (
source_rule_type == "source_zone_vacancy"
and bool(subjects)
and is_relational_identity_text(subjects[0])
):
reasons.append("relational_identity_without_typed_selector")
requested_clearance_profile = str(raw.get("source_clearance_profile") or "")
clearance_profile_parameters: dict[str, Any] = {}
if requested_clearance_profile:
if (
source_rule_type == "source_zone_vacancy"
and requested_clearance_profile == SHELF_SOURCE_GROUP_CLEARANCE_PROFILE
):
clearance_profile_parameters = shelf_source_group_clearance_profile_parameters(
requested_clearance_profile
)
else:
reasons.append("source_clearance_profile_unsupported")
if not check_id:
reasons.append("missing_check_id")
if not subjects:
reasons.append("missing_subject_queries")
if expected_count <= 0:
reasons.append("expected_source_count_not_compiled")
if unmapped:
reasons.append("unmapped_contract_parameters")
if raw.get("source_zone_vacancy_required_for_pass") is False:
reasons.append("source_vacancy_not_required_by_contract")
subject_groups = _source_subject_groups(
subjects,
source_rule_type=source_rule_type,
expected_count=expected_count,
raw=raw,
)
normalized = {
"expected_source_count": expected_count,
"subject_groups": _public_subject_groups(subject_groups),
"minimum_detection_confidence": output_score,
"source_input_minimum_detector_confidence": input_score,
"source_overlap_threshold": source_overlap,
"pass_source_residual_fraction_max": pass_residual,
"partial_source_residual_fraction_max": partial_residual,
"intact_source_residual_fraction_min": intact_residual,
"source_zone_dilation_pixels": int(raw.get("zone_expansion_pixels", 0)),
"registration_required": bool(
raw.get("registration_required", False) or clearance_profile_parameters
),
"registration_tolerance_pixels": int(raw.get("registration_tolerance_pixels", 0)),
"registration_method": "robust_static_background_alignment",
"confirm_with_color_and_shape": bool(raw.get("confirm_with_color_and_shape", False)),
"full_frame_search": bool(raw.get("full_frame_search", True)),
"require_tiled_search_for_negative": True,
"source_zone_vacancy_required_for_pass": bool(
raw.get("source_zone_vacancy_required_for_pass", True)
),
"closed_cabinet_storage_counts_as_not_visible": bool(
raw.get("closed_cabinet_storage_counts_as_not_visible", False)
),
"query_aliases_equivalent": bool(raw.get("query_aliases_equivalent", False)),
"use_color_guided_proposals": bool(raw.get("use_color_guided_proposals", False)),
"source_zone": {
"method": "per_instance_input_mask_or_bbox",
"description": "Each detected input target instance defines its own source footprint.",
},
**({
"source_selector_profile": source_selector_profile,
"source_selector": source_selector,
} if source_selector_profile else {}),
**clearance_profile_parameters,
}
shelf_source_region = {
"region_id": "lower_shelf_source_compartment",
"semantic_role": "source_region",
"image_roles": ["input", "pred"],
"source_image": "both",
"proposal_method": "grid_parser",
"query_or_rule": (
"Within the left shelving unit, select the lower compartment below the "
"horizontal shelf divider that contains the input binder group; transfer "
"the corresponding cell through registered shelf-grid pairing."
),
"materializer": {
"kind": "shelf_grid_parser",
"queries": ["shelving unit", "shelf compartment"],
"geometry_policy": "registered_rectified_compartment_grid",
"region_rule": (
"Within the left shelving unit, select the lower compartment below the "
"horizontal shelf divider that contains the input binder group."
),
},
"geometry_policy": "registered_rectified_compartment_grid",
"provenance": "registered source-clearance profile",
}
predicate = {
"schema_version": EXECUTABLE_PREDICATE_SCHEMA_VERSION,
"check_id": check_id,
"status": "executable" if not reasons else "blocked_uncompiled",
"family": "source_region_clearance",
"source_rule_type": source_rule_type,
"subjects": subject_groups,
"regions": (
[shelf_source_region]
if clearance_profile_parameters
else [normalized["source_zone"]]
),
"operations": [
_operation(
"detect_input_targets",
"object_detection",
"detector",
("input",),
parameters={"queries_from": "subjects"},
produces=("input_target_boxes",),
),
_operation(
"refine_input_targets",
"mask_refinement",
"segmenter",
("input",),
depends_on=("detect_input_targets",),
produces=("input_target_masks",),
),
*([
_operation(
"detect_source_anchor",
"object_detection",
"detector",
("input",),
parameters={"queries": source_selector.get("anchor_queries", []), "evidence_role": "source_selector_anchor"},
produces=("source_anchor_boxes",),
),
_operation(
"refine_source_anchor",
"mask_refinement",
"segmenter",
("input",),
depends_on=("detect_source_anchor",),
produces=("source_anchor_masks",),
),
_operation(
"select_source_instance",
"source_instance_selection",
"source_instance_selector",
("input",),
depends_on=("refine_input_targets", "refine_source_anchor"),
parameters=source_selector,
produces=("source_selector_certificate",),
),
] if source_selector_profile else []),
_operation(
"detect_output_targets",
"object_detection",
"detector",
("pred",),
parameters={"queries_from": "subjects", "search_scopes": ["full_frame", "tiled"]},
produces=("output_target_boxes", "detector_search_coverage"),
),
_operation(
"refine_output_targets",
"mask_refinement",
"segmenter",
("pred",),
depends_on=("detect_output_targets",),
produces=("output_target_masks",),
),
*([
_operation(
"register_source",
"image_registration",
"registration",
("input", "pred"),
produces=("input_to_output_transform",),
)
] if normalized["registration_required"] else []),
*([
_operation(
"materialize_source_shelf",
"region_resolution",
"typed_region_materializer",
("input", "pred"),
produces=("typed_regions", "registered_shelf_grid_pair"),
)
] if clearance_profile_parameters else []),
_operation(
"match_target_instances",
"instance_matching",
"matcher",
("input", "pred"),
depends_on=("refine_input_targets", "refine_output_targets"),
optional=True,
produces=("instance_matches",),
),
_operation(
"classify_source_states",
"source_state_classification",
"predicate_interpreter",
("input", "pred"),
depends_on=(
"refine_input_targets",
"refine_output_targets",
"detect_output_targets",
*(["select_source_instance"] if source_selector_profile else []),
*(["materialize_source_shelf"] if clearance_profile_parameters else []),
),
produces=("per_target_source_state",),
),
_operation(
"decide",
"predicate_decision",
"predicate_interpreter",
("input", "pred"),
depends_on=("classify_source_states",),
produces=("check_result",),
),
],
"state_schema": {
"unit": "source_target_instance",
"states": ["not_moved", "partial_residual", "moved", "deleted_or_invisible", "unknown"],
"not_moved": "A compatible output target overlaps its own input source footprint.",
"moved": "A compatible output target is detected only outside its source footprint.",
"deleted_or_invisible": "No accepted target remains after complete DINO+YOLO full-frame and tiled search.",
"unknown": "Input identity, source geometry, or negative search coverage is insufficient.",
},
"decision": {
"pass": {"remaining_source_count": 0, "partial_source_count": 0, "unresolved_source_count": 0},
"partial": {
"any": [
{
"remaining_source_count": {"minimum": 1, "maximum": max(0, expected_count - 1)},
"unresolved_source_count": 0,
},
{"partial_source_count": {"minimum": 1}, "unresolved_source_count": 0},
],
},
"fail": {"remaining_source_count": expected_count, "unresolved_source_count": 0},
"unknown": {"unresolved_source_count": {"minimum": 1}},
},
"parameters": normalized,
"parameter_provenance": {
"expected_source_count": expected_key or "default_missing",
"minimum_detection_confidence": output_score_key or "default:0.15",
"source_input_minimum_detector_confidence": input_score_key or f"default:{input_score}",
"source_overlap_threshold": source_overlap_key or "default:0.15",
"pass_source_residual_fraction_max": pass_residual_key or "default:0",
"partial_source_residual_fraction_max": partial_residual_key or "default:max(pass,0.03)",
"intact_source_residual_fraction_min": intact_residual_key or "default:max(0.25,partial)",
"source_zone_dilation_pixels": "zone_expansion_pixels" if "zone_expansion_pixels" in raw else "default:0",
"registration_required": "registration_required" if "registration_required" in raw else "default:false",
"registration_tolerance_pixels": (
"registration_tolerance_pixels" if "registration_tolerance_pixels" in raw else "default:0"
),
"source_anchor_query": "source_anchor_query" if raw.get("source_anchor_query") else "identity_query_only",
**({
"source_selector_profile": "decision_rule.parameters.source_selector_profile",
"source_selector": "decision_rule.parameters.source_selector",
} if source_selector_profile else {}),
**({
"source_clearance_profile": "decision_rule.parameters.source_clearance_profile",
"source_clearance_executor_version": "registered_metric_profile",
} if clearance_profile_parameters else {}),
},
"unmapped_contract_parameters": unmapped,
"reasons": list(dict.fromkeys(reasons)),
"provenance": provenance,
}
validation = validate_executable_predicate(predicate)
if not validation.valid:
predicate["status"] = "blocked_invalid"
predicate["reasons"] = list(dict.fromkeys((*predicate["reasons"], *validation.reasons)))
return predicate
def validate_executable_predicate(predicate: Mapping[str, Any]) -> PredicateValidation:
"""Validate structure and operation dependencies without executing tools."""
reasons: list[str] = []
if predicate.get("schema_version") != EXECUTABLE_PREDICATE_SCHEMA_VERSION:
reasons.append("unsupported_predicate_schema")
if not str(predicate.get("check_id") or "").strip():
reasons.append("missing_check_id")
status = str(predicate.get("status") or "")
if status not in {"executable", "blocked_uncompiled", "blocked_invalid", "manual_review_required"}:
reasons.append("invalid_predicate_status")
operations = _list(predicate.get("operations"))
if status == "executable" and not operations:
reasons.append("executable_predicate_has_no_operations")
operation_ids: set[str] = set()
for item in operations:
if not isinstance(item, Mapping):
reasons.append("operation_is_not_object")
continue
operation_id = str(item.get("id") or "")
kind = str(item.get("kind") or "")
if not operation_id:
reasons.append("operation_missing_id")
elif operation_id in operation_ids:
reasons.append("duplicate_operation_id:" + operation_id)
operation_ids.add(operation_id)
if kind not in PREDICATE_OPERATION_KINDS:
reasons.append("unsupported_operation_kind:" + kind)
for item in operations:
if not isinstance(item, Mapping):
continue
for dependency in _list(item.get("depends_on")):
if str(dependency) not in operation_ids:
reasons.append(f"missing_operation_dependency:{item.get('id', '')}:{dependency}")
if status == "executable":
if not _list(predicate.get("subjects")):
reasons.append("executable_predicate_has_no_subjects")
if not isinstance(predicate.get("decision"), Mapping) or not predicate.get("decision"):
reasons.append("executable_predicate_has_no_decision_table")
if _list(predicate.get("unmapped_contract_parameters")):
reasons.append("executable_predicate_has_unmapped_parameters")
if str(predicate.get("family") or "") == "registered_metric_bridge":
state_schema = predicate.get("state_schema") if isinstance(predicate.get("state_schema"), Mapping) else {}
decision = predicate.get("decision") if isinstance(predicate.get("decision"), Mapping) else {}
decide_operations = [
item for item in operations
if isinstance(item, Mapping) and str(item.get("kind") or "") == "predicate_decision"
]
versions = {
str(state_schema.get("operator_version") or ""),
str(decision.get("operator_version") or ""),
*{
str((item.get("parameters") or {}).get("operator_version") or "")
for item in decide_operations
if isinstance(item.get("parameters"), Mapping)
},
}
if versions != {REGISTERED_METRIC_OPERATOR_VERSION}:
reasons.append("stale_registered_metric_operator_version")
return PredicateValidation(not reasons, tuple(dict.fromkeys(reasons)))
|