
    h*                        S r SSKJr  SSKrSSKJr  SSKJrJrJ	r	  SSK
rSSKJr  SSKJs  Js  Jr  SSKJrJr  SSKJrJr  SS	KJrJr  S
/r " S S
\5      rg)zTransforms for text rendering and augmentation on images.

This module provides transforms for adding and manipulating text on images,
including text augmentation techniques like word insertion, deletion, and swapping.
    )annotationsN)Path)	AnnotatedAnyLiteral)AfterValidator)check_bboxesdenormalize_bboxes)check_range_boundsnondecreasing)BaseTransformInitSchemaImageOnlyTransform	TextImagec                     ^  \ rS rSrSr " S S\5      r        S                   SU 4S jjjr\SS j5       r	        SS jr
          SS jrSS	 jr        SS
 jrSU 4S jjrSrU =r$ )r      a  Apply text rendering transformations on images.

This class supports rendering text directly onto images using a variety of configurations,
such as custom fonts, font sizes, colors, and augmentation methods. The text can be placed
inside specified bounding boxes.

Args:
    font_path (str | Path): Path to the font file to use for rendering text.
    stopwords (list[str] | None): List of stopwords for text augmentation.
    augmentations (tuple[str | None, ...]): List of text augmentations to apply.
        None: text is printed as is
        "insertion": insert random stop words into the text.
        "swap": swap random words in the text.
        "deletion": delete random words from the text.
    fraction_range (tuple[float, float]): Range for selecting a fraction of bounding boxes to modify.
    font_size_fraction_range (tuple[float, float]): Range for selecting the font size as a fraction of
        bounding box height.
    font_color (tuple[float, ...]): Font color as RGB values (e.g., (0, 0, 0) for black).
    clear_bg (bool): Whether to clear the background before rendering text.
    metadata_key (str): Key to access metadata in the parameters.
    p (float): Probability of applying the transform.

Targets:
    image, volume

Image types:
    uint8, float32

References:
    doc-augmentation: https://github.com/danaaubakirova/doc-augmentation

Examples:
    >>> import albumentations as A
    >>> transform = A.Compose([
        A.TextImage(
            font_path=Path("/path/to/font.ttf"),
            stopwords=("the", "is", "in"),
            augmentations=("insertion", "deletion"),
            fraction_range=(0.5, 1.0),
            font_size_fraction_range=(0.5, 0.9),
            font_color=(255, 0, 0),  # red in RGB
            metadata_key="text_metadata",
            p=0.5
        )
    ])
    >>> transformed = transform(image=my_image, text_metadata=my_metadata)
    >>> image = transformed['image']
    # This will render text on `my_image` based on the metadata provided in `my_metadata`.

c                  f    \ rS rSr% S\S'   S\S'   S\S'   S\S	'   S\S
'   S\S'   S\S'   S\S'   Srg)TextImage.InitSchemaL   
str | Path	font_pathtuple[str, ...]	stopwordsztuple[str | None, ...]augmentationszgAnnotated[tuple[float, float], AfterValidator(nondecreasing), AfterValidator(check_range_bounds(0, 1))]fraction_rangefont_size_fraction_rangetuple[float, ...]
font_colorboolclear_bgstrmetadata_key N)__name__
__module____qualname____firstlineno____annotations____static_attributes__r"       f/var/www/fran/franai/venv/lib/python3.13/site-packages/albumentations/augmentations/text/transforms.py
InitSchemar   L   s;    ""--
 	

#
 	

 &%r)   r+   c
                   > [         T
U ]  U	S9  Xl        Xl        X@l        X l        [        U5      U l        XPl        X`l	        Xpl
        g )N)p)super__init__r!   r   r   r   listr   r   r   r   )selfr   r   r   r   r   r   r   r!   r-   	__class__s             r*   r/   TextImage.__init__^   sH     	1(","!-0(@%$ r)   c                    U R                   /$ )zGet list of targets that should be passed as parameters to transforms.

Returns:
    list[str]: List containing the metadata key name

)r!   )r1   s    r*   targets_as_paramsTextImage.targets_as_paramst   s     !!""r)   c                6   UR                  5       R                  5        Vs/ s H  oD(       d  M  UPM     nn[        U5      n[        S[	        X&-  5      5      nUS:X  a-  [
        R                  " XWU R                  U R                  5      nO[US:X  a"  [
        R                  " XWU R                  5      nO3US:X  a"  [
        R                  " XWU R                  5      nO[        S5      e[        R                  " SSU5      R                  5       nX:w  a  U$ S$ s  snf )	an  Apply a random text augmentation to the input text.

Args:
    text (str): Original text to augment
    fraction (float): Fraction of words to modify
    choice (Literal["insertion", "swap", "deletion"]): Type of augmentation to apply

Returns:
    str: Augmented text or empty string if no change was made

Raises:
    ValueError: If an invalid choice is provided

   	insertionswapdeletionz?Invalid choice. Choose from 'insertion', 'swap', or 'deletion'.z +  )stripsplitlenmaxintftextinsert_random_stopwordsr   	py_randomswap_random_wordsdelete_random_words
ValueErrorresub)	r1   textfractionchoicewordwords	num_wordsnum_words_to_modifyresult_sentences	            r*   
random_augTextImage.random_aug~   s    ( #'**,"4"4"6?"6$$"6?J	!!S)=%>?[ #;;EX\XfXfhlhvhvwOv#55eRVR`R`aOz!#77TXTbTbcO^__&&sO<BBD"1"9ArA @s
   
DDc                    SSK Jn  [        [        R
                  " U/5      5        [        [        R
                  " U/5      UR                  SS 5      S   nS USS  5       u  ppX-
  nU R                  R                  " U R                  6 nUR                  [        U R                  5      [        X-  5      5      nU R                  (       a  U R                  c  UnO;U R                  R!                  U R                  5      nUc  UOU R#                  USUS	9nU R$                  nXX4UUUUUS
.$ ! [         a  n[        S5      UeSnAff = f)a  Preprocess text metadata for a single bounding box.

Args:
    image (np.ndarray): Input image
    bbox (tuple[float, float, float, float]): Normalized bounding box coordinates
    text (str): Text to render in the bounding box
    bbox_index (int): Index of the bounding box in the original metadata

Returns:
    dict[str, Any]: Processed metadata including font, position, and text information

Raises:
    ImportError: If PIL.ImageFont is not installed

r   )	ImageFontz`ImageFont from PIL is required to use TextImage transform. Install it with `pip install Pillow`.N   c              3  8   #    U  H  n[        U5      v   M     g 7fN)rB   ).0xs     r*   	<genexpr>0TextImage.preprocess_metadata.<locals>.<genexpr>   s     %L6Kc!ff6Ks            ?)rM   )bbox_coords
bbox_indexoriginal_textrK   fontr   )PILrV   ImportErrorr	   nparrayr
   shaperE   uniformr   truetyper    r   rB   r   rM   rS   r   )r1   imagebboxrK   ra   rV   errdenormalized_bboxx_miny_minx_maxy_maxbbox_heightfont_size_fractionrc   augmented_textaugmentationr   s                     r*   preprocess_metadataTextImage.preprocess_metadata   sE   ,	%
 	RXXtf%&.rxx/?RaQRST%L6G6K%L"em!^^33T5R5RS!!#dnn"5s;M;[7\]!!T%7%7%?!N>>001C1CDL%1%9TttUXam?nN__
 "%7$!"$
 	
