forked from singnet/topic-analysis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathanalysis_results.py
140 lines (81 loc) · 3.86 KB
/
analysis_results.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
# Tested on python3.6
import time
import csv
import numpy as np
import os
import sys
import pathlib
import logging
sys.path.append(str(pathlib.Path(os.path.abspath('')).parents[0])+'/topic-analysis/plsa-service/plsa')
from flask import Flask, jsonify
from flask import make_response
from flask import request
from flask_httpauth import HTTPBasicAuth
auth = HTTPBasicAuth()
app = Flask(__name__)
status_list = ['Analysis started.','Preprocessing started.','Preprocessing finished. Topic analysis started.','Topic analysis finished.','Failed.']
# '/topic-analysis/api/v1.0/results'
@app.route('/topic-analysis/api/v1.0/results', methods=['GET'])
# @auth.login_required
def results():
try:
# Code to test exception handler for this try
# a=1/0
print('In results:', time.strftime("%c"))
handle = request.args['handle'].replace('e','-').replace('d',' ').replace('y','^')
print("handle =", handle)
except Exception as e:
logging.exception("message")
return make_response(jsonify({'Error': 'Request was not fulfilled. Please try again.', "error_msg": str(e)}),400)
try:
parameters_path = str(pathlib.Path(os.path.abspath('')).parents[0]) + '/appData/plsa/' + 'plsa-parameters/' + handle + '/'
print(parameters_path)
with open(parameters_path + 'status.txt', 'r') as f:
status = f.read().splitlines()
if status[0] not in status_list:
return make_response(jsonify({'Error': 'Analysis ended unexpectedly, corrupt status file or status file not written yet', "error_msg": ''}), 500)
if status[0] != 'Topic analysis finished.':
return make_response(jsonify({'status':status}), 200)
with open(parameters_path + 'plsa_topics.txt', 'r') as f:
topics = f.read().splitlines()
topic_by_doc = []
word_by_topic_conditional = []
logLikelihoods = []
docs_list = []
with open(parameters_path + 'topic-by-doc-matirx.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
docs_list = next(csv_reader)[1:]
for row in csv_reader:
topic_by_doc.append(list((np.array(row[1:])).astype(np.float)))
with open(parameters_path + 'topic_probability_pz', 'r') as f:
topic_probabilities = f.read().splitlines()
topic_probabilities = list((np.array(topic_probabilities)).astype(np.float))
with open(parameters_path + 'word_by_topic_conditional.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
for row in csv_reader:
word_by_topic_conditional.append(list((np.array(row[:-1])).astype(np.float)))
with open(parameters_path + 'logL.txt', 'r') as f:
logLikelihoods = f.read().splitlines()
logLikelihoods = list((np.array(logLikelihoods)).astype(np.float))
resp = {}
resp['status'] = status[0]
resp['total running time in minutes'] = float(status[1])
resp['docs_list'] = docs_list
resp['topics'] = topics
resp['topicByDocMatirx'] = topic_by_doc
resp['topicProbabilities'] = topic_probabilities
resp['wordByTopicConditional'] = word_by_topic_conditional
resp['logLikelihoods'] = logLikelihoods
return make_response(jsonify(resp), 200)
except Exception as e:
logging.exception("message")
# NOT: This line is tested: it throws back error message correctly
return make_response(jsonify({'Error': 'Request was not fulfilled. Please try again.', "error_msg": str(e)}), 500)
@app.errorhandler(404)
def not_found(error):
print ('In not_found:', time.strftime("%c"))
return make_response(jsonify({'Error': 'Not found'}), 404)
__end__ = '__end__'
if __name__ == '__main__':
# app.run(debug=True)
app.run(debug=False,port=4998)