o
    0jv~                     @   s`  d dl Z d dlZd dlZd dlZd dlmZ d dlmZ d dlm	Z	m
Z
mZmZmZmZ d dlZd dlZd dlmZ ddlmZ dd	lmZmZmZmZmZmZmZmZm Z  G d
d dZ!G dd dZ"G dd dZ#dd Z$G dd dZ%G dd dZ&G dd dZ'G dd dZ(G dd dZ)G dd dZ*G dd dZ+G d d! d!Z,G d"d# d#Z-dS )$    N)abstractmethod)Path)AnyCallableDictListOptionalUnion)Image   )logging   )	AudioWriter	CSVWriter
HtmlWriterImageWriter
JsonWriterMarkdownWriter
TextWriterVideoWriter
XlsxWriterc                   @   s`   e Zd ZdZdedefddZedee	e
f fddZedee	e
f fd	d
ZdddZdS )	WordMixinzB
    Mixin class for adding Word (.docx) export capabilities.
    argskwargsc                 O      | j | j d S N)_save_funcsappendsave_to_wordselfr   r    r!   f/var/www/html/Deteccion_Ine/venv/lib/python3.10/site-packages/paddlex/inference/common/result/mixin.py__init__.      zWordMixin.__init__returnc                 C      t z
        Convert the result to a Word-compatible format.

        Returns:
            Dict[str, Any]: A dictionary containing Word-compatible blocks and image data.
        NotImplementedErrorr    r!   r!   r"   _to_word1      zWordMixin._to_wordc                 C      |   S r'   )r+   r*   r!   r!   r"   word;      zWordMixin.wordNc                 O   s   ddl m}m} t|  }t|}||j d }|  }||d |}	|j|d |	|dd|dd	d
}
|
	|
  dS )z Save the result to a .docx file.   )WordConvertersave_imagesz.docximagesZword_blocksoriginal_image_widthi  original_image_heightr   )abs_image_pathsr4   r5   N)	converterr1   r2   r   _get_input_fnstemr+   convertgetsaveas_posix)r    	save_pathr   r   r1   r2   fn	save_fileZ	word_datar6   docr!   r!   r"   r   E   s   

zWordMixin.save_to_wordr%   N)__name__
__module____qualname____doc__listdictr#   r   r   strr   r+   propertyr.   r   r!   r!   r!   r"   r   )   s    		r   c                   @   s\   e Zd ZdedefddZedeee	f fddZ
edeee	f fdd	ZdddZd
S )
LatexMixinr   r   c                 O   r   r   )r   r   save_to_latexr   r!   r!   r"   r#   Y   r$   zLatexMixin.__init__r%   c                 C   r&   )z
        Convert the result to a LaTeX-compatible format.

        Returns:
            Dict[str, Any]: A dictionary containing LaTeX-compatible blocks and image data.
        r(   r*   r!   r!   r"   	_to_latex\   r,   zLatexMixin._to_latexc                 C   r-   )zProperty to access the LaTeX-compatible data.

        Returns:
            Dict[str, Any]: A dictionary containing LaTeX-compatible blocks and image data.
        )rM   r*   r!   r!   r"   latexf      zLatexMixin.latexNc                 O   s   ddl m}m} t|  }t|}||j d }|  }||d |}	|j|d |	d}
t|	 ddd	}|
|
 W d
   d
