o
    shI                     @   s~  d dl Z d dlZd dlmZmZmZ d dlZd dlm	Z	m
Z
mZmZ dejdefddZddeeejf d	eeeef  defd
dZ	ddeeejf deee jf d	eeeef  ddfddZdedeeejf fddZdeee jf deeejf fddZejejejejejejejejejejej e!dZ"dedej#fddZ$deeejf fddZ%dejde!fddZ&dS )    N)DictOptionalUnion)deserialize	safe_open	serializeserialize_filetensorreturnc                 C   s   t | s
| jdd} |  S )NF)inplace)_is_little_endianbyteswaptobytes)r	    r   e/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/safetensors/numpy.py_tobytes
   s   r   tensor_dictmetadatac                 C   s*   dd |   D }t||d}t|}|S )a&  
    Saves a dictionary of tensors into raw bytes in safetensors format.

    Args:
        tensor_dict (`Dict[str, np.ndarray]`):
            The incoming tensors. Tensors need to be contiguous and dense.
        metadata (`Dict[str, str]`, *optional*, defaults to `None`):
            Optional text only metadata you might want to save in your header.
            For instance it can be useful to specify more about the underlying
            tensors. This is purely informative and does not affect tensor loading.

    Returns:
        `bytes`: The raw bytes representing the format

    Example:

    ```python
    from safetensors.numpy import save
    import numpy as np

    tensors = {"embedding": np.zeros((512, 1024)), "attention": np.zeros((256, 256))}
    byte_data = save(tensors)
    ```
    c                 S   (   i | ]\}}||j j|jt|d qS )dtypeshapedatar   namer   r   .0kvr   r   r   
<dictcomp>)      ( zsave.<locals>.<dictcomp>r   )itemsr   bytes)r   r   	flattened
serializedresultr   r   r   save   s   r'   filenamec                 C   s$   dd |   D }t|||d dS )aj  
    Saves a dictionary of tensors into raw bytes in safetensors format.

    Args:
        tensor_dict (`Dict[str, np.ndarray]`):
            The incoming tensors. Tensors need to be contiguous and dense.
        filename (`str`, or `os.PathLike`)):
            The filename we're saving into.
        metadata (`Dict[str, str]`, *optional*, defaults to `None`):
            Optional text only metadata you might want to save in your header.
            For instance it can be useful to specify more about the underlying
            tensors. This is purely informative and does not affect tensor loading.

    Returns:
        `None`

    Example:

    ```python
    from safetensors.numpy import save_file
    import numpy as np

    tensors = {"embedding": np.zeros((512, 1024)), "attention": np.zeros((256, 256))}
    save_file(tensors, "model.safetensors")
    ```
    c                 S   r   r   r   r   r   r   r   r   L   r    zsave_file.<locals>.<dictcomp>r!   N)r"   r   )r   r(   r   r$   r   r   r   	save_file/   s   r)   r   c                 C   s   t | }t|S )a  
    Loads a safetensors file into numpy format from pure bytes.

    Args:
        data (`bytes`):
            The content of a safetensors file

    Returns:
        `Dict[str, np.ndarray]`: dictionary that contains name as key, value as `np.ndarray` on cpu

    Example:

    ```python
    from safetensors.numpy import load

    file_path = "./my_folder/bert.safetensors"
    with open(file_path, "rb") as f:
        data = f.read()

    loaded = load(data)
    ```
    )r   _view2np)r   flatr   r   r   loadP   s   r,   c                 C   sR   i }t | dd}| D ]	}||||< qW d   |S 1 s"w   Y  |S )a  
    Loads a safetensors file into numpy format.

    Args:
        filename (`str`, or `os.PathLike`)):
            The name of the file which contains the tensors

    Returns:
        `Dict[str, np.ndarray]`: dictionary that contains name as key, value as `np.ndarray`

    Example:

    ```python
    from safetensors.numpy import load_file

    file_path = "./my_folder/bert.safetensors"
    loaded = load_file(file_path)
    ```
    np)	frameworkN)r   keys
get_tensor)r(   r&   fr   r   r   r   	load_filek   s   
r2   )F64F32F16I64U64I32U32I16U16I8U8BOOL	dtype_strc                 C   s   t |  S N)_TYPES)r?   r   r   r   	_getdtype   s   rB   c                 C   sF   i }| D ]\}}t |d }tj|d |d|d }|||< q|S )Nr   r   )r   r   )rB   r-   
frombufferreshape)safeviewr&   r   r   r   arrr   r   r   r*      s   
r*   c                 C   sT   | j j}|dkrtjdkrdS dS |dkrdS |dkrdS |dkr#dS td| )	N=littleTF|<>zUnexpected byte order )r   	byteordersys
ValueError)r	   rL   r   r   r   r      s   
r   r@   )'osrM   typingr   r   r   numpyr-   safetensorsr   r   r   r   ndarrayr#   r   strr'   PathLiker)   r,   r2   float64float32float16int64uint64int32uint32int16uint16int8uint8boolrA   r   rB   r*   r   r   r   r   r   <module>   sF    . 
!&	