o
    5)i!                     @   sv   d dl Z d dlZd dlZd dlZd dlmZmZmZmZ d dl	m
Z
 eeZG dd dee
ZG dd dZeZdS )    N)ListDictTupleLiteral)Enumc                   @   s   e Zd ZdZdZdZdS )OutputFormatz.Supported output formats for LaTeX conversion.svghtmlN)__name__
__module____qualname____doc__SVGHTML r   r   :/var/www/html/oms-prod-mcp/app/services/latex_converter.pyr      s    r   c                   @   s   e Zd ZdZdZdejdfdededefdd	Z	d
efddZ
defddZdedeeeeef  fddZdeeeef  dee fddZdefddZddededefddZdS )LatexConverterz|Efficient LaTeX converter using batched MathJax processing.
    
    Supports both SVG and HTML (CHTML) output formats.
    nodez&node_scripts/batch_latex_converter.mjsi  script_pathoutput_format
cache_sizec                 C   s   || _ || _d| _dS )z
        Initialize the converter.

        Args:
            script_path: Path to the Node.js script
            output_format: Output format - 'svg' or 'html'
            cache_size: Unused in this implementation (kept for compatibility)
        N)r   r   _chtml_styles)selfr   r   r   r   r   r   __init__   s   
zLatexConverter.__init__	node_pathc                 C   
   || _ | S )z'Use the node path to execute the script)r   )r   r   r   r   r   with_node_path+      zLatexConverter.with_node_pathc                 C   r   )z#Set the output format (svg or html))r   )r   r   r   r   r   with_output_format0   r   z!LatexConverter.with_output_formathtml_contentreturnc           
      C   s   g }ddg}|D ]#\}}t ||t jD ]}|d}|d }|||df qqddg}	|	D ]#\}}t ||t jD ]}|d}|d }|||df q>q2td	|  |S )
z
        Find all LaTeX formulas in HTML content.

        Returns:
            List of tuples (placeholder, latex, is_display)
        )z\$\$(.*?)\$\$z$$)z\\\[(.*?)\\\]z\[\]r      T)z#(?<!\$)\$(?!\$)(.*?)(?<!\$)\$(?!\$)$)z\\\((.*?)\\\)z\(\)Fz
formulas: )refinditerDOTALLgroupstripappendloggerdebug)
r   r   formulasdisplay_patternspatterndelimmatchplaceholderlatexinline_patternsr   r   r   find_latex_in_html5   s*   

z!LatexConverter.find_latex_in_htmlr+   c           	   
      s~  |sg S g | j j| j tjkd}t|D ]\}\}}|d |||d qzAtj| j| j	gt
|dddd}t
|j}td|  t|trN|}n|dg }d|v r]|d | _|jd	d
 d |W S  tjy   z td j  td j   fdd|D W  Y d  S d  w t
jy   ztd   td    fdd|D W  Y d  S d  ww )a  
        Convert multiple LaTeX formulas to SVG or HTML in a single call.

        Args:
            formulas: List of tuples (latex_string, is_display)

        Returns:
            List of dictionaries with 'svg'/'html' and 'output' or 'error' keys
        )r+   formatincludeStylesr+   )idr1   displayT)inputcapture_outputtextcheckzConverted formulas response: resultsstylesc                 S   s   | d S )Nr6   r   )xr   r   r   <lambda>   s    z.LatexConverter.convert_batch.<locals>.<lambda>)keyzError running Node.js script: c                       g | ]	}d t  dqS F)successerrorstr.0_er   r   
<listcomp>       z0LatexConverter.convert_batch.<locals>.<listcomp>NzError parsing output: c                    rA   rB   rE   rG   rJ   r   r   rL      rM   )r   valuer   r   	enumerater(   
subprocessrunr   r   jsondumpsloadsstdoutr)   r*   
isinstancelistgetr   sortCalledProcessErrorprintstderrrD   JSONDecodeError)	r   r+   
input_datair1   r7   resultresponseoutputsr   rJ   r   convert_batchZ   sP   



	

zLatexConverter.convert_batchc                 C   s
   | j pdS )z
        Get the CHTML styles required for HTML output.
        
        Returns:
            CSS styles as a string, or empty string if not available
         )r   )r   r   r   r   get_chtml_styles   s   
zLatexConverter.get_chtml_stylesT	use_cachec                 C   s  |  |}|s	|S i }g }|D ]\}}}||f}	|	|vr%d||	< ||	 q|rZ| |}
t||
D ]'\\}}}|d rR|dpJ|dpJ|d}||||f< q2td|  q2|}i }|D ]#\}}}|||f}|r|}|rtdnd}d	| d
| d}|||< q`t| tdd}|D ]
}|	||| }q| j
tjkr| jrd| j d}d|v r|	d| d}|S d|v r|	dd| }|S )a>  
        Process HTML content and replace all LaTeX formulas with SVGs or HTML.

        Args:
            html_content: HTML content with LaTeX formulas
            use_cache: Unused in this implementation (kept for compatibility)

        Returns:
            HTML content with LaTeX replaced by SVG or HTML
        NrC   outputr   r	   zFailed to convert: zmath-displayzmath-inlinez<span class="z">z</span>T)r@   reversez<style id="mjx-styles">z</style>z</head>z<head>)r3   r(   rc   ziprX   r[   sortedkeyslenreplacer   r   r   r   )r   r   rf   formula_dataunique_formulas_mapunique_formulas_listrI   r1   r7   r@   r<   r`   rg   processed_htmlreplacementsr0   
is_displaywrapper_classwrapped_outputsorted_replacements
styles_tagr   r   r   process_html   sN   


zLatexConverter.process_htmlN)T)r
   r   r   r   r   r   r   rF   intr   r   r   r   r   boolr3   r   rc   re   rx   r   r   r   r   r      s&    
 "%A	r   )rR   rP   r#   loggingtypingr   r   r   r   enumr   	getLoggerr
   r)   rF   r   r   LatexToSVGConverterr   r   r   r   <module>   s    
 ^