S 1 sHw   Y  d
S )zSave the result to a .tex file.r0   )LatexConverterr2   z.texr3   Zlatex_blocks)r6   wzutf-8)encodingN)r7   rP   r2   r   r8   r9   rM   r:   openr=   write)r    r>   r   r   rP   r2   r?   r@   Z
latex_datar6   rN   fr!   r!   r"   rL   o   s   "zLatexMixin.save_to_latexrB   )rC   rD   rE   rG   rH   r#   r   r   rI   r   rM   rJ   rN   rL   r!   r!   r!   r"   rK   X   s    	rK   c                   @   s<   e Zd ZdZedeeef fddZdd Zd
dd	ZdS )StrMixinz6Mixin class for adding string conversion capabilities.r%   c                 C   r-   )zProperty to get the string representation of the result.

        Returns:
            Dict[str, str]: The string representation of the result.
        )_to_strr*   r!   r!   r"   rI      r/   zStrMixin.strc                 C   s   d| iS )a  Convert the given result data to a string representation.

        Args:
            json_format (bool): If True, return a JSON formatted string. Default is False.
            indent (int): Number of spaces to indent for JSON formatting. Default is 4.
            ensure_ascii (bool): If True, ensure all characters are ASCII. Default is False.

        Returns:
            Dict[str, str]: The string representation of the result.
        resr!   r*   r!   r!   r"   rW      s   zStrMixin._to_strNc                 C   s   t |   dS )z.Print the string representation of the result.N)r   inforW   r*   r!   r!   r"   print   s   zStrMixin.printrB   )	rC   rD   rE   rF   rJ   r   rI   rW   rZ   r!   r!   r!   r"   rV      s    	rV   c                 C   s   t | tjtjfrt| S t | tjtjfrt| S t | tjr)dd | 	 D S t | t
jr9t| jdddS t | trB|  S t | trRtdd |  D S t | ttfr`dd | D S | S )	zHelper function to format data into a JSON-serializable format.

    Args:
        obj: The object to be formatted.

    Returns:
        Any: The formatted object.
    c                 S      g | ]}t |qS r!   _format_data).0itemr!   r!   r"   
<listcomp>       z _format_data.<locals>.<listcomp>recordsF)ZorientZforce_asciic                 S   s   i | ]	\}}|t |qS r!   r\   )r^   kvr!   r!   r"   
<dictcomp>   s    z _format_data.<locals>.<dictcomp>c                 S   r[   r!   r\   )r^   ir!   r!   r"   r`      ra   )
isinstancenpZfloat32Zfloat64floatZint32Zint64intZndarraytolistpd	DataFramejsonloadsto_jsonr   r=   rH   itemsrG   tuple)objr!   r!   r"   r]      s   	

r]   c                   @   s   e Zd ZdZdddZdeeeeef f fddZe	deeeeef f fdd	Z
	
	ddedededededdfddZ		
	ddededefddZ	ddedededdfddZdS )	JsonMixinz7Mixin class for adding JSON serialization capabilities.r%   Nc                 C   s   t  | _| j| j d S r   )r   _json_writerr   r   save_to_jsonr*   r!   r!   r"   r#      s   zJsonMixin.__init__c                 C   s   dt t| iS )zConvert the object to a JSON-serializable format.

        Returns:
            Dict[str, Dict[str, Any]]: A dictionary representation of the object that is JSON-serializable.
        rX   )r]   copydeepcopyr*   r!   r!   r"   _to_json   s   zJsonMixin._to_jsonc                 C   r-   )zProperty to get the JSON representation of the result.

        Returns:
            Dict[str, Dict[str, Any]]: The dict type JSON representation of the result.
        )ry   r*   r!   r!   r"   rn      r/   zJsonMixin.jsonr   Fr>   indentensure_asciir   r   c                 O   s   dd }|   }||s?t|  }|j}	t|}
|D ]!}|
|	 d| d }| jj| || g|R ||d| qd
S t|dkrNt	d| d | jj||t
| d	  g|R ||d| d
S )ae  Save the JSON representation of the object to a file.

        Args:
            save_path (str): The path to save the JSON file. If the save path does not end with '.json', it appends the base name and suffix of the input path.
            indent (int): The number of spaces to indent for pretty printing. Default is 4.
            ensure_ascii (bool): If False, non-ASCII characters will be included in the output. Default is False.
            *args: Additional positional arguments to pass to the underlying writer.
            **kwargs: Additional keyword arguments to pass to the underlying writer.
        c                 S      t | \}}|d uo|dkS )Nzapplication/json	mimetypes
guess_type	file_path	mime_type_r!   r!   r"   _is_json_file      z-JsonMixin.save_to_json.<locals>._is_json_filer   z.jsonrz   r{   r0   z`The result has multiple json files need to be saved. But the `save_path` has been specified as ``!r   N)ry   r   r8   r9   ru   rT   r=   lenr   warningrG   keys)r    r>   rz   r{   r   r   r   Z	json_datar?   r9   base_save_pathkeyr!   r!   r"   rv      sF   

