/
extract.py
executable file
·219 lines (202 loc) · 7.98 KB
/
extract.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
#!/usr/bin/python
# Extractor: Extracts a soul from a harvested corpus
try:
import psyco
psyco.full()
except: pass
import gzip
import nltk
import simplejson as json
import os
import re
import cPickle as pickle
import random
import curses.ascii
import traceback
import sys
from libs.SpeechModels import TokenNormalizer, PhraseGenerator
from libs.tokenizer import word_tokenize, word_detokenize
from libs.tagger import pos_tag
from libs.summarize import SimpleSummarizer
from ConfigParser import SafeConfigParser
config = SafeConfigParser()
config.read('settings.cfg')
class CorpusSoul:
def __init__(self, directory):
self.normalizer = TokenNormalizer()
self.quote_engine_only = config.getboolean('soul', 'quote_engine_only')
# FIXME: http://www.w3schools.com/HTML/html_entities.asp
clean_ents = [("<", "<"), (">", ">"), ("&", "&")]
tagged_tweets = []
tweet_texts = []
self.vocab = set([])
for root, dirs, files in os.walk(directory):
for f in files:
# .jtwt: json-encoded twitter tweets, 1 per line
# TODO: Add @msgs to this user as hidden text
if f.endswith(".jtwt"):
fl = open(root+"/"+f, "r")
for jtweet in fl.readlines():
tweet = json.loads(jtweet)
txt = tweet['text'].encode('ascii', 'ignore')
if re.search("( |^)RT(:| )", txt, re.IGNORECASE): continue
if txt[0] == '@': txt = re.sub('^@[\S]+ ', '', txt)
for e in clean_ents:
txt = re.sub(e[0], e[1], txt)
if self.quote_engine_only:
tagged_tweets.append(txt)
else:
tokens = self.normalizer.normalize_tokens(word_tokenize(txt))
if tokens:
self.vocab.update(tokens)
tagged_tweet = pos_tag(tokens,
config.getboolean("soul","attempt_agfl"),
config.getboolean("soul","reject_agfl_failures"),
config.getboolean("soul","agfl_nltk_fallback"))
if tagged_tweet:
tweet_texts.append(word_detokenize(tokens))
tagged_tweets.append(tagged_tweet)
print "Loaded tweet #"+str(len(tagged_tweets)) #+"/"+str(len(files))
# .twt: plain-text tweets, 1 per line
elif f.endswith(".twt"):
fl = open(root+"/"+f, "r")
for tweet in fl.readlines():
txt = tweet.encode('ascii', 'ignore')
if txt.startswith('RT'): continue
if txt[0] == '@': txt = re.sub('^@[\S]+ ', '', txt)
for e in clean_ents:
txt = re.sub(e[0], e[1], txt)
if self.quote_engine_only:
tagged_tweets.append(txt)
else:
tokens = self.normalizer.normalize_tokens(word_tokenize(txt))
if tokens:
self.vocab.update(tokens)
tagged_tweet = pos_tag(tokens,
config.getboolean("soul","attempt_agfl"),
config.getboolean("soul","reject_agfl_failures"),
config.getboolean("soul","agfl_nltk_fallback"))
if tagged_tweet:
tweet_texts.append(word_detokenize(tokens))
tagged_tweets.append(tagged_tweet)
print "Loaded tweet #"+str(len(tagged_tweets)) #+"/"+str(len(files))
pass
# .post: long-winded material (blog/mailinglist posts, essays, articles, etc)
elif f.endswith(".post"):
fl = open(root+"/"+f, "r")
post = fl.read()
tweets = self.post_to_tweets(post)
for txt in tweets:
#txt = txt.encode('ascii', 'ignore')
for e in clean_ents:
txt = re.sub(e[0], e[1], txt)
if self.quote_engine_only:
tagged_tweets.append(txt)
else:
tokens = self.normalizer.normalize_tokens(word_tokenize(txt))
if tokens:
self.vocab.update(tokens)
tagged_tweet = pos_tag(tokens,
config.getboolean("soul","attempt_agfl"),
config.getboolean("soul","reject_agfl_failures"),
config.getboolean("soul","agfl_nltk_fallback"))
if tagged_tweet:
tweet_texts.append(word_detokenize(tokens))
tagged_tweets.append(tagged_tweet)
print "Loaded post-tweet #"+str(len(tagged_tweets))
# .irclog: irc log files. irssi format.
elif f.endswith(".irclog"):
pass
# .4sq: foursquare data
elif f.endswith(".4sq"):
pass
self.tagged_tweets = tagged_tweets
num_clusters = config.getint('soul', 'tweet_topics')
if num_clusters > 1:
self.cluster_tweets(tweet_texts, num_clusters)
else:
self.cluster_rates = {}
self.clustered_tweets = {}
self.clustered_tweets[0] = tagged_tweets
self.cluster_rates[0] = len(self.tagged_tweets)
def post_to_tweets(self, post, summarize=False):
# We do poorly with parentheticals. Just kill them.
post = re.sub(r"\([^\)]+\)", "", post)
if summarize:
summ = SimpleSummarizer()
post = summ.summarize(post, config.getint("soul", "post_summarize_len"))
sentences = nltk.sent_tokenize(post)
tweets = []
tweet = ""
for s in sentences:
if len(s) > config.getint("soul","post_len"): continue
if len(tweet + s) < config.getint("soul","post_len"):
tweet += s+" "
else:
if tweet: tweets.append(tweet)
tweet = ""
return tweets
def cluster_tweets(self, tweet_texts, num_clusters=3):
# XXX: move SearchableTextCollection to libs
from resurrect import SearchableTextCollection,SearchableText
print "Scoring tweets.."
tc = SearchableTextCollection(self.vocab)
for tweet in tweet_texts:
txt = SearchableText(tweet)
tc.add_text(txt)
tc.update_matrix()
print "Scored tweets.."
print "Clustering tweets.."
cluster = nltk.cluster.KMeansClusterer(num_clusters,
nltk.cluster.util.euclidean_distance,
repeats=20*num_clusters)
# EM takes waaaaaayy too long, even with SVD
#cluster = nltk.cluster.EMClusterer(means, svd_dimensions=100)
clustered = cluster.cluster(tc.D, assign_clusters=True)
print "Clustered tweets.."
clustered_tweets = {}
for i in xrange(len(clustered)):
if clustered[i] not in clustered_tweets:
clustered_tweets[clustered[i]] = []
clustered_tweets[clustered[i]].append(self.tagged_tweets[i])
self.cluster_rates = {}
for i in clustered_tweets.iterkeys():
self.cluster_rates[i] = len(clustered_tweets[i])
print
print "Cluster "+str(i)+": "+str(len(clustered_tweets[i]))
for t in clustered_tweets[i]:
print t
self.clustered_tweets = clustered_tweets
def main():
try:
print "Loading soul file..."
soul = pickle.load(open("target_user.soul", "r"))
print "Loaded soul file."
except pickle.UnpicklingError:
soul = pickle.load(gzip.GzipFile("target_user.soul", "r"))
print "Loaded soul file."
except KeyError:
soul = pickle.load(gzip.GzipFile("target_user.soul", "r"))
print "Loaded soul file."
except IOError:
print "No soul file found. Regenerating."
soul = CorpusSoul('target_user')
if config.getboolean("soul", "gzip_soul"):
pickle.dump(soul, gzip.GzipFile("target_user.soul", "w"))
else:
pickle.dump(soul, open("target_user.soul", "w"))
except Exception,e:
traceback.print_exc()
soul.normalizer.verify_scores()
voice = PhraseGenerator(soul.tagged_tweets, soul.normalizer,
config.getint("brain","hmm_context"),
config.getint("brain","hmm_offset"))
while True:
query = raw_input("> ")
if not query: query = "41"
if query.isdigit():
(str_result, tok_result, result) = voice.say_something()
print str(result)
print str_result
if __name__ == "__main__":
main()