ó
    ´OÂfÚ   ã                   óž   • S r SSKrSSKrSSKJrJr  SSKJr  SSKJr  SSK	J
r
  SSKJr  SSKJr   " S	 S
\S9rS rS rSS jr " S S\S9rg)zLanguage Model Interface.é    N)ÚABCMetaÚabstractmethod)Úbisect)Ú
accumulate)ÚNgramCounter)Ú	log_base2)Ú
Vocabularyc                   ó>   • \ rS rSrSrS r\S 5       r\S 5       rSr	g)Ú	Smoothingé   zÜNgram Smoothing Interface

Implements Chen & Goodman 1995's idea that all smoothing algorithms have
certain features in common. This should ideally allow smoothing algorithms to
work both with Backoff and Interpolation.
c                 ó   • Xl         X l        g)z¼
:param vocabulary: The Ngram vocabulary object.
:type vocabulary: nltk.lm.vocab.Vocabulary
:param counter: The counts of the vocabulary items.
:type counter: nltk.lm.counter.NgramCounter
N)ÚvocabÚcounts)ÚselfÚ
vocabularyÚcounters      Ú-/usr/lib/python3/dist-packages/nltk/lm/api.pyÚ__init__ÚSmoothing.__init__   s   € ð  Œ
Ø�ó    c                 ó   • [        5       e©N©ÚNotImplementedError)r   Úwords     r   Úunigram_scoreÚSmoothing.unigram_score&   ó   € ä!Ó#Ð#r   c                 ó   • [        5       er   r   ©r   r   Úcontexts      r   Úalpha_gammaÚSmoothing.alpha_gamma*   r   r   )r   r   N)
Ú__name__Ú
__module__Ú__qualname__Ú__firstlineno__Ú__doc__r   r   r   r"   Ú__static_attributes__© r   r   r   r      s4   † ñòð ñ$ó ð$ð ñ$ó ó$r   r   )Ú	metaclassc                 ó0   • [        U 5      [        U 5      -  $ )z0Return average (aka mean) for sequence of items.)ÚsumÚlen)Úitemss    r   Ú_meanr0   /   s   € äˆu‹:œ˜E›
Ñ"Ð"r   c                 óp   • [        U [        R                  5      (       a  U $ [        R                  " U 5      $ r   )Ú
isinstanceÚrandomÚRandom)Úseed_or_generators    r   Ú_random_generatorr6   4   s*   € ÜÐ#¤V§]¡]×3Ñ3Ø Ð Ü�=Š=Ð*Ó+Ð+r   c                 óà   • U (       d  [        S5      e[        U 5      [        U5      :w  a  [        S5      e[        [        U5      5      nUS   nUR	                  5       nU [        X4U-  5         $ )zXLike random.choice, but with weights.

Heavily inspired by python 3.6 `random.choices`.
z"Can't choose from empty populationz3The number of weights does not match the populationéÿÿÿÿ)Ú
ValueErrorr.   Úlistr   r3   r   )Ú
populationÚweightsÚrandom_generatorÚcum_weightsÚtotalÚ	thresholds         r   Ú_weighted_choicerA   :   sj   € ö
 ÜÐ=Ó>Ð>Ü
ˆ:ƒœ#˜g›,Ó&ÜÐNÓOÐOÜ”z 'Ó*Ó+€KØ˜‰O€EØ ×'Ñ'Ó)€IØ”f˜[°)Ñ*;Ó<Ñ=Ð=r   c                   óp   • \ rS rSrSrSS jrSS jrSS jr\SS j5       r	SS jr
S	 rS
 rS rSS jrSrg)ÚLanguageModeléI   zCABC for Language Models.

Cannot be directly instantiated itself.

Nc                 ó   • Xl         U(       aC  [        U[        5      (       d.  [        R                  " SU R
                  R                  < S3SS9  Uc
  [        5       OUU l        Uc  [        5       U l	        gUU l	        g)a  Creates new LanguageModel.

:param vocabulary: If provided, this vocabulary will be used instead
    of creating a new one when training.
:type vocabulary: `nltk.lm.Vocabulary` or None
:param counter: If provided, use this object to count ngrams.
:type counter: `nltk.lm.NgramCounter` or None
:param ngrams_fn: If given, defines how sentences in training text are turned to ngram
    sequences.
:type ngrams_fn: function or None
:param pad_fn: If given, defines how sentences in training text are padded.
:type pad_fn: function or None
z$The `vocabulary` argument passed to z- must be an instance of `nltk.lm.Vocabulary`.é   )Ú
stacklevelN)
Úorderr2   r	   ÚwarningsÚwarnÚ	__class__r$   r   r   r   )r   rH   r   r   s       r   r   ÚLanguageModel.__init__P   si   € ð Œ
Þœj¨´Z×@Ñ@Ü�MŠMØ6°t·~±~×7NÑ7NÑ6Qð R?ð ?àòð
 &0Ñ%7”Z”\¸ZˆŒ
Ø(/©”l“nˆ�¸Wˆ�r   c                 óÄ   ^ • T R                   (       d)  Uc  [        S5      eT R                   R                  U5        T R                  R                  U 4S jU 5       5        g)zUTrains the model on a text.

:param text: Training text as a sequence of sentences.

Nz:Cannot fit without a vocabulary or text to create it from.c              3   óZ   >#   • U  H   nTR                   R                  U5      v •  M"     g 7fr   )r   Úlookup)Ú.0Úsentr   s     €r   Ú	<genexpr>Ú$LanguageModel.fit.<locals>.<genexpr>t   s#   øé € ÐDºt°t˜4Ÿ:™:×,Ñ,¨T×2Ð2ºtùs   ƒ(+)r   r9   Úupdater   )r   ÚtextÚvocabulary_texts   `  r   ÚfitÚLanguageModel.fith   sN   ø€ ð �z�zØÑ&Ü ØPóð ð �J‰J×Ñ˜oÔ.Ø�‰×ÑÔD¹tÓDÕDr   c                 ó¤   • U R                  U R                  R                  U5      U(       a  U R                  R                  U5      5      $ S5      $ )z‘Masks out of vocab (OOV) words and computes their model score.

For model-specific logic of calculating scores, see the `unmasked_score`
method.
N)Úunmasked_scorer   rO   r    s      r   ÚscoreÚLanguageModel.scorev   sI   € ð ×"Ñ"Ø�J‰J×Ñ˜dÓ#Æ7 T§Z¡Z×%6Ñ%6°wÓ%?ó
ð 	
ØPTó
ð 	
r   c                 ó   • [        5       e)aŠ  Score a word given some optional context.

Concrete models are expected to provide an implementation.
Note that this method does not mask its arguments with the OOV label.
Use the `score` method for that.

:param str word: Word for which we want the score
:param tuple(str) context: Context the word is in.
    If `None`, compute unigram score.
:param context: tuple(str) or None
:rtype: float
r   r    s      r   rZ   ÚLanguageModel.unmasked_score€   s   € ô "Ó#Ð#r   c                 ó6   • [        U R                  X5      5      $ )zwEvaluate the log score of this word in this context.

The arguments are the same as for `score` and `unmasked_score`.

)r   r[   r    s      r   ÚlogscoreÚLanguageModel.logscore�   s   € ô ˜Ÿ™ DÓ2Ó3Ð3r   c                 óx   • U(       a  U R                   [        U5      S-      U   $ U R                   R                  $ )zšHelper method for retrieving counts for a given context.

Assumes context has been checked and oov words in it masked.
:type context: tuple(str) or None

é   )r   r.   Úunigrams)r   r!   s     r   Úcontext_countsÚLanguageModel.context_counts˜   s7   € ö 7>ˆD�K‰Kœ˜G› qÑ(Ñ)¨'Ñ2ð	
ØCGÇ;Á;×CWÑCWð	
r   c                 ót   • S[        U Vs/ s H  o R                  US   USS 5      PM     sn5      -  $ s  snf )a  Calculate cross-entropy of model for given evaluation text.

This implementation is based on the Shannon-McMillan-Breiman theorem,
as used and referenced by Dan Jurafsky and Jordan Boyd-Graber.

:param Iterable(tuple(str)) text_ngrams: A sequence of ngram tuples.
:rtype: float

r8   N)r0   r`   )r   Útext_ngramsÚngrams      r   ÚentropyÚLanguageModel.entropy£   s@   € ð ”EÙ?JÓKº{°e�]‰]˜5 ™9 e¨C¨R jÖ1¹{ÑKó
ñ 
ð 	
ùÚKs   ‹!5
c                 ó8   • [        SU R                  U5      5      $ )z~Calculates the perplexity of the given text.

This is simply 2 ** cross-entropy for the text, so the arguments are the same.

g       @)Úpowrj   )r   rh   s     r   Ú
perplexityÚLanguageModel.perplexity±   s   € ô �3˜Ÿ™ [Ó1Ó2Ð2r   c           	      ó|  ^ ^• Uc  / O
[        U5      n[        U5      nUS:X  aâ  [        U5      T R                  :¼  a  UT R                  * S-   S OUmT R	                  T R
                  R                  T5      5      nT(       aW  U(       dP  [        T5      S:”  a  TSS O/ mT R	                  T R
                  R                  T5      5      nT(       a	  U(       d  MP  [        U5      n[        U[        UU 4S jU 5       5      U5      $ / n[        U5       H%  nUR                  T R                  SX&-   US95        M'     U$ )ah  Generate words from the model.

:param int num_words: How many words to generate. By default 1.
:param text_seed: Generation can be conditioned on preceding context.
:param random_seed: A random seed or an instance of `random.Random`. If provided,
    makes the random sampling part of generation reproducible.
:return: One (str) word or a list of words generated from model.

Examples:

>>> from nltk.lm import MLE
>>> lm = MLE(2)
>>> lm.fit([[("a", "b"), ("b", "c")]], vocabulary_text=['a', 'b', 'c'])
>>> lm.fit([[("a",), ("b",), ("c",)]])
>>> lm.generate(random_seed=3)
'a'
>>> lm.generate(text_seed=['a'])
'b'

Nrc   c              3   óH   >#   • U  H  nTR                  UT5      v •  M     g 7fr   )r[   )rP   Úwr!   r   s     €€r   rR   Ú)LanguageModel.generate.<locals>.<genexpr>á   s   øé € Ð>²g°�d—j‘j  G×,Ð,²gùs   ƒ")Ú	num_wordsÚ	text_seedÚrandom_seed)r:   r6   r.   rH   re   r   rO   ÚsortedrA   ÚtupleÚrangeÚappendÚgenerate)	r   rt   ru   rv   r=   ÚsamplesÚ	generatedÚ_r!   s	   `       @r   r{   ÚLanguageModel.generate¹   s3  ù€ ð* $Ñ+‘B´°i³ˆ	Ü,¨[Ó9Ðà˜‹>ô �y“> T§Z¡ZÓ/ð ˜4Ÿ:™:˜+¨™/Ð+Ñ,àð ð
 ×)Ñ)¨$¯*©*×*;Ñ*;¸GÓ*DÓEˆGÞ¦'Ü),¨W«¸Ó)9˜' ! "™+¸r�Ø×-Ñ-¨d¯j©j×.?Ñ.?ÀÓ.HÓI�ö §' 'ô ˜W“oˆGÜ#ØÜÕ>±gÓ>Ó>Ø óð ð ˆ	Ü�yÖ!ˆAØ×ÑØ—‘ØØ'Ñ3Ø 0ð ð öñ "ð Ðr   )r   rH   r   )NNr   )rc   NN)r$   r%   r&   r'   r(   r   rW   r[   r   rZ   r`   re   rj   rn   r{   r)   r*   r   r   rC   rC   I   sE   † ñôEô0Eô
ð ó$ó ð$ô4ò	
ò
ò3÷5r   rC   r   )r(   r3   rI   Úabcr   r   r   Ú	itertoolsr   Únltk.lm.counterr   Únltk.lm.utilr   Únltk.lm.vocabularyr	   r   r0   r6   rA   rC   r*   r   r   Ú<module>r…      sK   ðñ  ã Û ß 'Ý Ý  å (Ý "Ý )ô$˜'ò $ò6#ò
,ô>ôe˜gó er   