zJsonMixin.save_to_jsonjson_formatc                 C   s$   |rt jtd| i||dS d| iS )a  Convert the given result data to a string representation.
        Args:
            data (dict): The data would be converted to str.
            json_format (bool): If True, return a JSON formatted string. Default is False.
            indent (int): Number of spaces to indent for JSON formatting. Default is 4.
            ensure_ascii (bool): If True, ensure all characters are ASCII. Default is False.
        Returns:
            Dict[str, str]: The string representation of the result.
        rX   r   )rn   dumpsr]   )r    r   rz   r{   r!   r!   r"   rW     s
   zJsonMixin._to_strc                 C   s   | j |||d}t| dS )aU  Print the string representation of the result.

        Args:
            json_format (bool): If True, print a JSON formatted string. Default is False.
            indent (int): Number of spaces to indent for JSON formatting. Default is 4.
            ensure_ascii (bool): If True, ensure all characters are ASCII. Default is False.
        )r   rz   r{   N)rW   r   rY   )r    r   rz   r{   Zstr_r!   r!   r"   rZ   #  s   
zJsonMixin.printrB   )r   F)Fr   F)rC   rD   rE   rF   r#   r   rI   r   ry   rJ   rn   rj   boolr   rv   rW   rZ   r!   r!   r!   r"   rt      sR    
	 
7
rt   c                   @   t   e Zd ZdZdededdfddZedeeef fdd	Z	e
deeef fd
dZdedededdfddZdS )Base64Mixinz4Mixin class for adding Base64 encoding capabilities.r   r   r%   Nc                 O   "   t |i || _| j| j dS )zInitializes the Base64Mixin.

        Args:
            *args: Positional arguments to pass to the TextWriter.
            **kwargs: Keyword arguments to pass to the TextWriter.
        N)r   _base64_writerr   r   save_to_base64r   r!   r!   r"   r#   6     zBase64Mixin.__init__c                 C   r&   )zAbstract method to convert the result to Base64.

        Returns:
            Dict[str, str]: The str type Base64 representation result.
        r(   r*   r!   r!   r"   
_to_base64@     zBase64Mixin._to_base64c                 C   r-   )z
        Property that returns the Base64 encoded content.

        Returns:
            Dict[str, str]: The base64 representation of the result.
        )r   r*   r!   r!   r"   base64I  r/   zBase64Mixin.base64r>   c           	      O   s   |   }t| ds=t|  }|j}t|}|D ]}|| d| d }| jj|	 || g|R i | qdS t
