Exemplo n.º 1
0
def create_slot(
    slot: Slot,
    schema_slot_counter: typing.Counter[str],
    parent_id: str,
    step_type: Optional[str],
    parent_type_id: str,
    slot_shared: bool,
) -> MutableMapping[str, Any]:
    """Gets slot.

    Args:
        slot: Slot data.
        schema_slot_counter: Slot counter.
        parent_id: Parent object ID.
        step_type: Step type.
        parent_type_id: ID of the parent object's type.
        slot_shared: Whether slot is shared.

    Returns:
        Slot.
    """
    role_key = "role" if step_type is not None else "roleName"

    cur_slot: MutableMapping[str, Any] = {
        "name": get_slot_name(slot, slot_shared),
        "@id": get_slot_id(slot, schema_slot_counter, parent_id, slot_shared),
        role_key: get_slot_role(slot, step_type, parent_type_id),
    }

    # Generate loosest constraints if none are given
    if not slot.constraints:
        if step_type is None:
            slot.constraints = sorted(list(ontology.entities) + ["EVENT"])
        else:
            primitive = ontology.get_default_event(step_type)
            if primitive is None:
                raise ValueError(f"Invalid primitive {primitive}")
            slot.constraints = ontology.events[primitive].args[
                slot.role].constraints
    constraints = get_slot_constraints(slot.constraints)
    cur_slot["entityTypes"] = constraints

    if slot.reference is not None:
        cur_slot["reference"] = f"wiki:{slot.reference}"

    # Set refvar and warn if missing
    if slot.refvar is not None:
        cur_slot["refvar"] = replace_whitespace(slot.refvar)
    else:
        logging.warning("%s misses refvar", str(slot))

    if slot.comment is not None:
        cur_slot["comment"] = slot.comment

    return cur_slot
Exemplo n.º 2
0
def get_slots() -> Any:
    """Gets slots and their type constraints, for a given primitive subtype.

    Returns:
        A JSON response.
    """
    if not request.args:
        abort(HTTPStatus.BAD_REQUEST)
    event_primitive = request.args.get("event_primitive")
    primitive = ontology.get_default_event(event_primitive)
    event_args = ontology.events[primitive].args
    slots = list(event_args)
    constraints = [sorted(arg.constraints) for arg in event_args.values()]
    return {"slots": slots, "constraints": constraints}
Exemplo n.º 3
0
def get_step_type(step: Step) -> str:
    """Gets type of step.

    Args:
        step: Step data.

    Returns:
        Step type.
    """
    primitive = ontology.get_default_event(step.primitive)

    if primitive not in ontology.events:
        logging.warning("Primitive '%s' in step '%s' not in ontology",
                        step.primitive, step.id)

    return f"kairos:Primitives/Events/{primitive}"
Exemplo n.º 4
0
def get_all_primitives() -> Any:
    """Gets all primitive subtypes, along with their subsubtypes and default description.

    Returns:
        A JSON response.
    """
    primitives = []
    default_subtypes = sorted(set((e.type, e.subtype) for e in ontology.events.values()))
    for event_type, subtype in default_subtypes:
        type_subtype = f"{event_type}.{subtype}"
        primitives.append(
            {
                "type": type_subtype,
                "subsubtypes": ontology.get_event_subcats(event_type, subtype),
                "description": ontology.events[ontology.get_default_event(type_subtype)].definition,
            }
        )
    return {"primitives": primitives}
Exemplo n.º 5
0
def request_top_n(
    description: str,
    *,
    n: int,
    ss_model: Optional[SentenceTransformer] = None,
    definition_embeddings: Optional[torch.FloatTensor] = None,
    template_embeddings: Optional[torch.FloatTensor] = None,
) -> Sequence[Mapping[str, Union[str, Sequence[str]]]]:
    """Get the top *n* predicted event primitives from the *ss_model* provided.

    Arguments:
        description: Text to be the basis of the prediction.
        n: Number of top predictions to be returned.
        ss_model: SentenceTransformer model to make the predictions.
        definition_embeddings: Embeddings of the definitions for event primitives.
        template_embeddings: Embeddings of the templates for the event primitives.

    Returns:
        List of predictions (in order of most similar -> least similar) in a dictionary containing the primitive,
        possible primitive subsubtypes, and the text that formed the basis of the prediction.
    """
    # Initialize model and embeddings
    if ss_model is None:
        ss_model = init_ss_model()

    if definition_embeddings is None or template_embeddings is None:
        definition_embeddings, template_embeddings = init_embeddings(ss_model)

    # Similarity scoring
    event_embedding = ss_model.encode([description], convert_to_tensor=True)
    def_cosine_scores = util.pytorch_cos_sim(event_embedding,
                                             definition_embeddings)
    template_cosine_scores = util.pytorch_cos_sim(event_embedding,
                                                  template_embeddings)
    cat_scores = torch.cat((def_cosine_scores, template_cosine_scores), 1)
    sorted_indices = cat_scores.argsort(descending=True)
    recommended_primitives = []

    # Get top n recommendations
    for idx in sorted_indices[0]:
        event = ontology.events[ontology.get_event_by_id(
            int(idx) % NUM_EVENTS + 1)]
        type_subtype = (event.type, event.subtype)
        if type_subtype not in recommended_primitives:
            recommended_primitives.append(type_subtype)
        if len(recommended_primitives) == n:
            break

    # Format recommendations
    json_return = []
    for rec_prim_type, rec_prim_subtype in recommended_primitives:
        primitive = f"{rec_prim_type}.{rec_prim_subtype}"
        subsubtypes = ontology.get_event_subcats(rec_prim_type,
                                                 rec_prim_subtype)
        description = ontology.events[ontology.get_default_event(
            primitive)].definition
        json_return.append({
            "type": primitive,
            "subsubtypes": subsubtypes,
            "description": description
        })

    return json_return