Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

import pathlib 

import sqlite3 

import logging 

import json 

import datetime 

import tempfile 

from xml.etree import ElementTree 

 

import flask 

import cophi 

import numpy as np 

import pandas as pd 

from werkzeug.utils import secure_filename 

 

TEMPDIR = tempfile.gettempdir() 

DATABASE_URI = str(pathlib.Path(TEMPDIR, "topicsexplorer.db")) 

LOGFILE = str(pathlib.Path(TEMPDIR, "topicsexplorer.log")) 

 

def init_logging(level=logging.DEBUG): 

# Set up basic configuration: 

logging.basicConfig(level=level, 

format="%(message)s", 

filename=LOGFILE, 

filemode="w") 

# Ignore messages from flask and werkzeug: 

logging.getLogger("flask").setLevel(logging.ERROR) 

logging.getLogger("werkzeug").setLevel(logging.ERROR) 

 

 

def get_status(): 

# Open logfile: 

with pathlib.Path(LOGFILE).open("r", encoding="utf-8") as logfile: 

# Read lines: 

messages = logfile.readlines() 

# Select and strip the last one: 

message = messages[-1].strip() 

# Format the log message: 

message = format_logging(message) 

# Get current time: 

now = datetime.datetime.now().strftime("%H:%M:%S") 

return f"{now}<br>{message}" 

 

def format_logging(message): 

if "n_documents" in message: 

n = message.split("n_documents: ")[1] 

return f"Number of documents: {n}." 

elif "vocab_size" in message: 

n = message.split("vocab_size: ")[1] 

return f"Number of types: {n}." 

elif "n_words" in message: 

n = message.split("n_words: ")[1] 

return f"Number of tokens: {n}." 

elif "n_topics" in message: 

n = message.split("n_topics: ")[1] 

return f"Number of topics: {n}." 

elif "n_iter" in message: 

# Logging might freeze at this point, 

# so better log something like this: 

return "Initializing topic model." 

elif "log likelihood" in message: 

iteration, log_likelihood = message.split("> log likelihood: ") 

return f"Iteration {iteration[1:]}, log-likelihood: {log_likelihood}." 

else: 

return message 

 

 

def get_db(): 

"""Establish connection to database. 

""" 

if "db" not in flask.g: 

# Establish connection to pointed URI: 

flask.g.db = sqlite3.connect(DATABASE_URI) 

return flask.g.db 

 

 

def close_db(e=None): 

"""Close connection to database. 

""" 

# Check if a connection was created: 

db = flask.g.pop("db", None) 

if db is not None: 

# Close connection if exists: 

db.close() 

 

 

def init_db(app): 

"""Initialize database and create tables. 

""" 

db = get_db() 

with app.open_resource("schema.sql") as schemafile: 

schema = schemafile.read().decode("utf-8") 

db.executescript(schema) 

db.commit() 

close_db() 

 

 

def get_data(corpus, topics, iterations, stopwords, mfw): 

"""Get input data. 

""" 

logging.info("Fetching corpus and parameters...") 

# Get text files, number of topics and number of iterations: 

data = {"corpus": flask.request.files.getlist("corpus"), 

"topics": int(flask.request.form["topics"]), 

"iterations": int(flask.request.form["iterations"])} 

# Get stopword list, if user selected one: 

if flask.request.files.get("stopwords", None): 

logging.info("Fetching external stopwords list...") 

data["stopwords"] = flask.request.files["stopwords"] 

# Use most frequent words threshold otherwise: 

else: 

logging.info("Fetching threshold value for most frequent words...") 

data["mfw"] = int(flask.request.form["mfw"]) 

return data 

 

 

def insert_into_textfiles(values): 

"""Insert text files into table. 

""" 

logging.info("Connecting to database...") 

# Connect to database: 

db = get_db() 

# Insert values into table: 

for textfile in values: 

# Get title and text: 

title, text = load_textfile(textfile) 

logging.info(f"Loading '{title}'...") 

# Execute SQL: 

db.execute(""" 

INSERT INTO textfiles (title, text)  

VALUES(?, ?); 

""", 

[title, text]) 

