Ë
    uPêjJ  ã                   ó†   — U d Z ddlmZmZ ddlZddlmZ ddlmZm	Z	m
Z
mZ ddlmZ erddlmZ dZeed	<    G d
„ de«      Zy)z,
Mistral OCR transformation implementation.
é    )ÚTYPE_CHECKINGÚFinalN)Úverbose_logger)ÚBaseOCRConfigÚDocumentTypeÚOCRRequestDataÚOCRResponse)Úget_secret_str)ÚLoggingÚMISTRAL_API_KEYÚMISTRAL_OCR_API_KEY_ENV_VARc                   ó  ‡ — e Zd ZdZdˆ fd„Zdedefd„Zdedz  fd„Zde	d	e	dede	fd
„Z
	 	 	 dde	dededz  dedz  de	dz  de	fd„Z	 ddedz  ded	e	de	dz  def
d„Zdeded	e	de	def
d„Zdedej"                  dddefd„Zˆ xZS )ÚMistralOCRConfigzh
    Mistral OCR transformation configuration.

    Reference: https://docs.mistral.ai/api/#tag/ocr
    ÚreturnNc                 ó"   •— t         ‰| �  «        y ©N)ÚsuperÚ__init__)ÚselfÚ	__class__s    €úl/home/oem/CyberBrain26-unified/.venv/lib/python3.12/site-packages/litellm/llms/mistral/ocr/transformation.pyr   zMistralOCRConfig.__init__   s   ø€ Ü‰ÑÕó    Úmodelc                 ó
   — g d¢S )aÇ  
        Get supported OCR parameters for Mistral OCR.

        Mistral OCR supports:
        - pages: List of page numbers to process
        - include_image_base64: Whether to include base64 encoded images
        - image_limit: Maximum number of images to return
        - image_min_size: Minimum size of images to include
        - bbox_annotation_format: Format for bounding box annotations
        - document_annotation_format: Format for document annotations
        - document_annotation_prompt: Prompt for document annotation extraction
        - extract_header: Whether to extract document header
        - extract_footer: Whether to extract document footer
        - table_format: Table output format ("markdown" or "html")
        - confidence_scores_granularity: Confidence score level ("word" or "page")
        - include_blocks: Whether to return paragraph-level bounding boxes and typed content blocks (OCR 4)
        - id: Request identifier
        )ÚpagesÚinclude_image_base64Úimage_limitÚimage_min_sizeÚbbox_annotation_formatÚdocument_annotation_formatÚdocument_annotation_promptÚextract_headerÚextract_footerÚtable_formatÚconfidence_scores_granularityÚinclude_blocksÚid© )r   r   s     r   Úget_supported_ocr_paramsz)MistralOCRConfig.get_supported_ocr_params"   s   € ò&
ð 	
r   c                 ó   — t         S r   )r   )r   s    r   Úget_api_key_env_varz$MistralOCRConfig.get_api_key_env_varE   s   € Ü*Ð*r   Únon_default_paramsÚoptional_paramsc                 ór   — | j                  |¬«      }i }|j                  «       D ]  \  }}||v sŒ|||<   Œ |S )z½
        Map OCR parameters to Mistral-specific format.

        Mistral accepts these parameters directly, so no transformation needed.
        Just filter out unsupported params.
        )r   )r)   Úitems)r   r,   r-   r   Úsupported_paramsÚmapped_paramsÚparamÚvalues           r   Úmap_ocr_paramszMistralOCRConfig.map_ocr_paramsH   sV   € ð #'×"?Ñ"?ÀeÐ"?Ó"LÐð  "ˆØ.×4Ñ4Ó6ò 	-‰LˆE�5ØÐ(Ò(Ø',�˜eÒ$ð	-ð Ðr   ÚheadersÚapi_keyÚapi_baseÚlitellm_paramsc                 óT   — |€t        t        «      }|€t        d«      ‚dd|› �i|¥}|S )zJ
        Validate environment and return headers for Mistral OCR.
        z}Missing Mistral API Key - A call is being made to Mistral but no key is set either in the environment variables or via paramsÚAuthorizationzBearer )r
   r   Ú
ValueError)r   r5   r   r6   r7   r8   Úkwargss          r   Úvalidate_environmentz%MistralOCRConfig.validate_environment^   sP   € ð ˆ?Ü$Ô%@ÓAˆGàˆ?Üð Póð ð
 ˜w w iÐ0ð