|dkrLtd| d | jj||t| d  g|R i | dS )a  Saves the Base64 encoded content to the specified path.

        Args:
            save_path (str): The path to save the base64 representation result. If the save path does not end with '.b64', it appends the base name and suffix of the input path.

            *args: Additional positional arguments that will be passed to the base64 writer.
            **kwargs: Additional keyword arguments that will be passed to the base64 writer.
        z.b64r   r0   zbThe result has multiple base64 files need to be saved. But the `save_path` has been specified as `r   r   N)r   rI   lowerendswithr   r8   r9   r   rT   r=   r   r   r   rG   r   )	r    r>   r   r   r   r?   r9   r   r   r!   r!   r"   r   S  s4   	

zBase64Mixin.save_to_base64)rC   rD   rE   rF   r   r   r#   r   rI   r   rJ   r   r   r!   r!   r!   r"   r   3  s    
	r   c                	   @   s~   e Zd ZdZddedededdfdd	Zedeee	j	f fd
dZ
edeee	j	f fddZdedededdfddZdS )ImgMixinz3Mixin class for adding image handling capabilities.pillowbackendr   r   r%   Nc                 O   s&   t |d|i|| _| j| j dS )a%  Initializes ImgMixin.

        Args:
            backend (str): The backend to use for image processing. Defaults to "pillow".
            *args: Additional positional arguments to pass to the ImageWriter.
            **kwargs: Additional keyword arguments to pass to the ImageWriter.
        r   N)r   _img_writerr   r   save_to_imgr    r   r   r   r!   r!   r"   r#   s  s   zImgMixin.__init__c                 C   r&   )zAbstract method to convert the result to an image.

        Returns:
            Dict[str, Image.Image]: The image representation result.
        r(   r*   r!   r!   r"   _to_img~  r   zImgMixin._to_imgc                 C   r-   )zProperty to get the image representation of the result.

        Returns:
            Dict[str, Image.Image]: The image representation of the result.
        )r   r*   r!   r!   r"   img  rO   zImgMixin.imgr>   c                 O   s   dd }|   }||sFt|  }||r|jnd}|j}t|}	|D ]}
|	| d|
 |  }| jj| ||
 g|R i | q$d	S t|dkrUt	
d| d | jj||t| d  g|R i | d	S )
a  Saves the image representation of the result to the specified path.

        Args:
            save_path (str): The path to save the image. If the save path does not end with .jpg or .png, it appends the input path's stem and suffix to the save path.
            *args: Additional positional arguments that will be passed to the image writer.
            **kwargs: Additional keyword arguments that will be passed to the image writer.
        c                 S       t | \}}|d uo|dS )Nzimage/r~   r   
startswithr   r!   r!   r"   _is_image_file     z,ImgMixin.save_to_img.<locals>._is_image_filez.pngr   r0   z_The result has multiple img files need to be saved. But the `save_path` has been specified as `r   r   N)r   r   r8   suffixr9   r   rT   r=   r   r   r   rG   r   )r    r>   r   r   r   r   r?   r   r9   r   r   r!   r!   r"   r     s    	&
0zImgMixin.save_to_img)r   )rC   rD   rE   rF   rI   r   r   r#   r   r
   r   rJ   r   r   r!   r!   r!   r"   r   p      r   c                	   @   ~   e Zd ZdZddedededdfdd	Zedeee	j
f fd
dZedeee	j
f fddZdedededdfddZdS )CSVMixinz1Mixin class for adding CSV handling capabilities.pandasr   r   r   r%   Nc                 O   s6   t |d|i|| _t| dsg | _| j| j dS )a  Initializes the CSVMixin.

        Args:
            backend (str): The backend to use for CSV operations (default is "pandas").
            *args: Optional positional arguments to pass to the CSVWriter.
            **kwargs: Optional keyword arguments to pass to the CSVWriter.
        r   r   N)r   _csv_writerhasattrr   r   save_to_csvr   r!   r!   r"   r#     s   
zCSVMixin.__init__c                 C   r-   )zProperty to get the pandas Dataframe representation of the result.

        Returns:
            Dict[str, pd.DataFrame]: The pandas.DataFrame representation of the result.
        )_to_csvr*   r!   r!   r"   csv  rO   zCSVMixin.csvc                 C   r&   )zAbstract method to convert the result to pandas.DataFrame.

        Returns:
            Dict[str, pd.DataFrame]: The pandas.DataFrame representation result.
        r(   r*   r!   r!   r"   r     r   zCSVMixin._to_csvr>   c           
      O      dd }|   }||s<t|  }|j}t|}|D ]}	|| d|	 d }| jj| ||	 g|R i | qd	S t|dkrKt	d| d | jj||t
| d  g|R i | d	S )
a  Saves the result to a CSV file.

        Args:
            save_path (str): The path to save the CSV file. If the path does not end with ".csv",
                the stem of the input path attribute (self['input_path']) will be used as the filename.
            *args: Optional positional arguments to pass to the CSV writer's write method.
            **kwargs: Optional keyword arguments to pass to the CSV writer's write method.
        c                 S   r|   )Nztext/csvr}   r   r!   r!   r"   _is_csv_file  r   z*CSVMixin.save_to_csv.<locals>._is_csv_filer   z.csvr0   z_The result has multiple csv files need to be saved. But the `save_path` has been specified as `r   r   N)r   r   r8   r9   r   rT   r=   r   r   r   rG   r   )
