o
    Nit                     @  s  d Z ddlm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m	Z	m
Z
mZ ddlmZ ddlmZmZmZ ddlmZ dd	lmZ dd
lmZ 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# ddl$m%Z%m&Z&m'Z' e	rddl(m)Z)m*Z* z
ddl+m,Z, dZ-W n e.y   dZ-Y nw e/e0Z1dZ2dZ3dZ4dZ5dZ6dZ7dddZ8dd d!d"d#d$d%d%d&d'd(d)Z9d*Z:e;d+Z<G d,d- d-eZ=G d.d/ d/eZ>G d0d1 d1eZ?G d2d3 d3eZ@d=d>d9d:ZAeAZBG d;d< d<eZCdS )?z#Base class of epub2/epub3 builders.    )annotationsN)path)TYPE_CHECKINGAny
NamedTuple)quote)ZIP_DEFLATED
ZIP_STOREDZipFile)nodes)smartquotes)addnodes)StandaloneHTMLBuilder)	BuildInfo)__)logging)status_iterator)copy_asset_file)copyfile	ensuredirrelpath)ElementNode)ImageTFzepub-cover.xhtmlztoctree-l%dz
 [%(uri)s]z#%d	Footnoteszlink-targetzTable of ContentsCover)toccoverzapplication/xhtml+xmlztext/css	image/pngz
image/webp	image/gifimage/svg+xml
image/jpegzfont/otfzfont/ttfz	font/woff).xhtmlz.cssz.pngz.webpz.gif.svgz.jpgz.jpegz.otfz.ttfz.woff)r#   z([^#:]*#)(.*)c                   @  &   e Zd ZU ded< ded< ded< dS )ManifestItemstrhrefid
media_typeN__name__
__module____qualname____annotations__ r/   r/   N/home/ubuntu/.local/lib/python3.10/site-packages/sphinx/builders/_epub_base.pyr%   V      
 r%   c                   @  s   e Zd ZU ded< ded< dS )Spiner&   idrefboollinearNr*   r/   r/   r/   r0   r2   \   s   
 r2   c                   @  r$   )Guider&   typetitleuriNr*   r/   r/   r/   r0   r6   a   r1   r6   c                   @  s6   e Zd ZU ded< ded< ded< ded< ded< d	S )
NavPointr&   navpointint	playordertextrefurilist[NavPoint]childrenNr*   r/   r/   r/   r0   r:   g   s   
 r:   entr&   languagereturnc                 C  s2   |  dd} t| } t| |} |  dd} | S )Nz&quot;")replacer   educateDashesOldSchooleducateQuotes)rC   rD   r/   r/   r0   sphinx_smarty_pantso   s
   
rJ   c                      s  e Zd ZdZdZg dZdZdZdZdZ	dZ
dZdZeZeZeZeZeZeZeZdZdZde fdd	ZdfddZdgddZdhddZ diddZ!djddZ"deddZ#dkd d!Z$dld$d%Z%dmd(d)Z&	*dndod,d-Z'dp fd/d0Z(dqd2d3Z)drd6d7Z*ded8d9Z+de fd:d;Z,ded<d=Z-	>	?	?dsdt fdHdIZ.dedJdKZ/dudvdNdOZ0dwdPdQZ1dedRdSZ2	dxdydYdZZ3dzd\d]Z4d{d_d`Z5dedadbZ6dedcddZ7  Z8S )|EpubBuilderz
    Builder that outputs epub files.

    It creates the metainfo files container.opf, toc.ncx, mimetype, and
    META-INF/container.xml.  Afterwards, all necessary files are zipped to an
    epub file.
    F)r    r   r   r!   T rE   Nonec                   s@   t    d| _d| _d| _d| _i | _| dd| _g | _	d S )Nr"   r   	use_indexepub)
superinit
out_suffixlink_suffixr=   tocidid_cacheget_builder_configrN   refnodesself	__class__r/   r0   rQ      s   

zEpubBuilder.initr   c                 C  s   t | j| jtddhS )NhtmlrO   )r   configtags	frozensetrX   r/   r/   r0   create_build_info   s   zEpubBuilder.create_build_info'tuple[str, dict[str, str | int | bool]]c                 C  s   | j j| j jfS N)r]   
epub_themeepub_theme_optionsrX   r/   r/   r0   get_theme_config   s   zEpubBuilder.get_theme_confignamer&   c                 C  s.   | j |}|sd| jd }|| j |< |S )zReturn a unique id for name.zepub-%drO   )rU   getenvnew_serialno)rY   rf   r(   r/   r/   r0   make_id   s
   
zEpubBuilder.make_iddoctreer   resultlist[dict[str, Any]]c              
   C  s   t |tjrD|drD|d }|dr|S |jjd }tdddD ]}| j| |v rA|	|t
