a
    yf                     @   s   d dl Z d dl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 d dlmZ d dlmZ d dlmZ d	d
 Zdd Zdd ZdddZdd ZdS )    N)List)	LetterBox)LOGGER)SETTINGS)check_requirements)	xyxy2xywh)plot_imagesc                    s*   ddl m}m  G  fddd|}|S )z4Extracts and returns the schema of a database table.r   )
LanceModelVectorc                       sr   e Zd ZU eed< ee ed< ee ed< eee  ed< eeee   ed< eeee   ed<  ed< dS )	z get_table_schema.<locals>.Schemaim_filelabelsclsbboxesmasks	keypointsZvectorN)__name__
__module____qualname__str__annotations__r   intfloat r
   vector_sizer   [/var/www/html/django/DPS/env/lib/python3.9/site-packages/ultralytics/data/explorer/utils.pySchema   s   
r   )lancedb.pydanticr	   r
   )r   r	   r   r   r   r   get_table_schema   s    	r   c                  C   s    ddl m}  G dd d| }|S )zLReturns a LanceModel schema for a database table with specified vector size.r   )r	   c                   @   s2   e Zd ZU eed< eed< eed< ee ed< dS )z$get_sim_index_schema.<locals>.Schemaidxr   countZsim_im_filesN)r   r   r   r   r   r   r   r   r   r   r   r   %   s   
r   )r   r	   )r	   r   r   r   r   get_sim_index_schema!   s    r!   c                    s   | d     | d< tt| d  | d dd d}dd |D | d< dd |D | d<  fd	d| d D | d
< d| v r| d  ng gg| d< d| v r| d  ng gg| d< | S )zLSanitizes input batch for inference, ensuring correct format and dimensions.r   r   c                 S   s   | d S )N   r   )xr   r   r   <lambda>1       z sanitize_batch.<locals>.<lambda>)keyc                 S   s   g | ]\}}|qS r   r   ).0box_r   r   r   
<listcomp>2   r%   z"sanitize_batch.<locals>.<listcomp>c                 S   s   g | ]\}}|qS r   r   )r'   r)   r   r   r   r   r*   3   r%   c                    s   g | ]} d  | qS )namesr   )r'   idataset_infor   r   r*   4   r%   r   r   r   )flattenr   tolistsortedzip)batchr.   Zbox_cls_pairr   r-   r   sanitize_batch.   s    "  r4   Tc                 C   sL  ddl }t| |jr | jddn|  } g gg}g g}| dg }| d|ur\| dg ng }| dd |kr|| dng }| dd |kr| dng }| d	g }	d
}
g g g g g f\}}}}}t|D ]\}}t|}t	|tj
}|jdd \}}t|
| |
| }|t|
dd|dddd |r`t||krt|| dkrtj|| tjd}|ddddgf  |9  < |ddddgf  |9  < || t||krt|| dkrtj|| tjdd }|t|
dd|d t||kr`|| dur`tj|| tjd}|ddddddf  |9  < || |tttj|| tjd|  qtj|dd}|rtj|ddntjdtjd}|rtj|ddntjdtjd}|rttj|ddntjdtjd}tj|dd}tjdd |	D dd}	t|||	|||t|ddd	S )z
    Plot images from the similar set.

    Args:
        similar_set (list): Pyarrow or pandas object containing the similar data points
        plot_labels (bool): Whether to plot labels or not
    r   Nlist)Zorientr   r   r   r   r   i     F)center)imager"   Zdtype   )Zaxis)r   3   c                 S   s   g | ]}t j|t jd qS )r9   )nparrayZint32)r'   cr   r   r   r*   j   r%   z%plot_query_result.<locals>.<listcomp>)r   r   kptsZmax_subplotssaveZthreaded)pandas
isinstanceZ	DataFrameto_dictZ	to_pydictget	enumeratecv2ZimreadZcvtColorZCOLOR_BGR2RGBshapeminappendr   Z	transposelenr<   r=   Zfloat32Zuint8ZonesstackZzerosZconcatenater   r   )Zsimilar_setZplot_labelsrA   Zempty_masksZempty_boxesZimagesr   r   r?   r   Z	plot_sizeZimgsZ	batch_idxZ
plot_boxesZ
plot_masksZ	plot_kptsr,   ZimfZimhwrr(   maskZkptZboxesr   r   r   plot_query_result:   sR      
" 
 "
*$$(rP   c                 C   s   t d ddlm} td s>td td}td|i |td d}dd	d
d|  d
g}|jj	j
d|d}|jd jjS )z:Plots images with optional labels from a similar data set.zopenai>=1.6.1r   )OpenAIopenai_api_keyzFOpenAI API key not found in settings. Please enter your API key below.zOpenAI API key: )Zapi_keysystema  
                You are a helpful data scientist proficient in SQL. You need to output exactly one SQL query based on
                the following schema and a user request. You only need to output the format with fixed selection
                statement that selects everything from "'table'", like `SELECT * from 'table'`

                Schema:
                im_file: string not null
                labels: list<item: string> not null
                child 0, item: string
                cls: list<item: int64> not null
                child 0, item: int64
                bboxes: list<item: list<item: double>> not null
                child 0, item: list<item: double>
                    child 0, item: double
                masks: list<item: list<item: list<item: int64>>> not null
                child 0, item: list<item: list<item: int64>>
                    child 0, item: list<item: int64>
                        child 0, item: int64
                keypoints: list<item: list<item: list<item: double>>> not null
                child 0, item: list<item: list<item: double>>
                    child 0, item: list<item: double>
                        child 0, item: double
                vector: fixed_size_list<item: float>[256] not null
                child 0, item: float

                Some details about the schema:
                - the "labels" column contains the string values like 'person' and 'dog' for the respective objects
                    in each image
                - the "cls" column contains the integer values on these classes that map them the labels

                Example of a correct query:
                request - Get all data points that contain 2 or more people and at least one dog
                correct query-
                SELECT * FROM 'table' WHERE  ARRAY_LENGTH(cls) >= 2  AND ARRAY_LENGTH(FILTER(labels, x -> x = 'person')) >= 2  AND ARRAY_LENGTH(FILTER(labels, x -> x = 'dog')) >= 1;
             )Zrolecontentuserzgpt-3.5-turbo)modelmessages)r   openairQ   r   loggerwarninggetpassupdateZchatZcompletionscreatechoicesmessagerT   )queryrQ   rR   rX   rW   responser   r   r   prompt_sql_queryq   s    

&
*rb   )T)r[   typingr   rF   numpyr<   Zultralytics.data.augmentr   Zultralytics.utilsr   rY   r   Zultralytics.utils.checksr   Zultralytics.utils.opsr   Zultralytics.utils.plottingr   r   r!   r4   rP   rb   r   r   r   r   <module>   s   
7