Ë
    T^(hœ|  ã            
       ó´  — d Z ddlZddlZddlZddl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mZmZmZmZ ddlmZ dd	lmZmZ eeeeef      eeeeeef      eeeeef         eeeeeef         f   Z G d
„ ded¬«      Z G d„ ded¬«      Z G d„ ded¬«      Z 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)ÚListÚOptionalÚTupleÚUnioné   )ÚBatchFeature)Ú
ImageInputÚ
is_batched)ÚImagesKwargsÚProcessingKwargsÚProcessorMixinÚ
TextKwargsÚUnpack)Ú
AddedToken)ÚBatchEncodingÚ	TextInputc                   óD   — e Zd ZU eee      ed<   ee   ed<   ee   ed<   y)ÚKosmos2ImagesKwargsÚbboxesÚnum_image_tokensÚfirst_image_token_idN)Ú__name__Ú
__module__Ú__qualname__r   r   ÚfloatÚ__annotations__Úint© ó    úl/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/transformers/models/kosmos2/processing_kosmos2.pyr   r   %   s%   … Ø�T˜%‘[Ñ!Ó!Ø˜s‘mÓ#Ø" 3™-Ô'r   r   F)Útotalc                   ó   — e Zd ZU ee   ed<   y)ÚKosmos2TextKwargsÚadd_eos_tokenN)r   r   r   r   Úboolr   r   r   r    r#   r#   +   s   … Ø˜D‘>Ô!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'   /   sC   … Ø"Ó"Ø&Ó&ð #'ØØØ).Ø*/Ø&+Ø%*ØØ"ñ

ð  ð
ñ�Ir   r'   c                   óf  ‡ — e Zd ZdZddgZdgZdZdZdˆ fd„	Z	 	 	 	 dde	d	e
eee   f   d
ee   defd„Zd„ Zd„ Z	 	 	 dde
eee   f   de	dedee   de
eee   f   f
d„Zd„ Zd„ Zdd„Zdd„Zed„ «       Zd	ede
eee      eee      f   defd„Z de
eeef   eeeeef   f   deeef   fd„Z!ˆ xZ"S )ÚKosmos2Processora,  
    Constructs an KOSMOS-2 processor which wraps a KOSMOS-2 image processor and a KOSMOS-2 tokenizer into a single
    processor.

    [`Kosmos2Processor`] offers all the functionalities of [`CLIPImageProcessor`] and some functionalities of
    [`XLMRobertaTokenizerFast`]. See the docstring of [`~Kosmos2Processor.__call__`] and [`~Kosmos2Processor.decode`]
    for more information.

    Args:
        image_processor (`CLIPImageProcessor`):
            An instance of [`CLIPImageProcessor`]. The image processor is a required input.
        tokenizer (`XLMRobertaTokenizerFast`):
            An instance of ['XLMRobertaTokenizerFast`]. The tokenizer is a required input.
        num_patch_index_tokens (`int`, *optional*, defaults to 1024):
            The number of tokens that represent patch indices.
    Úimage_processorÚ	tokenizerÚnum_patch_index_tokens)ÚCLIPImageProcessorÚCLIPImageProcessorFastÚAutoTokenizerc                 óì  •— 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 )NFz</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Ú
