
    kh[K                         d 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	 ddl
mZ ddlmZmZ eefZd Zd	 Zd
 Zd Z G d d      Z G d de      Z G d de      Z G d de      Z G d de      Z G d de      Zy)a  Various classifier implementations. Also includes basic feature extractor
methods.

Example Usage:
::

    >>> from textblob import TextBlob
    >>> from textblob.classifiers import NaiveBayesClassifier
    >>> train = [
    ...     ('I love this sandwich.', 'pos'),
    ...     ('This is an amazing place!', 'pos'),
    ...     ('I feel very good about these beers.', 'pos'),
    ...     ('I do not like this restaurant', 'neg'),
    ...     ('I am tired of this stuff.', 'neg'),
    ...     ("I can't deal with this", 'neg'),
    ...     ("My boss is horrible.", "neg")
    ... ]
    >>> cl = NaiveBayesClassifier(train)
    >>> cl.classify("I feel amazing!")
    'pos'
    >>> blob = TextBlob("The beer is good. But the hangover is horrible.", classifier=cl)
    >>> for s in blob.sentences:
    ...     print(s)
    ...     print(s.classify())
    ...
    The beer is good.
    pos
    But the hangover is horrible.
    neg

.. versionadded:: 0.6.0
    )chainN)cached_property)FormatError)word_tokenize)is_filelike
strip_puncc                 \    d t        j                  fd| D              }t        |      S )zReturn a set of all words in a dataset.

    :param dataset: A list of tuples of the form ``(words, label)`` where
        ``words`` is either a string of a list of tokens.
    c                 @    t        | t              rt        | d      S | S )NFinclude_punc)
isinstance
basestringr   )wordss    P/opt/mcp/mcp-sentiment/venv/lib/python3.12/site-packages/textblob/classifiers.pytokenizez)_get_words_from_dataset.<locals>.tokenize:   s    eZ( U;;L    c              3   4   K   | ]  \  }} |        y wN ).0r   _r   s      r   	<genexpr>z*_get_words_from_dataset.<locals>.<genexpr>@   s     #LqHUO#Ls   )r   from_iterableset)dataset	all_wordsr   s     @r   _get_words_from_datasetr   1   s*     ###LG#LLIy>r   c                     t        | t              rt        d t        | d      D              }|S t        d | D              }|S )Nc              3   6   K   | ]  }t        |d         ywF)allNr   r   ws     r   r   z'_get_document_tokens.<locals>.<genexpr>F   s"      
 qe$$
   Fr   c              3   6   K   | ]  }t        |d         ywr    r"   r#   s     r   r   z'_get_document_tokens.<locals>.<genexpr>K   s     @!Zu--@r%   )r   r   r   r   )documenttokenss     r   _get_document_tokensr)   D   sH    (J' 
"8%@
 
 M @x@@Mr   c                    	 t        t        |            }t        |t              rt        |g|      D cg c]  }| }}n,	 t        |d   t              sJ t        t        |g|            }t        |       t        fd|D              }|S # t        $ r i cY S w xY wc c}w # t        $ r}t        d      |d}~ww xY w)a_  A basic document feature extractor that returns a dict indicating
    what words in ``train_set`` are contained in ``document``.

    :param document: The text to extract features from. Can be a string or an iterable.
    :param list train_set: Training data set, a list of tuples of the form
        ``(words, label)`` OR an iterable of strings.
    r   z train_set is probably malformed.Nc              3   2   K   | ]  }d | d|v f  yw)	contains()Nr   )r   wordr(   s     r   r   z"basic_extractor.<locals>.<genexpr>f   s#     Vya(46>;Vs   )nextiterStopIterationr   r   r   r   	Exception
ValueErrorr)   dict)r'   	train_setel_zeror$   word_featureserrorfeaturesr(   s          @r   basic_extractorr:   O   s    tI' ':&$)7)Y$?@q@@	Lgaj*5553E7)Y4OPM "(+FVVVHO  	 A
  	L?@eK	Ls.   B 	B +B% BB%	B?.B::B?c                 @    t        |       }t        d |D              }|S )zdA basic document feature extractor that returns a dict of words that
    the document contains.
    c              3   ,   K   | ]  }d | ddf  yw)r,   r-   TNr   r#   s     r   r   z%contains_extractor.<locals>.<genexpr>o   s     =y1%t,=s   )r)   r4   )r'   r(   r9   s      r   contains_extractorr=   j   s#     "(+F=f==HOr   c                   L    e Zd ZdZedfdZd
