forked from endpnt/andoc
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathandoc.py
More file actions
419 lines (343 loc) · 14 KB
/
andoc.py
File metadata and controls
419 lines (343 loc) · 14 KB
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
#!/usr/bin/env python
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import cherrypy, simplejson, re, string
from os import path
from lxml import html as lxhtml
from lxml.html import builder as b
from urlparse import urlsplit
from doc import Document
from selection import *
from triple import *
from jinja2 import Template, Environment, FileSystemLoader
from redis import Redis
CURDIR = path.dirname(path.abspath(__file__))
STATICDIR = CURDIR + "/static/"
TEMPLATES_DIR = CURDIR + "/templates/"
def jsonify_tool_callback(*args, **kwargs):
response = cherrypy.response
response.headers['Content-Type'] = 'application/json'
response.body = simplejson.JSONEncoder().iterencode(response.body)
cherrypy.tools.jsonify = cherrypy.Tool('before_finalize',
jsonify_tool_callback, priority=30)
class Andoc(object):
def __init__(self):
self._documents = [1,2,3]
self._env = Environment(loader=FileSystemLoader(TEMPLATES_DIR))
self._redis = Redis()
self._txt_selections = TextSelections(self._redis)
self._html_selections = HtmlSelections(self._redis)
self._triples = Triples(self._redis)
def default(self):
default = self._env.get_template('default.html')
return default.render(title='Andoc Default')
default.exposed = True
def search(self,query):
search_tmpl = self._env.get_template('search/result.html')
return search_tmpl.render(title='Andoc Search', result='TODO')
search.exposed = True
def event(self, action, id=None):
if action == 'list':
event_list_tmpl = self._env.get_template('event/list.html')
return event_list_tmpl.render(title='Events')
return ""
event.exposed = True
def person(self, action):
if action == 'list':
person_list_tmpl = self._env.get_template('person/list.html')
persons = []
for t in self._triples.from_predicate('person'):
persons.append({'uri':t.subject, 'name':t.object})
return person_list_tmpl.render(
title = 'Persons',
persons = sorted(persons))
else:
return ""
person.exposed = True
def place(self, action):
if action == 'list':
place_list_tmpl = self._env.get_template('place/list.html')
html = []
places = []
for t in self._triples.from_predicate('place'):
places.append({'uri': t.subject, 'name': t.object})
return place_list_tmpl.render(
title = 'Places',
places = sorted(places))
else:
return ""
place.exposed = True
def date(self, action):
if action == 'list':
date_list_tmpl = self._env.get_template('date/list.html')
html = []
dates = []
for t in self._triples.from_predicate('date'):
dates.append({'uri': t.subject, 'name': t.object})
return date_list_tmpl.render(
title = 'Dates',
dates = sorted(dates))
else:
return ""
date.exposed = True
def doc(self, action='', id=None):
if action == 'list' and id is None:
list_tmpl = self._env.get_template('doc/list.html')
return list_tmpl.render(
title='Document List',
doclist=[1,2,3,4,5,6,7])
d = Document(id)
if not d.content:
return "No such document"
if action == 'raw':
raw_tmpl = self._env.get_template('doc/raw.html')
return raw_tmpl.render(title='Raw Document', doc = d)
elif action == 'struc':
struc_tmpl = self._env.get_template('doc/struc.html')
elements = self._render(d.id)
# TODO migrate this to jinja or keep lxml?
if elements:
html = []
for start, end, sel in elements:
if len(d.content[start:end].strip()) > 0:
cclass = b.CLASS('s' + str(start) + 'e' + str(end))
if sel is not None and sel.docid == d.id:
node = b.E(NAMESPACE[sel.ref], cclass)
node.text = d.content[start:end]
html.append(node)
else:
html.append(b.PRE(d.content[start:end], cclass))
return struc_tmpl.render(
title = "Document Semantic",
doc = d,
struc = lxhtml.tostring(b.DIV(*html)))
else:
return struc_tmpl.render(
title = "Document Semantic",
doc = d,
struc = 'Nothing here jet')
elif action == 'view':
view_tmpl = self._env.get_template('doc/view.html')
elements = self._render(d.id)
if elements:
content_html = []
meta_html = []
metalist = {}
for start, end, sel in elements:
if len(d.content[start:end]) > 0:
if sel is not None and sel.docid == d.id:
node = b.E(NAMESPACE[sel.ref])
node.text = d.content[start:end].strip()
content_html.append(node)
else:
content_html.append(b.PRE(d.content[start:end].strip()))
for pre in ('person','place','date','event'):
metalist[pre] = set()
#for sel, sub, pre, obj, start, end in self._triples:
# if sel is not None and sel.docid == d.id:
# metalist[pre].add(obj)
for pre in ('person','place','date','event'):
metali = []
for m in sorted(metalist[pre]):
metali.append(b.LI(m))
meta_html.append(b.H3(pre))
meta_html.append(b.UL(*metali))
content = lxhtml.tostring(b.DIV(*content_html))
meta = lxhtml.tostring(b.DIV(*meta_html))
return view_tmpl.render(
title = 'Document View',
doc = d,
content = content,
meta = meta)
else:
return view_tmpl.render(
title = 'Document View',
doc = d,
content = 'Nothing to render',
meta = '')
else:
return "Unknown action"
doc.exposed = True
def get_json(self):
cl = cherrypy.request.headers['Content-Length']
rawbody = cherrypy.request.body.read(int(cl))
return simplejson.loads(rawbody)
def _render(self, id):
d = Document(id)
if not d.content:
return False
selections = []
for sel in self._txt_selections.from_document_id(d.id):
t = (sel.start, sel.end, sel)
selections.append(t)
if len(selections) == 0:
return False
selections.sort()
# check for overlapping selections
# we create sets with all string positions
# and check for any intersections between them
# if they overlap, remove
removed = []
last = set()
for index, (start, end, sel) in enumerate(selections):
current = set(range(start,end))
intersec = last.intersection(current)
if intersec != current and len(intersec) > 0:
removed.append(selections.pop(index))
last = current
matched = set()
max = len(d.content)
# every possible char position
everything = set(range(0,max))
# every char position of all selected ranges
for start, end, sel in selections:
matched = matched.union(set(range(start,end)))
# positions of all unmatched chars
unmatched = list(everything.difference(matched))
if len(unmatched) > 0:
untouched = [] # list of untouched ranges
unmatch_last_pos = 0
unmatch_start = unmatched[0] # set position of the first unmatched char
unmatch_last = unmatched[-1] # set position of the last unmatched char
# this is detecting a gap in a range
# only add if we have a real range, not just a single position
for unmatch_pos in unmatched:
if unmatch_last_pos > 0 and unmatch_pos != unmatch_last_pos + 1:
if unmatch_start < unmatch_last_pos:
untouched.append((unmatch_start,unmatch_last_pos,None))
unmatch_start = unmatch_pos
unmatch_last_pos = unmatch_pos
# last unmatched range
if unmatch_start < unmatch_last:
untouched.append((unmatch_start,unmatch_last,None))
print "Selections"
print selections
print "Removed"
print removed
print "untouched"
print untouched
elements = selections + untouched
elements.sort()
return elements
class Rest(object):
def __init__(self):
self._redis = Redis()
self._txt_selections = TextSelections(self._redis)
self._html_selections = HtmlSelections(self._redis)
self._triples = Triples(self._redis)
def get_json(self):
cl = cherrypy.request.headers['Content-Length']
rawbody = cherrypy.request.body.read(int(cl))
return simplejson.loads(rawbody)
@cherrypy.tools.jsonify()
def selection(self,action,id):
d = Document(id)
if not d.content:
return "No such document"
if action == 'list':
selections = []
for s in self._txt_selections.from_document_id(d.id):
t = (s.start, s.end, s.ref)
selections.append(t)
print sorted(selections, reverse=True)
return sorted(selections, reverse=True)
elif action == 'add':
j = self.get_json()
start = j.get('start',0)
end = j.get('end',0)
ref = j.get('ref','')
if start == 0 and end == 0:
return "Nothing selected"
if len(d.content[start:end+1].strip()) == 0:
return "Empty string selected"
txtsel = TextSelection(d.id, start, end+1, ref)
txtsel.save(self._redis)
del txtsel
return d.content[start:end+1]
elif action == 'delete':
j = self.get_json()
start = j.get('start',0)
end = j.get('end',0)
ref = j.get('ref','')
if start == 0 and end == 0:
return "Nothing selected"
return "OK"
elif action == 'update':
return "OK"
else:
return "Nothing to do"
selection.exposed = True
@cherrypy.tools.jsonify()
def triple(self,action,id):
d = Document(id)
if not d.content:
return "No such document"
if action == 'add':
j = self.get_json()
sub = j.get('s','')
pre = j.get('p','')
obj = j.get('o','')
start = j.get('start',0)
end = j.get('end',0)
scheme, host, path, query, param = urlsplit(sub)
print sub, pre, obj, start, end
tsel = TextSelection(docid = d.id)
tsel.from_url(sub)
sub = '%s/t%se%s' % (sub, start, end)
trip = Triple(sub, pre, obj)
tid = trip.save(self._redis)
h = HtmlSelection(d.id, sub, start, end, tid)
h.save(self._redis)
s = tsel.start + start
e = tsel.start + end
return d.content[s:e]
if action == 'list':
tl = set()
for h in self._html_selections.from_document_id(d.id):
for t in self._triples.from_subject(h.node):
tl.add((t.subject, h.start, h.end, t.pre, t.object))
# JS fails to apply the selection with DOM errors,
# if they come in the wrong order.
# Sort by subject (the DOM node as url)
# and the start of the selection inside the node
def subject_sort(t):
scheme, netloc, path, query, fragment = urlsplit(t[0])
return (fragment.split('/')[0], t[1])
# Reversed since we need to build the page bottom to top
# in JS. This avoids problems with the offset inside
# a DOM node.
print sorted(tl, reverse=True, key=subject_sort)
return sorted(tl, reverse=True, key=subject_sort)
else:
return "Nothing to do"
triple.exposed = True
config = {'/static': {
'tools.staticdir.on': True,
'tools.staticdir.dir': STATICDIR },
'/data': {
'tools.staticdir.on': True,
'tools.staticdir.dir': CURDIR + '/data' },
'/': {'tools.sessions.on': True}
}
cherrypy.tree.mount(Andoc(), '/', config)
cherrypy.tree.mount(Rest(), '/rest/', config)
if hasattr(cherrypy.engine, 'block'):
# 3.1 syntax
cherrypy.engine.start()
cherrypy.engine.block()
else:
# 3.0 syntax
cherrypy.server.quickstart()
cherrypy.engine.start()