
    ZiyC                        S SK JrJrJr  S SK Jr  S SKJr  S SKJr  S SKJ	r	J
r
  S SKJr  S SKJr  S SKrS S	KJrJrJrJr  S SKr\R,                  " S
5      r " S S\5      r " S S\5      rSS\S\\S4   S\4S jjrS\\\4   S\\S4   4S jr " S S\5      r " S S\5      r " S S\5      r S\!S\"4S jr#S r$g)    )UnionListTuple)	TypedDict)	Generator)Transformer)v_argsDiscard)Tree)TokenN)log_htmlrtf_strippinglog_htmlrtf_statelog_htmlrtf_evaluated_charsis_logger_onRTFDEc                   ^    \ rS rSrSr\" SS9S\4S j5       r\S\	S\
\S	4   4S
 j5       rSrg	)StripNonVisibleRTFGroups    zVisits each Token in provided RTF Trees and strips out any RTF groups which are non-visible when de-encapsulated into HTML.
    T)treer   c                    UR                   n[        U5      S:X  a  gUS   nS/n[        U[        5      (       a  UR                  U;   a  U$ S/n[        U[        5      (       a  UR                  U;   a  g/ SQnU R                  U5      nXv;   a  g/ nSn	[        U[        5      (       aO  [        UR                   5      S:w  a6  UR                   S   n
[        U
[        5      (       a  U
R                  S:X  a  Sn	SnU	SL a?  US	   n[        U[        5      (       a%  UR                  S
:X  a  UnUR                  U;   a  U$ gU$ )a  Transformer which aggressively seeks out possible non-visible RTF groups and replaces them with empty strings.

NOTE: Currently deleting all groups that don't have an htmltag. Please file an issue if you find one that should be included in de-encapsulated HTML. I will refine what gets deleted and what is converted based on identified needs for greater functionality or specific issues which need to be addressed.

Args:
        tree: A .rtf group (Tree object) which needs its contents decoded.
r       htmltag_groupmhtmltag_group)s   \contexts	   \colortbls   \fonttblNSTAR_ESCAPET   CONTROLWORD)	childrenlen
isinstancer   dataget_first_controlwordr   typevalue)selfr   r   first_childknown_control_groups known_non_visible_control_groupsnon_visible_control_wordsfirst_controlunderstood_commandsis_star_escaped
first_itemcontrol_wordfirst_tokens                l/var/www/eduai.edurigo.com/question_generate/ques_gen_env/lib/python3.13/site-packages/RTFDE/transformers.pygroupStripNonVisibleRTFGroups.group$   sF    ==x=Aqk /0k4((#77,<+=(k4((#CC %P!228<5
 *,{D))%%&!+$--a0J*e,,??m3&*Od""1+K+u--##}4#.L#))-@@#r   r   returnNc                 v    U  H"  n UR                   S:X  a  UR                  s  $ M$     g! [         a     M4  f = f)zExtracts the first control word from a .rtf group.

Args:
        children: A list of child objects within a .rtf group

Returns:
        The first controlword found in a group. Returns None if no controls words are found.
        r   N)r"   r#   AttributeError)r   is     r/   r!   .StripNonVisibleRTFGroups.get_first_controlwordZ   sF     A66]*77N +   " s   *
88 )__name__
__module____qualname____firstlineno____doc__r	   r   r0   staticmethodr   r   strr!   __static_attributes__r7   r   r/   r   r       sR     3$ 3 3j  s4x  r   r   c                   |   \ rS rSrSrS\S\4S jrS\S\4S jr	S\S\4S jr
S	\S\4S
 jrS\S\4S jrS\S\4S jrS\S\4S jrS\S\4S jrS\4S jrS	\S\4S jrS\S\4S jrS\S\4S jrS\S\4S jrS\S\4S jrS\S\4S jrS\S\4S jrS\S\4S jrS\S\4S jrS\S\4S jrS\S\4S jrSrg )!
RTFCleanerl   zVisits each Token in provided RTF Trees. Converts all tokens that need converting. Deletes all tokens that shouldn't be visible. And, joins all strings that are left into one final string.
    argsr2   c                 $    SR                  U5      $ )zJoins the .rtf object's string representations together at highest level object `start`.

This is the final string combination. r   joinr$   rC   s     r/   startRTFCleaner.startp   s     xx~r   stringc                 6    UR                   b  UR                   $ g)z*Convert a string object into a raw string.r   r#   r$   rJ   s     r/   STRINGRTFCleaner.STRINGv   s    <<#<<r   c                     UR                   $ NrL   rM   s     r/   
SPACE_SAVERTFCleaner.SPACE_SAVE|   s    ||r   stringsc                 $    SR                  U5      $ )zGConvert all string objects withing a string group into a single string.r   rE   r$   rT   s     r/   rJ   RTFCleaner.string   s     xx  r   grpc                     / nU H4  n[        U[        [        5      5      (       a  M#  UR                  U5        M6     SR	                  U5      $ )z&Join the strings in all group objects.r   )r   r"   r
   appendrF   )r$   rX   _new_childrenr5   s       r/   r0   RTFCleaner.group   sD    A!T']++$$Q'	 
 xx&&r   c                 Z    U Vs/ s H	  o"c  M  UPM     nnSR                  U5      $ s  snf )z_Join the all the strings in an .rtf object into a single string representation of the document.r   rE   )r$   rC   r5   s      r/   documentRTFCleaner.document   s)    14a41xx~ 2s   ((c                     g)zDelete all open parens.r   r7   rG   s     r/   	OPENPARENRTFCleaner.OPENPAREN       r   c                     g)zDelete all closed parens.r   r7   rG   s     r/   
CLOSEPARENRTFCleaner.CLOSEPAREN   rc   r   c                     [         $ )zProcess MHTMLTAG groups

        Currently discarding because they don't need to be processed.

Returns:
        Always returns a discard object.r
   rG   s     r/   r   RTFCleaner.mhtmltag_group   s	     r   c                 $    SR                  U5      $ )zYHTMLTAG processing.

Takes any string values within an HTMLTAG and returns them.
        r   rE   rV   s     r/   r   RTFCleaner.htmltag_group   s    
 xx  r   htmltagc                     g)zDelete all HTMLTAG objectsr   r7   )r$   rl   s     r/   HTMLTAGRTFCleaner.HTMLTAG   rc   r   charc                     g)zDelete all star escape objectsr   r7   )r$   rp   s     r/   r   RTFCleaner.STAR_ESCAPE   s     r   symbolsc                 $    SR                  U5      $ )z7Join all visible symbols from in control symbol groups.r   rE   )r$   rs   s     r/   control_symbolRTFCleaner.control_symbol   s    xx  r   c                 "    SR                  5       $ )z8Convert non-breaking spaces into visible representation.    encoderG   s     r/   NONBREAKING_SPACERTFCleaner.NONBREAKING_SPACE        !!r   c                 "    SR                  5       $ )z9Convert non-breaking hyphens into visible representation.   ­ry   rG   s     r/   NONBREAKING_HYPHENRTFCleaner.NONBREAKING_HYPHEN   r}   r   c                 "    SR                  5       $ )z8Convert hyphen control char into visible representation.u   ‧ry   rG   s     r/   OPTIONAL_HYPHENRTFCleaner.OPTIONAL_HYPHEN   r}   r   c                     g)a  Convert a formula character into an empty string.

If we are attempting to represent formula characters the scope for this library has grown too inclusive. This was only used by Word 5.1 for the Macintosh as the beginning delimiter for a string of formula typesetting commands.r   r7   rG   s     r/   FORMULA_CHARACTERRTFCleaner.FORMULA_CHARACTER        r   c                     g)zProcess index subentry items

Discard index sub-entries. Because, we don't care about indexes when de-encapsulating at this time.r   r7   rG   s     r/   INDEX_SUBENTRYRTFCleaner.INDEX_SUBENTRY   r   r   c                 R    SSSS.nUR                  UR                  S5      nUb  U$ g)zzConvert encoded chars which are mis-categorized as control symbols into their respective chars. Delete all the other ones.   {   }   \)s   \{s   \}s   \\Nr   )getr#   )r$   rC   rs   replacements       r/   CONTROLSYMBOLRTFCleaner.CONTROLSYMBOL   s9     

 kk$**d3"r   c                 2   SSSSR                  S5      SR                  S5      SR                  S5      SR                  S5      SR                  S5      S	R                  S5      S
R                  S5      S.
nUR                  UR                  S5      nUb  U$ g)zConvert encoded chars which are mis-categorized as control words into their respective chars. Delete all the other ones.
           
   	u   ‘zutf-8u   ’u   “u   ”u   •u   –u   —)
