
    .iO                     F   d dl Z d dlZd dlZd dlZd dlZd dlZd dlm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 d dlmZ d dlmZmZmZmZmZ  ed          duZ ed          duZ ej         e!          Z"d Z# e$ej%        j&        ej%        j'         ej(        ej%        j'        d	          e#
          Z)dZ* e$dde+          Z, e$dddd          Z-d Z. G d d          Z/ G d de/          Z0 G d de0          Z1 G d de/          Z2d Z3d Z4d Z5d Z6d  Z7dS )!    N)Path)	find_spec)	add_input	get_inputsetup_loggingiterator_hasvalueBooleanOptionalActionPILcv2c                     |t           j        k    rd}n6|t           j        k    rd}n#t          dt          j        |          d          t          j        j        | ||g|R i |S )NFTz5Cannot create foreign_simple bitmap with bitmap type .)	pdfium_cFPDFBitmap_BGRxFPDFBitmap_BGRARuntimeErrorpdfium_iBitmapTypeToStrpdfium	PdfBitmapnew_foreign_simple)widthheightformatargskwargs	use_alphas         Q/var/www/html/analyses/venv/lib/python3.11/site-packages/pypdfium2/_cli/render.py_bitmap_wrapper_foreign_simpler      sy    )))			8+	+	+		vS[SklrSsvvvwww.ufiY$YYYRXYYY    T)force_packed)nativeforeignforeign_packedforeign_simple)	path_fillpath_stroke	text_filltext_strokeC   )metavarnargstype)   d   r      )r      r0   r0   r0   r0   r0   r0   )r1   r0   r   r0   c           
      \   t          | d           |                     ddd dd           |                     dd	
           |                     ddt          j        d           t          t
          t          d|                     ddfddt                                                                |                     ddt          d           |                     ddt          dd            | j        	 dodd it           |                     d!d"d#$           |                     d%d&d't          d(d)*           |                     d+t          dd,-           |                     d.t          dd/-           |                     d0d1g d2t          j        d34           |                     d5d6d78           |                     d9d:;          }|                    d<t                                          d=d>t          j        ?           |                    d@d6dA8           |                    dBdCdD dE           |                    dFdGt          dHI           |                    dJt          dK8           |                     dLdM;          }|                    dNdOt          t          j        dPQ           |                    dRt#          j                    t          dS           |                    dTdUdVt          j        dWX           |                    dYdZd[t          j        d\X           |                    d]t          j        d^           |                     d_d`;          }|                    dad6db8            |j        dpi t            |j        dqi t            |j        dri t            |j        dsi t           |                    dgd6dh8           |                     didj;          }|                    dkd6dl8           |                    dmd6dn8           d S )tNT)pagesz--outputz-oc                 h    t          |                                                                           S N)r   
