o
    Qer(  ã                   @   sœ   d 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m	Z	 ddl
Z
ddlmZ ddlmZ ddlmZ g ZdZdZd	Zd
ZdZdZdZG dd„ deƒZdS )Ú
é    )Úprint_functionN)Údefaultdict)ÚDataset)Ú_check_exists_and_downloadz2http://paddlemodels.bj.bcebos.com/wmt/wmt16.tar.gzZ 0c38be43600334966403524a40dcd81eiò+  iK  z<s>z<e>z<unk>c                   @   sZ   e Zd ZdZ						ddd„Zdd
d„Zdd„ Zdd„ Zdd„ Zdd„ Z	ddd„Z
dS )ÚWMT16a{
  
    Implementation of `WMT16 <http://www.statmt.org/wmt16/>`_ test dataset.
    ACL2016 Multimodal Machine Translation. Please see this website for more
    details: http://www.statmt.org/wmt16/multimodal-task.html#task1

    If you use the dataset created for your task, please cite the following paper:
    Multi30K: Multilingual English-German Image Descriptions.

    .. code-block:: text

        @article{elliott-EtAl:2016:VL16,
         author    = {{Elliott}, D. and {Frank}, S. and {Sima"an}, K. and {Specia}, L.},
         title     = {Multi30K: Multilingual English-German Image Descriptions},
         booktitle = {Proceedings of the 6th Workshop on Vision and Language},
         year      = {2016},
         pages     = {70--74},
         year      = 2016
        }

    Args:
        data_file(str): path to data tar file, can be set None if
            :attr:`download` is True. Default None
        mode(str): 'train', 'test' or 'val'. Default 'train'
        src_dict_size(int): word dictionary size for source language word. Default -1.
        trg_dict_size(int): word dictionary size for target language word. Default -1.
        lang(str): source language, 'en' or 'de'. Default 'en'.
        download(bool): whether to download dataset automatically if
            :attr:`data_file` is not set. Default True

    Returns:
        Dataset: Instance of WMT16 dataset. The instance of dataset has 3 fields:
            - src_ids (np.array) - The sequence of token ids of source language.
            - trg_ids (np.array) - The sequence of token ids of target language.
            - trg_ids_next (np.array) - The next sequence of token ids of target language.

    Examples:

        .. code-block:: python

            import paddle
            from paddle.text.datasets import WMT16

            class SimpleNet(paddle.nn.Layer):
                def __init__(self):
                    super(SimpleNet, self).__init__()

                def forward(self, src_ids, trg_ids, trg_ids_next):
                    return paddle.sum(src_ids), paddle.sum(trg_ids), paddle.sum(trg_ids_next)

            paddle.disable_static()

            wmt16 = WMT16(mode='train', src_dict_size=50, trg_dict_size=50)

            for i in range(10):
                src_ids, trg_ids, trg_ids_next = wmt16[i]
                src_ids = paddle.to_tensor(src_ids)
                trg_ids = paddle.to_tensor(trg_ids)
                trg_ids_next = paddle.to_tensor(trg_ids_next)

                model = SimpleNet()
                src_ids, trg_ids, trg_ids_next = model(src_ids, trg_ids, trg_ids_next)
                print(src_ids.numpy(), trg_ids.numpy(), trg_ids_next.numpy())

    NÚtrainéÿÿÿÿÚenTc                 C   sÞ   |  ¡ dv sJ d |¡ƒ‚|  ¡ | _|| _| jd u r)|s J dƒ‚t|ttd|ƒ| _|| _|dks4J dƒ‚|dks<J dƒ‚t||dkrDt	nt
ƒ| _t||dkrPt
nt	ƒ| _|  ||¡| _|  |dkrcdnd|¡| _|  ¡ | _d S )	N)r   ÚtestÚvalz3mode should be 'train', 'test' or 'val', but got {}z>data_file is not set and downloading automatically is disabledZwmt16r   z*dict_size should be set as positive numberr
   Úde)ÚlowerÚformatÚmodeÚ	data_filer   ÚDATA_URLÚDATA_MD5ÚlangÚminÚTOTAL_EN_WORDSÚTOTAL_DE_WORDSÚsrc_dict_sizeÚtrg_dict_sizeÚ
_load_dictÚsrc_dictÚtrg_dictÚ
_load_dataÚdata)Úselfr   r   r   r   r   Údownload© r!   úJD:\Projects\ConvertPro\env\Lib\site-packages\paddle/text/datasets/wmt16.pyÚ__init__m   s2   ÿ

þÿÿÿzWMT16.__init__Fc                 C   sè   t j tjjjd||f ¡}d}t j |¡r3t|dƒ�}t	| 
¡ ƒ|k}W d   ƒ n1 s.w   Y  |s<|  |||¡ i }t|dƒ�'}t|ƒD ]\}	}
|rXt |
 ¡ ¡||	< qH|	|t |
 ¡ ¡< qHW d   ƒ |S 1 smw   Y  |S )Núwmt16/%s_%d.dictFÚrb)ÚosÚpathÚjoinÚpaddleÚdatasetÚcommonÚ	DATA_HOMEÚexistsÚopenÚlenÚ	readlinesÚ_build_dictÚ	enumerateÚcptÚto_textÚstrip)r   r   Ú	dict_sizeÚreverseÚ	dict_pathZ
