
    9i4                         S SK Jr  S SKrS SKJr  S SKJrJr  S SK	r
S SKJr  S SKJr  S SKJr  S SKJrJr  S SKJr  S SKJrJr  S S	KJr  \R8                  " \\R:                  S
9 " S S\5      5       rS rg)    N)OrderedDict)AnyDict)COCO)COCOeval)dumpload)Metrics)METRICSMetric)default_group)	group_keymodule_namec                       \ rS rSrSrS rS\\\4   S\\\4   4S jr	S r
SS jrS	 rS
 rSS jrS rS rS rS rS rSrg)#ImageInstanceSegmentationCOCOMetric   zMThe metric computation class for COCO-style image instance segmentation.
    c           	          S U l         S U l        SS/U l        SU l        [        R
                  " SS[        [        R                  " S5      5      S-   SS	9U l        / U l	        g )
Nbboxsegm)d   i,  i  g      ?gffffff?g!@   T)endpoint)
ann_fileclassesmetricsproposal_numsnplinspaceintroundiou_thrsresultsselfs    u/var/www/html/land-doc-ocr/venv/lib/python3.13/site-packages/modelscope/metrics/image_instance_segmentation_metric.py__init__,ImageInstanceSegmentationCOCOMetric.__init__   sY    '-c"((#456:TK    outputsinputsc                    US   n[        US   [        5      (       a!  U VVs/ s H  u  pEU[        U5      4PM     nnnU R                  R	                  U5        U R
                  c!  US   S   S   U l        US   S   S   U l        g g s  snnf )Neval_resultr   	img_metasr   r   )
isinstancetupleencode_mask_resultsr"   extendr   r   )r$   r)   r*   resultbbox_resultsmask_resultss         r%   add'ImageInstanceSegmentationCOCOMetric.add"   s    'fQi''8>@8>4, $%8%FG8>  @F#== #K03J?DM";/29=DL !@s   B	c                    [        U R                  5      nUR                  U R                  S9U l        UR                  5       U l        U R                  U R                  U R                  5      u  p#[        5       nU R                   GH  nUnXR;  a  [        U S35      e [        X%   5      nUS:X  a  U H  nUR                  S5        M     UR                  U5      n	[#        XU5      n
U R                  U
R$                  l        U R                  U
R$                  l        [+        U R,                  5      U
R$                  l        U R0                  U
R$                  l        SSSS	S
SSSSSSSS.nU
R5                  5         U
R7                  5         U
R9                  5         / SQnU H*  nU SU 3n[;        U
R<                  X      S 5      nXU'   M,     U
R<                  S S nUS   S SUS   S SUS   S SUS	   S SUS
   S SUS   S 3XE S3'   GM     Ub  UR?                  5         U$ ! [         a    [!        S5           M.  f = f)N)catNmsz is not in resultsr   r   z2The testing results of the whole dataset is empty.r   r                        	   
      )mAPmAP_50mAP_75mAP_smAP_mmAP_lzAR@100zAR@300zAR@1000z	AR_s@1000z	AR_m@1000z	AR_l@1000)rC   rD   rE   rF   rG   rH   _z.3f _mAP_copypaste) r   r   	getCatIdsr   cat_ids	getImgIdsimg_idsformat_resultsr"   r   r   KeyErrorr	   poploadRes
IndexErrorprintr   paramscatIdsimgIdslistr   maxDetsr!   iouThrsevaluate
accumulate	summarizefloatstatscleanup)r$   cocoGtresult_filestmp_direval_resultsmetriciou_typepredictionsxcocoDtcocoEvalcoco_metric_namesmetric_itemsmetric_itemkeyvalaps                    r%   r\   ,ImageInstanceSegmentationCOCOMetric.evaluate-   sb   dmm$''t||'<'') $ 3 3DLL$,, O"}llFH)&);<=="<#78v% )f )4
  9H%)\\HOO"%)\\HOO"&*4+=+=&>HOO#&*mmHOO# ! ! L  ,+/~~&7&DEcJM$'S!	  ,
 #Ba5+Qr!uSk2a5+Qr!uSka5+Qr!uSk+ 8>23o #t OOY  JKs   !>H,,IIc                 N    U R                   R                  UR                   5        g N)r"   r1   )r$   others     r%   merge)ImageInstanceSegmentationCOCOMetric.merges   s    EMM*r(   c                     U R                   $ rt   )r"   r#   s    r%   __getstate__0ImageInstanceSegmentationCOCOMetric.__getstate__v   s    ||r(   c                 0    U R                  5         Xl        g rt   )r&   r"   )r$   states     r%   __setstate__0ImageInstanceSegmentationCOCOMetric.__setstate__y   s    r(   Nc                 \   [        U[        5      (       d   S5       e[        U5      [        U5      :X  d)   SR                  [        U5      [        U5      5      5       eUc7  [        R
                  " 5       n[        R                  " UR                  S5      nOSnU R                  X5      nXe4$ )a  Format the results to json (standard format for COCO evaluation).

