# coding: utf-8

"""
    Docling Serve

    No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)

    The version of the OpenAPI document: 
    Generated by OpenAPI Generator (https://openapi-generator.tech)

    Do not edit the class manually.
"""  # noqa: E501


from __future__ import annotations
import pprint
import re  # noqa: F401
import json

from pydantic import BaseModel, ConfigDict, Field, StrictFloat, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional, Union
from typing_extensions import Annotated
from yfkm3_services_parse_client.models.base_vlm_engine_options import BaseVlmEngineOptions
from yfkm3_services_parse_client.models.picture_classification_label import PictureClassificationLabel
from yfkm3_services_parse_client.models.vlm_model_spec import VlmModelSpec
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python

class PictureDescriptionVlmEngineOptions(BaseModel):
    """
    Configuration for VLM runtime-based picture description.  This is the new implementation that uses the pluggable runtime system with preset support. Supports all runtime types (Transformers, MLX, API, etc.) through the unified runtime interface.  Use `from_preset()` to create instances from registered presets.  Examples:     # Use preset with default runtime     options = PictureDescriptionVlmEngineOptions.from_preset(\"smolvlm\")      # Use preset with runtime override     from docling.datamodel.vlm_engine_options import MlxVlmEngineOptions, VlmEngineType     options = PictureDescriptionVlmEngineOptions.from_preset(         \"smolvlm\",         engine_options=MlxVlmEngineOptions(engine_type=VlmEngineType.MLX)     )
    """ # noqa: E501
    batch_size: Optional[Annotated[int, Field(strict=True, ge=1)]] = Field(default=8, description="Number of images to process in a single batch during picture description. Higher values improve throughput but increase memory usage. Adjust based on available GPU/CPU memory.")
    scale: Optional[Union[Annotated[float, Field(strict=True, gt=0.0)], Annotated[int, Field(strict=True, gt=0)]]] = Field(default=2.0, description="Scaling factor for image resolution before processing. Higher values (e.g., 2.0) provide more detail for the vision model but increase processing time and memory. Range: 0.5-4.0 typical.")
    picture_area_threshold: Optional[Union[StrictFloat, StrictInt]] = Field(default=0.05, description="Minimum picture area as fraction of page area (0.0-1.0) to trigger description. Pictures smaller than this threshold are skipped. Use lower values (e.g., 0.01) to describe small images.")
    classification_allow: Optional[List[PictureClassificationLabel]] = None
    classification_deny: Optional[List[PictureClassificationLabel]] = None
    classification_min_confidence: Optional[Union[StrictFloat, StrictInt]] = Field(default=0.0, description="Minimum classification confidence score (0.0-1.0) required for a picture to be processed. Pictures with classification confidence below this threshold are skipped. Higher values ensure only confidently classified images are described. Range: 0.0 (no filtering) to 1.0 (maximum confidence).")
    engine_options: BaseVlmEngineOptions = Field(description="Runtime configuration (transformers, mlx, api, etc.)")
    model_spec: VlmModelSpec = Field(description="Model specification with runtime-specific overrides")
    prompt: Optional[StrictStr] = Field(default='Describe this image in a few sentences.', description="Prompt template for the vision model. Customize to control description style, detail level, or focus.")
    generation_config: Optional[Dict[str, Any]] = Field(default=None, description="Generation configuration for text generation. Controls output length, sampling strategy, temperature, etc.")
    __properties: ClassVar[List[str]] = ["batch_size", "scale", "picture_area_threshold", "classification_allow", "classification_deny", "classification_min_confidence", "engine_options", "model_spec", "prompt", "generation_config"]

    model_config = ConfigDict(
        validate_by_name=True,
        validate_by_alias=True,
        validate_assignment=True,
        protected_namespaces=(),
    )


    def to_str(self) -> str:
        """Returns the string representation of the model using alias"""
        return pprint.pformat(self.model_dump(by_alias=True))

    def to_json(self) -> str:
        """Returns the JSON representation of the model using alias"""
        return json.dumps(to_jsonable_python(self.to_dict()))

    @classmethod
    def from_json(cls, json_str: str) -> Optional[Self]:
        """Create an instance of PictureDescriptionVlmEngineOptions from a JSON string"""
        return cls.from_dict(json.loads(json_str))

    def to_dict(self) -> Dict[str, Any]:
        """Return the dictionary representation of the model using alias.

        This has the following differences from calling pydantic's
        `self.model_dump(by_alias=True)`:

        * `None` is only added to the output dict for nullable fields that
          were set at model initialization. Other fields with value `None`
          are ignored.
        """
        excluded_fields: Set[str] = set([
        ])

        _dict = self.model_dump(
            by_alias=True,
            exclude=excluded_fields,
            exclude_none=True,
        )
        # override the default output from pydantic by calling `to_dict()` of engine_options
        if self.engine_options:
            _dict['engine_options'] = self.engine_options.to_dict()
        # override the default output from pydantic by calling `to_dict()` of model_spec
        if self.model_spec:
            _dict['model_spec'] = self.model_spec.to_dict()
        # set to None if classification_allow (nullable) is None
        # and model_fields_set contains the field
        if self.classification_allow is None and "classification_allow" in self.model_fields_set:
            _dict['classification_allow'] = None

        # set to None if classification_deny (nullable) is None
        # and model_fields_set contains the field
        if self.classification_deny is None and "classification_deny" in self.model_fields_set:
            _dict['classification_deny'] = None

        return _dict

    @classmethod
    def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
        """Create an instance of PictureDescriptionVlmEngineOptions from a dict"""
        if obj is None:
            return None

        if not isinstance(obj, dict):
            return cls.model_validate(obj)

        _obj = cls.model_validate({
            "batch_size": obj.get("batch_size") if obj.get("batch_size") is not None else 8,
            "scale": obj.get("scale") if obj.get("scale") is not None else 2.0,
            "picture_area_threshold": obj.get("picture_area_threshold") if obj.get("picture_area_threshold") is not None else 0.05,
            "classification_allow": obj.get("classification_allow"),
            "classification_deny": obj.get("classification_deny"),
            "classification_min_confidence": obj.get("classification_min_confidence") if obj.get("classification_min_confidence") is not None else 0.0,
            "engine_options": BaseVlmEngineOptions.from_dict(obj["engine_options"]) if obj.get("engine_options") is not None else None,
            "model_spec": VlmModelSpec.from_dict(obj["model_spec"]) if obj.get("model_spec") is not None else None,
            "prompt": obj.get("prompt") if obj.get("prompt") is not None else 'Describe this image in a few sentences.',
            "generation_config": obj.get("generation_config")
        })
        return _obj