logging.info("Committing to database...") 

db.commit() 

logging.info("Closing connection to database...") 

close_db() 

 

 

def insert_into_model(doc_topic, topics): 

logging.info("Connecting to database...") 

# Connect to database: 

db = get_db() 

# Insert values into table: 

db.execute(""" 

INSERT INTO model (doc_topic, topics) 

VALUES(?, ?); 

""", 

[doc_topic, topics]) 

logging.info("Committing to database...") 

db.commit() 

logging.info("Closing connection to database...") 

close_db() 

 

def select_textfiles(): 

""" 

TODO: fetchone? fetchall? nothing? 

""" 

cursor = get_db().cursor() 

return cursor.execute(""" 

SELECT title, text  

FROM textfiles; 

""") 

 

def select_doc_topic(): 

cursor = get_db().cursor() 

response = cursor.execute(""" 

SELECT doc_topic  

FROM model; 

""") 

return pd.read_json(response.fetchone()[0]) 

 

 

def select_topics(): 

cursor = get_db().cursor() 

response = cursor.execute(""" 

SELECT topics  

FROM model; 

""") 

return json.loads(response.fetchone()[0]) 

 

def select_document(title): 

cursor = get_db().cursor() 

response = cursor.execute(""" 

SELECT text  

FROM textfiles 

WHERE title is ?; 

""", [title]) 

return response.fetchone()[0] 

 

def get_documents(textfiles): 

for textfile in textfiles: 

title, text = textfile 

yield cophi.model.Document(text, title) 

 

def load_textfile(textfile): 

"""Load textfile and get title. 

""" 

# Get filename: 

filename = pathlib.Path(secure_filename(textfile.filename)) 

# Get title: 

title = filename.stem 

# Get file extension: 

suffix = filename.suffix 

# Read file: 

text = textfile.read().decode("utf-8") 

# If suffix implies any markup, remove it: 

if suffix in {".xml", ".html"}: 

logging.info("Removing markup...") 

text = remove_markup(text) 

return title, text 

 

 

def remove_markup(text): 

"""Parse string and remove markup. 

""" 

tree = ElementTree.fromstring(text) 

plaintext = ElementTree.tostring(tree, 

encoding="utf8", 

method="text") 

return plaintext.decode("utf-8") 

 

def get_stopwords(data, corpus): 

if "stopwords" in data: 

_, stopwords = load_textfile(data["stopwords"]) 

stopwords = stopwords.split("\n") 

else: 

stopwords = corpus.mfw(data["mfw"]) 

return stopwords 

 

 

def preprocess(data): 

logging.info("Querying corpus from database...") 

# Query text files: 

textfiles = select_textfiles() 

logging.info("Constructing document objetcs...") 

# Get cophi.model.Document object: 

documents = get_documents(textfiles) 

logging.info("Constructing corpus object...") 

# Create cophi.model.Corpus object: 

corpus = cophi.model.Corpus(documents) 

logging.info("Fetching stopwords...") 

# Get stopwords: 

stopwords = get_stopwords(data, corpus) 

logging.info("Fetching hapax legomena...") 

# Get hapax legomena: 

hapax = corpus.hapax 

# Join both lists: 

features = set(stopwords).union(set(hapax)) 

logging.info("Cleaning corpus...") 

# Clean document-term matrix: 

dtm = corpus.drop(corpus.dtm, features) 

# Get sizes: 

sizes = corpus.num_tokens 

# Convert to a NumPy array and return: 

return dtm.values, dtm.columns, dtm.index, sizes.values 

 

def get_topics(model, vocabulary, maximum=100): 

for i, distribution in enumerate(model.topic_word_): 

yield list(np.array(vocabulary)[np.argsort(distribution)][:-maximum-1:-1]) 

 

 

def get_similarities(matrix): 

d = matrix.T @ matrix 

norm = (matrix * matrix).sum(0, keepdims=True) ** .5 

return d / norm / norm.T 

 

def normalize(matrix, sizes): 

return matrix * sizes 

 

 

def scale(vector): 

return np.interp(vector, (vector.min(), vector.max()), (40, 100))