Ë
    ÃÓ^jï*  ã                  ó´   — d Z ddlmZ ddlZddlmZ ddlmZmZm	Z	 ddl
ZddlmZ ddlmc mc mZ ddlmZmZ ddlmZmZ dd	lmZmZ d
gZ G d„ d
e«      Zy)zÛTransforms 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                  óä   ‡ — e Zd ZdZ G d„ de«      Z	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dˆ fd„Zedd„«       Z	 	 	 	 	 	 	 	 dd„Z		 	 	 	 	 	 	 	 	 	 dd„Z
dd„Z	 	 	 	 	 	 	 	 dd	„Zdˆ fd
„Zˆ xZS )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                  ó^   — e Zd ZU ded<   ded<   ded<   ded<   ded	<   d
ed<   ded<   ded<   y)úTextImage.InitSchemaú
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_keyN)Ú__name__Ú
__module__Ú__qualname__Ú__annotations__© ó    úw/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/albumentations/augmentations/text/transforms.pyÚ
InitSchemar   L   s;   … ØÓØ"Ó"Ø-Ó-ð
ó 	
ð
#
ó 	
ð
 &Ó%Ø‹ØÔr%   r'   c
                ó¨   •— t         ‰
| �  |	¬«       || _        || _        || _        || _        t        |«      | _        || _        || _	        || _
        y )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+   zTextImage.__init__^   sV   ø€ ô 	‰Ñ˜1ÐÔØ(ˆÔØ"ˆŒØ,ˆÔØ"ˆŒÜ! -Ó0ˆÔØ(@ˆÔ%Ø$ˆŒØ ˆ�r%   c                ó   — | j                   gS )zŸGet list of targets that should be passed as parameters to transforms.

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

        )r   )r-   s    r&   Útargets_as_paramszTextImage.targets_as_paramst   s   € ð ×!Ñ!Ð"Ð"r%   c                ó   — |j                  «       j                  «       D �cg c]  }|sŒ|‘Œ	 }}t        |«      }t        dt	        ||z  «      «      }|dk(  r-t        j                  ||| j                  | j                  «      }nY|dk(  r"t        j                  ||| j                  «      }n2|dk(  r"t        j                  ||| j                  «      }nt        d«      ‚t        j                  dd|«      j                  «       }||k7  r|S dS c c}w )	a¶  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)	r-   ÚtextÚfractionÚchoiceÚwordÚwordsÚ	num_wordsÚnum_words_to_modifyÚresult_sentences	            r&   Ú
random_augzTextImage.random_aug~   sü   € ð( #'§*¡*£,×"4Ñ"4Ó"6Ö?˜$º$’Ð?ˆÐ?Ü˜“Jˆ	Ü! !¤S¨°IÑ)=Ó%>Ó?Ðà�[Ò Ü#×;Ñ;¸EÐCVÐX\×XfÑXfÐhl×hvÑhvÓw‰OØ�vÒÜ#×5Ñ5°eÐ=PÐRV×R`ÑR`Óa‰OØ�zÒ!Ü#×7Ñ7¸Ð?RÐTX×TbÑTbÓc‰OäÐ^Ó_Ð_äŸ&™&  s¨OÓ<×BÑBÓDˆØ"1°TÒ"9ˆÐA¸rÐAùò @s
   ¡D©Dc                óž  — 	 ddl m} t        t	        j
                  |g«      «       t        t	        j
                  |g«      |j                  dd «      d   }d„ |dd D «       \  }}	}
}||	z
  } | j                  j                  | j                  Ž }|j                  t        | j                  «      t        ||z  «      «      }| j                  r| j                  €|}n=| j                  j!                  | j                  «      }|€|n| j#                  |d|¬	«      }| j$                  }||	|