/  	r	s   D2 2
E<EEc           	        SU;   a  US   OUS   S   nX R                      nU/ :X  a  S/ 0$ [        U[        5      (       a  U/nU R                  R                  " U R
                  6 n[        [        U5      U-  5      nU R                  R                  [        [        U5      5      U5      nU Vs/ s H!  nU R                  X4U   S   XH   S   U5      PM#     n	nSU	0$ s  snf )a  Generate parameters based on input data.

Args:
    params (dict[str, Any]): Dictionary of existing parameters
    data (dict[str, Any]): Dictionary containing input data with image and metadata

Returns:
    dict[str, Any]: Dictionary containing the overlay data for text rendering

rk   imagesr   overlay_datarl   rK   )r!   
isinstancedictrE   ri   r   rB   r@   samplerangerw   )
r1   paramsdatark   metadatarL   num_bboxes_to_modifybbox_indices_to_updatera   r{   s
             r*   get_params_dependent_on_data&TextImage.get_params_dependent_on_data   s    ")DWd8nQ6G))*r>  h%% zH>>))4+>+>?"3x=8#;<!%!6!6uS]7KMa!b 5
4
 $$UZ,@,H(J^_eJfhrs4 	 
 L
 	

s   0(Cc                @    [         R                  " XU R                  S9$ )a  Apply text rendering to the input image.

Args:
    img (np.ndarray): Input image
    overlay_data (list[dict[str, Any]]): List of dictionaries containing text rendering information
    **params (Any): Additional parameters

Returns:
    np.ndarray: Image with rendered text

)r   )rC   render_textr   )r1   imgr{   r   s       r*   applyTextImage.apply   s    "   T]]KKr)   c           	        > [         TU ]  " U/UQ70 UD6nUS    Vs/ s H  nUS   US   US   US   US   S.PM     snUS'   U$ s  snf )aL  Apply the transform and include overlay data in the result.

Args:
    params (dict[str, Any]): Parameters for the transform
    *args (Any): Additional positional arguments
    **kwargs (Any): Additional keyword arguments

Returns:
    dict[str, Any]: Dictionary containing the transformed data and simplified overlay information

r{   r`   rK   rb   ra   r   )r`   rK   rb   ra   r   )r.   apply_with_params)r1   r   argskwargsresoverlayr2   s         r*   r   TextImage.apply_with_params  s     g'@@@ ".1	
 2  '}5!(!9%l3%l3 2	
N 
	
s   !A)r   r   r   r   r   r   r!   r   ))theisinatofrY   )      ?r   )g?g?)r   r   r   Ftextimage_metadatar_   )r   r   r   r   r   z;tuple[Literal['insertion', 'swap', 'deletion'] | None, ...]r   tuple[float, float]r   r   r   r   r   r   r!   r    r-   floatreturnNone)r   z	list[str])rK   r    rL   r   rM   z(Literal['insertion', 'swap', 'deletion']r   r    )
rk   
np.ndarrayrl   z!tuple[float, float, float, float]rK   r    ra   rB   r   dict[str, Any])r   r   r   r   r   r   )r   r   r{   zlist[dict[str, Any]]r   r   r   r   )r   r   r   r   r   r   r   r   )r#   r$   r%   r&   __doc__r   r+   r/   propertyr5   rS   rw   r   r   r   r(   __classcell__)r2   s   @r*   r   r      sY   1f, * &EU\.88B(10!! #! S	!
 ,! #6! &! ! ! ! 
! !, # #"B"B "B 9	"B
 
"BH6
6
 06
 	6

 6
 
6
p$
LLL +L 	L
 
L& r)   )r   
__future__r   rI   pathlibr   typingr   r   r   numpyrf   pydanticr   ,albumentations.augmentations.text.functionalr   rK   
functionalrC   albumentations.core.bbox_utilsr	   r
   albumentations.core.pydanticr   r   (albumentations.core.transforms_interfacer   r   __all__r   r"   r)   r*   <module>r      sF    # 	  * *  # < < K J `-S" Sr)   