expanduserresolve)ps    r   <lambda>zattach.<locals>.<lambda><   s$    a++--5577 r   zDOutput directory where the serially numbered images shall be placed.)r-   requiredhelpz--prefixzDCustom prefix for the images. Defaults to the input filename's stem.)r<   z--formatz-fz/The image format to use (default: conditional).)r-   r<   )pilz	numpy+pilz	numpy+cv2z--engine
engine_clsc                 8    |                                           S r6   lower)kengines_maps    r   r:   zattach.<locals>.<lambda>M   s    QWWYY/ r   zThe saver engine to use )destr-   r<   z--scale   zDefine the resolution of the output images. By default, one PDF point (1/72in) is rendered to 1x1 pixel. This factor scales the number of pixels that represent one point.)defaultr-   r<   z
--rotationr   )r   Z      i  z'Rotate pages by 90, 180 or 270 degrees.)rF   r-   choicesr<   --fill-colorr<   zColor the bitmap will be filled with before rendering. Shall be given in RGBA format as a sequence of integers ranging from 0 to 255. Defaults to white.z--optimize-mode)lcdprintz3The rendering optimisation mode. None if not given.)rI   r<   z--cropr)   r*   )r   r   r   r   z/Amount to crop from (left, bottom, right, top).)r+   r,   r-   rF   r<   z--draw-annotsz1Whether annotations may be shown (default: true).)actionrF   r<   z--draw-formsz+Whether forms may be shown (default: true).z--no-antialias+)textimagepathz&Item types that shall not be smoothed.)r,   rF   rI   r-   r<   z--force-halftone
store_truez)Always use halftone for image stretching.)rM   r<   zBitmap optionsz&Bitmap config, including pixel format.)titledescriptionz--bitmap-makerr!   zThe bitmap maker to use.)rI   rF   r<   r-   z--grayscalez0Whether to render in grayscale mode (no colors).z--byteorderrev_byteorderc                 <    ddd|                                           S )NFT)bgrrgbr@   )vs    r   r:   zattach.<locals>.<lambda>   s    t44QWWYY? r   z;Whether to use BGR or RGB byteorder (default: conditional).z--x-channelprefer_bgrxz@Whether to prefer BGRx/RGBx over BGR/RGB (default: conditional).)rD   rM   r<   z--maybe-alphazWhether to use BGRA if page content has transparency. Note, this makes format selection page-dependent. As this behavior can be confusing, it is not currently the default, but recommended for performance in these cases.Parallelizationz.Options for rendering with multiple processes.z--linear?zRender non-parallel if page count is less or equal to the specified value (default: 4). If this flag is given without a value, then render linear regardless of document length.)r,   r-   constr<   z--processeszXThe maximum number of parallel rendering processes. Defaults to the number of CPU cores.z--parallel-strategy)spawn
forkserverforkr^   zQThe process start method to use. ('fork' is discouraged due to stability issues.))rI   rF   r-   r<   z--parallel-libmpftrb   zRThe parallelization module to use (mp = multiprocessing, ft = concurrent.futures).z--parallel-mapzLThe map function to use (backend specific, the default is an iterative map).zFlat color schemezOptions for using pdfium's color scheme renderer. Note that this may flatten different colors into one, so the usability of this is limited. Alternatively, consider post-processing with lightness inversion (see below).z--sample-themezWUse a dark background sample theme as base. Explicit color params override selectively.--path-fill--path-stroke--text-fill--text-strokez--fill-to-strokea  When rendering with custom color scheme, only draw borders around fill areas using the `path_stroke` color, instead of filling with the `path_fill` color. This is actually recommended, since with a single fill color for paths the boundaries of adjacent fill paths are less visible.zPost processingzgOptions to post-process rendered images. Note, this may have a strongly negative impact on performance.z--invert-lightnessa]  Invert lightness using the HLS color space (e.g. white<->black, dark_blue<->light_blue). The intent is to achieve a dark theme for documents with light background, while providing better visual results than classical color inversion or a flat pdfium color scheme. However, note that --optimize-mode lcd is not recommendable when inverting lightness.z--exclude-imagesz7Whether to exclude PDF images from lightness inversion.)rJ   )rd   )re   )rf   )rg   )r   add_argumentstrrA   	PILEngineNumpyPILEngineNumpyCV2Enginetuplekeysfloatint	ColorOptsr	   add_argument_groupBitmapMakersmathinfos	cpu_count)parserbitmapparallelcolor_schemepostprocrC   s        @r   attachr}   8   s   fD!!!!
D77U	     U     Dy@    
 $.~^^K
////E%0@0@0B0B*C*CEE	      |	     #8     F  j   
 "D    
 15@	     &B	     &<	     +y7     :     && > '  F ##%%)y     A    
 ??L	     &Q	     & m     ((!F )  H  B     ,..i	     1yb     yc     y]     ,,# s -  L h    
 L;;;;;L;;;;;L;;;;;L;;;;; k     ((! )  H  o    
 H      r   c                        e Zd Zd Zd Zd ZdS )SavingEnginec                 "    || _         || _        d S r6   )r   postproc_kwargs)self
saver_argsr   s      r   __init__zSavingEngine.__init__   s    	.r   c                 V    | j         }|j        |j         |dz   d|j         dd| z  S )NrE   0dr   )r   
output_dirprefixn_digits)r   iextr   s       r   	_get_pathzSavingEngine._get_path   s?    yDK!N1!Nt}!N!N!N!N!N!N!NNNr   c                 j   | j         j        r?| j         j        dv r1t          j        |          rt
                              d           d}n| j         j        }|                     ||          }|                     |||| j	                   t
                              d|dz    d|j
                    d S )N)jpgjpegz8Page has transparency - overriding output format to PNG.pngzWrote page rE   z as )r   maybe_alphar   r   FPDFPage_HasTransparencyloggerinfor   _saving_hookr   name)r   r   ry   pager   out_paths         r   __call__zSavingEngine.__call__   s    9  	#TY%5%H%HXMnosMtMt%HKKRSSSCC)"C>>!S))(FD$2FGGG:!A#::8=::;;;;;r   N)__name__