Args:
    results (list[tuple | numpy.ndarray]): Testing results of the
        dataset.
    data_infos(list[tuple | numpy.ndarray]): data information
    jsonfile_prefix (str | None): The prefix of json files. It includes
        the file path and the prefix of filename, e.g., "a/b/prefix".
        If not specified, a temp file will be created. Default: None.

Returns:
    tuple: (result_files, tmp_dir), result_files is a dict containing                 the json filepaths, tmp_dir is the temporal directory created                 for saving json files when jsonfile_prefix is not specified.
zresults must be a listz?The length of results is not equal to the dataset len: {} != {}Nr"   )
r.   rY   lenformattempfileTemporaryDirectoryospjoinnameresults2json)r$   r"   rO   jsonfile_prefixkwargsrd   rc   s          r%   rP   2ImageInstanceSegmentationCOCOMetric.format_results}   s      '4((B*BB(7|s7|+ 	0MF3w<W.	0+ "113G!hhw||Y?OG((B$$r(   c                 ^    UR                  5       nUS   US   US   US   -
  US   US   -
  /$ )zConvert ``xyxy`` style bounding boxes to ``xywh`` style for COCO
evaluation.

Args:
    bbox (numpy.ndarray): The bounding boxes, shape (4, ), in
        ``xyxy`` order.

Returns:
    list[float]: The converted bounding boxes, in ``xywh`` order.
r   r   r9   r:   )tolist)r$   r   _bboxs      r%   	xyxy2xywh-ImageInstanceSegmentationCOCOMetric.xyxy2xywh   sG     !H!H!HuQx!HuQx	
 	
