a
    �˜ëjP  ã                   @   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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 d dl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ƒZ0G dd„ de0ƒZ1G dd„ de1ƒZ2G dd„ de0ƒZ3d d!„ Z4d"d#„ Z5d$d%„ Z6d&d'„ Z7d(d)„ Z8dS )*é    N)ÚPath)Ú	find_spec)Úsetup_logging)Ú	add_inputÚ	get_inputÚ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   úS/mnt/bigstor/www/usecases/.venv/lib/python3.9/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><   ó    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   r+   zThe saver engine to use )Údestr   r-   z--scaleé   zªDefine 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.)r5   r   Úchoicesr-   ú--fill-colorr-   z˜Color 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.)r8   r-   z--cropr   r   )r   r   r   r   z/Amount to crop from (left, bottom, right, top).)r   r   r   r5   r-   z--draw-annotsz1Whether annotations may be shown (default: true).)Úactionr5   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   r5   r8   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.)r8   r5   r-   r   z--grayscalez0Whether to render in grayscale mode (no colors).z--byteorderÚrev_byteorderc                 S   s   dddœ|   ¡  S )NFT)ZbgrZrgbr/   )Úvr   r   r   r*   š   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).)r3   r<   r-   z--maybe-alphazÛWhether 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ú?z°Render 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.))r8   r5   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 schemezÚOptions 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.)r9   )rN   )rO   )rP   )rQ   )r   Úadd_argumentÚstrr0   Ú	PILEngineÚNumpyPILEngineÚNumpyCV2EngineÚtupleÚkeysÚfloatÚintÚ	ColorOptsr   Úadd_argument_groupÚBitmapMakersÚmathÚinfÚosÚ	cpu_count)ÚparserÚbitmapÚparallelÚcolor_schemeZpostprocr   r2   r   Úattach8   sh   üþý
üüû ÿþýýüüüúýþûýüüýþûüûûýþýýþýýrf   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_argsrh   r   r   r   Ú__init__ô   s    zSavingEngine.__init__c                 C   s0   | j }|j|j› |d d|j› d�›d|› � S )Nr4   Ú0Údr   )r   Ú
output_dirÚprefixÚn_digits)ri   Ú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 r4   z as )r   Úmaybe_alphar   r   ZFPDFPage_HasTransparencyÚloggerÚinfors   Ú_saving_hookrh   Úname)ri   rq   rc   Úpagerr   Úout_pathr   r   r   Ú__call__ü   s    
zSavingEngine.__call__N)Ú__name__Ú
__module__Ú__qualname__rk   rs   r}   r   r   r   r   rg   ò   s   rg   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   )rh   rw   ÚdebugÚ	PIL.Imager	   ZPIL.ImageOpsZPIL.ImageFilterZPIL.ImageDraw©ri   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)ri   r|   rc   r{   rh   ÚposconvZ	pil_imager   r   r   ry     s    

zPILEngine._saving_hookc                 C   s*   t  | ||¡\}}}d| }t  |||¡S )Nr4   )ÚcolorsysZ
rgb_to_hlsZ
hls_to_rgb)ÚrÚgÚbÚhÚlÚsr   r   r   Ú_invert_px_lightness  s    zPILEngine._invert_px_lightnessé   r4   )Ú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¬   |}|r¨|j dkr tj |¡}n| |  ¡ ¡}|r¨t|jtj	gdd�ƒ\}}|r¨tj
 d|j¡}	tj |	¡}
