Ë
    ÛÓ^jös  ã            	       óø  — d Z ddlZddlZddlZddlmZ ddlmZ ddlm	Z	m
Z
mZmZmZ ddlmZ ddlmZmZ dd	lmZ eeeef      eeeeeef      z  eeeeef         z  eeeeeef         z  Zeedz  eedz  eedz  eedz     z     z     z     Z G d
„ de	d¬«      Z G d„ ded¬«      Z G d„ de
d¬«      Ze G d„ de«      «       Zdeeeeef   dedeeef   fd„Zdededefd„Z d„ Z!d„ Z"d„ Z#dd„Z$dgZ%y) zProcessor class for KOSMOS-2.é    Né   )ÚBatchFeature)Ú
ImageInput)ÚImagesKwargsÚProcessingKwargsÚProcessorMixinÚ
TextKwargsÚUnpack)Ú
AddedToken)ÚBatchEncodingÚ	TextInput)Úauto_docstringc                   ó<   — e Zd ZU dZedz  ed<   eed<   edz  ed<   y)ÚKosmos2ImagesKwargsa¯  
    bboxes (`Union[list[tuple[int]], list[tuple[float]], list[list[tuple[int]]], list[list[tuple[float]]]]`, *optional*):
        The bounding bboxes associated to `texts`.
    num_image_tokens (`int`, *optional* defaults to 64):
        The number of (consecutive) places that are used to mark the placeholders to store image information.
        This should be the same as `latent_query_num` in the instance of `Kosmos2Config` you are using.
    first_image_token_id (`int`, *optional*):
        The token id that will be used for the first place of the subsequence that is reserved to store image
        information. If unset, will default to `self.tokenizer.unk_token_id + 1`.
    NÚbboxesÚnum_image_tokensÚfirst_image_token_id)Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ú
NestedListÚ__annotations__Úint© ó    úy/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/models/kosmos2/processing_kosmos2.pyr   r   '   s$   … ñ	ð ˜ÑÓØÓØ ™*Ô$r   r   F)Útotalc                   ó   — e Zd ZU dZeed<   y)ÚKosmos2TextKwargsz“
    add_eos_token (`bool`, defaults to `False`):
    Whether or not to include `EOS` token id in the encoding when `add_special_tokens=True`.
    Úadd_eos_tokenN)r   r   r   r   Úboolr   r   r   r   r    r    8   s   … ñð
 Ôr   r    c            
       óD   — e Zd ZU eed<   eed<   ddddddddddœ	ddid	œZy
)ÚKosmos2ProcessorKwargsÚtext_kwargsÚimages_kwargsTFr   )	Úadd_special_tokensÚpaddingÚstrideÚreturn_overflowing_tokensÚreturn_special_tokens_maskÚreturn_offsets_mappingÚreturn_token_type_idsÚverboser!   r   é@   )r%   r&   N)r   r   r   r    r   r   Ú	_defaultsr   r   r   r$   r$   A   sC   … Ø"Ó"Ø&Ó&ð #'ØØØ).Ø*/Ø&+Ø%*ØØ"ñ

ð  ð
ñ�Ir   r$   c                   ó>  ‡ — e Zd Zdˆ fd„	Ze	 	 ddedz  deee   z  dee	   de
fd„«       Zd„ Zd	„ Z	 	 	 dd
eee   z  dedz  dededz  deee   z  f
d„Zdd„Zdd„Zed„ «       Zdedeee      eee      z  defd„Zdeeef   eeeeef   z  deeef   fd„Zˆ xZS )ÚKosmos2Processorc                 óì  •— d|_         d| _        d| _        d| _        d| _        d| _        d| _        d| _        d	| _        d
| _	        d| _
        d| _        | j                  | j                  | j                  | j                  | j
                  | j                  | j                  | j                  | j                  | j                  | j                  g| _        || _        t        | j                  «      D �cg c]   }dt        |«      j!                  d«      › d�‘Œ" }}g }| j                  |z   D ]   }|j#                  t%        |ddd¬«      «       Œ" |j'                  |«       t(        ‰	| �U  ||«       yc c}w )zŽ
        num_patch_index_tokens (`int`, *optional*, defaults to 1024):
            The number of tokens that represent patch indices.
        Fz</doc>z<image>z</image>z</chunk>z</line>z<phrase>z	</phrase>z<object>z	</object>ú</delimiter_of_multi_objects/>z<grounding>ú<patch_index_é   ú>T)ÚlstripÚrstripÚ
normalizedN)r-   Ú	eod_tokenÚ	boi_tokenÚ	eoi_tokenÚ	eoc_tokenÚ	eol_tokenÚ	bop_tokenÚ	eop_tokenÚ	boo_tokenÚ	eoo_tokenÚ	dom_tokenÚ	grd_tokenÚ
tag_tokensÚnum_patch_index_tokensÚrangeÚstrÚzfillÚappendr   Ú
add_tokensÚsuperÚ__init__)
ÚselfÚimage_processorÚ	tokenizerrG   ÚkwargsÚxÚpatch_index_tokensÚtokens_to_addÚtokenÚ	__class__s
            €r   rN   zKosmos2Processor.__init__X   sO  ø€ ð
 +0ˆ	Ô'à!ˆŒà"ˆŒØ#ˆŒà#ˆŒØ"ˆŒà#ˆŒØ$ˆŒà#ˆŒØ$ˆŒà9ˆŒà&ˆŒð �N‰NØ�N‰NØ�N‰NØ�N‰NØ�N‰NØ�N‰NØ�N‰NØ�N‰NØ�N‰NØ�N‰NØ�N‰Nð
