
    Ig(                         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
 d dlZd dlmZ d dlmZ d dlmZ d dlmZ  G d d	      Zy)
    N)Path)AnyDictListOptional)snapshot_download)RepositoryNotFoundError)logger)tqdmc                   .   e Zd Zedeeeef      fd       Zededeeef   fd       Z	eddedede
defd       Ze	 	 	 dd
edee   deee      de
def
d       Zededefd       Ze	 ddededede
def
d       Ze	 ddeeef   dededefd       Zy	)ModelManagementreturnc                     t               )zLists the supported models.

        Returns:
            List[Dict[str, Any]]: A list of dictionaries containing the model information.
        )NotImplementedError)clss    ^/var/www/html/answerous/venv/lib/python3.12/site-packages/fastembed/common/model_management.pylist_supported_modelsz%ModelManagement.list_supported_models   s     "##    
model_namec                     | j                         D ]*  }|j                         |d   j                         k(  s(|c S  t        d| d| j                   d      )a  
        Gets the model description from the model_name.

        Args:
            model_name (str): The name of the model.

        raises:
            ValueError: If the model_name is not supported.

        Returns:
            Dict[str, Any]: The model description.
        modelzModel z is not supported in .)r   lower
ValueError__name__)r   r   r   s      r   _get_model_descriptionz&ModelManagement._get_model_description   sa     ..0 	E!U7^%9%9%;;	 6*-B3<<.PQRSSr   urloutput_pathshow_progressc                 T   t         j                  j                  |      r|S t        j                  |d      }|j
                  dk(  rt        d      t        |j                  j	                  dd            }|dk(  rt        d| d       t        |xr |      }t        |d	d| 
      5 }t        |d      5 }|j                  d      D ]0  }|s|j                  t        |             |j!                  |       2 	 ddd       ddd       |S # 1 sw Y   xY w# 1 sw Y   |S xY w)ap  
        Downloads a file from Google Cloud Storage.

        Args:
            url (str): The URL to download the file from.
            output_path (str): The path to save the downloaded file to.
            show_progress (bool, optional): Whether to show a progress bar. Defaults to True.

        Returns:
            str: The path to the downloaded file.
        T)streami  zhAuthentication Error: You do not have permission to access this resource. Please check your credentials.zcontent-lengthr   zGWarning: Content-length header is missing or zero in the response from r   iB)totalunit
unit_scaledisablewbi   )
chunk_sizeN)ospathexistsrequestsgetstatus_codePermissionErrorintheadersprintboolr   openiter_contentupdatelenwrite)	r   r   r   r   responsetotal_size_in_bytesprogress_barfilechunks	            r   download_file_from_gcsz&ModelManagement.download_file_from_gcs-   s7    77>>+&<<D1 3&!1  "("2"2"6"67G"KL !#[\_[``abc0B]C%%%	
 
	*
 k4( *D%22d2C *E$++CJ7

5)**
	* * *
	* s*   +D8D-D?DD	DD'Nhf_source_repo	cache_dirextra_patternslocal_files_onlyc                 P    g d}||j                  |       t        d||||d|S )aD  
        Downloads a model from HuggingFace Hub.
        Args:
            hf_source_repo (str): Name of the model on HuggingFace Hub, e.g. "qdrant/all-MiniLM-L6-v2-onnx".
            cache_dir (Optional[str]): The path to the cache directory.
            extra_patterns (Optional[List[str]]): extra patterns to allow in the snapshot download, typically
                includes the required model files.
            local_files_only (bool, optional): Whether to only use local files. Defaults to False.
        Returns:
            Path: The path to the model directory.
        )zconfig.jsonztokenizer.jsonztokenizer_config.jsonzspecial_tokens_map.jsonzpreprocessor_config.json)repo_idallow_patternsr@   rB    )extendr   )r   r?   r@   rA   rB   kwargsrE   s          r   download_files_from_huggingfacez/ModelManagement.download_files_from_huggingface\   sG    (
 %!!.1  
")-	

 
 	
r   
targz_pathc                    t         j                  j                  |      st        | d      |j	                  d      st        | d      	 t        j                  |d      5 }|j                  |       ddd       |S # 1 sw Y   |S xY w# t
        j                  $ r/}d|v rt        j                  |       t        d| d	|       d}~ww xY w)
a  
        Decompresses a .tar.gz file to a cache directory.

        Args:
            targz_path (str): Path to the .tar.gz file.
            cache_dir (str): Path to the cache directory.

        Returns:
            cache_dir (str): Path to the cache directory.
        z! does not exist or is not a file..tar.gzz is not a .tar.gz file.zr:gz)r*   Ntmpz&An error occurred while decompressing z: )r)   r*   isfiler   endswithtarfiler4   
