forked from uptownnickbrown/epub2vec
-
Notifications
You must be signed in to change notification settings - Fork 0
/
epub2vec.py
189 lines (154 loc) · 7.38 KB
/
epub2vec.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
import os
import zipfile
import pandas as pd
import numpy as np
import re
import nltk.data
import csv
import logging
import time
from bs4 import BeautifulSoup
from gensim.models import word2vec
from sklearn.cluster import KMeans
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s',\
level=logging.INFO)
start_time = time.time()
print 'started at: ' + time.strftime("%Y/%m/%d, %H:%M:%S", time.localtime(start_time))
files = os.listdir('epub-input/')
epubs = [x for x in files if '.epub' in x]
epubids = []
for epub in epubs:
bookid = re.sub(r'(.*).epub',r'\1',epub)
epubids.append(bookid)
# print 'extracting ' + bookid + '...'
with zipfile.ZipFile('epub-input/' + str(epub),'r') as z:
z.extractall('./www/epub-output/' + str(bookid))
log_time = time.time()
print 'books extracted at: ' + time.strftime("%Y/%m/%d, %H:%M:%S", time.localtime(log_time))
bookids = []
filenames = []
chapters = []
print 'gathering xhtml or html files...'
for root, dirs, files in os.walk('.'):
for filename in files:
if '.xhtml' in filename or '.html' in filename:
full_filepath = root + '/' + filename
bookid = re.sub(r'.*/epub-output/(.*?)/.*',r'\1',root)
if bookid in epubids:
bookids.append(bookid)
filenames.append(filename)
# print 'gathering text from ' + bookid + '\t' + filename
soup = BeautifulSoup(open(full_filepath), 'lxml')
[s.extract() for s in soup('script')]
[s.extract() for s in soup('epub:switch')]
filetext = soup.find('body').get_text()
chapters.append(filetext)
log_time = time.time()
print str(len(chapters)) + ' chapters extracted at: ' + time.strftime("%Y/%m/%d, %H:%M:%S", time.localtime(log_time))
df = pd.DataFrame({'bookids':bookids,'filenames':filenames,'chapters':chapters},columns=['bookids','filenames','chapters'])
tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
def chapter_to_wordlist(chapter):
chapter = re.sub("[^a-zA-Z]"," ", chapter)
chapter_words = chapter.lower().split()
return(chapter_words)
def chapter_to_sentences( chapter, tokenizer):
raw_sentences = tokenizer.tokenize(chapter.strip())
sentences = []
for raw_sentence in raw_sentences:
if len(raw_sentence) > 0:
sentences.append( chapter_to_wordlist( raw_sentence))
return sentences
sentences = []
for chapter in df['chapters']:
sentences += chapter_to_sentences(chapter, tokenizer)
log_time = time.time()
print str(len(sentences)) + ' sentences extracted at: ' + time.strftime("%Y/%m/%d, %H:%M:%S", time.localtime(log_time))
num_features = 750 # Word vector dimensionality
min_word_count = 10 # Minimum word count
num_workers = 6 # Number of threads to run in parallel
context = 20 # Context window size
downsampling = 1e-3 # Downsample setting for frequent words
model = word2vec.Word2Vec(sentences, workers=num_workers, \
size=num_features, min_count = min_word_count, \
window = context, sample = downsampling)
model.init_sims(replace=True)
# save the model for later use. You can load it later using Word2Vec.load()
# >>> from gensim.models import Word2Vec
# >>> model = Word2Vec.load("300features_40minwords_10context.w2v")
# TODO add an arg when running the script to create the model or load one and skip everything before this point
model_name = str(int(start_time)) + '_' + str(num_features) + 'features_' + str(min_word_count) + 'minwords_' + str(context) + 'context.w2v'
model.save('models/' + model_name)
log_time = time.time()
print 'word2vec model saved at: ' + time.strftime("%Y/%m/%d, %H:%M:%S", time.localtime(log_time))
paragraphs = []
vectors = []
locations = []
p_bookids = []
print 'gathering paragraphs...'
for root, dirs, files in os.walk('.'):
for filename in files:
if '.xhtml' in filename or '.html' in filename:
full_filepath = root + '/' + filename
bookid = re.sub(r'.*/epub-output/(.*?)/.*',r'\1',root)
if bookid in epubids:
# print 'gathering text from ' + bookid + '\t' + filename
soup = BeautifulSoup(open(full_filepath), 'lxml')
[s.extract() for s in soup('script')]
[s.extract() for s in soup('epub:switch')]
for s in soup('p'):
paragraph = s.get_text()
if paragraph == '':
next
else:
location_id = s.get('id')
if location_id is None:
location_id = s.parent.get('id')
if location_id is None:
location_id = s.parent.parent.get('id')
if location_id is None:
location_id = ''
location = re.sub(r'.*/epub-output/.*?/(.*)',r'\1',full_filepath) + '#' + str(location_id)
locations.append(location)
p_bookids.append(bookid)
paragraphs.append(paragraph)
words = paragraph.split()
vector = np.zeros(num_features,dtype=float)
in_model_count = 0
for w in words:
if w in model.vocab:
in_model_count += 1
vector = vector + model[w]
if in_model_count > 0:
average_vector = vector / in_model_count
else:
average_vector = vector
vectors.append(average_vector)
num_paragraphs = len(paragraphs)
log_time = time.time()
print str(num_paragraphs) + ' paragraph vectors computed at: ' + time.strftime("%Y/%m/%d, %H:%M:%S", time.localtime(log_time))
# Set "k" (num_clusters) to be 1/21th of the number of paragraph vectors, or an
# average of 10 "similar paragraphs" per paragraph
p_vectors = np.array(vectors)
num_clusters = num_paragraphs / 21
kmeans_clustering = KMeans( n_clusters = num_clusters, n_jobs = -1 )
cluster_indices = kmeans_clustering.fit_predict( p_vectors )
log_time = time.time()
print 'k-means clustering complete at: ' + time.strftime("%Y/%m/%d, %H:%M:%S", time.localtime(log_time))
with open('www/clusters/' + str(int(start_time)) + '_cluster_output.csv', 'w') as cluster_output:
fieldnames = ['cluster_id','book', 'location', 'text']
writer = csv.DictWriter(cluster_output, fieldnames=fieldnames)
writer.writeheader()
# Print out some clusters!
for cluster in range(0,num_clusters):
p_indices = []
for i in range(0,num_paragraphs):
if( cluster_indices[i] == cluster ):
p_indices.append(i)
# print 'Outputting cluster %d' % cluster + ' - ' + str(len(p_indices)) + ' paragraphs.'
for p_index in p_indices:
writer.writerow({'cluster_id':cluster,'book': p_bookids[p_index], 'location': locations[p_index], 'text':paragraphs[p_index].encode('utf-8')})
with open('www/clusters/available-clusters.txt', 'a') as filelist:
filelist.write('\n' + str(int(start_time)) + '_cluster_output.csv')
end_time = time.time()
print 'finished outputting csv at: ' + time.strftime("%Y/%m/%d, %H:%M:%S", time.localtime(end_time))
print 'total time elapsed: ' + str(end_time - start_time) + ' seconds.'