ˆŒð '=ˆÔ#ÜJOÐPT×PkÑPkÓJlÖmÀQ ¬c°!«f¯l©l¸1«oÐ->¸aÒ@ÐmÐÐmàˆØ—_‘_Ð'9Ñ9ò 	aˆEØ× Ñ ¤¨E¸$ÀuÐY^Ô!_Õ`ð	aà×Ñ˜]Ô+ä‰Ñ˜¨)Õ4ùò ns   Ã4%E1NÚimagesÚtextrR   Úreturnc           
      ó<
  — |€|€t        d«      ‚ | j                  t        fd| j                  j                  i|¤Ž}|d   j                  dd «      }|d   j                  dd«      }|d   j                  dd «      }|d   j                  d	d
«      }|d   d   }	|d   d   }
|d   j                  dd «      }t        «       }|�' | j                  |fi |d   ¤Ž}|j                  |«       |�Í| j                  ||||¬«      }|	rd|sbt        |t        «      r| j                  j                  › |› �}n7t        |t        «      r'|D �cg c]  }| j                  j                  › |› �‘Œ }}|d   d   xr ||d   d<   |€|
nd
|d   d<   |€|nd |d   d<    | j                  dd|i|d   ¤Ž}|j                  |«       |	|d   d<   |
|d   d<   ||d   d<   |�� |��|€| j                  j                  dz   }|	}t!        |«      dz   }t        t#        |||z   «      «      }dgdg|z  z   dgz   }g }g }|d   }t        |t        «      r|g}|d   g|d<   |D ]p  }|d | |z   |||z   d  z   }|j%                  |«       t'        j&                  |«      }|rdg|z   }|dgt)        |«      t)        |«      z
  z  z  }|j%                  |«       Œr t        |t        «      �r×t+        t-        j.                  «      D ��cg c]  \  }}|t)        |«      f‘Œ c}}d„ ¬«      }|d   \  }}|d   \  }}|d   d   xr ||d   d<   d |d   d<    | j                  dd||   gi|d   ¤Ž}t)        |j.                  d   «      }||k7  �r5| j                  j0                  dk(  r‚|D �cg c]+  }|| j                  j2                  g|t)        |«      z
  z  z   ‘Œ- }}|D �cg c]  }|dg|t)        |«      z
  z  z   ‘Œ }}|d   D �cg c]  }|dg|t)        |«      z
  z  z   ‘Œ c}|d<   nš| j                  j0                  dk(  r�|D �cg c]+  }| j                  j2                  g|t)        |«      z
  z  |z   ‘Œ- }}|D �cg c]  }dg|t)        |«      z
  z  |z   ‘Œ }}|d   D �cg c]  }dg|t)        |«      z
  z  |z   ‘Œ c}|d<   t        |t        «      r|€|d   }|d   d   |d<   |d   }|j                  t5        ||d   |dœ|¬«      «       |S c c}w c c}}w c c}w c c}w c c}w c c}w c c}w c c}w )Nz*You have to specify either images or text.Útokenizer_init_kwargsr&   r   r   r/   r   r%   r!   Fr'   r(   Úreturn_tensors)r   rY   é   r   Ú	input_idsÚattention_maskc                 ó   — | d   S ©Néÿÿÿÿr   )rS   s    r   ú<lambda>z+Kosmos2Processor.__call__.<locals>.<lambda>ä   s   € ÐdeÐfhÑdi€ r   )Úkeyrc   ÚrightÚleft)r_   r`   Úimage_embeds_position_mask)ÚdataÚtensor_typer   )Ú
