
    Ng2                         d dl mZmZmZmZmZmZ d dlmZmZ d dl	m	Z	 d dl
ZddlmZmZ ddlmZmZmZmZmZmZmZ  G d d	e          ZdS )
    )ListUnionDictr   AnyOptional)MutableSequenceIterable)copyN   )BaseCoordElementBaseLayoutElement)Interval	RectangleQuadrilateral	TextBlockALL_BASECOORD_ELEMENTSBASECOORD_ELEMENT_NAMEMAPBASECOORD_ELEMENT_INDEXMAPc                   "   e Zd ZdZd#dddee         defdZd Zd Z	d	 Z
d
 Zd Zd Zd Zd Zd Zd Zd Zd Zi dfdZd$ded          fdZi dfdZd Zd%dZd Zd Zd Zd Zdeeef         fd Zdee          fd!Z!d&de"j#        fd"Z$dS )'LayoutaQ  
    The :obj:`Layout` class id designed for processing a list of layout elements
    on a page. It stores the layout elements in a list and the related `page_data`,
    and provides handy APIs for processing all the layout elements in batch. `

    Args:
        blocks (:obj:`list`):
            A list of layout element blocks
        page_data (Dict, optional):
            A dictionary storing the page (canvas) related information
            like `height`, `width`, etc. It should be passed in as a
            keyword argument to avoid any confusion.
            Defaults to None.
    N	page_datablocksr   c                   |Mt          |t                    r|j        j        dk    s(|j        j        dk    rd}nd| d}t	          |          t          |t
                    rt          |          }||ng | _        |pi | _        d S )Nr   zUPlease check the input: it should be lp.Layout([layout]) instead of lp.Layout(layout)zHBlocks should be a list of layout elements or empty (None), instead got z.
)	
isinstancer	   	__class____name__
ValueErrortuplelist_blocksr   )selfr   r   	error_msgs       X/var/www/html/ai-engine/env/lib/python3.11/site-packages/layoutparser/elements/layout.py__init__zLayout.__init__1   s     ^68,, 171A1Jh1V1V (H44t		rgmrrr	Y'''fe$$ 	"&\\F!'!3vv"b    c                     | j         |         }t          |t                    r'|                     | j         |         | j                  S |S Nr   )r!   r   slicer   r   )r"   keyr   s      r$   __getitem__zLayout.__getitem__D   sD    c"c5!! 	>>$,s"3t~>NNNMr&   c                     || j         |<   d S Nr!   )r"   r*   newvalues      r$   __setitem__zLayout.__setitem__K   s    $Sr&   c                     | j         |= d S r-   r.   )r"   r*   s     r$   __delitem__zLayout.__delitem__N   s    Lr&   c                 *    t          | j                  S r-   )lenr!   r"   s    r$   __len__zLayout.__len__Q   s    4<   r&   c              #   &   K   | j         D ]}|V  d S r-   r.   )r"   eles     r$   __iter__zLayout.__iter__T   s,      < 	 	CIIII	 	r&   c                     d                     d t          |                                           D                       }| j        j         d| dS )Nz, c                 "    g | ]\  }}| d | S )= ).0r*   vals      r$   
<listcomp>z#Layout.__repr__.<locals>.<listcomp>Y   s&    PPPcnnsnnPPPr&   ())joinvarsitemsr   r   )r"   info_strs     r$   __repr__zLayout.__repr__X   sP    99PPT$ZZ=M=M=O=OPPPQQ.)77H7777r&   c                 p    t          |t                    r | j        |j        k    o| j        |j        k    S dS )NF)r   r   r!   r   r"   others     r$   __eq__zLayout.__eq__\   s6    eV$$ 	<5=0VT^u5VV5r&   c                    t          |t                    r| j        |j        k    r)|                     | j        |j        z   | j                  S | j        i k    s|j        i k    r0|                     | j        |j        z   | j        p|j                  S t          d| j         d|j         d          t          |t                    r$|                     | j        |z   | j                  S t          d|j        j         d          )Nr   z(Incompatible page_data for two innputs: z vs .zInvalid input type for other )r   r   r   r   r!   r   r    r   rI   s     r$   __add__zLayout.__add__b   s$   eV$$ 	~00~~L5=0DN &    2%%B)>)>~~L5=0"n? &   
 !et~eeSXSbeee   t$$ 	>>$,"6$.>QQQK0HKKK  r&   c                 <    | j                             ||           d S r-   )r!   insert)r"   r*   values      r$   rP   zLayout.insertx   s     C'''''r&   c                 ^    |                      t          | j                  | j                  S r(   )r   r
   r!   r   r5   s    r$   r
   zLayout.copy{   s$    ~~d4<00DN~KKKr&   c                 T    |                      fd| D             | j                  S )Nc                 :    g | ]}|                               S r=   )relative_tor>   r8   rJ   s     r$   r@   z&Layout.relative_to.<locals>.<listcomp>   s%    444S__U##444r&   r   r   r   rI   s    `r$   rU   zLayout.relative_to~   s9    ~~4444t444  
 
 	
