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

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

from datetime import datetime 

import json 

import logging 

from pathlib import Path 

import shutil 

import sys 

import tempfile 

from xml.etree import ElementTree 

 

import re 

 

import cophi 

import flask 

import numpy as np 

import pandas as pd 

from werkzeug.utils import secure_filename 

 

from application import database 

 

TEMPDIR = tempfile.gettempdir() 

DATABASE = Path(TEMPDIR, "topicsexplorer.db") 

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

DATA_EXPORT = Path(TEMPDIR, "topicsexplorer-data") 

 

 

def init_app(name): 

"""Initialize Flask application. 

""" 

logging.debug("Initializing Flask app...") 

if getattr(sys, "frozen", False): 

logging.debug("Application is frozen.") 

root = Path(sys._MEIPASS) 

else: 

logging.debug("Application is not frozen.") 

root = Path("application") 

app = flask.Flask(name, 

template_folder=str(Path(root, "templates")), 

static_folder=str(Path(root, "static"))) 

return app 

 

 

def init_logging(level): 

"""Initialize logging. 

""" 

logging.basicConfig(level=level, 

format="%(message)s", 

filename=str(LOGFILE), 

filemode="w") 

# Disable logging for Flask and Werkzeug 

# (this would be a lot of spam, even level INFO): 

if level > logging.DEBUG: 

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

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

 

 

def init_db(app): 

"""Initialize SQLite database. 

""" 

logging.debug("Initializing database...") 

db = database.get_db() 

if getattr(sys, "frozen", False): 

root = Path(sys._MEIPASS) 

else: 

root = Path(".") 

with app.open_resource(str(Path(root, "schema.sql"))) as schemafile: 

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

db.executescript(schema) 

db.commit() 

database.close_db() 

 

 

def format_logging(message): 

"""Format log messages. 

""" 

if "n_documents" in message: 

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

return "Number of documents: {}".format(n) 

elif "vocab_size" in message: 

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

return "Number of types: {}".format(n) 

elif "n_words" in message: 

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

return "Number of tokens: {}".format(n) 

elif "n_topics" in message: 

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

return "Number of topics: {}".format(n) 

elif "n_iter" in message: 

return "Initializing topic model..." 

elif "log likelihood" in message: 

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

return "Iteration {}".format(iteration[1:]) 

else: 

return message 

 

 

def load_textfile(textfile): 

"""Load text file, return title and content. 

""" 

filename = Path(secure_filename(textfile.filename)) 

title = filename.stem 

suffix = filename.suffix 

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

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

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

content = remove_markup(content) 

return title, content 

# If suffix not allowed, ignore file: 

else: 

return None, None 

 

 

def remove_markup(text): 

"""Parse XML and drop tags. 

""" 

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

tree = ElementTree.fromstring(text) 

plaintext = ElementTree.tostring(tree, 

encoding="utf8", 

method="text") 

return plaintext.decode("utf-8") 

 

 

def get_documents(textfiles): 

"""Get Document objects. 

""" 

logging.info("Processing documents...") 

for textfile in textfiles: 

title, content = textfile 

yield cophi.model.Document(content, title) 

 

 

def get_stopwords(data, corpus): 

"""Get stopwords from file or corpus. 

""" 

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

if "stopwords" in data: 

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

stopwords = cophi.model.Document(stopwords).tokens 

else: 

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

return stopwords 

 

 

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

"""Get data from HTML forms. 

""" 

logging.info("Processing user data...") 

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

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

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

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

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

else: 

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

return data 

 

 

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

"""Get topics from topic model. 

""" 

logging.info("Fetching topics from topic model...") 

for distribution in model.topic_word_: 

words = list(np.array(vocabulary)[ 

np.argsort(distribution)][:-maximum - 1:-1]) 

yield "{}, ...".format(", ".join(words[:3])), words 

 

 

def get_document_topic(model, titles, descriptors): 

"""Get document-topic distribution from topic model. 

""" 

logging.info("Fetching document-topic distributions from topic model...") 

document_topic = pd.DataFrame(model.doc_topic_) 

document_topic.index = titles 

document_topic.columns = descriptors 

return document_topic 

 

 

def get_cosine(matrix, descriptors): 

"""Calculate cosine similarity between columns. 

""" 

logging.info("Calculcating cosine similarity...") 

d = matrix.T @ matrix 

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

similarities = d / norm / norm.T 