ValueErrorÚ_merge_kwargsr$   rQ   Úinit_kwargsÚpopÚ
setdefaultr   rP   ÚupdateÚpreprocess_examplesÚ
isinstancerI   Ú	bos_tokenÚlistÚunk_token_idr   rH   rK   ÚcopyÚlenÚsortedÚ	enumerater_   Úpadding_sideÚpad_token_idr   )rO   rX   rY   rR   Úoutput_kwargsr   r   r   r!   r'   r(   r]   ÚencodingÚimage_encodingÚsÚtext_encodingÚwith_bosÚstart_indexÚimage_token_idsÚbase_image_embeds_position_maskr_   rh   Úall_input_idsÚtext_idsÚmaskÚidxrS   Úsorted_lengthÚ_Úmin_len_not_paddedÚmax_len_paddeds                                  r   Ú__call__zKosmos2Processor.__call__‰   sY  € ð ˆ>˜d˜lÜÐIÓJÐJà*˜×*Ñ*Ü"ñ
à"&§.¡.×"<Ñ"<ð
ð ñ
ˆð ˜Ñ/×3Ñ3°H¸dÓCˆØ(¨Ñ9×=Ñ=Ð>PÐRTÓUÐØ,¨_Ñ=×AÑAÐBXÐZ^Ó_ÐØ% mÑ4×8Ñ8¸È%ÓPˆà*¨=Ñ9Ð:NÑOÐØ Ñ.¨yÑ9ˆØ& }Ñ5×@Ñ@ÐAQÐSWÓXˆä“>ˆàÐØ1˜T×1Ñ1°&Ñ[¸MÈ/Ñ<ZÑ[ˆNØ�O‰O˜NÔ+àÐØ×+Ñ+¨D°&¸&ÐScÐ+ÓdˆDá!©-Ü˜d¤CÔ(Ø"Ÿn™n×6Ñ6Ð7¸°vÐ>‘DÜ ¤dÔ+ØFJÖKÀ˜tŸ~™~×7Ñ7Ð8¸¸Ò<ÐK�DÐKà˜mÑ,Ð-AÑBÒTÀ}ð ˜-Ñ(Ð)=Ñ>ð BHÀ±gÐUZˆM˜-Ñ(¨Ñ3ØOUÈ~¹^ÐcgˆM˜-Ñ(Ð)9Ñ:Ø*˜DŸN™NÑU°ÐU¸ÀmÑ8TÑUˆMØ�O‰O˜MÔ*à=Oˆ�mÑ$Ð%9Ñ:Ø29ˆ�mÑ$ YÑ/Ø9Gˆ�mÑ$Ð%5Ñ6àÑ Ñ 2à#Ð+Ø'+§~¡~×'BÑ'BÀQÑ'FÐ$ð *ˆHô ˜h›-¨!Ñ+ˆKô #¤5Ð)=Ð?SÐVfÑ?fÓ#gÓhˆOØ/0¨c°Q°CÐ:JÑ4JÑ.JÈaÈSÑ.PÐ+ð ˆIØ)+Ð&Ø$ [Ñ1ˆMä˜$¤Ô$Ø!. �Ø.6Ð7GÑ.HÐ-I�Ð)Ñ*Ø)ò 8�à# L [Ð1°OÑCÀhÈ{Ð]mÑOmÐOoÐFpÑp�Ø× Ñ  Ô*ä—y‘yÐ!@ÓA�Ùà˜3 ™:�Dà˜˜œs 8›}¬s°4«yÑ8Ñ9Ñ9�Ø*×1Ñ1°$Õ7ð8ô ˜$¤Õ%Ü &Ü1:¸=×;RÑ;RÓ1S×T¡v s¨A�cœ3˜q›6’]ÓTÑZiô!�ð )6°aÑ(8Ñ%�Ð%Ø& rÑ*‘��Qà! -Ñ0Ð1EÑFÒXÈ=ð ˜mÑ,Ð-AÑBð BF�˜mÑ,Ð-=Ñ>à . §¡Ñ `°T¸#±Y°KÐ `À=ÐQ^ÑC_Ñ `�Ü!$ ]×%<Ñ%<¸QÑ%?Ó!@�à%¨Ó7Ø—~‘~×2Ñ2°gÒ=ØluÖ$vÐgh Q¨$¯.©.×*EÑ*EÐ)FÈ.Ô[^Ð_`Ó[aÑJaÑ)bÓ%bÐ$v˜	Ð$vàIcö6ØDE˜A   ~¼¸A»Ñ'>Ñ ?Ó?ð6Ð2ð 6ð JRÐRbÑIcö6ØDE˜A   ~¼¸A»Ñ'>Ñ ?Ó?ò6˜Ð!1Ò2ð Ÿ™×4Ñ4¸Ò>ØluÖ$vÐgh d§n¡n×&AÑ&AÐ%BÀnÔWZÐ[\ÓW]ÑF]Ñ%^ÐabÓ%bÐ$v˜	Ð$vàIcö6ØDE˜Q˜C >´C¸³FÑ#:Ñ;¸aÓ?ð6Ð2ð 6ð JRÐRbÑIcö6ØDE˜Q˜C >´C¸³FÑ#:Ñ;¸aÓ?ò6˜Ð!1Ñ2ô
 ˜$¤Ô$¨Ð)?Ø% a™L�	Ø-5Ð6FÑ-GÈÑ-J�Ð)Ñ*Ø-GÈÑ-JÐ*ð �O‰OÜà%.Ø*2Ð3CÑ*DØ6Pñð
 !/ôô	ð ˆùòK Lùój Uùò %wùò6ùò6ùò %wùò6ùò6s0   Å!S5Ë/S:
Î0T ÏTÏ,T
Ð,0TÑ"TÒTc                 ó@  — |€yt        |t        «      st        d«      ‚|D ]{  }|€Œt        |t        «      s|g}|D ]^  }t        |t        «      rBt	        |«      dk(  rt        d„ |D «       «      rŒ4t	        |«      dk(  rt        d„ |D «       «      rŒUt        d«      ‚ Œ} y)aÚ  
        Check `bboxes` for a single text example. It could be
            - `None`: no bounding box associated to a text.
            - A list with each element being the bounding boxes associated to one `<phrase> ... </phrase>` pair found
              in a text. This could be:
                  - `None`: no bounding box associated to a `<phrase> ... </phrase>` pair.
                  - A tuple of 2 integers: A single bounding box specified by patch indices.
                  - A tuple of 4 float point number: A single bounding box specified by (normalized) coordinates.
                  - A list containing the above 2 tuple types: Multiple bounding boxes for a
                   `<phrase> ... </phrase>` pair.
        Nz@`bboxes` (for a single text example) should be `None` or a list.é   c              3   ó<   K  — | ]  }t        |t        «      –— Œ y ­w©N)rr   r   ©Ú.0rS   s     r   ú	<genexpr>zAKosmos2Processor._check_bboxes_for_single_text.<locals>.<genexpr>/  s   è ø€ Ò.SÀa¬z¸!¼S×/AÑ.Sùó   ‚r6   c              3   ó<   K  — | ]  }t        |t        «      –— Œ y ­wr‘   )rr   Úfloatr’   s     r   r”   zAKosmos2Processor._check_bboxes_for_single_text.<locals>.<genexpr>0  s   è ø€ Ò1XÈ1´*¸QÄ×2FÑ1Xùr•   a'  Each element in `bboxes` (for a single text example) should be either `None`, a tuple containing 2 integers or 4 float point numbers, or a list containing such tuples. Also make sure the arguments `texts` and `bboxes` passed to `preprocess_text` are both in batches or both for a single example.)rr   rt   rk   Útuplerw   Úall)rO   r   ÚbboxÚelements       r   Ú_check_bboxes_for_single_textz.Kosmos2Processor._check_bboxes_for_single_text  s«   € ð ˆ>ØÜ˜F¤DÔ)ÜÐ_Ó`Ð`ð ò 	ˆDØˆ|ØÜ ¤dÔ+Ø�v�Øò 
