a
    yf\                     @   s  d dl Z d dlZd dlZd dlmZ 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mZmZmZ d dlmZmZ d dlmZmZmZ d dlmZ d d	lmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z( d d
l)m*Z* d dl+m,Z, e'eZ-dd Z.dd Z/dd Z0e	j1j2e- dddd Z3e	j1j2ddde	j1j2e- dddd Z4e	j1j2ddde	j1j2e- dddd Z5e	j16dedd Z7e	j16ded d! Z8d"d# Z9e	j1j:e	j1j2e" d$de	j1j2e( d%dd&d' Z;e	j1j2e" d$de	j1j2e- ddd(d) Z<d*d+ Z=d,d- Z>d.d/ Z?d0d1 Z@e	j1j2e%d2dd3d4 ZAd5d6 ZBe	j16ded7d8 ZCd9d: ZDe	j1j2e" d$dd;d< ZEe	j1j2e" d$dd=d> ZFd?d@ ZGdAdB ZHdCdD ZIdEdF ZJdGdH ZKe	j1j2e%dIddJdK ZLdLdM ZMe	j1j:e	j1j2e" d$ddNdO ZNdPdQ ZOdRdS ZPe	j1j:dTdU ZQdVdW ZRdXdY ZSe	j1j2e" d$ddZd[ ZTe	jUd\d] ZVe	j16d^g d_d`da ZWe	j1j:e	j1j2e" d$ddbdc ZXddde ZYe	j1j2e&jZdfddgdh Z[didj Z\dS )k    N)copy)Path)Image)CFGMODELSOURCESOURCES_LISTTMP)RTDETRYOLO)MODELS	TASK2DATATASKS)load_inference_source)ASSETSDEFAULT_CFGDEFAULT_CFG_PATHLOGGERONLINEROOTWEIGHTS_DIRWINDOWSchecksis_dir_writeableis_github_action_running)download)	TORCH_1_9c                  C   s   t t} | dddd dS )z(Test the forward pass of the YOLO model.N    T)sourceimgszaugment)r   r   model r#   M/var/www/html/django/DPS/env/lib/python3.9/site-packages/tests/test_python.pytest_model_forward'   s    r%   c                  C   sh   t t} | jddd |  } | t} | d |   | d |   | j	}| j
}| j}| j}dS )zVTest various methods and properties of the YOLO model to ensure correct functionality.T)verboseZdetailedcpuZon_train_startN)r   r   infoZreset_weightsloadtoZfuseZclear_callbackZreset_callbacksnamesdeviceZ
transformsZtask_map)r"   _r#   r#   r$   test_model_methods-   s    