s   \pars   \tabs   \lines   \lquotes   \rquotes
   \ldblquotes
   \rdblquotes   \bullets   \endashs   \emdashNr   )rz   r   r#   )r$   rC   wordsr   s       r/   r   RTFCleaner.CONTROLWORD   s     !1!1$OOG4$OOG4!1!1!1
 ii

D1"r   r7   N)r8   r9   r:   r;   r<   r   bytesrH   r   rN   rR   rJ   r0   r^   ra   re   r   r   rn   r   ru   r{   r   r   r   r   r   r   r?   r7   r   r/   rA   rA   l   s|   $ 5 U u  5 !d !u !
' '% 'T e 
e  u  4 !T !e !u   % 
!d !u !"e " "
"u " "
"E "e "
e  5 U % E  % r   rA   r   current_stater2   c              #   B  #    Uc  S/nOU/nU R                    H  nSn[        U[        5      (       a  [        X2S   5       H  nUv   M	     M5  [	        U5      nUb  UR                  U5        Uv   MZ  US   SL d  Md  [        S5      SL a  [        U5        Uv   M     g7f)a  Get a list of Tokens which should be suppressed by HTMLRTF control words.


    NOTE: This de-encapsulation supports the HTMLRTF control word within nested groups. The state of the HTMLRTF control word transfers when entering groups and is restored when exiting groups, as specified in [MSFT-RTF].