r    r>   r   r   r   r   r?   r9   r   r   r!   r!   r"   r     s   
&
0zCSVMixin.save_to_csv)r   )rC   rD   rE   rF   rI   r   r   r#   rJ   rl   rm   r   r   r   r   r!   r!   r!   r"   r     s    r   c                   @   r   )	HtmlMixinz2Mixin class for adding HTML handling capabilities.r   r   r%   Nc                 O   r   )a   
        Initializes the HTML writer and appends the save_to_html method to the save functions list.

        Args:
            *args: Positional arguments passed to the HtmlWriter.
            **kwargs: Keyword arguments passed to the HtmlWriter.
        N)r   _html_writerr   r   save_to_htmlr   r!   r!   r"   r#     s   zHtmlMixin.__init__c                 C   r-   )zProperty to get the HTML representation of the result.

        Returns:
            str: The str type HTML representation of the result.
        )_to_htmlr*   r!   r!   r"   html  rO   zHtmlMixin.htmlc                 C   r&   )zAbstract method to convert the result to str type HTML representation.

        Returns:
            Dict[str, str]: The str type HTML representation result.
        r(   r*   r!   r!   r"   r     r   zHtmlMixin._to_htmlr>   c           
      O   r   )
zSaves the HTML representation of the object to the specified path.

        Args:
            save_path (str): The path to save the HTML file.
            *args: Additional positional arguments.
            **kwargs: Additional keyword arguments.
        c                 S   r|   )Nz	text/htmlr}   r   r!   r!   r"   _is_html_file  r   z-HtmlMixin.save_to_html.<locals>._is_html_filer   z.htmlr0   z`The result has multiple html files need to be saved. But the `save_path` has been specified as `r   r   N)r   r   r8   r9   r   rT   r=   r   r   r   rG   r   )
r    r>   r   r   r   r   r?   r9   r   r   r!   r!   r"   r     s6   	

zHtmlMixin.save_to_html)rC   rD   rE   rF   r   r   r#   rJ   rI   r   r   r   r   r!   r!   r!   r"   r     s    r   c                   @   r   )	XlsxMixinz2Mixin class for adding XLSX handling capabilities.r   r   r%   Nc                 O   r   )a  Initializes the XLSX writer and appends the save_to_xlsx method to the save functions.

        Args:
            *args: Positional arguments to be passed to the XlsxWriter constructor.
            **kwargs: Keyword arguments to be passed to the XlsxWriter constructor.
        N)r   _xlsx_writerr   r   save_to_xlsxr   r!   r!   r"   r#   2  r   zXlsxMixin.__init__c                 C   r-   )zProperty to get the XLSX representation of the result.

        Returns:
            Dict[str, str]: The str type XLSX representation of the result.
        )_to_xlsxr*   r!   r!   r"   xlsx<  rO   zXlsxMixin.xlsxc                 C   r&   )zAbstract method to convert the result to str type XLSX representation.

        Returns:
            Dict[str, str]: The str type HTML representation result.
        r(   r*   r!   r!   r"   r   E  r   zXlsxMixin._to_xlsxr>   c           
      O   r   )
a  Saves the HTML representation to an XLSX file.

        Args:
            save_path (str): The path to save the XLSX file. If the path does not end with ".xlsx",
                             the filename will be set to the stem of the input path with ".xlsx" extension.
            *args: Additional positional arguments to pass to the XLSX writer.
            **kwargs: Additional keyword arguments to pass to the XLSX writer.
        c                 S   r|   )NzAapplication/vnd.openxmlformats-officedocument.spreadsheetml.sheetr}   r   r!   r!   r"   _is_xlsx_fileX  s   z-XlsxMixin.save_to_xlsx.<locals>._is_xlsx_filer   z.xlsxr0   z`The result has multiple xlsx files need to be saved. But the `save_path` has been specified as `r   r   N)r   r   r8   r9   r   rT   r=   r   r   r   rG   r   )
r    r>   r   r   r   r   r?   r9   r   r   r!   r!   r"   r   N  s6   