àð
ˆð ˆr   c                 ób   — |€d}|j                  d«      }|j                  d«      r|› d�S |› d�S )zl
        Get complete URL for Mistral OCR endpoint.

        Returns: https://api.mistral.ai/v1/ocr
        zhttps://api.mistral.ai/v1ú/z/v1z/ocrz/v1/ocr)ÚrstripÚendswith)r   r7   r   r-   r8   r<   s         r   Úget_complete_urlz!MistralOCRConfig.get_complete_url|   sI   € ð ÐØ2ˆHð —?‘? 3Ó'ˆð ×Ñ˜UÔ#Ø�Z˜tÐ$Ð$à�˜7Ð#Ð#r   Údocumentc                 óÂ   — t        j                  d|«       t        |t        «      st	        dt        |«      › �«      ‚||dœ}|j                  |«       t        |d¬«      S )aå  
        Transform OCR request to Mistral-specific format.

        Mistral OCR API accepts:
        {
            "model": "mistral-ocr-latest",
            "document": {
                "type": "document_url",
                "document_url": "<https-url or data-uri>"
            },
            "pages": [0],  # optional
            "include_image_base64": false,  # optional
            ...
        }

        Args:
            model: Model name (e.g., "mistral-ocr-latest")
            document: Document dict from user (Mistral format) - already validated in main.py
            optional_params: Already mapped optional parameters
            headers: Request headers

        Returns:
            OCRRequestData with JSON data
        z-Mistral OCR transform_ocr_request - model: %szExpected document dict, got )r   rC   N)ÚdataÚfiles)r   ÚdebugÚ
isinstanceÚdictr;   ÚtypeÚupdater   )r   r   rC   r-   r5   r<   rE   s          r   Útransform_ocr_requestz&MistralOCRConfig.transform_ocr_request•   sf   € ô@ 	×ÑÐLÈeÔTô ˜(¤DÔ)ÜÐ;¼DÀ»NÐ;KÐLÓMÐMð Ø ñ
ˆð 	�‰�OÔ$ô  4¨tÔ4Ð4r   Úraw_responseÚlogging_objÚLiteLLMLoggingObjc                 óZ  — 	 |j                  «       }t        j                  d|j                  «       «       t	        |j                  dg «      |j                  d|«      |j                  d«      |j                  d«      d¬«      S # t        $ r}t        j                  d|«       |‚d	}~ww xY w)
av  
        Return Mistral OCR response in native format.

        Mistral OCR is the standard format for LiteLLM OCR responses.
        No transformation needed - return native response.

        Mistral OCR returns:
        {
            "pages": [
                {
                    "index": 0,
                    "markdown": "extracted text content",
                    "images": [...],
                    "dimensions": {...}
                },
                ...
            ],
            "model": "mistral-ocr-2505-completion",
            "document_annotation": null,
            "usage_info": {...}
        }
        zMistral OCR response keys: %sr   r   Údocument_annotationÚ
usage_infoÚocr)r   r   rQ   rR   Úobjectz&Error parsing Mistral OCR response: %sN)Újsonr   rG   Úkeysr	   ÚgetÚ	ExceptionÚerror)r   r   rM   rN   r<   Úresponse_jsonÚes          r   Útransform_ocr_responsez'MistralOCRConfig.transform_ocr_responseÈ   s¦   € ð:	Ø#/×#4Ñ#4Ó#6ˆMä× Ñ Ð!@À-×BTÑBTÓBVÔWô Ø#×'Ñ'¨°Ó4Ø#×'Ñ'¨°Ó7Ø$1×$5Ñ$5Ð6KÓ$LØ(×,Ñ,¨\Ó:Øôð øô ò 	Ü× Ñ Ð!IÈ1ÔMØˆGûð	ús   ‚BB Â	B*ÂB%Â%B*)r   N)NNNr   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   ÚstrÚlistr)   r+   rI   r4   r=   rB   r   r   rL   ÚhttpxÚResponser	   r\   Ú__classcell__)r   s   @r   r   r      sZ  ø„ ñõð!
¨cð !
°dó !
ðF+ S¨4¡Zó +ðà ðð ðð ð	ð
 
óð4 #Ø#Ø&*ñàðð ðð �t‘ð	ð
 ˜‘*ðð ˜t™ðð 
óðF '+ñ$à˜‘*ð$ð ð$ð ð	$ð
 ˜t™ð$ð 
ó$ð215àð15ð ð15ð ð	15ð
 ð15ð 
ó15ðf,àð,ð —n‘nð,ð )ð	,ð 
÷,r   r   )r`   Útypingr   r   rc   Úlitellm._loggingr   Ú(litellm.llms.base_llm.ocr.transformationr   r   r   r	   Úlitellm.secret_managers.mainr
   Ú*litellm.litellm_core_utils.litellm_loggingr   rO   r   Ú__annotations__r   r(   r   r   ú<module>rl      sC   ðò÷ (ã å +÷ó õ 8áÝWà%6Ð ˜UÓ 6ô\�}õ \r   