o
    7tis                     @   s   d Z ddlZddlZddlmZ ddlmZmZm	Z	 ddl
Z
ddlmZ ddlmZ dZdd	 Zd
d ZG dd deZdZdZdd ZG dd deZdS )al  
In the dynamic landscape of generative NLP, traditional text processing pipelines limit research flexibility and reproducibility, as they are tailored to specific dataset, task, and model combinations. The escalating complexity, involving system prompts, model-specific formats, instructions, and more, calls for a shift to a structured, modular, and customizable solution.

Addressing this need, we present Unitxt, an innovative library for customizable textual data preparation and evaluation tailored to generative language models. Unitxt natively integrates with common libraries like HuggingFace and LM-eval-harness and deconstructs processing flows into modular components, enabling easy customization and sharing between practitioners. These components encompass model-specific formats, task prompts, and many other comprehensive dataset processing definitions. The Unitxt-Catalog centralizes these components, fostering collaboration and exploration in modern textual data workflows. Beyond being a tool, Unitxt is a community-driven platform, empowering users to build, share, and advance their pipelines collaboratively.
    N)partial)AnyDictOptional)Instance)ConfigurableTaska  
@misc{bandel2024unitxt,
      title={Unitxt: Flexible, Shareable and Reusable Data Preparation and Evaluation for Generative AI},
      author={Elron Bandel and Yotam Perlitz and Elad Venezian and Roni Friedman-Melamed and Ofir Arviv and Matan Orbach and Shachar Don-Yehyia and Dafna Sheinwald and Ariel Gera and Leshem Choshen and Michal Shmueli-Scheuer and Yoav Katz},
      year={2024},
      eprint={2401.14019},
      archivePrefix={arXiv},
      primaryClass={cs.CL}
}
c                  C   sL   t jdd u rtdddlm}  ttt| 	d} | dk r$tdd S )Nunitxtz`Please install unitxt via 'pip install unitxt'. For more information see: https://www.unitxt.ai/r   )__version__.)         zyPlease install a more recent version of unitxt via 'pip install --upgrade unitxt' to avoid errors due to breaking changes)
	importlibutil	find_spec	Exceptionr   r	   tuplemapintsplit)unitxt_version r   M/home/ubuntu/.local/lib/python3.10/site-packages/lm_eval/tasks/unitxt/task.pyassert_unitxt_installed   s   r   c                 C   sP   t |  \}}t  ddlm} |D ]}|g|d< q|||}|d d d d S )Nr   )evaluatemetricsscoreglobal)zipr   r   r   )itemsmetricpredictions
referencesr   	referenceresultsr   r   r   r   .   s   
r   c                       s   e Zd ZdZ	d(dee ddf fddZd(deeee	f  ddfdd	Z
d
d Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdef fddZd d! Zd"d# Zd$d% Zd&d' Z  ZS ))Unitxtr   Nconfigreturnc                    s\   |d u ri }d|v sJ dt  jd| ji|d dd t | _| jd d d | _d S )	Nrecipez(Unitxt task must have a 'recipe' string.version)metadatadataset_name)r&   testr   r   )super__init__VERSIONdatasetsImageimage_decoderdatasetr   )selfr&   	__class__r   r   r.   <   s   
zUnitxt.__init__dataset_kwargsc                 C   s&   t   ddlm} || jdd| _d S )Nr   )load_datasetT)	use_cache)r   r   r8   DATASET_NAMEr3   )r4   r7   r8   r   r   r   downloadL   s   zUnitxt.downloadc                 C   
   d| j v S Ntrainr3   r4   r   r   r   has_training_docsR      
zUnitxt.has_training_docsc                 C   r<   N
validationr?   r@   r   r   r   has_validation_docsU   rB   zUnitxt.has_validation_docsc                 C   r<   Nr,   r?   r@   r   r   r   has_test_docsX   rB   zUnitxt.has_test_docsc                 C   
   | j d S r=   r?   r@   r   r   r   training_docs[   rB   zUnitxt.training_docsc                 C   rH   rC   r?   r@   r   r   r   validation_docs^   rB   zUnitxt.validation_docsc                 C   rH   rF   r?   r@   r   r   r   	test_docsa   rB   zUnitxt.test_docsc                 C      |d S )Nsourcer   r4   docr   r   r   doc_to_textd      zUnitxt.doc_to_textc                 C   s   dS )NFr   r@   r   r   r   should_decontaminateg   s   zUnitxt.should_decontaminatec                 C   rL   )Ntargetr   rN   r   r   r   doc_to_targetj   rQ   zUnitxt.doc_to_targetc                 C   s   |ddgifS )Nuntil
r   r4   rO   ctxr   r   r   get_argumentsm   s   zUnitxt.get_argumentsc                    sT   t | |tr|dr|d}|| |}|S tdt jdd|i|S )Napply_chat_templatechat_templateztGot chat template format from Unitxt, but apply_chat_template is false. Add '--apply_chat_template' to command line.rO   r   )
isinstancerP   listgetr   r-   fewshot_context)r4   rO   kwargsr[   formated_sourcer5   r   r   r_   p   s   

zUnitxt.fewshot_contextc                 K   s:   | dd | dd tdd|| ||dd|gS )	a  Uses RequestFactory to construct Requests and returns an iterable of
        Requests which will be sent to the LM.

        :param doc:
            The document as returned from training_docs, validation_docs, or test_docs.
        :param ctx: str
            The context string, generated by fewshot_context. This includes the natural
            language description, as well as the few shot examples, and the question
            part of the document for `doc`.
        rZ   Fr[   generate_untilr   )request_typerO   	argumentsidxNr   )popr   rY   )r4   rO   rX   r`   r   r   r   construct_requests}   s   