r(   c                 R   / n[        [        U R                  5      5       H  nU R                  U   nX   n[        UR                  S   5       HP  n[	        5       nXGS'   U R                  XV   5      US'   [        XV   S   5      US'   SUS'   UR                  U5        MR     M     U$ )z,Convert proposal results to COCO json style.r   image_idr   r;   scorer   category_id)ranger   rO   shapedictr   r_   append)r$   r"   json_resultsidximg_idbboxesidatas           r%   _proposal2json2ImageInstanceSegmentationCOCOMetric._proposal2json   s    T\\*+C\\#&F\F6<<?+v#)Z #~~fi8V %fil 3W&']###D) , , r(   c                    / n[        [        U R                  5      5       H  nU R                  U   nX   n[        [        U5      5       H  nU[        U R                  5      :  a    MI  XV   n[        UR                  S   5       H]  n[        5       n	XIS'   U R                  Xx   5      U	S'   [        Xx   S   5      U	S'   U R                  U   U	S'   UR                  U	5        M_     M     M     U$ )z-Convert detection results to COCO json style.r   r   r   r;   r   r   )
r   r   rO   r   r   r   r   r_   rM   r   )
r$   r"   r   r   r   r2   labelr   r   r   s
             r%   	_det2json-ImageInstanceSegmentationCOCOMetric._det2json   s    T\\*+C\\#&F\Fs6{+
 C--v||A/A6D'-$#'>>&)#<DL$)&)A,$7DM*.,,u*=D' ''- 0 , ,$ r(   c                    / n/ n[        [        U R                  5      5       GH  nU R                  U   nX   u  pg[        [        U5      5       GH  nU[        U R                  5      :  a    MM  Xh   n	[        U	R                  S   5       H]  n
[        5       nX[S'   U R                  X   5      US'   [        X   S   5      US'   U R                  U   US'   UR                  U5        M_     [        U[        5      (       a  US   U   nUS   U   nOXx   nU	 Vs/ s H  oS   PM	     nn[        U	R                  S   5       H  n
[        5       nX[S'   U R                  X   5      US'   [        X   5      US'   U R                  U   US'   [        X   S   [        5      (       a  X   S   R                  5       X   S'   X   US	'   UR                  U5        M     GM     GM     X#4$ s  snf )
z9Convert instance segmentation results to COCO json style.r   r   r   r;   r   r   r   countssegmentation)r   r   rO   r   r   r   r   r_   rM   r   r.   r/   bytesdecode)r$   r"   bbox_json_resultssegm_json_resultsr   r   detsegr   r   r   r   segms
mask_scorer   s                  r%   
_segm2json.ImageInstanceSegmentationCOCOMetric._segm2json   s   T\\*+C\\#&F|HCs3x
 C--v||A/A6D'-$#'>>&)#<DL$)&)A,$7DM*.,,u*=D'%,,T2 0 c5))F5ME!$QJJE6<!=fdq'fJ!=v||A/A6D'-$#'>>&)#<DL$)*-$8DM*.,,u*=D'!%(8"4e<<-2Xh-?-F-F-H*+08D(%,,T2 03 ) ,L !33 ">s   G)c                 "   [        5       n[        US   [        5      (       a1  U R                  U5      nU S3US'   U S3US'   [	        XCS   5        U$ [        US   [
        5      (       aO  U R                  U5      nU S3US'   U S3US'   U S3US'   [	        US   US   5        [	        US   US   5        U$ [        US   [        R                  5      (       a)  U R                  U5      nU S3US'   [	        XCS   5        U$ [        S	5      e)
a  Dump the detection results to a COCO style json file.

There are 3 types of results: proposals, bbox predictions, mask
predictions, and they have different data types. This method will
automatically recognize the type, and dump them to json files.

Args:
    results (list[list | tuple | ndarray]): Testing results of the
        dataset.
    outfile_prefix (str): The filename prefix of the json files. If the
        prefix is "somepath/xxx", the json files will be named
        "somepath/xxx.bbox.json", "somepath/xxx.segm.json",
        "somepath/xxx.proposal.json".

Returns:
    dict[str: str]: Possible keys are "bbox", "segm", "proposal", and                 values are corresponding filenames.
r   z
.bbox.jsonr   proposalz
.segm.jsonr   r   z.proposal.jsonzinvalid type of results)r   r.   rY   r   r   r/   r   r   ndarrayr   	TypeError)r$   r"   outfile_prefixrc   r   s        r%   r   0ImageInstanceSegmentationCOCOMetric.results2json   sD   & vgaj$''>>'2L&4%5Z#@L *8)9'DL$F34  
E**??73L&4%5Z#@L *8)9'DL$&4%5Z#@L a,v"67a,v"67  
BJJ//..w7L*8)9'HL$J78  566r(   )r   rM   r   rO   r!   r   r   r"   )ru   r   rt   )__name__
__module____qualname____firstlineno____doc__r&   r   strr   r5   r\   rv   ry   r}   rP   r   r   r   r   r   __static_attributes__ r(   r%   r   r      sd    	>4S> 	>4S> 	>DL+%:
(.*4X&r(   r   c                    [        U [        5      (       a  U u  pOU n[        U5      n[        U5       Vs/ s H  n/ PM     nn[        [        U5      5       Hd  nX    HY  nXV   R	                  [
        R                  " [        R                  " USS2SS2[        R                  4   SSS95      S   5        M[     Mf     [        U [        5      (       a  UW4$ U$ s  snf )zEncode bitmap mask to RLE code.

Args:
    mask_results (list | tuple[list]): bitmap mask results.
        In mask scoring rcnn, mask_results is a tuple of (segm_results,
        segm_cls_score).

Returns:
    list | tuple: RLE encoded mask.
NFuint8)orderdtyper   )
r.   r/   r   r   r   	mask_utilencoder   arraynewaxis)r4   	cls_segmscls_mask_scoresnum_classesrI   encoded_mask_resultsr   cls_segms           r%   r0   r0   )  s     ,&&%1"	? 	i.K(-k(:;(:1B(:;3y>"!H #**  HH Arzz!12#%'( )*+, % # ,&&#_44## <s   C) os.pathpathr   r   collectionsr   typingr   r   numpyr   pycocotools.maskmaskr   pycocotools.cocor   pycocotools.cocoevalr   modelscope.fileior   r	   modelscope.metainfor
   modelscope.metricsr   r   modelscope.utils.registryr   register_moduleimage_ins_seg_coco_metricr   r0   r   r(   r%   <module>r      sg      #   $ ! ) ( ' . 3 	)J)JLQ& QLQh$r(   