r&   c                 T    |                      fd| D             | j                  S )Nc                 :    g | ]}|                               S r=   )condition_onrV   s     r$   r@   z'Layout.condition_on.<locals>.<listcomp>   s'    555Se$$555r&   r   rW   rI   s    `r$   rZ   zLayout.condition_on   s9    ~~5555555  
 
 	
r&   Fc                 \    |                      fd| D             | j                  S )Nc                 >    g | ]}|                               S r=   is_inr>   r8   centerrJ   soft_margins     r$   r@   z Layout.is_in.<locals>.<listcomp>   s)    CCCsSYYuk622CCCr&   r   rW   r"   rJ   ra   r`   s    ```r$   r^   zLayout.is_in   sB    ~~CCCCCCdCCCn  
 
 	
r&   returnc                     |s1|                      t          | j        ||          | j                  S | j                            ||           dS )ap  Sort the list of blocks based on the given

        Args:
            key ([type], optional): key specifies a function of one argument that
            is used to extract a comparison key from each list element.
            Defaults to None.
            reverse (bool, optional): reverse is a boolean value. If set to True,
            then the list elements are sorted as if each comparison were reversed.
            Defaults to False.
            inplace (bool, optional): whether to perform the sort inplace. If set
            to False, it will return another object instance with _block sorted in
            the order. Defaults to False.

        Examples::
            >>> import layoutparser as lp
            >>> i = lp.Interval(4, 5, axis="y")
            >>> l = lp.Layout([i, i.shift(2)])
            >>> l.sort(key=lambda x: x.coordinates[1], reverse=True)

        )r*   reverser   N)r   sortedr!   r   sort)r"   r*   re   inplaces       r$   rg   zLayout.sort   sb    *  	8>>t|g>>>$. "    L#w77777r&   c                 \    |                      fd| D             | j                  S )a:  
        Return a `Layout` object containing the elements that are in the `other` object.

        Args:
            other (:obj:`BaseCoordElement`):
                The block to filter the current elements.

        Returns:
            :obj:`Layout`:
                A new layout object after filtering.
        c                 B    g | ]}|                               |S r=   r]   r_   s     r$   r@   z$Layout.filter_by.<locals>.<listcomp>   s.    JJJSCIIe[&$I$IJSJJJr&   r   rW   rb   s    ```r$   	filter_byzLayout.filter_by   sD     ~~JJJJJJDJJJn  
 
 	
