791d0836dbc85da75bf4004f64fc31f4710a8531
[cipher-tools.git] / support / language_models.py
1 import string
2 import random
3 import collections
4 import itertools
5 from math import log10
6 import os
7
8 import support.norms
9
10 def datafile(name, sep='\t'):
11 """Read key,value pairs from file.
12 """
13 with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), name), 'r') as f:
14 for line in f:
15 splits = line.split(sep)
16 yield [splits[0], int(splits[1])]
17
18 english_counts = collections.Counter(dict(datafile('count_1l.txt')))
19 normalised_english_counts = support.norms.normalise(english_counts)
20
21 english_bigram_counts = collections.Counter(dict(datafile('count_2l.txt')))
22 normalised_english_bigram_counts = support.norms.normalise(english_bigram_counts)
23
24 english_trigram_counts = collections.Counter(dict(datafile('count_3l.txt')))
25 normalised_english_trigram_counts = support.norms.normalise(english_trigram_counts)
26
27 with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'words.txt'), 'r') as f:
28 keywords = [line.rstrip() for line in f]
29
30
31 def weighted_choice(d):
32 """Generate random item from a dictionary of item counts
33 """
34 target = random.uniform(0, sum(d.values()))
35 cuml = 0.0
36 for (l, p) in d.items():
37 cuml += p
38 if cuml > target:
39 return l
40 return None
41
42 def random_english_letter():
43 """Generate a random letter based on English letter counts
44 """
45 return weighted_choice(normalised_english_counts)
46
47
48 def ngrams(text, n):
49 """Returns all n-grams of a text
50
51 >>> ngrams(sanitise('the quick brown fox'), 2) # doctest: +NORMALIZE_WHITESPACE
52 ['th', 'he', 'eq', 'qu', 'ui', 'ic', 'ck', 'kb', 'br', 'ro', 'ow', 'wn',
53 'nf', 'fo', 'ox']
54 >>> ngrams(sanitise('the quick brown fox'), 4) # doctest: +NORMALIZE_WHITESPACE
55 ['theq', 'hequ', 'equi', 'quic', 'uick', 'ickb', 'ckbr', 'kbro', 'brow',
56 'rown', 'ownf', 'wnfo', 'nfox']
57 """
58 return [text[i:i+n] for i in range(len(text)-n+1)]
59
60
61 class Pdist(dict):
62 """A probability distribution estimated from counts in datafile.
63 Values are stored and returned as log probabilities.
64 """
65 def __init__(self, data=[], estimate_of_missing=None):
66 data1, data2 = itertools.tee(data)
67 self.total = sum([d[1] for d in data1])
68 for key, count in data2:
69 self[key] = log10(count / self.total)
70 self.estimate_of_missing = estimate_of_missing or (lambda k, N: 1./N)
71 def __missing__(self, key):
72 return self.estimate_of_missing(key, self.total)
73
74 def log_probability_of_unknown_word(key, N):
75 """Estimate the probability of an unknown word.
76 """
77 return -log10(N * 10**((len(key) - 2) * 1.4))
78
79 Pw = Pdist(datafile('count_1w.txt'), log_probability_of_unknown_word)
80 Pl = Pdist(datafile('count_1l.txt'), lambda _k, _N: 0)
81 P2l = Pdist(datafile('count_2l.txt'), lambda _k, _N: 0)
82 P3l = Pdist(datafile('count_3l.txt'), lambda _k, _N: 0)
83
84 def Pwords(words):
85 """The Naive Bayes log probability of a sequence of words.
86 """
87 return sum(Pw[w.lower()] for w in words)
88
89 def Pletters(letters):
90 """The Naive Bayes log probability of a sequence of letters.
91 """
92 return sum(Pl[l.lower()] for l in letters)
93
94 def Pbigrams(letters):
95 """The Naive Bayes log probability of the bigrams formed from a sequence
96 of letters.
97 """
98 return sum(P2l[p] for p in ngrams(letters, 2))
99
100 def Ptrigrams(letters):
101 """The Naive Bayes log probability of the trigrams formed from a sequence
102 of letters.
103 """
104 return sum(P3l[p] for p in ngrams(letters, 3))
105
106
107 def cosine_distance_score(text):
108 """Finds the dissimilarity of a text to English, using the cosine distance
109 of the frequency distribution.
110
111 >>> cosine_distance_score('abcabc') # doctest: +ELLIPSIS
112 0.73777...
113 """
114 # return support.norms.cosine_distance(english_counts,
115 # collections.Counter(sanitise(text)))
116 return 1 - support.norms.cosine_similarity(english_counts,
117 collections.Counter(sanitise(text)))
118
119
120 if __name__ == "__main__":
121 import doctest
122 doctest.testmod()