�Ü! '¬5Ô1Ü˜“\ QÒ&¬3Ñ.SÈ7Ô.SÕ+SÜ˜G›¨Ò)¬cÑ1XÐPWÔ1XÕ.Xä$ð@óð ñ
ñ	r   c                 ó\   — |j                  «       }|�|› d|› �}| j                  ||«      }|S )Nú )ÚstripÚ_insert_patch_index_tokens)rO   rY   Úimager   Úimg_info_tokenss        r   Ú_preprocess_single_examplez+Kosmos2Processor._preprocess_single_example9  s=   € Ø�z‰z‹|ˆØÐà%Ð& a¨ vÐ.ˆDð ×.Ñ.¨t°VÓ<ˆØˆr   Útextsr   r   c                 ó   — | j                   g|z  }dj                  | j                   g|z   | j                  gz   «      }d}t        |t        «      rd}|g}|€dgt        |«      z  }nt        |t        «      s|g}t        |«      t        |«      k7  r$t        dt        |«      › dt        |«      › d�«      ‚|s| j                  |«       |g}nE|�4t        |t        «      st        d«      ‚|D ]  }| j                  |«       Œ ndgt        |«      z  }t        |«      t        |«      k7  r$t        d	t        |«      › dt        |«      › d�«      ‚t        |||«      D �	�
�cg c]  \  }	}
}| j                  |	|
||«      ‘Œ }}
}	}|s|d
   }|S c c}}
}	w )a-  Add image and bounding box information to `texts` as image and patch index tokens.

        Args:
            texts (`Union[TextInput, list[TextInput]]`): The texts to be processed.
            images (`ImageInput`, *optional*): The images associated to `texts`.
            bboxes (`Union[list[tuple[int]], list[tuple[float]], list[list[tuple[int]]], list[list[tuple[float]]]]`, *optional*):
                The bounding bboxes associated to `texts`.
            num_image_tokens (`int`, *optional*, defaults to 64):
                The number of image tokens (used as latent queries). This should corresponds to the `latent_query_num`
                attribute in `Kosmos2Config`.

        Returns:
            `Union[TextInput, list[TextInput]]`: The processed texts with image and patch index tokens.
        rž   TFNzGThe number of examples in `texts` and `images` should be the same. Got ú v.s. ú	 instead.zS`bboxes` should be `None` or a list (as a batch) when `texts` is passed as a batch.zGThe number of examples in `texts` and `bboxes` should be the same. Got r   )r<   Újoinr=   rr   rI   rw   rt   rk   rœ   Úzipr£   )rO   r¤   rX   r   r   Ú
