Skip to content

pixano.features.schemas.annotations.text_generation

Answer(content) dataclass

Holds the parts of an answer for multi-choices questions.

Raises:

Type Description
ValueError

in case of parsing error at initialisation

Exemple of content : "[[A;B;C]] this is a justification."

Parameters:

Name Type Description Default
content str

lazy formated content of the message.

required
Source code in pixano/features/schemas/annotations/text_generation.py
def __init__(self, content: str):
    """Constructor of the Answer from a lazy formated message.

    Exemple of content : "[[A;B;C]] this is a justification."

    Args:
        content (str): lazy formated content of the message.
    """
    self.content, self._choices, self._explanation = Answer.parse(content)

__str__()

Formats the message content for frontend.

Returns:

Type Description
str

formated message content

Source code in pixano/features/schemas/annotations/text_generation.py
def __str__(self):
    """Formats the message content for frontend.

    Returns:
        str: formated message content
    """
    return Answer.format(self._choices, self._explanation)

format(choices, explanation) classmethod

Formats the message content for frontend.

Returns:

Type Description
str

formated message content

Source code in pixano/features/schemas/annotations/text_generation.py
@classmethod
def format(cls, choices, explanation):
    """Formats the message content for frontend.

    Returns:
        str: formated message content
    """
    return "[[{0}]] {1}".format(";".join(choices), explanation)

parse(content) classmethod

Utility function that parses a str content into the 3 fields of the Answer object.

The input should be formated as follow "[[A;B;C]] this is a justification."

Returns:

Type Description
str

content, the reformated content

list[str]

choices, the list of parsed answer elements

str

explanation, the explanation sentence

Source code in pixano/features/schemas/annotations/text_generation.py
@classmethod
def parse(cls, content: str) -> tuple[str, list[str], str]:
    """Utility function that parses a str content into the 3 fields of the Answer object.

    The input should be formated as follow "[[A;B;C]] this is a justification."

    Returns:
        content, the reformated content
        choices, the list of parsed answer elements
        explanation, the explanation sentence
    """
    choices = []
    explanation = ""
    try:
        re_choices_explanation = r"\[\[([a-zA-Z0-9]+(\;[a-zA-Z0-9]+)*)\]\]\s*(.*)"
        match_1 = re.match(re_choices_explanation, content)
        if match_1:
            explanation = str(match_1.groups()[-1])
            match_2 = re.findall(r"[a-zA-Z0-9]+", match_1.groups()[0])
            for m in match_2:
                choices.append(m)
        content = Answer.format(choices, explanation)
    except Exception:
        raise ValueError(f"could not parse answer message : {content} => {choices}, {explanation}")
    return content, choices, explanation

Message(created_at=None, updated_at=None, **data)

Bases: Annotation

Textual exchange in a question/answer conversation for image or text description and information extraction.

Attributes:

Name Type Description
number int

message number to associate different ANSWER messages to a QUESTION.

content str

actual text of the message.

user str

identify who is the author of the message (eg a human, a model, the ground truth, etc).

choices list[str]

list of allowed answers, for 'Multiple Choice Question' when type=QUESTION and question_type!=OPEN.

timestamp datetime

creation date of the message.

type str

type of the message within "SYSTEM", "QUESTION" or "ANSWER". - SYSTEM: used for prefix messages stating the context. No associated answer expected - QUESTION: used to ask a question about a View. Expecting at least one answer (same message number) - ANSWER: used to reply to a question message by refering its message number

question_type str

type of question, specifying how to read and parse the content field. Authorized calued within "OPEN", "SINGLE_CHOICE", "SINGLE_CHOICE_EXPLANATION", "MULTI_CHOICE", "MULTI_CHOICE_EXPLANATION". - OPEN: used for any open question, where no specific format of answer is expected - SINGLE_CHOICE: used for a multi-choice-question where only one answer is authorized. - SINGLE_CHOICE_EXPLANATION: similar to SINGLE_CHOICE, but an explanation is expected after the choosen answer. Cf Answer object - MULTI_CHOICE: used for a multi-choice-question where multi answers are authorized. - MULTI_CHOICE_EXPLANATION: similar to MULTI_CHOICE, but an explanation is expected after the choosen answers. Cf Answer object

