
    ^j:                       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
Zd dlmZ d dlmZ d dlmZmZ d dlmZ  ej*                  e      ZddZ	 	 	 	 dd	Z	 	 	 	 	 	 dd
ZddZ	 	 	 	 ddZddZ	 	 	 	 	 	 ddZ	 	 	 	 	 	 ddZy)    )annotationsN)chain)AnyUnioncast)CLASS_NAME_DATA_FIELD)polygon_to_maskrle_to_mask)Vectorc                h   | j                   sy | j                  }t        | j                   j                  j                  dd        }d}||k7  r@t        |d   |d   z  |d   |d   z        }|d   |d   |z  z
  dz  |d   |d   |z  z
  dz  f}t        |d         t        |d         }}t        |d   |d   z
        t        |d   |d   z
        }}g }	| j                   j                  j                         j                         }
t        |
j                  d         D ]P  }|
|   }|||||f   }|j                  |k7  rt        j                  ||d   |d   f      }|	j                  |       R t        t        j                  t         j"                     t!        j$                  |	t&                    S )N   )r   r   r      dtype)masks
orig_shapetupledatashapeminintcpunumpyrangecv2resizeappendr   nptNDArraynpbool_asarraybool)yolov8_resultsr   inference_shapepadgaintopleftbottomright	mask_mapsr   imasks                o/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/supervision/detection/utils/internal.pyextract_ultralytics_masksr0      s   **JN0055;;AB?@O
C*$AA.AA.

 Q*Q-$"66!;Q*Q-$"66!;

 CFSQ[C*SV34c/!:LsSTv:U6VEFI  %%))+113E5;;q>" QxCJU
*+::#::dZ]JqM$BCD BHH%rzz)4'HII    c           
     
   | d   st        j                  dt         j                        t        j                  dt         j                        t        j                  dt         j                        ddt        t        j                  dt
              ifS g }g }g }g }g }g }t        | d   d         }t        | d   d         }| d   D ]  }	|	d	   }
|	d
   }|	d   }|	d   }|
|dz  z
  }||dz  z
  }||z   }||z   }|	j                  d      xs |	j                  d      }t        |t              rddhj                  |      sd}|{	 |d   \  }}t        |d   ||f      }||f||fk7  rXt        j                  |j                  t         j                        ||ft        j                         j                  t"              }|~|j1                  ||||g       |j1                  |	d          |j1                  |	d          |j1                  |	d          |j1                         d|	v sb|j1                  |	d          xd|	vrm|j1                  ||||g       |j1                  |	d          |j1                  |	d          |j1                  |	d          d|	v s|j1                  |	d          t3        |	d         dk\  st        j4                  |	d   D cg c]  }|d	   |d
   g c}t              }t7        |||f      j                  t"              }|j1                  ||||g       |j1                  |	d          |j1                  |	d          |j1                  |	d          |j1                  |       d|	v s|j1                  |	d           t3        |      dkD  r%t        j4                  |t         j                        nt        j                  d      }t3        |      dkD  r%t        j4                  |t         j                        nt        j                  d      }t3        |      dkD  r%t        j4                  |t         j                        n$t        j                  dt         j                        }t3        |      dkD  rt        j4                  |      nt        j                  dt
              }t3        |      dkD  rt        j4                  |t"              nd}t3        |      dkD  r%t        j4                  |t         j                        nd}t        |i}||||||fS # t$        t&        t(        t*        f$ r#}t,        j/                  d|       d}Y d}~d}~ww xY wc c}w )a  Parse a Roboflow API or Inference package result into detection arrays.

    The returned ``data`` dict always contains ``CLASS_NAME_DATA_FIELD`` as a
    string-dtype NumPy array. When ``predictions`` is empty, the array has
    shape ``(0,)`` with ``dtype=str``, preserving dtype contracts for callers
    that mix empty and non-empty results.

    Args:
        roboflow_result: Raw dict from the Roboflow REST API or the Inference
            package (after ``.dict()`` serialisation).

    Returns:
        A 6-tuple of ``(xyxy, confidence, class_id, masks, tracker_ids, data)``
        where each array is aligned with the others. ``masks`` and
        ``tracker_ids`` are ``None`` when absent from the predictions.

    Examples:
        >>> from supervision.detection.utils.internal import process_roboflow_result
        >>> result = {"predictions": [], "image": {"width": 100, "height": 100}}
        >>> _, _, _, _, _, data = process_roboflow_result(result)
        >>> data["class_name"].dtype.kind
        'U'
    predictions)r      r   r   Nimagewidthheightxyr   rlerle_masksizecounts)interpolationzQFailed to decode RLE mask payload; falling back to box-only detection. Reason: %sclass_idclass
confidence
tracker_idpoints   )resolution_wh)r    emptyfloat64int64r   strr   get
isinstancedictissubsetr
   r   r   astypeuint8INTER_NEARESTr#   
