Utility functions and classes#

Module defining public utility functions and classes of the framework.

contextgem.public.utils.image_to_base64(source)[source]#

Converts an image to its Base64 encoded string representation.

Helper function that can be used when constructing Image objects.

Parameters:

source (str | pathlib.Path | typing.BinaryIO | bytes) – The image source - can be a file path (str or Path), file-like object (BytesIO, file handle, etc.), or raw bytes data.

Returns:

A Base64 encoded string representation of the image.

Return type:

str

Raises:
Example:
>>> from pathlib import Path
>>> import io
>>>
>>> # From file path
>>> base64_str = image_to_base64("path/to/image.jpg")
>>>
>>> # From file handle
>>> with open("image.png", "rb") as f:
...     base64_str = image_to_base64(f)
>>>
>>> # From bytes data
>>> with open("image.webp", "rb") as f:
...     image_bytes = f.read()
>>> base64_str = image_to_base64(image_bytes)
>>>
>>> # From BytesIO
>>> buffer = io.BytesIO(image_bytes)
>>> base64_str = image_to_base64(buffer)
contextgem.public.utils.create_image(source)[source]#

Creates an Image instance from various image sources.

This function automatically determines the MIME type and converts the image to base64 format using Pillow functionality. It supports common image formats including JPEG, PNG, and WebP.

Parameters:

source (str | pathlib.Path | PIL.Image.Image | typing.BinaryIO | bytes) – The image source - can be a file path (str or Path), PIL Image object, file-like object (BytesIO, file handle, etc.), or raw bytes data. A PIL Image object is saved in its format, e.g. JPEG for an image opened from a JPEG file, and as PNG if it has none, e.g. an image created in memory with PIL.Image.new(), or the result of an operation on another image.

Returns:

An Image instance with the appropriate MIME type and base64 data.

Return type:

contextgem.public.images.Image

Raises:
  • ValueError – If the image format is not supported or cannot be determined.

  • FileNotFoundError – If the image file path does not exist.

  • OSError – If the image cannot be opened or processed.

Example:
>>> from pathlib import Path
>>> from PIL import Image as PILImage
>>> import io
>>>
>>> # From file path
>>> img = create_image("path/to/image.jpg")
>>>
>>> # From PIL Image object
>>> pil_img = PILImage.open("path/to/image.png")
>>> img = create_image(pil_img)
>>>
>>> # From file-like object
>>> with open("image.jpg", "rb") as f:
...     img = create_image(f)
>>>
>>> # From bytes data
>>> with open("image.png", "rb") as f:
...     image_bytes = f.read()
>>> img = create_image(image_bytes)
>>>
>>> # From BytesIO
>>> buffer = io.BytesIO(image_bytes)
>>> img = create_image(buffer)
contextgem.public.utils.reload_logger_settings()[source]#

Reloads logger settings from environment variables.

This function should be called when environment variables related to logging have been changed after the module was imported. It re-reads the environment variables and reconfigures the logger accordingly.

Returns:

None

Example:
Reload logger settings#
import os

from contextgem import reload_logger_settings


# Initial logger settings are loaded from environment variables at import time

# Change logger level to WARNING
os.environ["CONTEXTGEM_LOGGER_LEVEL"] = "WARNING"
print("Setting logger level to WARNING")
reload_logger_settings()
# Now the logger will only show WARNING level and above messages

# Disable the logger completely
os.environ["CONTEXTGEM_LOGGER_LEVEL"] = "OFF"
print("Disabling the logger")
reload_logger_settings()
# Now the logger is disabled and won't show any messages

# You can re-enable the logger by setting it back to a valid level
# os.environ["CONTEXTGEM_LOGGER_LEVEL"] = "INFO"
# reload_logger_settings()
contextgem.public.utils.release_sat_model()[source]#

Releases the SaT model that is kept loaded, to free its memory.

A SaT model splits the text of a document into sentences, e.g. when an aspect or a concept is extracted with references to sentences, and into paragraphs with paragraph_segmentation_mode="sat". It is loaded when a document first needs it, which takes about a second for the default model, and is kept loaded for the documents that follow, for as long as the process runs. The model used last is kept, which holds a large amount of memory: about a gigabyte for the default model, and more once it has segmented a long document, or several documents at the same time, as it keeps the memory that it used for them. Call this function to free that memory, e.g. in a long-running process that segments no more documents. A document that needs the model then loads it again. A model that a document is being segmented with at the time, e.g. in another thread, is released when the segmentation ends.

Returns:

None

Return type:

None

Example:
Release the SaT model#
from contextgem import Document, release_sat_model


texts = [
    "The Supplier shall deliver the goods. Delivery is due within 30 days.",
    "The Customer shall pay the invoice. Payment is due within 14 days.",
]

# A SaT model splits the texts into sentences. It is loaded for the first
# document, and kept loaded for the documents that follow.
documents = []
for text in texts:
    documents.append(Document(raw_text=text, pre_segment_sentences=True))

for document in documents:
    print([sentence.raw_text for sentence in document.sentences])

# Free the memory of the model, e.g. when the process segments no more
# documents. A document that needs the model then loads it again.
release_sat_model()
class contextgem.public.utils.JsonObjectClassStruct(*args, **kwargs)[source]#

Bases: contextgem.internal.base.utils._JsonObjectClassStruct

A base class for the classes of the structure of a JsonObjectConcept that are defined inside a function, in a module with from __future__ import annotations.

Classes with type annotations, such as dataclasses or Pydantic models, need no base class to be a structure of a JsonObjectConcept, with their nested classes: their types are read with typing.get_type_hints(), which finds the classes of their module. In a module with postponed annotations, the types are strings, and a class defined inside a function cannot be found by its name. With this base class, a class named by the annotation of another class is found among the subclasses defined in the same function, or in a function that encloses it, as Python finds such names: each class of the structure is to inherit from it. A class is never found by its name alone, i.e. classes of the same name in other modules or functions are not mixed up.

Example:
Using JsonObjectClassStruct for class hierarchies#
from __future__ import annotations

from dataclasses import dataclass

from contextgem import JsonObjectClassStruct, JsonObjectConcept


def create_person_concept() -> JsonObjectConcept:
    # Classes defined inside a function, in a module with postponed annotations
    # (`from __future__ import annotations`), where the type of `Contact.address`
    # is the string "Address". As they inherit from JsonObjectClassStruct, "Address"
    # is found among the classes of the function. Classes defined at module level
    # need no base class.
    @dataclass
    class Address(JsonObjectClassStruct):
        street: str
        city: str
        country: str

    @dataclass
    class Contact(JsonObjectClassStruct):
        email: str
        phone: str
        address: Address

    @dataclass
    class Person(JsonObjectClassStruct):
        name: str
        age: int
        contact: Contact

    return JsonObjectConcept(
        name="Person", description="Person information", structure=Person
    )


person_concept = create_person_concept()

Replacement for __new__ that blocks direct instantiation of the decorated class while allowing subclasses to instantiate normally.

If invoked for the exact decorated class, an error is logged and TypeError is raised. For subclasses, the call is forwarded to the next __new__ in the MRO, preserving base-class behavior (e.g., Pydantic’s BaseModel.__new__).

Parameters:
  • inner_cls – The class being instantiated (decorated class or its subclass).

  • args (typing.Any) – Positional constructor arguments.

  • kwargs (typing.Any) – Keyword constructor arguments.

Returns:

A new instance when called for a subclass.

Raises:

TypeError – When attempting to instantiate the decorated class directly.

Return type:

Any