zXlsxMixin.save_to_xlsx)rC   rD   rE   rF   r   r   r#   rJ   rI   r   r   r   r   r!   r!   r!   r"   r   /  s    
r   c                	   @   r   )
VideoMixinz3Mixin class for adding Video handling capabilities.opencvr   r   r   r%   Nc                 O   s   || _ | j| j dS )a'  Initializes VideoMixin.

        Args:
            backend (str): The backend to use for video processing. Defaults to "opencv".
            *args: Additional positional arguments to pass to the VideoWriter.
            **kwargs: Additional keyword arguments to pass to the VideoWriter.
        N)_backendr   r   save_to_videor   r!   r!   r"   r#   w  s   zVideoMixin.__init__c                 C   r&   )zAbstract method to convert the result to a video.

        Returns:
            Dict[str, np.array]: The video representation result.
        r(   r*   r!   r!   r"   	_to_video  r   zVideoMixin._to_videoc                 C   r-   )zProperty to get the video representation of the result.

        Returns:
            Dict[str, np.array]: The video representation of the result.
        )r   r*   r!   r!   r"   video  rO   zVideoMixin.videor>   c                 O   s   dd }t |d| ji|}|  }||sOt|  }|j}||r&|jnd}	t|}
|D ]}|
| d| |	  }|j| || g|R i | q.d
S t	|dkr^t
d| d |j||t| d	  g|R i | d
S )a  Saves the video representation of the result to the specified path.

        Args:
            save_path (str): The path to save the video. If the save path does not end with .mp4 or .avi, it appends the input path's stem and suffix to the save path.
            *args: Additional positional arguments that will be passed to the video writer.
            **kwargs: Additional keyword arguments that will be passed to the video writer.
        c                 S   r   )Nzvideo/r   r   r!   r!   r"   _is_video_file  r   z0VideoMixin.save_to_video.<locals>._is_video_filer   z.mp4r   r0   zaThe result has multiple video files need to be saved. But the `save_path` has been specified as `r   r   N)r   r   r   r   r8   r9   r   rT   r=   r   r   r   rG   r   )r    r>   r   r   r   Zvideo_writerr   r?   r9   r   r   r   r!   r!   r"   r     s"   	$
.zVideoMixin.save_to_video)r   )rC   rD   rE   rF   rI   r   r   r#   r   rh   arrayr   rJ   r   r   r!   r!   r!   r"   r   t  r   r   c                   @   sx   e Zd ZdZdededdfddZedeee	j
f fdd	Zedeee	j
f fd
dZdedededdfddZdS )
AudioMixinz3Mixin class for adding Audio handling capabilities.r   r   r%   Nc                 O   s.   || _ | j| j t|d| j i|| _dS )zInitializes AudioMixin.

        Args:
            *args: Additional positional arguments to pass to the AudioWriter.
            **kwargs: Additional keyword arguments to pass to the AudioWriter.
        r   N)r   r   r   save_to_audior   _audio_writerr   r!   r!   r"   r#     s   zAudioMixin.__init__c                 C   r&   )zAbstract method to convert the result to a audio.

        Returns:
            Dict[str, np.array]: The audio representation result.
        r(   r*   r!   r!   r"   	_to_audio  r   zAudioMixin._to_audioc                 C   r-   )zProperty to get the audio representation of the result.

        Returns:
            Dict[str, np.array]: The audio representation of the result.
        )r   r*   r!   r!   r"   audio  rO   zAudioMixin.audior>   c                 O   s   dd }|   }||sFt|  }|j}||r|jnd}t|}	|D ]}
|	| d|
 |  }| jj| ||
 g|R i | q$d	S t|dkrUt	
d| d | jj||t| d  g|R i | d	S )
a  Saves the audio representation of the result to the specified path.

        Args:
            save_path (str): The path to save the audio. If the save path does not end with .mp4 or .avi, it appends the input path's stem and suffix to the save path.
            *args: Additional positional arguments that will be passed to the audio writer.
            **kwargs: Additional keyword arguments that will be passed to the audio writer.
        c                 S   r   )Nzaudio/r   r   r!   r!   r"   _is_audio_file  r   z0AudioMixin.save_to_audio.<locals>._is_audio_filez.wavr   r0   zaThe result has multiple audio files need to be saved. But the `save_path` has been specified as `r   r   N)r   r   r8   r9   r   r   rT   r=   r   r   r   rG   r   )r    r>   r   r   r   r   r?   r9   r   r   r   r!   r!   r"   r     s8   	

