Commit ac8c130c authored by narugo1992's avatar narugo1992
Browse files

dev(narugo): more docs

parent 159dce69
Loading
Loading
Loading
Loading
+40 −1
Original line number Diff line number Diff line
@@ -270,10 +270,31 @@ def parse_sdmeta_from_text(x: str) -> SDMetaData:


class _InvalidSDMetaError(Exception):
    """
    Custom exception raised when SD metadata is invalid or not found.

    This exception is used internally to signal that the metadata
    validation or extraction process has failed.
    """
    pass


def _sdtext_validate(text: str):
def _sdtext_validate(text: str) -> str:
    """
    Validate the given text as SD metadata.

    This function attempts to validate the input text as SD metadata. It first tries
    to validate it as NAI (Novel AI) metadata, and if that fails, it checks if the
    text is non-empty. If both checks fail, it raises an _InvalidSDMetaError.

    :param text: The text to validate as SD metadata.
    :type text: str

    :return: The validated text if it passes the checks.
    :rtype: str

    :raises _InvalidSDMetaError: If the text is invalid or empty.
    """
    from .nai import _naimeta_text_validate, _InvalidNAIMetaError

    try:
@@ -290,6 +311,21 @@ def _sdtext_validate(text: str):


def _get_raw_sdtext(image: ImageTyping) -> Optional[str]:
    """
    Extract raw SD metadata text from the given image.

    This function attempts to read SD metadata from various sources within the image,
    including PNG info, EXIF data, and GIF metadata. It tries each method in turn
    and returns the first valid SD metadata text found.

    :param image: The input image to extract metadata from.
    :type image: ImageTyping

    :return: The raw SD metadata text if found, otherwise None.
    :rtype: Optional[str]

    :raises _InvalidSDMetaError: If no valid SD metadata is found in the image.
    """
    image = load_image(image, force_background=None, mode=None)

    try:
@@ -334,6 +370,9 @@ def get_sdmeta_from_image(image: ImageTyping) -> Optional[SDMetaData]:
        ...     print(f"Parameters: {sd_meta.parameters}")
        ... else:
        ...     print("No SD metadata found in the image.")

    Note: This function depends on the load_image and parse_sdmeta_from_text functions.
    Ensure these are properly imported or defined in the current scope.
    """
    image = load_image(image, mode=None, force_background=None)
    try:
+52 −3
Original line number Diff line number Diff line
@@ -107,13 +107,36 @@ class _InvalidNAIMetaError(Exception):

def _naimeta_validate(data):
    """
    Validate the NAI metadata.
    Validate the Novel AI (NAI) metadata.

    This function checks if the provided metadata is in the correct format and contains
    the required fields for NAI metadata. It also performs additional validation on specific fields.

    :param data: The metadata to validate.
    :type data: dict
    :return: The validated metadata.

    :return: The validated metadata if it passes all checks.
    :rtype: dict
    :raises _InvalidNAIMetaError: If the metadata is invalid.

    :raises _InvalidNAIMetaError: If the metadata is invalid or missing required fields.

    :Example:

    >>> metadata = {
    ...     'Software': 'Novel AI',
    ...     'Source': 'User',
    ...     'Comment': '{"prompt": "A beautiful landscape"}',
    ...     'Generation time': '1.5'
    ... }
    >>> validated_data = _naimeta_validate(metadata)
    >>> print(validated_data == metadata)
    True

    Note:

        - The function checks for the presence of 'Software', 'Source', and 'Comment' fields.
        - The 'Comment' field must be a valid JSON string.
        - If present, the 'Generation time' field must be convertible to a float.
    """
    if isinstance(data, dict) and data.get('Software') and data.get('Source') and data.get('Comment'):
        try:
@@ -134,6 +157,32 @@ def _naimeta_validate(data):


def _naimeta_text_validate(data):
    """
    Validate the Novel AI (NAI) metadata provided as a JSON string.

    This function first attempts to parse the input string as JSON, then validates
    the resulting dictionary using the _naimeta_validate function.

    :param data: The metadata to validate, provided as a JSON string.
    :type data: str

    :return: The validated metadata as a dictionary.
    :rtype: dict

    :raises _InvalidNAIMetaError: If the input is not a valid JSON string or if the
                                  parsed metadata is invalid.

    :Example:

    >>> json_metadata = '{"Software": "Novel AI", "Source": "User", "Comment": "{}", "Generation time": "2.0"}'
    >>> validated_data = _naimeta_text_validate(json_metadata)
    >>> print(isinstance(validated_data, dict))
    True

    Note:
    - This function is useful when dealing with NAI metadata stored as JSON strings.
    - It combines JSON parsing and metadata validation in one step.
    """
    try:
        return _naimeta_validate(json.loads(data))
    except (TypeError, json.JSONDecodeError):