o
    i.                     @   s  d dl Z d dlmZ d dlmZmZmZmZmZm	Z	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mZmZmZ ddlmZ dd	lmZ dd
lmZmZ ddlmZ ddlmZ ddl m!Z" ddl m#Z# G dd dZ$dd Z%dd Z&dd Z'e(e$e&e' e$Z)dgZ*dS )    N)Path)DictIterableIteratorListOptionalSetUnion)ndarray)NumpyOps   )IDSORTHSPACYintify_attr)copy_reg)Errors)SimpleFrozenListensure_path)Vocab   )
SpanGroups)DOCBIN_ALL_ATTRS)Docc                	   @   s   e Zd ZdZede fdee dedee	 ddfdd	Z
defd
dZde	ddfddZdedee	 fddZdddZdefddZdedd fddZdeeef ddfddZdeeef dd fddZdS ) DocBina  Pack Doc objects for binary serialization.

    The DocBin class lets you efficiently serialize the information from a
    collection of Doc objects. You can control which information is serialized
    by passing a list of attribute IDs, and optionally also specify whether the
    user data is serialized. The DocBin is faster and produces smaller data
    sizes than pickle, and allows you to deserialize without executing arbitrary
    Python code.

    The serialization format is gzipped msgpack, where the msgpack object has
    the following structure:

    {
        "attrs": List[uint64], # e.g. [TAG, HEAD, ENT_IOB, ENT_TYPE]
        "tokens": bytes, # Serialized numpy uint64 array with the token data
        "spans": List[Dict[str, bytes]], # SpanGroups data for each doc
        "spaces": bytes, # Serialized numpy boolean array with spaces data
        "lengths": bytes, # Serialized numpy int32 array with the doc lengths
        "strings": List[str] # List of unique strings in the token data
        "version": str, # DocBin version number
    }

    Strings for the words, tags, labels etc are represented by 64-bit hashes in
    the token data, and every string that occurs at least once is passed via the
    strings object. This means the storage is more efficient if you pack more
    documents together, because you have less duplication in the strings.

    A notable downside to this format is that you can't easily extract just one
    document from the DocBin.
    Fattrsstore_user_datadocsreturnNc                 C   s   dd |D }d|v r dd |D }t tjjd|t ddt|}d| _dd |D | _| j	d	t
 g | _g | _g | _g | _g | _g | _t | _|| _|D ]}| | qQdS )
a~  Create a DocBin object to hold serialized annotations.

        attrs (Iterable[str]): List of attributes to serialize. 'orth' and
            'spacy' are always serialized, so they're not required.
        store_user_data (bool): Whether to write the `Doc.user_data` to bytes/file.
        docs (Iterable[Doc]): Docs to add.

        DOCS: https://spacy.io/api/docbin#init
        c                 S      g | ]}t |qS  r   .0attrr    r    K/home/ubuntu/.local/lib/python3.10/site-packages/spacy/tokens/_serialize.py
<listcomp>C       z#DocBin.__init__.<locals>.<listcomp>Nc                 S   s   g | ]
}t |d u r|qS Nr!   r"   r    r    r%   r&   E   s    r   )dictkeykeysz0.1c                 S   s    g | ]}|t kr|tkr|qS r    )r   r   r"   r    r    r%   r&   K   s     r   )KeyErrorr   E983formatr   r+   sortedversionr   insertr   tokensspacescatsspan_groups	user_dataflagssetstringsr   add)selfr   r   r   	int_attrs	non_validdocr    r    r%   __init__4   s.   zDocBin.__init__c                 C   s
   t | jS )z7RETURNS: The number of Doc objects added to the DocBin.)lenr2   )r;   r    r    r%   __len__X   s   
zDocBin.__len__r>   c                 C   s  | | j}t|jdkr||jd df}| j| | t}|jd |jd ks.J ||jd df}| jt	j
|td | jd|ji |D ]C}| j|j | j|j | j|j | j|j | jt|j | j|j | j|j | j|j | j|j qN| j|j | jr| jt|j | j|j !  |j " D ].\}}|D ]'}| j|j# |j$|j%j&jv r| j|j' |j(|j%j&jv r| j|j) qqdS )zAdd a Doc's annotations to the DocBin for serialization.

        doc (Doc): The Doc object to add.

        DOCS: https://spacy.io/api/docbin#add
        r   r   dtypehas_unknown_spacesN)*to_arrayr   r@   shapereshaper2   appendr   r3   numpyasarrayboolr7   rD   r9   r:   texttag_lemma_norm_strmorphdep_	ent_type_
ent_kb_id_ent_id_r4   r   r6   srslymsgpack_dumpsr5   spansto_bytesitemslabel_kb_idr>   vocabkb_id_idid_)r;   r>   arrayr3   tokenr*   groupspanr    r    r%   r:   \   sB   
z
DocBin.addr]   c           
      c   s   | j D ]}||  q| jt}tt| jD ]o}| j| }| j| }| j| }|	dr0d}t
||dd|f |d}|| j|}| j| |_| j| ra| j| tjkra|j| j|  n|j  |t| jk r| j| durtj| j| dd}	|j|	 |V  qdS )aa  Recover Doc objects from the annotations, using the given vocab.
        Note that the user data of each doc will be read (if available) and returned,
        regardless of the setting of 'self.store_user_data'.

        vocab (Vocab): The shared vocab.
        YIELDS (Doc): The Doc objects.

        DOCS: https://spacy.io/api/docbin#get_docs
        rD   N)wordsr3   F)use_list)r9   r   indexr   ranger@   r2   r7   r3   getr   