|f|||||d
œS # t        $ r}t        d«      |‚d}~ww xY w)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  ó2   K  — | ]  }t        |«      –— Œ y ­w©N)r<   )Ú.0Úxs     r&   ú	<genexpr>z0TextImage.preprocess_metadata.<locals>.<genexpr>Á   s   è ø€ Ò%L°¤c¨!§fÑ%Lùs   ‚é   ç      à?)rG   )Úbbox_coordsÚ
bbox_indexÚoriginal_textrE   Úfontr   )ÚPILrO   ÚImportErrorr	   ÚnpÚarrayr
   Úshaper?   Úuniformr   Útruetyper   r   r<   r   rG   rM   r   )r-   ÚimageÚbboxrE   rY   rO   ÚerrÚdenormalized_bboxÚx_minÚy_minÚx_maxÚy_maxÚbbox_heightÚfont_size_fractionr[   Úaugmented_textÚaugmentationr   s                     r&   Úpreprocess_metadatazTextImage.preprocess_metadata¢   sT  € ð,	Ý%ô
 	”R—X‘X˜t˜fÓ%Ô&Ü.¬r¯x©x¸¸Ó/?ÀÇÁÈRÈaÀÓQÐRSÑTÐá%LÐ6GÈÈÐ6KÔ%LÑ"ˆˆu�e˜UØ˜e‘mˆà3˜TŸ^™^×3Ñ3°T×5RÑ5RÐSÐà×!Ñ!¤# d§n¡nÓ"5´sÐ;MÐP[Ñ;[Ó7\Ó]ˆà×!Ò! T×%7Ñ%7Ð%?Ø!‰NàŸ>™>×0Ñ0°×1CÑ1CÓDˆLà%1Ð%9™T¸t¿¹ÈtÐUXÐam¸Ó?nˆNà—_‘_ˆ
ð " 5¨%°Ð7Ø$Ø!Ø"ØØ$ñ
ð 	
øô/ ò 	ÜØróàðûð	ús   ‚D2 Ä2	EÄ;EÅEc           	     ó¶  — d|v r|d   n|d   d   }|| j                      }|g k(  rdg iS t        |t        «      r|g} | j                  j                  | j
                  Ž }t        t        |«      |z  «      }| j                  j                  t        t        |«      «      |«      }|D �cg c]"  }| j                  |||   d   ||   d   |«      ‘Œ$ }	}d|	iS c c}w )aL  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

        rc   Úimagesr   Úoverlay_datard   rE   )r   Ú
isinstanceÚdictr?   ra   r   r<   r:   ÚsampleÚrangero   )
r-   ÚparamsÚdatarc   ÚmetadatarF   Únum_bboxes_to_modifyÚbbox_indices_to_updaterY   rr   s
             r&   Úget_params_dependent_on_dataz&TextImage.get_params_dependent_on_dataÚ   s  € ð ")¨D¡��W’°d¸8±nÀQÑ6Gˆà˜×)Ñ)Ñ*ˆà�rŠ>à ðð ô �h¤Ô%Ø �zˆHà)�4—>‘>×)Ñ)¨4×+>Ñ+>Ð?ˆä"¤3 x£=°8Ñ#;Ó<Ðà!%§¡×!6Ñ!6´u¼SÀ»]Ó7KÐMaÓ!bÐð 5ö
àð ×$Ñ$ U¨H°ZÑ,@ÀÑ,HÈ(ÐS]ÑJ^Ð_eÑJfÐhrÕsð
ˆð 
ð ˜Lð
ð 	
ùò
s   Â)'Cc                óF   — t        j                  ||| j                  ¬«      S )aL  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   )r=   Úrender_textr   )r-   Úimgrr   rw   s       r&   ÚapplyzTextImage.apply   s   € ô" × Ñ   l¸T¿]¹]ÔKÐKr%   c           	     óŽ   •— t        ‰| �  |g|¢­i |¤Ž}|d   D �cg c]  }|d   |d   |d   |d   |d   dœ‘Œ c}|d<   |S c c}w )a„  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

        rr   rX   rE   rZ   rY   r   )rX   rE   rZ   rY   r   )r*   Úapply_with_params)r-   rw   ÚargsÚkwargsÚresÚoverlayr.   s         €r&   r‚   zTextImage.apply_with_params  sy   ø€ ô ‰gÑ'¨Ð@°Ò@¸Ñ@ˆð " .Ñ1ö	
ð ð  ' }Ñ5Ø ™Ø!(¨Ñ!9Ø% lÑ3Ø% lÑ3óò	
ˆˆNÑð ˆ
ùò	
s   œA))ÚtheÚisÚinÚatÚofrR   )ç      ð?rŒ   )gš™™™™™é?gÍÌÌÌÌÌì?)r   r   r   FÚtextimage_metadatarW   )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])rE   r   rF   r�   rG   z(Literal['insertion', 'swap', 'deletion']r�   r   )
rc   ú
np.ndarrayrd   z!tuple[float, float, float, float]rE   r   rY   r<   r�   údict[str, Any])rw   r“   rx   r“   r�   r“   )r   r’   rr   zlist[dict[str, Any]]rw   r   r�   r’   )rw   r“   rƒ   r   r„   r   r�   r“   )r    r!   r"   Ú__doc__r   r'   r+   Úpropertyr0   rM   ro   r|   r€   r‚   Ú__classcell__)r.   s   @r&   r   r      sT  ø„ ñ1ôfÐ,ô ð* &EØU\Ø.8Ø8BØ(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   rC   Úpathlibr   Útypingr   r   r   Únumpyr^   Úpydanticr   Ú,albumentations.augmentations.text.functionalr   rE   Ú
functionalr=   Ú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%   