
    9j                    .   d Z ddlmZ ddlmZ ddlmZmZmZm	Z	m
Z
mZm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 ddl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%Z%ddl&Z&ddlZddl'Z'erddl(m)Z)  G d de*      Z+y# e#$ r	 ddl$m"Z" Y 1w xY w)z/
Created : 2015-03-12

@author: Eric Lapouyade
    )annotations)PathLike)TYPE_CHECKINGAnyOptionalIOUnionDictSetN)etree)Document)	parse_xml)XmlPart)RELATIONSHIP_TYPE)EnvironmentTemplatemeta)TemplateError)escape   Subdocc                  b   e Zd ZdZdZdZd+dZd,d-dZd Zd Z	d.dZ
d	 Zd
 Zd Zd Zd/dZ	 d/	 	 	 	 	 d0dZ	 d/	 	 	 	 	 d0dZd Zd/dZd Zd Zd Zd Zd/dZd Z	 	 d1	 	 	 	 	 	 	 d2dZd Zd Zd/d3dZed        Zd Z d Z!d  Z"d! Z#d" Z$d# Z%d$ Z&d% Z'd& Z(d' Z)d( Z*d4d)Z+	 	 d5	 	 	 	 	 d6d*Z,y)7DocxTemplatez;Class for managing docx files as they were jinja2 templateszJhttp://schemas.openxmlformats.org/officeDocument/2006/relationships/headerzJhttp://schemas.openxmlformats.org/officeDocument/2006/relationships/footerc                j    || _         | j                          d | _        d| _        d| _        d| _        y NF)template_filereset_replacementsdocxis_renderedis_savedallow_missing_pics)selfr   s     \/var/www/html/eeg-assistent/abrechnung/venv/lib/python3.12/site-packages/docxtpl/template.py__init__zDocxTemplate.__init__.   s4    *!	 "'    c                ~    | j                   r| j                  r%|r"t        | j                        | _         d| _        y y y r   )r   r    r   r   )r#   reloads     r$   	init_docxzDocxTemplate.init_docx6   s5    yyT--& !3!34DI$D 39-r&   c                \    | j                          i | _        d | _        d| _        d| _        y )Ni  F)r)   pic_mapcurrent_rendering_partdocx_ids_indexr!   r#   s    r$   render_initzDocxTemplate.render_init;   s*    &*#"r&   c                .    t        | j                  |      S N)getattrr   )r#   names     r$   __getattr__zDocxTemplate.__getattr__B   s    tyy$''r&   c                2    t        j                  |dd      S )NunicodeF)encodingpretty_print)r   tostring)r#   xmlr7   s      r$   xml_to_stringzDocxTemplate.xml_to_stringE   s     ~~cIEJJr&   c                :    | j                          | j                  S r1   )r)   r   r.   s    r$   get_docxzDocxTemplate.get_docxJ   s    yyr&   c                `    | j                  | j                  j                  j                        S r1   )r;   r   _elementbodyr.   s    r$   get_xmlzDocxTemplate.get_xmlN   s#    !!$))"4"4"9"9::r&   c                    t        |d      5 }|j                  | j                                d d d        y # 1 sw Y   y xY w)Nw)openwriterA   )r#   filenamefhs      r$   	write_xmlzDocxTemplate.write_xmlQ   s5    (C  	%BHHT\\^$	% 	% 	%s    6?c                8   t        j                  dd|t         j                        }d }t        j                  d||t         j                        }d }t        j                  d||t         j                        }d }t        j                  d	||t         j                        }t        j                  d
