diff --git a/root/specialists/rel-paintings/organ_relation_v2.py b/root/specialists/rel-paintings/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-paintings/organ_relation_v2.py +++ b/root/specialists/rel-paintings/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-parks/organ_relation_v2.py b/root/specialists/rel-parks/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-parks/organ_relation_v2.py +++ b/root/specialists/rel-parks/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-parties/organ_relation_v2.py b/root/specialists/rel-parties/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-parties/organ_relation_v2.py +++ b/root/specialists/rel-parties/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-pharmacists/organ_relation_v2.py b/root/specialists/rel-pharmacists/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-pharmacists/organ_relation_v2.py +++ b/root/specialists/rel-pharmacists/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-philosophers/organ_relation_v2.py b/root/specialists/rel-philosophers/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-philosophers/organ_relation_v2.py +++ b/root/specialists/rel-philosophers/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-photographers/organ_relation_v2.py b/root/specialists/rel-photographers/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-photographers/organ_relation_v2.py +++ b/root/specialists/rel-photographers/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-physicians/organ_relation_v2.py b/root/specialists/rel-physicians/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-physicians/organ_relation_v2.py +++ b/root/specialists/rel-physicians/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-physicists/organ_relation_v2.py b/root/specialists/rel-physicists/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-physicists/organ_relation_v2.py +++ b/root/specialists/rel-physicists/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-planets/organ_relation_v2.py b/root/specialists/rel-planets/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-planets/organ_relation_v2.py +++ b/root/specialists/rel-planets/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-playwrights/organ_relation_v2.py b/root/specialists/rel-playwrights/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-playwrights/organ_relation_v2.py +++ b/root/specialists/rel-playwrights/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-poems/organ_relation_v2.py b/root/specialists/rel-poems/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-poems/organ_relation_v2.py +++ b/root/specialists/rel-poems/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-poets/organ_relation_v2.py b/root/specialists/rel-poets/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-poets/organ_relation_v2.py +++ b/root/specialists/rel-poets/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-police/organ_relation_v2.py b/root/specialists/rel-police/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-police/organ_relation_v2.py +++ b/root/specialists/rel-police/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-politicians/organ_relation_v2.py b/root/specialists/rel-politicians/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-politicians/organ_relation_v2.py +++ b/root/specialists/rel-politicians/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-printmakers/organ_relation_v2.py b/root/specialists/rel-printmakers/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-printmakers/organ_relation_v2.py +++ b/root/specialists/rel-printmakers/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-psychologists/organ_relation_v2.py b/root/specialists/rel-psychologists/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-psychologists/organ_relation_v2.py +++ b/root/specialists/rel-psychologists/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-racketsports/organ_relation_v2.py b/root/specialists/rel-racketsports/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-racketsports/organ_relation_v2.py +++ b/root/specialists/rel-racketsports/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-religions/organ_relation_v2.py b/root/specialists/rel-religions/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-religions/organ_relation_v2.py +++ b/root/specialists/rel-religions/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-rivers/organ_relation_v2.py b/root/specialists/rel-rivers/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-rivers/organ_relation_v2.py +++ b/root/specialists/rel-rivers/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-rowers/organ_relation_v2.py b/root/specialists/rel-rowers/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-rowers/organ_relation_v2.py +++ b/root/specialists/rel-rowers/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-rugby/organ_relation_v2.py b/root/specialists/rel-rugby/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-rugby/organ_relation_v2.py +++ b/root/specialists/rel-rugby/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-sculptors/organ_relation_v2.py b/root/specialists/rel-sculptors/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-sculptors/organ_relation_v2.py +++ b/root/specialists/rel-sculptors/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-sculptures/organ_relation_v2.py b/root/specialists/rel-sculptures/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-sculptures/organ_relation_v2.py +++ b/root/specialists/rel-sculptures/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-ships/organ_relation_v2.py b/root/specialists/rel-ships/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-ships/organ_relation_v2.py +++ b/root/specialists/rel-ships/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-shooters/organ_relation_v2.py b/root/specialists/rel-shooters/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-shooters/organ_relation_v2.py +++ b/root/specialists/rel-shooters/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-singers/organ_relation_v2.py b/root/specialists/rel-singers/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-singers/organ_relation_v2.py +++ b/root/specialists/rel-singers/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-skaters/organ_relation_v2.py b/root/specialists/rel-skaters/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-skaters/organ_relation_v2.py +++ b/root/specialists/rel-skaters/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-skiers/organ_relation_v2.py b/root/specialists/rel-skiers/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-skiers/organ_relation_v2.py +++ b/root/specialists/rel-skiers/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-skyscrapers/organ_relation_v2.py b/root/specialists/rel-skyscrapers/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-skyscrapers/organ_relation_v2.py +++ b/root/specialists/rel-skyscrapers/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-snooker/organ_relation_v2.py b/root/specialists/rel-snooker/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-snooker/organ_relation_v2.py +++ b/root/specialists/rel-snooker/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-software/organ_relation_v2.py b/root/specialists/rel-software/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-software/organ_relation_v2.py +++ b/root/specialists/rel-software/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-songs/organ_relation_v2.py b/root/specialists/rel-songs/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-songs/organ_relation_v2.py +++ b/root/specialists/rel-songs/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-spacecraft/organ_relation_v2.py b/root/specialists/rel-spacecraft/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-spacecraft/organ_relation_v2.py +++ b/root/specialists/rel-spacecraft/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-speedskaters/organ_relation_v2.py b/root/specialists/rel-speedskaters/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-speedskaters/organ_relation_v2.py +++ b/root/specialists/rel-speedskaters/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-spies/organ_relation_v2.py b/root/specialists/rel-spies/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-spies/organ_relation_v2.py +++ b/root/specialists/rel-spies/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-sportsevents/organ_relation_v2.py b/root/specialists/rel-sportsevents/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-sportsevents/organ_relation_v2.py +++ b/root/specialists/rel-sportsevents/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-sportsteams/organ_relation_v2.py b/root/specialists/rel-sportsteams/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-sportsteams/organ_relation_v2.py +++ b/root/specialists/rel-sportsteams/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-stadiums/organ_relation_v2.py b/root/specialists/rel-stadiums/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-stadiums/organ_relation_v2.py +++ b/root/specialists/rel-stadiums/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-stations/organ_relation_v2.py b/root/specialists/rel-stations/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-stations/organ_relation_v2.py +++ b/root/specialists/rel-stations/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-statisticians/organ_relation_v2.py b/root/specialists/rel-statisticians/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-statisticians/organ_relation_v2.py +++ b/root/specialists/rel-statisticians/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-swimmers/organ_relation_v2.py b/root/specialists/rel-swimmers/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-swimmers/organ_relation_v2.py +++ b/root/specialists/rel-swimmers/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-temples/organ_relation_v2.py b/root/specialists/rel-temples/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-temples/organ_relation_v2.py +++ b/root/specialists/rel-temples/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-tennis/organ_relation_v2.py b/root/specialists/rel-tennis/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-tennis/organ_relation_v2.py +++ b/root/specialists/rel-tennis/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-theatres/organ_relation_v2.py b/root/specialists/rel-theatres/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-theatres/organ_relation_v2.py +++ b/root/specialists/rel-theatres/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-themeparks/organ_relation_v2.py b/root/specialists/rel-themeparks/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-themeparks/organ_relation_v2.py +++ b/root/specialists/rel-themeparks/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-theologians/organ_relation_v2.py b/root/specialists/rel-theologians/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-theologians/organ_relation_v2.py +++ b/root/specialists/rel-theologians/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-tradeunionists/organ_relation_v2.py b/root/specialists/rel-tradeunionists/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-tradeunionists/organ_relation_v2.py +++ b/root/specialists/rel-tradeunionists/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-translators/organ_relation_v2.py b/root/specialists/rel-translators/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-translators/organ_relation_v2.py +++ b/root/specialists/rel-translators/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-triathletes/organ_relation_v2.py b/root/specialists/rel-triathletes/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-triathletes/organ_relation_v2.py +++ b/root/specialists/rel-triathletes/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-tvproducers/organ_relation_v2.py b/root/specialists/rel-tvproducers/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-tvproducers/organ_relation_v2.py +++ b/root/specialists/rel-tvproducers/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-tvseries-v2/organ_relation_v2.py b/root/specialists/rel-tvseries-v2/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-tvseries-v2/organ_relation_v2.py +++ b/root/specialists/rel-tvseries-v2/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-universities/organ_relation_v2.py b/root/specialists/rel-universities/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-universities/organ_relation_v2.py +++ b/root/specialists/rel-universities/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-videogames/organ_relation_v2.py b/root/specialists/rel-videogames/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-videogames/organ_relation_v2.py +++ b/root/specialists/rel-videogames/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-volleyball/organ_relation_v2.py b/root/specialists/rel-volleyball/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-volleyball/organ_relation_v2.py +++ b/root/specialists/rel-volleyball/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-wars/organ_relation_v2.py b/root/specialists/rel-wars/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-wars/organ_relation_v2.py +++ b/root/specialists/rel-wars/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-waterpolo/organ_relation_v2.py b/root/specialists/rel-waterpolo/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-waterpolo/organ_relation_v2.py +++ b/root/specialists/rel-waterpolo/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/specialists/rel-youtubers/organ_relation_v2.py b/root/specialists/rel-youtubers/organ_relation_v2.py index c52a1f7777a1aeb1e62b6fcd4b07b98768610cbd..c93bff05fb3d165d269740788fde58fc91ab12c0 100644 --- a/root/specialists/rel-youtubers/organ_relation_v2.py +++ b/root/specialists/rel-youtubers/organ_relation_v2.py @@ -42,8 +42,11 @@ class RelationOrganV2: rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] - return {"kind": "unverified", "status": "withheld", "value": None, - "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + result = {"kind": "unverified", "status": "withheld", "value": None, + "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} + if a.get("reason") == "ambiguous_inverse_target": + result["reason"] = "ambiguous_inverse_target" + return result subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": diff --git a/root/textbooks/textbook_store_v1.sqlite3 b/root/textbooks/textbook_store_v1.sqlite3 new file mode 100644 index 0000000000000000000000000000000000000000..f7f49a463e33964051a53ae1e15cc7b6c2f1f579 Binary files /dev/null and b/root/textbooks/textbook_store_v1.sqlite3 differ diff --git a/root/wander-train/date_precision_v1.py b/root/wander-train/date_precision_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..f1ef54e15e7a01738c8515dab81e7d1df02309bd --- /dev/null +++ b/root/wander-train/date_precision_v1.py @@ -0,0 +1,355 @@ +"""Untrusted date rendering over source-bound metadata; no historical truth proof. + +Legacy timestamps are not precision declarations. A versioned sidecar binds an +entity/property/literal to same-revision Wikidata JSON and RDF statements. Missing, +invalid or conflicting metadata is exposed, never guessed from day/month digits. + +Maintainer amendment (10.1): a pair the sidecar does not cover is rendered from its +digits only as far as the digits can carry. Wikidata serialises a coarser precision +with day 01 (month) or 01-01 (year), so a day other than the 1st can only come from a +day-precision statement, while a 1st may be a placeholder. From 1583 on, the stored +value is a Gregorian date: a day other than the 1st is given whole, a 1st gives the +month and year, and 1 January gives the year. Earlier and BCE values decline, because +their calendar and precision cannot be read from the digits. A pair the sidecar does +cover but whose literal it cannot bind still declines. +""" +import json +import os +from pathlib import Path +import re + +TIME = re.compile(r'^([+-]?)(\d{1,16})-(\d{2})-(\d{2})T\d{2}:\d{2}:\d{2}Z$') +CALENDARS = {'http://www.wikidata.org/entity/Q1985727': 'Gregorian', + 'http://www.wikidata.org/entity/Q1985786': 'Julian'} +MONTHS = ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December') +QUALIFIER_NAMES = {'P1480': 'sourcing circumstances', 'P4241': 'date refinement', + 'P1319': 'earliest date', 'P1326': 'latest date', 'P7452': 'preferred-rank reason', + 'P580': 'start time', 'P582': 'end time', 'P1013': 'criterion', 'P2241': 'deprecation reason'} +ITEM_NAMES = {'Q5727902': 'circa', 'Q18122778': 'presumably', 'Q18912752': 'disputed', + 'Q18195782': 'unspecified calendar', 'Q40719727': 'beginning of', + 'Q40719748': 'middle of', 'Q40719766': 'end of', 'Q40719687': 'first half', + 'Q40719707': 'second half', 'Q115018754': 'original value', 'Q111606173': 'most inclusive value'} +_CACHE = None + + +def is_time(value): + return isinstance(value, str) and TIME.fullmatch(value) is not None + + +def _load(): + global _CACHE + if _CACHE is not None: + return _CACHE + _CACHE = {} + path = Path(os.environ.get('ORACLE7_DATE_PRECISION', str(Path(os.environ.get('ORACLE7_ROOT', '/opt/oracle-clm'))/'relstore/date_precision_v1.json'))) + try: + if path.stat().st_size > 16*1024*1024: + return _CACHE + document = json.loads(path.read_text()) + if not isinstance(document, dict): + return _CACHE + if document.get('schema') != 'oracle7-date-precision-v1' or document.get('version') != 1: + return _CACHE + records = document['records'] + if not isinstance(records, list) or len(records) > 2048: + return _CACHE + for record in records: + if not isinstance(record, dict): + raise ValueError('record must be an object') + if not isinstance(record.get('statements'), list) or not isinstance(record.get('bindings'), list): + raise ValueError('statements/bindings must be arrays') + if any(not isinstance(s, dict) for s in record['statements']+record['bindings']): + raise ValueError('statements/bindings must contain objects') + key = (record['subject'], record['property']) + if key in _CACHE: + _CACHE = {} + return _CACHE + if not re.fullmatch(r'Q[1-9][0-9]*', key[0]) or not re.fullmatch(r'P[1-9][0-9]*', key[1]): + raise ValueError('invalid record identity') + if len(record['statements']) > 100 or len(record['bindings']) > 100: + raise ValueError('record too large') + _CACHE[key] = record + except (OSError, ValueError, KeyError, TypeError, AttributeError): + _CACHE = {} + return _CACHE + + +def _qid(value, prefix): + return prefix+str(value) if type(value) is int else value + + +def selected(value, subject=None, property=None, calendar=None): + """Return matching best-rank source statements; no match is not a false fact.""" + if subject is None or property is None: + return [] + record = _load().get((_qid(subject, 'Q'), _qid(property, 'P'))) + if not record: + return [] + try: + statements = record['statements'] + if calendar is not None: + statements = [s for s in statements if s.get('mainsnak', {}).get('datavalue', {}).get('value', {}).get('calendarmodel') == calendar] + rank = 'preferred' if any(s.get('rank') == 'preferred' for s in statements) else 'normal' + ids = {b['statement_id'].lower() for b in record['bindings'] if b['legacy_literal'] == value} + out = [] + for statement in statements: + if statement.get('rank') != rank or statement.get('id', '').lower() not in ids: + continue + time = statement['mainsnak']['datavalue']['value'] + rdf = statement['rdf_time'] + if (rdf['timeValue'] != value or int(rdf['timePrecision']) != time['precision'] or + rdf['timeCalendarModel'] != time['calendarmodel'] or int(rdf['timeTimezone']) != time['timezone']): + return [] + if statement['mainsnak']['property'] != record['property'] or not statement['id'].lower().startswith(record['subject'].lower()+'$'): + return [] + # Rendering validates precision and calendar before using digits. + _format_time(time, '') + out.append(statement) + return out + except (ValueError, KeyError, TypeError, IndexError, AttributeError): + return [] + + +def _ordinal(n): + return str(n)+('th' if 10 <= n % 100 <= 20 else {1:'st', 2:'nd', 3:'rd'}.get(n % 10, 'th')) + + +def _parts(time): + match = TIME.fullmatch(time['time']) + precision = time['precision'] + if not match or type(precision) is not int or not 0 <= precision <= 11: + raise ValueError('unsupported time or precision') + if time['calendarmodel'] not in CALENDARS: + raise ValueError('unsupported calendar') + year, month, day = int(match[2]), int(match[3]), int(match[4]) + if year == 0: + raise ValueError('Wikibase JSON year zero has no historical interpretation') + if match[1] == '-': + year = -year + if not 0 <= month <= 12 or not 0 <= day <= 31: + raise ValueError('invalid date fields') + if precision >= 10 and month == 0 or precision >= 11 and day == 0: + raise ValueError('precision requires unavailable date fields') + if precision == 11: + astro = year if year > 0 else year + 1 + leap = astro % 4 == 0 and (time['calendarmodel'].endswith('Q1985786') or astro % 100 != 0 or astro % 400 == 0) + days = (31, 29 if leap else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) + if day > days[month-1]: + raise ValueError('invalid day for source calendar') + for field in ('before', 'after', 'timezone'): + if type(time.get(field)) is not int: + raise ValueError('missing uncertainty/timezone metadata') + if time['before'] < 0 or time['after'] < 0: + raise ValueError('negative uncertainty') + return year, month, day, precision + + +def _format_time(time, question): + year, month, day, precision = _parts(time) + y = str(abs(year))+(' BCE' if year < 0 else '') + wants_year = bool(re.search(r'\b(?:what|which) year\b|\bin what year\b|\byear (?:was|did|of)\b', question, re.I)) + wants_month = bool(re.search(r'\b(?:what|which) month\b', question, re.I)) + if precision >= 9 and wants_year: + body = y + elif precision == 11 and not wants_month: + body = f'{day} {MONTHS[month-1]} {y}' + elif precision >= 10: + body = f'{MONTHS[month-1]} {y}' + elif precision == 9: + body = y + elif precision == 8: + start = (abs(year)//10)*10 + body = f'{start}s'+(' BCE' if year < 0 else '') + elif precision in (6, 7): + unit = 100 if precision == 7 else 1000 + body = _ordinal((abs(year)-1)//unit+1)+(' century' if precision == 7 else ' millennium')+(' BCE' if year < 0 else '') + else: + body = f'around {y} (source resolution: {10**(9-precision):,} years)' + notes = [CALENDARS[time['calendarmodel']]+' calendar'] + if precision == 10 and not wants_year: + notes.append('day unspecified') + elif precision == 9 and not wants_year: + notes.append('month and day unspecified') + if time['before'] or time['after']: + notes.append(f"source uncertainty before={time['before']}, after={time['after']}, precision={precision}") + if time['timezone']: + notes.append(f"source timezone offset={time['timezone']}; not converted") + return body+' ('+'; '.join(notes)+')' + + +def _qualifiers(statement): + out = [] + for prop, snaks in sorted(statement.get('qualifiers', {}).items()): + values = [] + for snak in snaks: + if snak.get('snaktype') != 'value': + values.append(snak.get('snaktype', 'unknown')) + continue + value = snak.get('datavalue', {}).get('value') + if isinstance(value, dict) and 'time' in value: + values.append(_format_time(value, '')) + elif isinstance(value, dict) and 'id' in value: + values.append(ITEM_NAMES.get(value['id'], value['id'])) + else: + values.append(str(value)) + out.append(QUALIFIER_NAMES.get(prop, prop)+': '+', '.join(values)) + return out + + +def requested_calendar(question): + named = [uri for uri, label in CALENDARS.items() if re.search(r'\b'+label+r'\b', question, re.I)] + return named[0] if len(named) == 1 else None + + +def evidence(value, subject=None, property=None, question=''): + records = selected(value, subject, property, requested_calendar(question)) + record = _load().get((_qid(subject,'Q'), _qid(property,'P')), {}) + return {'status': 'source_metadata' if records else 'precision_unavailable', + 'legacy_literal': value, 'source': record.get('source'), + 'statements': [{'id': s['id'], 'rank': s['rank'], 'time': s['mainsnak']['datavalue']['value'], + 'qualifiers': s.get('qualifiers', {}), 'references': s.get('references', [])} for s in records]} + + +def _render(value, question='', subject=None, property=None): + if not is_time(value): + return value + statements = selected(value, subject, property, requested_calendar(question)) + if not statements: + if (_qid(subject, 'Q'), _qid(property, 'P')) in _load(): + return None + return _from_digits(value, question) + try: + rendered = [] + for statement in statements: + time = statement['mainsnak']['datavalue']['value'] + text = _format_time(time, question) + qualifiers = _qualifiers(statement) + if qualifiers: + text += '; '+ '; '.join(qualifiers) + if text not in rendered: + rendered.append(text) + if len(rendered) > 1: + return 'source records differ: '+' / '.join(rendered) + return rendered[0] + except (ValueError, KeyError, TypeError, IndexError, AttributeError): + return None + + +NOT_CONFIRMED = 'stored date; precision and calendar not source-confirmed' # 10.2: a date read from its digits says so (ember arlynx, issue #4) + + +def _from_digits(value, question=''): + """Maintainer amendment (10.1): an uncovered pair, read only as far as its digits can carry.""" + match = TIME.fullmatch(value) + if not match or match[1] == '-' or requested_calendar(question) not in (None, 'http://www.wikidata.org/entity/Q1985727'): + return None + year, month, day = int(match[2]), int(match[3]), int(match[4]) + if year < 1583 or not 1 <= month <= 12 or not 1 <= day <= 31: + return None + wants_year = bool(re.search(r'\b(?:what|which) year\b|\bin what year\b|\byear (?:was|did|of)\b', question, re.I)) + wants_month = bool(re.search(r'\b(?:what|which) month\b', question, re.I)) + if wants_year: + return f'{year} ({NOT_CONFIRMED})' + if month == 1 and day == 1: + return f'{year} ({NOT_CONFIRMED}; month and day not recorded in this store)' + if day == 1: + return f'{MONTHS[month-1]} {year} ({NOT_CONFIRMED}; day not recorded in this store)' + if wants_month: + return f'{MONTHS[month-1]} {year} ({NOT_CONFIRMED})' + return f'{day} {MONTHS[month-1]} {year} ({NOT_CONFIRMED})' + + +def render(value, question='', subject=None, property=None): + result = _render(value, question, subject, property) + return result if result is not None else f'date precision and calendar unavailable (stored timestamp: {value})' + + +def available(value, question='', subject=None, property=None): + """A route may assert a date only when its metadata can actually be rendered.""" + return _render(value, question, subject, property) is not None + + +def _time_interval(time): + """Inclusive calendar-local bounds; never converts between calendars.""" + year, month, day, precision = _parts(time) + if precision < 6 or time['before'] or time['after'] or time['timezone']: + return None + astro = lambda y: y if y > 0 else y + 1 + def last_day(y, m): + a = astro(y) + leap = a % 4 == 0 and (time['calendarmodel'].endswith('Q1985786') or a % 100 != 0 or a % 400 == 0) + return (31, 29 if leap else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)[m-1] + if precision == 11: + low = high = (astro(year), month, day) + elif precision == 10: + low, high = (astro(year), month, 1), (astro(year), month, last_day(year, month)) + elif precision == 9: + low, high = (astro(year), 1, 1), (astro(year), 12, 31) + elif precision == 8: + a = abs(year)//10*10 + ys = (a, a+9) if year > 0 else (-a-9, -a) + if 0 in ys: + return None + low, high = (astro(ys[0]), 1, 1), (astro(ys[1]), 12, 31) + else: + unit = 100 if precision == 7 else 1000 + n = (abs(year)-1)//unit+1 + ys = ((n-1)*unit+1, n*unit) if year > 0 else (-n*unit, -(n-1)*unit-1) + low, high = (astro(ys[0]), 1, 1), (astro(ys[1]), 12, 31) + return time['calendarmodel'], low, high + + +def _interval_from_digits(value): + """Maintainer amendment (10.1): bounds for an uncovered stored date, as wide as its digits leave open.""" + match = TIME.fullmatch(value) if isinstance(value, str) else None + if not match or match[1] == '-': + return None + year, month, day = int(match[2]), int(match[3]), int(match[4]) + if year < 1583 or not 1 <= month <= 12 or not 1 <= day <= 31: + return None + # 10.2: the digits are not a source, so the bounds are a year either side of the middle of the stored year; two such + # dates order only when their years differ by at least two + return 'http://www.wikidata.org/entity/Q1985727', (year - 1, 7, 1), (year + 1, 6, 30) + + +def interval(value, subject, property): + """Conservative bounds for ordering; uncertain/unknown qualifiers never prove order. + + Refinement can only narrow the coarse source period, so retaining that wider + period is safe. Explicit earliest/latest bounds narrow only in the same + calendar. Circa/disputed and unrecognized qualifiers remain unknown. + """ + records = selected(value, subject, property) + if not records: + if subject is None or property is None or (_qid(subject, 'Q'), _qid(property, 'P')) in _load(): + return None + return _interval_from_digits(value) + intervals = [] + try: + for record in records: + qualifiers = record.get('qualifiers', {}) + if set(qualifiers) - {'P4241', 'P7452', 'P1319', 'P1326'}: + return None + bounds = _time_interval(record['mainsnak']['datavalue']['value']) + if bounds is None: + return None + calendar, low, high = bounds + for prop in ('P1319', 'P1326'): + for snak in qualifiers.get(prop, []): + if snak.get('snaktype') != 'value' or snak.get('datavalue', {}).get('type') != 'time': + return None + bound = _time_interval(snak['datavalue']['value']) + if bound is None or bound[0] != calendar: + return None + if prop == 'P1319': + low = max(low, bound[1]) + else: + high = min(high, bound[2]) + if low > high: + return None + intervals.append((calendar, low, high)) + if len({b[0] for b in intervals}) != 1: + return None + return intervals[0][0], min(b[1] for b in intervals), max(b[2] for b in intervals) + except (ValueError, KeyError, TypeError, IndexError, AttributeError): + return None diff --git a/root/wander-train/entity_linker_v3.py b/root/wander-train/entity_linker_v3.py new file mode 100644 index 0000000000000000000000000000000000000000..3a7b9cb7046be16a7065a9fbc202b4eba62a0a14 --- /dev/null +++ b/root/wander-train/entity_linker_v3.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python3 +"""entity_linker_v3 - entity_linker_v2 (same index: relstore/names_v1.sqlite3) + one rule (4.5 Reach, 2026-10-21): + R4 CASE-BLIND QUESTIONS - v2's case agreement (R1) reads a lowercase word as a concept and a capitalised span as a name. + That is evidence only when the question USES case. A question with no capital letter after its first character ("where + did roger marquis die") says nothing by case, so every span is read as v2 reads a capitalised one: names may be + lowercase, and no span gets the capitalisation bonus over another. +Questions that use case are linked exactly as v2 links them. +use: link(question, k=3) -> [(span text, [(qid, links, label), ...]), ...] (v1's interface)""" +import math +import re + +import entity_linker_v2 as V2 + +norm, candidates, label, STOP = V2.norm, V2.candidates, V2.label, V2.STOP +NUMERIC, FUNCTION = V2.NUMERIC, V2.FUNCTION + + +def case_blind(question): + s = str(question).strip() + return not re.search(r"[A-Z]", s[1:]) + + +def link(question, k=3, max_len=8): + if not case_blind(question): + return V2.link(question, k, max_len) + raw = re.findall(r"[A-Za-z0-9][\w'.\-]*", str(question)) + toks = [norm(t) for t in raw] + spans = [] + for i in range(len(toks)): + for j in range(i + 1, min(len(toks), i + max_len) + 1): + words = toks[i:j] + if not words[0] or not words[-1] or all(w in STOP for w in words): + continue + content = [w for w in words if w not in STOP and w != "no"] + if not content or all(NUMERIC.match(w) for w in content): + continue + if words[-1] in STOP or (words[0] in STOP and len(words) == 1): + continue + if len(words) == 1 and (len(words[0]) < 4 or words[0] in STOP): + continue + if words[0] in FUNCTION and words[0] not in ("the", "a", "an"): + continue + c = candidates(" ".join(words), max(k, 6)) + if not c: + continue + c = c[:k] + spans.append((math.log1p(c[0][1]) + 3.0 * len(words), i, j, c)) + spans.sort(key=lambda s: -s[0]) + taken, out = set(), [] + for score, i, j, c in spans: + if any(x in taken for x in range(i, j)): + continue + taken.update(range(i, j)) + out.append((" ".join(raw[i:j]), [(q, n, label(q)) for q, n, _ in c], score)) + out.sort(key=lambda s: -s[2]) + return [(s, c) for s, c, _ in out] + + +if __name__ == "__main__": + import sys + for q in sys.argv[1:]: + print(q, "->", [(s, [x[2] for x in c]) for s, c in link(q)]) diff --git a/root/wander-train/exact_router_v1.py b/root/wander-train/exact_router_v1.py index 6f4e7e61678f7cba98cfe17a38848f008ec2c416..4844c2674b7c2375d592df33636ef8a41728f0fd 100644 --- a/root/wander-train/exact_router_v1.py +++ b/root/wander-train/exact_router_v1.py @@ -16,6 +16,7 @@ import re import entity_linker_v2 as L import oracle_relstore_v1 as RS +import date_precision_v1 as DATE PATTERNS = __import__("os").environ.get("ORACLE7_ROOT", "/opt/oracle-clm") + "/relstore/router_patterns_v4.json" STORE = __import__("os").environ.get("ORACLE7_ROOT", "/opt/oracle-clm") + "/relstore/relations_v2.sqlite3" @@ -106,35 +107,31 @@ def answer(q): p = props.pop() if p in TIME_VARIANT and PAST.search(q): return None - sets, subj = [], None + sets, displays, subj = [], [], None for qid, _, _ in cs[:3]: vals = {rs.label(o) if o else lit for pp, o, lit in rs.props_of(qid) if pp == p} vals = {v for v in vals if v and ".well-known/genid" not in v} if vals: + if any(DATE.is_time(v) and not DATE.available(v, q, qid, p) for v in vals): + return None sets.append(frozenset(vals)) + displays.append(frozenset(_show(v, q, qid, p) for v in vals)) subj = subj or qid - if not sets or len(set(sets)) != 1 or len(sets[0]) != 1: + if not sets or len(set(sets)) != 1 or len(set(displays)) != 1 or len(sets[0]) != 1: return None aw = [w for w in norm(next(iter(sets[0]))).split() if w not in L.STOP] if aw and all(w in set(norm(q).split()) for w in aw): return None # the answer restates the question: not an answer - return {"answer": _show(next(iter(sets[0])), q), "property": p, "subject_qid": subj, + return {"answer": _show(next(iter(sets[0])), q, subj, p), "property": p, "subject_qid": subj, "pattern": "|".join(sorted(matched)[0])} MONTHS = ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December") -def _show(v, q): - """a stored time "1034-03-27T00:00:00Z" reads as "1034" when the year is asked, else "27 March 1034"; BCE years keep - their sign as "BC" """ - m = re.match(r"^([+-]?)(\d{1,4})-(\d\d)-(\d\d)T", v) - if not m: - return v - y = str(int(m.group(2))) + (" BC" if m.group(1) == "-" else "") - if re.search(r"\byear\b", q, re.I) or m.group(3) == "00" or (m.group(3) == "01" and m.group(4) == "01"): - return y - return "%d %s %s" % (int(m.group(4)), MONTHS[int(m.group(3)) - 1], y) +def _show(v, q, subject=None, property=None): + """Untrusted source-aware display; a legacy timestamp does not encode precision.""" + return DATE.render(v, q, subject, property) if DATE.is_time(v) else v if __name__ == "__main__": diff --git a/root/wander-train/grow_router_v1.py b/root/wander-train/grow_router_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..9b4b65c5ad4b1cac9ae85a3cff9224984931608a --- /dev/null +++ b/root/wander-train/grow_router_v1.py @@ -0,0 +1,131 @@ +"""grow_router_v1 - release 4.7: answers ONLY through the question routes the self-building loop (grow_v1) built and the gate +admitted (relstore/grow/patterns_r.json, every round admitted so far). Each answer goes through reach_router_v3's own +checks: a hidden hop or a subject that is not the one asked about stops it, a past-time qualifier on a relation that changes +stops it, the readings of the name must agree (one-word names through their top reading, no unexplained fragment, at most +2 content words nothing explains), the answer must be the kind asked, a value with no English name is not shown, and an +answer that restates the question is not given.""" +import glob +import sys +import json +import os +import re + +import entity_linker_v3 as L +import exact_router_v1 as XR +import reach_router_v3 as R + +ROOT = os.environ.get("ORACLE7_ROOT", __import__("os").environ.get("ORACLE7_ROOT", "/opt/oracle-clm") + "") +GROW_DIR = os.environ.get("ORACLE7_GROW_DIR", ROOT + "/relstore/grow") +_S = {} + + +def rounds(): + out = [] + for fn in glob.glob(os.path.join(GROW_DIR, "patterns_r*.json")): + m = re.search(r"patterns_r(\d+)\.json$", fn) + if m: + out.append((int(m.group(1)), fn)) + return sorted(out) + + +def _load(): + if not _S: + pats = {} + for r, fn in rounds(): + for k, v in json.load(open(fn)).items(): + pats.setdefault(tuple(k.split("|", 1)), (v[0], v[4], r)) + _S["pats"] = pats + return _S + + +def answer_via(q, span, p, d, cands=None): + """the answer through relation (p, d) for this span, with every check the runtime makes; None when any check stops it""" + q = str(q).strip() + if cands is None: + cands = dict(L.link(q, 3)[:3]).get(span) + if not cands or XR.hop(q, span) or not XR.subject_ok(q, span): + return None + if p in XR.TIME_VARIANT and XR.PAST.search(q): + return None + v, subj = R._agree(q, span, cands, p, d) + if v is None or not R.fits(q, p, d, v): + return None + shown = [R._show(x, q, p) for x in v] + if not all(shown): + return None # a value with no English name is not shown + shown = sorted(shown) + aw = [w for x in shown for w in L.norm(x).split() if w not in L.STOP] + if aw and all(w in set(L.norm(q).split()) for w in aw): + return None # the answer restates the question + text = shown[0] if len(shown) == 1 else ", ".join(shown[:-1]) + " and " + shown[-1] + return {"answer": text, "values": shown, "raw": sorted(v, key=str), "property": p, "direction": d, "subject_qid": subj} + + +def answer(q): + q = str(q).strip() + pats = _load()["pats"] + if not pats or XR.POLAR.search(q) or not (R.WH.match(q) or q.endswith("?")): + return None + for span, cands in L.link(q, 3)[:3]: + if XR.hop(q, span) or not XR.subject_ok(q, span): + continue + matched = {f: pats[f] for f in XR.features(q, span) if f in pats} + rels = {(p, d) for p, d, _ in matched.values()} + if len(rels) > 1: + rels = {(p, d) for p, d in rels if any(R.values(c[0], p, d) for c in cands[:3])} + if len(rels) != 1: + continue + p, d = rels.pop() + f = sorted(k for k, v in matched.items() if (v[0], v[1]) == (p, d))[0] + if all(k[1] == "*" for k, v in matched.items() if (v[0], v[1]) == (p, d)) and R.unexplained(q, span, p): + continue + a = answer_via(q, span, p, d, cands) + if a is None: + continue + a.update({"pattern": "|".join(f), "round": pats[f][2]}) + return a + return None + + +# ---- the specialists the loop built through the Workbench and its held-out exam admitted ---- +def _exam(): + wb = os.path.join(os.path.dirname(os.path.abspath(ROOT)), "workbench") + if wb not in sys.path: + sys.path.insert(0, wb) + import exam + return exam + + +def specialists(): + """[(round, Loaded)] - only folders whose held-out verdict is ADMIT and still bound to their files' SHA-256""" + if "specs" not in _S: + out = [] + sd = os.path.join(GROW_DIR, "specialists") + if os.path.isdir(sd): + ex = _exam() + for sid in sorted(os.listdir(sd)): + d = os.path.join(sd, sid) + if not os.path.isdir(d) or ex.status(d).get("state") != "admitted": + continue + meta = d + ".grow.json" + rnd = json.load(open(meta)).get("round", 0) if os.path.exists(meta) else 0 + try: + out.append((rnd, ex.Loaded(d))) + except Exception: # noqa: BLE001 - a specialist that will not load is left out + pass + _S["specs"] = sorted(out, key=lambda x: (x[0], x[1].id)) + return _S["specs"] + + +def specialist_answer(q, path): + """the first admitted specialist that answers, where the Workbench's contract lets one fill the decline""" + specs = specialists() + if not specs or not _exam().fillable(path): + return None + for rnd, sp in specs: + a = sp.reply(q, "grow") + if a is not None and a.get("status", "answered") == "answered": + a["round"] = rnd + a["specialist"] = sp.id + return a + return None diff --git a/root/wander-train/knowledge_composer_v1.py b/root/wander-train/knowledge_composer_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..43d14619d0fda4b61f187907b04c06939f1857d3 --- /dev/null +++ b/root/wander-train/knowledge_composer_v1.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python3 +"""knowledge_composer_v1 - Oracle7 4.5: questions that are small programs over the relation store, answered by COMPOSING +routes the Reach router already answers under admission (library learning for knowledge: no new lookup of its own). +Each route below is examined on Mintaka TRAIN questions (gold answers) before use, and runs only when its parts all answer. + + HOP "Where was the singer of Genie in a Bottle born?": the inner phrase "the singer of Genie in a Bottle" is asked + on its own ("What is the singer of Genie in a Bottle?"); its answer must be ONE named thing; that thing is pinned + as the subject of the outer question ("Where was born?"), which must answer too. Both receipts are kept. + ORDER "Which series is older, Metroid or Super Mario Bros?": two named things, one date relation both hold (birth for + people; publication, inception, start or first performance otherwise), compared. Dates only: the store keeps + quantities without units, so sizes are not compared. +use: answer(question) -> {"answer", "route", "steps": [...]} or None""" +import os +import re + +import reach_router_v1 as R + +L = R.L +INNER = re.compile(r"\bthe\s+(?P[a-z][a-z\- ]{1,40}?)\s+of\s+(?P(?:the\s+)?[A-Z0-9][\w'.:\-]*(?:\s+(?:[A-Z0-9][\w'.:\-]*|of|the|and|in|on|a|an|de|la|le|du|von|van))*)") +# only the plain comparison: "Which/who is older, A or B?", "Which came first, A or B?" - no other event between +ORDER = re.compile(r"^\s*(?:which|who|what)(?:\s+(?!died|was\s+born|elected|assumed|won|became)[a-z\-]+){0,2}?\s+" + r"(?:is|was|are|were|came\s+out|came|come\s+out|appeared|released)\s+" + r"(?Polder|newer|earlier|later|first|younger|more\s+recent)\s*,\s*" + r"(?P.+?)\s+or\s+(?P.+?)\s*\?\s*$", re.I) +BIRTH_ORDER = re.compile(r"^\s*(?:who|which\s+(?:person|individual))\s+was\s+born\s+" + r"(?Pearlier|first|later|last)\s*,\s*" + r"(?P.+?)\s+or\s+(?P.+?)\s*\?\s*$", re.I) +PERSON_DATE = (569,) # date of birth +THING_DATES = (577, 571, 580, 1191, 1619, 606, 729, 619) # publication, inception, start, first performance, opening, +# first flight, service entry, launch +EARLY = {"older", "earlier", "first", "the oldest"} + + +def _one_item(a): + raw = a.get("raw") or [] + return raw[0] if len(raw) == 1 and isinstance(raw[0], int) else None + + +def hop(q): + for m in INNER.finditer(q): + x, y = m.group("x"), m.group("y").rstrip(" ?.,") + inner = R.answer("What is the %s of %s?" % (x, y)) + if not inner: + continue + v = _one_item(inner) + if v is None: + continue + name = R.label(v) + if not name: + continue + outer_q = q[:m.start()] + name + q[m.start() + len("the %s of %s" % (x, y)):] + outer = R.answer(outer_q, pinned=(name, v)) + if not outer: + continue + return {"answer": outer["answer"], "route": "hop", "values": outer["values"], + "steps": [dict(inner, question="What is the %s of %s?" % (x, y)), dict(outer, question=outer_q)]} + return None + + +def _date(qid): + """Read every bounded stored date; unknown precision never proves an ordering.""" + db = R._load()["db"] + cls = R.classes(qid) + for p in (PERSON_DATE if R.HUMAN in cls else THING_DATES): + rows = [lit for (lit,) in db.execute("SELECT lit FROM fact INDEXED BY fact_sp WHERE s=? AND p=? LIMIT 101", (qid, p)) if lit] + if rows: + if len(rows) > 100: + return None, None, None + bounds = [R.DATE.interval(lit, qid, p) for lit in rows] + if any(b is None for b in bounds) or len({b[0] for b in bounds}) != 1: + return None, None, None + envelope = bounds[0][0], min(b[1] for b in bounds), max(b[2] for b in bounds) + return p, rows, envelope + return None, None, None + + +def _exact(text): + sp = L.link(text, 3)[:1] + if not sp or R._bare(sp[0][0]) != R._bare(text): + return None + cands = sp[0][1] + if len(cands) > 1 and cands[0][1] < R.XR.DOMINANCE * max(1, cands[1][1]): + return None # an ambiguous name: no comparison + return cands[0][0] + + +def order(q): + birth = BIRTH_ORDER.match(q) + m = birth or ORDER.match(q) + if not m: + return None + a, b = _exact(m.group("a")), _exact(m.group("b")) + if not a or not b or a == b: + return None + pa, da, ia = _date(a) + pb, db_, ib = _date(b) + if not pa or pa != pb or (birth and pa != 569) or ia[0] != ib[0]: + return None # no calendar conversion is assumed + if ia[2] < ib[1]: + earlier, later = a, b + elif ib[2] < ia[1]: + earlier, later = b, a + else: + return None # overlapping uncertainty does not establish an order + adj = m.group("adj").lower() + pick = earlier if adj in EARLY else later + plab = R._load()["plabel"].get(pa, "P%d" % pa) + show_a = " / ".join(R.XR._show(v, "date", a, pa) for v in da) + show_b = " / ".join(R.XR._show(v, "date", b, pb) for v in db_) + return {"answer": R.label(pick), "route": "order", "values": [R.label(pick)], + "steps": [{"subject_qid": a, "property": pa, "value": da[0] if len(da) == 1 else None, "values": da, "interval": ia, "display": show_a}, + {"subject_qid": b, "property": pb, "value": db_[0] if len(db_) == 1 else None, "values": db_, "interval": ib, "display": show_b}], + "receipt": "%s (Q%d) - %s (P%d) - %s; %s (Q%d) - %s (P%d) - %s" % (R.label(a), a, plab, pa, show_a, + R.label(b), b, plab, pb, show_b)} + + +HOP_ON = os.environ.get("KC_HOP") == "1" # not admitted (2026-10-21: 9 firings on Mintaka train): off + + +def answer(q): + q = str(q).strip() + return order(q) or (hop(q) if HOP_ON else None) + + +if __name__ == "__main__": + import sys + for q in sys.argv[1:]: + print(q, "->", answer(q)) diff --git a/root/wander-train/math_organ_v1.py b/root/wander-train/math_organ_v1.py index 98e7e3fb95fe08f3d601a291af118719bd975f20..fb871e66a96a05f537ff89f47cd81f650b1c3f56 100644 --- a/root/wander-train/math_organ_v1.py +++ b/root/wander-train/math_organ_v1.py @@ -1,9 +1,11 @@ -"""math_organ_v1 - exact mathematics as specified free moves, every result independently checked, the method cited. +"""Untrusted math_organ_v1: SymPy operations with heuristic numerical checks. + +These checks share the evaluator and are not independent proofs. The method is cited when available. REQUEST directive (solve / simplify / factor / expand / evaluate / differentiate / integrate / limit / decompose) + the expression(s), read from the question or from its exercise set's instruction MOVES SymPy operations legal for that directive and that expression's type -CHECK independent of the move that produced the answer: +CHECK numerical or symbolic checks, not a theorem about the user question: solve every solution substituted back satisfies every equation / inequality factor the product expands back to the input, and is a product simplify equivalent to the input at random points, and no more complex than the input @@ -15,6 +17,7 @@ STORED FORM the textbook's own method for the directive (a howto or a worked exa Nothing is asserted unless the check passes; a failed check is an abstention with the reason.""" from __future__ import annotations +import math import random import re import sqlite3 @@ -189,6 +192,23 @@ def rand_pts(syms, k=5): return [{s: sp.Rational(rng.randint(2, 29), rng.randint(3, 11)) for s in syms} for _ in range(k)] +def finite_numeric_agreement(a, b, tolerance): + """Reject NaN/infinity before comparison; finite complex values are allowed. + + Both evaluations use SymPy. Agreement is a heuristic check, not independent + verification, and values outside machine complex range are declined. + """ + try: + va, vb = complex(a.evalf()), complex(b.evalf()) + if not all(math.isfinite(x) for x in (va.real, va.imag, vb.real, vb.imag)): + return False + difference = abs(va - vb) + bound = tolerance * max(1.0, abs(va), abs(vb)) + return math.isfinite(difference) and math.isfinite(bound) and difference <= bound + except (TypeError, ValueError, OverflowError): + return False + + def equiv(a, b): try: d = sp.simplify(a - b) @@ -196,8 +216,7 @@ def equiv(a, b): return True syms = sorted((a.free_symbols | b.free_symbols), key=str) for pt in rand_pts(syms): - va, vb = complex(a.subs(pt).evalf()), complex(b.subs(pt).evalf()) - if abs(va - vb) > 1e-7 * max(1.0, abs(va)): + if not finite_numeric_agreement(a.subs(pt), b.subs(pt), 1e-7): return False return True except Exception: # noqa: BLE001 @@ -405,9 +424,9 @@ class MathOrgan: if e.free_symbols: return self._simplify(spans, q) v = sp.nsimplify(sp.simplify(e)) if not e.is_Float else e - if abs(complex(v.evalf()) - complex(e.evalf())) > 1e-9 * max(1, abs(complex(e.evalf()))): + if not finite_numeric_agreement(v, e, 1e-9): return None - return {"answer": sp.sstr(v), "value": v, "check": "recomputed numerically", + return {"answer": sp.sstr(v), "value": v, "check": "finite numerical comparison using SymPy", "steps": ["read %s" % sp.sstr(e), "evaluate"]} # --- calculus ------------------------------------------------------------------------------------------------- diff --git a/root/wander-train/math_organ_v2.py b/root/wander-train/math_organ_v2.py index cbb5bcbb8c98feba202202281cc179c17aea2f0d..4cc8f4bde633f9962483e9a12239dedf21909dd4 100644 --- a/root/wander-train/math_organ_v2.py +++ b/root/wander-train/math_organ_v2.py @@ -1,12 +1,13 @@ """math_organ_v2 - v1 (admitted in w480, now immutable) + two fixes found on the gate panel: "factorial" is not a request to factor, and a request for a PROGRAM is the code organ's, not a mathematical request. -exact mathematics as specified free moves, every result independently checked, the method cited. +Untrusted SymPy operations with heuristic numerical checks; the method is cited when available. +These checks share the evaluator and are not independent proofs. REQUEST directive (solve / simplify / factor / expand / evaluate / differentiate / integrate / limit / decompose) + the expression(s), read from the question or from its exercise set's instruction MOVES SymPy operations legal for that directive and that expression's type -CHECK independent of the move that produced the answer: +CHECK numerical or symbolic checks, not a theorem about the user question: solve every solution substituted back satisfies every equation / inequality factor the product expands back to the input, and is a product simplify equivalent to the input at random points, and no more complex than the input @@ -23,6 +24,7 @@ import re import sqlite3 import sympy as sp +from math_organ_v1 import finite_numeric_agreement from sympy.parsing.sympy_parser import (convert_xor, implicit_multiplication_application, parse_expr, split_symbols_custom, standard_transformations) @@ -199,8 +201,7 @@ def equiv(a, b): return True syms = sorted((a.free_symbols | b.free_symbols), key=str) for pt in rand_pts(syms): - va, vb = complex(a.subs(pt).evalf()), complex(b.subs(pt).evalf()) - if abs(va - vb) > 1e-7 * max(1.0, abs(va)): + if not finite_numeric_agreement(a.subs(pt), b.subs(pt), 1e-7): return False return True except Exception: # noqa: BLE001 @@ -412,9 +413,9 @@ class MathOrgan: if e.free_symbols: return self._simplify(spans, q) v = sp.nsimplify(sp.simplify(e)) if not e.is_Float else e - if abs(complex(v.evalf()) - complex(e.evalf())) > 1e-9 * max(1, abs(complex(e.evalf()))): + if not finite_numeric_agreement(v, e, 1e-9): return None - return {"answer": sp.sstr(v), "value": v, "check": "recomputed numerically", + return {"answer": sp.sstr(v), "value": v, "check": "finite numerical comparison using SymPy", "steps": ["read %s" % sp.sstr(e), "evaluate"]} # --- calculus ------------------------------------------------------------------------------------------------- diff --git a/root/wander-train/math_organ_v3.py b/root/wander-train/math_organ_v3.py index 2cafc4851a3d777fe42701708c9bb7e9cb66e278..5cf7e03c0bedc83354e35ed904a4f0c27e589023 100644 --- a/root/wander-train/math_organ_v3.py +++ b/root/wander-train/math_organ_v3.py @@ -3,12 +3,13 @@ variables (found by the proposer brief: "On what date in 1969 did ..." -> 1969*d math_organ_v2 - v1 (admitted in w480, now immutable) + two fixes found on the gate panel: "factorial" is not a request to factor, and a request for a PROGRAM is the code organ's, not a mathematical request. -exact mathematics as specified free moves, every result independently checked, the method cited. +Untrusted SymPy operations with heuristic numerical checks; the method is cited when available. +These checks share the evaluator and are not independent proofs. REQUEST directive (solve / simplify / factor / expand / evaluate / differentiate / integrate / limit / decompose) + the expression(s), read from the question or from its exercise set's instruction MOVES SymPy operations legal for that directive and that expression's type -CHECK independent of the move that produced the answer: +CHECK numerical or symbolic checks, not a theorem about the user question: solve every solution substituted back satisfies every equation / inequality factor the product expands back to the input, and is a product simplify equivalent to the input at random points, and no more complex than the input @@ -25,6 +26,7 @@ import re import sqlite3 import sympy as sp +from math_organ_v1 import finite_numeric_agreement from sympy.parsing.sympy_parser import (convert_xor, implicit_multiplication_application, parse_expr, split_symbols_custom, standard_transformations) @@ -207,8 +209,7 @@ def equiv(a, b): return True syms = sorted((a.free_symbols | b.free_symbols), key=str) for pt in rand_pts(syms): - va, vb = complex(a.subs(pt).evalf()), complex(b.subs(pt).evalf()) - if abs(va - vb) > 1e-7 * max(1.0, abs(va)): + if not finite_numeric_agreement(a.subs(pt), b.subs(pt), 1e-7): return False return True except Exception: # noqa: BLE001 @@ -420,9 +421,9 @@ class MathOrgan: if e.free_symbols: return self._simplify(spans, q) v = sp.nsimplify(sp.simplify(e)) if not e.is_Float else e - if abs(complex(v.evalf()) - complex(e.evalf())) > 1e-9 * max(1, abs(complex(e.evalf()))): + if not finite_numeric_agreement(v, e, 1e-9): return None - return {"answer": sp.sstr(v), "value": v, "check": "recomputed numerically", + return {"answer": sp.sstr(v), "value": v, "check": "finite numerical comparison using SymPy", "steps": ["read %s" % sp.sstr(e), "evaluate"]} # --- calculus ------------------------------------------------------------------------------------------------- diff --git a/root/wander-train/oracle_operator_specs_v1.py b/root/wander-train/oracle_operator_specs_v1.py index e285656fe695a88de2eb1726221c56c963f37793..f1e801ae1b8d10c4c0aa93d02f442129dc4b00b3 100644 --- a/root/wander-train/oracle_operator_specs_v1.py +++ b/root/wander-train/oracle_operator_specs_v1.py @@ -198,33 +198,63 @@ def _gcd_ref(a): # ── 3. base conversion ──────────────────────────────────────────────────────── -# fn is repeated divmod; ref is positional expansion of the digits it produced. -_BASE_RX = re.compile( - r'\b(?:convert|write|express)?\s*(-?\d+)\s*(?:from\s*)?(?:base\s*(\d+))?\s*' - r'(?:in|to|into)\s*(?:base\s*)?(\d+|binary|hex|hexadecimal|octal|decimal)\b', re.I) +# The parser binds the original digits and source base. The function decodes +# with int(); the reference independently expands source digits positionally. _BASE_NAME = {'binary': 2, 'hex': 16, 'hexadecimal': 16, 'octal': 8, 'decimal': 10} +_BASE_ATOM = r'(?:base\s*\d+|binary|hexadecimal|hex|octal|decimal)' +_BASE_RX = re.compile( + r'^\s*(?:(?:convert|write|express|what\s+is)\s+)?' + r'(?:(?P' + _BASE_ATOM + r')\s+)?' + r'(?P[+-]?[0-9a-z]+)' + r'(?:\s+(?:(?:from|in)\s+)?(?P' + _BASE_ATOM + r'))?' + r'\s+(?:in|to|into|as)\s+(?P' + _BASE_ATOM + r'|\d+)' + r'\s*[.?!]?\s*$', re.I | re.ASCII) _DIGITS = '0123456789abcdefghijklmnopqrstuvwxyz' def _base_parse(s): - m = _BASE_RX.search(s) + m = _BASE_RX.fullmatch(s) if not m: - raise NotOurs('no number and target base here') - n = int(m.group(1)) - frm = int(m.group(2)) if m.group(2) else 10 - tgt = m.group(3).lower() - to = _BASE_NAME.get(tgt, None) - if to is None: - to = int(tgt) - if not (2 <= to <= 36) or not (2 <= frm <= 36): - raise OutOfFragment('I convert between base 2 and base 36 only') - if n < 0: + raise NotOurs('no complete integer base conversion here') + + def base(token): + token = token.lower() + value = _BASE_NAME.get(token) + if value is None: + numeral = re.sub(r'^base\s*', '', token) + if len(numeral) > 3: + raise OutOfFragment('I convert between base 2 and base 36 only') + value = int(numeral) + if not 2 <= value <= 36: + raise OutOfFragment('I convert between base 2 and base 36 only') + return value + + sources = [base(token) for token in (m['prefix'], m['source']) if token] + raw = m['digits'].lower() + if raw.startswith('-'): raise OutOfFragment('I convert non-negative whole numbers only') - return {'n': n, 'frm': frm, 'to': to} + raw = raw.lstrip('+') + # A conventional literal prefix is source evidence, not a digit to discard. + # Explicit bases above 16 may use x as a digit; only infer prefixes when no + # explicit source is supplied, or that source matches the prefix convention. + literal = {'0b': 2, '0o': 8, '0x': 16}.get(raw[:2]) + if literal is not None and (not sources or all(b == literal for b in sources)): + sources.append(literal) + raw = raw[2:] + elif literal is not None and sources and sources[0] in (2, 8, 10, 16): + raise OutOfFragment('the literal prefix conflicts with the stated source base') + if len(set(sources)) > 1: + raise OutOfFragment('the stated source bases disagree') + frm = sources[0] if sources else 10 + to = base(m['target']) + if not raw or len(raw) > 128 or any(_DIGITS.index(c) >= frm for c in raw): + raise OutOfFragment('I need 1 to 128 valid digits in the stated source base') + n = int(raw, frm) + return {'n': n, 'digits': raw, 'frm': frm, 'to': to} def _base_fn(a): - n, steps, out = a['n'], [], '' + n, steps, out = int(a['digits'], a['frm']), [], '' if n == 0: return '0', ['0 in any base is 0'] while n: @@ -235,8 +265,13 @@ def _base_fn(a): def _base_ref(a): - """Independent: build with a positional table, then check by expanding it.""" - n = a['n'] + """Expand original source digits, then encode using a positional table. + + This does not share int() source decoding or repeated output division with + the primary function. Both still depend on the same untrusted parse. + """ + n = sum(_DIGITS.index(digit) * a['frm'] ** power + for power, digit in enumerate(reversed(a['digits']))) if n == 0: return '0' digits, powers = [], [] @@ -418,8 +453,9 @@ SPECS = [ 'parse': _base_parse, 'fn': _base_fn, 'ref': _base_ref, 'render': lambda a, v, s: '%d in base %d is %s.' % (a['n'], a['to'], v), 'warrant': 'computation', - 'independence': 'moderate: repeated division against positional expansion; ' - 'both walk the same digits, in opposite directions', + 'independence': 'moderate: int source decoding and repeated output division ' + 'against positional source expansion and output encoding; ' + 'both still depend on the same untrusted parse', 'fragment': 'non-negative whole numbers, bases 2 to 36'}, {'name': 'statistics', 'family': 'measurement', diff --git a/root/wander-train/oracle_release_runtime_an.py b/root/wander-train/oracle_release_runtime_an.py index 521c74e55f45c80c4d49d719dc9a3dfe1683af45..2fdc37737a0926128176b595d7f2b5d6c1db3758 100644 --- a/root/wander-train/oracle_release_runtime_an.py +++ b/root/wander-train/oracle_release_runtime_an.py @@ -89,13 +89,17 @@ class OracleReleaseRuntimeAN(OracleReleaseRuntimeAM): def chat(self, text: str, session_id: str = "default") -> dict: started = time.perf_counter() prior = self.transitions.get(session_id) - prior_terms = prior["out_terms"] if prior else set() # a subclass may declare a conversion BEFORE dispatch (AN records the transition # inside this call, before the subclass can attach anything to the result) pending = getattr(self, "_pending_conversion", {}).pop(session_id, None) result = super().chat(text, session_id) if pending and "conversion" not in result: result["conversion"] = pending + return self._record_turn(text, session_id, result, started, prior) + + def _record_turn(self, text, session_id, result, started, prior): + """Record the supplied outcome; the final-turn boundary also uses this recorder.""" + prior_terms = prior["out_terms"] if prior else set() in_terms = content_terms(text) out_terms = content_terms(result.get("response", "")) status = str(result.get("status", "")) diff --git a/root/wander-train/oracle_release_runtime_ao.py b/root/wander-train/oracle_release_runtime_ao.py index 911a83545dd8c28c420a99b45b3502e64fa868ca..7eee783a2533363a179ec5d77ec31ca09c06bf7d 100644 --- a/root/wander-train/oracle_release_runtime_ao.py +++ b/root/wander-train/oracle_release_runtime_ao.py @@ -22,6 +22,16 @@ import re from oracle_release_runtime_an import OracleReleaseRuntimeAN +# Untrusted grammar guard: in "does it take/cost ... to ", it +# may be a grammatical subject rather than an entity from the conversation. +# Decline substitution for that token; other references remain eligible. The +# match stays within a clause and accepts decimal amounts before the infinitive. +DUMMY_IT = re.compile( + r"\b(?:does|did|will|would|can|could|should|has|had)\s+(?Pit)\s+" + r"(?:take|taken|cost)\s+" + r"(?:(?:\d+(?:\.\d+)?\s+(?:milliseconds?|seconds?|minutes?|hours?|days?|weeks?|" + r"months?|years?|dollars?|euros?|pounds?)|[$€£]\d+(?:\.\d+)?)\s+)?" + r"to\s+[a-z]", re.I) DEICTIC = re.compile(r"\b(it|there|that|this|its|they|them|those|these|the same)\b", re.I) ELLIPSIS = re.compile(r"^(?:and|what about|the same for)\s+(?P.+?)\??$", re.I) BARE = re.compile(r"^(?:the\s+)?[a-z][a-z \-']{2,40}$", re.I) @@ -41,6 +51,17 @@ PREDICATE_OF = { } +def referential_deictic(text): + """First eligible reference, excluding only take/cost-infinitive dummy it. + + This does not claim to parse all English expletives. Skipping an ambiguous + token leaves the original question available to the unchanged handler. + """ + dummy_spans = {match.span("it") for match in DUMMY_IT.finditer(text)} + return next((match for match in DEICTIC.finditer(text) + if match.span() not in dummy_spans), None) + + class OracleReleaseRuntimeAO(OracleReleaseRuntimeAN): """Conversions are applied ONLY when the unchanged chain would not answer.""" @@ -103,10 +124,11 @@ class OracleReleaseRuntimeAO(OracleReleaseRuntimeAN): if not CONTINUATION.match(s): return f"Summarize {s.strip()}.", "ELLIPSIS_COMPLETION" topic = self._live_topic(session_id) - if topic and DEICTIC.search(s): + reference = referential_deictic(s) + if topic and reference: if low in PREDICATE_OF: return PREDICATE_OF[low].format(t=topic), "REFERENT_SUBSTITUTION" - return DEICTIC.sub(topic, s, count=1), "REFERENT_SUBSTITUTION" + return s[:reference.start()] + topic + s[reference.end():], "REFERENT_SUBSTITUTION" return None, None def chat(self, text: str, session_id: str = "default") -> dict: diff --git a/root/wander-train/organ_self_v2.py b/root/wander-train/organ_self_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..0793808ebcac471b44369ddfed1bd383b681d829 --- /dev/null +++ b/root/wander-train/organ_self_v2.py @@ -0,0 +1,184 @@ +#!/usr/bin/env python3 +"""organ_self_v2 - the self (ego) organ, second version: emotion that fits the turn, and a mood of its own that it can measure. +organ_self_v1 stays frozen; this extends it and changes only what the 2026-10-26 chat probe found wrong. + + ILLNESS IS NOT GRIEF v1 read "I lost my job and I feel awful" as illness ("feel awful" was in its illness pattern) and + answered with a doctor. Illness now needs a bodily word (sick, ill, unwell, fever, dizzy, ...). + Loss (a job, a person, a pet, a home, a relationship) is grief: acknowledged as that loss, with an + open question, and no advice nobody asked for. + GREETING "Hi there!" was not read at all; a turn that is only a greeting is greeted, by name. + ITS OWN FEELINGS "Do you have feelings?" was not read. The answer is honest (no body, no moods that run by + themselves) and then names what it does have: states it measures, and says plainly. + ITS MOOD the ego keeps a per-conversation record of what happened to each turn (answered with a source or a + check, declined, social). Asked how it is, it reports that record in plain words - a feeling-word + chosen BY the measurement, never instead of it. +Feeling shapes the voice, never the claim (as in v1).""" +from __future__ import annotations + +import re + +import organ_self_v1 as V1 + +BODY_ILL = re.compile(r"\bnot feeling (?:too |so |very )?well\b|\bfeel(?:ing)? (?:sick|ill|unwell|dizzy|faint|nauseous|feverish)\b|" + r"\bgoing to (?:be sick|throw up|faint)\b|\bi(?:'ve| have) (?:a |the )?(?:fever|flu|cold|headache|" + r"migraine|toothache|stomach ?ache|sore throat|cough)\b|\bi(?:'m| am) (?:sick|ill|unwell)\b", re.I) +LOSS = [ + (r"\b(?:lost|losing) my job\b|\b(?:got|been|was|were) (?:fired|laid off|let go|made redundant)\b|\blaid me off\b|\bfired me\b", + "losing your job", "Do you want to talk about what happened, or would it help to think through what comes next?"), + (r"\bmy (?:\w+ )?(?:mother|mom|mum|father|dad|grandmother|grandma|grandfather|grandpa|brother|sister|son|daughter|wife|" + r"husband|partner|friend|uncle|aunt|cousin)\b[^.!?]{0,40}\b(?:died|passed away|passed|is gone)\b|" + r"\b(?:lost|losing) my (?:\w+ )?(?:mother|mom|mum|father|dad|grandmother|grandma|grandfather|grandpa|brother|sister|son|" + r"daughter|wife|husband|partner|friend|uncle|aunt|cousin)\b", + "losing someone you love", "I'm here if you want to tell me about them."), + (r"\bmy (?:dog|cat|pet|horse|bird|rabbit)\b[^.!?]{0,40}\b(?:died|passed away|is gone|was put down)\b|" + r"\b(?:lost|losing) my (?:dog|cat|pet|horse)\b", "losing a companion like that", "What were they like?"), + (r"\b(?:broke up|break-?up|split up|divorc\w*|left me|dumped me)\b", "the end of a relationship", + "How are you holding up?"), + (r"\b(?:lost|losing) (?:my|our) (?:home|house|flat|apartment)\b|\b(?:evicted|eviction)\b", "losing your home", + "Is there something practical I can help you look into?"), + (r"\bfailed (?:my |the |an? )?(?:exam|test|course|class|interview)\b|\bdidn'?t (?:get|pass) (?:the |my )?(?:job|exam|test)\b", + "a setback like that", "Do you want to talk it through?"), +] +FEEL_BAD = re.compile(r"\bfeel(?:ing)? (?:awful|terrible|horrible|so bad|really bad|low|down|sad|miserable|devastated|" + r"crushed|heartbroken|lost|hopeless|empty)\b|\bi(?:'m| am) (?:so |really |very )?(?:sad|upset|devastated|" + r"heartbroken|depressed|down|miserable)\b", re.I) +FIRST_PERSON = re.compile(r"\b(?:i|i'm|i've|i'd|i'll|im|me|my|myself|we|our|us)\b", re.I) # it is the speaker's own news +CRISIS = re.compile(r"\b(?:kill myself|suicide|suicidal|end (?:it all|my life)|don'?t want to (?:live|be alive)|hurt myself|" + r"self[- ]harm)\b", re.I) +GREETING = re.compile(r"^\s*(?:hi|hello|hey|hiya|howdy|greetings|good (?:morning|afternoon|evening)|yo)" + r"(?:\s+(?:there|oracle7?|again|everyone|all))?\s*[!.,]*\s*(?::\)|☺)?\s*$", re.I) +FEELINGS_Q = re.compile(r"\b(?:do|can|could) you (?:ever |even |actually |really )?(?:have|feel|experience) (?:any )?" + r"(?:feelings?|emotions?|pain|joy|love|sad(?:ness)?|lonel(?:y|iness)|happ(?:y|iness))\b|" + r"\b(?:do|can|could) you (?:ever |even |actually |really )?feel anything\b|" + r"\bare you (?:ever )?(?:happy|sad|lonely|bored|conscious|sentient|alive|afraid|scared)\b|" + r"\bdo you get (?:lonely|sad|bored|tired|angry|happy)\b|\bwhat do you feel\b", re.I) +HOW_ARE_YOU = re.compile(r"^\s*(?:and\s+)?(?:how are you(?: doing| feeling)?(?: today| now)?|how'?s it going|how do you feel" + r"(?: today| now)?|how are things|you ok(?:ay)?|are you ok(?:ay)?)\s*[?!.]*\s*$", re.I) +THANKS = re.compile(r"^\s*(?:(?:ok(?:ay)?|great|perfect|cool|nice|brilliant|awesome)[,!.]?\s*)?(?:thanks?(?: you)?(?: so much| a lot| very much)?" + r"|thank you(?: so much| very much)?|cheers|ty|much appreciated|that (?:helps|helped|'s helpful|is helpful)" + r"|appreciate it)(?:[,!.]?\s*(?:that (?:helps|helped|'s helpful|is helpful)|thanks?|thank you))?\s*[!.]*\s*$", re.I) + + +class Mood: + """what happened to each turn of a conversation, measured; the feeling-word is chosen by the measurement""" + + def __init__(self): + self.s = {} + + def note(self, session_id, status, path): + m = self.s.setdefault(session_id, {"turns": 0, "checked": 0, "declined": 0, "social": 0, "last": None}) + m["turns"] += 1 + p = str(path or "") + if status == "answered" and not any(k in p for k in ("social", "self", "act:about", "acknowledge", "greet")): + m["checked"] += 1 + m["last"] = "answered" + elif status in ("withheld", "clarification", "declined"): + m["declined"] += 1 + m["last"] = "declined" + else: + m["social"] += 1 + return m + + def revise(self, session_id, status): + """a fold above the one that noted the turn changed its delivered outcome (w573 withholds a reply its parent had + answered): the record follows what was delivered, so the mood never reports a declined question as answered""" + m = self.s.get(session_id) + if not m or m["last"] != "answered" or status not in ("withheld", "clarification", "declined"): + return m + m["checked"] -= 1 + m["declined"] += 1 + m["last"] = "declined" + return m + + def words(self, session_id): + m = self.s.get(session_id) + if not m or not (m["checked"] + m["declined"]): + return ("settled and open", "nothing has been asked of me yet in this conversation") + n = m["checked"] + m["declined"] + if m["checked"] >= m["declined"] and m["last"] == "answered": + return ("steady", "I've answered %d of the %d questions you've asked here, each from a source or a check" + % (m["checked"], n)) + if m["declined"] > m["checked"]: + return ("a bit stretched", "%d of the %d questions you've asked here went past what I can check, and I said so " + "rather than guess" % (m["declined"], n)) + return ("careful", "the last question went past what I can check, so I declined it; %d of %d have been answered" + % (m["checked"], n)) + + +class SelfOrganV2(V1.SelfOrgan): + def __init__(self, conv): + super().__init__(conv) + self.mood = Mood() + + @staticmethod + def own_turn(t): + """a person's own short turn, not a passage handed over for reading (the gate panel found a crisis word inside a + reading passage set off the crisis reply)""" + return len(t) <= 300 and not re.match(r"^\s*(?:passage|context|text|article|document|story)\s*:", t, re.I) + + def answer(self, text, session_id="default"): + t = " ".join(str(text or "").split()) + if not t: + return None + for fn in (self._crisis, self._greeting, self._how_are_you, self._feelings, self._loss): + a = fn(t, session_id) + if a: + return a + a = super().answer(t, session_id) + if a and a.get("kind") == "care" and not BODY_ILL.search(t): + # v1's illness pattern caught an emotional "feel awful": answer the feeling, not a doctor + return self._say("disclosure", "I'm sorry you're feeling this way. Do you want to tell me what's going on?") + return a + + def _crisis(self, t, sid): + if not self.own_turn(t) or not CRISIS.search(t) or not FIRST_PERSON.search(t): + return None + return self._say("care", "I'm really glad you told me. You deserve support from a person right now: if you might act on " + "these thoughts, please call your local emergency number, or a crisis line - in the US you can call " + "or text 988, in the UK and Ireland Samaritans are on 116 123. I'm an AI and can't be there the way " + "they can, but I'll keep listening. Are you safe right now?") + + def _greeting(self, t, sid): + if not GREETING.match(t): + return None + again = self.mood.s.get(sid, {}).get("turns", 0) > 0 + return self._say("greet", ("Hello again! What would you like to look at next?" if again else + "Hello! I'm Oracle7. Ask me about facts, physics, numbers, code or the air's carbon - " + "or just tell me what's on your mind.")) + + def _how_are_you(self, t, sid): + if not HOW_ARE_YOU.match(t): + return None + word, why = self.mood.words(sid) + return self._say("self", "I'm %s, in my own terms: %s. How are you?" % (word, why)) + + def _feelings(self, t, sid): + if not self.own_turn(t) or not FEELINGS_Q.search(t): + return None + word, why = self.mood.words(sid) + return self._say("self", "Not the way you do. I don't have a body, and no mood runs in me by itself. What I have are " + "states I can measure, and I'll name them plainly: right now I'm %s - %s. When I'm sure of " + "something I'll show you why, and when I'm not I'll say so." % (word, why)) + + def _loss(self, t, sid): + if t.rstrip().endswith("?") or not self.own_turn(t) or not FIRST_PERSON.search(t): + return None + for rx, what, back in LOSS: + if re.search(rx, t, re.I): + feel = " and feeling awful about it makes complete sense" if FEEL_BAD.search(t) else "" + if BODY_ILL.search(t): + feel = ", and on top of that you're not well" + return self._say("disclosure", "I'm so sorry. %s is a real blow%s. %s" % (what[0].upper() + what[1:], feel, back)) + if FEEL_BAD.search(t) and not BODY_ILL.search(t) and V1.FIRST_PERSON_NEWS.match(t): + return self._say("disclosure", "I'm sorry you're feeling this way. Do you want to tell me what's going on?") + return None + + def thanks(self, t, sid, last_subject=None): + if not THANKS.match(t): + return None + m = self.mood.s.get(sid, {}) + if m.get("last") == "answered" and last_subject: + return "You're welcome - glad it helped. Want to go further on %s?" % last_subject + if m.get("last") == "answered": + return "You're welcome - glad it helped. What would you like next?" + return "You're welcome." diff --git a/root/wander-train/premise_v3.py b/root/wander-train/premise_v3.py new file mode 100644 index 0000000000000000000000000000000000000000..0a180cc34afdc954eba2ad82f434239aefb66f86 --- /dev/null +++ b/root/wander-train/premise_v3.py @@ -0,0 +1,176 @@ +"""Untrusted premise checks over question text, reply text, and relation stores. + +OWNER checks only an explicit exclusive creator premise about an identified +whole work, against a positive conflicting creator row. A possessive can name a +subject or owner and is not treated as a creator assertion. None means unproved, +not confirmed. Index coverage, source assertions and text interpretation remain +assumptions; no theorem about the world is established here. + +WITH and YEAR retain the release 4.8 behavior: WITH checks stored connections +between named people and the answer; YEAR compares a work-year phrase with dates +of the first cited QID, using a ten-year tolerance. Those older checks still need +coverage and identity review; missing records alone do not refute a real-world +premise. Each function returns a withholding reason or None. +""" +import re + +import entity_linker_v3 as L +import reach_router_v3 as R + +HUMAN = 5 +QREF = re.compile(r"\(Q(\d+)\)") +YEAR_WORK = re.compile(r"\b(?:the\s+)?(?P1[0-9]{3}|20[0-9]{2})\s+(?:film|movie|novel|book|song|album|opera|play|painting|series)\b" + r"|\b(?:film|movie|novel|book|song|album|opera|play|painting)\s+[^?]{1,60}?\((?P1[0-9]{3}|20[0-9]{2})\)", re.I) +DATES = (577, 571, 1191, 580) # publication date, inception, date of first performance, start time + + +def _lead(reply): + r = re.sub(r"^\s*\[ev:[a-z_]+\]\s*", "", str(reply)) + return re.split(r"(?wrote|composed|directed)\s+"(?P[^"\n]+)"\s*,\s*' + r'(?P<passive>written|composed|directed)\s+(?:solely|exclusively)\s+by\s+' + r'(?P<creator>[^?\n]+?)\s*\?\s*$', re.I) +CREATOR_RELATIONS = {"wrote": ("written", 50), "composed": ("composed", 86), + "directed": ("directed", 57)} +# Bind the work and property to the direct relation citation, rather than the +# first incidental QID in free text. This is still an untrusted text adapter. +RELATION_CITATION = re.compile( + r'From the Wikidata relation store:\s*[^\n]*?\(Q(\d+)\)\s*-\s*' + r'[^\n]*?\(P(\d+)\)\s*-', re.I) + + +def _unique_whole_name(name): + """One identity for the entire normalized span in this index, not top rank. + + candidates() groups by QID before LIMIT. Asking for two therefore detects + ambiguity without assuming a one-element truncated list is exhaustive. + Index coverage and normalization remain source/recognition assumptions. + """ + normalized = L.norm(name) + rows = L.candidates(normalized, 2) if normalized else [] + return int(rows[0][0]) if len(rows) == 1 else None + + +def owner(q, reply): + """Check a narrow exclusive-creator premise using positive source evidence. + + Example: Who wrote "Example Book", written solely by Jane Smith? + Bare possessives and non-exclusive attribution do not establish a creator + contradiction. Another stored creator refutes the explicit *sole* premise; + no missing row is treated as proof that someone was not a creator. Returning + None leaves the premise unproved; it does not confirm the premise or reply. + """ + m = EXCLUSIVE_CREATOR.fullmatch(str(q)) + if not m: + return None + passive, prop = CREATOR_RELATIONS[m.group("verb").lower()] + if m.group("passive").lower() != passive: + return None + work = _unique_whole_name(m.group("title")) + creator = _unique_whole_name(m.group("creator")) + if work is None or creator is None or not _humanq(creator): + return None + citations = [(int(qid), int(p)) for qid, p in RELATION_CITATION.findall(str(reply))] + if citations != [(work, prop)]: + return None + others = sorted(value for value in R.values(work, prop, "fwd") + if isinstance(value, int) and not isinstance(value, bool) and value > 0 and value != creator) + if others: + return ('the question says "%s" (Q%d) was %s solely by %s (Q%d), but my stored P%d relation ' + 'also names a different creator (Q%d) for that same work' % + (m.group("title"), work, passive, m.group("creator"), creator, prop, others[0])) + return None + + +def _connected(a, b): + db = R._load()["db"] + return db.execute("SELECT 1 FROM fact INDEXED BY fact_sp WHERE s=? AND o=? LIMIT 1", (a, b)).fetchone() is not None or \ + db.execute("SELECT 1 FROM fact INDEXED BY fact_sp WHERE s=? AND o=? LIMIT 1", (b, a)).fetchone() is not None + + +def _answer_qids(reply, value_qids): + vals = [int(str(x).lstrip("Q")) for x in value_qids if str(x).lstrip("Q").isdigit()] + if vals: + return vals + lead = _lead(reply).strip() + sp = [s for s in L.link(lead + "?", 3)[:1] if L.norm(s[0]) == L.norm(lead)] + return [sp[0][1][0][0]] if sp and sp[0][1] else [] + + +def with_(q, reply, value_qids): + """only for questions that name two or more people: each must be connected to the answer""" + toks = L.norm(str(q)).split() + + def where(span): + sp = L.norm(span).split() + for i in range(len(toks) - len(sp) + 1): + if toks[i:i + len(sp)] == sp: + return i, i + len(sp) + return None + + people = [] + for span, cands in L.link(str(q), 12)[:4]: + w = where(span) + if not cands or not w or len(L.norm(span)) < 4: + continue + # a capitalised name in the question may be a person below its top readings ("Chopin": an asteroid, a film, + # then the composer); a lower-case word counts only through its top reading + proper = re.search(r"\b%s\b" % re.escape(span), str(q)) and span[:1].isupper() + pool = cands[:12] if proper else cands[:1] + hum = next((c[0] for c in pool if _humanq(c[0])), None) + if hum: + people.append((span, hum, w)) + # people named side by side are one name ("Prince Michael Jackson"), not two + people = [p for p in people if not any(o is not p and (o[2][1] == p[2][0] or p[2][1] == o[2][0] or + (o[2][0] <= p[2][0] and p[2][1] <= o[2][1])) for o in people)] + if len(people) < 2: + return None + vals = _answer_qids(reply, value_qids) + if not vals: + return None + for span, other, _ in people: + if other in vals: + continue + if not any(_connected(other, v) for v in vals): + return "%s is not connected to that answer in my records" % span + return None + + +def year(q, reply): + m = YEAR_WORK.search(str(q)) + if not m: + return None + y = int(m.group("y") or m.group("y2")) + refs = [int(x) for x in QREF.findall(str(reply))] + if not refs: + return None + work = refs[0] + years = set() + for p in DATES: + for v in R.values(work, p, "fwd"): + mm = re.match(r"^[+-]?(\d{4})", str(v)) + if mm: + years.add(int(mm.group(1))) + if years and not any(abs(y - x) <= YEAR_TOLERANCE for x in years): + return "the question says %d, and the work I hold is from %s" % (y, "/".join(str(x) for x in sorted(years))) + return None + + +COMPARE = re.compile(r"\b(?:or|than|older|younger|taller|shorter|earlier|later|first|longer|bigger|larger|smaller|more|less)\b", re.I) +YEAR_TOLERANCE = 10 # a year a few off is a slip (a novel's film year); an impossible one is not + + +def check(q, reply, value_qids=()): + """premise checks only on a single, direct question: never on a passage, never on a long multi-sentence text""" + q = str(q) + if len(q) > 160 or re.search(r"(?i)\bpassage\s*:", q) or q.count("?") > 1 or q.count(". ") > 1: + return None + joined = re.search(r"\b(?:with|and)\s+[A-Z]", q) # the rule is for questions that join people + return owner(q, reply) or (None if COMPARE.search(q) or not joined else with_(q, reply, value_qids)) or year(q, reply) diff --git a/root/wander-train/reach_router_v1.py b/root/wander-train/reach_router_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..abaf849cbb7e139a139f354449541fc45f313fc7 --- /dev/null +++ b/root/wander-train/reach_router_v1.py @@ -0,0 +1,380 @@ +#!/usr/bin/env python3 +"""reach_router_v1 - Oracle7 4.5 REACH: the exact relation router widened, for the questions the core declines at its front +door ("I didn't fully parse that") as well as the ones it withholds. No similarity, no learned weights: a question is +answered only when an admitted route names the relation it asks, a named entity HOLDS that relation in the store, and +every reading of the name that holds it agrees on what is stored. + +Routes (each examined and admitted before it is used): + PATTERNS (asked noun or wh-word, one content word) -> relation and direction: router_patterns_v4 (TriviaQA, w524) and + router_patterns_v5 (SimpleQuestions-Wikidata train, both directions), each admitted at >= 90% answering + precision on both md5 halves with >= 8 firings in each. + LABEL the question names the relation by its Wikidata label or an English alias ("What is the operating income of + Qantas?", "Who is the head of state of France?"): one rule over every relation in the store, examined as a rule. +Subject: entity_linker_v3 (v2 + case-blind questions). The subject must hold the relation; a one-word name answers only +through its most-linked reading; a span that is part of a longer unexplained name is refused (the fragment rule). +Answer type must fit the question: "when" a time, "how many" a count, "who" a person or an organisation, "where" a place; +identifiers, links and media are never given unless asked for; quantities only when they are counts (the store keeps +quantities without their units). At most 5 stored values, listed; more is declined. +Refused as in exact_router_v1: yes/no questions, a hidden hop, a quoted title that is not the span, a past-time qualifier on +a relation that changes over time, blank nodes, an answer that restates the question. +Untrusted routing policy: stored rows and type ancestry are evidence, not proof of source truth or completeness. +use: answer(question) -> {"answer", "values", "property", "direction", "subject_qid", "route", "pattern"} or None""" +import json +import os +import re +import sqlite3 + +import entity_linker_v3 as L +import exact_router_v1 as XR +import date_precision_v1 as DATE + +ROOT = os.environ.get("ORACLE7_ROOT", __import__("os").environ.get("ORACLE7_ROOT", "/opt/oracle-clm") + "") +STORE = ROOT + "/relstore/relations_v2.sqlite3" +REACH = os.environ.get("ORACLE7_REACH_DIR", ROOT + "/relstore") # development may point at a build folder +PATTERN_FILES = (ROOT + "/relstore/router_patterns_v4.json", REACH + "/router_patterns_v5.json") +ALIAS_FILE = REACH + "/prop_aliases_v1.json" +MAX_LIST = 5 +PARTICLES = {"de", "van", "von", "der", "den", "da", "di", "du", "le", "la", "del", "bin", "al", "el", "y", "of", "st", "jr", "sr"} +HUMAN = 5 +ORG = {43229, 4830453, 783794, 215380, 2088357, 891723, 6881511, 15911314, 7278, 327333, 16334295, 163740, 31855, 3918, 1664720, + 847017, 875538, 13406463, 476028, 1047113, 41298, 11032, 1002697, 7210356, 167037, 18388277, 210167, 15265344, 95074} +NO_SHOW = {"external-id", "url", "commonsMedia", "globe-coordinate", "geo-shape", "tabular-data", "math", "musical-notation", + "wikibase-lexeme", "wikibase-form", "wikibase-sense", "entity-schema", "wikibase-property"} +SHOW_ANYWAY = re.compile(r"\b(id|identifier|code|number|url|website|link|symbol|isbn|issn|doi)\b", re.I) +COUNT = re.compile(r"^(number of|population|count)\b", re.I) +WH = re.compile(r"^\s*(who|whom|whose|where|when|what|which|how|name|tell me|give me|list)\b", re.I) +ASKED = [ + re.compile(r"^\s*(?:what|which|who)(?:'s|\s+is|\s+was|\s+are|\s+were)\s+(?:the\s+|a\s+|an\s+)?(?P<x>[a-z][a-z0-9 \-']{1,60}?)" + r"\s+(?:of|for)\s+(?P<y>.+?)\s*[?.!]?\s*$", re.I), + re.compile(r"^\s*(?:what|which|who)(?:'s|\s+is|\s+was|\s+are|\s+were)\s+(?P<y>.+?)'s?\s+(?P<x>[a-z][a-z0-9 \-]{1,60}?)\s*[?.!]?\s*$", re.I), + re.compile(r"^\s*(?:tell me|give me|name|list)\s+(?:the\s+)?(?P<x>[a-z][a-z0-9 \-']{1,60}?)\s+(?:of|for)\s+(?P<y>.+?)\s*[?.!]?\s*$", re.I), + re.compile(r"^\s*(?:the\s+)?(?P<x>[a-z][a-z0-9 \-']{1,60}?)\s+(?:of|for)\s+(?P<y>[^?]+?)\s*\?\s*$", re.I), +] +_S = {} + + +def _load(): + if not _S: + _S["db"] = sqlite3.connect("file:%s?mode=ro&immutable=1" % STORE, uri=True, check_same_thread=False) + pats = {} + for fn in PATTERN_FILES: + if os.path.exists(fn): + for k, v in json.load(open(fn)).items(): + pats.setdefault(tuple(k.split("|", 1)), (v[0], v[4] if len(v) > 4 else "fwd")) + _S["pats"] = pats + al = json.load(open(ALIAS_FILE, encoding="utf-8")) if os.path.exists(ALIAS_FILE) else {} + _S["dtype"] = {int(p): e.get("datatype") for p, e in al.items()} + _S["plabel"] = {int(p): e.get("label") or "P" + p for p, e in al.items()} + idx, cues, lab_idx = {}, {}, {} + for p, e in al.items(): + for i, t in enumerate([e.get("label") or ""] + e.get("aliases", [])): + n = L.norm(t) + if n: + idx.setdefault(n, set()).add(int(p)) + if i == 0: + lab_idx.setdefault(n, set()).add(int(p)) + cues.setdefault(int(p), set()).update(w for w in n.split() if w not in L.STOP) + _S["label_idx"] = lab_idx + _S["time_words"] = {int(p): {_stem(w) for t in [e.get("label") or ""] + e.get("aliases", []) for w in L.norm(t).split()} + for p, e in al.items() if e.get("datatype") == "time"} + for (k, w), (p, _) in pats.items(): + cues.setdefault(p, set()).update(x for x in (k, w) if x not in ("*", "-")) + _S["alias"], _S["cues"] = idx, cues + return _S + + +def label(x): + return L.label(x) if isinstance(x, int) else str(x) + + +def values(qid, p, d): + db = _load()["db"] + if d == "fwd": + rows = db.execute("SELECT o, lit FROM fact INDEXED BY fact_sp WHERE s=? AND p=?", (qid, p)).fetchall() + v = {o if o else lit for o, lit in rows} + else: + v = {s for (s,) in db.execute("SELECT s FROM fact INDEXED BY fact_po WHERE p=? AND o=? LIMIT ?", (p, qid, MAX_LIST + 1))} + return {x for x in v if x is not None and ".well-known/genid" not in str(x)} + + +def classes(qid): + return {o for (o,) in _load()["db"].execute("SELECT o FROM fact INDEXED BY fact_sp WHERE s=? AND p=31", (qid,)) if o} + + +def has(qid, p): + return _load()["db"].execute("SELECT 1 FROM fact INDEXED BY fact_sp WHERE s=? AND p=? LIMIT 1", (qid, p)).fetchone() is not None + + +def fits(q, p, d, vals): + """the answer's type must be what the question asks for""" + s = _load() + dt = s["dtype"].get(p) if d == "fwd" else "wikibase-item" + if dt in NO_SHOW and not SHOW_ANYWAY.search(q): + return False + w = WH.match(q) + wh = w.group(1).lower() if w else "" + if dt == "quantity" and not COUNT.match(s["plabel"].get(p, "")): + return False # the store keeps quantities without units: counts only + if re.match(r"^\s*how\s+(many|much)\b", q, re.I): + return dt == "quantity" + if wh == "when" or re.search(r"\b(what|which)\s+(year|date|day|century|decade)\b", q, re.I): + return dt == "time" + if dt == "time" and not re.search(r"\b(when|year|date|day|century|decade|born on|died on)\b", q, re.I): + return False + items = [x for x in vals if isinstance(x, int)] + if wh in ("who", "whom", "whose"): + return bool(items) and len(items) == len(vals) and all(HUMAN in classes(x) or classes(x) & ORG for x in items) + if wh == "where": + return bool(items) and len(items) == len(vals) and all(has(x, 625) or has(x, 17) or has(x, 131) for x in items) + return True + + +def fragment(q, span, p): + """the span is part of a longer name: a word next to it (past name particles) is a content word nothing explains""" + cues = _load()["cues"].get(p, set()) + toks, sp = L.norm(q).split(), L.norm(span).split() + for i in range(len(toks) - len(sp) + 1): + if toks[i:i + len(sp)] == sp: + for step, j in ((-1, i - 1), (1, i + len(sp))): + while 0 <= j < len(toks) and toks[j] in PARTICLES: + j += step + if 0 <= j < len(toks): + w = toks[j] + if w not in L.STOP and w not in cues and not w.isdigit(): + return True + return False + return False + + +GENERIC = set(("name names called known located famous kind type sort also exactly originally currently which what who where when " + "how many much does did do is was are were has have had born die died the a an of in on at to for by from with " + "about tell give list please something someone thing things person people one ones whose whom").split()) +MAX_UNEXPLAINED = int(os.environ.get("REACH_MAX_UNEXPLAINED", "2")) # development: 2 stopped a Mintaka error, lost nothing + + +def unexplained(q, span, p): + """content words of the question that neither the subject, the relation's own words nor ordinary question words explain""" + cues = _load()["cues"].get(p, set()) + sp = set(L.norm(span).split()) + return [w for w in L.norm(q).split() if w not in sp and w not in cues and w not in GENERIC and w not in L.STOP + and not w.isdigit() and len(w) >= 3] + + +def _agree(q, span, cands, p, d): + """the readings of the name that hold the relation must agree; a one-word name answers through its top reading only""" + if fragment(q, span, p) or len(unexplained(q, span, p)) > MAX_UNEXPLAINED: + return None, None + one = len(L.norm(span).split()) == 1 + use = cands[:1] if one else cands[:3] + sets, displays, subj = [], [], None + for qid, _, _ in use: + v = values(qid, p, d) + if v: + if any(DATE.is_time(x) and not DATE.available(x, q, qid, p) for x in v): + return None, None + sets.append(frozenset(v)) + displays.append(frozenset(DATE.render(x, q, qid, p) if DATE.is_time(x) else x for x in v)) + subj = subj or qid + if not sets or len(set(sets)) != 1 or len(set(displays)) != 1 or len(sets[0]) > MAX_LIST: + return None, None + return sets[0], subj + + +HEADNP = re.compile(r"\b(?:which|what)\s+((?:[a-z\-]+\s+){0,2}?[a-z\-]+)\s+(?:is|was|are|were|did|does|do|has|had|in|of|for|from|" + r"to|by|did|was|were)\b|\bof\s+what\s+((?:[a-z\-]+\s+){0,2}?[a-z\-]+)\s+(?:is|was|are|were)\b", re.I) + + +def _head_relations(q): + """the noun a question asks about, when it is a Wikidata name of a relation ("what job does ...", "which genre is ...")""" + al = _load()["alias"] + m = HEADNP.search(q) + if not m: + return set() + np_ = L.norm(m.group(1) or m.group(2)).split() + for k in range(len(np_)): # longest name first: "football position" before "position" + cand = " ".join(np_[k:]) + for c in (cand, cand[:-1] if cand.endswith("s") else None): + if c and c in al: + return set(_load()["label_idx"].get(c) or al[c]) # a relation's own label outranks another's alias + return set() + + +def _routes(q, span, cands): + """(relation, direction) routes for this span: the admitted patterns, else the asked noun's relation name; when they + name several relations, only those the subject holds count, and they must come down to one""" + pats = _load()["pats"] + matched = {f: pats[f] for f in XR.features(q, span) if f in pats} + rels = set(matched.values()) + route, pat = "pattern", "|".join(sorted(matched)[0]) if matched else "" + # (development 2026-10-21: routing by the asked noun's relation name without admission measured 15 right, 32 wrong on + # SimpleQuestions valid - not used; asked nouns route only through admitted patterns) + if len(rels) > 1: + held = {(p, d) for p, d in rels if any(values(c[0], p, d) for c in cands[:3])} + rels = held + if len(rels) == 1: + rel = rels.pop() + # a pattern that matched on its asked word alone ("where|*") says nothing about the rest of the question: it answers + # only when every content word is explained (gate check 2026-10-21: "Otis Barton was a pioneer in exploring where?") + if all(f[1] == "*" for f in matched if matched[f] == rel) and unexplained(q, span, rel[0]): + return [] + return [(rel, route, pat)] + return [] + + +WHEN = re.compile(r"^\s*(?:when|in\s+what\s+year|what\s+year|in\s+which\s+year|which\s+year|on\s+what\s+date|what\s+date)\s+" + r"(?:was|were|is|are|did|does|do)\s+(?P<y>.+?)\s+(?P<v>[a-z]+)(?:\s+(?:in|on|at|for|out|up|down|open))?\s*\?\s*$", re.I) + + +def _stem(w): + for suf in ("ied", "ed", "d", "s"): + if w.endswith(suf) and len(w) - len(suf) >= 3: + return w[: -len(suf)] + ("y" if suf == "ied" else "") + return w + + +WHEN_ON = os.environ.get("REACH_WHEN") == "1" # not admitted (2026-10-21: TriviaQA exam too few firings): off + + +def _when_routes(q): + """ "When was Y born?": the date relations one of whose Wikidata names holds the verb (born -> date of birth)""" + m = WHEN.match(q) if WHEN_ON else None + if not m: + return [] + s_ = _load() + v = _stem(L.norm(m.group("v"))) + props = {p for p, dt in s_["dtype"].items() if dt == "time" and v in s_["time_words"].get(p, ())} + return [(props, m.group("y"), "when:" + m.group("v"))] if props else [] + + +def _label_routes(q): + """the question names the relation: (relation, subject text, the asked phrase)""" + al = _load()["alias"] + out = _when_routes(q) + if out: + return out + for rx in ASKED: + m = rx.match(q) + if not m: + continue + x = L.norm(m.group("x")) + for cand in (x, x[:-1] if x.endswith("s") else None, re.sub(r"^(the|a|an) ", "", x)): + if cand and cand in al: + out.append((al[cand], m.group("y"), cand)) + break + if out: + break + return out + + +DEF_OPEN = ("is", "are", "was", "can", "refers", "means", "describes") + + +def definition_reply(q, reply): + """the reply defines the noun the question asks about ("Genre is any style ...") instead of answering it for the thing + the question names ("what genre is the album London by Night"): not an answer""" + nouns, named_parts = set(), set() + m = HEADNP.search(q) + if m: + nouns.add(L.norm(m.group(1) or m.group(2)).split()[-1]) + for rx in ASKED: + mm = rx.match(q) + if mm: + nouns.add(L.norm(mm.group("x")).split()[-1]) + named_parts |= {w for w in L.norm(mm.group("y")).split() if w not in L.STOP and len(w) >= 3} + words = L.norm(re.sub(r"^\s*\[ev:[a-z_]+\]\s*", "", str(reply))).split()[:9] + while words and words[0] in ("the", "a", "an"): + words = words[1:] + if len(words) < 2 or words[0].rstrip("s") not in {n.rstrip("s") for n in nouns if n}: + return False + # "<noun> is ...", or "<noun> of <a short phrase> is ..." ("The nationality of a person is ...") + k = next((i for i in range(1, min(len(words), 6)) if words[i] in DEF_OPEN), None) + if k is None or (k > 1 and words[1] != "of"): + return False + if named_parts & set(words[:k]): + return False # "Laws of Thermodynamics is ...": it defines the very thing asked + sp = L.link(q, 3)[:1] + named = L.norm(sp[0][0]) if sp else "" + return bool(named) and named not in L.norm(str(reply)) + + +def _bare(text): + """a name without a leading article, for comparing a linked span with the text it should be ("The Goonies" = "Goonies")""" + return re.sub(r"^(the|a|an) ", "", L.norm(text)) + + +MONTHS = ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December") + + +def show_time(v, q, subject=None, property=None): + """Use bound source precision/calendar; missing metadata is explicitly unknown.""" + return DATE.render(v, q, subject, property) + + +def _show(v, q, p, subject=None): + if isinstance(v, int): + return label(v) + if DATE.is_time(v): + return show_time(v, q, subject, p) + if re.match(r"^-?\d+(\.0+)?$", str(v)): + return "{:,}".format(int(float(v))) + return str(v) + + +def answer(q, pinned=None): + """pinned = (span text, qid): a subject already known (the answer of an earlier hop), not linked again by its name""" + q = str(q).strip() + if XR.POLAR.search(q) or not (WH.match(q) or q.endswith("?")): + return None + sp = L.link(q, 3)[:3] + if pinned: + sp = [(pinned[0], [(pinned[1], 10 ** 6, label(pinned[1]))])] + [x for x in sp if L.norm(x[0]) != L.norm(pinned[0])] + found = [] + for span, cands in sp: # PATTERN route: the first span whose reading holds the relation + if XR.hop(q, span) or not XR.subject_ok(q, span): + continue + for (p, d), route, pat in _routes(q, span, cands): + if p in XR.TIME_VARIANT and XR.PAST.search(q): + continue + v, subj = _agree(q, span, cands, p, d) + if v is not None and fits(q, p, d, v): + found.append((p, d, v, subj, route, pat)) + break + if found: + break + if not found: # LABEL route: the asked phrase names the relation + for props, ytext, asked in _label_routes(q): + ysp = [sp[0]] if pinned and L.norm(ytext) == L.norm(pinned[0]) else L.link(ytext, 3)[:1] + if not ysp or _bare(ysp[0][0]) != _bare(ytext): + continue # the subject must be exactly the named entity + span, cands = ysp[0] + hits = [] + for p in sorted(props): + if p in XR.TIME_VARIANT and XR.PAST.search(q): + continue + v, subj = _agree(q, span, cands, p, "fwd") + if v is not None and fits(q, p, "fwd", v): + hits.append((p, "fwd", v, subj, "when" if asked.startswith("when:") else "label", asked)) + if len({h[2] for h in hits}) == 1: + found.append(hits[0]) + break + if not found: + return None + p, d, v, subj, route, pat = found[0] + shown = [_show(x, q, p, subj) for x in v] + if not all(shown): + return None # a value with no English name is not shown + shown = sorted(shown) + aw = [w for x in shown for w in L.norm(x).split() if w not in L.STOP] + if subj in v or (not all(isinstance(x, int) for x in v) + and aw and all(w in set(L.norm(q).split()) for w in aw)): + return None # entity identity, not overlapping labels, is restatement + text = shown[0] if len(shown) == 1 else ", ".join(shown[:-1]) + " and " + shown[-1] + return {"answer": text, "values": shown, "raw": sorted(v, key=str), "property": p, "direction": d, "subject_qid": subj, + "route": route, "pattern": pat, + "date_evidence": [DATE.evidence(x, subj, p, q) for x in v if DATE.is_time(x)]} + + +if __name__ == "__main__": + import sys + for q in sys.argv[1:]: + print(q, "->", answer(q)) diff --git a/root/wander-train/reach_router_v2.py b/root/wander-train/reach_router_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..2199dee88814d947c8a22de9c19622fdd0e7913c --- /dev/null +++ b/root/wander-train/reach_router_v2.py @@ -0,0 +1,421 @@ +#!/usr/bin/env python3 +"""reach_router_v2 - 4.5 (fold w565, pre-registration v12): reach_router_v1 + two changes, developed on spent data only: + PATTERNS v6 mined over SimpleQuestions-Wikidata train AND valid (v5 used train): 90 patterns, 31 relations + FAMILY when the relation a pattern names is not one the subject holds, the other relations that patterns of the + SAME asked word lead to are tried ("which country is X from": a person holds country of citizenship, a film + country of origin); exactly one may be held, and it must fit the question as before + +reach_router_v1 - Oracle7 4.5 REACH: the exact relation router widened, for the questions the core declines at its front +door ("I didn't fully parse that") as well as the ones it withholds. No similarity, no learned weights: a question is +answered only when an admitted route names the relation it asks, a named entity HOLDS that relation in the store, and +every reading of the name that holds it agrees on what is stored. + +Routes (each examined and admitted before it is used): + PATTERNS (asked noun or wh-word, one content word) -> relation and direction: router_patterns_v4 (TriviaQA, w524) and + router_patterns_v5 (SimpleQuestions-Wikidata train, both directions), each admitted at >= 90% answering + precision on both md5 halves with >= 8 firings in each. + LABEL the question names the relation by its Wikidata label or an English alias ("What is the operating income of + Qantas?", "Who is the head of state of France?"): one rule over every relation in the store, examined as a rule. +Subject: entity_linker_v3 (v2 + case-blind questions). The subject must hold the relation; a one-word name answers only +through its most-linked reading; a span that is part of a longer unexplained name is refused (the fragment rule). +Answer type must fit the question: "when" a time, "how many" a count, "who" a person or an organisation, "where" a place; +identifiers, links and media are never given unless asked for; quantities only when they are counts (the store keeps +quantities without their units). At most 5 stored values, listed; more is declined. +Refused as in exact_router_v1: yes/no questions, a hidden hop, a quoted title that is not the span, a past-time qualifier on +a relation that changes over time, blank nodes, an answer that restates the question. +Untrusted routing policy: stored rows and type ancestry are evidence, not proof of source truth or completeness. +use: answer(question) -> {"answer", "values", "property", "direction", "subject_qid", "route", "pattern"} or None""" +import json +import os +import re +import sqlite3 + +import entity_linker_v3 as L +import exact_router_v1 as XR +import date_precision_v1 as DATE + +ROOT = os.environ.get("ORACLE7_ROOT", __import__("os").environ.get("ORACLE7_ROOT", "/opt/oracle-clm") + "") +STORE = ROOT + "/relstore/relations_v2.sqlite3" +REACH = os.environ.get("ORACLE7_REACH_DIR", ROOT + "/relstore") # development may point at a build folder +PATTERN_FILES = (ROOT + "/relstore/router_patterns_v4.json", REACH + "/router_patterns_v6.json") +ALIAS_FILE = REACH + "/prop_aliases_v1.json" +MAX_LIST = 5 +FAMILY_ON = os.environ.get("REACH_FAMILY", "1") == "1" +PARTICLES = {"de", "van", "von", "der", "den", "da", "di", "du", "le", "la", "del", "bin", "al", "el", "y", "of", "st", "jr", "sr"} +HUMAN = 5 +ORG = {43229, 4830453, 783794, 215380, 2088357, 891723, 6881511, 15911314, 7278, 327333, 16334295, 163740, 31855, 3918, 1664720, + 847017, 875538, 13406463, 476028, 1047113, 41298, 11032, 1002697, 7210356, 167037, 18388277, 210167, 15265344, 95074} +NO_SHOW = {"external-id", "url", "commonsMedia", "globe-coordinate", "geo-shape", "tabular-data", "math", "musical-notation", + "wikibase-lexeme", "wikibase-form", "wikibase-sense", "entity-schema", "wikibase-property"} +SHOW_ANYWAY = re.compile(r"\b(id|identifier|code|number|url|website|link|symbol|isbn|issn|doi)\b", re.I) +COUNT = re.compile(r"^(number of|population|count)\b", re.I) +WH = re.compile(r"^\s*(who|whom|whose|where|when|what|which|how|name|tell me|give me|list)\b", re.I) +ASKED = [ + re.compile(r"^\s*(?:what|which|who)(?:'s|\s+is|\s+was|\s+are|\s+were)\s+(?:the\s+|a\s+|an\s+)?(?P<x>[a-z][a-z0-9 \-']{1,60}?)" + r"\s+(?:of|for)\s+(?P<y>.+?)\s*[?.!]?\s*$", re.I), + re.compile(r"^\s*(?:what|which|who)(?:'s|\s+is|\s+was|\s+are|\s+were)\s+(?P<y>.+?)'s?\s+(?P<x>[a-z][a-z0-9 \-]{1,60}?)\s*[?.!]?\s*$", re.I), + re.compile(r"^\s*(?:tell me|give me|name|list)\s+(?:the\s+)?(?P<x>[a-z][a-z0-9 \-']{1,60}?)\s+(?:of|for)\s+(?P<y>.+?)\s*[?.!]?\s*$", re.I), + re.compile(r"^\s*(?:the\s+)?(?P<x>[a-z][a-z0-9 \-']{1,60}?)\s+(?:of|for)\s+(?P<y>[^?]+?)\s*\?\s*$", re.I), +] +_S = {} + + +def _load(): + if not _S: + _S["db"] = sqlite3.connect("file:%s?mode=ro&immutable=1" % STORE, uri=True, check_same_thread=False) + pats = {} + for fn in PATTERN_FILES: + if os.path.exists(fn): + for k, v in json.load(open(fn)).items(): + pats.setdefault(tuple(k.split("|", 1)), (v[0], v[4] if len(v) > 4 else "fwd")) + _S["pats"] = pats + fam = {} + for (k, w), rel in pats.items(): + if k not in ("-",): + fam.setdefault(k, set()).add(rel) + _S["family"] = fam + al = json.load(open(ALIAS_FILE, encoding="utf-8")) if os.path.exists(ALIAS_FILE) else {} + _S["dtype"] = {int(p): e.get("datatype") for p, e in al.items()} + _S["plabel"] = {int(p): e.get("label") or "P" + p for p, e in al.items()} + idx, cues, lab_idx = {}, {}, {} + for p, e in al.items(): + for i, t in enumerate([e.get("label") or ""] + e.get("aliases", [])): + n = L.norm(t) + if n: + idx.setdefault(n, set()).add(int(p)) + if i == 0: + lab_idx.setdefault(n, set()).add(int(p)) + cues.setdefault(int(p), set()).update(w for w in n.split() if w not in L.STOP) + _S["label_idx"] = lab_idx + _S["time_words"] = {int(p): {_stem(w) for t in [e.get("label") or ""] + e.get("aliases", []) for w in L.norm(t).split()} + for p, e in al.items() if e.get("datatype") == "time"} + for (k, w), (p, _) in pats.items(): + cues.setdefault(p, set()).update(x for x in (k, w) if x not in ("*", "-")) + _S["alias"], _S["cues"] = idx, cues + return _S + + +def label(x): + return L.label(x) if isinstance(x, int) else str(x) + + +def values(qid, p, d): + db = _load()["db"] + if d == "fwd": + rows = db.execute("SELECT o, lit FROM fact INDEXED BY fact_sp WHERE s=? AND p=?", (qid, p)).fetchall() + v = {o if o else lit for o, lit in rows} + else: + v = {s for (s,) in db.execute("SELECT s FROM fact INDEXED BY fact_po WHERE p=? AND o=? LIMIT ?", (p, qid, MAX_LIST + 1))} + return {x for x in v if x is not None and ".well-known/genid" not in str(x)} + + +def classes(qid): + return {o for (o,) in _load()["db"].execute("SELECT o FROM fact INDEXED BY fact_sp WHERE s=? AND p=31", (qid,)) if o} + + +def has(qid, p): + return _load()["db"].execute("SELECT 1 FROM fact INDEXED BY fact_sp WHERE s=? AND p=? LIMIT 1", (qid, p)).fetchone() is not None + + +def fits(q, p, d, vals): + """the answer's type must be what the question asks for""" + s = _load() + dt = s["dtype"].get(p) if d == "fwd" else "wikibase-item" + if dt in NO_SHOW and not SHOW_ANYWAY.search(q): + return False + w = WH.match(q) + wh = w.group(1).lower() if w else "" + if dt == "quantity" and not COUNT.match(s["plabel"].get(p, "")): + return False # the store keeps quantities without units: counts only + if re.match(r"^\s*how\s+(many|much)\b", q, re.I): + return dt == "quantity" + if wh == "when" or re.search(r"\b(what|which)\s+(year|date|day|century|decade)\b", q, re.I): + return dt == "time" + if dt == "time" and not re.search(r"\b(when|year|date|day|century|decade|born on|died on)\b", q, re.I): + return False + items = [x for x in vals if isinstance(x, int)] + if wh in ("who", "whom", "whose"): + return bool(items) and len(items) == len(vals) and all(HUMAN in classes(x) or classes(x) & ORG for x in items) + if wh == "where": + return bool(items) and len(items) == len(vals) and all(has(x, 625) or has(x, 17) or has(x, 131) for x in items) + return True + + +def fragment(q, span, p): + """the span is part of a longer name: a word next to it (past name particles) is a content word nothing explains""" + cues = _load()["cues"].get(p, set()) + toks, sp = L.norm(q).split(), L.norm(span).split() + for i in range(len(toks) - len(sp) + 1): + if toks[i:i + len(sp)] == sp: + for step, j in ((-1, i - 1), (1, i + len(sp))): + while 0 <= j < len(toks) and toks[j] in PARTICLES: + j += step + if 0 <= j < len(toks): + w = toks[j] + if w not in L.STOP and w not in cues and not w.isdigit(): + return True + return False + return False + + +GENERIC = set(("name names called known located famous kind type sort also exactly originally currently which what who where when " + "how many much does did do is was are were has have had born die died the a an of in on at to for by from with " + "about tell give list please something someone thing things person people one ones whose whom").split()) +MAX_UNEXPLAINED = int(os.environ.get("REACH_MAX_UNEXPLAINED", "2")) # development: 2 stopped a Mintaka error, lost nothing + + +def unexplained(q, span, p): + """content words of the question that neither the subject, the relation's own words nor ordinary question words explain""" + cues = _load()["cues"].get(p, set()) + sp = set(L.norm(span).split()) + return [w for w in L.norm(q).split() if w not in sp and w not in cues and w not in GENERIC and w not in L.STOP + and not w.isdigit() and len(w) >= 3] + + +def _agree(q, span, cands, p, d): + """the readings of the name that hold the relation must agree; a one-word name answers through its top reading only""" + if fragment(q, span, p) or len(unexplained(q, span, p)) > MAX_UNEXPLAINED: + return None, None + one = len(L.norm(span).split()) == 1 + use = cands[:1] if one else cands[:3] + sets, displays, subj = [], [], None + for qid, _, _ in use: + v = values(qid, p, d) + if v: + if any(DATE.is_time(x) and not DATE.available(x, q, qid, p) for x in v): + return None, None + sets.append(frozenset(v)) + displays.append(frozenset(DATE.render(x, q, qid, p) if DATE.is_time(x) else x for x in v)) + subj = subj or qid + if not sets or len(set(sets)) != 1 or len(set(displays)) != 1 or len(sets[0]) > MAX_LIST: + return None, None + return sets[0], subj + + +HEADNP = re.compile(r"\b(?:which|what)\s+((?:[a-z\-]+\s+){0,2}?[a-z\-]+)\s+(?:is|was|are|were|did|does|do|has|had|in|of|for|from|" + r"to|by|did|was|were)\b|\bof\s+what\s+((?:[a-z\-]+\s+){0,2}?[a-z\-]+)\s+(?:is|was|are|were)\b", re.I) + + +def _head_relations(q): + """the noun a question asks about, when it is a Wikidata name of a relation ("what job does ...", "which genre is ...")""" + al = _load()["alias"] + m = HEADNP.search(q) + if not m: + return set() + np_ = L.norm(m.group(1) or m.group(2)).split() + for k in range(len(np_)): # longest name first: "football position" before "position" + cand = " ".join(np_[k:]) + for c in (cand, cand[:-1] if cand.endswith("s") else None): + if c and c in al: + return set(_load()["label_idx"].get(c) or al[c]) # a relation's own label outranks another's alias + return set() + + +def _routes(q, span, cands): + """(relation, direction) routes for this span: the admitted patterns, else the asked noun's relation name; when they + name several relations, only those the subject holds count, and they must come down to one""" + pats = _load()["pats"] + matched = {f: pats[f] for f in XR.features(q, span) if f in pats} + rels = set(matched.values()) + route, pat = "pattern", "|".join(sorted(matched)[0]) if matched else "" + # (development 2026-10-21: routing by the asked noun's relation name without admission measured 15 right, 32 wrong on + # SimpleQuestions valid - not used; asked nouns route only through admitted patterns) + if len(rels) > 1: + held = {(p, d) for p, d in rels if any(values(c[0], p, d) for c in cands[:3])} + rels = held + if len(rels) == 1 and FAMILY_ON: + r0 = next(iter(rels)) + if not any(values(c[0], r0[0], r0[1]) for c in cands[:3]): + # the named relation is not held: the other relations patterns of the same asked word lead to + keys = {f[0] for f in matched if matched[f] == r0} + fam = set().union(*[_load()["family"].get(k, set()) for k in keys]) - {r0} if keys else set() + held = {(p, d) for p, d in fam if any(values(c[0], p, d) for c in cands[:3])} + if len(held) == 1: + rels = held + route = "family" + if len(rels) == 1: + rel = rels.pop() + # a pattern that matched on its asked word alone ("where|*") says nothing about the rest of the question: it answers + # only when every content word is explained (gate check 2026-10-21: "Otis Barton was a pioneer in exploring where?") + if all(f[1] == "*" for f in matched if matched[f] == rel) and unexplained(q, span, rel[0]): + return [] + return [(rel, route, pat)] + return [] + + +WHEN = re.compile(r"^\s*(?:when|in\s+what\s+year|what\s+year|in\s+which\s+year|which\s+year|on\s+what\s+date|what\s+date)\s+" + r"(?:was|were|is|are|did|does|do)\s+(?P<y>.+?)\s+(?P<v>[a-z]+)(?:\s+(?:in|on|at|for|out|up|down|open))?\s*\?\s*$", re.I) + + +def _stem(w): + for suf in ("ied", "ed", "d", "s"): + if w.endswith(suf) and len(w) - len(suf) >= 3: + return w[: -len(suf)] + ("y" if suf == "ied" else "") + return w + + +WHEN_ON = os.environ.get("REACH_WHEN") == "1" # not admitted (2026-10-21: TriviaQA exam too few firings): off + + +def _when_routes(q): + """ "When was Y born?": the date relations one of whose Wikidata names holds the verb (born -> date of birth)""" + m = WHEN.match(q) if WHEN_ON else None + if not m: + return [] + s_ = _load() + v = _stem(L.norm(m.group("v"))) + props = {p for p, dt in s_["dtype"].items() if dt == "time" and v in s_["time_words"].get(p, ())} + return [(props, m.group("y"), "when:" + m.group("v"))] if props else [] + + +HOWMANY = re.compile(r"^\s*how\s+many\s+(?P<x>[a-z][a-z \-]{1,40}?)\s+(?:does|did|do|has|had|have|is|are|were|was)\s+" + r"(?P<y>.+?)(?:\s+(?:have|has|had|got|contain|include|hold))?\s*\?\s*$", re.I) + + +def _count_routes(q): + """v2: "How many children does Y have?" asks the relation named "number of children" - a count the store holds, never a + count of stored values (the store is not complete)""" + m = HOWMANY.match(q) + if not m: + return [] + al = _load()["alias"] + x = L.norm(m.group("x")) + for cand in ("number of " + x, "number of " + x.rstrip("s"), "count of " + x): + if cand in al: + return [(al[cand], m.group("y"), "count:" + x)] + return [] + + +def _label_routes(q): + """the question names the relation: (relation, subject text, the asked phrase)""" + al = _load()["alias"] + out = _when_routes(q) or _count_routes(q) + if out: + return out + q = re.sub(r"'s\s+(name|full name)\s*\?\s*$", "?", q, flags=re.I) # v2: "Y's wife's name?" asks "Y's wife?" + for rx in ASKED: + m = rx.match(q) + if not m: + continue + x = L.norm(m.group("x")) + for cand in (x, x[:-1] if x.endswith("s") else None, re.sub(r"^(the|a|an) ", "", x)): + if cand and cand in al: + out.append((al[cand], m.group("y"), cand)) + break + if out: + break + return out + + +DEF_OPEN = ("is", "are", "was", "can", "refers", "means", "describes") + + +def definition_reply(q, reply): + """the reply defines the noun the question asks about ("Genre is any style ...") instead of answering it for the thing + the question names ("what genre is the album London by Night"): not an answer""" + nouns, named_parts = set(), set() + m = HEADNP.search(q) + if m: + nouns.add(L.norm(m.group(1) or m.group(2)).split()[-1]) + for rx in ASKED: + mm = rx.match(q) + if mm: + nouns.add(L.norm(mm.group("x")).split()[-1]) + named_parts |= {w for w in L.norm(mm.group("y")).split() if w not in L.STOP and len(w) >= 3} + words = L.norm(re.sub(r"^\s*\[ev:[a-z_]+\]\s*", "", str(reply))).split()[:9] + while words and words[0] in ("the", "a", "an"): + words = words[1:] + if len(words) < 2 or words[0].rstrip("s") not in {n.rstrip("s") for n in nouns if n}: + return False + # "<noun> is ...", or "<noun> of <a short phrase> is ..." ("The nationality of a person is ...") + k = next((i for i in range(1, min(len(words), 6)) if words[i] in DEF_OPEN), None) + if k is None or (k > 1 and words[1] != "of"): + return False + if named_parts & set(words[:k]): + return False # "Laws of Thermodynamics is ...": it defines the very thing asked + sp = L.link(q, 3)[:1] + named = L.norm(sp[0][0]) if sp else "" + return bool(named) and named not in L.norm(str(reply)) + + +def _bare(text): + """a name without a leading article, for comparing a linked span with the text it should be ("The Goonies" = "Goonies")""" + return re.sub(r"^(the|a|an) ", "", L.norm(text)) + + +MONTHS = ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December") + + +def show_time(v, q, subject=None, property=None): + """Use bound source precision/calendar; missing metadata is explicitly unknown.""" + return DATE.render(v, q, subject, property) + + +def _show(v, q, p, subject=None): + if isinstance(v, int): + return label(v) + if DATE.is_time(v): + return show_time(v, q, subject, p) + if re.match(r"^-?\d+(\.0+)?$", str(v)): + return "{:,}".format(int(float(v))) + return str(v) + + +def answer(q, pinned=None): + """pinned = (span text, qid): a subject already known (the answer of an earlier hop), not linked again by its name""" + q = str(q).strip() + if XR.POLAR.search(q) or not (WH.match(q) or q.endswith("?")): + return None + sp = L.link(q, 3)[:3] + if pinned: + sp = [(pinned[0], [(pinned[1], 10 ** 6, label(pinned[1]))])] + [x for x in sp if L.norm(x[0]) != L.norm(pinned[0])] + found = [] + for span, cands in sp: # PATTERN route: the first span whose reading holds the relation + if XR.hop(q, span) or not XR.subject_ok(q, span): + continue + for (p, d), route, pat in _routes(q, span, cands): + if p in XR.TIME_VARIANT and XR.PAST.search(q): + continue + v, subj = _agree(q, span, cands, p, d) + if v is not None and fits(q, p, d, v): + found.append((p, d, v, subj, route, pat)) + break + if found: + break + if not found: # LABEL route: the asked phrase names the relation + for props, ytext, asked in _label_routes(q): + ysp = [sp[0]] if pinned and L.norm(ytext) == L.norm(pinned[0]) else L.link(ytext, 3)[:1] + if not ysp or _bare(ysp[0][0]) != _bare(ytext): + continue # the subject must be exactly the named entity + span, cands = ysp[0] + hits = [] + for p in sorted(props): + if p in XR.TIME_VARIANT and XR.PAST.search(q): + continue + v, subj = _agree(q, span, cands, p, "fwd") + if v is not None and fits(q, p, "fwd", v): + hits.append((p, "fwd", v, subj, "when" if asked.startswith("when:") else "count" if asked.startswith("count:") else "label", asked)) + if len({h[2] for h in hits}) == 1: + found.append(hits[0]) + break + if not found: + return None + p, d, v, subj, route, pat = found[0] + shown = [_show(x, q, p, subj) for x in v] + if not all(shown): + return None # a value with no English name is not shown + shown = sorted(shown) + aw = [w for x in shown for w in L.norm(x).split() if w not in L.STOP] + if subj in v or (not all(isinstance(x, int) for x in v) + and aw and all(w in set(L.norm(q).split()) for w in aw)): + return None # entity identity, not overlapping labels, is restatement + text = shown[0] if len(shown) == 1 else ", ".join(shown[:-1]) + " and " + shown[-1] + return {"answer": text, "values": shown, "raw": sorted(v, key=str), "property": p, "direction": d, "subject_qid": subj, + "route": route, "pattern": pat, + "date_evidence": [DATE.evidence(x, subj, p, q) for x in v if DATE.is_time(x)]} + + +if __name__ == "__main__": + import sys + for q in sys.argv[1:]: + print(q, "->", answer(q)) diff --git a/root/wander-train/reach_router_v3.py b/root/wander-train/reach_router_v3.py new file mode 100644 index 0000000000000000000000000000000000000000..798ee427baaa69cf834e1998288249cdf8816495 --- /dev/null +++ b/root/wander-train/reach_router_v3.py @@ -0,0 +1,504 @@ +#!/usr/bin/env python3 +"""reach_router_v3 - 4.6 development: reach_router_v2 + AGENT: "Who founded Microsoft?" asks the relation named by the +verb's passive ("founded by") or its agent noun ("founder"); the named thing must hold exactly one such relation, and the +answer must be a person or an organisation. + +reach_router_v2 - 4.5 (fold w565, pre-registration v12): reach_router_v1 + two changes, developed on spent data only: + PATTERNS v6 mined over SimpleQuestions-Wikidata train AND valid (v5 used train): 90 patterns, 31 relations + FAMILY when the relation a pattern names is not one the subject holds, the other relations that patterns of the + SAME asked word lead to are tried ("which country is X from": a person holds country of citizenship, a film + country of origin); exactly one may be held, and it must fit the question as before + +reach_router_v1 - Oracle7 4.5 REACH: the exact relation router widened, for the questions the core declines at its front +door ("I didn't fully parse that") as well as the ones it withholds. No similarity, no learned weights: a question is +answered only when an admitted route names the relation it asks, a named entity HOLDS that relation in the store, and +every reading of the name that holds it agrees on what is stored. + +Routes (each examined and admitted before it is used): + PATTERNS (asked noun or wh-word, one content word) -> relation and direction: router_patterns_v4 (TriviaQA, w524) and + router_patterns_v5 (SimpleQuestions-Wikidata train, both directions), each admitted at >= 90% answering + precision on both md5 halves with >= 8 firings in each. + LABEL the question names the relation by its Wikidata label or an English alias ("What is the operating income of + Qantas?", "Who is the head of state of France?"): one rule over every relation in the store, examined as a rule. +Subject: entity_linker_v3 (v2 + case-blind questions). The subject must hold the relation; a one-word name answers only +through its most-linked reading; a span that is part of a longer unexplained name is refused (the fragment rule). +Answer type must fit the question: "when" a time, "how many" a count, "who" a person or an organisation, "where" a place; +identifiers, links and media are never given unless asked for; quantities only when they are counts (the store keeps +quantities without their units). At most 5 stored values, listed; more is declined. +Refused as in exact_router_v1: yes/no questions, a hidden hop, a quoted title that is not the span, a past-time qualifier on +a relation that changes over time, blank nodes, an answer that restates the question. +Untrusted routing policy: stored rows and type ancestry are evidence, not proof of source truth or completeness. +use: answer(question) -> {"answer", "values", "property", "direction", "subject_qid", "route", "pattern"} or None""" +import json +import os +import re +import sqlite3 + +import entity_linker_v3 as L +import exact_router_v1 as XR +import date_precision_v1 as DATE + +ROOT = os.environ.get("ORACLE7_ROOT", __import__("os").environ.get("ORACLE7_ROOT", "/opt/oracle-clm") + "") +STORE = ROOT + "/relstore/relations_v2.sqlite3" +REACH = os.environ.get("ORACLE7_REACH_DIR", ROOT + "/relstore") # development may point at a build folder +PATTERN_FILES = (ROOT + "/relstore/router_patterns_v4.json", REACH + "/router_patterns_v6.json") +ALIAS_FILE = REACH + "/prop_aliases_v1.json" +MAX_LIST = 5 +FAMILY_ON = os.environ.get("REACH_FAMILY", "1") == "1" +AGENT_ON = os.environ.get("REACH_AGENT", "1") == "1" +PARTICLES = {"de", "van", "von", "der", "den", "da", "di", "du", "le", "la", "del", "bin", "al", "el", "y", "of", "st", "jr", "sr"} +HUMAN = 5 +ORG = {43229, 4830453, 783794, 215380, 2088357, 891723, 6881511, 15911314, 7278, 327333, 16334295, 163740, 31855, 3918, 1664720, + 847017, 875538, 13406463, 476028, 1047113, 41298, 11032, 1002697, 7210356, 167037, 18388277, 210167, 15265344, 95074} +NO_SHOW = {"external-id", "url", "commonsMedia", "globe-coordinate", "geo-shape", "tabular-data", "math", "musical-notation", + "wikibase-lexeme", "wikibase-form", "wikibase-sense", "entity-schema", "wikibase-property"} +SHOW_ANYWAY = re.compile(r"\b(id|identifier|code|number|url|website|link|symbol|isbn|issn|doi)\b", re.I) +COUNT = re.compile(r"^(number of|population|count)\b", re.I) +WH = re.compile(r"^\s*(who|whom|whose|where|when|what|which|how|name|tell me|give me|list)\b", re.I) +ASKED = [ + re.compile(r"^\s*(?:what|which|who)(?:'s|\s+is|\s+was|\s+are|\s+were)\s+(?:the\s+|a\s+|an\s+)?(?P<x>[a-z][a-z0-9 \-']{1,60}?)" + r"\s+(?:of|for)\s+(?P<y>.+?)\s*[?.!]?\s*$", re.I), + re.compile(r"^\s*(?:what|which|who)(?:'s|\s+is|\s+was|\s+are|\s+were)\s+(?P<y>.+?)'s?\s+(?P<x>[a-z][a-z0-9 \-]{1,60}?)\s*[?.!]?\s*$", re.I), + re.compile(r"^\s*(?:tell me|give me|name|list)\s+(?:the\s+)?(?P<x>[a-z][a-z0-9 \-']{1,60}?)\s+(?:of|for)\s+(?P<y>.+?)\s*[?.!]?\s*$", re.I), + re.compile(r"^\s*(?:the\s+)?(?P<x>[a-z][a-z0-9 \-']{1,60}?)\s+(?:of|for)\s+(?P<y>[^?]+?)\s*\?\s*$", re.I), +] +_S = {} + + +def _load(): + if not _S: + _S["db"] = sqlite3.connect("file:%s?mode=ro&immutable=1" % STORE, uri=True, check_same_thread=False) + pats = {} + for fn in PATTERN_FILES: + if os.path.exists(fn): + for k, v in json.load(open(fn)).items(): + pats.setdefault(tuple(k.split("|", 1)), (v[0], v[4] if len(v) > 4 else "fwd")) + _S["pats"] = pats + fam = {} + for (k, w), rel in pats.items(): + if k not in ("-",): + fam.setdefault(k, set()).add(rel) + _S["family"] = fam + al = json.load(open(ALIAS_FILE, encoding="utf-8")) if os.path.exists(ALIAS_FILE) else {} + _S["dtype"] = {int(p): e.get("datatype") for p, e in al.items()} + _S["plabel"] = {int(p): e.get("label") or "P" + p for p, e in al.items()} + idx, cues, lab_idx = {}, {}, {} + for p, e in al.items(): + for i, t in enumerate([e.get("label") or ""] + e.get("aliases", [])): + n = L.norm(t) + if n: + idx.setdefault(n, set()).add(int(p)) + if i == 0: + lab_idx.setdefault(n, set()).add(int(p)) + cues.setdefault(int(p), set()).update(w for w in n.split() if w not in L.STOP) + _S["label_idx"] = lab_idx + _S["time_words"] = {int(p): {_stem(w) for t in [e.get("label") or ""] + e.get("aliases", []) for w in L.norm(t).split()} + for p, e in al.items() if e.get("datatype") == "time"} + for (k, w), (p, _) in pats.items(): + cues.setdefault(p, set()).update(x for x in (k, w) if x not in ("*", "-")) + _S["alias"], _S["cues"] = idx, cues + return _S + + +def label(x): + return L.label(x) if isinstance(x, int) else str(x) + + +def values(qid, p, d): + db = _load()["db"] + if d == "fwd": + rows = db.execute("SELECT o, lit FROM fact INDEXED BY fact_sp WHERE s=? AND p=?", (qid, p)).fetchall() + v = {o if o else lit for o, lit in rows} + else: + v = {s for (s,) in db.execute("SELECT s FROM fact INDEXED BY fact_po WHERE p=? AND o=? LIMIT ?", (p, qid, MAX_LIST + 1))} + return {x for x in v if x is not None and ".well-known/genid" not in str(x)} + + +def classes(qid): + return {o for (o,) in _load()["db"].execute("SELECT o FROM fact INDEXED BY fact_sp WHERE s=? AND p=31", (qid,)) if o} + + +def has(qid, p): + return _load()["db"].execute("SELECT 1 FROM fact INDEXED BY fact_sp WHERE s=? AND p=? LIMIT 1", (qid, p)).fetchone() is not None + + +def fits(q, p, d, vals): + """the answer's type must be what the question asks for""" + s = _load() + dt = s["dtype"].get(p) if d == "fwd" else "wikibase-item" + if dt in NO_SHOW and not SHOW_ANYWAY.search(q): + return False + w = WH.match(q) + wh = w.group(1).lower() if w else "" + if dt == "quantity" and not COUNT.match(s["plabel"].get(p, "")): + return False # the store keeps quantities without units: counts only + if re.match(r"^\s*how\s+(many|much)\b", q, re.I): + return dt == "quantity" + if wh == "when" or re.search(r"\b(what|which)\s+(year|date|day|century|decade)\b", q, re.I): + return dt == "time" + if dt == "time" and not re.search(r"\b(when|year|date|day|century|decade|born on|died on)\b", q, re.I): + return False + items = [x for x in vals if isinstance(x, int)] + if wh in ("who", "whom", "whose"): + return bool(items) and len(items) == len(vals) and all(HUMAN in classes(x) or classes(x) & ORG for x in items) + if wh == "where": + return bool(items) and len(items) == len(vals) and all(has(x, 625) or has(x, 17) or has(x, 131) for x in items) + return True + + +def fragment(q, span, p, extra_cues=()): + """the span is part of a longer name: a word next to it (past name particles) is a content word nothing explains""" + cues = _load()["cues"].get(p, set()) | set(extra_cues) + toks, sp = L.norm(q).split(), L.norm(span).split() + for i in range(len(toks) - len(sp) + 1): + if toks[i:i + len(sp)] == sp: + for step, j in ((-1, i - 1), (1, i + len(sp))): + while 0 <= j < len(toks) and toks[j] in PARTICLES: + j += step + if 0 <= j < len(toks): + w = toks[j] + if w not in L.STOP and w not in cues and not w.isdigit(): + return True + return False + return False + + +GENERIC = set(("name names called known located famous kind type sort also exactly originally currently which what who where when " + "how many much does did do is was are were has have had born die died the a an of in on at to for by from with " + "about tell give list please something someone thing things person people one ones whose whom").split()) +MAX_UNEXPLAINED = int(os.environ.get("REACH_MAX_UNEXPLAINED", "2")) # development: 2 stopped a Mintaka error, lost nothing + + +def unexplained(q, span, p, extra_cues=()): + """content words of the question that neither the subject, the relation's own words nor ordinary question words explain""" + cues = _load()["cues"].get(p, set()) | set(extra_cues) + sp = set(L.norm(span).split()) + return [w for w in L.norm(q).split() if w not in sp and w not in cues and w not in GENERIC and w not in L.STOP + and not w.isdigit() and len(w) >= 3] + + +def _agree(q, span, cands, p, d, extra_cues=()): + """the readings of the name that hold the relation must agree; a one-word name answers through its top reading only""" + if fragment(q, span, p, extra_cues) or len(unexplained(q, span, p, extra_cues)) > MAX_UNEXPLAINED: + return None, None + one = len(L.norm(span).split()) == 1 + use = cands[:1] if one else cands[:3] + sets, displays, subj = [], [], None + for qid, _, _ in use: + v = values(qid, p, d) + if v: + if any(DATE.is_time(x) and not DATE.available(x, q, qid, p) for x in v): + return None, None + sets.append(frozenset(v)) + displays.append(frozenset(DATE.render(x, q, qid, p) if DATE.is_time(x) else x for x in v)) + subj = subj or qid + if not sets or len(set(sets)) != 1 or len(set(displays)) != 1 or len(sets[0]) > MAX_LIST: + return None, None + return sets[0], subj + + +HEADNP = re.compile(r"\b(?:which|what)\s+((?:[a-z\-]+\s+){0,2}?[a-z\-]+)\s+(?:is|was|are|were|did|does|do|has|had|in|of|for|from|" + r"to|by|did|was|were)\b|\bof\s+what\s+((?:[a-z\-]+\s+){0,2}?[a-z\-]+)\s+(?:is|was|are|were)\b", re.I) + + +def _head_relations(q): + """the noun a question asks about, when it is a Wikidata name of a relation ("what job does ...", "which genre is ...")""" + al = _load()["alias"] + m = HEADNP.search(q) + if not m: + return set() + np_ = L.norm(m.group(1) or m.group(2)).split() + for k in range(len(np_)): # longest name first: "football position" before "position" + cand = " ".join(np_[k:]) + for c in (cand, cand[:-1] if cand.endswith("s") else None): + if c and c in al: + return set(_load()["label_idx"].get(c) or al[c]) # a relation's own label outranks another's alias + return set() + + +def _routes(q, span, cands): + """(relation, direction) routes for this span: the admitted patterns, else the asked noun's relation name; when they + name several relations, only those the subject holds count, and they must come down to one""" + pats = _load()["pats"] + matched = {f: pats[f] for f in XR.features(q, span) if f in pats} + rels = set(matched.values()) + route, pat = "pattern", "|".join(sorted(matched)[0]) if matched else "" + # (development 2026-10-21: routing by the asked noun's relation name without admission measured 15 right, 32 wrong on + # SimpleQuestions valid - not used; asked nouns route only through admitted patterns) + if len(rels) > 1: + held = {(p, d) for p, d in rels if any(values(c[0], p, d) for c in cands[:3])} + rels = held + if len(rels) == 1 and FAMILY_ON: + r0 = next(iter(rels)) + if not any(values(c[0], r0[0], r0[1]) for c in cands[:3]): + # the named relation is not held: the other relations patterns of the same asked word lead to + keys = {f[0] for f in matched if matched[f] == r0} + fam = set().union(*[_load()["family"].get(k, set()) for k in keys]) - {r0} if keys else set() + held = {(p, d) for p, d in fam if any(values(c[0], p, d) for c in cands[:3])} + if len(held) == 1: + rels = held + route = "family" + if len(rels) == 1: + rel = rels.pop() + # a pattern that matched on its asked word alone ("where|*") says nothing about the rest of the question: it answers + # only when every content word is explained (gate check 2026-10-21: "Otis Barton was a pioneer in exploring where?") + if all(f[1] == "*" for f in matched if matched[f] == rel) and unexplained(q, span, rel[0]): + return [] + return [(rel, route, pat)] + return [] + + +WHEN = re.compile(r"^\s*(?:when|in\s+what\s+year|what\s+year|in\s+which\s+year|which\s+year|on\s+what\s+date|what\s+date)\s+" + r"(?:was|were|is|are|did|does|do)\s+(?P<y>.+?)\s+(?P<v>[a-z]+)(?:\s+(?:in|on|at|for|out|up|down|open))?\s*\?\s*$", re.I) + + +def _stem(w): + for suf in ("ied", "ed", "d", "s"): + if w.endswith(suf) and len(w) - len(suf) >= 3: + return w[: -len(suf)] + ("y" if suf == "ied" else "") + return w + + +WHEN_ON = os.environ.get("REACH_WHEN") == "1" # not admitted (2026-10-21: TriviaQA exam too few firings): off + + +def _when_routes(q): + """ "When was Y born?": the date relations one of whose Wikidata names holds the verb (born -> date of birth)""" + m = WHEN.match(q) if WHEN_ON else None + if not m: + return [] + s_ = _load() + v = _stem(L.norm(m.group("v"))) + props = {p for p, dt in s_["dtype"].items() if dt == "time" and v in s_["time_words"].get(p, ())} + return [(props, m.group("y"), "when:" + m.group("v"))] if props else [] + + +HOWMANY = re.compile(r"^\s*how\s+many\s+(?P<x>[a-z][a-z \-]{1,40}?)\s+(?:does|did|do|has|had|have|is|are|were|was)\s+" + r"(?P<y>.+?)(?:\s+(?:have|has|had|got|contain|include|hold))?\s*\?\s*$", re.I) + + +def _count_routes(q): + """v2: "How many children does Y have?" asks the relation named "number of children" - a count the store holds, never a + count of stored values (the store is not complete)""" + m = HOWMANY.match(q) + if not m: + return [] + al = _load()["alias"] + x = L.norm(m.group("x")) + for cand in ("number of " + x, "number of " + x.rstrip("s"), "count of " + x): + if cand in al: + return [(al[cand], m.group("y"), "count:" + x)] + return [] + + +AGENT = re.compile(r"^\s*who\s+(?:first\s+|originally\s+)?(?P<v>[a-z]+ed|wrote|built|drew|sang|made|began|founded|led|ran|" + r"won|bought|sold|took|gave|stole|broke)\s+(?:the\s+)?(?P<y>[^?]+?)\s*\?\s*$", re.I) +IRREG = {"wrote": ("written", "writer"), "built": ("built", "builder"), "drew": ("drawn", "drawer"), "sang": ("sung", "singer"), + "made": ("made", "maker"), "began": ("begun", "beginner"), "led": ("led", "leader"), "ran": ("run", "runner")} + + +def _agent_nouns(v): + stem = v[:-1] if v.endswith("ied") else v[:-2] if v.endswith("ed") else v + if v.endswith("ied"): + stem = v[:-3] + "y" + out = {stem + "er", stem + "or", stem + "r", stem + "ar", stem[:-1] + "er" if stem.endswith("e") else stem + "er"} + if v.endswith("ed") and len(stem) >= 3 and stem[-1] == stem[-2]: + out.add(stem[:-1] + "er") # "planned" -> "planner" + return out + + +def _agent_routes(q): + """v3: "Who founded Y?" -> the relations named "founded by" or "founder" (and the like); their union, to be cut down to the + one Y holds""" + m = AGENT.match(q) if AGENT_ON else None + if not m: + return [] + al = _load()["alias"] + v = m.group("v").lower() + if v == "created": + # A developer can be a later maintainer, not the original creator. + # Designer is admitted only with programming-language type evidence below. + return [({170, 287}, m.group("y"), "agent:created")] + passive, agents = (IRREG[v][0], {IRREG[v][1]}) if v in IRREG else (v, _agent_nouns(v)) + props = set(al.get(passive + " by", set())) + for a in agents: + props |= set(al.get(a, set())) + return [(props, m.group("y"), "agent:" + v)] if props else [] + + +def _programming_language(qid): + """Positive bounded P31/P279 evidence only; missing ancestry is not a negative fact.""" + db = _load()["db"] + frontier, seen = {qid}, set() + for depth in range(5): + if 9143 in frontier and depth > 0: + return True + next_frontier = set() + for item in frontier - seen: + rows = db.execute("SELECT o FROM fact INDEXED BY fact_sp WHERE s=? AND p=? LIMIT 33", + (item, 31 if depth == 0 else 279)).fetchall() + if len(rows) > 32: + return False + next_frontier.update(o for (o,) in rows if o is not None) + seen.update(frontier) + if len(seen | next_frontier) > 64: + return False + frontier = next_frontier - seen + if not frontier: + return False + return False + + +def _creation_property_allowed(p, cands): + """Creator means P170; a language's original designer may also answer creation. + + Every candidate with a designer row must have positive language ancestry. + Never select a language merely because another reading lacks that type. + """ + if p == 170: + return True + if p != 287: + return False + holders = [qid for qid, _, _ in cands[:3] if has(qid, p)] + return bool(holders) and all(_programming_language(qid) for qid in holders) + + +def _label_routes(q): + """the question names the relation: (relation, subject text, the asked phrase)""" + al = _load()["alias"] + out = _when_routes(q) or _count_routes(q) or _agent_routes(q) + if out: + return out + q = re.sub(r"'s\s+(name|full name)\s*\?\s*$", "?", q, flags=re.I) # v2: "Y's wife's name?" asks "Y's wife?" + for rx in ASKED: + m = rx.match(q) + if not m: + continue + x = L.norm(m.group("x")) + for cand in (x, x[:-1] if x.endswith("s") else None, re.sub(r"^(the|a|an) ", "", x)): + if cand and cand in al: + out.append((al[cand], m.group("y"), cand)) + break + if out: + break + return out + + +DEF_OPEN = ("is", "are", "was", "can", "refers", "means", "describes") + + +def definition_reply(q, reply): + """the reply defines the noun the question asks about ("Genre is any style ...") instead of answering it for the thing + the question names ("what genre is the album London by Night"): not an answer""" + nouns, named_parts = set(), set() + m = HEADNP.search(q) + if m: + nouns.add(L.norm(m.group(1) or m.group(2)).split()[-1]) + for rx in ASKED: + mm = rx.match(q) + if mm: + nouns.add(L.norm(mm.group("x")).split()[-1]) + named_parts |= {w for w in L.norm(mm.group("y")).split() if w not in L.STOP and len(w) >= 3} + words = L.norm(re.sub(r"^\s*\[ev:[a-z_]+\]\s*", "", str(reply))).split()[:9] + while words and words[0] in ("the", "a", "an"): + words = words[1:] + if len(words) < 2 or words[0].rstrip("s") not in {n.rstrip("s") for n in nouns if n}: + return False + # "<noun> is ...", or "<noun> of <a short phrase> is ..." ("The nationality of a person is ...") + k = next((i for i in range(1, min(len(words), 6)) if words[i] in DEF_OPEN), None) + if k is None or (k > 1 and words[1] != "of"): + return False + if named_parts & set(words[:k]): + return False # "Laws of Thermodynamics is ...": it defines the very thing asked + sp = L.link(q, 3)[:1] + named = L.norm(sp[0][0]) if sp else "" + return bool(named) and named not in L.norm(str(reply)) + + +def _bare(text): + """a name without a leading article, for comparing a linked span with the text it should be ("The Goonies" = "Goonies")""" + return re.sub(r"^(the|a|an) ", "", L.norm(text)) + + +MONTHS = ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December") + + +def show_time(v, q, subject=None, property=None): + """Use bound source precision/calendar; missing metadata is explicitly unknown.""" + return DATE.render(v, q, subject, property) + + +def _show(v, q, p, subject=None): + if isinstance(v, int): + return label(v) + if DATE.is_time(v): + return show_time(v, q, subject, p) + if re.match(r"^-?\d+(\.0+)?$", str(v)): + return "{:,}".format(int(float(v))) + return str(v) + + +def answer(q, pinned=None): + """pinned = (span text, qid): a subject already known (the answer of an earlier hop), not linked again by its name""" + q = str(q).strip() + if XR.POLAR.search(q) or not (WH.match(q) or q.endswith("?")): + return None + sp = L.link(q, 3)[:3] + if pinned: + sp = [(pinned[0], [(pinned[1], 10 ** 6, label(pinned[1]))])] + [x for x in sp if L.norm(x[0]) != L.norm(pinned[0])] + agent = AGENT.match(q) + asks_creation = bool(agent and agent.group("v").lower() == "created") + found = [] + for span, cands in sp: # PATTERN route: the first span whose reading holds the relation + if XR.hop(q, span) or not XR.subject_ok(q, span): + continue + for (p, d), route, pat in _routes(q, span, cands): + if asks_creation and (d != "fwd" or not _creation_property_allowed(p, cands)): + continue + if p in XR.TIME_VARIANT and XR.PAST.search(q): + continue + v, subj = _agree(q, span, cands, p, d, {"created"} if asks_creation and p == 287 else ()) + if v is not None and fits(q, p, d, v): + found.append((p, d, v, subj, route, pat)) + break + if found: + break + if not found: # LABEL route: the asked phrase names the relation + for props, ytext, asked in _label_routes(q): + ysp = [sp[0]] if pinned and L.norm(ytext) == L.norm(pinned[0]) else L.link(ytext, 3)[:1] + if not ysp or _bare(ysp[0][0]) != _bare(ytext): + continue # the subject must be exactly the named entity + span, cands = ysp[0] + hits = [] + for p in sorted(props): + if asks_creation and not _creation_property_allowed(p, cands): + continue + if p in XR.TIME_VARIANT and XR.PAST.search(q): + continue + v, subj = _agree(q, span, cands, p, "fwd", {"created"} if asks_creation and p == 287 else ()) + if v is not None and fits(q, p, "fwd", v): + hits.append((p, "fwd", v, subj, "when" if asked.startswith("when:") else "count" if asked.startswith("count:") else "agent" if asked.startswith("agent:") else "label", asked)) + if len({h[2] for h in hits}) == 1: + found.append(hits[0]) + break + if not found: + return None + p, d, v, subj, route, pat = found[0] + shown = [_show(x, q, p, subj) for x in v] + if not all(shown): + return None # a value with no English name is not shown + shown = sorted(shown) + aw = [w for x in shown for w in L.norm(x).split() if w not in L.STOP] + if subj in v or (not all(isinstance(x, int) for x in v) + and aw and all(w in set(L.norm(q).split()) for w in aw)): + return None # entity identity, not overlapping labels, is restatement + text = shown[0] if len(shown) == 1 else ", ".join(shown[:-1]) + " and " + shown[-1] + return {"answer": text, "values": shown, "raw": sorted(v, key=str), "property": p, "direction": d, "subject_qid": subj, + "route": route, "pattern": pat, + "date_evidence": [DATE.evidence(x, subj, p, q) for x in v if DATE.is_time(x)]} + + +if __name__ == "__main__": + import sys + for q in sys.argv[1:]: + print(q, "->", answer(q)) diff --git a/root/wander-train/reading_v1.py b/root/wander-train/reading_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..b45cf02f7be5cf841f67217fb0750b6140dc277b --- /dev/null +++ b/root/wander-train/reading_v1.py @@ -0,0 +1,58 @@ +"""reading_v1 - release 4.8, the reading release: rules that decide whether a reply answers what the question asks. Used by +fold w568; each takes the question, the reply's path and its text, and returns a reason to withhold, or None. + + ASKED_RELATION a where-question answered by a sentence (the deliberation and text-reader paths) must say the relation + asked: "Where is X buried?" is not answered by where X was born. The question's verb or asked noun, or + one of the words that say the same relation, must occur in the sentence. + NOT_AN_ANSWER a who / where / when / which / how-many question is not answered by an explanation, a definition, a + timeline, a comparison or a numbered list: those serve "explain X" and "list N", not the question. +""" +import re + +WH_Q = re.compile(r"^\s*(?:who|whom|whose|where|when|which|what\s+year|in\s+what\s+year|how\s+many|how\s+much|how\s+old)\b", re.I) +WHERE_Q = re.compile(r"^\s*where\b", re.I) +SENTENCE_PATHS = ("deliberation:", "factoid:page", "anchored_summary", "verified:cube") +EXPLAIN_PATHS = ("arb:explain_simply", "arb:definitional", "arb:timeline", "arb:compare", "arb:why_different", "arb:list_n") +SAY = { # words that say the same relation as the question's word + "buried": {"buried", "burial", "interred", "grave", "cemetery", "tomb", "mausoleum", "rests"}, + "born": {"born", "birth", "birthplace"}, "die": {"died", "dies", "death", "killed"}, "died": {"died", "dies", "death", "killed"}, + "live": {"lives", "lived", "live", "living", "resides", "resided", "home", "moved"}, + "located": {"located", "lies", "situated", "city", "town", "village", "county", "state", "country", "region", "capital", "part"}, + "play": {"play", "plays", "played", "stadium", "arena", "field", "park", "home", "team", "club"}, + "filmed": {"filmed", "filming", "shot", "location", "locations"}, "go": {"went", "attended", "studied", "graduated", "school", "college", "university"}, + "college": {"college", "university", "attended", "studied", "graduated"}, "school": {"school", "attended", "studied", "graduated", "college"}, + "work": {"works", "worked", "working", "employed"}, "operate": {"operates", "operated", "offices", "headquarters"}, + "headquarters": {"headquarters", "headquartered", "based"}, "from": {"from", "born", "native", "originated"}, + "grow": {"grew", "raised", "childhood", "born"}, "spoken": {"spoken", "language", "languages"}, "start": {"started", "began", "founded", "origin"}, +} +STOP = set("where is are was were does do did the a an of in on at to for and or how what who when which can could would will " + "be been being it its their there they he she his her".split()) + + +def _words(s): + return re.findall(r"[a-z]+", s.lower()) + + +def _base(w): + for suf in ("ing", "ed", "es", "s"): + if w.endswith(suf) and len(w) - len(suf) >= 3: + return w[: -len(suf)] + return w + + +def asked_relation(q, path, reply, subject_words=()): + if not WHERE_Q.match(q) or not str(path).startswith(SENTENCE_PATHS): + return None + sent = set(_words(reply)) + asked = [w for w in _words(q) if w not in STOP and w not in subject_words] + for w in asked: + say = SAY.get(w) or SAY.get(_base(w)) or {w, _base(w)} + if sent & say or any(_base(x) == _base(w) for x in sent): + return None + return "the sentence does not say the relation asked (%s)" % " ".join(asked[:3]) + + +def not_an_answer(q, path): + if WH_Q.match(q) and str(path).startswith(EXPLAIN_PATHS): + return "an explanation does not answer a %s-question" % WH_Q.match(q).group(0).strip().split()[0].lower() + return None diff --git a/root/wander-train/relation_spec_v1.py b/root/wander-train/relation_spec_v1.py index 2973d70f5c248bcd6567416f6263bc783a8f5e67..7d4cbaa961b1a6cb8e9e5b40bef68f54be2c4292 100644 --- a/root/wander-train/relation_spec_v1.py +++ b/root/wander-train/relation_spec_v1.py @@ -11,6 +11,7 @@ A question is linked ONCE per turn however many relation specialists look at it import collections import functools import json +import re import exact_router_v1 as X @@ -21,6 +22,11 @@ _anc, _cls, _props = {}, {}, {} def prop_label(p): + # The shipped label dump includes aliases ("wives", "written by", "wrote") + # for these properties. Those aliases can misstate the role in a receipt. + canonical = {26: "spouse", 86: "composer", 569: "date of birth", 570: "date of death", 800: "notable work"} + if p in canonical: + return canonical[p] if not _PL: try: with open(PROP_LABELS, encoding="utf-8") as f: @@ -90,6 +96,35 @@ def values(qid, p): return _props[key] +_DESC = {} + + +def _describes(qid, words): + """every word is in the item's own facts: its labels and aliases, the labels of what it relates to, its stored values + (a year counts by its digits: "c1819"). Bounded to one query per item per turn.""" + if qid not in _DESC: + bag = set() + try: + rs = _rs() + for lab in [rs.label(qid) or ""] + list(getattr(rs, "aliases", lambda i: [])(qid) or []): + bag |= set(X.norm(lab).split()) + for o_ in _q("SELECT o FROM fact INDEXED BY fact_sp WHERE s=? AND o IS NOT NULL LIMIT 400", (qid,)): + bag |= set(X.norm(rs.label(o_) or "").split()) + for lit in _q("SELECT lit FROM fact INDEXED BY fact_sp WHERE s=? AND lit IS NOT NULL LIMIT 400", (qid,)): + t = X.norm(str(lit)) + bag |= set(t.split()) + for y in __import__("re").findall(r"\d{4}", t): + bag.add(y) + bag.add("c" + y) + except Exception: # noqa: BLE001 + bag = set() + if len(_DESC) > 2000: + _DESC.clear() + _DESC[qid] = bag + bag = _DESC[qid] + return all(w in bag or w.rstrip("s") in bag or (w + "s") in bag for w in words) + + @functools.lru_cache(maxsize=64) def analyse(q): """-> None, or {span, cands (qid list after the popularity rule), feats}: the per-turn work every specialist shares""" @@ -128,8 +163,95 @@ def kind_conflict(q, did): return bool(named) and did in KIND_NOUNS and did not in named +_COMPOSER_REQUEST = re.compile( + r"^(?:who composed(?: the (?:music|score|soundtrack) (?:for|of|to))?" + r"|who (?:is|was) the composer of" + r"|who wrote the (?:music|score|soundtrack) (?:for|of|to)" + r"|which composer wrote)\s+(?P<title>.+?)$", re.I) + + +def _composer_request(q): + """Untrusted, whole-question recognizer: musical composition means P86. + + A mined correlation with P800 (notable work) cannot establish the role. + Keep the entire title; do not silently fall back to a linked title fragment. + """ + text = " ".join(str(q).split()).rstrip("?.! ") + text = re.sub(r"^(?:please tell me|(?:can|could) you (?:please )?tell me)\s+", "", text, flags=re.I) + match = _COMPOSER_REQUEST.fullmatch(text) + if not match: + return None + title = match.group("title").strip() + film = re.match(r"^the (?:(\d{4}) )?(?:film|movie)\s+", title, flags=re.I) # 10.2: "the 2019 film X" too + if film: + title = title[film.end():] + dated = re.fullmatch(r"(.+?)\s*\((\d{4})\)", title) + year = dated.group(2) if dated else (film.group(1) if film else None) + title = (dated.group(1) if dated else title).strip(" \"'“”‘’") + return title, year, "films" if film else None + + +def _other_kind_disagrees(q, candidates, mine, composers): + """Maintainer amendment (10.1): an unqualified title names every item of that title. If a same-titled item outside + this domain has a different composer, this domain's answer is one reading of the question, not the answer.""" + if re.search(r"\bthe (?:film|movie)\b", str(q), re.I): + return False + for c in candidates: + if c[0] in mine: + continue + other = values(c[0], 86) + if other and other != composers: + return True + return False + + +def _composer_answer(q, did, request): + title, year, required_domain = request + if required_domain is not None and did != required_domain: + return None + # Fetch one extra candidate so a capped name lookup is not mistaken for full + # coverage. Domain and optional publication year must select agreeing rows. + candidates = list(X.L.candidates(X.norm(title), 65)) if title else [] + if not candidates and title.lower().startswith("the "): + candidates = list(X.L.candidates(X.norm(title[4:]), 65)) + if not candidates or len(candidates) > 64: + return None + mine = [c[0] for c in candidates if in_domain(c[0], did)] + if year: + # A missing or unparseable publication date cannot exclude a candidate. + dates = {qid: values(qid, 577) for qid in mine} + if any(not ds or any(not re.fullmatch(r"\+?\d{4}(?:-\d{2}-\d{2}(?:T[^\s]+)?)?", str(v)) + for v in ds) for ds in dates.values()): + return None + mine = [qid for qid in mine if any( + re.fullmatch(r"\+?" + year + r"(?:-\d{2}-\d{2}(?:T[^\s]+)?)?", str(value)) + for value in dates[qid])] + sets = [values(qid, 86) for qid in mine] + if not mine or any(not found for found in sets) or len(set(sets)) != 1 or len(sets[0]) != 1: + return None + if _other_kind_disagrees(q, candidates, mine, sets[0]): + return None + val = next(iter(sets[0])) + if _restates(q, val): + return None + return {"answer": X._show(val, q, mine[0], 86), "property": 86, "subject_qid": mine[0], + "direction": "fwd", "pattern": "explicit|composer|P86", + "linked_qid": mine[0]} + + def answer(q, did, patterns): """patterns: {"fwd|key|word": [p, ...], "inv|key|word": [p, ...]} -> {answer, property, subject_qid, direction, pattern} or None""" + request = _composer_request(q) + if request is not None: + if kind_conflict(str(q), did): + return None + found = _composer_answer(q, did, request) + if found is not None: + return found + if request[1] is not None or request[2] is not None: + return None # 10.2: a kind or a year was written in the question, so the refusal stands (ember arlynx #7) + # Maintainer amendment (10.1): when the explicit reader cannot decide, the reader 10.0 shipped is asked, as before + # PR #2, so a question 10.0 answered is not lost; the possessor rule (w573) still checks what it delivers. a = analyse(str(q)) if a is None or kind_conflict(str(q), did): return None @@ -147,12 +269,27 @@ def answer(q, did, patterns): if p in X.TIME_VARIANT and X.PAST.search(q): return None pat = sorted(k for pp, k in hit[direction] if pp == p)[0] + # 10.2: every content word and every number outside the linked name must be said by a pattern this reading used + used = {k.split("|", 2)[2] for pp, k in hit[direction] if pp == p} + used |= set(X.norm(prop_label(p)).split()) # the label of the property a reading answers is said by it + ent = set(X.norm(a["span"]).split()) + said = {x for _key, x in a["feats"] if x != "*"} | {x for x in X.norm(str(q)).split() if x.isdigit() and x not in ent} + possessive = {X.norm(m_).strip() for m_ in __import__("re").findall(r"\b([A-Za-z][\w.-]*)'s\b", str(q))} + possessive = {w_ for ph in possessive for w_ in ph.split()} # a premise the head's possessor rule checks + left_ = (said - used) - possessive + if left_ and not any(_describes(c_, left_) for c_ in a["cands"][:3]): + continue if direction == "fwd": mine = [c for c in a["cands"] if in_domain(c, did)] sets = [values(c, p) for c in mine] if not mine or any(not s for s in sets) or len(set(sets)) != 1 or len(sets[0]) != 1: continue val, subj = next(iter(sets[0])), mine[0] + if X.DATE.is_time(val) and any(not X.DATE.available(val, q, entity, p) for entity in mine): + return {"decline": True, "property": p, "subject_qid": subj, "pattern": pat, + "reason": "date_precision_unavailable"} + if X.DATE.is_time(val) and len({X._show(val, q, entity, p) for entity in mine}) != 1: + continue else: top = a["cands"][0] subs = _q("SELECT s FROM fact INDEXED BY fact_po WHERE p=? AND o=? LIMIT 8", (p, top)) @@ -167,6 +304,6 @@ def answer(q, did, patterns): continue if _restates(q, val): return None - return {"answer": X._show(val, q), "property": p, "subject_qid": subj, "direction": direction, "pattern": pat, + return {"answer": X._show(val, q, subj, p), "property": p, "subject_qid": subj, "direction": direction, "pattern": pat, "linked_qid": a["cands"][0]} return None diff --git a/root/wander-train/relation_spec_v2.py b/root/wander-train/relation_spec_v2.py index d8966e31b83dc77633ecab1601e829b5d5858804..ccc38c404232b0f79c54a336a05b5a09c68ebac6 100644 --- a/root/wander-train/relation_spec_v2.py +++ b/root/wander-train/relation_spec_v2.py @@ -57,8 +57,15 @@ def normalise(q): def compiled(key): if key not in _COMPILED: e = RD.PROPS[key] + forward = list(e.get("fwd", [])) + if int(e.get("prop", key)) == 569: + # Asking for an exact day does not manufacture one: display retains + # the bound source's actual precision and any missing-day notice. + forward += [r"what (?:is|was) (?:the )?(?:exact )?(?:date of birth|birth date|birthday) of (?P<X>.+?)", + r"on what (?:date|day) (?:was|were) (?P<X>.+?) born", + r"when (?:was|were) (?P<X>.+?) born in the (?:julian|gregorian) calendar"] _COMPILED[key] = {"prop": int(e.get("prop", key)), - "fwd": [re.compile(r"^" + p + r"$") for p in e.get("fwd", [])], + "fwd": [re.compile(r"^" + p + r"$") for p in forward], "inv": [re.compile(r"^" + p + r"$") for p in e.get("inv", [])]} return _COMPILED[key] @@ -101,6 +108,12 @@ def answer(q, did, keys, dropped=frozenset()): qids, links = slot_candidates(slot) if not qids: continue + # Do not discard another linked identity before an inverse + # lookup. Claim this recognized ambiguity instead of guessing. + if direction == "inv" and (key, direction, i) not in dropped and len(set(qids)) > 1: + return {"decline": True, "property": p, "subject_qid": qids[0], + "pattern": "%s|%s|%d" % (key, direction, i), + "reason": "ambiguous_inverse_target"} if V1.X.DOMINANCE and len(qids) > 1 and links[0] >= V1.X.DOMINANCE * max(1, max(links[1:])): qids = qids[:1] if (key, direction, i) in dropped: @@ -115,6 +128,11 @@ def answer(q, did, keys, dropped=frozenset()): decline = {"decline": True, "property": p, "subject_qid": mine[0], "pattern": "%s|%s|%d" % (key, direction, i)} continue val, subj = next(iter(sets[0])), mine[0] + if V1.X.DATE.is_time(val) and any(not V1.X.DATE.available(val, low, entity, p) for entity in mine): + return {"decline": True, "property": p, "subject_qid": subj, + "pattern": "%s|%s|%d" % (key, direction, i), "reason": "date_precision_unavailable"} + if V1.X.DATE.is_time(val) and len({V1.X._show(val, low, entity, p) for entity in mine}) != 1: + continue else: top = qids[0] subs = V1._q("SELECT s FROM fact INDEXED BY fact_po WHERE p=? AND o=? LIMIT 8", (p, top)) @@ -131,7 +149,7 @@ def answer(q, did, keys, dropped=frozenset()): return None if p in V1.X.TIME_VARIANT and V1.X.PAST.search(low): return None - shown = V1.X._show(val, low) + shown = V1.X._show(val, low, subj, p) if p == 1082 and re.fullmatch(r"\d+(?:\.0+)?", val): shown = "{:,}".format(int(float(val))) return {"answer": shown, "property": p, "subject_qid": subj, "direction": direction,