img_tokensr¢   ÚbatchedrS   rY   r¡   rš   Úresults                r   rq   z$Kosmos2Processor.preprocess_examplesC  sÐ  € ð, —n‘nÐ%Ð(8Ñ8ˆ
ØŸ(™( D§N¡NÐ#3°jÑ#@ÀDÇNÁNÐCSÑ#SÓTˆð ˆÜ�eœSÔ!ØˆGØ�GˆEàˆ>Ø�Vœc %›jÑ(‰FÜ˜F¤DÔ)Ø�XˆFÜˆu‹:œ˜V›Ò$ÜØYÔZ]Ð^cÓZdÐYeÐekÔloÐpvÓlwÐkxð  yBð  Cóð ñ Ø×.Ñ.¨vÔ6Ø�X‰FØÐÜ˜f¤dÔ+Ü Ð!vÓwÐwØò 6�Ø×2Ñ2°1Õ5ñ6ð �Vœc %›jÑ(ˆFäˆv‹;œ#˜e›*Ò$ÜØYÔZ]Ð^cÓZdÐYeÐekÔloÐpvÓlwÐkxð  yBð  Cóð ô &)¨°¸Ó%?÷
ð 
á!��e˜Tð ×+Ñ+¨D°%¸¸ÕOð
ˆò 
ñ
 Ø˜A‘YˆFàˆùô
s   ÅF	c                 ó\   — |j                  | j                  «      d   }|rt        |«      S |S rb   )Úsplitr=   Ú+clean_text_and_extract_entities_with_bboxes)rO   rY   Úcleanup_and_extractÚcaptions       r   Úpost_process_generationz(Kosmos2Processor.post_process_generation…  s,   € Ø—*‘*˜TŸ^™^Ó,¨RÑ0ˆÙÜ>¸wÓGÐGØˆr   c                 óx   —  | j                   |fd|i|¤Ž}|D �cg c]  }| j                  |d¬«      ‘Œ c}S c c}w )aÈ  
        Post-process the output of the model to decode the text.

        Args:
            generated_outputs (`torch.Tensor` or `np.ndarray`):
                The output of the model `generate` function. The output is expected to be a tensor of shape `(batch_size, sequence_length)`
                or `(sequence_length,)`.
            skip_special_tokens (`bool`, *optional*, defaults to `True`):
                Whether or not to remove special tokens in the output. Argument passed to the tokenizer's `batch_decode` method.
            **kwargs:
                Additional arguments to be passed to the tokenizer's `batch_decode method`.

        Returns:
            `list[str]`: The decoded text.
        Úskip_special_tokensF)r°   )Úbatch_decoder²   )rO   Úgenerated_outputsr´   rR   Úgenerated_textsrY   s         r   Úpost_process_image_text_to_textz0Kosmos2Processor.post_process_image_text_to_text‹  sH   € ð  ,˜$×+Ñ+Ð,=ÑqÐSfÐqÐjpÑqˆØZiÖjÐRV�×,Ñ,¨TÀuÐ,ÕMÒjÐjùÒjs   š7c                 ól   — | j                   j                  }| j                  j                  }||z   dgz   S )Nrh   )rQ   Úmodel_input_namesrP   )rO   Útokenizer_input_namesÚimage_processor_input_namess      r   rº   z"Kosmos2Processor.model_input_namesž  s9   € à $§¡× @Ñ @ÐØ&*×&:Ñ&:×&LÑ&LÐ#Ø$Ð'BÑBÐFbÐEcÑcÐcr   c                 óþ  — |�t        |«      dk(  r|S t        t        j                  d|¬«      «      }t        |«      t        |«      k7  r$t	        dt        |«      › dt        |«      › d�«      ‚d}g }t        ||«      D ]É  \  }}|j                  «       \  }}	|j                  |||	 «       |	}|€Œ2t        |t        «      r|g}g }