d|t         j                        }t        j                  dd|t         j                        }t        j                  dd|t         j                        }t        j                  dd|t         j                        }dD ]0  }dd|iz  }t        j                  |d|t         j                        }2 dD ]0  }dd|iz  }t        j                  |d|t         j                        }2 d }t        j                  d||t         j                        }d }t        j                  d||t         j                        }d }	t        j                  d|	|      }|S )zMake a lots of cleaning to have a raw xml understandable by jinja2 :
        strip all unnecessary xml tags, manage table cell background color and colspan,
        unescape html entities, etc...z8(?<={)(<[^>]*>)+(?=[\{%\#])|(?<=[%\}\#])(<[^>]*>)+(?=\}) flagsc                n    t        j                  dd| j                  d      t         j                        S )Nz</w:t>.*?(<w:t>|<w:t [^>]*>)rJ   r   rK   resubgroupDOTALLms    r$   	striptagsz)DocxTemplate.patch_xml.<locals>.striptagse   s(    66.AGGAJbii r&   z,{%(?:(?!%}).)*|{#(?:(?!#}).)*|{{(?:(?!}}).)*c                   | j                  d      | j                  d      z   }t        j                  dd|t        j                        }t        j                  dd|d      }t        j                  dd	| j                  d
      z  |      S )Nr      .<w:r[ >](?:(?!<w:r[ >]).)*<w:t></w:t>.*?</w:r>rJ   rK   z<w:gridSpan[^/]*/>count(<w:tcPr[^>]*>)z\1<w:gridSpan w:val="{{%s}}"/>   rQ   rO   rP   rR   rT   cell_xmls     r$   colspanz'DocxTemplate.patch_xml.<locals>.colspanr   sx    wwqzAGGAJ.HvvAii	H vv3RKH66"1AGGAJ> r&   zE(<w:tc[ >](?:(?!<w:tc[ >]).)*){%\s*colspan\s+([^%]*)\s*%}(.*?</w:tc>)c                   | j                  d      | j                  d      z   }t        j                  dd|t        j                        }t        j                  dd|d      }t        j                  dd	| j                  d
      z  |      S )Nr   rW   rX   rJ   rK   z<w:shd[^/]*/>rY   r[   z7\1<w:shd w:val="clear" w:color="auto" w:fill="{{%s}}"/>r\   r]   r^   s     r$   cellbgz&DocxTemplate.patch_xml.<locals>.cellbg   sy    wwqzAGGAJ.HvvAii	H vv.HAFH66"JQWWUVZW r&   zD(<w:tc[ >](?:(?!<w:tc[ >]).)*){%\s*cellbg\s+([^%]*)\s*%}(.*?</w:tc>)z'<w:t>((?:(?!<w:t>).)*)({{.*?}}|{%.*?%})z<w:t xml:space="preserve">\1\2z({{r\s.*?}}|{%r\s.*?%})zX</w:t></w:r><w:r><w:t xml:space="preserve">\1</w:t></w:r><w:r><w:t xml:space="preserve">z</w:t>(?:(?!</w:t>).)*?{%-{%z'-%}(?:(?!<w:t[ >]|{%|{{).)*?<w:t[^>]*?>%})trtcprzP<w:%(y)s[ >](?:(?!<w:%(y)s[ >]).)*({%%|{{)%(y)s ([^}%%]*(?:%%}|}})).*?</w:%(y)s>yz\1 \2)re   rf   rg   zG<w:%(y)s[ >](?:(?!<w:%(y)s[ >]).)*({#)%(y)s ([^}#]*(?:#})).*?</w:%(y)s>c                r    d }t        j                  d|| j                         t         j                        S )Nc                    d| j                  d      z   dz   | j                  d      z   | j                  d      z   dz   | j                  d      z   S )NzK<w:vMerge w:val="{% if loop.first %}restart{% else %}continue{% endif %}"/>r   {% if loop.first %}r\   rW   {% endif %}   rQ   m1s    r$   v_mergez;DocxTemplate.patch_xml.<locals>.v_merge_tc.<locals>.v_merge   sb    ahhqk"+, hhqk" hhqk	"
 $$ hhqk"r&   z?(</w:tcPr[ >].*?<w:t(?:.*?)>)(.*?)(?:{%\s*vm\s*%})(.*?)(</w:t>)rK   rN   )rT   rr   s     r$   
v_merge_tcz*DocxTemplate.patch_xml.<locals>.v_merge_tc   s0    	 66R	ii r&   z6<w:tc[ >](?:(?!<w:tc[ >]).)*?{%\s*vm\s*%}.*?</w:tc[ >]c                V   | j                         }d }d }t        j                  d|      rOt        j                  d||t        j                        }t        j                  dd|t        j                        }n't        j                  d||t        j                        }d	|z   d
z   S )Nc                x    | j                  d      dz   | j                  d      z   dz   | j                  d      z   S )Nr   z{{ r\   z * loop.length }}rW   ro   rp   s    r$   with_gridspanzADocxTemplate.patch_xml.<locals>.h_merge_tc.<locals>.with_gridspan   sF    HHQKhhqk" ** hhqk	"r&   c                    d| j                  d      z   | j                  d      z   | j                  d      z   | j                  d      z   S )Nz'<w:gridSpan w:val="{{ loop.length }}"/>r   r\   rW   rn   ro   )m2s    r$   without_gridspanzDDocxTemplate.patch_xml.<locals>.h_merge_tc.<locals>.without_gridspan   sN    =hhqk"hhqk" hhqk" hhqk	"r&   z
w:gridSpanz(w:gridSpan w:val=")(\d+)(")rK   z{%\s*hm\s*%}rJ   z?(</w:tcPr[ >].*?<w:t(?:.*?)>)(.*?)(?:{%\s*hm\s*%})(.*?)(</w:t>)rl   rm   )rQ   rO   searchrP   rR   )rT   xml_to_patchrv   ry   r:   s        r$   
h_merge_tcz*DocxTemplate.patch_xml.<locals>.h_merge_tc   s    	  yy5 ff3! ))	 ff#))	 ffV$ ))	 )3.>>r&   z6<w:tc[ >](?:(?!<w:tc[ >]).)*?{%\s*hm\s*%}.*?</w:tc[ >]c                   | j                  d      j                  dd      j                  dd      j                  dd      j                  dd	      j                  d
d	      j                  dd      j                  dd      S )Nr   z&#8216;'z&lt;<z&gt;>u   “"u   ”u   ‘u   ’rQ   replacerS   s    r$   
clean_tagsz*DocxTemplate.patch_xml.<locals>.clean_tags!  sf    
S)%%$$$$	r&   z(?<=\{[\{%])(.*?)(?=[\}%]})rO   rP   rR   )
r#   src_xmlrU   r`   rb   ri   patrs   r|   r   s
             r$   	patch_xmlzDocxTemplate.patch_xmlU   s    &&G))	
	
 &&;))	
	 &&T))	
	 &&S))	
 &&6-))	
 &&&g))	
 &&6gRYYW&&6gRYY
 ( 		FA d(  ffS(G299EG		F # 	FA [(  ffS(G299EG	F	( &&E))	
0	?d &&E))	

	 &&7WMr&   Nc                L   t        j                  dd|      }	 || _        |r|j                  |      }nt	        |      }|j                  |      }t        j                  dd	|      }|j                  d