r.   c                  C   s4   ddl m}  |  }tdddd}|j|dd}dS )	z^Test profiling of the YOLO model with `profile=True` to assess performance and resource usage.r   )DetectionModel      @   T)profileN)Zultralytics.nn.tasksr/   torchrandnpredict)r/   r"   imr-   r#   r#   r$   test_model_profileA   s    r8   zdirectory is not writeable)reasonc                  C   sp   t d } t| d*}tD ]}|| d qW d   n1 sB0    Y  tt| dd}t|dkslJ dS )zWTests YOLO predictions with file, directory, and pattern sources listed in a text file.zsources_multi_row.txtw
Nr   r   r      )r	   openr   writer   r   len)filefsrcresultsr#   r#   r$   test_predict_txtJ   s    0rE   Tzdisabled for testingc                  C   s   t d } t| ddd:}t|}|dg |dd tD  W d   n1 sV0    Y  tt| d	d
}t	|dksJ dS )zJTests YOLO predictions with sources listed in multiple rows of a CSV file.zsources_multi_row.csvr:    newliner   c                 S   s   g | ]
}|gqS r#   r#   ).0rC   r#   r#   r$   
<listcomp>]       z.test_predict_csv_multi_row.<locals>.<listcomp>Nr   r<   r=   )
r	   r>   csvwriterwriterow	writerowsr   r   r   r@   rA   rB   rM   rD   r#   r#   r$   test_predict_csv_multi_rowU   s    
2rQ   c                  C   sn   t d } t| ddd$}t|}|t W d   n1 s@0    Y  tt| dd}t|dksjJ dS )	zITests YOLO predictions with sources listed in a single row of a CSV file.zsources_single_row.csvr:   rF   rG   Nr   r<   r=   )	r	   r>   rL   rM   rN   r   r   r   r@   rP   r#   r#   r$   test_predict_csv_single_rowb   s    
(rR   
model_namec              	   C   sF  t t|  }ttt}t|ttdddddks<J t||dddddksXJ t|t	
ddddksvJ t|||gdddddksJ tt|||gdddd	dksJ t|t	d
dd tjdddksJ tttttrdntttttttjdtjdg}t||ddt|ksBJ dS )z^Test YOLO model predictions on various image input types and sources, including online images.Tr   )r   saver&   r   r0   )r   rT   save_txtr   )   r1   r   r   r   rV   )r   rT   streamr   @    r1   zIhttps://github.com/ultralytics/assets/releases/download/v0.0.0/zidane.jpg)rY   rZ   r1   )dtypeN)r   r   cv2imreadstrr   r@   r   r>   r4   randlistzerosnumpyZastypenpZuint8r   r   )rS   r"   r7   batchr#   r#   r$   test_predict_imgn   s     " $.
re   r"   c                 C   s   t t|  tddd dS )zfTest model prediction methods with 'visualize=True' to generate and display prediction visualizations.r   T)r   Z	visualizeN)r   r   r   r!   r#   r#   r$   test_predict_visualize   s    rf   c            
      C   s   t t} td }|jddd |d }|d }|d }|d }| d| | d	| | | | | tt}||||fD ]L}t |t	
t||fD ]$}||ddd
d}	t|	dksJ q|  qdS )zbTest YOLO prediction on SOURCE converted to greyscale and 4-channel images with various filenames.Zim4Tparentsexist_okzgreyscale.jpgz4ch.pngu$   non_UTF_测试文件_tést_image.jpgzimage with spaces.jpgLZRGBAr   )rT   r&   r   r0   N)r   r>   r   r	   mkdirconvertrT   r   r   r\   r]   r^   r@   unlink)
r7   	directoryZsource_greyscaleZsource_rgbaZsource_non_utfZsource_spacesr"   rB   r   rD   r#   r#   r$   test_predict_grey_and_4ch   s"    


ro   zenvironment is offlinez:No auth https://github.com/JuanBindez/pytubefix/issues/166c               
   C   s^   t t} z| jdddd W n< tjjtfyX } ztd|  W Y d}~n
d}~0 0 dS )zUTest YOLO model on a YouTube video stream, handling potential network-related errors.zhttps://youtu.be/G17sBkb38XQ`   T)r   rT   zWARNING: YouTube Test Error: N)	r   r   r6   urlliberror	HTTPErrorConnectionErrorr   warning)r"   er#   r#   r$   test_youtube   s
    rw   c               	   C   s   d} t t}|j| ddd |j| dddd dD ]}ttd	 d
d}t|}W d   n1 sf0    Y  td| d }||d< t|dd
d}t|| W d   n1 s0    Y  |j| d|d q2dS )z
    Tests streaming tracking on a short 10 frame video using ByteTrack tracker and different GMC methods.

    Note imgsz=160 required for tracking for higher confidence and better matches.
    zXhttps://github.com/ultralytics/assets/releases/download/v0.0.0/decelera_portrait_min.mov   zbytetrack.yaml)r   trackerzbotsort.yamlT)r   ry   Zsave_frames)ZorbZsiftZecczcfg/trackers/botsort.yamlzutf-8)encodingNzbotsort-.yamlZ