r&   c                 T    |                      fd| D             | j                  S )a  
        Shift all layout elements by user specified amounts on x and y axis respectively. If shift_distance is one
        numeric value, the element will by shifted by the same specified amount on both x and y axis.

        Args:
            shift_distance (:obj:`numeric` or :obj:`Tuple(numeric)` or :obj:`List[numeric]`):
                The number of pixels used to shift the element.

        Returns:
            :obj:`Layout`:
                A new layout object with all the elements shifted in the specified values.
        c                 :    g | ]}|                               S r=   )shift)r>   r8   shift_distances     r$   r@   z Layout.shift.<locals>.<listcomp>   s%    7773SYY~&&777r&   r   rW   )r"   ro   s    `r$   rn   zLayout.shift   s;     ~~7777$7774>  
 
 	
r&   r   Tc                 d    |                      fd| D             | j                  S )a  Pad all layout elements on the four sides of the polygon with the user-defined pixels. If
        safe_mode is set to True, the function will cut off the excess padding that falls on the negative
        side of the coordinates.

        Args:
            left (:obj:`int`, `optional`, defaults to 0): The number of pixels to pad on the upper side of the polygon.
            right (:obj:`int`, `optional`, defaults to 0): The number of pixels to pad on the lower side of the polygon.
            top (:obj:`int`, `optional`, defaults to 0): The number of pixels to pad on the left side of the polygon.
            bottom (:obj:`int`, `optional`, defaults to 0): The number of pixels to pad on the right side of the polygon.
            safe_mode (:obj:`bool`, `optional`, defaults to True): A bool value to toggle the safe_mode.

        Returns:
            :obj:`Layout`:
                A new layout object with all the elements padded in the specified values.
        c           	      B    g | ]}|                               S r=   )pad)r>   r8   bottomleftright	safe_modetops     r$   r@   zLayout.pad.<locals>.<listcomp>   s-    JJJcSWWT5#vy99JJJr&   r   rW   )r"   rt   ru   rw   rs   rv   s    `````r$   rr   z
Layout.pad   sL      ~~JJJJJJJJTJJJn  
 
 	
r&   c                 T    |                      fd| D             | j                  S )a  
        Scale all layout element by a user specified amount on x and y axis respectively. If scale_factor is one
        numeric value, the element will by scaled by the same specified amount on both x and y axis.

        Args:
            scale_factor (:obj:`numeric` or :obj:`Tuple(numeric)` or :obj:`List[numeric]`): The amount for downscaling or upscaling the element.

        Returns:
            :obj:`Layout`:
                A new layout object with all the elements scaled in the specified values.
        c                 :    g | ]}|                               S r=   )scale)r>   r8   scale_factors     r$   r@   z Layout.scale.<locals>.<listcomp>   s%    555SYY|$$555r&   r   rW   )r"   r{   s    `r$   rz   zLayout.scale   s;     ~~5555555  
 
 	