__module____qualname__r   r   r    r   r   r   r      sD        / / /O O O	< 	< 	< 	< 	<r   r   c                       e Zd Zd Z eej        j                  Zd Z	ed             Z
dZe ej        d          d                         Zed             Zd	S )
rj   c                 x    | j         d         sd S t                              d           dd ladd ladd ladd lad S )Ninvert_lightnessz&PIL engine imports for post-processingr   )r   r   debug	PIL.Imager
   PIL.ImageOpsPIL.ImageFilterPIL.ImageDrawr   s    r   
do_importszPILEngine.do_imports
  sa    #$67 	F=>>>r   c                     |                     |          }|                     |          } | j        |||fi |}|                    |           d S r6   )get_posconv_to_pil_hookpostprocesssave)r   r   ry   r   r   posconv	pil_images          r   r   zPILEngine._saving_hook  s^    $$T**%%f--	$D$YgQQQQ	x     r   c                 l    t          j        | ||          \  }}}d|z
  }t          j        |||          S )NrE   )colorsys
rgb_to_hls
hls_to_rgb)rgbhlss         r   _invert_px_lightnesszPILEngine._invert_px_lightness  s:    %aA..1aE"1a+++r      rE   )maxsizec                 `    t           j        j                            | j        | j                  S r6   )r
   ImageFilter
Color3DLUTgenerateLINV_LUT_SIZEr   )clss    r   _get_linv_lutzPILEngine._get_linv_lut$  s%     )2233DcF^___r   c                 P   |}|r|j         dk    r t          j                            |          }n'|                    |                                           }|rt          |                    t          j	        gd                    \  }}|rt          j
                            d|j                  }	t          j                            |	          }
|D ]9}fd|                                D             }|
                    |d           :|                    ||	           |S )NLrE   	max_depth1c                 B    g | ]\  }}                     ||          S r   	to_bitmap.0xyr   s      r   
<listcomp>z)PILEngine.postprocess.<locals>.<listcomp>9  s-    "]"]"]tq!7#4#4Q#:#:"]"]"]r   )fill)mask)moder
   ImageOpsinvertfilterr   r   get_objectsr   FPDF_PAGEOBJ_IMAGEImagenewsize	ImageDrawDrawget_quad_pointspolygonpaste)r   	src_imager   r   r   exclude_images	dst_imagehave_images
obj_walkerr   drawobjqpointss      `         r   r   zPILEngine.postprocess)  s&   	 	:~$$L//	::		%,,S->->-@-@AA	 
: +<T=M=MxOjNkwx=M=y=y*{*{'Z :9==in==D=--d33D) 6 6"]"]"]"]sGZGZG\G\"]"]"]W15555OOIDO999r   N)r   r   r   r   staticmethodr   r   to_pilr   r   r   r   classmethod	functools	lru_cacher   r   r   r   r   rj   rj     s            < 0 788L! ! ! , , \,
 MY###` ` $# [`   [  r   rj   c                   4     e Zd Z fdZed             Z xZS )rk   c                     t                               d           dd lat	                                                       d S )NzNumPy+PIL engine importsr   )r   r   r   r
   superr   )r   	__class__s    r   r   zNumpyPILEngine.do_importsA  s>    /000r   c                 p    t           j                            |                                 | j                  S r6   )r
   r   	fromarrayto_numpyr   )ry   s    r   r   zNumpyPILEngine._to_pil_hookG  s&    y""6??#4#4fkBBBr   )r   r   r   r   r   r   __classcell__)r   s   @r   rk   rk   ?  sZ             C C \C C C C Cr   rk   c                   0    e Zd Zd Zd Zed             ZdS )rl   c                 h    t                               d           dd la| j        d         rdd lad S d S )NzNumPy+cv2 engine importsr   r   )r   r   r   r   numpynpr   s    r   r   zNumpyCV2Engine.do_importsN  sK    /000


 01 		 	r   c                     |                                 } | j        |||fi |}t                              t	          |          |           d S r6   )r   r   r   imwriteri   )r   r   ry   r   r   np_arrays         r   r   zNumpyCV2Engine._saving_hookU  sO    ??$$#4#HfdNNoNNCMM8,,,,,r   c                    |}|r|j         t          j        k    r| }n|j        rt          j        t          j        fnt          j        t          j        f\  }}t          	                    ||          }t          
                    |          \  }	}
}|
 }