return pd.DataFrame(similarities, index=descriptors, columns=descriptors) 

 

 

def scale(vector, minimum=50, maximum=100): 

"""Min-max scaler for a vector. 

""" 

logging.debug("Scaling data from {} to {}...".format(minimum, maximum)) 

return np.interp(vector, (vector.min(), vector.max()), (minimum, maximum)) 

 

 

def export_data(): 

"""Export model output to ZIP archive. 

""" 

logging.info("Creating data archive...") 

if DATA_EXPORT.exists(): 

unlink_content(DATA_EXPORT) 

else: 

DATA_EXPORT.mkdir() 

model, stopwords = database.select("data_export") 

document_topic, topics, document_similarities, topic_similarities = model 

 

logging.info("Preparing document-topic distributions...") 

document_topic = pd.read_json(document_topic, orient="index") 

document_topic.columns = [col.replace(",", "").replace( 

" ...", "") for col in document_topic.columns] 

 

logging.info("Preparing topics...") 

topics = pd.read_json(topics, orient="index") 

topics.index = ["Topic {}".format(n) for n in range(topics.shape[0])] 

topics.columns = ["Word {}".format(n) for n in range(topics.shape[1])] 

 

logging.info("Preparing topic similarity matrix...") 

topic_similarities = pd.read_json(topic_similarities) 

topic_similarities.columns = [col.replace(",", "").replace( 

" ...", "") for col in topic_similarities.columns] 

topic_similarities.index = [ix.replace(",", "").replace( 

" ...", "") for ix in topic_similarities.index] 

 

logging.info("Preparing document similarity matrix...") 

document_similarities = pd.read_json(document_similarities) 

data_export = {"document-topic-distribution": document_topic, 

"topics": topics, 

"topic-similarities": topic_similarities, 

"document-similarities": document_similarities, 

"stopwords": json.loads(stopwords)} 

 

for name, data in data_export.items(): 

if name in {"stopwords"}: 

with Path(DATA_EXPORT, "{}.txt".format(name)).open("w", encoding="utf-8") as file: 

for word in data: 

file.write("{}\n".format(word)) 

else: 

path = Path(DATA_EXPORT, "{}.csv".format(name)) 

data.to_csv(path, sep=";", encoding="utf-8") 

shutil.make_archive(DATA_EXPORT, "zip", DATA_EXPORT) 

 

 

def unlink_content(directory, pattern="*"): 

"""Deletes the content of a directory. 

""" 

logging.info("Cleaning up in data directory...") 

for p in directory.rglob(pattern): 

if p.is_file(): 

p.unlink() 

 

 

def series2array(s): 

"""Convert pandas Series to a 2-D array. 

""" 

for i, v in zip(s.index, s): 

yield [i, v] 

 

 

def createJsonGraph(graph, cutoff=.25): 

# create DataFrame for easier handling 

# TODO: sort Dataframe by Index and Columns! --> else: not "symmetrical" --Done below 

# df = pd.DataFrame(graph) 

df = pd.read_json(graph) 

df = df.T.sort_index() 

df = df.T.sort_index() 

 

# TODO: different for doc-topics-matrix: only transpose once; no symmetric matrix, skip step below; maybe redo function for this purpose 

 

# half symmetric matrix 

df = df.where(np.tril(np.ones(df.shape), -1).astype(bool)) 

 

graph = df.to_dict() 

 

# TODO: special version for the seminar: groups from suffixes _s, _t, _k 

 

r = re.compile(r'(_.{,2}\b)') 

 

# TODO: translate from label to id 

 

# translation: map title to a number and then undo it again... 

translation = {} 

 

nodes = [] 

edges = [] 

 

for e, i in enumerate(graph.keys()): 

translation[i] = e 

group = re.findall(r, i) 

if len(group) > 0: 

nodes.append({'id': e, 'label': i, 

'group': group[0] 

}) 

else: 

nodes.append({'id': e, 'label': i, 

# 'group': group[0] 

}) 

 

for f, j in graph.items(): 

for g, h in j.items(): 

# below: which similarity is cut off --> for non-total-linked graph 

if h < 1.0:# and h >= cutoff: 

# if h >= 0.75: 

# if h < 1.0: 

edges.append({'from': translation[f], 'to': translation[g], 'value': h}) 

 

# create dict and json requested by vis.js 

data = { 

'nodes': nodes, 

'edges': edges 

} 

 

return json.dumps(data, indent=4)