gmc_methodr:   )	r   r   trackr>   r   yamlZ	safe_loadr	   Z	safe_dump)Z	video_urlr"   ZgmcrB   datary   r#   r#   r$   test_track_stream   s    (*r   c                   C   s   t tjdddd dS )z+Test the validation mode of the YOLO model.
coco8.yamlr   T)r~   r   Zsave_hybridN)r   r   valr#   r#   r#   r$   test_val   s    r   c               	   C   s,   t t} | jdddddddd | t d	S )
zKTest training the YOLO model from scratch using the provided configuration.r   rV   r   diskr0   r"   )r~   epochsr   cacherd   close_mosaicnameN)r   r   trainr   r!   r#   r#   r$   test_train_scratch   s    r   c               	   C   s0   t td } | jdddddddd | t d	S )
zGTest training of the YOLO model starting from a pre-trained checkpoint.yolo11n-seg.ptzcoco8-seg.yamlr0   r   ram      ?r   )r~   r   r   r   Z
copy_pasteZmixupr   N)r   r   r   r   r!   r#   r#   r$   test_train_pretrained   s    r   c                  C   sH   t d d dD ]0} d| jv r8trBt| jtdd}qt| j qdS )z]Test YOLO model creation for all available YAML configurations in the `cfg/models` directory.cfgmodelsz*.yamlZrtdetrrZ   rW   N)r   rglobr   r   r
   r   r   )mr-   r#   r#   r$   test_all_model_yamls   s
    
r   zPWindows slow CI export bug https://github.com/ultralytics/ultralytics/pull/16003c                  C   sD   t t} | jddddd | jdd | jtdd | jdd d	S )
zUTest the complete workflow including training, validation, prediction, and exporting.r   r0   r   ZSGD)r~   r   r   Z	optimizerrW   Ztorchscript)formatN)r   r   r   r   r6   r   Zexportr!   r#   r#   r$   test_workflow   s
    r   c                  C   st   dd } t t}|d|  ttd}|j}|j|ddd}|D ].\}}}td|j td| |j	}t| q@d	S )
zGTest callback functionality during YOLO prediction setup and execution.c                    sN    j \}}}t|tr|n|g} fddtt|D }t j|| _dS )zKCallback function that handles operations at the end of a prediction batch.c                    s   g | ]} j jqS r#   )datasetbs)rI   r-   	predictorr#   r$   rJ      rK   zQtest_predict_callback_and_setup.<locals>.on_predict_batch_end.<locals>.<listcomp>N)rd   
isinstancer`   ranger@   ziprD   )r   pathZim0sr-   r   r#   r   r$   on_predict_batch_end   s    z=test_predict_callback_and_setup.<locals>.on_predict_batch_endr   )r   Trx   )rX   r   Ztest_callbackN)
r   r   Zadd_callbackr   r   r   r6   printshapeboxes)r   r"   r   r   rD   rZim0r   r#   r#   r$   test_predict_callback_and_setup   s    

r   c                 C   s   t t|  ttgdd}|D ]}|  }t|t||j |jdt	j
d}|jtd dd |jtd d	 |jdd
 |jdd |  |  |jdd |jddd t|t||j qdS )zNEnsure YOLO model predictions can be processed and printed in various formats.rx   rW   r'   )r,   r[   zruns/tests/label.txtT)Ztxt_fileZ	save_confzruns/tests/crops/)save_dir)	normalizer1   )Zdecimals)Zpil)confr   N)r   r   r   r'   rb   r   r@   r   r*   r4   float32rU   r	   	save_cropto_jsonZto_dfZto_csvZto_xmlZplot)r"   rD   r   r#   r#   r$   test_results  s    r   c                     s&  t td g} ttd | dddd}t|d j}|D ]tjjjj	
  }|jdrlg dng d	kszJ |d
 d }| sJ tjjtdd |  D ksJ t|d   dd  D }t fdd|D sJ tfdd|D tjjks6J q6dS )zeTest output from prediction args for saving YOLO detection labels and crops; ensures accurate saving.z
zidane.jpg
yolo11n.ptrx   T)r   rU   r   r   zbus.jpg)r   r=   r   r   )r   r   r   zlabels/z.txtc                 S   s   g | ]}|r|qS r#   r#   )rI   liner#   r#   r$   rJ   '  rK   z)test_labels_and_crops.<locals>.<listcomp>Zcropsc                 S   s    g | ]}| d D ]}|qqS )*)glob)rI   prB   r#   r#   r$   rJ   *  rK   c                 3   s(   | ] }j |d d  D v V  qdS )c                 S   s   h | ]
}|j qS r#   r   )rI   dr#   r#   r$   	<setcomp>,  rK   z2test_labels_and_crops.<locals>.<genexpr>.<setcomp>N)r+   get)rI   c)	crop_dirsr   r#   r$   	<genexpr>,  rK   z(test_labels_and_crops.<locals>.<genexpr>c                    s   g | ]} |j v r|qS r#   r   )rI   rB   )im_namer#   r$   rJ   .  rK   N)r   r   r   r   r   r   r   stemr   clsinttolistendswithexistsr@   r~   	read_text
splitlinesr`   iterdirall)ZimgsrD   Z	save_pathZcls_idxslabelsZ
crop_filesr#   )r   r   r   r$   test_labels_and_crops  s    $*r   c                  C   s   ddl m} m} ddlm} tD ]N}tt| d}t	d| dt
d | t
| |d}|jd	d
 |  q |t