t        d„ |D «       «      st	        d«      ‚|D ],  }| j                  |«      \  }}|
j                  |› d	|› �«       Œ. t        |
«      dk(  rŒ¤d
j                  |
«      }|j                  d|› d�«       ŒË |t        |«      k  r|j                  ||d  «       dj                  |«      }|S )Nr   z<phrase>.+?</phrase>)ÚstringzuThe number of elements in `bboxes` should be the same as the number of `<phrase> ... </phrase>` pairs in `text`. Got r¦   r§   c              3   ó$   K  — | ]  }|d u–— Œ
 y ­wr‘   r   )r“   Úboxs     r   r”   z>Kosmos2Processor._insert_patch_index_tokens.<locals>.<genexpr>¾  s   è ø€ Ò7¨3�s $”Ñ7ùs   ‚zTThe multiple bounding boxes for a single phrase should not contain any `None` value.rž   z  </delimiter_of_multi_objects/> z	<object> z
 </object>Ú )rw   rt   ÚreÚfinditerrk   r©   ÚspanrK   rr   r˜   r™   Ú#_convert_bbox_to_patch_index_tokensr¨   )rO   rY   r   Úmatched_phrasesÚcurr_posÚbufferÚmatchedrš   rŠ   ÚendÚpatch_index_stringsrÀ   Úpatch_index_1Úpatch_index_2Úposition_strs                  r   r    z+Kosmos2Processor._insert_patch_index_tokens¤  sÖ  € Øˆ>œS ›[¨AÒ-ØˆKäœrŸ{™{Ð+BÈ4ÔPÓQˆÜˆÓ¤3 v£;Ò.Üð Hô  ILð  M\ó  I]ð  H^ð  ^dô  ehð  ioó  epð  dqð  qzð  {óð ð ˆØˆÜ  °&Ó9ò 	@‰MˆG�TØ—\‘\“^‰FˆAˆsØ�M‰M˜$˜x¨Ð,Ô-ØˆHàˆ|Øä˜$¤Ô&Ø�v�Ø"$ÐäÑ7°$Ô7Ô7Ü Øjóð ð ò O�Ø/3×/WÑ/WÐX[Ó/\Ñ,�˜}Ø#×*Ñ*¨m¨_¸A¸m¸_Ð+MÕNðOô Ð&Ó'¨1Ò,ØØ=×BÑBÐCVÓWˆLØ�M‰M˜I l ^°:Ð>Õ?ð/	@ð2 ”c˜$“iÒØ�M‰M˜$˜x˜y˜/Ô*à�w‰w�v‹ˆØˆr   rš   c                 ó  — t        |«      dk(  r|\  }}n7t        t        j                  | j                  «      «      }t        ||«      \  }}dt        |«      j                  d«      › d�}dt        |«      j                  d«      › d�}||fS )Nr�   r5   r6   r7   )rw   r   ÚmathÚsqrtrG   Úcoordinate_to_patch_indexrI   rJ   )rO   rš   Úidx_1Úidx_2Únum_patches_per_sideÚtoken_1Útoken_2s          r   rÅ   z4Kosmos2Processor._convert_bbox_to_patch_index_tokensÑ  sŒ   € ô ˆt‹9˜Š>Ø‰LˆE‘5ô $'¤t§y¡y°×1LÑ1LÓ'MÓ#NÐ Ü4°TÐ;OÓP‰LˆE�5à!¤# e£*×"2Ñ"2°1Ó"5Ð!6°aÐ8ˆØ!¤# e£*×"2Ñ"2°1Ó"5Ð!6°aÐ8ˆà˜ÐÐr   )i   )NN)NNr/   )T)r   r   r   rN   r   r   r   rt   r
   r$   r   r�   rœ   r£   Ú	BboxInputr   rI   rq   r²   r¸   Úpropertyrº   r˜   r—   r    rÅ   Ú__classcell__)rW   s   @r   r2   r2   V   sa  ø„ õ/5ðb ð %)Ø,0ñJà˜TÑ!ðJð ˜$˜y™/Ñ)ðJð Ð/Ñ0ð	Jð
 
òJó ðJòX!òFð %)Ø Ø')ñ@à˜4 	™?Ñ*ð@ð ˜TÑ!ð@ð ð	@ð
  ™*ð@ð 