extractallTarErrorshutilrmtree)r   rJ   r@   tares        r   decompress_to_cachez#ModelManagement.decompress_to_cache   s     ww~~j)
|+LMNN ""9-
|+BCDD	Yj&1 S"      	Y 	!i(Ej\QSTUSVWXX	Ys6   B $B7B BB B C!*CC
source_urlc                 
   d|j                  d      d    }t        |      dz  }||z  }t        |      |z  }|j                         r(t        t	        |j                  d                  dkD  r|S |j                         rt        j                  |       |j                  dd       t        |      | d	z  }	|	j                         r|	j                          |s| j                  |t        |	      
       | j                  t        |	      t        |             |j                         sJ d| d|        |	j                          |j                  |       |S t        j                  d| d       t!        d| d      )Nzfast-/rM   *r   T)parentsexist_okrL   )r   )rJ   r@   zCould not find z in z(Could not find the model tar.gz file at z and local_files_only=True.)splitr   r+   r7   listglobrS   rT   mkdirunlinkr>   strrW   renamer
   errorr   )
r   r   rX   r@   rB   fast_model_namecache_tmp_dirmodel_tmp_dir	model_dirmodel_tar_gzs
             r   retrieve_model_gcsz"ModelManagement.retrieve_model_gcs   s    "*"2"23"7";!<=Y%/%7Oo5	 #d9>>#+>&?"@1"D!MM-(D48IO+<G)DD !&&- ' 
 ##s</@CP]L^#_ '')__]O4P]+__)!  +  LL:9+E`a :9+E`a r   r   retriesc                 T   |j                  dd      }|rdn|}|j                  di       j                  d      }|j                  di       j                  d      }d}|dkD  r|dz  }|rP|d	   g}	|	j                  |j                  d
g              	 t         | j                  |ft	        |      |	d|      S |s|r"	 | j                  |d   |t	        |      |      S |rt        j                  d       nt        j                  d| d| d       t        j                  |       |dz  }|dkD  rt        d|d    d      # t
        t        t        f$ r%}
|st        j                  d|
 d       Y d}
~
d}
~
ww xY w# t        $ r |st        j                  d|        Y w xY w)a  
        Downloads a model from HuggingFace Hub or Google Cloud Storage.

        Args:
            model (Dict[str, Any]): The model description.
                Example:
                ```
                {
                    "model": "BAAI/bge-base-en-v1.5",
                    "dim": 768,
                    "description": "Base English model, v1.5",
                    "size_in_GB": 0.44,
                    "sources": {
                        "url": "https://storage.googleapis.com/qdrant-fastembed/fast-bge-base-en-v1.5.tar.gz",
                        "hf": "qdrant/bge-base-en-v1.5-onnx-q",
                    }
                }
                ```
            cache_dir (str): The path to the cache directory.
            retries: (int): The number of times to retry (including the first attempt)

        Returns:
            Path: The path to the downloaded model directory.
        rB   F   sourceshfr   g      @r   
model_fileadditional_files)r@   rA   z+Could not download model from HuggingFace: z Falling back to other sources.Nr   )rB   z#Could not download model from url: z!Could not find model in cache_dirz:Could not download model from either source, sleeping for z
 seconds, z retries left.   zCould not load model z from any source.)r-   rG   r   rI   rd   EnvironmentErrorr	   r   r
   rf   rl   	Exceptiontimesleep)r   r   r@   rm   rH   rB   	hf_source
url_sourcerx   rA   rV   s              r   download_modelzModelManagement.download_model   s   8 "::&8%@'!WIIi,006	YYy"-11%8
kqLG"'"5!6%%eii0BB&GH;;;%&))n+9 %	  -	Y11g"I)9	 2    @APQVPWWabiajjxy JJuQJES kV 0w0@@QRSS7 )*A:N +I! M= = ! Y+'J:,%WXYs*   'E > F E>E99E>#F'&F')T)NNF)F)rt   )r   
__module____qualname__classmethodr   r   rd   r   r   r   r3   r>   r   rI   rW   r   rl   r0   r{   rF   r   r   r   r      s   $d4S>&: $ $ T TS#X T T& , ,3 ,t ,_b , ,\  $(.2!&#
#
 C=#
 !c+	#

 #
 
#
 #
J "S "S " "H X]***-*:=*QU*	* *X DELTcNLT/3LT>ALT	LT LTr   r   )r)   rw   rS   rP   pathlibr   typingr   r   r   r   r,   huggingface_hubr   huggingface_hub.utilsr	   logurur
   r   r   rF   r   r   <module>r      s7    	     , ,  - 9  RT RTr   