
    ^j}                       U d dl mZ d dlZd dlZd dlZd dlZd dlZd dlmZ d dl	m
Z
mZ d dlZd dlm	Z d dlmZmZ d dlmZ d dlmZ d dlmZmZ d d	lmZ d d
lmZ  G d de      Z G d de      Zej@                  e!ejD                  e#ejH                  e!ejJ                  e!ejL                  e!ejN                  e!ejP                  e!ejR                  e#iZ*de+d<   ej@                  dgejD                  dgejH                  ddgejJ                  dgejL                  dgejN                  dgejP                  dgejR                  dgiZ,de+d<   ej@                  ddgejD                  dgejH                  g dejJ                  ddgejL                  ddgejN                  ddgejP                  ddgejR                  dgiZ-de+d<   g dZ.	 	 	 	 	 	 	 	 d'dZ/ ee/dd      d'd       Z0	 d(	 	 	 	 	 	 	 d)dZ1d*dZ2	 d(	 	 	 	 	 	 	 	 	 d+d Z3	 d(	 	 	 	 	 	 	 d)d!Z4	 d(	 	 	 	 	 	 	 d)d"Z5	 	 	 	 	 	 d,d#Z6	 d(	 	 	 	 	 	 	 d)d$Z7	 d(	 	 	 	 	 	 	 d-d%Z8	 	 	 	 	 	 d.d&Z9y)/    )annotationsN)Enum)Anycast)
deprecatedvoid)Image)denormalize_boxes)polygon_to_maskpolygon_to_xyxy)warn_deprecated)_validate_resolutionc                  T    e Zd ZdZdZdZdZdZdZdZ	dZ
d	Zedd
       Zedd       Zy)LMMa  
    Enum specifying supported Large Multimodal Models (LMMs).

    .. deprecated:: 0.27.0
        `LMM` is deprecated and will be removed in `supervision-0.31.0`.
        Use `VLM` instead.

    Attributes:
        PALIGEMMA: Google's PaliGemma vision-language model.
        FLORENCE_2: Microsoft's Florence-2 vision-language model.
        QWEN_2_5_VL: Qwen2.5-VL open vision-language model from Alibaba.        QWEN_3_VL: Qwen3-VL open vision-language model from Alibaba.
        GOOGLE_GEMINI_2_0: Google Gemini 2.0 vision-language model.
        GOOGLE_GEMINI_2_5: Google Gemini 2.5 vision-language model.
        MOONDREAM: The Moondream vision-language model.
    	paligemma
florence_2qwen_2_5_vl	qwen_3_vldeepseek_vl_2
gemini_2_0
gemini_2_5	moondreamc                @    | D cg c]  }|j                    c}S c c}w Nvalueclscs     d/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/supervision/detection/vlm.pylistzLMM.list1       !$%A%%%   c                (   t        d       t        ||       r|S t        |t              r|j                         }	  | |      S t	        dt        |       d| j                   d      # t        $ r  t	        d| d| j                                w xY w)Nzn`LMM` is deprecated since `supervision-0.27.0` and will be removed in `supervision-0.31.0`. Use `VLM` instead.Invalid value: . Must be one of Invalid value type: . Must be an instance of  or str.)r   
isinstancestrlower
ValueErrorr!   type__name__r   r   s     r    
from_valuezLMM.from_value5   s    7	
 eS!LeS!KKMEY5z! "4;-/H||nH&
 	
  Y ?5'9J388:,!WXXYs   A( ()BNreturnz	list[str])r   z	LMM | strr3   r   r/   
__module____qualname____doc__	PALIGEMMA
FLORENCE_2QWEN_2_5_VL	QWEN_3_VLDEEPSEEK_VL_2GOOGLE_GEMINI_2_0GOOGLE_GEMINI_2_5	MOONDREAMclassmethodr!   r1        r    r   r      sY    " IJKI#M$$I& & 
 