from_arrayr4   r5   r   _EMPTY_BYTESrX   
from_bytesclearr6   rV   msgpack_loadsupdate)
r;   r]   stringorth_colir7   r2   r3   r>   r6   r    r    r%   get_docs   s*   







zDocBin.get_docsotherc                 C   s   | j |j krttjjd| j |j d| j|jkr&ttjjd| j|jd| j|j | j|j | j	
|j	 | j|j | j|j | j|j | j|j dS )ab  Extend the annotations of this DocBin with the annotations from
        another. Will raise an error if the pre-defined attrs of the two
        DocBins don't match, or if they differ in whether or not to store
        user data.

        other (DocBin): The DocBin to merge into the current bin.

        DOCS: https://spacy.io/api/docbin#merge
        r   )paramcurrentrt   r   N)r   
ValueErrorr   E166r.   r   r2   extendr3   r9   ro   r4   r5   r7   r6   )r;   rt   r    r    r%   merge   s&   
zDocBin.mergec              
   C   s   | j D ]}t|jdksJ |jqdd | j D }| j r#t| j ntg }| jr1t| jntg }| j| j|	d|	dtj|dd	dt
t| j| j| j| jd	}| jrb| j|d< tt|S )	zSerialize the DocBin's annotations to a bytestring.

        RETURNS (bytes): The serialized DocBin.

        DOCS: https://spacy.io/api/docbin#to_bytes
        r   c                 S   r   r    )r@   )r#   r2   r    r    r%   r&      r'   z#DocBin.to_bytes.<locals>.<listcomp>Cint32rB   )	r0   r   r2   r3   lengthsr9   r4   r7   r5   r6   )r2   r@   rF   rI   vstackrJ   r3   r0   r   tobyteslistr/   r9   r4   r7   r5   r   r6   zlibcompressrV   rW   )r;   r2   r}   r3   msgr    r    r%   rY      s$   

zDocBin.to_bytes
bytes_datac                 C   s\  z
t t|}W n tjy   ttjw |d | _t	|d | _
tj|d dd}tj|d td}tj|d dd}|jt| j t| jf}||}||jd	f}t ||| _t ||| _|d
 | _|ddd |D | _|ddd |D | _d|v rt|d | _ndgt|  | _| jD ]}t|jdksJ |jq| S )zDeserialize the DocBin's annotations from a bytestring.

        bytes_data (bytes): The data to load from.
        RETURNS (DocBin): The loaded DocBin.

        DOCS: https://spacy.io/api/docbin#from_bytes
        r   r9   r}   r|   rB   r3   r2   uint64r   r4   r5   c                 S   s   g | ]}d qS )    r    r#   _r    r    r%   r&          z%DocBin.from_bytes.<locals>.<listcomp>r7   c                 S   s   g | ]}i qS r    r    r   r    r    r%   r&      r   r6   Nr   )rV   rn   r   
decompresserrorrw   r   E1014r   r8   r9   rI   
frombufferrK   sizer@   rG   r   	unflattenr2   r3   r4   ri   r5   r7   r   r6   rF   )r;   r   r   r}   flat_spacesflat_tokensrF   r2   r    r    r%   rl      s0   




zDocBin.from_bytespathc              	   C   sd   t |}|d}z	||   W n ty   ttjw W d   dS 1 s+w   Y  dS )zSave the DocBin to a file (typically called .spacy).

        path (str / Path): The file path.

        DOCS: https://spacy.io/api/docbin#to_disk
        wbN)r   openwriterY   rw   r   E870r;   r   file_r    r    r%   to_disk   s   
"zDocBin.to_diskc                 C   sF   t |}|d}| |  W d   | S 1 sw   Y  | S )zLoad the DocBin from a file (typically called .spacy).

        path (str / Path): The file path.
        RETURNS (DocBin): The loaded DocBin.

        DOCS: https://spacy.io/api/docbin#to_disk
        rbN)r   r   rl   readr   r    r    r%   	from_disk
  s   
zDocBin.from_disk)rt   r   r   N)__name__
__module____qualname____doc__	ALL_ATTRSr   r   rP   rK   r   r?   intrA   r:   r   r   rs   rz   bytesrY   rl   r	   r   r   r   r    r    r    r%   r      s,    !
$&
 !r   c                 C   sR   d }| D ]}|d urt dd|}|d u r|}q|| q|d ur'| S dS )NT)r   r   )r   rl   rz   rY   )binsmergedbyte_stringdoc_binr    r    r%   
merge_bins  s   
r   c                 C   s   t |  ffS r(   )unpickle_binrY   )r   r    r    r%   
pickle_bin'  s   r   c                 C   s   t  | S r(   )r   rl   )r   r    r    r%   r   +  s   r   )+r   pathlibr   typingr   r   r   r   r   r   r	   rI   rV   r
   	thinc.apir   r   r   r   r   r   compatr   errorsr   utilr   r   r]   r   _dict_proxiesr   r>   r   r   r   r   r   r   r   pickleBinder__all__r    r    r    r%   <module>   s0    $  
