o
    rZhB                     @   sr   d Z ddlZddlmZ zddlZW n ey   dZY nw dadddZdddZdd	d
Z	dd Z
dd ZdS )aP  
A set of functions used to interface with the external megam_ maxent
optimization package. Before megam can be used, you should tell NLTK where it
can find the megam binary, using the ``config_megam()`` function. Typical
usage:

    >>> from nltk.classify import megam
    >>> megam.config_megam() # pass path to megam if not found in PATH # doctest: +SKIP
    [Found megam: ...]

Use with MaxentClassifier. Example below, see MaxentClassifier documentation
for details.

    nltk.classify.MaxentClassifier.train(corpus, 'megam')

.. _megam: https://www.umiacs.umd.edu/~hal/megam/index.html
    N)find_binaryc                 C   s   t d| dgg dddadS )aA  
    Configure NLTK's interface to the ``megam`` maxent optimization
    package.

    :param bin: The full path to the ``megam`` binary.  If not specified,
        then nltk will search the system for a ``megam`` binary; and if
        one is not found, it will raise a ``LookupError`` exception.
    :type bin: str
    megamZMEGAM)z	megam.optr   Z	megam_686zmegam_i686.optz0https://www.umiacs.umd.edu/~hal/megam/index.html)Zenv_varsZbinary_namesurlN)r   
_megam_bin)bin r   B/var/www/auris/lib/python3.10/site-packages/nltk/classify/megam.pyconfig_megam)   s   
r	   Tc                    s      }dd t|D }| D ]J\t dr*|d fdd|D  n	|d|   |s@t || n|D ]}|d t ||| qB|d	 qd
S )a  
    Generate an input file for ``megam`` based on the given corpus of
    classified tokens.

    :type train_toks: list(tuple(dict, str))
    :param train_toks: Training data, represented as a list of
        pairs, the first member of which is a feature dictionary,
        and the second of which is a classification label.

    :type encoding: MaxentFeatureEncodingI
    :param encoding: A feature encoding, used to convert featuresets
        into feature vectors. May optionally implement a cost() method
        in order to assign different costs to different class predictions.

    :type stream: stream
    :param stream: The stream to which the megam input file should be
        written.

    :param bernoulli: If true, then use the 'bernoulli' format.  I.e.,
        all joint features have binary values, and are listed iff they
        are true.  Otherwise, list feature values explicitly.  If
        ``bernoulli=False``, then you must call ``megam`` with the
        ``-fvals`` option.

    :param explicit: If true, then use the 'explicit' format.  I.e.,
        list the features that would fire for any of the possible
        labels, for each token.  If ``explicit=True``, then you must
        call ``megam`` with the ``-explicit`` option.
    c                 S   s   i | ]\}}||qS r   r   ).0ilabelr   r   r   
<dictcomp>b   s    z$write_megam_file.<locals>.<dictcomp>cost:c                 3   s"    | ]}t  |V  qd S N)strr   )r
   lencodingZ
featuresetr   r   r   	<genexpr>i   s     z#write_megam_file.<locals>.<genexpr>z%dz #
N)labels	enumeratehasattrwritejoin_write_megam_featuresencode)Z
train_toksr   stream	bernoulliexplicitr   Zlabelnumr   r   r   r   write_megam_fileB   s   

r!   c                 C   sh   t du rtd|sJ d|  d}t |d}|D ]}| r1| \}}t||t|< q|S )z
    Given the stdout output generated by ``megam`` when training a
    model, return a ``numpy`` array containing the corresponding weight
    vector.  This function does not currently handle bias features.
    Nz.This function requires that numpy be installedznon-explicit not supported yetr   d)numpy
ValueErrorstripsplitZzerosfloatint)sZfeatures_countr    linesweightslinefidweightr   r   r   parse_megam_weights~   s   r/   c                 C   sb   | st d| D ]&\}}|r#|dkr|d|  q|dkr"t dq|d| d|  qd S )Nz:MEGAM classifier requires the use of an always-on feature.   z %sr   z3If bernoulli=True, then allfeatures must be binary. )r$   r   )Zvectorr   r   r-   Zfvalr   r   r   r      s   r   c                 C   s~   t | tr	tdtdu rt  tg|  }tj|tjd}| \}}|j	dkr3t
  t
| tdt |tr:|S |dS )z=
    Call the ``megam`` binary with the given arguments.
    z args should be a list of stringsN)stdoutr   zmegam command failed!zutf-8)
isinstancer   	TypeErrorr   r	   
subprocessPopenPIPEcommunicate
returncodeprintOSErrordecode)argscmdpr2   stderrr   r   r   
call_megam   s   




rA   r   )TT)T)__doc__r5   Znltk.internalsr   r#   ImportErrorr   r	   r!   r/   r   rA   r   r   r   r   <module>   s   


<