rB   r   c                  T    e Zd ZdZdZdZdZdZdZdZ	dZ
d	Zedd
       Zedd       Zy)VLMa   
    Enum specifying supported Vision-Language Models (VLMs).

    Attributes:
        PALIGEMMA: Google's PaliGemma vision-language model.
        FLORENCE_2: Microsoft's Florence-2 vision-language model.
        QWEN_2_5_VL: Qwen2.5-VL open vision-language model from Alibaba.
        QWEN_3_VL: Qwen3-VL open vision-language model from Alibaba.
        GOOGLE_GEMINI_2_0: Google Gemini 2.0 vision-language model.
        GOOGLE_GEMINI_2_5: Google Gemini 2.5 vision-language model.
        MOONDREAM: The Moondream vision-language model.
    r   r   r   r   r   r   r   r   c                @    | D cg c]  }|j                    c}S c c}w r   r   r   s     r    r!   zVLM.list`   r"   r#   c                   t        ||       r|S t        |t              r|j                         }	  | |      S t        dt        |       d| j                   d      # t        $ r  t        d| d| j	                                w xY w)Nr%   r&   r'   r(   r)   )r*   r+   r,   r-   r!   r.   r/   r0   s     r    r1   zVLM.from_valued   s    eS!LeS!KKMEY5z! "4;-/H||nH&
 	
  Y ?5'9J388:,!WXXYs   A )BNr2   )r   	VLM | strr3   rD   r4   rA   rB   r    rD   rD   I   sY     IJKI#M$$I& & 
 
rB   rD   zdict[VLM, type]RESULT_TYPESresolution_whinput_whzdict[VLM, list[str]]REQUIRED_ARGUMENTSclasses)rJ   rI   rL   ALLOWED_ARGUMENTS)
<OD><CAPTION_TO_PHRASE_GROUNDING><DENSE_REGION_CAPTION><REGION_PROPOSAL><OCR_WITH_REGION>#<REFERRING_EXPRESSION_SEGMENTATION><REGION_TO_SEGMENTATION><OPEN_VOCABULARY_DETECTION><REGION_TO_CATEGORY><REGION_TO_DESCRIPTION>c           
        t        | t              r	 t        | j                               } t        |t        |          s!t	        dt        |       dt        |           t        j                  | g       }|D ]  }||vst	        d|        t        j                  | g       }|D ]!  }||vst	        d| d| j                          | S # t        $ r4 t	        d|  dt        D cg c]  }|j
                   nc c}w c}       w xY w)a  
    Validates the parameters and result type for a given Vision-Language Model (VLM).

    Args:
        vlm: The VLM enum or string specifying the model.
        result: The result object to validate (type depends on VLM).
        kwargs: Dictionary of arguments to validate against required/allowed lists.

    Returns:
        The validated VLM enum value.

    Raises:
        ValueError: If the VLM, result type, or arguments are invalid.
    zInvalid vlm value: r&   zInvalid VLM result type: z
. Must be zMissing required argument: z	Argument z is not allowed for )r*   r+   rD   r,   r-   r   rH   r.   rK   getrM   name)vlmresultkwargserequired_argsargallowed_argss          r    _validate_vlm_parametersrb      s.   " #s	ciik"C fl3/0'V~ZS@Q?RS
 	
 '**33M Bf:3%@AAB %((b1L Nl"y-A#((LMMN J)  	%cU*;c<RQWW<R<R;ST 	s   C D	&C:9D	z0.29.0z0.32.0)targetdeprecated_in	remove_inc                    t        | ||      S r   )r   )r[   r\   r]   s      r    validate_vlm_parametersrg      s     VV$$rB   c                   t        |      \  }}t        j                  d      }|j                  |       }|rt	        j
                  |      nt	        j                  d      }|j                  d   dk(  rJt	        j                  d      t	        j                  dt              t	        j                  dt              fS t	        j
                  |ddg df   t              }|j                  t              d	z  t	        j
                  ||||g      z  }t        j                  j                  |ddd
f   j                  t                    }	d}
|gt	        j
                  |	D cg c]  }||v  c}t              }||   }|	|   }	t	        j
                  |	D cg c]  }|j                  |       c}      }
||
|	fS c c}w c c}w )a  
    Parse bounding boxes from paligemma-formatted text, scale them to the specified
    resolution, and optionally filter by classes.

    Args:
        result: String containing paligemma-formatted locations and labels.
        resolution_wh: tuple (width, height) to which we scale the box coordinates.
        classes: Optional list of valid class names. If provided, boxes and labels not
            in this list are filtered out.

    Returns:
        A tuple of `(xyxy, class_id, class_name)` where `xyxy` is an array of
            shape `(n, 4)` in format `[x1, y1, x2, y2]`, `class_id` is an
            optional array of shape `(n,)` with class indices, and `class_name`
            is an array of shape `(n,)` with class labels.
    zK(?<!<loc\d{4}>)<loc(\d{4})><loc(\d{4})><loc(\d{4})><loc(\d{4})> ([\w\s\-]+))r      r   r      r   dtypeN)   r         i   rk   )r   recompilefindallnparrayemptyshapeintr+   floatastypecharstripboolindex)r\   rI   rL   whpatternmatchesmatches_arrxyxy_arr
class_nameclass_idrZ   masks                r    from_paligemmar      sm   (  .DAqjjVG oof%G9@BHHW$5bhhvFVKq xx$c!:BHHQc<RRRxxA|O4EBHs#d*RXXq!Ql-CCH{1a4077<=J(,HxxZ@T@MD>%
88ZHTW]]40HIXz)) A Is   #F<Gc                   	 | j                  d      }|dk(  ry| |d }|j                  d      }|dk(  ry|d|dz    }|j                  d      }|dk(  ry|d|dz    }||dz   d j                         }|j                  d      r|dd j                         }||z   dz   }t	        j
                  |      S # t        $ r Y yw xY w)a  
    Attempt to recover and parse a truncated or malformed JSON snippet from Qwen-2.5-VL
    output.

    This utility extracts a JSON-like portion from a string that may be truncated or
    malformed, cleans trailing commas, and attempts to parse it into a Python object.

    Args:
        text: Raw text containing the JSON snippet possibly truncated or
            incomplete.

    Returns:
        Parsed Python object (usually list) if recovery and parsing succeed;
            otherwise `None`.
    [N}ro   ,])findrfindrstripendswithjsonloads	Exception)textfirst_bracketsnippet
last_brace
prefix_endprefixbodyrepaireds           r    &recover_truncated_qwen_2_5_vl_responser     s     		#B}~&]]3'
*JN+\\#&
):>*zA~'(//1==9##%DD=3&zz(## s"   B3 B3 B3 AB3 3	B?>B?c                   t        |      \  }}t        |      \  }}| j                         }t        j                  dd|t        j                        j                         }t        j                  dd|      j                         }|j                  d      }	|j                  d      }
|	dk7  r |
dk7  r|
|	kD  r||	|
dz    j                         }	 t        j                  |      }t)        |t*              sJt!        j"                  d
      t!        j"                  dt$              t!        j"                  dt&              fS g }g }|D ]C  }t)        |t,              rd|vsd|vr|j/                  |d          |j/                  |d          E |sJt!        j"                  d
      t!        j"                  dt$              t!        j"                  dt&              fS t!        j0                  |t2              }t!        j0                  |t&              }|||||gz  }|||||gz  }d	}|mt!        j0                  |D cg c]  }||v  c}t4              }||   }||   }t!        j0                  |D cg c]  }|j7                  |       c}t$              }|||fS # t        j                  $ r t        |      }||}n}	 t        j                  |      }nf# t        t        t        f$ rO t!        j"                  d
      t!        j"                  dt$              t!        j"                  dt&              fcY cY S w xY wY Sw xY wc c}w c c}w )a  
    Parse and rescale bounding boxes and class labels from Qwen-2.5-VL JSON output.

    The JSON is expected to be enclosed in triple backticks with the format:
      ```json
      [
          {"bbox_2d": [x1, y1, x2, y2], "label": "some class name"},
          ...
      ]
      ```

    Args:
        result: String containing Qwen-2.5-VL JSON bounding box and label data.
        input_wh: Width and height of the coordinate space where boxes
            are normalized.
        resolution_wh: Target width and height to scale bounding boxes.
        classes: Optional list of valid class names to filter results. If provided,
            only boxes with labels in this list are returned.

    Returns:
        A tuple of `(xyxy, class_id, class_name)` where `xyxy` is an array of
            shape `(N, 4)` in `(x_min, y_min, x_max, y_max)` format, `class_id`
            is an optional array of shape `(N,)` with class indices, and
            `class_name` is an array of shape `(N,)` with class names.
    z^```(json)? flagsz```$r   r   r   ro   Nrj   rl   rm   bbox_2dlabel)r   r}   rr   sub
IGNORECASEr   r   r   r   JSONDecodeErrorr   astliteral_evalr-   SyntaxError	TypeErrorru   rw   ry   r+   r*   r!   dictappendrv   rz   r~   r   )r\   rJ   rI   rL   in_win_hout_wout_hr   startenddatar   
boxes_listlabels_listitemxyxyr   r   r   r   s                        r    from_qwen_2_5_vlr   1  s   @ &h/JD$'6LE5<<>D66."d"--@FFHD66'2t$**,DIIcNE
**S/C{sbyS5[EC!G$**,zz$ dD! "((4s";RXXdRU=VWWJK *$%$)>'QUBU$y/*4=)	*  "((4s";RXXdRU=VWW88Je,D+S1J4tT**D5%..DHxxzBe')B$ODz%
88zJeW]]51JRUV:%%W  9$?D''-Y7 HHV$HHT-HHT- L C KsC   J 5L;*M #L88KL8AL1,L80L11L87L8c                     t        | d||      S )a[  
    Parse and scale bounding boxes from Qwen-3-VL style JSON output.

    Args:
        result: String containing the Qwen-3-VL JSON output.
        resolution_wh: Target resolution `(width, height)` to scale bounding boxes.
        classes: Optional list of valid classes to filter results.

    Returns:
        A tuple of `(xyxy, class_id, class_name)` where `xyxy` is an array of
            shape `(N, 4)` in `(x_min, y_min, x_max, y_max)` format scaled to
            `resolution_wh`, `class_id` is an optional array of class indices,
            and `class_name` is an array of class names.
    )  r   )r\   rJ   rI   rL   )r   )r\   rI   rL   s      r    from_qwen_3_vlr     s    & #	 rB   c           	        |\  }}t        j                  d| t         j                        }t        j                  d| t         j                        }t        |      t        |      k7  r$t	        dt        |       dt        |       d      g }g }t        ||      D ]  \  }	}
|	j                         }t        j                  d|
      D ]s  }t        t        |j                  d      j                  d	            \  }}}}|j                  |d
z  |z  |d
z  |z  |d
z  |z  |d
z  |z  g       |j                  |       u  t        j                  |t        j                        }t        j                  |      }|ht        j                  |D cg c]  }||v  c}t              }||   }||   }t        j                  |D cg c]  }|j                  |       c}      }nat!        t#        t%        |                  }t'        |      D ci c]  \  }}||
 }}}t        j                  |D cg c]  }||   	 c}      }|||fS c c}w c c}w c c}}w c c}w )u  
    Parse bounding boxes from deepseek-vl2-formatted text, scale them to the specified
    resolution, and optionally filter by classes.

    The DeepSeek-VL2 output typically contains pairs of <|ref|> ... <|/ref|> labels
    and <|det|> ... <|/det|> bounding box definitions. Each <|det|> section may
    contain one or more bounding boxes in the form [[x1, y1, x2, y2], [x1, y1, x2, y2], ...]
    (scaled to 0..999). For example:

    ```
    <|ref|>The giraffe at the back<|/ref|><|det|>[[580, 270, 999, 904]]<|/det|><|ref|>The giraffe at the front<|/ref|><|det|>[[26, 31, 632, 998]]<|/det|><|end▁of▁sentence|>
    ```

    Args:
        result: String containing deepseek-vl2-formatted locations and labels.
        resolution_wh: Tuple (width, height) to which we scale the box coordinates.
        classes: Optional list of valid class names. If provided, boxes and labels not
            in this list are filtered out.

    Returns:
        A tuple of `(xyxy, class_id, class_name)` where `xyxy` is an array of
            shape `(n, 4)` in format `[x1, y1, x2, y2]`, `class_id` is an
            optional array of shape `(n,)` with class indices, and `class_name`
            is an array of shape `(n,)` with class labels.
    z<\|ref\|>(.*?)<\|/ref\|>r   z<\|det\|>(.*?)<\|/det\|>zNumber of ref tags (z) and det tags (z) in the result must be equal.z	\[(.*?)\]z[]r   i  rm   )rr   rt   Slenr-   zipr}   maprz   splitr   ru   rv   float32r~   r   sortedr!   set	enumerate)r\   rI   rL   widthheightlabel_segmentsdetection_segments	xyxy_listclass_name_listr   detection_blobcurrent_class_nameboxx1y1x2y2r   r   rZ   r   r   unique_classesiclass_to_ids                            r    from_deepseek_vl_2r     s=   : "ME6ZZ ;V244PN$?rttT
>c"455"3~#6"7 8 !3455SU
 	

 $&I!#O!$^5G!H 7~"[[]::lN; 
	7C 		$(=(=c(BCNBB#X%#X&#X%#X&	 ""#56
	77 88IRZZ0D/*JxxZ@T@MDz%
88ZHTW]]40HIS_ 56.7.GH71dtQwHH88:F4[.FG:%% A I IFs   III3Ic                   t        |       dk(  s
J d|         t        t        | j                                     }|t        vrt        | dt               | |   } |dv rFt        j                  | d   t        j                        }t        j                  | d         }||ddfS |d	k(  r.t        j                  | d   t        j                        }|dddfS |d
k(  rt        j                  | d   t        j                        }|j                  ddd      }t        j                  |D cg c]  }t        |       c}      }t        j                  | d         }||d|fS |dv rg }g }| d   D ]  }	|	D ]  }t        j                  |d      j                  t        j                        }t        ||      j                  t              }
|j                  |
       t        |      }|j                  |         t        j                  |t        j                        }t        j                  |      }|d|dfS |dk(  rFt        j                  | d   t        j                        }t        j                  | d         }||ddfS |dv r&t!        | t"              sJ dt%        |               | dk(  r<t        j&                  dt        j                        t        j                  g       ddfS t)        j*                  d      }|j-                  |       }|
J d|         t/        |      \  }}t        j                  |j1                         gt        j                        }|t        j                  ||||g      dz  z  }| d|j3                          }t        j                  |g      }||ddfS t5        d|       c c}w )a  
    Parse results from the Florence 2 multi-model model.
    https://huggingface.co/microsoft/Florence-2-large

    Args:
        result: dict containing the model output
        resolution_wh: (output_width, output_height) to which we rescale the boxes.

    Returns:
        A tuple of `(xyxy, labels, masks, obb_boxes)` where `xyxy` is an array
            of shape `(n, 4)` in format `[x1, y1, x2, y2]`, `labels` is an
            optional array of shape `(n,)` with class labels, `masks` is an
            optional array of shape `(n, h, w)` with segmentation masks, and
            `obb_boxes` is an optional array of shape `(n, 4, 2)` with oriented
            bounding boxes.
    ro   z,Expected result with a single element. Got: z% not supported. Supported tasks are: )rN   rO   rP   bboxesrm   labelsNrQ   rR   
quad_boxesr   rk   rq   )rS   rT   polygons)r   rq   rU   bboxes_labels)rV   rW   z4Expected string as <REGION_TO_CATEGORY> result, got zNo object detected.rj   z,<loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)>z1Expected string to end in location tags, but got r   zUnimplemented task: )r   nextiterkeysSUPPORTED_TASKS_FLORENCE_2r-   ru   rv   r   reshaper   r{   int32r   r~   r   r*   r+   r.   rw   rr   rs   searchr   groupsr   RuntimeError)r\   rI   taskr   r   xyxyxyxypolygonr   
masks_listpolygons_of_same_classr   xyxy_boxmasksr   matchr   r   result_strings                     r    from_florence_2r     s   0 v;!TKF8TTV[[]#$D--f9:T9UV
 	
 D\FRRxxx(

;&*+VT4''""xxx(

;T4%%""88F<0

C##B1-xxJg1JK&*+VT8++RR,.	-/
&,Z&8 	+"1 +**Wg6==bhhG&w>EEdK!!$'*73  *+	+ xx	4$T5$&&,,xxx(

;&12VT4''BB&#& 	
B4<.Q	
& **88F"**5rxx|T4OO**LMv&  	
?xH	
  $M21xx(

;!Q1&--/=/*VT4''
-dV4
55a Ks   ,N?c                ^   t        |      \  }}| j                         }t        |      D ]7  \  }}|dk(  sdj                  ||dz   d       } | j	                  d      d   }  n 	 t        j                  |       }t        |t              sJt        j                  d      t        j                  dt        	      t        j                  dt        	      fS g }	g }
|D ]U  }t        |t              rd
|vsd|vr|	j                  |d          |d
   }|
j                  |d   |d   |d   |d   g       W t!        |
      dk(  rJt        j                  d      t        j                  dt        	      t        j                  dt        	      fS t#        t        j$                  |
t        j&                  	      ||fd      }
t        j$                  |	      }d}|gt        j$                  |D cg c]  }||v  c}t(        	      }|
|   }
||   }t        j$                  |D cg c]  }|j+                  |       c}      }|
||fS # t
        j                  $ rM t        j                  d      t        j                  dt        	      t        j                  dt        	      fcY S w xY wc c}w c c}w )a  
    Parse and scale bounding boxes from Google Gemini style
    [JSON output](https://ai.google.dev/gemini-api/docs/vision?lang=python).

    The JSON is expected to be enclosed in triple backticks with the format:
        ```json
        [
            {"box_2d": [x1, y1, x2, y2], "label": "some class name"},
            ...
        ]
        ```

    For example:
        ```json
        [
            {"box_2d": [10, 20, 110, 120], "label": "cat"},
            {"box_2d": [50, 100, 150, 200], "label": "dog"}
        ]
        ```

    Args:
        result: String containing the JSON snippet enclosed by triple backticks.
        resolution_wh: (output_width, output_height) to which we rescale the boxes.
        classes: Optional list of valid class names. If provided, returned boxes/labels
            are filtered to only those classes found here.

    Returns:
        A tuple of `(xyxy, class_id, class_name)` where `xyxy` is an array of
            shape `(n, 4)` in format `[x1, y1, x2, y2]`, `class_id` is an
            optional array of shape `(n,)` with class indices, and `class_name`
            is an array of shape `(n,)` with class labels.

    ```json