dZed        Zd Z	d Z
d Zd	 Zy)BaseClassifiera  Abstract classifier class from which all classifers inherit. At a
    minimum, descendant classes must implement a ``classify`` method and have
    a ``classifier`` property.

    :param train_set: The training set, either a list of tuples of the form
        ``(text, classification)`` or a file-like object. ``text`` may be either
        a string or an iterable.
    :param callable feature_extractor: A feature extractor function that takes one or
        two arguments: ``document`` and ``train_set``.
    :param str format: If ``train_set`` is a filename, the file format, e.g.
        ``"csv"`` or ``"json"``. If ``None``, will attempt to detect the
        file format.
    :param kwargs: Additional keyword arguments are passed to the constructor
        of the :class:`Format <textblob.formats.BaseFormat>` class used to
        read the data. Only applies when a file-like object is passed as
        ``train_set``.

    .. versionadded:: 0.6.0
    Nc                     || _         || _        t        |      r| j                  ||      | _        n|| _        t        | j                        | _        d | _        y r   )format_kwargsfeature_extractorr   
_read_datar5   r   	_word_settrain_features)selfr5   rB   formatkwargss        r   __init__zBaseClassifier.__init__   sR     $!2y!!__Y?DN&DN0NN
 #r   c                     |s"t        j                  |      }|sEt        d      t        j                         }||j	                         vrt        d| d      ||   } ||fi | j                  j                         S )zhReads a data file and returns an iterable that can be used
        as testing or training data.
        z@Could not automatically detect format for the given data source.'z' format not supported.)formatsdetectr   get_registrykeysr3   rA   to_iterable)rF   r   rG   format_classregistrys        r   rC   zBaseClassifier._read_data   s    
 ">>'2L!# 
 ++-HX]]_, 1VH,C!DEE#F+LG:t'9'9:FFHHr   c                     t        d      )zThe classifier object.z)Must implement the "classifier" property.NotImplementedErrorrF   s    r   
classifierzBaseClassifier.classifier   s     ""MNNr   c                     t        d      )zClassifies a string of text.z#Must implement a "classify" method.rT   rF   texts     r   classifyzBaseClassifier.classify   s    !"GHHr   c                     t        d      )zTrains the classifier.z Must implement a "train" method.rT   )rF   labeled_featuresets     r   trainzBaseClassifier.train   s    !"DEEr   c                     t        d      )z3Returns an iterable containing the possible labels.z!Must implement a "labels" method.rT   rV   s    r   labelszBaseClassifier.labels   s    !"EFFr   c                     	 | j                  || j                        S # t        t        f$ r | j                  |      cY S w xY w)zWExtracts features from a body of text.

        :rtype: dictionary of features
        )rB   rD   	TypeErrorAttributeErrorrY   s     r   extract_featureszBaseClassifier.extract_features   sC    	0))$??>* 	0))$//	0s     A Ar   )__name__