|tt
| d  |S q"|S t |tjrU|D ]}| ||}qL|S )z>Collect section titles, their depth in the toc and the refuri.r?   )zhttp://zhttps://zirc:zmailto:classes   r   levelr?   r>   )
isinstancer   	referencerg   
startswithparent
attributesrangetoctree_templateappendr\   escapesspastextr   get_refnodes)rY   rk   rl   r?   rn   rr   elemr/   r/   r0   r~      s(   

zEpubBuilder.get_refnodesr   c                 C  sJ   t  }|D ]}|d |v rtjtd|d ddd q||d  qd S )Nr?   zduplicated ToC entry found: %srO   duplicated_toc_entryr7   subtype)setloggerwarningr   add)rY   r   appearednoder/   r/   r0   check_refnodes   s   zEpubBuilder.check_refnodesc                 C  sl   | j j| jj| ddd}| |g | _t| jj}|r.|d7 }| jD ]
}||d  |d< q#| | j dS )zwGet the total table of contents, containing the root_doc
        and pre and post files not managed by sphinx.
        FTprune_toctreesincludehidden/r?   N)	rh   get_and_resolve_doctreer]   root_docr~   rW   r   dirnametoc_add_files)rY   rk   
master_diritemr/   r/   r0   get_toc   s   
zEpubBuilder.get_tocrW   c              
   C  s   | ddt| jj| j tt| jj| jj 	 d t
| jjD ]\}}| ddt|tt|d q%| jjD ]\}}|dt|tt|d q@dS )z;Add the root_doc, pre and post files to a list of refnodes.r      rq   N)insertr\   r{   r]   r   rR   r|   rh   titlesr}   reversedepub_pre_filesepub_post_filesrz   )rY   rW   filer>   r/   r/   r0   r      s0   

zEpubBuilder.toc_add_filesprefixfragmentc                 C  s   || dd S )z;Return a href/id attribute with colons replaced by hyphens.:-)rG   )rY   r   r   r/   r/   r0   fix_fragment  s   zEpubBuilder.fix_fragmenttreenodes.documentc                   s   d fdd}| tjD ],}d|v r+ j|d }|r+ |d|d	|d< d
|v r9 d|d
 |d
< q| tjD ]}|| |jdd}t	|tj
rV|| q@| tjD ]}|| q]dS )zReplace colons with hyphens in href and id attributes.

        Some readers crash because they interpret the part as a
        transport protocol specification.
        r   r   rE   rM   c                   s<   g }| d D ]}  d|}||vr|| q|| d< dS )zUpdate IDs of given *node*.idsrL   N)r   rz   )r   new_idsnode_idnew_idrX   r/   r0   update_node_id  s   
z+EpubBuilder.fix_ids.<locals>.update_node_idr?   r      refidrL   T)ascendN)r   r   rE   rM   )findallr   rt   	refuri_rematchr   grouptarget	next_noders   r   r   desc_signature)rY   r   r   rt   mr   r   r   r/   rX   r0   fix_ids  s$   	
zEpubBuilder.fix_idsinline	show_urlsc                 C  sR  ddd}ddd}ddd}|dkrdS |dkr)t |tj}||\}}d}	t|tjD ]u}
|
dd}|dr||
 vr|
j	
|
d }|dkrm| jd	|i }t||}|d | j |
j	|| q1|dkrt|	 }|	d7 }	|||}|
j	|| ||||}||| |d d |d< ||d d  |d7 }q1dS ) z+Add visible link targets for external linksdocr   labelr&   rE   nodes.footnote_referencec                 S  s(   t d}|t | | | |S )z.Create a footnote_reference node with childrenz[#]_)r   footnote_referencerz   Textnote_autofootnote_ref)r   r   footnote_refr/   r/   r0   make_footnote_ref:  s   

z8EpubBuilder.add_visible_links.<locals>.make_footnote_refr9   nodes.footnotec                 S  sN   t |}t  }|t | || |dt d| | | |S )z$Create a footnote node with childrenr   rL   )r   footnote	paragraphrz   r   r   r   note_autofootnote)r   r   r9   r   parar/   r/   r0   make_footnoteC  s   