ValueErrorAssertionErrorKeyError	TypeErrorloggerwarningr   lenarrayr	   ) roboflow_resultxyxyrA   r?   
class_namer   tracker_idsimage_widthimage_height
predictionr8   r9   r6   r7   x_miny_minx_maxy_maxrle_datahwr.   excpointpolygonxyxy_arrconfidence_arrclass_id_arrclass_name_arr	masks_arrtracker_id_arrr   s                                    r/   process_roboflow_resultrp   6   s   B =)HHV2::.HHQbjj)HHQbhh'"BHHQc$:;
 	
 !D JHJ)+EKog.w78Kw/9:L%m4 ==
sOsO7#H%EAIFQJ>>%(FJNN:,F(D)2
 (8
2 H '1"8H#51v>q6lK88::BHH-$l3&)&7&7 fTl	  KKue45OOJz23j12j67LLz)"":l#;<Z'KKue45OOJz23j12j67z)"":l#;<H%&!+hh7A(7KLe%*eCj)LTWG #\'BfTl  KKue45OOJz23j12j67LLz)"":l#;<{==@ -0IMRZZ(rxx?O  36j/A2E2::.288TU; 
 x=1 	*XXarxx(  !$J! 3!39O  (+5zA~d#4  25[1AA1EBHH-4  1F~/VD 	 w )D  ,
   0 Ms   A:T0U/
0U,	U''U,c                     t         j                               t        j                               k(  xr t         fd D              S )z
    Compares the data payloads of two Detections instances.

    Args:
        data_a, data_b: The data payloads of the instances.

    Returns:
        True if the data payloads are equal, False otherwise.
    c              3  V   K   | ]   }t        j                  |   |          " y wN)r    array_equal).0keydata_adata_bs     r/   	<genexpr>z is_data_equal.<locals>.<genexpr>   s)      <58vc{F3K0<s   &)setkeysall)rw   rx   s   ``r/   is_data_equalr~      sA     v{{}V[[]!33  <<B< 9 r1   c                     t         j                               t        j                               k(  xr t         fd D              S )z
    Compares the metadata payloads of two Detections instances.

    Args:
        metadata_a, metadata_b: The metadata payloads of the instances.

    Returns:
        True if the metadata payloads are equal, False otherwise.
    c              3     K   | ]e  }t        |   t        j                        r9t        |   t        j                        rt        j                  |   |         n
|   |   k(   g y wrs   )rK   r    ndarrayrt   )ru   rv   
metadata_a
metadata_bs     r/   ry   z$is_metadata_equal.<locals>.<genexpr>   sm      D 	 z#

3:c?BJJ7 	z#
38
 _
3/	0Ds   A+A.rz   )r   r   s   ``r/   is_metadata_equalr      sH     z !S):%;;  D D A r1   c                   | si S | D cg c]  }t        |j                                c}t        fdD              st        d      | D ]J  }|j	                         D cg c]  }t        |       }}t        t        |            dkD  sAt        d       d   D ci c]  }|g  }}| D ]   }|D ]  }||   j                  ||           " |D ]  }t        d ||   D              r%t        t        j                  ||               ||<   =t        d ||   D              rc||   d   j                  }|dk(  rt        j                  ||         ||<   |dkD  rt        j                  ||         ||<   t        d| d	      t        d
| d       t        t        t         t"        t$        j&                  t        j(                     t        t*           f   f   |      S c c}w c c}w c c}w )a  
    Merges the data payloads of a list of Detections instances.

    Warning: Assumes that empty detections were filtered-out before passing data to
    this function.

    Args:
        data_list: The data payloads of the Detections instances. Each data payload
            is a dictionary with the same keys, and the values are either lists or
            npt.NDArray[np.generic].

    Returns:
        A single data payload containing the merged data, preserving the original data
            types (list or npt.NDArray[np.generic]).

    Raises:
        ValueError: If data values within a single object have different lengths or if
            dictionaries have different keys.
    c              3  .   K   | ]  }|d    k(    ywr   N ru   keys_setall_keys_setss     r/   ry   zmerge_data.<locals>.<genexpr>       Jx=++J   z7All data dictionaries must have the same keys to merge.r   z>All data values within a single object must have equal length.r   c              3  <   K   | ]  }t        |t                y wrs   )rK   listru   items     r/   ry   zmerge_data.<locals>.<genexpr>  s     C$z$%Cs   c              3  P   K   | ]  }t        |t        j                           y wrs   )rK   r    r   r   s     r/   ry   zmerge_data.<locals>.<genexpr>  s     K$D"**-Ks   $&z$Unexpected array dimension for key ''.z!Inconsistent data types for key 'z.'. Only np.ndarray and list types are allowed.)r{   r|   r}   rQ   valuesrW   r   r   r   from_iterablendimr    hstackvstackr   rL   rI   r   r   r   genericr   )	data_listr   valuelengthsrv   merged_datar   r   s          @r/   
merge_datar      s   , 	2;<$S%<MJMJJRSS +/;;=9%3u:99s7|q P  7DA6F"Gs37"GK"G / 	/C##DI.	//  C+c2BCC#E$7$7C8H$IJKK+c:JKKs#A&++Dqy#%99[-=#>C #%99[-=#>C  #GuB!OPP3C5 9% & " S%BJJ 7c BCCDkRRC =
 : #Hs    G&#G+"