normalized)r0   Ú	eod_tokenÚ	boi_tokenÚ	eoi_tokenÚ	eoc_tokenÚ	eol_tokenÚ	bop_tokenÚ	eop_tokenÚ	boo_tokenÚ	eoo_tokenÚ	dom_tokenÚ	grd_tokenÚ
tag_tokensr8   ÚrangeÚstrÚzfillÚappendr   Ú
add_tokensÚsuperÚ__init__)
Úselfr6   r7   r8   ÚkwargsÚxÚpatch_index_tokensÚtokens_to_addÚtokenÚ	__class__s
            €r    rV   zKosmos2Processor.__init__[   sM  ø€ Ø*/ˆ	Ô'à!ˆŒà"ˆŒØ#ˆŒà#ˆŒØ"ˆŒà#ˆŒØ$ˆŒà#ˆŒØ$ˆŒà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ÚimagesÚtextrX   Ú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 )a	  
        This method uses [`CLIPImageProcessor.__call__`] method to prepare image(s) for the model, and
        [`XLMRobertaTokenizerFast.__call__`] to prepare text for the model.

        Please refer to the docstring of the above two methods for more information.

        The rest of this documentation shows the arguments specific to `Kosmos2Processor`.

        Args:
            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`.
            add_eos_token (`bool`, defaults to `False`):
                Whether or not to include `EOS` token id in the encoding when `add_special_tokens=True`.
        Nz*You have to specify either images or text.Útokenizer_init_kwargsr)   r   r   r2   r   r(   r$   Fr*   r+   Úreturn_tensors)r   r_   é   r   Ú	input_idsÚattention_maskc                 ó   — | d   S ©Néÿÿÿÿr   )rY   s    r    ú<lambda>z+Kosmos2Processor.__call__.<locals>.<lambda>ø   s   € ÐdeÐfhÑdi€ r   )Úkeyri   ÚrightÚleft)re   rf   Úimage_embeds_position_mask)ÚdataÚtensor_typer   )Ú
ValueErrorÚ_merge_kwargsr'   r7   Úinit_kwargsÚpopÚ
setdefaultr   r6   ÚupdateÚpreprocess_examplesÚ
isinstancerQ   Ú	bos_tokenÚlistÚunk_token_idr   rP   rS   ÚcopyÚlenÚsortedÚ	enumeratere   Úpadding_sideÚpad_token_idr   )!rW   r^   r_   ÚaudioÚvideosrX   Úoutput_kwargsr   r   r   r$   r*   r+   rc   ÚencodingÚimage_encodingÚsÚtext_encodingÚwith_bosÚstart_indexÚimage_token_idsÚbase_image_embeds_position_maskre   rn   Úall_input_idsÚtext_idsÚmaskÚidxrY   Úsorted_lengthÚ_Úmin_len_not_paddedÚmax_len_paddeds!                                    r    Ú__call__zKosmos2Processor.__call__ˆ   sY  € ð8 ˆ>˜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)rx   r   ©Ú.0rY   s     r    ú	<genexpr>zAKosmos2Processor._check_bboxes_for_single_text.<locals>.<genexpr>C  s   è ø€ Ò.SÀa¬z¸!¼S×/AÑ.Sùó   ‚r?   c              3   ó<   K  — | ]  }t        |t        «      –— Œ y ­wr™   )rx   r   rš   s     r    rœ   zAKosmos2Processor._check_bboxes_for_single_text.<locals>.<genexpr>D  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.)rx   rz   rq   Útupler}   Úall)rW   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)rW   r_   Úimager   Úimg_info_tokenss        r    Ú_preprocess_single_examplez+Kosmos2Processor._preprocess_single_exampleM  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        |«      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   )rE   ÚjoinrF   rx   rQ   r}   r
   rq   r£   rz   Úziprª   )rW   r«   r^   r   r   Ú
img_tokensr©   ÚbatchedrY   r_   r¨   r¡   Úresults                r    rw   z$Kosmos2Processor.preprocess_examplesW  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Ô#Ø�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                  |i |¤ŽS )zÃ
        This method forwards all its arguments to PreTrainedTokenizer's [`~PreTrainedTokenizer.batch_decode`]. Please
        refer to the docstring of this method for more information.
        )r7   Úbatch_decode©rW   ÚargsrX   s      r    rµ   zKosmos2Processor.batch_decodeš  s    € ð
 +ˆt�~‰~×*Ñ*¨DÐ;°FÑ;Ð;r   c                 ó:   —  | j                   j                  |i |¤ŽS )z½
        This method forwards all its arguments to PreTrainedTokenizer's [`~PreTrainedTokenizer.decode`]. Please refer to
        the docstring of this method for more information.
        )r7   Údecoder¶   s      r    r¹   zKosmos2Processor.decode¢  s    € ð
 %ˆt�~‰~×$Ñ$ dÐ5¨fÑ5Ð5r   c                 ó\   — |j                  | j                  «      d   }|rt        |«      S |S rh   )ÚsplitrF   Ú+clean_text_and_extract_entities_with_bboxes)rW   r_   Ú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½   )rµ   r¿   )rW   Úgenerated_outputsrÁ   rX   Úgenerated_textsr_   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                 óœ   — | j                   j                  }| j                  j                  }t        t        j                  ||z   «      «      S r™   )r7   Úmodel_input_namesr6   rz   ÚdictÚfromkeys)rW   Útokenizer_input_namesÚimage_processor_input_namess      r    rÆ   z"Kosmos2Processor.model_input_namesÂ  sA   € ð !%§¡× @Ñ @ÐØ&*×&:Ñ&:×&LÑ&LÐ#Ü”D—M‘MÐ"7Ð:UÑ"UÓVÓWÐWr   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>Ú )r}   rz   ÚreÚfinditerrq   r°   ÚspanrS   rx   rŸ   r    Ú#_convert_bbox_to_patch_index_tokensr¯   )rW   r_   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—   r>   r?   r@   )r}   r   ÚmathÚsqrtr8   Úcoordinate_to_patch_indexrQ   rR   )rW   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   )NNNN)NNr2   )T)#r   r   r   Ú__doc__Ú
attributesÚvalid_kwargsÚimage_processor_classÚtokenizer_classrV   r	   r   r   r   r   r'   r   r•   r£   rª   Ú	BboxInputr   r   rQ   rw   rµ   r¹   r¿   rÄ   ÚpropertyrÆ   r   r   r§   rÓ   Ú__classcell__)r]   s   @r    r5   r5   D   s•  ø„ ñð" $ [Ð1€JØ,Ð-€LØLÐØ%€Oõ+5ð^ "Ø26ØØñ`àð`ð �I˜t I™Ð.Ñ/ð`ð Ð/Ñ0ð`ð 
ó`òD!òFð "Ø Ø*,ñ@à�Y  Y¡Ð/Ñ0ð@ð ð@ð ð	@ð
 # 3™-ð@ð 
ˆs�D˜‘Iˆ~Ñ	ó@òF<ò6óókð& ñXó ðXð
+¨sð +¸EÀ$ÀuÈSÁzÑBRÐTXÐY^Ð_dÑYeÑTfÐBfÑ<gð +Ðloó +ðZ Ø˜%  S ™/¨5°¸¸uÀeÐ1KÑ+LÐLÑMð à	ˆs�Cˆx‰÷ r   r5   r¡   rã   r`   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`.rd   )rq   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 functioin 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   r=   z<patch_index_(\d+)>rd   r>   z><patch_index_r@   )	rÐ   rÑ   rÒ   Úgroupsr»   ÚsearchrS   r   Úgroup)r_   ÚpatternÚmatchesÚentities_with_patch_indicesÚmatchrÒ   Ú
phrase_tagÚphraseÚmatch_contentÚpatch_index_pairsÚentity_bboxesÚpairrY   Úyr¡   Úentitys                   r    Ú#extract_entities_with_patch_indicesr  T  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)r}   rÐ   Úsub)r  r_   Úentity_nameÚstartrØ   Úadjusted_startÚadjusted_endÚadjusted_entitys           r    Úadjust_entity_positionsr  Ž  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¦   r}   rA   rB   rS   )r_   ÚentitiesÚnew_textÚleading_spacesÚnew_entitiesr  r  rØ   r   Úentity_name_leading_spacesÚentity_name_trailing_spacess              r    Ú_cleanup_spacesr  ˜  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—   rd   )rÐ   r  r  r  rý   rS   r  )r_   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æ   r|   rÞ   rÐ   Útypingr   r   r   r   Úimage_processing_utilsr   Úimage_utilsr	   r
   Úprocessing_utilsr   r   r   r   r   Útokenization_utilsr   Útokenization_utils_baser   r   r   r   rë   r   r#   r'   r5   rà   rý   r  r  r  r¼   Ú__all__r   r   r    ú<module>r,     s:  ðñ $ã Û Û 	ß /Ó /å 2ß 1ß bÕ bÝ ,ß ?ð Øˆˆs�Cˆx‰ÑØˆˆu�e˜U EÐ)Ñ	*Ñ+Øˆˆe�C˜�H‰oÑ	ÑØˆˆe�E˜5 %Ð'Ñ(Ñ	)Ñ*ð,ñ€	ô(˜,¨eõ (ô"˜
¨%õ "ôÐ-°Uõ ô*A �~ô A ðH E¨%°¸¸uÐ*DÑ$Eð Ð]`ð ÐejÐknÐpsÐksÑetó ð>( cð (°3ð (Ècó (òZ7'òtò"ó*5ð: Ð
�r   