o
    E+ iO                     @   s  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 e!Z"dd Z#e$ej%j&ej%j'ej(ej%j'd	d
e#dZ)dZ*e$dde+dZ,e$dddddZ-dd Z.G dd dZ/G dd de/Z0G dd de0Z1G dd de/Z2dd Z3d d! Z4d"d# Z5d$d% Z6d&d' Z7dS )(    N)Path)	find_spec)	add_input	get_inputsetup_loggingiterator_hasvalueBooleanOptionalActionPILcv2c                 O   sT   |t jkrd}n|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_BGRxZFPDFBitmap_BGRARuntimeErrorpdfium_iZBitmapTypeToStrpdfium	PdfBitmapZnew_foreign_simple)widthheightformatargskwargsZ	use_alpha r   a/home/app/PaddleOCR-VL-test/.venv_paddleocr/lib/python3.10/site-packages/pypdfium2/_cli/render.py_bitmap_wrapper_foreign_simple   s   

r   T)Zforce_packed)nativeZforeignZforeign_packedZforeign_simple)Z	path_fillZpath_strokeZ	text_fillZtext_strokeC   )metavarnargstype)   d   r      )r      r"   r"   r"   r"   r"   r"   )r#   r"   r   r"   c                    s  t | dd | jdddd ddd | jd	d
d | jddtjdd tttd | jdd fdddt   d | jddt	dd | jddt
ddd | j	dpd d!it | jd"d#d$d% | jd&d'd(t	d)d*d+ | jd,tdd-d. | jd/tdd0d. | jd1d2g d3tjd4d5 | jd6d7d8d9 | jd:d;d<}|jd=t d>d?tjd@ |jdAd7dBd9 |jdCdDdEd dFd |jdGdHtdIdJ |jdKtdLd9 | jdMdNd<}|jdOdPt
tjdQdR |jdSt t
dTd |jdUdVdWtjdXdY |jdZd[d\tjd]dY |jd^tjd_d | jd`dad<}|jdbd7dcd9 |jdqi t |jdri t |jdsi t |jdti t |jdhd7did9 | jdjdkd<}|jdld7dmd9 |jdnd7dod9 d S )uNT)pagesz--outputz-oc                 S   s   t |   S N)r   
expanduserresolve)pr   r   r   <lambda><   s    zattach.<locals>.<lambda>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,   )Zpilz	numpy+pilz	numpy+cv2z--engine
engine_clsc                    s    |    S r&   lower)kZengines_mapr   r   r*   M   s    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.)r4   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.)r7   r,   z--cropr   r   )r   r   r   r   z/Amount to crop from (left, bottom, right, top).)r   r   r   r4   r,   z--draw-annotsz1Whether annotations may be shown (default: true).)actionr4   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   r4   r7   r   r,   z--force-halftone
store_truez)Always use halftone for image stretching.)r;   r,   zBitmap optionsz&Bitmap config, including pixel format.)titledescriptionz--bitmap-makerr   zThe bitmap maker to use.)r7   r4   r,   r   z--grayscalez0Whether to render in grayscale mode (no colors).z--byteorderrev_byteorderc                 S   s   ddd|    S )NFT)Zbgrrgbr.   )vr   r   r   r*      s    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).)r2   r;   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.Z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)spawnZ
forkserverforkrI   zQThe process start method to use. ('fork' is discouraged due to stability issues.))r7   r4   r   r,   z--parallel-libmpftrL   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.)r8   )rN   )rO   )rP   )rQ   )r   add_argumentstrr/   	PILEngineNumpyPILEngineNumpyCV2Enginetuplekeysfloatint	ColorOptsr   add_argument_groupBitmapMakersmathinfos	cpu_count)parserbitmapZparallelcolor_schemeZpostprocr   r1   r   attach8   sh  

re   c                   @   s$   e Zd Zdd Zdd Zdd ZdS )SavingEnginec                 C   s   || _ || _d S r&   )r   postproc_kwargs)self
saver_argsrg   r   r   r   __init__   s   
zSavingEngine.__init__c                 C   s0   | j }|j|j |d d|j dd|  S )Nr3   0dr   )r   
output_dirprefixn_digits)rh   iextr   r   r   r   	_get_path   s   *zSavingEngine._get_pathc                 C   st   | j jr| j jdv rt|rtd d}n| j j}| ||}| |||| j	 td|d  d|j
  d S )N)jpgZjpegz8Page has transparency - overriding output format to PNG.pngzWrote page r3   z as )r   maybe_alphar   r   ZFPDFPage_HasTransparencyloggerinforr   _saving_hookrg   name)rh   rp   rc   pagerq   out_pathr   r   r   __call__   s   
 zSavingEngine.__call__N)__name__
__module____qualname__rj   rr   r|   r   r   r   r   rf      s    rf   c                   @   s\   e Zd Zdd ZeejjZdd Z	edd Z
dZeejdd	d
d Zedd ZdS )rT   c                 C   s<   | 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   )rg   rv   debug	PIL.Imager	   ZPIL.ImageOpsZPIL.ImageFilterZPIL.ImageDrawrh   r   r   r   
do_imports
  s   

zPILEngine.do_importsc                 C   s8   | |}| |}| j|||fi |}|| d S r&   )get_posconv_to_pil_hookpostprocesssave)rh   r{   rc   rz   rg   posconvZ	pil_imager   r   r   rx     s   

zPILEngine._saving_hookc                 C   s*   t | ||\}}}d| }t |||S )Nr3   )colorsys
rgb_to_hls
hls_to_rgb)rgbhlsr   r   r   _invert_px_lightness  s   zPILEngine._invert_px_lightness   r3   )maxsizec                 C   s   t jj| j| jS r&   )r	   ZImageFilterZ
Color3DLUTgenerateLINV_LUT_SIZEr   )clsr   r   r   _get_linv_lut$  s   zPILEngine._get_linv_lutc                    s   |}|rT|j dkrtj|}n||  }|rTt|jtj	gdd\}}|rTtj
d|j}	tj|	}
|D ]} fdd| D }|
j|dd q8|j||	d |S )	NLr3   	max_depth1c                       g | ]
\}}  ||qS r   Z	to_bitmap.0xyr   r   r   
<listcomp>9      z)PILEngine.postprocess.<locals>.<listcomp>)fill)mask)moder	   ZImageOpsinvertfilterr   r   get_objectsr   FPDF_PAGEOBJ_IMAGEImagenewsizeZ	ImageDrawZDrawget_quad_pointsZpolygonZpaste)r   	src_imagerz   r   r   exclude_images	dst_imagehave_images
obj_walkerr   Zdrawobjqpointsr   r   r   r   )  s   
zPILEngine.postprocessN)r}   r~   r   r   staticmethodr   r   Zto_pilr   rx   r   r   classmethod	functools	lru_cacher   r   r   r   r   r   rT     s    


rT   c                       s(   e Zd Z fddZedd Z  ZS )rU   c                    s    t d dd lat   d S )NzNumPy+PIL engine importsr   )rv   r   r   r	   superr   r   	__class__r   r   r   A  s   
zNumpyPILEngine.do_importsc                 C   s   t j|  | jS r&   )r	   r   Z	fromarrayto_numpyr   )rc   r   r   r   r   G     zNumpyPILEngine._to_pil_hook)r}   r~   r   r   r   r   __classcell__r   r   r   r   rU   ?  s    rU   c                   @   s(   e Zd Zdd Zdd Zedd ZdS )rV   c                 C   s,   t d dd la| jd rdd lad S d S )NzNumPy+cv2 engine importsr   r   )rv   r   r
   rg   numpynpr   r   r   r   r   N  s
   

zNumpyCV2Engine.do_importsc                 C   s2   |  }| j|||fi |}tt|| d S r&   )r   r   r
   ZimwriterS   )rh   r{   rc   rz   rg   Znp_arrayr   r   r   rx   U  s   zNumpyCV2Engine._saving_hookc                    s"  |}|r|j tjkr| }n0|jrtjtjfntjtjf\}}t	||}t
|\}	}
}|
 }
t|	|
|g}t	||}|r|j tjksJJ d|| t|jtjgdd\}}|rt|j|jdftj}|D ]}t fdd| D tj}t||gd qltj|||d}|S )Nz=Not sure how to paste with mask on {RGB,BGR}X image using cv2r3   r   c                    r   r   r   r   r   r   r   r   n  r   z.NumpyCV2Engine.postprocess.<locals>.<listcomp>)r   dst)r   r   ZFPDFBitmap_GrayrC   r
   ZCOLOR_RGB2HLSZCOLOR_HLS2RGBZCOLOR_BGR2HLSZCOLOR_HLS2BGRZcvtColorsplitmerger   r   r   r   r   r   Zzerosr   r   Zuint8arrayr   Zint32ZfillPolyZcopyTo)r   r   rc   rz   r   r   r   Z
convert_toZconvert_fromr   r   r   r   r   r   r   r   r   r   r   r   Z  s*   "
 zNumpyCV2Engine.postprocessN)r}   r~   r   r   rx   r   r   r   r   r   r   rV   L  s
    rV   c                 C   sJ   |   t dt   |  tj||dd}|r|  |||fad S )NzInitializing data for process T)passwordZ	autoclose)rv   rw   r`   getpidr   ZPdfDocument