z4EpubBuilder.add_visible_links.<locals>.make_footnoter   tuple[Element, int]c                 S  s   t | tj}|r|d }|j|j|d fS | tjD ]}t|dkr:| t	kr:|j|j|d f  S qt
| tj}t }|tt	 || |||d fS )zsFind or create a spot to place footnotes.

            The function returns the tuple (parent, index).
            rp   r   )listr   r   r   rv   indexrubriclenr}   FOOTNOTES_RUBRIC_NAMEnextdocumentrz   r   )r   fnsfnr   r   rubr/   r/   r0   footnote_spotM  s   	
z4EpubBuilder.add_visible_links.<locals>.footnote_spotnoNr   r   r?   rL   )zhttp:zhttps:zftp:r   rn   r   r   r   )r   r   r   r&   rE   r   )r   r   r   r&   r9   r&   rE   r   )r   r   rE   r   )r   r   r   r   r   rt   rg   ru   r}   rv   r   link_target_templater   rz   css_link_target_classr   FOOTNOTE_LABEL_TEMPLATEadd_backref)rY   r   r   r   r   r   r   fn_spotfn_idxnrr   r9   idxlinkr   r   r   r/   r/   r0   add_visible_links5  s<   

	


zEpubBuilder.add_visible_linksdocnamec                   s,   |  | | || jj t || dS )zWrite one document file.

        This method is overwritten in order to fix fragment identifiers
        and to add visible external links.
        N)r   r   r]   epub_show_urlsrP   	write_doc)rY   r   rk   rZ   r/   r0   r   }  s   
zEpubBuilder.write_doc'list[tuple[str, list[tuple[str, Any]]]]c                 C  s   |D ][\}}|D ]T\}\}}}t |D ]\}\}}	| j|	 }
r1|| |
d|
df||< q|D ]'\}}t |D ]\}\}}	| j|	 }
rZ|| |
d|
df||< q<q4qqdS )z'Fix href attributes for genindex pages.r   r   N)	enumerater   r   r   r   )rY   r   _keycolumns
_entrynamelinkssubitemsiismainr   r   _subentrynamesubentrylinksr/   r/   r0   fix_genindex  s"    zEpubBuilder.fix_genindexfilenamer4   c                 C  s   t |d }|tv S )z=Does the filename extension indicate a vector graphic format?rp   )r   splitextVECTOR_GRAPHICS_EXTENSIONS)rY   r   extr/   r/   r0   is_vector_graphics  s   zEpubBuilder.is_vector_graphicsc           	      C  s  t t| j| j t| jtddt| j| j	j
D ]}| j| }ztt| j|}W nN ty{   | |sFttdt| j| zt| j| | j| j | dd W n  tyx } zttdt| j|| W Y d}~nd}~ww Y qw | jjr|jdkr| }| jjd	kr|j\}}| jj}||krt|| | }|||ftj}z|t| j| j| W q ty } zttd
t| j|| W Y d}~qd}~ww dS )zCopy images using Pillow, the Python Imaging Library.
        The method tries to read and write the files with Pillow, converting
        the format and resizing the image if necessary/possible.
        zcopying images... brownz-cannot read image file %r: copying it insteadTforcezcannot copy image file %r: %sNPr   zcannot write image file %r: %s)r   r   joinoutdirimagedirr   imagesr   r   app	verbosityr   opensrcdirOSErrorr   r   r   r   r]   epub_fix_imagesmodeconvertepub_max_image_widthsizeroundresizeBICUBICsave)	rY   srcdestimgerrwidthheightnwnhr/   r/   r0   copy_image_files_pil  sj   




z EpubBuilder.copy_image_files_pilc                   sT   | j r(| jjs| jjr!tsttd t 	  dS | 
  dS t 	  dS dS )zzCopy image files to destination directory.
        This overwritten method can use Pillow to convert image files.
        z&Pillow not found - copying image filesN)r   r]   r   r   PILLOW_AVAILABLEr   r   r   rP   copy_image_filesr  rX   rZ   r/   r0   r    s   zEpubBuilder.copy_image_filesc                 C  s   d S rb   r/   rX   r/   r/   r0   copy_download_files  s   zEpubBuilder.copy_download_files	page.htmlNpagenameaddctxdict[str, Any]templatenameoutfilename
str | None	event_argr   c                   sL   | drd|v r| jsdS | |d  | j|d< t ||||| dS )zCreate a rendered page.

        This method is overwritten for genindex pages in order to fix href link
        attributes.
        genindexgenindexentriesNdoctype)ru   rN   r   r  rP   handle_page)rY   r  r  r  r  r  rZ   r/   r0   r    s   
