Xj݀ r ddlZ ddlmZddlZejejredddl m Z ddl Z ddl Z ddlZddlZddlmZdd lmZdd lmZd d gZe j,e j.ej0d Zej4dOdededefdZejsddlmZdZ e fdZ!dZ"dZ#dZ$dZ%ej4de&fdZ'dZ(dZ)dZ*dPdZ+de&fd Z,ej4d!edefd"Z-ejsd!edefd#Z-Gd$d%Z.Gd&d'Z/de&fd(Z0d)e&fd*Z1ej4de&fd+Z2Gd,d-eZ3Gd.d/e3Z4Gd0d1e3Z5dQd2Z6dQd3Z7ejpd4ejrejtzjvZ<ejpd5ejrejtzjvZ=ejpd6ejrejtzj|Z?d7Z@d8ZAd9ZBejeDejZEejeDeDgd:ZFejeDeDgd;ZGejeeeHeFeGzZIdPd<ZJejpd=ejjZMd>ZNejpd?jZPd@ZQdAZRdBZSdCZTdDZUdEZVdPdFZWej4dGZXej4dHZYej4dIZZdJZ[ejejGdKdLe Z^e_dMk(rddNlm`Z`e`jyy#e$rGddZeZYwxYw#e$rddlZejsddlm Z YzwxYw)RNc(eZdZdZdZdZdZdZy) fake_cythonFc|SNselffuncs b/mnt/ssd/data/Dropbox/adrian/vault-secondbrain/venv/lib/python3.12/site-packages/lxml/html/diff.pycfunczfake_cython.cfuncsd{c|Srrrs r cclasszfake_cython.cclass st r c|Srr)r _values r declarezfake_cython.declare sE\r cy)Nobjectr)r type_names r __getattr__zfake_cython.__getattr__ sr N)__name__ __module__ __qualname__compiledr rrrrr r rrs*+19r r)_difflibzLEmbedded difflib is not compiled to a fast binary, using the stdlib instead.)SequenceMatcher)etree)fragment_fromstring)defs html_annotatehtmldiff)keytext_escapesreturncdgdz}|D]R}|dxx|dk(zcc<|dxx|dk(zcc<|dxx|dk(zcc<|d xx|d k(zcc<|d xx|d k(zcc<TtdD] }||s |jd |||}"|S)NFr&r<>"'z&<>"')rangereplace)r%r&r3chis r html_escaper6-s %gkG  bCi  bCi  bCi  bCi  bCi  1X: 1:<< Xa[9D: Kr )escapec&dt|d|dS)Nz z)r6)r%versions r default_markupr:EsGd $$r c|Dcgc]\}}t||}}}|d}|ddD]}t|||}t|}t||}dj |j Scc}}w)a doclist should be ordered from oldest to newest, like:: >>> version1 = 'Hello World' >>> version2 = 'Goodbye World' >>> print(html_annotate([(version1, 'version 1'), ... (version2, 'version 2')])) Goodbye World The documents must be *fragments* (str/UTF8 or unicode), not complete documents The markup argument is a function to markup the spans of words. This function is called like markup('Hello', 'version 2'), and returns HTML. The first argument is text and never includes any markup. The default uses a span with a title: >>> print(default_markup('Some Text', 'by Joe')) Some Text rrN)tokenize_annotatedhtml_annotate_merge_annotationscompress_tokensmarkup_serialize_tokensjoinstrip)doclistmarkupdocr9 tokenlist cur_tokenstokensresults r r"r"Is6&-.!S'$C1.I.1JAB-' F;  !,J $Z 8F 776? "".sA2c<t|d}|D] }||_ |S)zFTokenize a document and add an annotation attribute to each token F include_hrefs)tokenize annotation)rErNrHtoks r r=r=qs+c /F$#$ Mr ct||}|j}|D]$\}}}}}|dk(s|||} |||} t| | &y)zMerge the annotations from tokens_old into tokens_new, when the tokens in the new document already existed in the old document. abequalN)InsensitiveSequenceMatcher get_opcodescopy_annotations) tokens_old tokens_newscommandscommandi1i2j1j2eq_oldeq_news r r>r>ys_ #Z:>A}}H#+-RR g 2&F2&F VV , -r ct|t|k(sJt||D]\}}|j|_y)zN Copy annotations from the tokens listed in src to the tokens in dest N)lenziprN)srcdestsrc_tokdest_toks r rWrWsB s8s4y   d^1%001r c|dg}|ddD]W}|js8|djs)|dj|jk(r t||G|j |Y|S)zl Combine adjacent tokens when there is no HTML between the tokens, and they share an annotation rrN)pre_tags post_tagsrNcompress_merge_backappend)rHrIrOs r r?r?sk Qi[Fabz 2J((r %%7  , MM#   Mr rHc |d}t|tust|tur|j|y||jz|z}t||j|j |j}|j |_||d<y)zY Merge tok into the last element of tokens (modifying the list of tokens in-place). rkrlrmtrailing_whitespaceN)typetokenrorrrlrmrN)rHrOlastr%mergeds r rnrns ":D Dz$s)5"8 cd...4t $ !$+.+B+BD!OOr r c#K|D]^}|jEd{|j}|||j|jz}||jEd{`y7O7 w)zz Serialize the list of tokens into a list of text chunks, calling markup_func around text to add annotations. N)rlhtmlrNrrrm)rH markup_funcrtrxs r r@r@sg #>>!!zz|4!1!12U5N5NN ??"" #! #s"A+A'AA+A) A+)A+ct|}t|}t||} dj|j}t|S#tt f$r!}t |d}Yd}~t|Sd}~wwxYw)a Do a diff of the old and new document. The documents are HTML *fragments* (str/UTF8 or unicode), they are not complete documents (i.e., no tag). Returns HTML with and tags added around the appropriate text. Markup is generally ignored, with the markup from new_html preserved, and possibly some markup from old_html (though it is considered acceptable to lose some of the old markup). Only the words in the HTML are diffed. The exception is tags, which are treated like words, and the href attribute of tags, which are noted inside the tag itself when there are changes. r<N)rMhtmldiff_tokensrArB ValueError TypeErrorprintfixup_ins_del_tags)old_htmlnew_htmlold_html_tokensnew_html_tokensrIexcs r r#r#sz"x(Ox(O _o >F&&( f %%  " c  f %%sAA> A99A>cPt||}|j}g}|D]v\}}}}} |dk(r |jt||| d.|dk(s|dk(rt||| } t | ||dk(s|dk(s]t|||} t | |xt ||S)z] Does a diff on the tokens themselves, returning a list of text chunks (not tokens). rQrTT)rTinsertr3delete)rUrVextend expand_tokens merge_insert merge_deletecleanup_delete) html1_tokens html2_tokensrZr[rIr\r]r^r_r` ins_tokens del_tokenss r r{r{s" #\\BA}}H F#+ -RR g  MM- R(;4H I  h 'Y"6&|Br':;J V , h 'Y"6&|Br':;J V , -6 Mr c#K|D]W}|jEd{|r |js|j|jz|jEd{Yy7H7 w)zeGiven a list of tokens, return a generator of the chunks of text for the data in the tokens. N)rlhide_when_equalrxrrrm)rHrTrts r rrs\#>>!!E11**,!:!:: :??"" #! #s"A$A AA$A"A$"A$rEctt|D]\}}|Dcgc]}|d }}|dk(rv|r!|djds |dxxdz cc<|jd|j ||djdr |ddd|d<|jd|j |ycc}w)z| doc is the already-handled document (as a list of text chunks); here we add ins_chunks to the end of that. rrSrk zNz )group_by_first_itemmark_unbalancedendswithror) ins_chunksrEbalanced marked_chunksitemchunkss r rr s$7z7R#S-&34d$q'44 s?3r7++C0B3 JJw  JJv 2w$b'#2,B JJy ! JJv 4s B<chunkc|ddk7ryd}t|D]0\}}|dk(rd}|dk(r|||cS|js+|||cS||dS)Nrr+r<r/r,r-) enumerateisspace)r start_posr5r4s r tag_name_of_chunkr+st  Qx3I5!&2 9I 3Y1% % ZZ\1% % &  r cJ|jdddjdS)Nrrz<>/)splitrB)rs r rr@s#{{4#A&,,U33r c eZdZy) DEL_STARTNrrrrr r rrGr rc eZdZy)DEL_ENDNrrr r rrIrr rcz|jt|j||jty)z Adds the text chunks in del_chunks to the document doc (another list of text chunks) with marker to show it is a delete. cleanup_delete later resolves these markers into tags.N)rorrr) del_chunksrEs r rrMs( JJyJJzJJwr rct|}d} |jt|}|jt|dz}dx}}dx}}t ||dz|} | D]\} } | dk7rnw|dz }t | } t|dz|D]S} || tur<|| }|ddk7s|ddk(rSt |}|dk(re|dk7s Jd||| k7r{|dz }Ut| D]x\} } | d k7rnn|dz }t | }t|dz d d D]I} || tur=|| }|ddk(r |ddk7rTt |}|dk(s|dk(rk||k7rr|dz }Kz ||z }t|dz||zdzD]} || ||<|dz }|r'||dz jd s||dz xxd z cc<d ||<|dz }t||zdz||z D]} || ||<|dz }||dz jd r||dz d d ||dz <d||<|dz }t||z |D]} || ||<|dz }||||zdz=|}>#t$rYy wxYw)a Cleans up any DEL_START/DEL_END markers in the document, replacing them with . To do this while keeping the document valid, it may need to drop some tags (either start or end tags). It may also move the del into adjacent tags to try to move it to a similar location where it was originally located (e.g., moving a delete into preceding
tag, if the del looks like (DEL_START, 'Text
', DEL_END) rrusr+rinsdelzUnexpected delete tag: uerkrzNz ) rdindexrrr|rrr2reversedr)r chunk_countr del_startdel_endshift_end_leftshift_start_rightunbalanced_startunbalanced_enddeleted_chunksr del_chunkunbalanced_start_namer5rnameunbalanced_end_nameposs r rrWs_f+KI  ; Y :I ll7IM:G-..*,-->( ! G)DE$2 ' Hi4  ! $5i$@ !719k2 '!9 )q 8s?eAh#o(/5=u}I(?y&II}00!Q&!! '  '2$,N#; $ Hi4 a N"3I"> 9q="b1 $!9'q 8s?uQx3(/5=DEM..!# $  $, ,.(y1}i2C&Ca&GH A )F3K 1HC  vcAg//4 37Os "Os  qy#33a7>9QR A )F3K 1HC  #'? # #C ($S1Wocr2F37Os  qw/9 A )F3K 1HC  3#44q88 9 a    sI IIcg}g}|D]}|jds|jd|f)t|}|tvr|jd|fP|ddk(r|r~|j \}}}||k(r<|jd|f|j ||jd|f|}d}n)|jd|f|j ||}|r~||jd|f|j|||fg}|r=|j \}}}|jd|f|j ||}|r=|S)Nr+rSrrrr) startswithror empty_tagspopr) r tag_stackmarkedrr start_name start_chunkparentsrs r rrsiI F "$ MM3, '  ' :  MM3, '  8s?3<==?0 K%NNC#56NN6*NNC<0$F ENND+#67NN6*$F   tUm,   dE62 3FE"J "+--/;k*+v  Mr c(eZdZdZdZddZdZdZy)rta8 Represents a diffable token, generally a word that is displayed to the user. Opening tags are attached to this token when they are adjacent (pre_tags) and closing tags that follow the word (post_tags). Some exceptions occur when there are empty tags adjacent to a word, so there may be close tags in pre_tags, or open tags in post_tags. We also keep track of whether the word was originally followed by whitespace, even though we do not want to treat the word as equivalent to a similar word that does not have a trailing space.FNcltj||}||ng|_||ng|_||_|Sr)str__new__rlrmrr)clsr%rlrmrrobjs r rz token.__new__)s;kk#t$#+#7xR %.%:  "5 r c dtj|d|jd|jd|jd S)Nztoken(, ))r__repr__rlrmrrr s r rztoken.__repr__2s. LL  t~~t?W?WY Yr ct|Sr)rrs r rxz token.html6s 4yr NNr<)rrr__doc__rrrrxrr r rtrts OYr rtc(eZdZdZ ddZdZdZy) tag_tokenz Represents a token that is actually a tag. Currently this is just the tag, which takes up visible space just like a word but is only represented in a document by a tag. Ncvtj|td||||}||_||_||_|S)Nz: rq)rtrrstagdata html_repr)rrrrrlrmrrrs r rztag_token.__new__?sJmmCD6D6!2%-&/0CE!  r c d|jd|jd|jd|jd|jd|j d S)Nz tag_token(rz , html_repr=z , post_tags=z , pre_tags=z, trailing_whitespace=r)rrrrlrmrrrs r rztag_token.__repr__Js8 HH II NN MM NN  $ $ & &r c|jSr)rrs r rxztag_token.htmlRs ~~r r)rrrrrrrxrr r rr9s55946 &r rceZdZdZdZdZy) href_tokenzh Represents the href in an anchor tag. Unlike other words, we only show the href when it changes. Tc d|zS)Nz Link: %srrs r rxzhref_token.html\s T!!r N)rrrrrrxrr r rrUs(O"r rc~tj|r|}n t|d}t|d|}t |S)ak Parse the given HTML and returns token objects (words with attached tags). This parses only the content of a page; anything in the head is ignored, and the and elements are themselves optional. The content is then parsed by lxml, which ensures the validity of the resulting parsed document (though lxml may make incorrect guesses when the markup is particular bad). and tags are also eliminated from the document, as that gets confusing. If include_hrefs is true, then the href attribute of
tags is included as a special kind of diffable token.Tcleanup)skip_tagrL)r iselement parse_html flatten_el fixup_chunks)rxrLbody_elrs r rMrM`s: tT40 $m LF  r c6|r t|}t|dS)a Parses an HTML fragment, returning an lxml element. Note that the HTML will be wrapped in a
tag that was not in the original document. If cleanup is true, make sure there's no or , and get rid of any and tags. T) create_parent) cleanup_htmlr )rxrs r rrysD! t4 88r z z zct|}|r||jd}t|}|r|d|j}t d|}|S)z This 'cleans' the HTML, meaning that any page structure is removed (only the contents of are used, if there is any and tags are removed. Nr<) _search_bodyend_search_end_bodystart_replace_ins_del)rxmatchs r rrsS  E EIIKL! T "E NU[[]# B %D Kr cHt|j}|d|||dfS)zP This function takes a word, such as 'test ' and returns ('test',' ') rN)rdrstrip)wordstripped_lengths r split_trailing_whitespacers.$++-(O / "D)9$: ::r c g}d}g}|D]-}t|trq|ddk(r:|d}t|d\}}td||||}g}|j |n.|ddk(r&|d}t ||d }g}|j |t |r0t|\}}t||| }g}|j |t|r|j |t|rF|r|j ||sJd |d |d |d ||jj |.J|std|gS|djj||S)zM This function takes a list of chunks and produces a list of tokens. Nrimgrr,)rrlrrhrefr)rlrrzWeird state, cur_word=z , result=z , chunks=z of r<)rlrk) isinstancetuplerrroris_wordrt is_start_tag is_end_tagrmr) r tag_accumcur_wordrIrrfrrrrs r rrsIH F$ eU #Qx5 Ah+DU1X+N(($UC3.79LN  h'qV#Qx%dYTWX  h'  5>)B5)I &E&UYL_`HI MM( # %   U #    '989x""))%0 5I$L b9-..r ##I. Mr )address blockquotecenterdirdivdlfieldsetformh1h2h3h4h5h6hrisindexmenunoframesnoscriptolppretableul) dddtframesetlitbodytdtfootththeadtrc#bK|s<|jdk(r d|jdt|fn t||jtvr$|jst |s |j syt|j}|D]}t||D]}t||Ed{|jdk(r(|jdr|rd|jdf|s7t|t|j }|D]}t|yy7ww)a Takes an lxml element el, and generates all the text chunks for that tag. Each start tag is a chunk, each word is a chunk, and each end tag is a chunk. If skip_tag is true, then the outermost container tag is not returned (just its contents).rrfNrKrRr) rget start_tagrr%rdtail split_wordsr6rend_tag)elrLr start_wordsrchild end_wordss r rrs   66U?"&&-27 7B-  vvBGGCGBGGbgg&K $ Be=AAAB vv}Mrvvf~&& bk(  $Dd# # $  BsB3D/5D-6A8D/z \S+(?:\s+|$)cD|r|jsgSt|}|S)z_ Splits some text into words. Includes trailing whitespace on each word when appropriate. )rB _find_words)r%wordss r r,r,#s# tzz|  E Lr z ^[ \t\n\r]c dj|jjDcgc]\}}d|dt|dc}}}d|j|dScc}}w)z= The text representation of the start tag for a tag. r<rz="r/r+r-)rAattribitemsr6r)r.rr attributess r r*r*.sj99??, D% D6K&'q)Jrvvhzl! $$ sA c`|j}|r t|rdnd}d|jd|S)zg The text representation of an end tag for a tag. Includes trailing whitespace when appropriate. rr<r?s r rrBs >>$ r cL|jdxr|jd S)Nr+r:r>r?s r rrEs" >>#  ;s~~d';#;;r cPt|d}t|t|d}|S)z Given an html string, move any or tags inside of any block-level elements, e.g. transform

word

to

word

FrT) skip_outer)r_fixup_ins_del_tagsserialize_html_fragment)rxrEs r rrHs) T5 )C "34 8D Kr ct|tr Jd|tj|dd}|r;||j ddzd}|d|j d}|j S|S) z Serialize a single lxml element as HTML. The serialized form includes the elements tail. If skip_outer is true, then don't serialize the outermost tag z1You should pass in an element, not a string like rxunicode)methodencodingr-rNr+)rrrtostringfindrfindrB)r.rCrxs r rErEQs| "c"D ;B6BD " >>"Vi @DDIIcN1$%&$TZZ_%zz| r ct|jddD]5}t|st||j|j 7y)z?fixup_ins_del_tags that works on an lxml document in-place rr)rN)listiter_contains_block_level_tag_move_el_inside_blockrdrop_tag)rEr.s r rDrDdsE388E5)*(, bbff- r c6|jtD]}yy)zPTrue if the element contains any block-level elements, like