d  |t
d  dS )z`Test utility functions in ultralytics/data/utils.py, including dataset stats and auto-splitting.r   )HUBDatasetStats	autosplit)zip_directoryz.zipz=https://github.com/ultralytics/hub/raw/main/example_datasets/F)Zunzipdir)taskT)rT   Zcoco8zcoco8/images/valN)Zultralytics.data.utilsr   r   ultralytics.utils.downloadsr   r   r   r   with_suffixr   r	   Zget_jsonZprocess_images)r   r   r   r   rA   statsr#   r#   r$   test_data_utils1  s    
r   c                  C   sF   ddl m} m} d}td| td |ttd dddd	 |   d
S )zNTest dataset conversion functions from COCO to YOLO format and class mappings.r   )coco80_to_coco91_classconvert_cocozinstances_val2017.jsonz?https://github.com/ultralytics/assets/releases/download/v0.0.0/)r   Zyolo_labelsTF)Z
labels_dirr   Zuse_segmentsZuse_keypointsZ	cls91to80N)Zultralytics.data.converterr   r   r   r	   )r   r   rA   r#   r#   r$   test_data_converterE  s
    r   c                  C   s,   ddl m}  | ttd td td d dS )zNAutomatically annotate data using specified detection and segmentation models.r   auto_annotater   zmobile_sam.ptZauto_annotate_labels)Z	det_modelZ	sam_model
output_dirN)Zultralytics.data.annotatorr   r   r   r	   r   r#   r#   r$   test_data_annotatorP  s    r   c                  C   s2   ddl m}  |  }d|_tt}d|_|| dS )z!Test event sending functionality.r   )EventsTtestN)ultralytics.hub.utilsr   enabledr   r   mode)r   eventsr   r#   r#   r$   test_events\  s    r   c                     s   ddl m} m}m  tt" | ddiddi W d   n1 sF0    Y  |  t t	j
dd	 jd
d  fdddD  dS )zNTest configuration initialization utilities from the 'ultralytics.cfg' module.r   )check_dict_alignmentcopy_default_cfgsmart_valuear0   brV   Nr{   z
_copy.yamlF)
missing_okc                    s   g | ]} |qS r#   r#   )rI   xr   r#   r$   rJ   o  rK   z!test_cfg_init.<locals>.<listcomp>)nonetruefalse)ultralytics.cfgr   r   r   
contextlibsuppressSyntaxErrorr   cwdr   r   replacerm   )r   r   r#   r   r$   test_cfg_initg  s    0r   c                  C   s4   ddl m} m}m}m} |  |  |  |   dS )z9Test initialization utilities in the Ultralytics library.r   get_git_branchget_git_origin_urlget_ubuntu_versionr   N)ultralytics.utilsr   r   r   r   r   r#   r#   r$   test_utils_initr  s
    r   c                   C   sR   t d t t t   t jddgdd t jdd t dd t   d	S )
z_Test various utility checks for filenames, git status, requirements, image sizes, and versions.z
yolov5n.ptiX  r0   )Zmax_dimT)warnultralyticsz8.0.0N)	r   Zcheck_yolov5u_filenameZgit_describer   check_requirementsZcheck_imgszZcheck_imshowZcheck_versionZ
print_argsr#   r#   r#   r$   test_utils_checks|  s    

r   z3Windows profiling is extremely slow (cause unknown)c                  C   s(   ddl m}  | dgddddd  dS )	zVBenchmark model performance using 'ProfileModels' from 'ultralytics.utils.benchmarks'.r   ProfileModelszyolo11n.yamlr   r0   r1   )r   Zmin_timeZnum_timed_runsZnum_warmup_runsN)Zultralytics.utils.benchmarksr   r3   r   r#   r#   r$   test_utils_benchmarks  s    r   c                  C   sb   ddl m}  ddlm}m}m} tdddd}| ddddd}|||gd	d
 || |  dS )zGTest Torch utility functions including profiling and FLOP calculations.r   )Conv)get_flops_with_torch_profilerr3   	time_syncr0   r2      rV   )ksr1   )nN)ultralytics.nn.modules.convr   ultralytics.utils.torch_utilsr   r3   r   r4   r5   )r   r   r3   r   r   r   r#   r#   r$   test_utils_torchutils  s    r  c                  C   s   ddl m}  | d dS )z>Test file download utilities from ultralytics.utils.downloads.r   get_google_drive_file_infozUhttps://drive.google.com/file/d/1cqT-cJgANNrhIHCrEufUYhQ4RqiWG_lJ/view?usp=drive_linkN)r   r  r  r#   r#   r$   test_utils_downloads  s    r  c                  C   s   ddl m} m}m}m}m}m}m}m}m	}m
}	m}
 |dtdg tdd}t|||| t||	|| t|| || t|||| tdd}tdd |d	d	df< tj||
||d
d d	S )zRTest utility operations functions for coordinate transformation and normalization.r   )	ltwh2xywh	ltwh2xyxymake_divisible	xywh2ltwh	xywh2xyxy
xywhn2xyxyxywhr2xyxyxyxy	xyxy2ltwh	xyxy2xywh
xyxy2xywhnxyxyxyxy2xywhr      
            NgMbP?)Zrtol)Zultralytics.utils.opsr  r  r	  r
  r  r  r  r  r  r  r  r4   Ztensorr_   Zallcloser5   )r  r  r	  r
  r  r  r  r  r  r  r  r   r#   r#   r$   test_utils_ops  s    4r  c                  C   s~   ddl m} m}m}m} | t |t |td  td }|jddd ||}t	| W d   n1 sp0    Y  dS )zMTest file handling utilities including file age, date, and paths with spaces.r   )file_age	file_dateget_latest_runspaces_in_pathrunszpath/with spacesTrg   N)
Zultralytics.utils.filesr  r  r  r  r   r   r	   rk   r   )r  r  r  r  r   new_pathr#   r#   r$   test_utils_files  s    
r  c               	   C   s   ddl m} m} ddlm} | td}|d|dN tt$ |t	dt
d  W d	   n1 sh0    Y  W d	   n1 s0    Y  |jd
ksJ dd	S )zRTest torch_save backoff when _torch_save raises RuntimeError to ensure robustness.r   )	MagicMockpatch)
torch_save)Zside_effectz%ultralytics.utils.patches._torch_save)newr0   ztest.ptNr  z9torch_save was not attempted the expected number of times)Zunittest.mockr   r!  Zultralytics.utils.patchesr"  RuntimeErrorpytestZraisesr4   ra   r	   Z
call_count)r   r!  r"  Zmockr#   r#   r$   test_utils_patches_torch_save  s    
Pr&  c            	      C   s   ddl m} m}m}m}m} d\}}td|dd}|||| |||| |||| | || |||}|  || dS )zSTest Convolutional Neural Network modules including CBAM, Conv2, and ConvTranspose.r   )CBAMConv2ConvTransposeDWConvTranspose2dFocusr     r  r  N)	r  r'  r(  r)  r*  r+  r4   ra   Z
fuse_convs)	r'  r(  r)  r*  r+  c1c2r   r   r#   r#   r$   test_nn_modules_conv  s    
r0  c                  C   s~   ddl m} m}m}m}m} d\}}td|dd}| ||| |||| |||| |||| |||| dS )zbTest various blocks in neural network modules including C1, C3TR, BottleneckCSP, C3Ghost, and C3x.r   )C1C3TRBottleneckCSPC3GhostC3xr,  r  r  N)Zultralytics.nn.modules.blockr1  r2  r3  r4  r5  r4   ra   )r1  r2  r3  r4  r5  r.  r/  r   r#   r#   r$   test_nn_modules_block  s    r6  c                  C   s:   ddl m} m} ddlm} |   |  |dddd dS )	zCTest Ultralytics HUB functionalities (e.g. export formats, logout).r   )export_fmts_hublogout)smart_requestGETzhttps://github.comT)progressN)Zultralytics.hubr7  r8  r   r9  )r7  r8  r9  r#   r#   r$   test_hub  s
    r<  c                   C   s   t ttS )z?Load and return an image from a predefined source using OpenCV.)r\   r]   r^   r   r#   r#   r#   r$   image  s    r=  z)auto_augment, erasing, force_color_jitter))N        F)Zrandaugmentr   T)Zaugmixg?F)Zautoaugmentr>  Tc                 C   sv   ddl m} |ddddddd|dd	d	||d
}|tt| tj}|jdksTJ t	|sbJ |j
tjksrJ dS )zjTests classification transforms during training with various augmentations to ensure proper functionality.r   )classify_augmentations   )r   r   r   )g{Gz?g      ?)g      ?gUUUUUU?r   gQ?g?)sizemeanZstdscaleratioZhflipZvflipauto_augmentZhsv_hZhsv_sZhsv_vforce_color_jittererasing)r1   r@  r@  N)Zultralytics.data.augmentr?  r   Z	fromarrayr\   ZcvtColorZCOLOR_BGR2RGBr   r4   Z	is_tensorr[   r   )r=  rE  rG  rF  r?  Z	transformZtransformed_imager#   r#   r$   test_classify_transforms_train  s(    rH  c                   C   s8   t djddddddd t d	jd
dddddd dS )z,Tune YOLO model for performance improvement.zyolo11n-pose.ptzcoco8-pose.yamlFr   r0   rV   r'   )r~   Zplotsr   r   Z
iterationsr,   zyolo11n-cls.ptZ
imagenet10N)r   Ztuner#   r#   r#   r$   test_model_tune7  s    rI  c                  C   sh   t t} t td }tgttgfD ]@}t| j|ddt|ksDJ t|j|ddt|ks"J q"dS )zTest YOLO model embeddings.r   r   r<   N)r   r   r   r   r@   Zembed)Zmodel_detectZmodel_segmentrd   r#   r#   r$   test_model_embeddings?  s
    rJ  z3YOLOWorld with CLIP is not supported in Python 3.12c                  C   s~   t d} | ddg | tdd t d} | jddd	d
dd ddlm} t d} | jddgiddgiddd	d
d|d dS )zVTests YOLO world models with CLIP support, including detection and training scenarios.zyolov8s-world.pttreeZwindowg{Gz?)r   zyolov8s-worldv2.ptz
dota8.yamlr0   r   r   )r~   r   r   r   r   r   )WorldTrainerFromScratchzyolov8s-worldv2.yamlZ	yolo_data)r   r   )r~   r   r   r   r   ZtrainerN)r   Zset_classesr   r   Z)ultralytics.models.yolo.world.train_worldrL  )r"   rL  r#   r#   r$   test_yolo_worldI  s*    	rM  c                  C   sH   t d} | jdddddd | jddd | jddddd	 | t d
S )zZTest YOLOv10 model training, validation, and prediction steps with minimal configurations.zyolov10n.yamlr   r0   r   r   )r~   r   r   r   r   )r~   r   T)r   rU   r   r    N)r   r   r   r6   r   r!   r#   r#   r$   test_yolov10i  s
    rN  )]r   rL   rq   r   pathlibr   r\   rb   rc   r%  r4   r}   ZPILr   testsr   r   r   r   r	   r   r
   r   r   r   r   r   Zultralytics.data.buildr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r   ZIS_TMP_WRITEABLEr%   r.   r8   markZskipifrE   rQ   rR   Zparametrizere   rf   ro   Zslowrw   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r  r&  r0  r6  r<  Zfixturer=  rH  rI  rJ  ZIS_PYTHON_3_12rM  rN  r#   r#   r#   r$   <module>   s   4	







	









	


