You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ossie.apache.org by jb...@apache.org on 2026/10/04 14:29:40 UTC

(ossie) branch main updated: fix(ontology): accept verbalizations in any role order (#456)

This is an automated email from the ASF dual-hosted git repository.

jbonofre pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/ossie.git


The following commit(s) were added to refs/heads/main by this push:
     new 4fe66946 fix(ontology): accept verbalizations in any role order (#456)
4fe66946 is described below

commit 4fe669469a8c778f6f2b5cff36659206bd53b532
Author: Adegbite Ayoade Abel <tr...@gmail.com>
AuthorDate: Sun Oct 4 15:29:35 2026 +0100

    fix(ontology): accept verbalizations in any role order (#456)
    
    * fix(ontology): accept verbalizations in any role order
    
    _parse_verbalization() compared each {Concept} token with the role at the
    same position, so a reverse reading such as '{Company} employs {Person}'
    for a relationship declared Person -> Company was rejected.
    
    Tokens are now matched to roles by concept name and role name. A reading
    that uses a role twice is rejected. When a concept plays several unnamed
    roles, its tokens take them in declared order, as before. The declared
    roles are unchanged; RelationshipVerbalization.roles follows the reading.
    
    Closes #445
    
    * fix(ontology): name the unused role when a ring reading repeats one
    
    For a ring with a named role, a reading such as '{Person} has parent
    {Person}' failed with "uses role '{Person}' more than once", which does
    not say what to change. When the concept still has an unused role under
    another name, the error now names it.
---
 converters/ontology/src/ossie_ontology/model.py    | 42 +++++++++++--
 .../ontology/tests/test_verbalization_parsing.py   | 73 +++++++++++++++++++++-
 2 files changed, 106 insertions(+), 9 deletions(-)

diff --git a/converters/ontology/src/ossie_ontology/model.py b/converters/ontology/src/ossie_ontology/model.py
index 9badc883..e1563cb6 100644
--- a/converters/ontology/src/ossie_ontology/model.py
+++ b/converters/ontology/src/ossie_ontology/model.py
@@ -1140,6 +1140,11 @@ def _parse_verbalization(relationship: Relationship, verbalization: str) -> Rela
     """
         Parse a verbalization string into an ordered list of :class:`VerbalizationRole` objects.
 
+        Tokens are matched to the relationship's roles by concept name (and role name
+        when given), so a reading may list the roles in any order; the returned roles
+        follow the reading order. Each role must appear exactly once. When a concept
+        plays several unnamed roles, its tokens take those roles in declared order.
+
         Format example:
 
             'every chain- super {Store} reports returns of {Item} big -box for average- {Amount:amt}'
@@ -1166,18 +1171,43 @@ def _parse_verbalization(relationship: Relationship, verbalization: str) -> Rela
         )
     segments: list[str] = []
     roles: list[VerbalizationRole] = []
+    used: set[int] = set()
     prev_end = 0
-    for idx, m in enumerate(tokens):
-        role = relationship.role(idx)
+    for m in tokens:
         segments.append(verbalization[prev_end:m.start()].strip())
         verb_concept_name = m.group(1).strip()
-        rel_role_name = role.explicit_name
         verb_role_name = m.group(2).strip() if m.group(2) else None
-        if rel_role_name != verb_role_name or role.player.name != verb_concept_name:
+        matches = [
+            role for role in relationship.roles
+            if role.player.name == verb_concept_name and role.explicit_name == verb_role_name
+        ]
+        if not matches:
+            declared = ", ".join(
+                VerbalizationRole(concept=r.player, name=r.explicit_name).verbalization_name()
+                for r in relationship.roles
+            )
+            raise ValueError(
+                f"No role of relationship {relationship.full_name} ({declared}) "
+                f"matches verbalization role '{m.group(0)}' in '{verbalization}'"
+            )
+        # Match by concept (and role name) so readings may list roles in any order.
+        # When several roles still match (e.g. a ring without role names), take the
+        # first unused one, which keeps them in declared order.
+        role = next((r for r in matches if r.idx not in used), None)
+        if role is None:
+            # If the same concept still has an unused role under another name, the
+            # token most likely just lacks that role name, so point the author to it.
+            unused = [
+                VerbalizationRole(concept=r.player, name=r.explicit_name).verbalization_name()
+                for r in relationship.roles
+                if r.player.name == verb_concept_name and r.idx not in used
+            ]
+            hint = f"; did you mean {' or '.join(repr(u) for u in unused)}?" if unused else ""
             raise ValueError(
-                f"Role {idx}: '{role.player.name}:{role.name}' "
-                f"does not match verbalization role '{verb_concept_name}:{verb_role_name}'"
+                f"Verbalization '{verbalization}' uses role '{m.group(0)}' more than once "
+                f"for relationship {relationship.full_name}{hint}"
             )
+        used.add(role.idx)
         roles.append(VerbalizationRole(concept=role.player, name=verb_role_name))
         prev_end = m.end()
     segments.append(verbalization[prev_end:].strip())
diff --git a/converters/ontology/tests/test_verbalization_parsing.py b/converters/ontology/tests/test_verbalization_parsing.py
index 4f9b405f..35232ab4 100644
--- a/converters/ontology/tests/test_verbalization_parsing.py
+++ b/converters/ontology/tests/test_verbalization_parsing.py
@@ -177,14 +177,14 @@ def test_builtin_integer_concept_resolves():
 def test_wrong_concept_name_in_token_raises():
     """Verbalization says {Item} but the relationship role plays Store."""
     verbalization = "{Item}"
-    with pytest.raises(ValueError, match="does not match verbalization role"):
+    with pytest.raises(ValueError, match="No role of relationship"):
         _rel("r", Concept("Store"), [], verbalization)
 
 
 def test_wrong_role_name_in_token_raises():
     """Verbalization says {Store:wrong} but the relationship role name is unset."""
     verbalization = "{Store:wrong}"
-    with pytest.raises(ValueError, match="does not match verbalization role"):
+    with pytest.raises(ValueError, match="No role of relationship"):
         _rel("r", Concept("Store"), [], verbalization)
 
 
@@ -198,4 +198,71 @@ def test_same_concept_different_roles_valid():
     assert len(roles) == 2
     assert roles[0].name is None
     assert roles[1].name == "parent"
-    assert roles[0].concept is roles[1].concept
\ No newline at end of file
+    assert roles[0].concept is roles[1].concept
+
+
+def test_reverse_reading_accepted():
+    """A reading may list the roles in a different order from the declaration."""
+    person = Concept("Person")
+    company = Concept("Company")
+    rel = Relationship(
+        "works for",
+        person,
+        [(company, None)],
+        verbalizes=["{Person} works for {Company}", "big- {Company} employs {Person} full -time"],
+    )
+    forward, reverse = rel.verbalizations
+    assert [r.concept for r in forward.roles] == [person, company]
+    assert [r.concept for r in reverse.roles] == [company, person]
+    assert reverse.roles[0].prefix == "big"
+    assert reverse.roles[0].following_text == "employs"
+    assert reverse.roles[1].postfix == "full time"
+    assert [r.player for r in rel.roles] == [person, company]
+
+
+def test_reverse_reading_ternary():
+    verbalization = "{Warehouse} receives {Item} from {Supplier}"
+    supplier, item, warehouse = Concept("Supplier"), Concept("Item"), Concept("Warehouse")
+    rel = _rel("delivers", supplier, [(item, None), (warehouse, None)], verbalization)
+    roles = parse_verbalization(rel, verbalization).roles
+    assert [r.concept for r in roles] == [warehouse, item, supplier]
+    assert roles[0].following_text == "receives"
+    assert roles[1].following_text == "from"
+
+
+def test_reading_with_repeated_role_raises():
+    """Using one role twice leaves another out, which is rejected."""
+    verbalization = "{Person} works with {Person}"
+    with pytest.raises(ValueError, match="more than once"):
+        _rel("works for", Concept("Person"), [(Concept("Company"), None)], verbalization)
+
+
+def test_ring_reading_missing_role_name_points_to_unused_role():
+    """A ring token that lacks a role name names the unused role in the error."""
+    person = Concept("Person")
+    with pytest.raises(ValueError, match=re.escape("did you mean '{Person:parent}'?")):
+        _rel("parenthood", person, [(person, "parent")], "{Person} has parent {Person}")
+
+
+def test_ring_reading_without_role_names_is_positional():
+    """When a concept plays two unnamed roles, tokens take them in declared order."""
+    person = Concept("Person")
+    verbalization = "{Person} manages {Person}"
+    rel = _rel("manages", person, [(person, None)], verbalization)
+    roles = parse_verbalization(rel, verbalization).roles
+    assert [r.name for r in roles] == [None, None]
+    assert roles[0].following_text == "manages"
+
+
+def test_ring_reverse_reading_with_role_names():
+    """Role names disambiguate a ring, so its reverse reading is accepted."""
+    person = Concept("Person")
+    rel = Relationship(
+        "parenthood",
+        person,
+        [(person, "parent")],
+        verbalizes=["{Person} has parent {Person:parent}", "{Person:parent} is parent of {Person}"],
+    )
+    reverse = rel.verbalizations[1]
+    assert [r.name for r in reverse.roles] == ["parent", None]
+    assert reverse.roles[0].following_text == "is parent of"