dict_foundÚdÚ	word_dictZfdictÚidxÚliner!   r!   r"   r   �   s*   
ÿÿü
ÿúzWMT16._load_dictc              	   C   sZ  t tƒ}tj| jdd��?}| d¡D ]1}t |¡}| ¡  	d¡}t
|ƒdkr'q| jdkr0|d n|d }| 	¡ D ]
}	||	  d7  < q8qW d   ƒ n1 sNw   Y  t|d	ƒ�K}
|
 t d
tttf ¡¡ ttt |¡dd„ dd�ƒD ]\}}|d |kr€ n|
 t |d ¡¡ |
 t d¡¡ qtW d   ƒ d S W d   ƒ d S 1 s¦w   Y  d S )NÚr©r   zwmt16/trainú	é   r
   r   é   Úwbz	%s
%s
%s
c                 S   s   | d S )NrA   r!   )Úxr!   r!   r"   Ú<lambda>²   s    z#WMT16._build_dict.<locals>.<lambda>T)Úkeyr7   é   r   )r   ÚintÚtarfiler.   r   Úextractfiler3   r4   r5   Úsplitr/   r   ÚwriteÚto_bytesÚ
START_MARKÚEND_MARKÚUNK_MARKr2   ÚsortedÚsixÚ	iteritems)r   r8   r6   r   r:   Úfr<   Ú
line_splitZsenÚwZfoutr;   Úwordr!   r!   r"   r1   ¢   s:   
ÿûÿ	ÿ
þÿúý"ùzWMT16._build_dictc                    sB  ˆ j t }ˆ j t }ˆ j t ‰ˆ jdkrdnd}d| }g ˆ _g ˆ _g ˆ _tj	ˆ j
dd��j}| d ˆ j¡¡D ]W}t |¡}| ¡  d¡}t|ƒdkrLq7||  ¡ }|g‡ ‡fd	d
„|D ƒ |g }	||  ¡ }
‡ ‡fdd
„|
D ƒ}||g }|g| }ˆ j |	¡ ˆ j |¡ ˆ j |¡ q7W d   ƒ d S 1 sšw   Y  d S )Nr
   r   rA   r=   r>   zwmt16/{}r?   r@   c                    ó   g | ]	}ˆ j  |ˆ¡‘qS r!   )r   Úget©Ú.0rU   ©r   Zunk_idr!   r"   Ú
<listcomp>Í   s    ÿz$WMT16._load_data.<locals>.<listcomp>c                    rW   r!   )r   rX   rY   r[   r!   r"   r\   Ò   s    )r   rM   rN   rO   r   Úsrc_idsÚtrg_idsÚtrg_ids_nextrH   r.   r   rI   r   r   r3   r4   r5   rJ   r/   Úappend)r   Zstart_idZend_idZsrc_colZtrg_colrS   r<   rT   Z	src_wordsr]   Z	trg_wordsr^   r_   r!   r[   r"   r   ¸   s:   



ÿþ

î"ÿzWMT16._load_datac                 C   s.   t  | j| ¡t  | j| ¡t  | j| ¡fS ©N)ÚnpÚarrayr]   r^   r_   )r   r;   r!   r!   r"   Ú__getitem__Û   s   ÿzWMT16.__getitem__c                 C   s
   t | jƒS ra   )r/   r]   )r   r!   r!   r"   Ú__len__ß   s   
zWMT16.__len__c                 C   sV   || j kr| jn| j}tj tjjj	d||f ¡}tj 
|¡s#J dƒ‚	 	 |  ||¡S )aŸ  
        return the word dictionary for the specified language.

        Args:
            lang(string): A string indicating which language is the source
                          language. Available options are: "en" for English
                          and "de" for Germany.
            reverse(bool): If reverse is set to False, the returned python
                           dictionary will use word as key and use index as value.
                           If reverse is set to True, the returned python
                           dictionary will use index as key and word as value.

        Returns:
            dict: The word dictionary for the specific language.

        Examples:
    
            .. code-block:: python
    
                from paddle.text.datasets import WMT16
                wmt16 = WMT16(mode='train', src_dict_size=50, trg_dict_size=50)
                en_dict = wmt16.get_dict('en')

        r$   z Word dictionary does not exist. )r   r   r   r&   r'   r(   r)   r*   r+   r,   r-   r   )r   r   r7   r6   r8   r!   r!   r"   Úget_dictâ   s   
ÿzWMT16.get_dict)Nr   r	   r	   r
   T)F)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r#   r   r1   r   rd   re   rf   r!   r!   r!   r"   r   +   s    B
ú
"#r   )rj   Ú
__future__r   r&   rQ   rH   Únumpyrb   Úcollectionsr   r)   Z	paddle.ior   Zpaddle.compatÚcompatr3   Zpaddle.dataset.commonr   Ú__all__r   r   r   r   rM   rN   rO   r   r!   r!   r!   r"   Ú<module>   s(   