r&   c                      fd| D             S )Nc                 :    g | ]}|                               S r=   )
crop_image)r>   r8   images     r$   r@   z%Layout.crop_image.<locals>.<listcomp>   s%    666#u%%666r&   r=   )r"   r   s    `r$   r~   zLayout.crop_image   s    66666666r&   c                     d | D             S )z
        Iterate through all the text blocks in the list and append their ocr'ed text results.

        Returns:
            :obj:`List[str]`: A list of text strings of the text blocks in the list of layout elements.
        c                 <    g | ]}t          |d           |j        S )text)hasattrr   r>   r8   s     r$   r@   z$Layout.get_texts.<locals>.<listcomp>   s)    AAASGC,@,@AAAAr&   r=   r5   s    r$   	get_textszLayout.get_texts   s     BADAAAAr&   c                      fd| D             S )au  Given user-provided attribute name, check all the elements in the list and return the corresponding
        attribute values.

        Args:
            attr_name (:obj:`str`): The text string of certain attribute name.

        Returns:
            :obj:`List`:
                The list of the corresponding attribute value (if exist) of each element in the list.
        c                 P    g | ]"}t          |          t          |          #S r=   )r   getattr)r>   r8   	attr_names     r$   r@   z#Layout.get_info.<locals>.<listcomp>	  s2    SSSC73	;R;RSY''SSSr&   r=   )r"   r   s    `r$   get_infozLayout.get_info   s      TSSS4SSSSr&   c                 *    | j         d | D             dS )zGenerate a dict representation of the layout object with
        the page_data and all the blocks in its dict representation.

        Returns:
            :obj:`Dict`:
                The dictionary representation of the layout object.
        c                 6    g | ]}|                                 S r=   to_dictr   s     r$   r@   z"Layout.to_dict.<locals>.<listcomp>  s     7V7V7V#7V7V7Vr&   )r   r   r   r5   s    r$   r   zLayout.to_dict  s$     "^7V7VQU7V7V7VWWWr&   c                 8   d}d}| D ]C}t          |t                    r
d}|j        }n|}t          |t          |j                           }Dt          |         j        |rg }| D ]}t          |t                    rEt          |          }|j        j        k    r% t          |j        d                       |_        n5|j        k    r t          |d                       }t          |          }|	                    |           nfd| D             }|S )a6  Convert all elements into blocks of the same type based
        on the type casting rule::

            Interval < Rectangle < Quadrilateral < TextBlock

        Returns:
            List[BaseLayoutElement]:
                A list of base layout elements of the maximal compatible
                type
        FTto_c                 `    g | ]*}|j         k    r t          |d                        n|+S )r   )_namer   )r>   r8   target_coord_names     r$   r@   z1Layout.get_homogeneous_blocks.<locals>.<listcomp>>  s]         9 111 86#46677999  r&   )
r   r   blockmaxr   r   r   r
   r   append)r"   has_textblockmax_coord_levelr8   r   
new_blocksr   s         @r$   get_homogeneous_blockszLayout.get_homogeneous_blocks  sj     
	 
	C#y))  $	!!;EK!H OO 3?CI 	J 	' 	'c9-- +s))Cy*;;;$QGCI7P=N7P7P$Q$Q$S$S	y$555Egc+D1B+D+DEEGG#E**C!!#&&&&	'     	  J r&   c                 t    |r|                                  }n| }t          j        d |D                       }|S )a  Convert the layout object into the dataframe.
        Warning: the page data won't be exported.

        Args:
            enforce_same_type (:obj:`bool`, optional):
                If true, it will convert all the contained blocks to
                the maximal compatible data type.
                Defaults to False.

        Returns:
            pd.DataFrame:
                The dataframe representation of layout object
        c                 6    g | ]}|                                 S r=   r   r   s     r$   r@   z'Layout.to_dataframe.<locals>.<listcomp>Z  s     ;;;S3;;==;;;r&   )r   pd	DataFrame)r"   enforce_same_typer   dfs       r$   to_dataframezLayout.to_dataframeG  sG      	0022FFF\;;F;;;<<	r&   r-   )NFF)r   r   r   r   T)F)%r   
__module____qualname____doc__r   r   r   r%   r+   r0   r2   r6   r9   rG   rK   rN   rP   r
   rU   rZ   r^   rg   rk   rn   rr   rz   r~   r   r   strr   r   r   r   r   r   r   r=   r&   r$   r   r   !   s8        )4 ) ) )x~ )D ) ) ) )&  % % %  ! ! !  8 8 8    ,( ( (L L L
 
 


 
 

 (*% 
 
 
 
8 8hx>P 8 8 8 88 ,.e 
 
 
 
"
 
 
"
 
 
 
*
 
 
 7 7 7B B BT T TXc3h X X X X0->(? 0 0 0 0d r|      r&   r   )typingr   r   r   r   r   collections.abcr   r	   r
   pandasr   baser   r   layout_elementsr   r   r   r   r   r   r   r   r=   r&   r$   <module>r      s   : 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 5 5 5 5 5 5 5 5           5 5 5 5 5 5 5 5                 { { { { {_ { { { { {r&   