ro   N```r   rj   rl   rm   box_2dr   rp   rq   r   rI   normalization_factor)r   
splitlinesr   joinr   r   r   r   ru   rw   ry   r+   r*   r!   r   r   r   r
   rv   float64r~   r   )r\   rI   rL   r   r   linesr   liner   r   r   r   r   r   r   rZ   r   s                    r    from_google_gemini_2_0r   O  s]   N  .DAqEU# 49YYuQUW~.F\\%(+F	Vzz&! dD!xx$c!:BHHTQT<UUUFD 6$%)=PTATd7m$8nSVSVSVSV456 4yA~xx$c!:BHHTQT<UUU
RZZ(!f!D
 &!JHxxZ@T@MDz%
88ZHTW]]40HI:%%E  Vxx$c!:BHHTQT<UUUV: A Is   %I )J%J*AJ"!J"c           
     V   t        |      \  }}| j                         }t        |      D ]7  \  }}|dk(  sdj                  ||dz   d       } | j	                  d      d   }  n 	 t        j                  |       }t        |t              set        j                  d      t        j                  g t              t        j                  g t              t        j                  g t              dfS g }	g }
g }g }|D ]l  }t        |t               rd	|vsd
|vr|
j#                  |d
          |d	   }t%        t        j                  |d   |d   |d   |d   gg      j'                  t        j(                        ||fd      d   }|	j#                  |       d|v r||d   }t        |t              r|j+                  d      s.|j#                  t        j,                  ||ft.                     nV|j1                  d      }	 t3        j4                  |      }t7        j8                  t;        j<                  |            j?                  d      }t        |d         t        |d         }}t        |d         t        |d         }}||z
  }||z
  }|dkD  r|dkD  r}|jA                  ||ft6        jB                  jD                        }t        j,                  ||ft.              }t        j                  |      dkD  |||||f<   |j#                  |       n/|j#                  t        j,                  ||ft.                     nd}d|v r|U|j#                  |d          kd}o |	set        j                  d      t        j                  g t              t        j                  g t              t        j                  g t              dfS t        j                  |	t              }t        j                  |
      }|t        j                  |D cg c]  }||v  c}t.              }||   }||   }t        j                  |D cg c]  }|jI                  |       c}      }|!tK        ||      D  cg c]
  \  }} | s	| }}} |tK        ||      D ! cg c]
  \  }!} | s	|! }}!} natM        t        tO        |                  }"t        |"      D #ci c]  \  }}#|#|
 }$}}#t        j                  |D cg c]  }|$|   	 c}      }|t        j                  |t              nd}%|t        j                  |      nd}&||||%|&fS # t
        j                  $ rh t        j                  d      t        j                  g t              t        j                  g t              t        j                  g t              dfcY S w xY w# tF        $ r0 |j#                  t        j,                  ||ft.                     Y w xY wc c}w c c}w c c} }w c c} }!w c c}#}w c c}w )a/  
    Parse and scale bounding boxes and masks from Google Gemini 2.5 style
    [JSON output](https://ai.google.dev/gemini-api/docs/vision?lang=python).

    The JSON is expected to be enclosed in triple backticks with the format:
        ```json
        [
            {
                "box_2d": [x1, y1, x2, y2],
                "mask": "data:image/png;base64,...",
                "label": "some class name",
                "confidence": 0.95,
            },
            ...
        ]
        ```

    Args:
        result: String containing the JSON snippet enclosed by triple backticks.
        resolution_wh: (output_width, output_height) to which we rescale the boxes.
        classes: Optional list of valid class names. If provided, returned boxes/labels
            are filtered to only those classes found here.

    Returns:
        A tuple of `(xyxy, class_id, class_name, confidence, masks)` where
            `xyxy` is an array of shape `(n, 4)` in format `[x1, y1, x2, y2]`,
            `class_id` is an array of shape `(n,)` with class indices,
            `class_name` is an array of shape `(n,)` with class labels,
            `confidence` is an optional array of shape `(n,)` with confidence
            scores, and `masks` is an optional array of shape `(n, h, w)` with
            segmentation masks.
    r   r   ro   Nr   r   rj   rm   r   r   rp   rq   r   r   r   zdata:image/png;base64,L)resample
confidence)(r   r   r   r   r   r   r   r   ru   rw   rv   ry   r+   rz   r*   r!   r   r   r
   r{   r   
startswithzerosr~   removeprefixbase64	b64decoder	   openioBytesIOconvertresize
ResamplingBILINEARr   r   r   r   r   )'r\   rI   rL   r   r   r   r   r   r   r   r   confidence_listr   r   r   absolute_bboxpng_str	png_bytesmask_imgy_miny_maxx_minx_maxbbox_height
bbox_widthnp_maskr   r   rZ   r   r   mkeepr   unique_labelsr   label_to_idr  r   s'                                          r    from_google_gemini_2_5r    s   V  .DAqEU# 49YYuQUW~.F\\%(+F		
zz&! dD!HHVHHRs#HHRs#HHRu%
 	
 JK*,O02J 8#$%)=PTAT4=)8n)HHs1vs1vs1vs1v678??

Ka&!%
 	
 	-(T>%v,!'3/w7I7I,8 %%bhh1vT&BC%223KLGL$*$4$4W$=	#(::bjj.C#D#L#LS#Q (+=+;'<c-PQBR>Su'*=+;'<c-PQBR>Su&+em%*U]
&?zA~'/!+[ 9).)9)9)B)B (7 (H >@XX!"Ad>G AC@RUV@VGE%Ku$<=&--g6&--bhh1vT.JKJ4*&&tL'9:"Oq8#t HHVHHRs#HHRs#HHRu%
 	
 88Je,D+&J xxZ@T@MDz%
88ZHTW]]40HI!+.z4+@I4D!IJI&03OT0JSWQdqSOStC
O4509-0HIHAuuaxII88:F4[.FG 3B2M.SW  %/$:BHHZ E 	 e  
HHVHHRs#HHRs#HHRu%
 	

f % H"))"((Aq6*FGHX A II T JFsV   %U AWX

X:
XX
X(XX >X&A8W
W5XXc                ~  	 |\  }}|dk  s|dk  rt        d| d| d      d| vst        | d   t              st        j                  dt
              S g }| d   D ]@  	t        	fdd	D              s	d
   }	d   }	d   }	d   }|j                  ||||g       B t        |      dk(  r4t        t        j                  t           t        j                  d            S t        t        j                  t           t        t        j                  |      j                  t        j                         ||f            S )a   
    Parse and scale bounding boxes from moondream JSON output.

    The JSON is expected to have a key "objects" with a list of dictionaries:
      {
          "objects": [
              {"x_min": 0.1, "y_min": 0.2, "x_max": 0.3, "y_max": 0.4},
              ...
          ]
      }

      For Example:
      {
          "objects": [
              {"x_min": 0.1, "y_min": 0.2, "x_max": 0.3, "y_max": 0.4},
              {"x_min": 0.5, "y_min": 0.6, "x_max": 0.7, "y_max": 0.8}
          ]
      }

    Args:
        result: Dictionary containing the JSON output from the model.
        resolution_wh: (output_width, output_height) to which we rescale the boxes.

    Returns:
        An array of shape `(n, 4)` containing the bounding boxes coordinates
            in format `[x1, y1, x2, y2]`.
    r   z8Both dimensions in resolution_wh must be positive. Got (z, z).objectsrj   rm   c              3  &   K   | ]  }|v  
 y wr   rA   ).0kr   s     r    	<genexpr>z!from_moondream.<locals>.<genexpr>  s     K19Ks   )r  r  r  r  r  r  r  r  )rI   )r-   r*   r!   ru   rw   rz   allr   r   r   nptNDArrayr   r
   rv   r{   r   )
r\   rI   r   r   r   r  r  r  r  r   s
            @r    from_moondreamr)  W  s6   @ DAqAvaFqcA3bQ
 	
 j	1BD&Ixxe,,Dy! 	2K&JKKWWWWUE5%01	2 4yA~CKK$bhhv&677CHHTN!!"**-a&	
 rB   )r[   rG   r\   r   r]   dict[str, Any]r3   rD   r   )r\   r+   rI   tuple[int, int]rL   list[str] | Noner3   Btuple[npt.NDArray[Any], npt.NDArray[Any] | None, npt.NDArray[Any]])r   r+   r3   z
Any | None)
r\   r+   rJ   r+  rI   r+  rL   r,  r3   r-  )r\   r*  rI   r+  r3   zbtuple[npt.NDArray[Any], npt.NDArray[Any] | None, npt.NDArray[Any] | None, npt.NDArray[Any] | None])r\   r+   rI   r+  rL   r,  r3   zttuple[npt.NDArray[Any], npt.NDArray[Any] | None, npt.NDArray[Any], npt.NDArray[Any] | None, npt.NDArray[Any] | None])r\   r*  rI   r+  r3   znpt.NDArray[Any]):
__future__r   r   r  r	  r   rr   enumr   typingr   r   numpyru   numpy.typingr'  	deprecater   r   PILr	   !supervision.detection.utils.boxesr
   &supervision.detection.utils.convertersr   r   supervision.utils.internalr   supervision.validatorsr   r   rD   r8   r+   r9   r   r:   r;   r<   r=   r>   r?   rH   __annotations__rK   rM   r   rb   rg   r   r   r   r   r   r   r   r  r)  rA   rB   r    <module>r:     sw   " 
  	  	     &  ? S 6 70
$ 0
f(
$ (
X MM3NNDOOSMM3s33MM4	!o 	 MMO$NN_%OOj/2MMO$(O,O,MMO$	, ( 	 MMOY/NN_%OO=MMOY/3OY7OY7MMO$	+ ' 	 (	(()7((V #
%
%
 NR**** /**:J**G**Z*b !%	Y&Y&Y& #Y& 	Y&
 HY&~ !%"  H	8 NRD&D& /D&:JD&GD&N]6]6+:]6]6F !%T&T&"T& T& H	T&t !%nn"n n	nb??"? ?rB   