
    j5j?                    .   d Z ddlm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
 ddlmZmZ ddlmZ dd	lmZmZ dd
lmZ ddlmZmZmZ ddlmZ ddlmZ ddlmZmZ  e g d      Z!ejD                  dk(  rdndZ# ejH                  e%      Z& G d dejN                        Z( ee#      Z)e)jT                  Z*e)jV                  Z+d#dZ,d$dZ-d$dZ.ddddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d%dZ/ G d d      Z0dddd ddd!	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d&d"Z1y)'z$Interface to Ghostscript executable.    )annotationsN)dequefspath)Path)PIPECalledProcessError)Version)ImageUnidentifiedImageError)	ToolProbe)ColorConversionNeededErrorInputFileErrorSubprocessOutputError)
Resolution)GhostscriptRasterDevice)runrun_polling_stderr)CMYKGrayLeaveColorUnchangedRGBUseDeviceIndependentColorntgswin64cgsc                       e Zd ZdZdddZd Zy)DuplicateFilterzFilter out duplicate log messages.

    A context window of default 5 messages is used to determine if a message is a
    duplicate. This is because some Ghostscript messages are word wrapped.
    c                n    t        g |      | _        || _        t        j                  | _        d| _        y )N)maxlenr   )r   windowloggerloggingDEBUGlevelnocount)selfr"   context_windows      P/var/www/html/qr/venv/lib/python3.12/site-packages/ocrmypdf/_exec/ghostscript.py__init__zDuplicateFilter.__init__4   s)    "'>"B}}
    c                   |j                   | j                  v r'| xj                  dz  c_        |j                  | _        y| j                  dk\  rWd| j                   d}d| _        | j                  j                  | j                  |       | j                  j                          | j                  j                  |j                          y)N   Fz(suppressed z repeated lines)r   T)msgr!   r&   r%   r"   logclearappend)r'   recordrep_msgs      r)   filterzDuplicateFilter.filter:   s    ::$JJ!OJ!>>DLzzQ(4DE
g6!!#KKvzz*r+   N)   )r"   zlogging.Logger)__name__
__module____qualname____doc__r*   r4    r+   r)   r   r   -   s    r+   r   )programc                     t        d t        j                  D              s#t        j                  t	        t                     yy)zIdempotently attach the duplicate-suppressing filter to the GS logger.

    Called at the top of each work function so the filter is present in the
    main process *and* in any subprocess worker that calls Ghostscript.
    c              3  <   K   | ]  }t        |t                y wN)
isinstancer   ).0fs     r)   	<genexpr>z/_ensure_log_filter_installed.<locals>.<genexpr>T   s     C!z!_-Cs   N)anyr/   filters	addFilterr   r:   r+   r)   _ensure_log_filter_installedrF   N   s-     Cs{{CCoc*+ Dr+   c                d    t        j                  d| t         j                        }t        |      S )Nerrorflags)research
IGNORECASEboolstreammatchs     r)   _gs_error_reportedrR   X   s"    IIhbmm<E;r+   c                    t        j                  d| t         j                  t         j                  z        }t	        |      S )zDid Ghostscript warn about a DeviceN with inappropriate alternate?

    If so, we need the user to select a color conversion, or the resulting PDF will
    not present correctly in some PDF viewers.
    z DeviceN.*inappropriate alternaterI   )rK   rL   rM   	MULTILINErN   rO   s     r)   _gs_devicen_reportedrU   ]   s4     II+mmbll*E
 ;r+   r-   F)pagenopage_dpirotationfilter_vectorstop_on_erroruse_cropboxc                  t                |j                  d      }|s|}d}
|j                  |
k  xs |j                  |
k  }|r5t	        t        |j                  |
      t        |j                  |
            }n|}t        j                  t        j                  f}||v rg nddg}t        ddddd	| d