d      j                  dd      j                  dd      j                  dd      }| j                  |      }|S # t        $ r^}t        |d      rK|j                  ?t        |j                  dz
  d      }t        d |j                         ||dz          |_        |d }~ww xY w)Nz
<w:p([ >])z\n<w:p\1linenorn   r   c                0    t        j                  dd|       S )Nz<[^>]+>rJ   )rO   rP   )xs    r$   <lambda>z.DocxTemplate.render_xml_part.<locals>.<lambda>>  s    bffZQ7 r&      z\n<w:p([ >])z<w:p\1z{_{z{{z}_}z}}z{_%rc   z%_}rd   )rO   rP   r,   from_stringr   renderr   hasattrr   maxmap
splitlinesdocx_contextr   resolve_listing)	r#   r   partcontext	jinja_envtemplatedst_xmlexcline_numbers	            r$   render_xml_partzDocxTemplate.render_xml_part1  s   &&W=	*.D'$009#G,oog.G &&)W=OOE4(WUD!WUD!WUD!	 	 &&w/#  	sH%#***@!#**q.!4#&7&&({QH$ 
 I	s   7B< <	D#ADD#c                    g d}|
t               }|D ]e  }t        | j                  j                  |      }|j	                  |      }|j                  |      }t        | j                  j                  ||       g y )N)authorcomments
identifierlanguagesubjecttitle)r   r2   r   core_propertiesr   r   setattr)r#   r   r   
propertiespropinitialr   rendereds           r$   render_propertieszDocxTemplate.render_propertiesM  sq    


 #I 	?Ddii77>G ,,W5Hw/HDII--tX>		?r&   c                   |
t               }| j                  j                  D ]  }|j                  j                  j
                  D ]  }|j                  dk(  s| j                  t        |j                  t              r|j                  j                  d      n|j                        }| j                  ||||      }|j                  d      |_          y )NzLapplication/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xmlutf-8)r   r   sectionsr   packagepartscontent_typer   