, , etc. TF)rOany_block_level_tag)r.s r rPrPps%bgg*+ r cz|j}|jtD]}||usnB||}|j|_d|_|j t||g|ddyt |D]}t |rKt|||js'||}|j|_d|_|j|Y||}|j|||j||jr3||}|j|_d|_|jd|yy)zt helper for _fixup_ins_del_tags; actually takes the etc tags and moves them inside any block-level tags. Nr) makeelementrOrTr%rrNrPrQr+addnextr3ror) r.rrVblock_level_el children_tagr0tail_tag child_tagtext_tags r rQrQys$..K!"''#67   #   #3' GG DH%1b $ $U + !% -zz&s+ %  !  h'#C(I JJui (   U # $ wws#  !X r c|j}|j}|j}|r3t|s |xsd|z}n|djxsd|z|d_|j |}|rC|j }||jxsd|z|_n|jxsd|z|_|j |||dzy)z Removes an element, but merges its contents into its place, e.g., given

Hi there!

, if you remove the element you get

Hi there!

r<rkNr) getparentr%r+rdr getprevious getchildren)r.parentr%r+rpreviouss r _merge_element_contentsrcs \\^F 77D 77D 2wJB$&Db6;;,"4BrFK LL E >>#  !;;,"4FK%]]0bD8HMNN,F5qr c>eZdZdZdZej defdZy)rUzt Acts like SequenceMatcher, but tries not to find very small equal blocks amidst large spans of changes r,r'c tt|jt|j}|j}t||dz}t j |}|Dcgc]}|d|kDs|ds|c}Scc}w)Nr0r,)minrdrS thresholdrget_matching_blocks)r sizergactualrs r rhz.InsensitiveSequenceMatcher.get_matching_blockssy"%c$&&k3tvv;"?'+~~  419-  44T:!' 7Y&Aw   s'BN) rrrrrgcythonr rNrhrr r rUrUs+ I \\ T  r rU__main__) _diffcommand))z&z<z>z"z')F)T)brk ImportErrorrr<rdifflibinspect isfunctionget_close_matches"cython.cimports.lxml.html._difflibrr itertools functoolsoperatorrelxmlr lxml.htmlr r!__all__partialgroupby itemgetterrr rrr6rxr7r:r"r=r>rWr?rNrnr@r#r{rrrrrrrrrtrrrMrcompileISsearchrrsubrrrrr frozensetrblock_level_tagsblock_level_container_tagssortedrTrUfindallr3r,rr;r*r-rrrrrErDrPrQrcfinalrrUrrmmainrr r rs2  ,%w'334 Z\ \B  ) J ''i'' (9(9?Rx?R?RST?UVcU_b&*$#1&#P -1     #"&8%P#$<SS$444    $H4HV2t22jCB8"" 2 9rzz,RTT 299 2::mRTT"$$Y7>>2::12449=AA ;2lV^^It 7 !6>>)Y8.6,V^^Iy B 8 %fnnUE&1133-4 $6bjj"$$/77 # =177%!# <&  F-0   & z&LK::]F", ??+,s"M:4N:NNN65N6