| d| d|j                  dd|j                  dg	|z   |	rdgng z   |rdgng z   |rdgng z   dt        |      dddt        |       gz   }	 t        |t        t        d      }|j                   j#                  d      }t+        |      rAt        j                  |       |r*d|v r&t%        |      j'                  d       t-        d      	 t/        j0                  |      5 }|r|j                  |j                  z  }|j                  |j                  z  }t        dt3        t        |j4                  |z                    t        dt3        t        |j6                  |z                    f}|j9                  |t.        j:                  j<                        }|t        j?                  d |       |d!k(  r*|jA                  t.        jB                  jD                        }n]|d"k(  r*|jA                  t.        jB                  jF                        }n.|d#k(  r)|jA                  t.        jB                  jH                        }|d"z  d!k(  r|jK                         }|jM                  ||$       ddd       y# t        $ r[}t        j                  |j                   j#                  d             t%        |      j'                  d       t)        d      |d}~ww xY w# 1 sw Y   yxY w# tN        $ r t        j                  d%| d&| d'        tP        $ r,}t        j                  d%| d&| d'       tO               |d}~ww xY w)(a  Rasterize one page of a PDF at resolution raster_dpi in canvas units.

    Args:
        input_file: The PDF file to rasterize.
        output_file: The file to write the rasterized PDF to.
        raster_device: The Ghostscript raster device to use to rasterize the PDF.
        raster_dpi: Resolution in dots per inch at which to rasterize page.
        pageno: Page number to rasterize (beginning at page 1).
        page_dpi: Resolution, overriding output image DPI.
        rotation: Cardinal angle, clockwise, to rotate page.
        filter_vector: If True, remove vector graphics objects.
        stop_on_error: If True, stop rasterizing on the first error.
        use_cropbox: If True, rasterize the CropBox instead of MediaBox.
            Default is False (use MediaBox).
       
   z-dTextAlphaBits=4z-dGraphicsAlphaBits=4-dSAFER-dBATCH	-dNOPAUSEz-dInterpolateControl=-1z	-sDEVICE=z-dFirstPage=z-dLastPage=z-rrA   xz-dUseCropBoxz-dFILTERVECTOR-dPDFSTOPONERROR-o-sstdout=%stderr-dAutoRotatePages=/Nonez-fT)stdoutstderrcheckreplace)errors)
missing_okzGhostscript rasterizing failedNzrecoverable image errora  Ghostscript rasterizing failed. The input file contains errors that cause PDF viewers to interpret it differently and incorrectly. Try using --continue-on-soft-render-error and manually inspect the input and output files to check for visual differences or errors.r-   zRotating output by %iZ      i  )dpizGhostscript (using z at z* dpi) produced an invalid page image file.))rF   roundrb   yr   maxr   PNGMONOPNGMONODGSr   r   r   r	   r/   rH   rh   decoder   unlinkr   rR   r   r   openintwidthheightresize
ResamplingLANCZOSdebug	transpose	Transpose	ROTATE_90
ROTATE_180
ROTATE_270	flip_axissaver   OSError)
input_fileoutput_fileraster_device
raster_dpirV   rW   rX   rY   rZ   r[   MIN_RASTER_DPIneeds_low_dpi_resizeeffective_dpimono_devicesantialias_argsargs_gsperh   imscale_xscale_ynew_sizes                          r)   rasterize_pdfr   k   s   8 !"!!!$J N~%F)F  "
n-s:<</P
 # ,335L5U5UVL L( 	!#:;  %'6(#&"#1]__Q$78
	
 	  +N	4 "/B	8 $1b	:  ;%:
	
 4MT> XX__I_.F&!		&6&@$$$5 T $.ZZ$ 	/# %,,8$,,83uRXX%789:3uRYY%89:; YYx)9)9)A)AB#		18< r>eoo&?&?@B_eoo&@&@AB_eoo&@&@ABc>R''113HGGKXG./	/ 	/%  M		!((///34[  D 1#$DE1LM$	/ 	/0 " 		!-ZL A* *	
 	 .		!-ZL A* *	
 %&A-.sP   L2 N% %FN)N% 2	N;ANNN"N% "N% %.O?'O::O?c                  p    e Zd ZdZ ej
                  d      Z ej
                  d      Zd Zd Z	d Z
d Zy)	GhostscriptFollowerzHParses the output of Ghostscript and uses it to update the progress bar.z#Processing pages \d+ through (\d+).z
Page (\d+)c                .    d| _         || _        d | _        y )Nr   )r&   progressbar_classprogressbar)r'   r   s     r)   r*   zGhostscriptFollower.__init__   s    
!2r+   c                    | S r>   r:   )r'   s    r)   	__enter__zGhostscriptFollower.__enter__  s	     r+   c                V    | j                   r| j                   j                  |||      S y)NF)r   __exit__)r'   exc_type	exc_value	tracebacks       r)   r   zGhostscriptFollower.__exit__  s)    ##,,Xy)LLr+   c                   | j                   sy | j                  s| j                  j                  |j	                               }|r]t        |j                  d            | _        | j                  | j                  dd      | _        | j                  j                          y y | j                  j                  |j	                               r| j                  j                          y y )Nr-   zPDF/A conversionpage)totaldescunit)r   r   
re_processrQ   stripry   groupr&   r   re_pageupdate)r'   linems      r)   __call__zGhostscriptFollower.__call__  s    %%%%djjl3A _
#'#9#9**+=F $: $    **,  ||!!$**,/  '') 0r+   N)r6   r7   r8   r9   rK   compiler   r   r*   r   r   r   r:   r+   r)   r   r      s:    RBCJbjj'G 