zAudioMixin.save_to_audio)rC   rD   rE   rF   r   r   r#   r   rI   rh   r   r   rJ   r   r   r!   r!   r!   r"   r     s    r   c                   @   s   e Zd ZdZdgZdedefddZe	dd	e	e
ee
e	e
ef f f fd
dZed	e	e
ee
e	e
ef f f fddZ	d	dddZdededee
ef dee	e
ee
e	e
ef f f  d	df
ddZdS )MarkdownMixinz6Mixin class for adding Markdown handling capabilities.Zmarkdown_textsr   r   c                 O   s2   t |i || _t|i || _| j| j dS )a&  Initializes the Markdown writer and appends the save_to_markdown method to the save functions.

        Args:
            *args: Positional arguments to be passed to the MarkdownWriter constructor.
            **kwargs: Keyword arguments to be passed to the MarkdownWriter constructor.
        N)r   _markdown_writerr   r   r   r   save_to_markdownr   r!   r!   r"   r#     s   zMarkdownMixin.__init__TFr%   c                 C   r&   )a  
        Convert the result to markdown format.

        Args:
            pretty (Optional[bool]): whether to pretty markdown by HTML, default by True.

        Returns:
            Dict[str, Union[str, Dict[str, Any]]]: A dictionary containing markdown text and image data.
        r(   )r    prettyshow_formula_numberr!   r!   r"   _to_markdown  s   zMarkdownMixin._to_markdownc                 C   r-   )zProperty to access the markdown data.

        Returns:
            Dict[str, Union[str, Dict[str, Any]]]: A dictionary containing markdown text and image data.
        )r   r*   r!   r!   r"   markdown  rO   zMarkdownMixin.markdownNc                 O   s   dt fdd}||s-t|  }||r|jnd}|j}	t|}
|
|	 |  }|| _n|| _| j| jj| j	j| j| j
||dg|R i | dS )a  Save the markdown data to a file.

        Args:
            save_path (Union[str, Path]): The path where the markdown file will be saved.
            *args: Additional positional arguments for saving.
            **kwargs: Additional keyword arguments for saving.
        r%   c                 S   sF   h d}t jt| \}}| |v rdS tt| \}}|dkS )a  Check if a file is a markdown file based on its extension or MIME type.

            Args:
                file_path (Union[str, Path]): The path to the file.

            Returns:
                bool: True if the file is a markdown file, False otherwise.
            >   z.mdown.mdz.mkdz	.markdownTztext/markdown)ospathsplitextrI   r   r~   r   )r   Zmarkdown_extensionsr   extr   r!   r!   r"   _is_markdown_file(  s   	z9MarkdownMixin.save_to_markdown.<locals>._is_markdown_filer   )r   r   N)r   r   r8   r   r9   r>   
_save_datar   rT   r   r   )r    r>   r   r   r   r   r   r?   r   r9   r   r!   r!   r"   r     s&   
zMarkdownMixin.save_to_markdownsave_mkd_funcsave_img_funcr>   datac                 O   s   t |}|du r
dS | D ]:\}}|| jv r%|| |g|R i | t|trH|j}	| D ]\}
}|rG||	|
  |g|R i | q1qdS )a  Internal method to save markdown and image data.

        Args:
            save_mkd_func (Callable): Function to save markdown text.
            save_img_func (Callable): Function to save image data.
            save_path (Union[str, Path]): The base path where the data will be saved.
            data (Optional[Dict[str, Union[str, Dict[str, Any]]]]): The markdown data to save.
            *args: Additional positional arguments for saving.
            **kwargs: Additional keyword arguments for saving.
        N)r   rq   MARKDOWN_SAVE_KEYSr=   rg   rH   parent)r    r   r   r>   r   r   r   r   valuer   Zimg_pathZimg_datar!   r!   r"   r   J  s(   


zMarkdownMixin._save_data)TFrB   )rC   rD   rE   rF   r   rG   rH   r#   r   r   rI   r	   r   r   rJ   r   r   r   r   r   r   r!   r!   r!   r"   r     s4    (	
-
r   ).rw   rn   r~   r   abcr   pathlibr   typingr   r   r   r   r   r	   numpyrh   r   rl   ZPILr
   utilsr   Zutils.ior   r   r   r   r   r   r   r   r   r   rK   rV   r]   rt   r   r   r   r   r   r   r   r   r!   r!   r!   r"   <module>   s2    ,/*!u=>@AE?B