|D ](}‡ fdd„| ¡ D ƒ}|
j|dd� qp|j||	d� |S )	NÚLr4   ©Z	max_depthÚ1c                    s   g | ]\}}ˆ   ||¡‘qS r   ©Z	to_bitmap©Ú.0ÚxÚy©rŠ   r   r   Ú
<listcomp>9  r+   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_imager{   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‡   ry   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   )rw   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  s    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 )NzNumPy+cv2 engine importsr   r¯   )rw   r‚   r
   rh   Ú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   )ri   r|   rc   r{   rh   Znp_arrayr   r   r   ry   U  s    zNumpyCV2Engine._saving_hookc                    s(  |}|�r$|j tjkr| }n`|jr0tjtjfn
tjtjf\}}t 	||¡}t 
|¡\}	}
}|
 }
t |	|
|g¡}t 	||¡}|�r$|j tjks˜J dƒ‚| |¡‰ t|jtjgdd�ƒ\}}|�r$t |j|jdftj¡}|D ]4}t ‡ fdd„| ¡ D ƒtj¡}t ||gd¡ qÞtj|||d�}|S )Nz=Not sure how to paste with mask on {RGB,BGR}X image using cv2r4   rš   c                    s   g | ]\}}ˆ   ||¡‘qS r   rœ   r�   r¡   r   r   r¢   n  r+   z.NumpyCV2Engine.postprocess.<locals>.<listcomp>)r¤   Údst)r   r   ZFPDFBitmap_GrayrD   r
   ZCOLOR_RGB2HLSZCOLOR_HLS2RGBZCOLOR_BGR2HLSZCOLOR_HLS2BGRZcvtColorÚsplitÚmerger   r†   r   r¨   r©   r¿   Úzerosr   r   Zuint8Úarrayr­   Úint32ZfillPolyZcopyTo)r—   r®   rc   r{   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…   ry   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)rw   rx   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   s0   ||  }|j f i |¤Ž}|| ||ƒ | ¡  d S r&   )ÚrenderÚclose)rq   rÎ   r   rÍ   r{   rc   r   r   r   Ú_render_job‚  s    rÒ   c                 C   s   t | gt¢R Ž  d S r&   )rÒ   rÉ   )rq   r   r   r   Ú_render_parallel_job‰  s    rÓ   c                   C   s   d S r&   r   r   r   r   r   Ú_do_nothing�  r+   rÔ   c                    s   ˆ j  ¡ stdˆ j ›�ƒ‚tˆ ˆ jd�}t|ƒ‰t‡fdd„ˆ jD ƒƒsPtdƒ‚tˆ jƒttˆ jƒƒkrptdƒ‚ˆ j	d u rŠˆ j
j› d�ˆ _	ˆ jd u r¤ˆ jrždnd	ˆ _ˆ jd u rÆˆ jd
 dkrÀdndˆ _ˆ jd u rÖdˆ _ˆ jd u �rtsòtsòJ dƒ‚t�r
t�rˆ jdk�rtˆ _ntˆ _ˆ jd u �r2tˆ jtƒˆ _ˆ jd u �rXtˆ jtƒ�oTˆ jdkˆ _tƒ }ˆ j�rv|jf i t¤Ž |jf i ‡ fdd„tD ƒ¤Ž |�rªtjf i |¤Žnd }tˆ jˆ jˆ j ˆ j!ˆ jˆ j"ˆ j#ˆ jˆ j$ˆ jˆ jˆ j%t&ˆ j' |ˆ j(d�}ˆ j)D ]}d|d|› �< �qút*j+ˆ j ˆ j	tt,ˆƒƒˆ jˆ j%d�}tˆ j-ˆ j.d�}ˆ j-�rbˆ j"dk�rbt/ 0d¡ t1ˆ ƒ 2¡ }|d= |d= |d �rŒd|d< t/ 3|› ¡ |�rªt/ 3|› ¡ ˆ  ||¡}	tˆ jƒˆ jk�rút/ 4d¡ |	 5¡  ˆ jD ]}
t6|
|||	ƒ �qà�nt/ 4d¡ t7 8ˆ j9¡}t|j:dft;j<t=j>|d �d!fd"�}|ˆ j? \}}ˆ j@�rNˆ j@}ˆ j9d#k�rntAtA }}|	 5¡  ntB|	j5 }}ttC|||jDˆ jEˆ j||	fd$�}tFˆ jGtˆ jƒƒ}||fi |¤Ž�.}tH||ƒ}|tIˆ jƒD ]}�qÔW d   ƒ n1 �sò0    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ž   rq   )Úpdf_lenr   r   Ú	<genexpr>™  r+   zmain.<locals>.<genexpr>z*Out-of-bounds page indices are prohibited.z&Duplicate page indices are prohibited.Ú_)r   r   r   r"   r$   é   r"   rt   ru   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>º  r+   zmain.<locals>.<dictcomp>)ÚscaleÚrotationÚcropÚ	grayscaleÚ
fill_colorÚoptimize_modeÚdraw_annotsZmay_draw_formsÚforce_halftonerD   rF   rv   Úbitmap_makerre   Úfill_to_strokeTZ	no_smooth)rn   ro   rp   r   rv   )r�   r¯   r:   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initargs)JÚoutputÚis_dirÚ
ValueErrorr   Z
draw_formsÚlenÚallr%   Úsetro   rÌ   Ústemrà   Zsample_themer   Zlinearr.   Úhave_pilÚhave_cv2rV   rT   rD   Ú
issubclassrF   ÚdictÚupdateÚSampleThemeÚColorSchemeFieldsr   ZPdfColorSchemerÜ   rÝ   rÞ   rß   rá   râ   rã   rv   r]   rä   rå   Zno_antialiasÚtypesÚSimpleNamespacerS   r�   r¯   rw   ÚwarningÚvarsÚcopyr‚   rx   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_kwargsre   r   r   rj   rh   Z
print_argsrÍ   rq   ÚctxZpool_backendsZ	pool_ctorZmap_attrrÊ   rË   Úpool_kwargsZn_procsÚpoolZmap_funcr×   r   )r   rÕ   r   Úmain‘  sÂ    




ñ

ûþ




þ

þ
r  )9r`   r^   r÷   Úloggingr‹   r·   Úpathlibr   ÚmultiprocessingrL   Úconcurrent.futuresZfuturesrM   Úimportlib.utilr   Z	pypdfium2r   Zpypdfium2.internalZinternalr   Zpypdfium2.rawÚrawr   Zpypdfium2_cli._setupr   Zpypdfium2_cli._parsersr   r   r   Zpypdfium2_cfg.stlr   rð   rñ   Ú	getLoggerr~   rw   r   ró   r   Z
new_nativeZnew_foreignrü   r]   rö   rZ   r[   rõ   rf   rg   rT   rU   rV   rÏ   rÒ   rÓ   rÔ   r  r   r   r   r   Ú<module>   sX   
	üû ;7(