*r+   r   z1.52)jpeg_qualityjpeg_maxdpipdf_version	pdfa_partr   rZ   c          
     R   t                g }
|dk(  rg d}
n|dk(  rg d}
nddg}
t               }|t        d      k(  r|
j                  d       t        j
                  d	k(  rd
}	||nd}g }|ddddddd| d| d| g	}t        ddddt        |       ddd| g|	rdgng z   |
z   |z   d| dd| d d!t        |      d"gz   }|j                  d# | D               	 t        |      5 }t        |t        d$d$d%d&|'      }d d d        j                  }t        |      r+|j                  d(      D ]  }t         j#                  |        t%        |      rt'        |      y # 1 sw Y   bxY w# t(        $ r0}t         j#                  |j                         t+        d)      |d }~ww xY w)*Njpeg)-dAutoFilterColorImages=falsez-dColorImageFilter=/DCTEncode-dAutoFilterGrayImages=falsez-dGrayImageFilter=/DCTEncodelossless)z-dPassThroughJPEGImages=truer   z-dColorImageFilter=/FlateEncoder   z-dGrayImageFilter=/FlateEncodez-dAutoFilterColorImages=truez-dAutoFilterGrayImages=truez9.56.0z-dNEWPDF=falser   F_   z-dDownsampleColorImages=truez#-dColorImageDownsampleThreshold=1.0z-dDownsampleGrayImages=truez"-dGrayImageDownsampleThreshold=1.0z-dDownsampleMonoImages=truez"-dMonoImageDownsampleThreshold=1.0z-dColorImageResolution=z-dGrayImageResolution=z-dMonoImageResolution=r`   ra   r_   z-dCompatibilityLevel=z-sDEVICE=pdfwriterf   z-sColorConversionStrategy=rc   z-dJPEGQ=z-dSubsetFonts=falsez-dPDFA=z-dPDFACompatibilityPolicy=1rd   re   c              3  2   K   | ]  }t        |        y wr>   r   )r@   ss     r)   rB   z generate_pdfa.<locals>.<genexpr>  s     06!90s   Tzutf-8rj   )rh   ri   textencodingrk   callbackz****z"Ghostscript PDF/A rendering failed)rF   versionr
   r1   osnameru   strr   extendr   r   r   rh   rR   splitr/   rH   rU   r   r	   r   )	pdf_pagesr   compressioncolor_conversion_strategyr   r   r   r   r   rZ   compression_args
gs_versioneffective_jpeg_qualitydownsample_argsr   pbarr   rh   partr   s                       r)   generate_pdfar   !  sE    !" f
 

	"

 +)

 JWX&& 	 01	ww$ .:-E\2 "$O*1)0)0%k]3$[M2$[M2

" #C$4#56%()B(CD		
 $1b
	: 	 	 -./!i[!);
	
 0 NN0i00 H !23 		t"  A		   f%
 V,  		$ '
 --FGG (5		 		  Q 			!((#$HIqP	Qs0   E- )E! E- !E*&E- -	F&6+F!!F&)returnNone)r   rN   )r   os.PathLiker   r   r   r   r   r   rV   ry   rW   zResolution | NonerX   
int | NonerY   rN   rZ   rN   r[   rN   )r   r   r   r   r   r   r   r   r   r   r   r   r   r   rZ   rN   )2r9   
__future__r   r#   r   rK   collectionsr   r   pathlibr   
subprocessr   r	   packaging.versionr
   PILr   r   ocrmypdf._exec._prober   ocrmypdf.exceptionsr   r   r   ocrmypdf.helpersr   ocrmypdf.pluginspecr   ocrmypdf.subprocessr   r   	frozensetCOLOR_CONVERSION_STRATEGIESr   ru   	getLoggerr6   r/   Filterr   PROBEr   	availablerF   rR   rU   r   r   r   r:   r+   r)   <module>r      s   + "  	 	    / % - + 
 ( 7 7'  77d?Z g!gnn 8 	"
--OO	,
( "&L.L.L. +	L.
 L. L.  L. L. L. L. L.^$* $*Z  $"NHNH 	NH
  #NH NH NH NH NH NHr+   