t                              |	|
|g          }t          	                    ||          }|r|j         t          j        k    s
J d            |                    |          t          |                    t          j        gd                    \  }}|rt"                              |j        |j        dft"          j                  }|D ]b}t"                              fd|                                D             t"          j                  }t                              ||gd           ct                              |||          }|S )Nz=Not sure how to paste with mask on {RGB,BGR}X image using cv2rE   r   c                 B    g | ]\  }}                     ||          S r   r   r   s      r   r   z.NumpyCV2Engine.postprocess.<locals>.<listcomp>n  s-    +f+f+f1G,=,=a,C,C+f+f+fr   )r   dst)r   r   FPDFBitmap_GrayrU   r   COLOR_RGB2HLSCOLOR_HLS2RGBCOLOR_BGR2HLSCOLOR_HLS2BGRcvtColorsplitmerger   r   r   r   r   r   zerosr   r   uint8arrayr   int32fillPolycopyTo)r   r   ry   r   r   r   r   
convert_toconvert_fromr   r   r   r   r   r   r   r   r   s                    @r   r   zNumpyCV2Engine.postprocessZ  s   	 	P} 888&J		U[Ui  ,VC,=s?P+Q+Qps  qB  DG  DU  pV(
LLLJ??	))I..1aBIIq!Qi00	LLLAA	 	P}(@@@@  CB@@@ ,,T22*;T=M=MxOjNkwx=M=y=y*{*{'Z P88V]FL!$DbhOOD) 9 9"$((+f+f+f+fPSPcPcPePe+f+f+fhjhp"q"qTG9a8888 #

94Y
 O OIr   N)r   r   r   r   r   r   r   r   r   r   rl   rl   L  sM          - - -
   [  r   rl   c                      |              t                               dt          j                                 |             t	          j        ||d          }|r|                                 |||fad S )NzInitializing data for process T)password	autoclose)r   r   rv   getpidr   PdfDocument
init_formsProcObjs)logging_initengine_initinputr  may_init_formsr   enginepdfs           r   _render_parallel_initr  t  sz    LNNN
KK>>>???KMMM

UX
F
F
FC  VV$HHHr   c                 J    ||          } |j         di |} || ||           d S )Nr   )render)r   r  r   r  r   ry   s         r   _render_jobr     s<    q6DT[""6""F
F1fdr   c                 *    t          | gt          R   d S r6   )r   r  )r   s    r   _render_parallel_jobr"    s    Hr   c                      d S r6   r   r   r   r   _do_nothingr$    s      r   c                       j                                         st          d j                   t            j                  }t          |          t          fd j        D                       st          d          t           j                  t          t           j                            k    rt          d           j	         j
        j         d _	         j         j        rdnd _         j         j        d	         d