G0c                t   | si S | D cg c]  }t        |j                                c}t        fdD              st        d      i }| D ]  }|j	                         D ]  \  }}||vr|||<   ||   }t        |t        j                        rCt        |t        j                        r)t        j                  ||   |      rct        d| d      t        |t        j                        st        |t        j                        rt        d| d      ||   |k7  st        d| d        |S c c}w )aS  
    Merge metadata from a list of metadata dictionaries.

    This function combines the metadata dictionaries. If a key appears in more than one
    dictionary, the values must be identical for the merge to succeed.

    Warning: Assumes that empty detections were filtered-out before passing metadata to
    this function.

    Args:
        metadata_list: A list of metadata dictionaries to merge.

    Returns:
        A single merged metadata dictionary.

    Raises:
        ValueError: If there are conflicting values for the same key or if
        dictionaries have different keys.
    c              3  .   K   | ]  }|d    k(    ywr   r   r   s     r/   ry   z!merge_metadata.<locals>.<genexpr>F  r   r   z;All metadata dictionaries must have the same keys to merge.zConflicting metadata for key: 'z&': {type(value)}, {type(other_value)}.r   )	r{   r|   r}   rQ   itemsrK   r    r   rt   )metadata_listmetadatamerged_metadatarv   r   other_valuer   s         @r/   merge_metadatar   .  sL   ( 	:GHhS)HMJMJJVWW&(O! P"..* 	PJC/)',$)#.K%,K1T~~oc&:EB$9# ?> >  E2::.*["**2U 5cU ;: : 
 #3'50$'Fse2%NOO)	PP. 9 Is    D5c           	        i }| j                         D ]/  \  }}t        |t        j                        r	||   ||<   *t        |t              rt        |t
              r	||   ||<   St        |t              r|D cg c]  }||   	 c}||<   zt        |t        j                        rR|j                  t        k(  r(t        |      D cg c]  \  }}|s	||    c}}||<   |D cg c]  }||   	 c}||<   t        |t              r||   g||<   t        dt        |             t        d| dt        |              |S c c}w c c}}w c c}w )a6  
    Retrieve a subset of the data dictionary based on the given index.

    Args:
        data: The data dictionary of the Detections object.
        index: The index or indices specifying the subset to retrieve.

    Returns:
        A subset of the data dictionary corresponding to the specified index.
    zUnsupported index type: zUnsupported data type for key 'z': )r   rK   r    r   r   slicer   r#   	enumerater   rT   type)r   indexsubset_datarv   r   r-   index_values          r/   get_data_itemr   d  sL    CEKjjl U
UeRZZ($U|Kt$%'#(<C E4(6;#<E!H#<C E2::.;;$&7@7G(%3Q;a(K$ ;@'@Qa'@K$E3'$)%L>C ":4;- HII=cU#d5k]STT)U,  $=( (As   :E
EE&Ec                   t        j                  |j                  j                  |j                  j                  z
  |j                  j
                  |j                  j
                  z
  g      }t        j                  |j                  j                  |j                  j
                  g      }t        t        j                  t         j                     t        j                  || |z
              S )a)  
    Get array of cross products of each anchor with a vector.
    Args:
        anchors: Array of anchors of shape (number of anchors, detections, 2)
        vector: Vector to calculate cross product with

    Returns:
        Array of cross products of shape (number of anchors, detections)
    )r    rX   endr8   startr9   r   r   r   numbercross)anchorsvectorvector_at_zerovector_starts       r/   cross_productr     s     XXJJLL6<<>>)JJLL6<<>>)	
N 88V\\^^V\\^^<=LBII<9O P r1   )r$   r   returnznpt.NDArray[np.bool_] | None)rY   dict[str, Any]r   ztuple[npt.NDArray[np.floating], npt.NDArray[np.floating], npt.NDArray[np.integer], npt.NDArray[np.bool_] | None, npt.NDArray[np.integer] | None, dict[str, npt.NDArray[np.generic]]])rw   .dict[str, npt.NDArray[np.generic] | list[Any]]rx   r   r   r#   )r   r   r   r   r   r#   )r   z4list[dict[str, npt.NDArray[np.generic] | list[Any]]]r   r   )r   zlist[dict[str, Any]]r   r   )r   r   r   z<int | slice | list[int] | npt.NDArray[np.integer | np.bool_]r   r   )r   npt.NDArray[np.number]r   r   r   r   ) 
__future__r   logging	itertoolsr   typingr   r   r   r   r   r    numpy.typingr   supervision.configr   &supervision.detection.utils.convertersr	   r
   supervision.geometry.corer   	getLogger__name__rU   r0   rp   r~   r   r   r   r   r   r   r1   r/   <module>r      s    "   # # 
   4 O ,			8	$!JHQ#QQh:: 
$*:SC:S3:Sz3l%
8%G% 4%P#-3r1   