zEpubBuilder.handle_pagec                 C  s0   t td tt| jd| jd dd dS )z!Write the metainfo file mimetype.zwriting mimetype file...mimetypeTr   N)r   infor   r   r   r   template_dirr   rX   r/   r/   r0   build_mimetype  s   
zEpubBuilder.build_mimetypeMETA-INF/container.xmloutnamec                 C  s@   t td | jd }t| tt| jd|d dd dS )z/Write the metainfo file META-INF/container.xml.z&writing META-INF/container.xml file...zMETA-INFzcontainer.xmlTr   N)	r   r  r   r   r   r   r   r   r  )rY   r"  r   r/   r/   r0   build_container  s   

zEpubBuilder.build_containerc                 C  s   t d }durtt|}nt }i }t| jj|d< t| jj	|d< t| jj
|d< t| jj|d< t| jj|d< t| jj|d< t| jj|d	< t| jj|d
< ttd||d< g |d< g |d< g |d< |S )zaCreate a dictionary with all metadata for the content.opf
        file properly escaped.
        SOURCE_DATE_EPOCHNr8   authoruidlang	publisher	copyrightschemer(   z%Y-%m-%ddatemanifest_itemsspinesguides)osgetenvtimegmtimer<   r\   r{   r]   
epub_titleepub_authorepub_uidepub_languageepub_publisherepub_copyrightepub_schemeepub_identifierstrftime)rY   source_date_epoch
time_tuplemetadatar/   r/   r0   content_metadata  s"   zEpubBuilder.content_metadatac                 C  s  t td |  }g | _dddddddd	d
| jjd g
| jj| _| j	s/| j
d| j  t| jD ]g\}}}|  t|D ]Y}tt||| j}|| jv rTqBt|d }|| jvrp|dvrot jtd|ddd qB|tjd}ttt|t| |t| j| }|d 
| | j
| qBq5t }	| jD ],}
d|
d v rq|
d | jv rqt t| |
d d}|d 
| |	!|
d  q| j"D ]#}t t| |d | j d}|d 
| |	!|d | j  q| j	rt t| d| j d}|d 
| |	!d| j  | jD ]!}||	vr;|#| jr;t t| |d}|d 
| qd}| jj$r| jj$\}}|tjd}t| ||d< |rt t| | j%d}|d &d| | j%| jvrt| j%d }| j
| j% tt| j%t| | j%t| j| }|d 
| t|| jj'd}| (t| j%d || |	!| j% d}d}| jj)r| jj)D ];\}}}|*dd }|| jvr| j
| |dkrd}|dkrd}|d 
t+t|t|t| q|r$|r$|d 
t+d| j,d t| j% |rA| jrA|d 
t+d| j,d t| jd d  t-t| j.d | j|dd! dS )"zWrite the metainfo file content.opf It contains bibliographic data,
        a file list and the spine (the reading order).
        zwriting content.opf file...z
.buildinfor  content.opftoc.ncxr!  z	Thumbs.dbzehthumbs.dbz	.DS_Storez	nav.xhtml.epubr  rp   )z.jsz.xmlz!unknown mimetype for %s, ignoringrO   unknown_project_filesr   r   r,  #r?   Tr-  r   FNr   )imager8   r   r.  zcontent.opf.jinjacontextr   )/r   r  r   r?  filesr]   epub_basenameepub_exclude_filesignored_filesrN   rz   rR   r/  walkr   sortsortedr   r   r   r   media_typesr   rG   sepr%   r\   r{   r   rj   r   rW   r2   r   domain_indicesendswith
epub_covercoverpage_namer   projectr  
epub_guidesplitr6   guide_titlesr   r  )rY   r>  rootdirsrH  r   r   r   r   
spinefilesrefnodespiner  rf   	html_tmplrE  ctxauto_add_coverauto_add_tocr7   r9   r8   r   r/   r/   r0   build_content%  s   




 






	
zEpubBuilder.build_contentr   rr   r<   incrr:   c                 C  sB   |r	|  j d7  _ |  jd7  _td| j | j |d |d g S )z;Create a new entry in the toc from the node at given level.r   navPointr>   r?   )r=   rT   r:   )rY   r   rr   rc  r/   r/   r0   new_navpoint  s   zEpubBuilder.new_navpointr@   c                 C  s|  g }| tddddg  d}d}|D ]}|d sq|d dd }|| jv r)q|d | jjkr2q|d |krP| ||}|  |d	 j | | | nf|d |d
 kr|d
