
    j                     j    d Z ddlmZ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  G d de	      Zy)	z,
Mistral OCR transformation implementation.
    )AnyDictOptionalN)verbose_logger)BaseOCRConfigDocumentTypeOCRRequestDataOCRResponse)get_secret_strc                        e Zd ZdZd fdZdedefdZdedededefdZ		 	 	 dd	e
ded
ee   dee   dee   de
fdZ	 ddee   dededee   def
dZdededed	edef
dZdedej$                  dedefdZ xZS )MistralOCRConfigzl
    Mistral OCR transformation configuration.
    
    Reference: https://docs.mistral.ai/api/#tag/ocr
    returnc                 "    t         |           y N)super__init__)self	__class__s    /Users/manta/Documents/Projects/TheRoad-I1/backend/.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
        )pagesinclude_image_base64image_limitimage_min_sizebbox_annotation_formatdocument_annotation_format )r   r   s     r   get_supported_ocr_paramsz)MistralOCRConfig.get_supported_ocr_params   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_params1   sQ      88u8E .446LE5((',e$ 7 r   headersapi_keyapi_baselitellm_paramsc                 L    |t        d      }|t        d      dd| i|}|S )zJ
        Validate environment and return headers for Mistral OCR.
        MISTRAL_API_KEYz}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   
ValueError)r   r*   r   r+   r,   r-   kwargss          r   validate_environmentz%MistralOCRConfig.validate_environmentG   sU     ?01  ? P 
 wwi0

 r   c                 b    |d}|j                  d      }|j                  d      r| dS | dS )zt
        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   r,   r   r"   r-   r2   s         r   get_complete_urlz!MistralOCRConfig.get_complete_urlg   sI     2H ??3' U#Zt$$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: zExpected document dict, got )r   r9   N)datafiles)r   debug
isinstancedictr1   typeupdater	   )r   r   r9   r"   r*   r2   r;   s          r   transform_ocr_requestz&MistralOCRConfig.transform_ocr_request   sk    @ 	J5'RS (D);DN;KLMM  
 	O$ 4t44r   raw_responselogging_objc                 b   	 |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)
a  
        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: r   r   document_annotation
usage_infoocr)r   r   rF   rG   objectz$Error parsing Mistral OCR response: N)jsonr   r=   keysr
   get	Exceptionerror)r   r   rC   rD   r2   response_jsones          r   transform_ocr_responsez'MistralOCRConfig.transform_ocr_response   s    :	(--/M  #>}?Q?Q?S>T!UV #''4#''7$1$5$56K$L(,,\:   	  #Gs!KLG	s   BB 	B.B))B.)r   N)NNNr   )__name__
__module____qualname____doc__r   strlistr    r?   r)   r   r   r3   r8   r   r	   rB   httpxResponser   r
   rQ   __classcell__)r   s   @r   r   r      sI   
c 
d 
*   	
 
4 "&"&)-  #	
 3- ! 
J *.$3-$ $ 	$
 !$ 
$41515 15 	15
 15 
15f,, nn, 	, 
,r   r   )rU   typingr   r   r   rX   litellm._loggingr   (litellm.llms.base_llm.ocr.transformationr   r   r	   r
   litellm.secret_managers.mainr   r   r   r   r   <module>r_      s5    ' &  +  8N} Nr   