init_formsProcObjs)logging_initengine_initinputr   Zmay_init_formsr   enginepdfr   r   r   _render_parallel_initt  s   r   c                 C   s(   ||  }|j di |}|| || d S )Nr   )render)rp   r   r   r   rz   rc   r   r   r   _render_job  s   r   c                 C   s   t | gtR   d S r&   )r   r   )rp   r   r   r   _render_parallel_job  r   r   c                   C   s   d S r&   r   r   r   r   r   _do_nothing  s    r   c                    s   j  std j t  jd}t|tfdd jD s(tdt jtt jkr8td j	d u rE j
j d _	 jd u rR jrOdnd	 _ jd u rc jd
 dkr`dnd _ jd u rkd _ jd u rtsxtsxJ dtrtr jdkrt _nt _ jd u rt jt _ jd u rt jto jdk _t } jr|jd%i t |jd%i  fddtD  |rtjd%i |nd }t j j j  j! j j" j# j j$ j j j%t& j' | j(d} j)D ]	}d|d| < qt*j+ j  j	tt, j j%d}t j- j.d} j-r' j"dkr't/0d t1 2 }|d= |d= |d r<d|d< t/3|  |rKt/3|   ||}	t j jkrst/4d |	5   jD ]
}
t6|
|||	 qfd S t/4d t78 j9}t|j:dft;j<t=j>|d d!fd"}| j? \}} j@r j@} j9d#krtAtA}}|	5  ntB|	j5}}ttC|||jD jE j||	fd$}tF jGt j}||fi |}tH||}|tI jD ]}qW d    d S 1 sw   Y  d S )&Nz*Output path is not an existing directory: )r   c                 3   s(    | ]}d |  ko k n  V  qdS )r   Nr   )r   rp   )pdf_lenr   r   	<genexpr>  s   & zmain.<locals>.<genexpr>z*Out-of-bounds page indices are prohibited.z&Duplicate page indices are prohibited._)r   r   r   r"   r$      r"   rs   rt   r   z?Either pillow or numpy+cv2 must be installed for rendering CLI.c                    s"   i | ]}t  |r|t  |qS r   )getattr)r   f)r   r   r   
<dictcomp>  s   " zmain.<locals>.<dictcomp>)scalerotationcrop	grayscale
fill_coloroptimize_modedraw_annotsZmay_draw_formsforce_halftonerC   rF   ru   bitmap_makerrd   fill_to_strokeTZ	no_smooth)rm   rn   ro   r   ru   )r   r   r9   ztLCD optimization clashes with lightness inversion, as post-processing colors defeats the idea of subpixel rendering.
subcommandr%   r   z<obfuscated>zLinear rendering ...zParallel rendering ...imap)Z
mp_contextmaprK   rJ   )ZinitializerZinitargsr   )Joutputis_dir
ValueErrorr   Z
draw_formslenallr%   setrn   r   stemr   Zsample_themer   Zlinearr-   have_pilhave_cv2rV   rT   rC   
issubclassrF   dictupdateSampleThemeColorSchemeFieldsr   ZPdfColorSchemer   r   r   r   r   r   r   ru   r]   r   r   Zno_antialiastypesSimpleNamespacerS   r   r   rv   warningvarscopyr   rw   r   r   rL   Zget_contextZparallel_strategyZPoolr   partialrM   ProcessPoolExecutorZparallel_libZparallel_mapr   r   r   _inputr   minZ	processesr   r   )r   r   Z	cs_kwargsrd   r   r   ri   rg   Z
print_argsr   rp   ctxZpool_backendsZ	pool_ctorZmap_attrr   r   pool_kwargsZn_procspoolZmap_funcr   r   )r   r   r   main  s   

















$r  )8r`   r^   r   loggingr   r   pathlibr   multiprocessingrL   concurrent.futuresfuturesrM   importlib.utilr   Zpypdfium2._helpersZ_helpersr   Zpypdfium2.internalZinternalr   Zpypdfium2.rawrawr   Zpypdfium2._cli._parsersr   r   r   r   r   r   r   	getLoggerr}   rv   r   r   r   Z
new_nativeZnew_foreignr   r]   r   rZ   r[   r   re   rf   rT   rU   rV   r   r   r   r   r  r   r   r   r   <module>   sV   
	 ;7(