7 }|ro| jj	ro|d	 j | ||d | ||}|d	 j | | | n3|d |k r|d t
|k r|  |d t
|k s|d }| ||}|d	 j | | | n |}q|d jS )zCreate the toc navigation structure.

        Subelements of a node are nested inside the navpoint.  For nested nodes
        the parent node is reinserted in the subnav.
        dummyr   rL   Nr>   r?   rD  rr   rp   r   F)rz   r:   rW  rK  r]   epub_tocdepthre  poprA   epub_tocdupr   )rY   r   navstackrr   lastnoder   r   r;   r/   r/   r0   build_navpoints  sJ   


zEpubBuilder.build_navpoints	navpointsc                 C  s6   i }| j j|d< t| j j|d< ||d< ||d< |S )z]Create a dictionary with all metadata for the toc.ncx file
        properly escaped.
        r&  r8   rr   rm  )r]   r5  r\   r{   r3  )rY   rr   rm  r>  r/   r/   r0   toc_metadata  s   zEpubBuilder.toc_metadatac                 C  s   t td | jjdkr%| jj| jj| ddd}| |g }| 	| n| j
}| | | |}tdd | j
D }t|| jj}tt| jd| j| ||dd	 d
S )z Write the metainfo file toc.ncx.zwriting toc.ncx file...defaultFr   c                 s  s    | ]}|d  V  qdS )rr   Nr/   ).0r   r/   r/   r0   	<genexpr>  s    z(EpubBuilder.build_toc.<locals>.<genexpr>ztoc.ncx.jinjaTrF  N)r   r  r   r]   epub_tocscoperh   r   r   r~   r   rW   r   rl  maxminrg  r   r   r   r  r   rn  )rY   rk   rW   rm  rr   r/   r/   r0   	build_toc  s$   



zEpubBuilder.build_tocc                 C  s   | j jd }ttd| t| j|}t|dt	8}|
t| jddt dD ]}|
t| j||t	 q*| jD ]}|
t| j||t	 q<W d   dS 1 sVw   Y  dS )z~Write the epub file.

        It is a zip file with the mimetype file stored uncompressed as the first
        entry.
        rB  zwriting %s file...wr  )r!  r@  rA  N)r]   rI  r   r  r   r   r   r   r
   r   writer	   rH  )rY   r"  epub_filenamerO   r   r/   r/   r0   
build_epub
  s   
"zEpubBuilder.build_epub)rE   rM   )rE   r   )rE   ra   )rf   r&   rE   r&   )rk   r   rl   rm   rE   rm   )r   rm   rE   rM   )rW   rm   rE   rM   )r   r&   r   r&   rE   r&   )r   r   rE   rM   )r   )r   r   r   r&   rE   rM   )r   r&   rk   r   rE   rM   )r   r   rE   rM   )r   r&   rE   r4   )r  NN)r  r&   r  r  r  r&   r  r  r  r   rE   rM   )r!  )r"  r&   rE   rM   )rE   r  )T)r   r  rr   r<   rc  r4   rE   r:   )r   rm   rE   r@   )rr   r<   rm  r@   rE   r  )9r+   r,   r-   __doc__
copysourcesupported_image_typessupported_remote_imagesadd_permalinksallow_sharp_as_current_pathembeddeddownload_supporthtml_scaled_image_linksearchCOVERPAGE_NAMErT  TOCTREE_TEMPLATEry   LINK_TARGET_TEMPLATEr   CSS_LINK_TARGET_CLASSr   GUIDE_TITLESrX  MEDIA_TYPESrO  	REFURI_REr   r  r  rQ   r`   re   rj   r~   r   r   r   r   r   r   r   r   r   r  r  r  r  r   r#  r?  rb  re  rl  rn  ru  ry  __classcell__r/   r/   rZ   r0   rK   }   sj    	



	




#H



7

	

 


.
rK   )rB   )rC   r&   rD   r&   rE   r&   )Drz  
__future__r   r\   r/  rer1  r   typingr   r   r   urllib.parser   zipfiler   r	   r
   docutilsr   docutils.utilsr   sphinxr   sphinx.builders.htmlr    sphinx.builders.html._build_infor   sphinx.localer   sphinx.utilr   sphinx.util.displayr   sphinx.util.fileutilr   sphinx.util.osutilr   r   r   docutils.nodesr   r   PILr   r  ImportError	getLoggerr+   r   r  r  r  r   r   r  r  r  r   compiler  r%   r2   r6   r:   rJ   r|   rK   r/   r/   r/   r0   <module>   sv    
	