zUnitxt.construct_requestsc                    s&   |d }| | fdd| j D S )a  Take a single document and the LM results and evaluates, returning a
        dict where keys are the names of submetrics and values are the values of
        the metric for that one document

        :param doc:
            The document as returned from training_docs, validation_docs, or test_docs.
        :param results:
            The results of the requests created in construct_requests.
        r   c                    s   i | ]}| d d fqS )metrics. replace.0r    r!   r"   r   r   
<dictcomp>   s    z*Unitxt.process_results.<locals>.<dictcomp>r   )r4   rO   r$   continuationr   rn   r   process_results   s   zUnitxt.process_resultsc                 C      dd | j D S )z
        :returns: {str: [float] -> float}
            A dictionary where keys are the names of submetrics and values are
            functions that aggregate a list of metrics
        c                 S   s"   i | ]}| d dtt|dqS )rh   ri   )r    )rk   r   r   rl   r   r   r   ro      s    z&Unitxt.aggregation.<locals>.<dictcomp>rp   r@   r   r   r   aggregation   s   zUnitxt.aggregationc                 C   rs   )z
        :returns: {str: bool}
            A dictionary where keys are the names of submetrics and values are
            whether a higher value of the submetric is better
        c                 S   s   i | ]	}| d ddqS )rh   ri   Trj   rl   r   r   r   ro      s    z+Unitxt.higher_is_better.<locals>.<dictcomp>rp   r@   r   r   r   higher_is_better   s   zUnitxt.higher_is_better)N)__name__
__module____qualname__r/   r   dictr.   r   strr   r;   rA   rE   rG   rI   rJ   rK   rP   rR   rT   rY   r_   rg   rr   rt   ru   __classcell__r   r   r5   r   r%   9   s0     r%   z <img\s+src=["\'](.*?)["\']\s*/?>z<img\s+src=["\'](.*?)["\']c                 C   sT   t t| }g }|D ]}|}|dD ]}| rt|}|| }q|| q
|S )N/)refindallimage_source_regexr   isdigitr   append)textinstanceimage_sourcesimagesimage_sourcecurrentkeyr   r   r   extract_images   s   
r   c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	UnitxtMultiModalTc                 C   s   t td|d S )Nz<image>rM   )r}   subimages_regexrN   r   r   r   rP      s   zUnitxtMultiModal.doc_to_textc                    s    t |d |} fdd|D S )NrM   c                    s   g | ]} j |qS r   )r2   decode_example)rm   imager@   r   r   
<listcomp>   s    z1UnitxtMultiModal.doc_to_image.<locals>.<listcomp>)r   )r4   rO   r   r   r@   r   doc_to_image   s   zUnitxtMultiModal.doc_to_imagec                 C   s   |ddgid|  |ifS )NrU   rV   visual)r   rW   r   r   r   rY      s   zUnitxtMultiModal.get_argumentsN)rv   rw   rx   
MULTIMODALrP   r   rY   r   r   r   r   r      s
    r   )__doc__importlib.utilr   r}   	functoolsr   typingr   r   r   r0   lm_eval.api.instancer   lm_eval.api.taskr   	_CITATIONr   r   r%   r   r   r   r   r   r   r   r   <module>   s"     