Source code in pixano/features/schemas/base_schema.py
def __init__(self, /, created_at: datetime | None = None, updated_at: datetime | None = None, **data: Any):
    """Create a new model by parsing and validating input data from keyword arguments.

    Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
    validated to form a valid model.

    `self` is explicitly positional-only to allow `self` as a field name.

    Args:
        created_at: The creation date of the object.
        updated_at: The last modification date of the object.
        data: The data of the object validated by Pydantic.
    """
    created_at, updated_at = validate_and_init_create_at_and_update_at(created_at, updated_at)
    data.update({"created_at": created_at, "updated_at": updated_at})
    super().__init__(**data)

none() classmethod

Utility function to get a None equivalent. Should be removed when Lance could manage None value.

Returns:

Type Description
Message

"None" Message.

Source code in pixano/features/schemas/annotations/text_generation.py
@classmethod
def none(cls) -> "Message":
    """Utility function to get a None equivalent.
    Should be removed when Lance could manage None value.

    Returns:
        "None" Message.
    """
    return cls(
        id="",
        item=ItemRef.none(),
        view=ViewRef.none(),
        entity=EntityRef.none(),
        source_ref=SourceRef.none(),
        number=0,
        user="",
        type="QUESTION",
        content="",
        choices=[],
        timestamp=datetime(1, 1, 1, 0, 0, 0, 0),
    )

create_message(number, user, type, content, choices=[], timestamp=datetime(1, 1, 1, 0, 0, 0, 0), id='', item_ref=ItemRef.none(), view_ref=ViewRef.none(), entity_ref=EntityRef.none(), source_ref=SourceRef.none())

Create a Message instance.

Parameters:

Name Type Description Default
number int

message number to associate diffrent ANSWER messages to a QUESTION

required
user str

identify who is the author of the message (eg a human, a model, the ground truth, etc)

required
type Literal['SYSTEM', 'QUESTION', 'ANSWER']

type of the message within "SYSTEM", "QUESTION" or"ANSWER"

required
content str

actual text of the message

required
choices list[str]

list of allowed answers

[]
timestamp datetime

creation date of the message

datetime(1, 1, 1, 0, 0, 0, 0)
id str

object id

''
item_ref ItemRef

Item reference.

none()
view_ref ViewRef

View reference.

none()
entity_ref EntityRef

Entity reference.

none()
source_ref SourceRef

Source reference.

none()

Returns:

Type Description
Message

The created Message instance.

Source code in pixano/features/schemas/annotations/text_generation.py
def create_message(
    number: int,
    user: str,
    type: Literal["SYSTEM", "QUESTION", "ANSWER"],
    content: str,
    choices: list[str] = [],
    timestamp: datetime = datetime(1, 1, 1, 0, 0, 0, 0),
    id: str = "",
    item_ref: ItemRef = ItemRef.none(),
    view_ref: ViewRef = ViewRef.none(),
    entity_ref: EntityRef = EntityRef.none(),
    source_ref: SourceRef = SourceRef.none(),
) -> Message:
    """Create a Message instance.

    Args:
        number: message number to associate diffrent ANSWER messages to a QUESTION
        user: identify who is the author of the message (eg a human, a model, the ground truth, etc)
        type: type of the message within "SYSTEM", "QUESTION" or"ANSWER"
        content: actual text of the message
        choices: list of allowed answers
        timestamp: creation date of the message
        id: object id
        item_ref: Item reference.
        view_ref: View reference.
        entity_ref: Entity reference.
        source_ref: Source reference.

    Returns:
        The created `Message` instance.
    """
    return Message(
        number=number,
        user=user,
        type=type,
        content=content,
        choices=choices,
        timestamp=timestamp,
        id=id,
        item_ref=item_ref,
        view_ref=view_ref,
        entity_ref=entity_ref,
        source_ref=source_ref,
    )

is_message(cls, strict=False)

Check if a class is a Message or subclass of Message.

Source code in pixano/features/schemas/annotations/text_generation.py
def is_message(cls: type, strict: bool = False) -> bool:
    """Check if a class is a Message or subclass of Message."""
    return issubclass_strict(cls, Message, strict)