isinstanceblobbytesdecoder   encode_blob)r#   r   r   sectionr   r:   s         r$   render_footnoteszDocxTemplate.render_footnotesh  s     #Iyy)) 	5G,,22 5$$6 ..%dii7 		((1!YYC
 ..sD'9MC!$G!4DJ5	5r&   c                r    d fdfd}t        j                  d||t         j                        }|S )Nc                    |j                  d      j                  dd| d| d      }|j                  dd|d| d      }|j                  d	d
      }|j                  dd|d| d      }|S )Nr   	z</w:t></w:r><w:r>z<w:tab/></w:r><w:r>z<w:t xml:space="preserve">z</w:t></w:r></w:p><w:p>z<w:r>
z'</w:t><w:br/><w:t xml:space="preserve">zB</w:t></w:r></w:p><w:p><w:r><w:br w:type="page"/></w:r></w:p><w:p>r   )run_propertiesparagraph_propertiesrT   r:   s       r$   resolve_textz2DocxTemplate.resolve_listing.<locals>.resolve_text~  s    ''!*$$ 8F~WC ++ (9C ++d$MNC++ (9C Jr&   c                     t        j                  d|j                  d            rj                  d      ndt        j                  d fd|j                  d      t         j                        S )Nz<w:rPr>.*?</w:rPr>r   rJ   z<w:t(?: [^>]*)?>.*?</w:t>c                     |       S r1    )r   r   r   r   s    r$   r   zCDocxTemplate.resolve_listing.<locals>.resolve_run.<locals>.<lambda>  s    ,~7KQO r&   rK   rO   rz   rQ   rP   rR   )r   rT   r   r   s   ` @r$   resolve_runz1DocxTemplate.resolve_listing.<locals>.resolve_run  sY    YY'<aggajIN8F^11!4BN66,O
ii	 r&   c                    t        j                  d| j                  d            rj                  d      ndt        j                  dfd| j                  d      t         j                        S )Nz<w:pPr>.*?</w:pPr>r   rJ   z<w:r(?: [^>]*)?>.*?</w:r>c                     |       S r1   r   )r   r   r   s    r$   r   zIDocxTemplate.resolve_listing.<locals>.resolve_paragraph.<locals>.<lambda>  s    +&:A> r&   rK   r   )rT   r   r   s    @r$   resolve_paragraphz7DocxTemplate.resolve_listing.<locals>.resolve_paragraph  s`    #%99-BAGGAJ#O 1E$**1-2 ! 66,>
ii	 r&   z<w:p(?: [^>]*)?>.*?</w:p>rK   r   )r#   r:   r   r   r   s      @@r$   r   zDocxTemplate.resolve_listing|  s7    	.	
	 ff(*;S		
 
r&   c                    | j                         }| j                  |      }| j                  || j                  j                  ||      }|S r1   )rA   r   r   r   _part)r#   r   r   r:   s       r$   	build_xmlzDocxTemplate.build_xml  s>    llnnnS!""3		)L
r&   c                l    | j                   j                  }|j                  }|j                  ||       y r1   )r   r?   r@   r   )r#   treerootr@   s       r$   map_treezDocxTemplate.map_tree  s(    yy!!yyT4 r&   c              #     K   | j                   j                  j                  j                         D ]<  \  }}|j                  |k(  s|j
                  j                  s-||j
                  f > y wr1   )r   r   relsitemsreltypetarget_partr   )r#   urirelKeyvals       r$   get_headers_footersz DocxTemplate.get_headers_footers  sW     99??//557 	.KFCs")=)=coo--	.s   AA1A1A1c                J    | j                  t        |j                              S r1   )r;   r   r   )r#   r   s     r$   get_part_xmlzDocxTemplate.get_part_xml  s    !!)DII"677r&   c                t    t        j                  d|t         j                        }|r|j                  d      S y)Nz <\?xml[^\?]+\bencoding="([^"]+)"r   r   )rO   matchIrQ   )r#   r:   rT   s      r$   get_headers_footers_encodingz)DocxTemplate.get_headers_footers_encoding  s-    HH8#rttD771:r&   c              #     K   | j                  |      D ]a  \  }}| j                  |      }| j                  |      }| j                  |      }| j	                  ||||      }||j                  |      f c y wr1   )r   r   r   r   r   r   )r#   r   r   r   r   r   r:   r7   s           r$   build_headers_footers_xmlz&DocxTemplate.build_headers_footers_xml  s|      44S9 	/LFD##D)C88=H..%C&&sD'9EC#**X...	/s   A7A9c                   | j                   j                  j                  |   j                  }t	        j
                  |j                  |j                  ||j                        }|j                  j                         D ]A  \  }}|j                  |j                  |j                  |j                  |j                         C || j                   j                  j                  |   _        y r1   )r   r   r   r   r   loadpartnamer   r   r   load_relr   _targetrIdis_external)r#   r   r:   r   new_partr   rels          r$   map_headers_footers_xmlz$DocxTemplate.map_headers_footers_xml  s    yy##F+77<<t/@/@#t||T		) 	RHCckk3;;Q	R/7		V$,r&   c                   | j                          |r|st        |      }n||_        | j                  ||      }| j	                  |      }| j                  |       | j                  |       | j                  || j                  |      }|D ]  \  }}| j                  ||        | j                  || j                  |      }	|	D ]  \  }}| j                  ||        | j                  ||       | j                  ||       d| _        y )N)
autoescapeT)r/   r   r   r   
fix_tablesfix_docpr_idsr   r   
HEADER_URIr   
FOOTER_URIr   r   r    )
r#   r   r   r   xml_srcr   headersr   r:   footerss
             r$   r   zDocxTemplate.render  s    	':>	'1	$ ..)4 w' 	4  	d 00$//9U" 	6KFC((5	6 00$//9U" 	6KFC((5	6 	w	2gy1  r&   c                X   t        j                  d      }t        j                  ||      }d|j                  d   z   dz   |j	                  dz         D ]  }|j                  dz         }|j                  d	z         }d
}|j	                  dz         D ]H  }|j                  dz         }	t        |      |z   t        |	      k  s2t        |	      t        |      z
  }J |d
kD  rd}
d }|D ]7  }|j                  dz         |
t        |j                  dz               z  }
9 |
d
kD  r|
t        |      z  }|
t        |      |z   z  }|D ]J  }|j                  dz   t        t        t        |j                  dz               |z  |z                     L t        |      D ]3  }t        j                  |d	z   dz   t        t        |            i       5 |j                  d	z         }t        |      }d
}fd}|j	                  dz         D ]9  }|j                  dz         }	t        j                   ||	d
      }t#        ||      }; ||z
  }|d
kD  sd}|| d  D ]3  }|t        |j                  dz               z  }|j%                  |       5 |j                  d	z         }d
}t        |      d
kD  r|t        |      z  }t        |      }|D ]G  }|j                  dz   t        t        t        |j                  dz               |z                      I  |S )NT)recover)parser{rC   }tbltblGridgridColr   re   rf   g        c                    |j                  dz         }|d n|j                  dz         }| | t        |j                  dz               z   S | dz   S )NtcPrgridSpanr   r   )findintget)totalcelltc_pr	grid_spannss       r$   get_cell_lenz-DocxTemplate.fix_tables.<locals>.get_cell_len7  sZ    		"v+.$)MDuzz"z/7R	( 3y}}R%Z'@#AAAqy r&   )r   	XMLParser
fromstringnsmapiterr  findalllenr  floatsetstrr  range
SubElement	functoolsreducer   remove)r#   r:   r   r   tr   columnsto_addrh   cellswidthnew_averagecold_averageicolumns_lencells_len_maxr
  	cells_len	to_removeremoved_widthcolumns_leftextra_spacer	  s                          @r$   r   zDocxTemplate.fix_tables  s@   .F34::c?"S(2:& Q	TAffR)^,Goob9n5GFVVBI& 7		"t),L6)SZ7 Z#g,6F7
 z "  8AuuR#X2quuR#X!778 19"'#g,"6K"'3w<&+@"AK$ H #E!%%S/$:[$H;$V W #6] ((#R)^b3hCDT@U5V oob9n5Gg,KM! VVBI& >		"t),%,,\5!D	 #M9 =>
 $m3I 1} !$ )- &A!U155c?%;;MNN1%&
  'rI~>  |$q("/#l2C"CK"%k"2K% TAEE"s(CE!%%S/,B[,P(Q$RSTaQ	Tf r&   c                    |j                  dt        j                  j                  j                        D ]9  }| xj
                  dz  c_        t        | j
                        |j                  d<   ; y )Nz
//wp:docPr
namespacesr   id)xpathr   oxmlr	  r  r-   r  attrib)r#   r   elts      r$   r   zDocxTemplate.fix_docpr_idsb  sV    ::ltyy||7I7I:J 	8C1$"4#6#67CJJt	8r&   c                @    ddl m} | j                           || |      S )Nr   r   )subdocr   r)   )r#   docpathr   s      r$   
new_subdoczDocxTemplate.new_subdoch  s    "dG$$r&   c                    t        | d      r| j                         }n%t        | d      5 }|j                         }d d d        t        j                        dz  }|S # 1 sw Y   #xY w)Nreadrbl    )r   r6  rD   binasciicrc32)file_objbufrG   crcs       r$   get_file_crczDocxTemplate.get_file_crcn  s]    8V$--/Ch%  ggi  nnS!J.
	   s   AA&c                    | j                  |      }t        |d      r|j                         | j                  |<   yt	        |d      5 }|j                         | j                  |<   ddd       y# 1 sw Y   yxY w)a  Replace one media by another one into a docx

        This has been done mainly because it is not possible to add images in
        docx header/footer.
        With this function, put a dummy picture in your header/footer,
        then specify it with its replacement in this function using the file path
        or file-like objects.

        Syntax: tpl.replace_media('dummy_media_to_replace.png','media_to_paste.jpg')
            -- or --
                tpl.replace_media(io.BytesIO(image_stream), io.BytesIO(new_image_stream))

        Note: for images, the aspect ratio will be the same as the replaced image

        Note2: it is important to have the source media file as it is required
                to calculate its CRC to find them in the docx
        r6  r7  N)r=  r   r6  crc_to_new_mediarD   )r#   src_filedst_filer<  rG   s        r$   replace_mediazDocxTemplate.replace_mediay  sk    & )8V$)1D!!#&h% 7-/WWY%%c*7 7 7s   A//A8c                    t        |d      r|j                         | j                  |<   yt        |d      5 }|j                         | j                  |<   ddd       y# 1 sw Y   yxY w)a  Replace embedded picture with original-name given by embedded_file.
           (give only the file basename, not the full path)
           The new picture is given by dst_file (either a filename or a file-like
           object)

        Notes:
            1) embedded_file and dst_file must have the same extension/format
               in case dst_file is a file-like object, no check is done on
               format compatibility
            2) the aspect ratio will be the same as the replaced image
            3) There is no need to keep the original file (this is not the case
               for replace_embedded and replace_media)
        r6  r7  N)r   r6  pics_to_replacerD   )r#   embedded_filerA  rG   s       r$   replace_piczDocxTemplate.replace_pic  s_     8V$2:--/D  /h% @68ggi$$]3@ @ @s   AA'c                    t        |d      5 }| j                  |      }|j                         | j                  |<   ddd       y# 1 sw Y   yxY w)a  Replace one embedded object by another one into a docx

        This has been done mainly because it is not possible to add images
        in docx header/footer.
        With this function, put a dummy picture in your header/footer,
        then specify it with its replacement in this function

        Syntax: tpl.replace_embedded('dummy_doc.docx','doc_to_paste.docx')

        Note2 : it is important to have the source file as it is required to
                calculate its CRC to find them in the docx
        r7  N)rD   r=  r6  crc_to_new_embedded)r#   r@  rA  rG   r<  s        r$   replace_embeddedzDocxTemplate.replace_embedded  sK     (D! 	6R##H-C,.GGID$$S)	6 	6 	6s   /AAc                    t        |d      5 }|j                         | j                  |<   ddd       y# 1 sw Y   yxY w)a0  Replace one file in the docx file

        First note that a MSWord .docx file is in fact a zip file.

        This method can be used to replace document embedded in the docx template.

        Some embedded document may have been modified by MSWord while saving
        the template : thus replace_embedded() cannot be used as CRC is not the
        same as the original file.

        This method works for embedded MSWord file like Excel or PowerPoint file,
        but won't work for others like PDF, Python or even Text files :
        For these ones, MSWord generate an oleObjectNNN.bin file which is no
        use to be replaced as it is encoded.

        Syntax:

        tpl.replace_zipname(
            'word/embeddings/Feuille_Microsoft_Office_Excel1.xlsx',
            'my_excel_file.xlsx')

        The zipname is the one you can find when you open docx with WinZip,
        7zip (Windows) or unzip -l (Linux). The zipname starts with
        "word/embeddings/". Note that the file is renamed by MSWord,
        so you have to guess a little bit...
        r7  N)rD   r6  zipname_to_replace)r#   zipnamerA  rG   s       r$   replace_zipnamezDocxTemplate.replace_zipname  s;    6 (D! 	9R/1wwyD##G,	9 	9 	9s   4=c                <    i | _         i | _        i | _        i | _        y)aZ  Reset replacement dictionaries

        This will reset data for image/embedded/zipname replacement

        This is useful when calling several times render() with different
        image/embedded/zipname replacements without re-instantiating
        DocxTemplate object.
        In this case, the right sequence for each rendering will be :
            - reset_replacements(...)
            - replace_zipname(...), replace_media(...) and/or replace_embedded(...),
            - render(...)

        If you instantiate DocxTemplate object before each render(),
        this method is useless.
        N)r?  rH  rK  rD  r.   s    r$   r   zDocxTemplate.reset_replacements  s$      !##% "$!r&   c                .   | j                   s| j                  s| j                  rXt        |d      rrt	        j
                         }t        |      j                  |       |j                  d       |j                  d       |j                          |j                  d       nd|z  }t        j                  ||       t        j                  |      5 }t        j                  |d      5 }|j                         D ]-  }|j                  |j                         }|j                   | j                  v r*|j#                  || j                  |j                             a|j                   j%                  d      rB|j&                  | j                   v r*|j#                  || j                   |j&                            |j                   j%                  d      rC|j&                  | j                  v r+|j#                  || j                  |j&                            |j#                  ||       0 	 d d d        d d d        t        |d      st        j(                  |       t        |d      r|j                  d       y y y # 1 sw Y   RxY w# 1 sw Y   VxY w)Nr6  r   z %s_docxtpl_before_replace_mediasrC   zword/media/zword/embeddings/)r?  rH  rK  r   ioBytesIOr   saveseektruncateosrenamezipfileZipFileinfolistr6  rF   writestr
startswithCRCr  )r#   	docx_filetmp_filezinzoutitemr;  s          r$   post_processingzDocxTemplate.post_processing  s     D$<$<@W@Wy&)::<Y',,X6a q!""$q! >	I		)X.* 5c__Y4 5 # 5!hht}}5==D,C,CC MM$0G0G0VW MM44]C $D,A,A A MM$0E0Edhh0OP MM445GH $D,D,D D MM$0H0H0RS MM$4555& 8V,		(#y&)q! *G AX5 55 5s%   J+EI?.J?J	JJc                >    | j                   r| j                          y y r1   )rD  _replace_picsr.   s    r$   pre_processingzDocxTemplate.pre_processing  s       r&   c                   | j                   D ci c]  }|d }}| j                  j                  }| j                  ||       |j                  j                         D ]N  \  }}|j                  t        j                  t        j                  fv s3| j                  |j                  |       P | j                  s)|j                         D ]  \  }}|r	t        d|z         yyc c}w )zRReplaces pictures xml tags in the docx template with pictures provided by the userFz)Picture %s not found in the docx templateN)rD  r   r   _replace_docx_part_picsr   r   r   REL_TYPEHEADERFOOTERr   r"   
ValueError)r#   keyreplaced_picsr   relidr   img_idreplaceds           r$   rd  zDocxTemplate._replace_pics  s     04/C/CDeDD yy~~$$T=9 ))//+ 	MJE3{{x@@,,S__mL	M &&$1$7$7$9  $CfL  ' Es   
C$c                    | j                   S r1   )r+   r.   s    r$   get_pic_mapzDocxTemplate.get_pic_map/  s    ||r&   c                   t        j                  |j                        }i }|j                  dt        j
                  j                  j                        }|D ]  }d }	 |j                  d   t        j
                  j                  j                  d   k(  r|j                  dt        j
                  j                  j                        d   }|j                  dt        j
                  j                  j                        }	t        |	      dkD  r|	d   }nd}
|j                  d	|
z  t        j
                  j                  j                        d   }|j                  d
|
z  t        j
                  j                  j                        }|r|d   }nd}|j                  d|
z  t        j
                  j                  j                        }|r|d   }nd}|j                  |   j                  |j                  |   j                  f||<   | j                  j                         D ](  \  }}||k(  s||k(  s||k(  s|||   d   _        d||<    n  | j"                  j%                  |       y # t         $ r Y 'w xY w)Nz//a:graphic/a:graphicDatar*  r   piczpic:pic/pic:blipFill/a:blipr   z@r:embedzpic:pic/pic:nvPicPr/pic:cNvPr/z%s@namez%s@titlerJ   z%s@descrr   T)r   r  r   r-  r   r.  r	  r  r/  r  r   
target_refr   rD  r   r   	Exceptionr+   update)r#   doc_partrm  etpart_mapgdsgdr   blipdestnon_visual_propertiesrF   titlesr   descriptionsdescriptionro  img_datas                     r$   rg  z$DocxTemplate._replace_docx_part_pics2  sS   hmm,hh2tyy||?Q?QhR 3	BC099U#tyy||'9'9%'@@885$)),,BTBT $ D  ::jTYY\\=O=O:PD4y1}"1g (H%88 55$)),,BTBT $  !66499<<CUCU "  "1IEE!xx!66499<<CUCU  (    ".q/K"$K MM#&11MM#&22&" )-(<(<(B(B(D $FH)Vu_+@U6>*1-304f-	U3	j 	H%  s     B8I4D%I4 I44	J Jc                    | j                          | j                  j                  j                  |t        j
                  d      S )NT)r   )r)   r   r   	relate_torh  	HYPERLINK)r#   urls     r$   build_url_idzDocxTemplate.build_url_idp  s2    yy((h.@.@d(SSr&   c                    | j                   s&| j                  st        | j                        | _        | j                           | j                  j                  |g|i | | j                  |       d| _         y )NT)r!   r    r   r   r   re  rR  rb  )r#   rF   argskwargss       r$   rR  zDocxTemplate.savet  sb     }}T%5%5 !3!34DI		x1$1&1X&r&   c                   t        | j                        }| j                  |j                  j                        }| j                  |      }| j                  | j                  fD ]  }|j                  j                  j                         D ]n  \  }}|j                  |k(  s|j                  j                  s-| j                  t        |j                  j                              }|| j                  |      z  }p  |r|}	n
t               }	|	j!                  |      }
t#        j$                  |
      }|t'        |j)                               }||z
  S |S r1   )r   r   r;   r?   r@   r   r   r   r   r   r   r   r   r   r   r   parser   find_undeclared_variablesr  keys)r#   r   r   temp_docr:   r   r   r   _xmlenvparse_contentall_variablesprovided_variabless                r$   !get_undeclared_template_variablesz.DocxTemplate.get_undeclared_template_variables~  s)    D../   !2!2!7!78nnS! OOT__5 	0C'~~2288: 0KK3&S__-A-A--i8L8L.MND4>>$//C0	0 C-C		#66}E !$W\\^!4 #555 r&   )r   Union[IO[bytes], str, PathLike]returnNone)T)r(   bool)r6   r1   )r   Dict[str, Any]r   Optional[Environment]r  r  r   )r   r  r   r  r   r  r  r  )r  r   )rF   r  r  r  )NN)r   r  r   zOptional[Dict[str, Any]]r  zSet[str])-__name__
__module____qualname____doc__r   r   r%   r)   r/   r4   r;   r=   rA   rH   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r4  staticmethodr=  rB  rF  rI  rM  r   rb  re  rd  rr  rg  r  rR  r  r   r&   r$   r   r   $   s   E 	U  	U (%
(K
;%Zx: KO?%?2G?	?8 KO5%52G5	5(3j!
.
8/8 ,0 	* *  )*  	* 
 
* \Yv8%  74@,6"9<"*%"N!
,<&|T ,0,0!(! *! 
	!r&   r   ),r  
__future__r   rU  r   typingr   r   r   r   r	   r
   r   r  rP  lxmlr   r   r   docx.opc.oxmlr   docx.opc.partr   docx.oxml.nsdocx.opc.constantsr   rh  jinja2r   r   r   jinja2.exceptionsr   htmlr   ImportErrorcgirO   r8  rW  r2  r   objectr   r   r&   r$   <module>r     sz   
 #  E E E  	   # !  < . . + 
  	 {6 {  s   B BB