__module____qualname____doc__r:   rI   rC   r   rW   r[   r^   r`   rd   r   r   r   r?   r?   v   sF    * ,;4#I& O OIFG	0r   r?   c                   b     e Zd ZdZdZedf fd	Zd Zed        Z	d Z
d Zd Zdd	Zd
 Z xZS )NLTKClassifieraH  An abstract class that wraps around the nltk.classify module.

    Expects that descendant classes include a class variable ``nltk_class``
    which is the class in the nltk.classify module to be wrapped.

    Example: ::

        class MyClassifier(NLTKClassifier):
            nltk_class = nltk.classify.svm.SvmClassifier
    Nc                     t        |   |||fi | | j                  D cg c]  \  }}| j                  |      |f c}}| _        y c c}}w r   )superrI   r5   rd   rE   )rF   r5   rB   rG   rH   dc	__class__s          r   rI   zNLTKClassifier.__init__   sJ     	$5vHHIMXA 5 5a 8!<XXs   A
c                 f    | j                   j                  }d| dt        | j                         dS )N< trained on z instances>)ro   re   lenr5   rF   
class_names     r   __repr__zNLTKClassifier.__repr__   s0    ^^,,
:,l3t~~+>*?{KKr   c                 ^    	 | j                         S # t        $ r}t        d      |d}~ww xY w)zThe classifier.@NLTKClassifier must have a nltk_class variable that is not None.N)r^   rc   r3   )rF   r8   s     r   rW   zNLTKClassifier.classifier   s6    	::< 	U	s    	,',c                     	  | j                   j                  | j                  g|i || _        | j                  S # t        $ r}t        d      |d}~ww xY w)a  Train the classifier with a labeled feature set and return
        the classifier. Takes the same arguments as the wrapped NLTK class.
        This method is implicitly called when calling ``classify`` or
        ``accuracy`` methods and is included only to allow passing in arguments
        to the ``train`` method of the wrapped NLTK class.

        .. versionadded:: 0.6.2

        :rtype: A classifier
        rx   N)
nltk_classr^   rE   rW   rc   r3   )rF   argsrH   r8   s       r   r^   zNLTKClassifier.train   sg    	3doo33##&*.4DO ??" 	U	s   := 	AAAc                 6    | j                   j                         S )z&Return an iterable of possible labels.)rW   r`   rV   s    r   r`   zNLTKClassifier.labels  s    %%''r   c                 Z    | j                  |      }| j                  j                  |      S )zIClassifies the text.

        :param str text: A string of text.
        )rd   rW   r[   rF   rZ   text_featuress      r   r[   zNLTKClassifier.classify  s)    
 --d3''66r   c                     t        |      r| j                  ||      }n|}|D cg c]  \  }}| j                  |      |f }}}t        j                  j                  | j                  |      S c c}}w )aG  Compute the accuracy on a test set.

        :param test_set: A list of tuples of the form ``(text, label)``, or a
            file pointer.
        :param format: If ``test_set`` is a filename, the file format, e.g.
            ``"csv"`` or ``"json"``. If ``None``, will attempt to detect the
            file format.
        )r   rC   rd   nltkr[   accuracyrW   )rF   test_setrG   	test_datarm   rn   test_featuress          r   r   zNLTKClassifier.accuracy  si     x &9I ICLM41a$//2A6MM}}%%doo}EE Ns   A0c                    | xj                   |z  c_         | j                  j                  t        |             | j                   D cg c]  \  }}| j	                  |      |f c}}| _        	  | j                  j                  | j
                  g|i || _        yc c}}w # t        $ r}t        d      |d}~ww xY w)zUpdate the classifier with new training data and re-trains the
        classifier.

        :param new_data: New data as a list of tuples of the form
            ``(text, label)``.
        rx   NT)r5   rD   updater   rd   rE   rz   r^   rW   rc   r3   )rF   new_datar{   rH   rm   rn   r8   s          r   r   zNLTKClassifier.update  s     	("5h?@IMXA 5 5a 8!<X	3doo33##&*.4DO  Y
  	U	s   	B 0/B& &	C /B;;C r   )re   rf   rg   rh   rz   r:   rI   rv   r   rW   r^   r`   r[   r   r   __classcell__)ro   s   @r   rj   rj      sP    	 J ,;4YL  *(7F r   rj   c                   N    e Zd ZdZej
                  j                  Zd Zd Z	d Z
y)NaiveBayesClassifieraP  A classifier based on the Naive Bayes algorithm, as implemented in
    NLTK.

    :param train_set: The training set, either a list of tuples of the form
        ``(text, classification)`` or a filename. ``text`` may be either
        a string or an iterable.
    :param feature_extractor: A feature extractor function that takes one or
        two arguments: ``document`` and ``train_set``.
    :param format: If ``train_set`` is a filename, the file format, e.g.
        ``"csv"`` or ``"json"``. If ``None``, will attempt to detect the
        file format.

    .. versionadded:: 0.6.0
    c                 Z    | j                  |      }| j                  j                  |      S )a  Return the label probability distribution for classifying a string
        of text.

        Example:
        ::

            >>> classifier = NaiveBayesClassifier(train_data)
            >>> prob_dist = classifier.prob_classify("I feel happy this morning.")
            >>> prob_dist.max()
            'positive'
            >>> prob_dist.prob("positive")
            0.7

        :rtype: nltk.probability.DictionaryProbDist
        rd   rW   prob_classifyr~   s      r   r   z"NaiveBayesClassifier.prob_classifyD  s)      --d3,,];;r   c                 :     | j                   j                  |i |S )zReturn the most informative features as a list of tuples of the
        form ``(feature_name, feature_value)``.

        :rtype: list
        )rW   most_informative_featuresrF   r{   rH   s      r   informative_featuresz)NaiveBayesClassifier.informative_featuresW  s      9t88$I&IIr   c                 :     | j                   j                  |i |S )zoDisplays a listing of the most informative features for this
        classifier.

        :rtype: None
        )rW   show_most_informative_featuresr   s      r   show_informative_featuresz.NaiveBayesClassifier.show_informative_features_  s      >t==tNvNNr   N)re   rf   rg   rh   r   r[   r   rz   r   r   r   r   r   r   r   r   2  s)     33J<&JOr   r   c                   `    e Zd ZdZej
                  j                  j                  Zd Z	e	Z
d Zy)DecisionTreeClassifieraR  A classifier based on the decision tree algorithm, as implemented in
    NLTK.

    :param train_set: The training set, either a list of tuples of the form
        ``(text, classification)`` or a filename. ``text`` may be either
        a string or an iterable.
    :param feature_extractor: A feature extractor function that takes one or
        two arguments: ``document`` and ``train_set``.
    :param format: If ``train_set`` is a filename, the file format, e.g.
        ``"csv"`` or ``"json"``. If ``None``, will attempt to detect the
        file format.

    .. versionadded:: 0.6.2
    c                 :     | j                   j                  |i |S )a  Return a string containing a pretty-printed version of this decision
        tree. Each line in the string corresponds to a single decision tree node
        or leaf, and indentation is used to display the structure of the tree.

        :rtype: str
        )rW   pretty_formatr   s      r   r   z$DecisionTreeClassifier.pretty_formatz  s      -t,,d=f==r   c                 :     | j                   j                  |i |S )zReturn a string representation of this decision tree that expresses
        the decisions it makes as a nested set of pseudocode if statements.

        :rtype: str
        )rW   
pseudocoder   s      r   r   z!DecisionTreeClassifier.pseudocode  s      *t))4:6::r   N)re   rf   rg   rh   r   r[   decisiontreer   rz   r   pprintr   r   r   r   r   r   h  s/     ++BBJ> F;r   r   c                   b    e Zd ZdZej
                  j                  ZedfdZ	d Z
d Z	 	 	 ddZy)	PositiveNaiveBayesClassifiera  A variant of the Naive Bayes Classifier that performs binary
    classification with partially-labeled training sets, i.e. when only
    one class is labeled and the other is not. Assuming a prior distribution
    on the two labels, uses the unlabeled set to estimate the frequencies of
    the features.

    Example usage:
    ::

        >>> from text.classifiers import PositiveNaiveBayesClassifier
        >>> sports_sentences = ['The team dominated the game',
        ...                   'They lost the ball',
        ...                   'The game was intense',
        ...                   'The goalkeeper catched the ball',
        ...                   'The other team controlled the ball']
        >>> various_sentences = ['The President did not comment',
        ...                        'I lost the keys',
        ...                        'The team won the game',
        ...                        'Sara has two kids',
        ...                        'The ball went off the court',
        ...                        'They had the ball for the whole game',
        ...                        'The show is over']
        >>> classifier = PositiveNaiveBayesClassifier(positive_set=sports_sentences,
        ...                                           unlabeled_set=various_sentences)
        >>> classifier.classify("My team lost the game")
        True
        >>> classifier.classify("And now for something completely different.")
        False


    :param positive_set: A collection of strings that have the positive label.
    :param unlabeled_set: A collection of unlabeled strings.
    :param feature_extractor: A feature extractor function.
    :param positive_prob_prior: A prior estimate of the probability of the
        label ``True``.

    .. versionadded:: 0.7.0
          ?c                    || _         || _        || _        | j                  D cg c]  }| j                  |       c}| _        | j                  D cg c]  }| j                  |       c}| _        || _        y c c}w c c}w r   )rB   positive_setunlabeled_setrd   positive_featuresunlabeled_featurespositive_prob_prior)rF   r   r   rB   r   rH   rm   s          r   rI   z%PositiveNaiveBayesClassifier.__init__  su     "3(*DHDUDU!Vq$"7"7":!VEIEWEW"X4#8#8#;"X#6  "W"Xs   A:A?c                     | j                   j                  }d| dt        | j                         dt        | j                         dS )Nrq   rr   z labeled and z unlabeled instances>)ro   re   rs   r   r   rt   s     r   rv   z%PositiveNaiveBayesClassifier.__repr__  sO    ^^,,

|<D,=,=(>'? @t))*++@B	
r   c                     | j                   j                  | j                  | j                  | j                        | _        | j
                  S )a  Train the classifier with a labeled and unlabeled feature sets and return
        the classifier. Takes the same arguments as the wrapped NLTK class.
        This method is implicitly called when calling ``classify`` or
        ``accuracy`` methods and is included only to allow passing in arguments
        to the ``train`` method of the wrapped NLTK class.

        :rtype: A classifier
        )rz   r^   r   r   r   rW   r   s      r   r^   z"PositiveNaiveBayesClassifier.train  s?     ////""D$;$;T=U=U
 r   Nc                    || _         |rG| xj                  |z  c_        | xj                  |D cg c]  }| j                  |       c}z  c_        |rG| xj                  |z  c_        | xj
                  |D cg c]  }| j                  |       c}z  c_         | j                  j                  | j                  | j
                  | j                   g|i || _        yc c}w c c}w )zUpdate the classifier with new data and re-trains the
        classifier.

        :param new_positive_data: List of new, labeled strings.
        :param new_unlabeled_data: List of new, unlabeled strings.
        T)	r   r   r   rd   r   r   rz   r^   rW   )rF   new_positive_datanew_unlabeled_datar   r{   rH   rm   s          r   r   z#PositiveNaiveBayesClassifier.update  s     $7 !22""2C'-.%%a(' " "44##2D(-.%%a(( # 0$////""##$$
 	

 
 '
(s   C 8C%)NNr   )re   rf   rg   rh   r   r[   r   rz   r=   rI   rv   r^   r   r   r   r   r   r     s@    %N ;;J -7
  	 r   r   c                       e Zd Zej                  j
                  j                  j                  Zej                  j
                  j                  Zd Z	y)MaxEntClassifierc                 Z    | j                  |      }| j                  j                  |      S )a  Return the label probability distribution for classifying a string
        of text.

        Example:
        ::

            >>> classifier = MaxEntClassifier(train_data)
            >>> prob_dist = classifier.prob_classify("I feel happy this morning.")
            >>> prob_dist.max()
            'positive'
            >>> prob_dist.prob("positive")
            0.7

        :rtype: nltk.probability.DictionaryProbDist
        r   )rF   rZ   featss      r   r   zMaxEntClassifier.prob_classify  s)      %%d+,,U33r   N)
re   rf   rg   r   r[   maxentMaxentClassifierrh   rz   r   r   r   r   r   r     s7    mm""33;;G%%66J4r   r   )rh   	itertoolsr   r   textblob.formatsrL   textblob.decoratorsr   textblob.exceptionsr   textblob.tokenizersr   textblob.utilsr   r   strbytesr   r   r)   r:   r=   r?   rj   r   r   r   r   r   r   r   <module>r      s   B   " / + - 25\

&6P0 P0ff^ fR3O> 3Ol$;^ $;No> od4~ 4r   