k    rdnd _         j        d _         j        Jt"          st$          s
J d            t"          rt$          r j        dk    rt&           _        nt(           _         j        t-           j        t(                     _         j        *t-           j        t(                    o
 j        dk     _        t1                      } j        r |j        d#i t4            |j        d#i  fdt6          D              |rt9          j        d#i |nd }t1           j         j         j          j!         j         j"         j#         j         j$         j         j         j%        tL           j'                 | j(                  } j)        D ]
}d|d| <   tU          j+         j          j	        t          tY                               j         j%                  }t1           j-         j.                  } j-        r% j"        dk    rt^          0                    d           tc                     2                                }|d= |d= |d         rd|d<   t^          3                    |            |rt^          3                    |                                 ||          }	t           j                   j        k    rLt^          4                    d           |	5                                  j        D ]}
tm          |
|||	           d S t^          4                    d           to          j8         j9                  }t1          |j:        dftw          j<        tz          j>        |          df           }| j?                 \  }} j@        r j@        } j9        d!k    r#t          t          }}|	5                                 nt          |	j5        }}t1          t          |||jD         jE         j        ||	f"          }t           jG        t           j                            } ||fi |5 }t          ||          } |t           j                  D ]}	 d d d            d S # 1 swxY w Y   d S )$Nz*Output path is not an existing directory: )r  c              3   8   K   | ]}d |cxk    ok     nc V  dS )r   Nr   )r   r   pdf_lens     r   	<genexpr>zmain.<locals>.<genexpr>  s?      44AqA444444r   z*Out-of-bounds page indices are prohibited.z&Duplicate page indices are prohibited._)r   r   r   r0   r2      r0   r   r   r*   z?Either pillow or numpy+cv2 must be installed for rendering CLI.c                 R    i | ]#}t          |          |t          |          $S r   )getattr)r   fr   s     r   
<dictcomp>zmain.<locals>.<dictcomp>  s6    [[['RVXYJZJZ[74++[[[r   )scalerotationcrop	grayscale
fill_coloroptimize_modedraw_annotsmay_draw_formsforce_halftonerU   rZ   r   bitmap_makerr{   fill_to_strokeT	no_smooth)r   r   r   r   r   )r   r   rK   ztLCD optimization clashes with lightness inversion, as post-processing colors defeats the idea of subpixel rendering.
subcommandr4   r  z<obfuscated>zLinear rendering ...zParallel rendering ...imap)
mp_contextmapra   r`   )initializerinitargsr   )Joutputis_dir
ValueErrorr   
draw_formslenallr4   setr   r  stemr3  sample_themer   linearr>   have_pilhave_cv2rl   rj   rU   
issubclassrZ   dictupdateSampleThemeColorSchemeFieldsr   PdfColorSchemer/  r0  r1  r2  r4  r5  r7  r   rs   r8  r9  no_antialiastypesSimpleNamespaceri   r   r   r   warningvarscopyr   r   r   r   rb   get_contextparallel_strategyPoolr   partialrc   ProcessPoolExecutorparallel_libparallel_mapr$  r   r  _inputr  min	processesr,  r"  )r   r  	cs_kwargsr{   r   r-   r   r   
print_argsr  r   ctxpool_backends	pool_ctormap_attrr  r  pool_kwargsn_procspoolmap_funcr)  r'  s   `                     @r   mainrm    s   ; WUdkUUVVV
DT_
5
5
5C#hhG444444444 GEFFF
4:#c$*oo....ABBB{+++,0,=W..CW{#q1S88eee{ f8ff%ffff 	(h 	(4;%+?+?,DOO'DO !'CC%doyAAZdkUZFZI (	'';'''I\\[[[[5F[[[\\\9BL6(559555L
=yN_*&,*&&#D$56#,  F" ! * *%)!4!!""&[s7||$$&  J 0,  O  O!3u!<!<  N  	O  	O  	Od""J< *W"5* 0!/
:
LLJ!!! (&'''__Z99F
4:$+%%*+++ 	0 	0A3////	0 	0
 	,---nT344(F##B$:sKKKUS
 
 
 ,D,=>	8 	)(H!V++(3[+L(5v7H+L/$k3:t}do_egmn
 
 

 dnc$*oo66Yw..+.. 	$tX..HX2DJ??  	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s   *VV
V)8rv   rt   rT  loggingr   r   pathlibr   multiprocessingrb   concurrent.futuresfuturesrc   importlib.utilr   pypdfium2._helpers_helpersr   pypdfium2.internalinternalr   pypdfium2.rawrawr   pypdfium2._cli._parsersr   r   r   r   r	   rK  rL  	getLoggerr   r   r   rN  r   
new_nativenew_foreignr\  rs   rQ  rp   rq   rP  r}   r   rj   rk   rl   r  r   r"  r$  rm  r   r   r   <module>r~     s   
			                         $ $ $ $ $ $ # # # # # # % % % % % %                          9U4'9U4'		8	$	$Z Z Z t(*&Y&v'7'CRVWWW3	   M DAC000	d&&&&  w w wt< < < < < < < <,4 4 4 4 4 4 4 4n
C 
C 
C 
C 
Ci 
C 
C 
C% % % % %l % % %P% % %       { { { { {r   