-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathweb_app.py
executable file
·420 lines (398 loc) · 18.9 KB
/
web_app.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
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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
"Web API for CommonplacesCultures"
import json
import re
from typing import Optional
from collections import namedtuple
import psycopg2
import psycopg2.extras
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from starlette.middleware.cors import CORSMiddleware
from starlette.responses import JSONResponse
# FastAPI application server
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.mount("/public", StaticFiles(directory="public"), name="public")
app.mount("/components", StaticFiles(directory="public/components"), name="components")
app.mount("/css", StaticFiles(directory="public/css"), name="css")
app.mount("/img", StaticFiles(directory="public/img"), name="img")
with open("config.json") as config_file:
CONFIG = json.load(config_file)
SORT_KEY_MAP = {
-1: [""],
0: ["passageidentcount DESC", "sourceauthor", "sourcetitle"],
1: ["targetdate", "targetauthor"],
2: ["sourcedate", "sourceauthor"],
3: ["targetauthor"],
4: ["targetauthor"],
}
FULL_TEXT_FIELDS = {
"author",
"sourceauthor",
"targetauthor",
"title",
"sourcetitle",
"targettitle",
"matchcontext",
"sourcematchcontext",
"targetmatchcontext",
"sourcemodulename",
"targetmodulename",
}
BOOLEAN_ARGS = re.compile(r"""(NOT \w+)|("[^"]+")|(\w+)""")
QUERY_CONDITION = namedtuple("QueryConditions", ["joiner", "field", "operator", "value"])
def add_to_condition(query_conditions, joiner, field, operator):
"""Update query condition"""
if not query_conditions:
query_conditions = f"{field} {operator} %s"
elif joiner in ("AND", "OR"):
query_conditions += f" {joiner} {field} {operator} %s"
else:
query_conditions += f" AND {field} {operator} %s"
return query_conditions
def build_query(request: Request):
"""Build SQL query"""
query_conditions = ""
query_values = []
for param, value in request.query_params.items():
if param in ("duplicates", "facet", "offset"):
continue # TODO fix duplicates?
if value != "":
if param != "sorting":
# if param == "duplicates": TODO
# param_value =
if param == "bible":
if value == "ignore":
query_conditions = add_to_condition(
query_conditions, joiner="", field="authorident", operator="!="
)
query_values.append(1)
elif value == "only":
query_conditions = add_to_condition(
query_conditions,
joiner="",
field="authorident",
operator="=",
)
query_values.append(1)
else:
continue
elif param in FULL_TEXT_FIELDS:
if "OR" in value:
if query_conditions:
query_conditions += " AND"
query_conditions += f" ({param} ~* %s"
values = value.split(" OR ")
first_value = values.pop()
query_values.append(fr"\m{first_value}\M")
for query_value in values:
query_conditions += f" OR {param} ~* %s"
query_values.append(fr"\m{query_value}\M")
query_conditions += ")"
else:
for not_query, quoted_query, regular_query in BOOLEAN_ARGS.findall(value):
if quoted_query:
if query_conditions:
query_conditions += " AND"
query_conditions += f" {param}=%s"
query_values.append(quoted_query[1:-1])
else:
if not_query != "":
query_value = not_query
else:
query_value = regular_query
if query_value.startswith("NOT "):
if query_conditions:
query_conditions += " AND"
query_conditions += f" {param} !~* %s"
split_value = " ".join(query_value.split()[1:]).strip()
query_values.append(fr"\m{split_value}\M")
else:
if query_conditions:
query_conditions += " AND"
query_conditions += f" {param} ~* %s"
query_values.append(fr"\m{query_value}\M")
else:
value = value.replace('"', "")
if "-" in value:
if query_conditions:
query_conditions += " AND "
values = [v for v in re.split(r"(-)", value) if v]
if values[0] == "-":
query_conditions += f" {param} <= %s"
query_values.append(int(values[1]))
elif values[-1] == "-":
query_conditions += f" {param} >= %s"
query_values.append(int(values[0]))
else:
query_conditions += f" {param} BETWEEN %s AND %s"
query_values.extend([int(values[0]), int(values[2])])
else:
query_conditions = add_to_condition(query_conditions, joiner="", field=param, operator="=")
query_values.append(value)
return query_conditions, tuple(query_values)
@app.get("/")
@app.get("/nav/{dbname}")
@app.get("/nav/{dbname}/passage/{passage_id}")
@app.get("/nav/{dbname}/query/search")
@app.get("/nav/{dbname}/topic/{topicID}")
@app.get("/nav/{dbname}/commonplace/search")
def index(dbname="ecco"):
"""Index file for app"""
if dbname is None:
dbname = "ecco"
with open("public/index.html") as index_file:
index_html = index_file.read()
index_html = index_html.replace(r"{{ .title }}", "Commonplace Cultures")
index_html = index_html.replace(r"{{ .dbSelected }}", dbname)
return HTMLResponse(index_html)
@app.get("/api/{dbname}/commonplaces/{passage_id}")
def find_common_places(dbname: str, passage_id: int):
"""Retrieve commonplaces"""
filtered_authors = {}
filtered_titles = {}
with psycopg2.connect(
database=CONFIG["database"], user=CONFIG["user"], password=CONFIG["password"], host="localhost"
) as conn:
cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cursor.execute(
f"SELECT sourceauthor, sourcetitle, sourcedate, sourceleftcontext, sourcematchcontext, sourcerightcontext, sourcephiloid, sourcemodulename, targetauthor, targettitle, targetdate, targetleftcontext, targetmatchcontext, targetrightcontext, targetphiloid, targetmodulename, authorident FROM {dbname} WHERE passageident=%s",
(passage_id,),
)
for row in cursor:
source_author = row["sourceauthor"].replace("<fs/>", "; ")
source_title = row["sourcetitle"].replace("<fs/>", "; ")
target_author = row["targetauthor"].replace("<fs/>", "; ")
target_title = row["targettitle"].replace("<fs/>", "; ")
if source_author not in filtered_authors:
filtered_authors[source_author] = {
"author": source_author,
"title": source_title,
"date": row["sourcedate"],
"leftContext": row["sourceleftcontext"],
"rightContext": row["sourcerightcontext"],
"matchContext": row["sourcematchcontext"],
"philoID": row["sourcephiloid"],
"databaseName": row["sourcemodulename"],
"passageID": passage_id,
"authorident": row["authorident"],
}
else:
if (
filtered_authors[source_author]["date"] > row["sourcedate"]
or filtered_authors[source_author]["date"] == row["sourcedate"]
and len(filtered_authors[source_author]["matchContext"]) < len(row["sourcematchcontext"])
):
filtered_authors[source_author] = {
"author": source_author,
"title": source_title,
"date": row["sourcedate"],
"leftContext": row["sourceleftcontext"],
"rightContext": row["sourcerightcontext"],
"matchContext": row["sourcematchcontext"],
"philoID": row["sourcephiloid"],
"databaseName": row["sourcemodulename"],
"passageID": passage_id,
"authorident": row["authorident"],
}
if source_title not in filtered_titles:
filtered_titles[source_title] = {
"author": source_author,
"title": source_title,
"date": row["sourcedate"],
"leftContext": row["sourceleftcontext"],
"rightContext": row["sourcerightcontext"],
"matchContext": row["sourcematchcontext"],
"philoID": row["sourcephiloid"],
"databaseName": row["sourcemodulename"],
"passageID": passage_id,
"authorident": row["authorident"],
}
else:
if filtered_titles[source_title]["date"] > row["sourcedate"]:
filtered_titles[source_title] = {
"author": source_author,
"title": source_title,
"date": row["sourcedate"],
"leftContext": row["sourceleftcontext"],
"rightContext": row["sourcerightcontext"],
"matchContext": row["sourcematchcontext"],
"philoID": row["sourcephiloid"],
"databaseName": row["sourcemodulename"],
"passageID": passage_id,
"authorident": row["authorident"],
}
# Process target results
if target_author not in filtered_authors:
filtered_authors[target_author] = {
"author": target_author,
"title": target_title,
"date": row["targetdate"],
"leftContext": row["targetleftcontext"],
"rightContext": row["targetrightcontext"],
"matchContext": row["targetmatchcontext"],
"philoID": row["targetphiloid"],
"databaseName": row["targetmodulename"],
"passageID": passage_id,
"authorident": row["authorident"],
}
else:
if (
filtered_authors[target_author]["date"] > row["targetdate"]
or filtered_authors[target_author]["date"] == row["targetdate"]
and len(filtered_authors[target_author]["matchContext"]) < len(row["targetmatchcontext"])
):
filtered_authors[target_author] = {
"author": target_author,
"title": target_title,
"date": row["targetdate"],
"leftContext": row["targetleftcontext"],
"rightContext": row["targetrightcontext"],
"matchContext": row["targetmatchcontext"],
"philoID": row["targetphiloid"],
"databaseName": row["targetmodulename"],
"passageID": passage_id,
"authorident": row["authorident"],
}
if target_title not in filtered_titles:
filtered_titles[target_title] = {
"author": target_author,
"title": target_title,
"date": row["targetdate"],
"leftContext": row["targetleftcontext"],
"rightContext": row["targetrightcontext"],
"matchContext": row["targetmatchcontext"],
"philoID": row["targetphiloid"],
"databaseName": row["targetmodulename"],
"passageID": passage_id,
"authorident": row["authorident"],
}
else:
if filtered_titles[target_title]["date"] > row["targetdate"]:
filtered_titles[target_title] = {
"author": target_author,
"title": target_title,
"date": row["targetdate"],
"leftContext": row["targetleftcontext"],
"rightContext": row["targetrightcontext"],
"matchContext": row["targetmatchcontext"],
"philoID": row["targetphiloid"],
"databaseName": row["targetmodulename"],
"passageID": passage_id,
"authorident": row["authorident"],
}
unique_titles = [value for value in filtered_titles.values()]
unique_titles.sort(key=lambda x: x["date"])
unique_authors = []
results = {}
for value in filtered_authors.values():
if value["date"] not in results:
results[value["date"]] = [value]
else:
results[value["date"]].append(value)
for key, value in results.items():
unique_authors.append({"date": key, "result": value})
unique_authors.sort(key=lambda x: x["date"])
full_results = {"passageList": unique_titles, "titleList": unique_authors}
return full_results
@app.get("/api/{dbname}/fulltext")
def full_text_query(
dbname: str,
sorting: int,
request: Request,
offset: Optional[int] = None,
):
"""Full text query"""
# TODO: replicate duplicate IDS functionality. Can't recall what this does...
# duplicate_ids =
query = f"SELECT sourceauthor, sourcetitle, sourcedate, sourceleftcontext, sourcematchcontext, sourcerightcontext, sourcephiloid, sourcemodulename, targetauthor, targettitle, targetdate, targetleftcontext, targetmatchcontext, targetrightcontext, targetphiloid, targetmodulename, passageident, passageidentcount, authorident FROM {dbname} WHERE "
sort_fields = ", ".join(SORT_KEY_MAP[sorting])
query_conditions, query_values = build_query((request))
query += query_conditions
if offset is None:
if sorting == -1:
query += " LIMIT 40"
else:
query += f" ORDER BY {sort_fields} LIMIT 40"
else:
if sorting == -1:
query += f" OFFSET {offset} LIMIT 40"
else:
query += f" ORDER BY {sorting} OFFSET {offset} LIMIT 40"
results = {"fullList": []}
with psycopg2.connect(
database=CONFIG["database"], user=CONFIG["user"], password=CONFIG["password"], host="localhost"
) as conn:
cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cursor.execute(query, query_values)
for row in cursor:
source_author = row["sourceauthor"].replace("<fs/>", "; ")
source_title = row["sourcetitle"].replace("<fs/>", "; ")
target_author = row["targetauthor"].replace("<fs/>", "; ")
target_title = row["targettitle"].replace("<fs/>", "; ")
results["fullList"].append(
{
"sourceAuthor": source_author,
"sourceTitle": source_title,
"sourceDate": row["sourcedate"],
"sourceLeftContext": row["sourceleftcontext"],
"sourceRightContext": row["sourcerightcontext"],
"sourceMatchContext": row["sourcematchcontext"],
"philoID": row["sourcephiloid"],
"databaseName": row["sourcemodulename"],
"targetAuthor": target_author,
"targetTitle": target_title,
"targetDate": row["targetdate"],
"targetLeftContext": row["targetleftcontext"],
"targetRightContext": row["targetrightcontext"],
"targetMatchContext": row["targetmatchcontext"],
"targetPhiloID": row["targetphiloid"],
"targetmodulename": row["targetmodulename"],
"passageID": row["passageident"],
"authorident": row["authorident"],
"passageIDCount": row["passageidentcount"],
}
)
if len(results["fullList"]) == 0:
return []
return results
@app.get("/api/{dbname}/fulltextcount")
def full_text_count(dbname: str, request: Request):
"""Get full text count"""
# TODO: duplicate ID functionality
query = f"SELECT COUNT(*) FROM {dbname} WHERE "
query_conditions, query_values = build_query(request)
query += query_conditions
with psycopg2.connect(database=CONFIG["database"], user=CONFIG["user"], password=CONFIG["password"]) as conn:
cursor = conn.cursor()
cursor.execute(query, query_values)
total_count = cursor.fetchone()[0]
return {"totalCount": total_count}
@app.get("/api/{dbname}/fulltextfacet")
def full_text_facet(dbname: str, facet: str, request: Request):
"""Get full text facet"""
# TODO: duplicate ID functionality
query_conditions, query_values = build_query(request)
if facet.endswith("date"):
query = f"SELECT CONCAT(decade, '-', decade + 9) AS year, COUNT(*) FROM (SELECT floor({facet} / 10) * 10 AS decade FROM {dbname} WHERE {query_conditions}) t GROUP BY decade ORDER BY COUNT(*) DESC LIMIT 100"
else:
query = f"SELECT {facet}, COUNT(*) FROM {dbname} WHERE {query_conditions} GROUP BY {facet} ORDER BY COUNT(*) DESC LIMIT 100"
results = []
with psycopg2.connect(database=CONFIG["database"], user=CONFIG["user"], password=CONFIG["password"]) as conn:
cursor = conn.cursor()
cursor.execute(query, query_values)
for row in cursor:
facet_value, count = row
results.append({"facet": facet_value, "count": count})
return results
@app.get("/config/config.json")
def export_config():
"""Export config"""
return JSONResponse(CONFIG)