ˆt�C‰y‰ó@óDókð& ñdó ðdð
+¨sð +¸DÀÀsÁÑ<LÈtÐTYÐZ_ÑT`ÑOaÑ<að +Ðfió +ðZ Ø˜#˜s˜(‘O e¨E°5¸%ÀÐ,FÑ&GÑGð à	ˆs�Cˆx‰÷ r   r2   rš   rÕ   rZ   c                 ó.  — | \  }}}}||kD  r||kD  st        d«      ‚t        j                  ||z  «      }t        j                  ||z  «      }t        j                  ||z  dz
  «      }t        j                  ||z  dz
  «      }	||z  |z   }
|	|z  |z   }|
|fS )a  Convert a bounding box to a pair of patch indices.

    Args:
        bbox (`tuple[float, float, float, float]`):
            The 4 coordinates of the bounding box, with the format being (x1, y1, x2, y2) specifying the upper-left and
            lower-right corners of the box. It should have x2 > x1 and y2 > y1.
        num_patches_per_side (`int`): the number of patches along each side.

    Returns:
        `tuple[int, int]`: A pair of patch indices representing the upper-left patch and lower-right patch.
    zTThe coordinates in `bbox` should be `(x1, y1, x2, y2)` with `x2 > x1` and `y2 > y1`.r^   )rk   rÐ   ÚfloorÚceil)rš   rÕ   Úx1Úy1Úx2Úy2Úul_xÚul_yÚlr_xÚlr_yÚul_idxÚlr_idxs               r   rÒ   rÒ   ã  s¯   € ð Ñ€RˆˆR�à�ŠG˜˜RšÜÐoÓpÐpä�:‰:�bÐ/Ñ/Ó0€DÜ�:‰:�bÐ/Ñ/Ó0€Dä�9‰9�RÐ.Ñ.°Ñ2Ó3€DÜ�9‰9�RÐ.Ñ.°Ñ2Ó3€DàÐ(Ñ(¨4Ñ/€FØÐ(Ñ(¨4Ñ/€Fà�6ˆ>Ðr   ræ   rç   c                 ó"  — d|z  }| |z  }| |z  }||z  }||z  }| |k(  r||z  }||z  }	||z  |z   }
||z  |z   }nQ||k(  s||k(  r||z  }||z  }	||z  |z   }
||z  |z   }n,||z  |dz  z   }||z  |dz  z   }	||z  |dz  z   }
||z  |dz  z   }||	|
|fS )a�  
    Given a grid of length `num_patches_per_side` and the indices of the upper-left and lower-right corners of a
    bounding box, returns the normalized coordinates of the bounding box, in the form (x1, y1, x2, y2).

    Args:
        ul_idx (`int`): the index of the grid cell that corresponds to the upper-left corner of the bounding box.
        lr_idx (`int`): the index of the grid cell that corresponds to the lower-right corner of the bounding box.
        num_patches_per_side (`int`): the number of patches along each side.

    Returns:
        `tuple[float]`: the normalized coordinates of the bounding box, in the form (x1, y1, x2, y2).
    g      ð?r�   r   )ræ   rç   rÕ   Ú	cell_sizerâ   rã   rä   rå   rÞ   rß   rà   rá   s               r   Úpatch_index_to_coordinaterê     s  € ð Ð*Ñ*€Ið Ð(Ñ(€DØÐ)Ñ)€DàÐ(Ñ(€DØÐ)Ñ)€Dð �ÒØ�IÑˆØ�IÑˆØ�IÑ 	Ñ)ˆØ�IÑ 	Ñ)‰Ø	�Š˜ šØ�IÑˆØ�IÑˆØ�IÑ 	Ñ)ˆØ�IÑ 	Ñ)‰à�IÑ 	¨A¡Ñ-ˆØ�IÑ 	¨A¡Ñ-ˆØ�IÑ 	¨A¡Ñ-ˆØ�IÑ 	¨A¡Ñ-ˆàˆr�2�rˆ>Ðr   c           
      ó$  — d}t        j                  || «      }g }|D �]o  }|j                  d«      }|j                  «       \  }}}|s*d}|j                  d«      d   |j                  d«      d   f}|j	                  d«      }	g }
|	D ]À  }t        j
                  d|«      }t        j
                  d|dd «      }|sŒ5|sŒ8|rD|
j                  t        |j                  d«      «      t        |j                  d«      «      f«       Œ~|
j                  t        |j                  d«      «      t        |j                  d«      «      f«       ŒÂ |r|j                  |||
f«       �ŒE|
D ]&  }d|d   › d	|d   › d
�}|j                  |||gf«       Œ( �Œr |S )aÞ  Extract entities contained in `text`. The bounding bboxes is given in the form of patch indices.

    This function is only intended to be used within `clean_text_and_extract_entities_with_bboxes` where further
    processing happens, including converting to normalized coordinates and whitespace character cleaning up.

    Examples:

    ```python
    >>> text = "<grounding> An image of<phrase> a snowman</phrase><object><patch_index_0044><patch_index_0863></object> warming himself by<phrase> a fire</phrase><object><patch_index_0005><patch_index_0911></object>."
    >>> entities = extract_entities_with_patch_indices(text)
    >>> entities
    [(' a snowman', (31, 41), [(44, 863)]), (' a fire', (130, 137), [(5, 911)])]
    ```z™(?:(<phrase>([^<]+)</phrase>))?<object>((?:<patch_index_\d+><patch_index_\d+></delimiter_of_multi_objects/>)*<patch_index_\d+><patch_index_\d+>)</object>r�   Nr   r4   z<patch_index_(\d+)>r^   r5   z><patch_index_r7   )	rÂ   rÃ   rÄ   Úgroupsr®   ÚsearchrK   r   Úgroup)rY   ÚpatternÚmatchesÚentities_with_patch_indicesÚmatchrÄ   Ú
phrase_tagÚphraseÚmatch_contentÚpatch_index_pairsÚentity_bboxesÚpairrS   Úyrš   Úentitys                   r   Ú#extract_entities_with_patch_indicesrû   /  s—  € ð k€Gô �k‰k˜' 4Ó(€Gð #%Ðàó Kˆà�z‰z˜!‹}ˆØ,1¯L©L«NÑ)ˆ
�F˜MÙØˆFà—J‘J˜q“M !Ñ$ e§j¡j°£m°AÑ&6Ð7ˆDð *×/Ñ/Ð0PÓQÐàˆØ%ò 		MˆDä—	‘	Ð0°$Ó7ˆAÜ—	‘	Ð0°$°q°r°(Ó;ˆAâ’QÙØ!×(Ñ(¬#¨a¯g©g°a«j«/¼3¸q¿w¹wÀq»z»?Ð)KÕLà!×(Ñ(¬#¨a¯g©g°a«j«/¼3¸q¿w¹wÀq»z»?Ð)KÕLð		Mñ Ø'×.Ñ.°¸¸mÐ/LÖMà%ò K�à(¨¨a©¨	°ÀÀQÁ¸yÈÐJ�Ø+×2Ñ2°F¸DÀ4À&Ð3IÕJòKð7Kð@ 'Ð&r   c           	      ó®   — | \  }\  }}t        t        j                  dd|d| «      «      }t        t        j                  dd|d| «      «      }|||ff}|S )zfAdjust the positions of the entities in `text` to be relative to the text with special fields removed.ú<.*?>rÁ   N)rw   rÂ   Úsub)rú   rY   Úentity_nameÚstartrÊ   Úadjusted_startÚadjusted_endÚadjusted_entitys           r   Úadjust_entity_positionsr  i  s_   € à &Ñ€K‘�%˜äœŸ™ ¨¨T°&°5¨\Ó:Ó;€NÜ”r—v‘v˜g r¨4°°¨:Ó6Ó7€LØ" ^°\Ð$BÐC€OØÐr   c                 ó”  — | j                  «       }t        | «      t        | j                  «       «      z
  }g }|D ]‰  \  }\  }}}t        |«      t        |j                  «       «      z
  }	t        |«      t        |j                  «       «      z
  }
||z
  |	z   }||z
  |
z
  }|j                  «       }|j	                  |||f|f«       Œ‹ ||fS )z9Remove the spaces around the text and the entities in it.)rŸ   rw   r8   r9   rK   )rY   ÚentitiesÚnew_textÚleading_spacesÚnew_entitiesrÿ   r   rÊ   r   Úentity_name_leading_spacesÚentity_name_trailing_spacess              r   Ú_cleanup_spacesr  s  s×   € à�z‰z‹|€HÜ˜“Y¤ T§[¡[£]Ó!3Ñ3€Nà€LØ-5ò AÑ)ˆ‘\�e˜S 6Ü%(¨Ó%5¼¸K×<NÑ<NÓ<PÓ8QÑ%QÐ"Ü&)¨+Ó&6¼¸[×=OÑ=OÓ=QÓ9RÑ&RÐ#à˜Ñ&Ð)CÑCˆØ�NÑ"Ð%@Ñ@ˆØ!×'Ñ'Ó)ˆà×Ñ˜[¨5°#¨,¸Ð?Õ@ðAð �\Ð!Ð!r   c           	      ó  — t        j                  dd| «      }t        | «      }g }|D ]M  }|dd |d   }}t        || «      }|D �	cg c]  }	t	        |	d   |	d   |«      ‘Œ }
}	|j                  ||
fz   «       ŒO t        ||«      S c c}	w )a�  Remove the tag tokens from `text`, extract entities in it with some cleaning up of white characters.

    Examples:

    ```python
    >>> text = "<grounding> An image of<phrase> a snowman</phrase><object><patch_index_0044><patch_index_0863></object> warming himself by<phrase> a fire</phrase><object><patch_index_0005><patch_index_0911></object>."
    >>> clean_text, entities = clean_text_and_extract_entities_with_bboxes(text)
    >>> clean_text
    'An image of a snowman warming himself by a fire.'

    >>> entities
    [('a snowman', (12, 21), [(0.390625, 0.046875, 0.984375, 0.828125)]), ('a fire', (41, 47), [(0.171875, 0.015625, 0.484375, 0.890625)])]
    ```rý   rÁ   r   r�   r^   )rÂ   rþ   rû   r  rê   rK   r  )rY   rÕ   Úprocessed_textrñ   r  Úitemrú   r   r  rš   Úbboxes_in_coordss              r   r¯   r¯   ˆ  s¦   € ô —V‘V˜G R¨Ó.€Nä"EÀdÓ"KÐØ€HØ+ò ?ˆØ˜a ˜ D¨¡G�ˆÜ1°&¸$Ó?ˆØjpÖqÐbfÔ5°d¸1±g¸tÀA¹wÐH\Õ]ÐqÐÐqà�‰˜Ð+;Ð*=Ñ=Õ>ð?ô ˜>¨8Ó4Ð4ùò	 rs   ÁB)é    )&r   rv   rÐ   rÂ   Úimage_processing_utilsr   Úimage_utilsr   Úprocessing_utilsr   r   r   r	   r
   Útokenization_pythonr   Útokenization_utils_baser   r   Úutilsr   rt   r˜   r   r—   rØ   r   r   r    r$   r2   rÒ   rê   rû   r  r  r¯   Ú__all__r   r   r   ú<module>r     s‰  ðñ $ã Û Û 	å 2Ý %ß bÕ bÝ -ß ?Ý #ð 	ˆˆs�Cˆx‰ÑØ
ˆ5�˜˜u eÐ+Ñ,Ñ-ñ.à
ˆ4��c˜3�h‘Ñ Ñ!ñ"ð ˆ4��e˜U EÐ)Ñ*Ñ+Ñ,ñ-ð 
ð �%˜$‘,  e¨d¡l°T¸%À$¹,ÈÈeÐVZÉlÑI[Ñ:[Ñ5\Ñ&\Ñ!]Ñ]Ñ^€
ô%˜,¨eõ %ô"˜
¨%õ ôÐ-°Uõ ð* ôI �~ó I ó ðI ðX E¨%°¸¸uÐ*DÑ$Eð Ð]`ð ÐejÐknÐpsÐksÑetó ð>( cð (°3ð (Ècó (òZ7'òtò"ó*5ð: Ð
�r   