Returns:
    A list of Tokens which should be suppressed by HTMLRTF control words.
    NFTRTFDE.HTMLRTF_Stripping_logger)r   r   r   get_stripped_HTMLRTF_valuestoggle_htmlrtfrZ   r   r   )r   r   htmlrtf_stackchild
is_htmlrtftoggles         r/   r   r      s      &
eT""5e2=NO P (.J%$$Z0r"d* @ATI)%0 s   A7B="Br   c                 :   [        U [        5      (       a  U R                  S:X  av  U R                  R	                  5       R                  5       n[        U5      S:  a$  US   S:X  a  [        S5      SL a  [        SU 5        g[        S5      SL a  [        S	U 5        gg
)zIdentify if htmlrtf is being turned on or off.

Returns:
    Bool representing if htmlrtf is being enabled or disabled. None if object is not an HTMLRTF token.
HTMLRTFr   r   0z$RTFDE.HTMLRTF_Stripping_state_loggerTOFFFONN)	r   r   r"   r#   decodestripr   r   r   )r   
htmlrtfstrs     r/   r   r     s     %::"++-335JJ!#
2#(= FG4O%e4BCtK!B/r   c                   H   ^  \ rS rSrSrS\\   4U 4S jjrS\4S jrSr	U =r
$ )DeleteTokensFromTreei$  aS  Removes a series of tokens from a Tree.

Parameters:
    tokens_to_delete: A list of tokens to delete from the Tree object. (sets self.to_delete)

Attributes:
    to_delete: A list of tokens to delete from the Tree object.
    delete_start_pos: The starting position for all the identified tokens. Used to identify which tokens to delete.
tokens_to_deletec                    > [         TU ]  5         Xl        U R                   Vs1 s H  o"R                  iM     snU l        gs  snf )zSetup attributes including token start_pos tracking.

Args:
    tokens_to_delete: A list of tokens to delete from the Tree object. (sets self.to_delete)
N)super__init__	to_delete	start_posdelete_start_pos)r$   r   r5   	__class__s      r/   r   DeleteTokensFromTree.__init__/  s5     	)6:nn Enn E Es   Atokenc                    [        S5      SL a  Ub  [        U5        [        U[        5      (       a  UR                  U R
                  ;   a  [        U R                  5       H  u  p#UR                  UR                  :X  d  M!  UR                  UR                  :X  d  M=  UR                  UR                  :X  d  MY  [        S5      SL a  [        U5        U R                  R                  U5        [        s  $    U$ )zDiscard any identified tokens.

Args:
        token: All tokens within the transformed tree.

Returns:
        Returns all non-identified tokens. Returns Discard objects for any identified tokens.
z&RTFDE.HTMLRTF_Stripping_logger_VERBOSETr   )r   r   r   r   r   r   	enumerater   end_posr#   r   popr
   )r$   r   enr5   s       r/   __default_token__&DeleteTokensFromTree.__default_token__9  s     @ATI +E2eU##$"7"77&t~~6EBu6		U]]25;;.'(HITQ1%8**2.& 7 r   )r   r   )r8   r9   r:   r;   r<   r   r   r   r   r?   __classcell__)r   s   @r/   r   r   $  s+    Fe Fu  r   r   c                   B    \ rS rSrSrS\4S jrS\4S jrS\4S jrSr	g)	StripUnusedSpecialCharactersiQ  a  Strip all unused tokens which lark has extracted from the RTF.

These tokens are largely artifacts of the RTF format.

We have to do this because we use the "keep_all_tokens" option in our lark parser. It's better to be explicit then to allow for ambiguity because of the grammar.
    r   c                     [         $ zERemove RTF braces.

Returns:
        Always returns a discard object.rh   r$   r   s     r/   _LBRACE$StripUnusedSpecialCharacters._LBRACEY  	    
 r   c                     [         $ r   rh   r   s     r/   _RBRACE$StripUnusedSpecialCharacters._RBRACE`  r   r   c                     [         $ )zRemove spaces which are not a part of the content

These are mostly spaces used to separate control words from the content they precede.

Returns:
        Always returns a discard object.
        rh   r   s     r/   _SPACE_DELETE*StripUnusedSpecialCharacters._SPACE_DELETEg  s	     r   r7   N)
r8   r9   r:   r;   r<   r   r   r   r   r?   r7   r   r/   r   r   Q  s+    U U 5 r   r   c                   &    \ rS rSrSrS\4S jrSrg)StripControlWordsir  zGVisits each control word and strips the whitespace from around it.
    r   c                 T    UR                  UR                  R                  5       S9nU$ )zStrips the whitespace from around a provided control word.

Args:
        token: A CONTROLWORD token to strip whitespace from.
        rL   )updater#   r   )r$   r   toks      r/   r   StripControlWords.CONTROLWORDv  s&     ll!2!2!4l5
r   r7   N)r8   r9   r:   r;   r<   r   r   r?   r7   r   r/   r   r   r  s     r   r   raw_rtfc                 L   / nSn[         R                  " X 5       Hb  n[        US   5      nUR                  5       S   nXXT-    UR	                  5       UR                  5       S   XT-   US.nUR                  U5        Md     SnSnU H  n	XpXS    -  nU	S   nM     XpUS	 -  nXq4$ )
a  Extracts binary objects from a rtf file.

Parameters:
    raw_rtf: (bytes): It's the raw RTF file as bytes.

Returns:
    A tuple containing (new_raw, found_bytes)
        new_raw: (bytes) A bytes object where any binary data has been removed.
        found_bytes: (list) List of dictionaries containing binary data extracted from the rtf file. Each dictionary includes the data extracted, where it was extracted from in the original rtf file and where it can be inserted back into the stripped output.

    Description of found_bytes dictionaries:

        "bytes": (bytes) The binary data contained which was extracted.
        "ctrl_char": (tuple) Tuple containing the binary control word and its numeric parameter
        "start_pos": (int) The position (in the original raw rtf data) where the binary control word started.
        "bin_start_pos": (int) The position (in the original raw rtf data) where the binary data starts.
        "end_pos": (int) The position (in the original raw rtf data) where the binary data ends.

    Here is an example of what this looks like (by displaying the printable representation so you can see the bytes and then splitting the dict keys on new lines to make it readable.)
        >> print(repr(found_bytes))

        "{'bytes': b'\xf4UP\x13\xdb\xe4\xe6CO\xa8\x16\x10\x8b\n\xfbA\x9d\xc5\xd1C',
          'ctrl_char': (b'\\bin', b'20'),
          'start_pos': 56,
          'end_pos': 83,
          'bin_start_pos': 63}"
    s   (\\bin)([0-9]+)[ ]?   r   r   )r   	ctrl_charr   r   bin_start_posr   r   r   N)refinditerintspangroupsrZ   )
r   found_bytesbyte_finder	matchitemparamr   byte_objnew_rawstart_buffer	new_bytess
             r/   strip_binary_objectsr     s    8 K)K[[6	IaL!!(,$=3FG!*!1!1!3!*!1!!4,2%2	 	8$ 7 GL 	<+(>?? + ! |}%%G!!r   c                 R    US:X  a   U R                  SR                  5       S5      n U $ )Nhtmlrx   s   &nbsp;)replacerz   )contentcontent_types     r/   transform_based_on_content_typer     s(    v//)"2"2"4i@Nr   rQ   )%typingr   r   r   r   collections.abcr   lark.visitorsr   r	   r
   	lark.treer   
lark.lexerr   r   RTFDE.utilsr   r   r   r   logging	getLoggerlogr   rA   boolr   r>   r   r   r   r   r   tupler   r   r7   r   r/   <module>r      s     & %  % % )   	 k k  J{ JXG GRd 5d;K W` :%c	* uT$Y/? $+; +Z; B /"% /"E /"dr   