564
|
1 from OFS.SimpleItem import SimpleItem
|
|
2 from Products.PageTemplates.PageTemplateFile import PageTemplateFile
|
|
3
|
|
4 import xml.etree.ElementTree as ET
|
|
5
|
|
6 import re
|
|
7 import logging
|
|
8 import urllib
|
|
9 import urlparse
|
|
10 import base64
|
|
11
|
576
|
12 from datetime import datetime
|
|
13
|
564
|
14 from SrvTxtUtils import getInt, getText, getHttpData
|
|
15
|
|
16 def serialize(node):
|
|
17 """returns a string containing an XML snippet of node"""
|
|
18 s = ET.tostring(node, 'UTF-8')
|
|
19 # snip off XML declaration
|
|
20 if s.startswith('<?xml'):
|
|
21 i = s.find('?>')
|
|
22 return s[i+3:]
|
|
23
|
|
24 return s
|
|
25
|
|
26
|
|
27 class MpiwgXmlTextServer(SimpleItem):
|
|
28 """TextServer implementation for MPIWG-XML server"""
|
|
29 meta_type="MPIWG-XML TextServer"
|
|
30
|
|
31 manage_options=(
|
|
32 {'label':'Config','action':'manage_changeMpiwgXmlTextServerForm'},
|
|
33 )+SimpleItem.manage_options
|
|
34
|
|
35 manage_changeMpiwgXmlTextServerForm = PageTemplateFile("zpt/manage_changeMpiwgXmlTextServer", globals())
|
|
36
|
|
37 def __init__(self,id,title="",serverUrl="http://mpdl-text.mpiwg-berlin.mpg.de/mpiwg-mpdl-cms-web/", timeout=40, serverName=None, repositoryType='production'):
|
|
38 """constructor"""
|
|
39 self.id=id
|
|
40 self.title=title
|
|
41 self.timeout = timeout
|
|
42 self.repositoryType = repositoryType
|
|
43 if serverName is None:
|
|
44 self.serverUrl = serverUrl
|
|
45 else:
|
|
46 self.serverUrl = "http://%s/mpiwg-mpdl-cms-web/"%serverName
|
|
47
|
|
48 def getHttpData(self, url, data=None):
|
|
49 """returns result from url+data HTTP request"""
|
|
50 return getHttpData(url,data,timeout=self.timeout)
|
|
51
|
|
52 def getServerData(self, method, data=None):
|
|
53 """returns result from text server for method+data"""
|
|
54 url = self.serverUrl+method
|
|
55 return getHttpData(url,data,timeout=self.timeout)
|
|
56
|
|
57
|
|
58 def getRepositoryType(self):
|
|
59 """returns the repository type, e.g. 'production'"""
|
572
|
60 return getattr(self, 'repositoryType', None)
|
564
|
61
|
|
62 def getTextDownloadUrl(self, type='xml', docinfo=None):
|
|
63 """returns a URL to download the current text"""
|
|
64 docpath = docinfo.get('textURLPath', None)
|
|
65 if not docpath:
|
|
66 return None
|
|
67
|
|
68 docpath = docpath.replace('.xml','.'+type)
|
|
69 url = '%sdoc/GetDocument?id=%s'%(self.serverUrl.replace('interface/',''), docpath)
|
|
70 return url
|
|
71
|
|
72
|
|
73 def getPlacesOnPage(self, docinfo=None, pn=None):
|
|
74 """Returns list of GIS places of page pn"""
|
|
75 #FIXME!
|
|
76 docpath = docinfo.get('textURLPath',None)
|
|
77 if not docpath:
|
|
78 return None
|
|
79
|
|
80 places=[]
|
|
81 text=self.getServerData("xpath.xql", "document=%s&xpath=//place&pn=%s"%(docpath,pn))
|
|
82 dom = ET.fromstring(text)
|
|
83 result = dom.findall(".//resultPage/place")
|
|
84 for l in result:
|
|
85 id = l.get("id")
|
|
86 name = l.text
|
|
87 place = {'id': id, 'name': name}
|
|
88 places.append(place)
|
|
89
|
|
90 return places
|
|
91
|
|
92
|
565
|
93 def getTextInfo(self, mode=None, docinfo=None):
|
564
|
94 """reads document info, including page concordance, from text server"""
|
|
95 logging.debug("getTextInfo mode=%s"%mode)
|
565
|
96
|
|
97 field = ''
|
609
|
98 if mode in ['pages', 'toc', 'figures', 'notes', 'handwritten']:
|
565
|
99 # translate mode to field param
|
609
|
100 if mode == 'handwritten':
|
|
101 field = '&field=notesHandwritten'
|
|
102 else:
|
|
103 field = '&field=%s'%mode
|
565
|
104 else:
|
|
105 mode = None
|
|
106
|
564
|
107 # check cached info
|
|
108 if mode:
|
|
109 # cached toc-request?
|
|
110 if 'full_%s'%mode in docinfo:
|
|
111 return docinfo
|
|
112
|
|
113 else:
|
565
|
114 # cached but no toc-request?
|
564
|
115 if 'numTextPages' in docinfo:
|
|
116 return docinfo
|
|
117
|
|
118 docpath = docinfo.get('textURLPath', None)
|
|
119 if docpath is None:
|
|
120 logging.error("getTextInfo: no textURLPath!")
|
|
121 return docinfo
|
|
122
|
|
123 # fetch docinfo
|
565
|
124 pagexml = self.getServerData("query/GetDocInfo","docId=%s%s"%(docpath,field))
|
564
|
125 dom = ET.fromstring(pagexml)
|
565
|
126 # all info in tag <doc>
|
|
127 doc = dom
|
564
|
128 if doc is None:
|
|
129 logging.error("getTextInfo: unable to find document-tag!")
|
|
130 else:
|
565
|
131 if mode is None:
|
|
132 # get general info from system-tag
|
568
|
133 sys = doc.find('system')
|
|
134 if sys is not None:
|
|
135 docinfo['numTextPages'] = getInt(getText(sys.find('countPages')))
|
|
136 docinfo['numFigureEntries'] = getInt(getText(sys.find('countFigures')))
|
609
|
137 docinfo['numHandwritten'] = getInt(getText(sys.find('countNotesHandwritten')))
|
|
138 docinfo['numNotes'] = getInt(getText(sys.find('countNotes')))
|
|
139 docinfo['numPlaces'] = getInt(getText(sys.find('countPlaces')))
|
568
|
140 docinfo['numTocEntries'] = getInt(getText(sys.find('countTocEntries')))
|
565
|
141
|
|
142 else:
|
|
143 # result is in list-tag
|
|
144 l = doc.find('list')
|
|
145 if l is not None:
|
|
146 lt = l.get('type')
|
|
147 # pageNumbers
|
|
148 if lt == 'pages':
|
|
149 # contains tags with page numbers
|
|
150 # <item n="14" o="2" o-norm="2" file="0014"/>
|
|
151 # n=scan number, o=original page no, on=normalized original page no
|
|
152 # pageNumbers is a dict indexed by scan number
|
|
153 pages = {}
|
|
154 for i in l:
|
|
155 page = {}
|
|
156 pn = getInt(i.get('n'))
|
|
157 page['pn'] = pn
|
568
|
158 no = i.get('o')
|
565
|
159 page['no'] = no
|
568
|
160 non = i.get('o-norm')
|
565
|
161 page['non'] = non
|
|
162
|
|
163 if pn > 0:
|
|
164 pages[pn] = page
|
|
165
|
|
166 docinfo['pageNumbers'] = pages
|
|
167
|
|
168 # toc
|
609
|
169 elif lt in ['toc', 'figures', 'notes', 'notesHandwritten']:
|
565
|
170 # contains tags with table of contents/figures
|
568
|
171 # <item n="2.1." lv="2">CAP.I. <ref o="119">132</ref></item>
|
565
|
172 tocs = []
|
568
|
173 for te in l:
|
|
174 if te.tag == 'item':
|
|
175 toc = {}
|
|
176 toc['level-string'] = te.get('n')
|
|
177 toc['level'] = te.get('lv')
|
|
178 toc['content'] = te.text.strip()
|
|
179 ref = te.find('ref')
|
|
180 toc['pn'] = getInt(ref.text)
|
|
181 toc['no'] = ref.get('o')
|
|
182 toc['non'] = ref.get('o-norm')
|
|
183 tocs.append(toc)
|
564
|
184
|
565
|
185 # save as full_toc/full_figures
|
|
186 docinfo['full_%s'%mode] = tocs
|
564
|
187
|
|
188 return docinfo
|
|
189
|
|
190
|
|
191 def getTextPage(self, mode="text", pn=1, docinfo=None, pageinfo=None):
|
|
192 """returns single page from fulltext"""
|
|
193
|
|
194 logging.debug("getTextPage mode=%s, pn=%s"%(mode,pn))
|
576
|
195 startTime = datetime.now()
|
564
|
196 # check for cached text -- but ideally this shouldn't be called twice
|
|
197 if pageinfo.has_key('textPage'):
|
|
198 logging.debug("getTextPage: using cached text")
|
|
199 return pageinfo['textPage']
|
|
200
|
|
201 docpath = docinfo.get('textURLPath', None)
|
|
202 if not docpath:
|
|
203 return None
|
|
204
|
|
205 # stuff for constructing full urls
|
|
206 selfurl = docinfo['viewerUrl']
|
|
207 textParams = {'docId': docpath,
|
|
208 'page': pn}
|
565
|
209
|
575
|
210 normMode = pageinfo.get('characterNormalization', 'reg')
|
|
211 # TODO: change values in form
|
|
212 if normMode == 'regPlusNorm':
|
|
213 normMode = 'norm'
|
576
|
214
|
|
215 # TODO: this should not be necessary when the backend is fixed
|
579
|
216 #textParams['normalization'] = normMode
|
576
|
217
|
564
|
218 if not mode:
|
|
219 # default is dict
|
|
220 mode = 'text'
|
|
221
|
|
222 modes = mode.split(',')
|
|
223 # check for multiple layers
|
|
224 if len(modes) > 1:
|
|
225 logging.debug("getTextPage: more than one mode=%s"%mode)
|
|
226
|
|
227 # search mode
|
|
228 if 'search' in modes:
|
|
229 # add highlighting
|
|
230 highlightQuery = pageinfo.get('highlightQuery', None)
|
|
231 if highlightQuery:
|
|
232 textParams['highlightQuery'] = highlightQuery
|
|
233 textParams['highlightElem'] = pageinfo.get('highlightElement', '')
|
|
234 textParams['highlightElemPos'] = pageinfo.get('highlightElementPos', '')
|
|
235
|
|
236 # ignore mode in the following
|
|
237 modes.remove('search')
|
|
238
|
|
239 # pundit mode
|
|
240 punditMode = False
|
|
241 if 'pundit' in modes:
|
|
242 punditMode = True
|
|
243 # ignore mode in the following
|
|
244 modes.remove('pundit')
|
|
245
|
|
246 # other modes don't combine
|
|
247 if 'dict' in modes:
|
|
248 textmode = 'dict'
|
|
249 textParams['outputFormat'] = 'html'
|
|
250 elif 'xml' in modes:
|
|
251 textmode = 'xml'
|
|
252 textParams['outputFormat'] = 'xmlDisplay'
|
576
|
253 normMode = 'orig'
|
564
|
254 elif 'gis' in modes:
|
|
255 #FIXME!
|
|
256 textmode = 'gis'
|
|
257 else:
|
|
258 # text is default mode
|
575
|
259 textmode = 'plain'
|
564
|
260 textParams['outputFormat'] = 'html'
|
|
261
|
565
|
262 try:
|
570
|
263 # fetch the page
|
|
264 pagexml = self.getServerData("query/GetPage",urllib.urlencode(textParams))
|
565
|
265 dom = ET.fromstring(pagexml)
|
|
266 except Exception, e:
|
570
|
267 logging.error("Error reading page: %s"%e)
|
565
|
268 return None
|
|
269
|
566
|
270 # plain text or text-with-links mode
|
575
|
271 if textmode == "plain" or textmode == "dict":
|
574
|
272 # the text is in div@class=text
|
|
273 pagediv = dom.find(".//div[@class='text']")
|
|
274 logging.debug("pagediv: %s"%repr(pagediv))
|
564
|
275 if pagediv is not None:
|
575
|
276 # add textmode and normMode classes
|
579
|
277 #pagediv.set('class', 'text %s %s'%(textmode, normMode))
|
576
|
278 self._processWTags(textmode, normMode, pagediv)
|
567
|
279 #self._processPbTag(pagediv, pageinfo)
|
566
|
280 self._processFigures(pagediv, docinfo)
|
|
281 #self._fixEmptyDivs(pagediv)
|
565
|
282 # get full url assuming documentViewer is parent
|
|
283 selfurl = self.getLink()
|
564
|
284 # check all a-tags
|
|
285 links = pagediv.findall('.//a')
|
|
286 for l in links:
|
|
287 href = l.get('href')
|
|
288 if href:
|
|
289 # is link with href
|
|
290 linkurl = urlparse.urlparse(href)
|
|
291 if linkurl.path.endswith('GetDictionaryEntries'):
|
|
292 #TODO: replace wordInfo page
|
|
293 # add target to open new page
|
|
294 l.set('target', '_blank')
|
566
|
295
|
|
296 if punditMode:
|
|
297 self._addPunditAttributes(pagediv, pageinfo, docinfo)
|
577
|
298
|
576
|
299 s = serialize(pagediv)
|
|
300 logging.debug("getTextPage done in %s"%(datetime.now()-startTime))
|
|
301 return s
|
564
|
302
|
|
303 # xml mode
|
|
304 elif textmode == "xml":
|
574
|
305 # the text is in body
|
|
306 pagediv = dom.find(".//body")
|
|
307 logging.debug("pagediv: %s"%repr(pagediv))
|
564
|
308 if pagediv is not None:
|
|
309 return serialize(pagediv)
|
|
310
|
|
311 # pureXml mode WTF?
|
|
312 elif textmode == "pureXml":
|
574
|
313 # the text is in body
|
|
314 pagediv = dom.find(".//body")
|
|
315 logging.debug("pagediv: %s"%repr(pagediv))
|
564
|
316 if pagediv is not None:
|
|
317 return serialize(pagediv)
|
|
318
|
566
|
319 # gis mode FIXME!
|
564
|
320 elif textmode == "gis":
|
574
|
321 # the text is in div@class=text
|
|
322 pagediv = dom.find(".//div[@class='text']")
|
|
323 logging.debug("pagediv: %s"%repr(pagediv))
|
564
|
324 if pagediv is not None:
|
|
325 # fix empty div tags
|
565
|
326 self._fixEmptyDivs(pagediv)
|
564
|
327 # check all a-tags
|
|
328 links = pagediv.findall(".//a")
|
|
329 # add our URL as backlink
|
|
330 selfurl = self.getLink()
|
|
331 doc = base64.b64encode(selfurl)
|
|
332 for l in links:
|
|
333 href = l.get('href')
|
|
334 if href:
|
|
335 if href.startswith('http://mappit.mpiwg-berlin.mpg.de'):
|
|
336 l.set('href', re.sub(r'doc=[\w+/=]+', 'doc=%s'%doc, href))
|
|
337 l.set('target', '_blank')
|
|
338
|
|
339 return serialize(pagediv)
|
|
340
|
579
|
341 logging.error("getTextPage: error in text mode %s or in text!"%(textmode))
|
564
|
342 return None
|
565
|
343
|
575
|
344 def _processWTags(self, textMode, normMode, pagediv):
|
|
345 """selects the necessary information from w-spans and removes the rest from pagediv"""
|
|
346 logging.debug("processWTags(textMode=%s,norm=%s,pagediv"%(repr(textMode),repr(normMode)))
|
576
|
347 startTime = datetime.now()
|
575
|
348 wtags = pagediv.findall(".//span[@class='w']")
|
|
349 for wtag in wtags:
|
|
350 if textMode == 'dict':
|
576
|
351 # delete non-a-tags
|
|
352 wtag.remove(wtag.find("span[@class='nodictionary orig']"))
|
|
353 wtag.remove(wtag.find("span[@class='nodictionary reg']"))
|
|
354 wtag.remove(wtag.find("span[@class='nodictionary norm']"))
|
|
355 # delete non-matching children of a-tag and suppress remaining tag name
|
579
|
356 atag = wtag.find("*[@class='dictionary']")
|
576
|
357 if normMode == 'orig':
|
|
358 atag.remove(atag.find("span[@class='reg']"))
|
|
359 atag.remove(atag.find("span[@class='norm']"))
|
|
360 atag.find("span[@class='orig']").tag = None
|
|
361 elif normMode == 'reg':
|
|
362 atag.remove(atag.find("span[@class='orig']"))
|
|
363 atag.remove(atag.find("span[@class='norm']"))
|
|
364 atag.find("span[@class='reg']").tag = None
|
|
365 elif normMode == 'norm':
|
|
366 atag.remove(atag.find("span[@class='orig']"))
|
|
367 atag.remove(atag.find("span[@class='reg']"))
|
|
368 atag.find("span[@class='norm']").tag = None
|
|
369
|
575
|
370 else:
|
576
|
371 # delete a-tag
|
579
|
372 wtag.remove(wtag.find("*[@class='dictionary']"))
|
576
|
373 # delete non-matching children and suppress remaining tag name
|
|
374 if normMode == 'orig':
|
|
375 wtag.remove(wtag.find("span[@class='nodictionary reg']"))
|
|
376 wtag.remove(wtag.find("span[@class='nodictionary norm']"))
|
|
377 wtag.find("span[@class='nodictionary orig']").tag = None
|
|
378 elif normMode == 'reg':
|
|
379 wtag.remove(wtag.find("span[@class='nodictionary orig']"))
|
|
380 wtag.remove(wtag.find("span[@class='nodictionary norm']"))
|
|
381 wtag.find("span[@class='nodictionary reg']").tag = None
|
|
382 elif normMode == 'norm':
|
|
383 wtag.remove(wtag.find("span[@class='nodictionary orig']"))
|
|
384 wtag.remove(wtag.find("span[@class='nodictionary reg']"))
|
|
385 wtag.find("span[@class='nodictionary norm']").tag = None
|
575
|
386
|
576
|
387 # suppress w-tag name
|
|
388 wtag.tag = None
|
|
389
|
|
390 logging.debug("processWTags in %s"%(datetime.now()-startTime))
|
575
|
391 return pagediv
|
|
392
|
566
|
393 def _processPbTag(self, pagediv, pageinfo):
|
565
|
394 """extracts information from pb-tag and removes it from pagediv"""
|
|
395 pbdiv = pagediv.find(".//span[@class='pb']")
|
|
396 if pbdiv is None:
|
|
397 logging.warning("getTextPage: no pb-span!")
|
|
398 return pagediv
|
|
399
|
|
400 # extract running head
|
|
401 rh = pbdiv.find(".//span[@class='rhead']")
|
|
402 if rh is not None:
|
|
403 pageinfo['pageHeaderTitle'] = getText(rh)
|
|
404
|
|
405 # remove pb-div from parent
|
|
406 ppdiv = pagediv.find(".//span[@class='pb']/..")
|
|
407 ppdiv.remove(pbdiv)
|
|
408 return pagediv
|
564
|
409
|
565
|
410 def _addPunditAttributes(self, pagediv, pageinfo, docinfo):
|
564
|
411 """add about attributes for pundit annotation tool"""
|
|
412 textid = docinfo.get('DRI', "fn=%s"%docinfo.get('documentPath', '???'))
|
|
413 pn = pageinfo.get('pn', '1')
|
|
414 # TODO: use pn as well?
|
|
415 # check all div-tags
|
|
416 divs = pagediv.findall(".//div")
|
|
417 for d in divs:
|
|
418 id = d.get('id')
|
|
419 if id:
|
566
|
420 # TODO: check path (cf RFC2396)
|
564
|
421 d.set('about', "http://echo.mpiwg-berlin.mpg.de/%s/pn=%s/#%s"%(textid,pn,id))
|
|
422 cls = d.get('class','')
|
|
423 cls += ' pundit-content'
|
|
424 d.set('class', cls.strip())
|
|
425
|
|
426 return pagediv
|
|
427
|
566
|
428 def _processFigures(self, pagediv, docinfo):
|
|
429 """processes figure-tags"""
|
576
|
430 # unfortunately etree can not select class.startswith('figure')
|
|
431 divs = pagediv.findall(".//span[@class]")
|
566
|
432 scalerUrl = docinfo['digilibScalerUrl']
|
|
433 viewerUrl = docinfo['digilibViewerUrl']
|
|
434 for d in divs:
|
576
|
435 if not d.get('class').startswith('figure'):
|
|
436 continue
|
|
437
|
566
|
438 try:
|
|
439 a = d.find('a')
|
|
440 img = a.find('img')
|
|
441 imgsrc = img.get('src')
|
|
442 imgurl = urlparse.urlparse(imgsrc)
|
|
443 imgq = imgurl.query
|
|
444 imgparams = urlparse.parse_qs(imgq)
|
|
445 fn = imgparams.get('fn', None)
|
|
446 if fn is not None:
|
|
447 # parse_qs puts parameters in lists
|
|
448 fn = fn[0]
|
|
449 # TODO: check valid path
|
|
450 # fix img@src
|
|
451 newsrc = '%s?fn=%s&dw=200&dh=200'%(scalerUrl,fn)
|
|
452 img.set('src', newsrc)
|
|
453 # fix a@href
|
|
454 newlink = '%s?fn=%s'%(viewerUrl,fn)
|
|
455 a.set('href', newlink)
|
|
456 a.set('target', '_blank')
|
|
457
|
|
458 except:
|
|
459 logging.warn("processFigures: strange figure!")
|
|
460
|
583
|
461
|
|
462 def _cleanSearchResult(self, pagediv):
|
|
463 """fixes search result html (change pbs and figures)"""
|
|
464 # replace figure-tag with figureNumText
|
|
465 for fig in pagediv.findall(".//span[@class='figure']"):
|
|
466 txt = fig.findtext(".//span[@class='figureNumText']")
|
|
467 tail = fig.tail
|
|
468 fig.clear()
|
|
469 fig.set('class', 'figure')
|
|
470 fig.text = txt
|
|
471 fig.tail = tail
|
|
472
|
|
473 # replace lb-tag with "//"
|
|
474 for lb in pagediv.findall(".//br[@class='lb']"):
|
|
475 lb.tag = 'span'
|
|
476 lb.text = '//'
|
|
477
|
|
478 # replace pb-tag with "///"
|
|
479 for pb in pagediv.findall(".//span[@class='pb']"):
|
|
480 tail = pb.tail
|
|
481 pb.clear()
|
|
482 pb.set('class', 'pb')
|
|
483 pb.text = '///'
|
|
484 pb.tail = tail
|
|
485
|
|
486 return pagediv
|
|
487
|
|
488 def _cleanSearchResult2(self, pagediv):
|
|
489 """fixes search result html (change pbs and figures)"""
|
|
490 # unfortunately etree can not select class.startswith('figure')
|
|
491 divs = pagediv.findall(".//span[@class]")
|
|
492 for d in divs:
|
|
493 cls = d.get('class')
|
|
494 if cls.startswith('figure'):
|
|
495 # replace figure-tag with figureNumText
|
|
496 txt = d.findtext(".//span[@class='figureNumText']")
|
|
497 d.clear()
|
|
498 d.set('class', 'figure')
|
|
499 d.text = txt
|
|
500
|
|
501 elif cls.startswith('pb'):
|
|
502 # replace pb-tag with "//"
|
|
503 d.clear()
|
|
504 d.set('class', 'pb')
|
|
505 d.text = '//'
|
|
506
|
|
507 return pagediv
|
|
508
|
|
509
|
566
|
510
|
565
|
511 def _fixEmptyDivs(self, pagediv):
|
|
512 """fixes empty div-tags by inserting a space"""
|
|
513 divs = pagediv.findall('.//div')
|
|
514 for d in divs:
|
|
515 if len(d) == 0 and not d.text:
|
|
516 # make empty divs non-empty
|
|
517 d.text = ' '
|
|
518
|
|
519 return pagediv
|
|
520
|
|
521
|
564
|
522 def getSearchResults(self, mode, query=None, pageinfo=None, docinfo=None):
|
|
523 """loads list of search results and stores XML in docinfo"""
|
583
|
524 normMode = pageinfo.get('characterNormalization', 'reg')
|
|
525 logging.debug("getSearchResults mode=%s query=%s norm=%s"%(mode, query, normMode))
|
564
|
526 if mode == "none":
|
|
527 return docinfo
|
|
528
|
568
|
529 #TODO: put mode into query
|
|
530
|
564
|
531 cachedQuery = docinfo.get('cachedQuery', None)
|
|
532 if cachedQuery is not None:
|
|
533 # cached search result
|
583
|
534 if cachedQuery == '%s_%s_%s'%(mode,query,normMode):
|
564
|
535 # same query
|
|
536 return docinfo
|
|
537
|
|
538 else:
|
|
539 # different query
|
|
540 del docinfo['resultSize']
|
568
|
541 del docinfo['results']
|
564
|
542
|
|
543 # cache query
|
583
|
544 docinfo['cachedQuery'] = '%s_%s_%s'%(mode,query,normMode)
|
564
|
545
|
|
546 # fetch full results
|
|
547 docpath = docinfo['textURLPath']
|
568
|
548 params = {'docId': docpath,
|
564
|
549 'query': query,
|
568
|
550 'pageSize': 1000,
|
|
551 'page': 1,
|
|
552 'outputFormat': 'html'}
|
|
553 pagexml = self.getServerData("query/QueryDocument",urllib.urlencode(params))
|
|
554 results = []
|
|
555 try:
|
|
556 dom = ET.fromstring(pagexml)
|
583
|
557 # clean html output
|
|
558 self._processWTags('plain', normMode, dom)
|
|
559 self._cleanSearchResult(dom)
|
568
|
560 # page content is currently in multiple <td align=left>
|
576
|
561 alldivs = dom.findall(".//tr[@class='hit']")
|
568
|
562 for div in alldivs:
|
576
|
563 # change tr to div
|
|
564 div.tag = 'div'
|
|
565 # change td to span
|
|
566 for d in div.findall('td'):
|
|
567 d.tag = 'span'
|
|
568
|
568
|
569 # TODO: can we put etree in the session?
|
|
570 results.append(div)
|
|
571
|
|
572 except Exception, e:
|
|
573 logging.error("GetSearchResults: Error parsing search result: %s"%e)
|
564
|
574
|
568
|
575 # store results in docinfo
|
|
576 docinfo['resultSize'] = len(results)
|
|
577 docinfo['results'] = results
|
564
|
578
|
|
579 return docinfo
|
|
580
|
|
581
|
|
582 def getResultsPage(self, mode="text", query=None, pn=None, start=None, size=None, pageinfo=None, docinfo=None):
|
583
|
583 """returns single page from the list of search results"""
|
564
|
584 logging.debug("getResultsPage mode=%s, pn=%s"%(mode,pn))
|
|
585 # get (cached) result
|
|
586 self.getSearchResults(mode=mode, query=query, pageinfo=pageinfo, docinfo=docinfo)
|
|
587
|
568
|
588 resultxml = docinfo.get('results', None)
|
564
|
589 if not resultxml:
|
568
|
590 logging.error("getResultPage: unable to find results")
|
564
|
591 return "Error: no result!"
|
|
592
|
|
593 if size is None:
|
|
594 size = pageinfo.get('resultPageSize', 10)
|
|
595
|
|
596 if start is None:
|
|
597 start = (pn - 1) * size
|
|
598
|
576
|
599 if resultxml is not None:
|
564
|
600 # paginate
|
|
601 first = start-1
|
576
|
602 last = first+size
|
|
603 tocdivs = resultxml[first:last]
|
564
|
604
|
576
|
605 toc = ET.Element('div', attrib={'class':'queryResultPage'})
|
|
606 for div in tocdivs:
|
|
607 # check all a-tags
|
|
608 links = div.findall(".//a")
|
|
609 for l in links:
|
|
610 href = l.get('href')
|
|
611 if href:
|
|
612 # assume all links go to pages
|
|
613 linkUrl = urlparse.urlparse(href)
|
|
614 linkParams = urlparse.parse_qs(linkUrl.query)
|
|
615 # take some parameters (make sure it works even if the link was already parsed)
|
|
616 params = {'pn': linkParams.get('page',linkParams.get('pn', None)),
|
|
617 'highlightQuery': linkParams.get('highlightQuery',None),
|
|
618 'highlightElement': linkParams.get('highlightElem',linkParams.get('highlightElement',None)),
|
|
619 'highlightElementPos': linkParams.get('highlightElemPos',linkParams.get('highlightElementPos',None))
|
|
620 }
|
|
621 if not params['pn']:
|
|
622 logging.warn("getResultsPage: link has no page: %s"%href)
|
|
623
|
|
624 url = self.getLink(params=params)
|
|
625 l.set('href', url)
|
564
|
626
|
576
|
627 toc.append(div)
|
|
628
|
|
629 return serialize(toc)
|
564
|
630
|
|
631 return "ERROR: no results!"
|
|
632
|
|
633
|
|
634 def getToc(self, mode='text', docinfo=None):
|
|
635 """returns list of table of contents from docinfo"""
|
|
636 logging.debug("getToc mode=%s"%mode)
|
|
637 if mode == 'text':
|
|
638 queryType = 'toc'
|
|
639 else:
|
|
640 queryType = mode
|
|
641
|
|
642 if not 'full_%s'%queryType in docinfo:
|
|
643 # get new toc
|
|
644 docinfo = self.getTextInfo(queryType, docinfo)
|
|
645
|
|
646 return docinfo.get('full_%s'%queryType, [])
|
|
647
|
568
|
648
|
564
|
649 def getTocPage(self, mode='text', pn=None, start=None, size=None, pageinfo=None, docinfo=None):
|
|
650 """returns single page from the table of contents"""
|
|
651 logging.debug("getTocPage mode=%s, pn=%s start=%s size=%s"%(mode,repr(pn),repr(start),repr(size)))
|
|
652 fulltoc = self.getToc(mode=mode, docinfo=docinfo)
|
|
653 if len(fulltoc) < 1:
|
|
654 logging.error("getTocPage: unable to find toc!")
|
|
655 return "Error: no table of contents!"
|
|
656
|
|
657 if size is None:
|
|
658 size = pageinfo.get('tocPageSize', 30)
|
|
659
|
|
660 if start is None:
|
|
661 start = (pn - 1) * size
|
|
662
|
|
663 # paginate
|
|
664 first = (start - 1)
|
|
665 last = first + size
|
|
666 tocs = fulltoc[first:last]
|
|
667 tp = '<div>'
|
609
|
668 label = {'figures': 'Figure', 'notes': 'Note', 'handwritten': 'Handwritten note'}.get(mode, 'Item')
|
564
|
669 for toc in tocs:
|
|
670 pageurl = self.getLink('pn', toc['pn'])
|
|
671 tp += '<div class="tocline">'
|
568
|
672 content = toc['content']
|
609
|
673 lvs = toc['level-string']
|
568
|
674 if content:
|
609
|
675 tp += '<div class="toc name">[%s] %s</div>'%(lvs, toc['content'])
|
|
676 elif lvs:
|
|
677 tp += '<div class="toc name">[%s %s]</div>'%(label, lvs)
|
568
|
678 else:
|
609
|
679 tp += '<div class="toc name">[%s]</div>'%(label)
|
568
|
680
|
|
681 if toc.get('no', None):
|
|
682 tp += '<div class="toc page"><a href="%s">Page: %s (%s)</a></div>'%(pageurl, toc['pn'], toc['no'])
|
|
683 else:
|
|
684 tp += '<div class="toc page"><a href="%s">Page: %s</a></div>'%(pageurl, toc['pn'])
|
|
685
|
564
|
686 tp += '</div>\n'
|
|
687
|
|
688 tp += '</div>\n'
|
|
689
|
|
690 return tp
|
|
691
|
|
692
|
|
693 def manage_changeMpiwgXmlTextServer(self,title="",serverUrl="http://mpdl-text.mpiwg-berlin.mpg.de/mpdl/interface/",timeout=40,repositoryType=None,RESPONSE=None):
|
|
694 """change settings"""
|
|
695 self.title=title
|
|
696 self.timeout = timeout
|
|
697 self.serverUrl = serverUrl
|
|
698 if repositoryType:
|
|
699 self.repositoryType = repositoryType
|
|
700 if RESPONSE is not None:
|
|
701 RESPONSE.redirect('manage_main')
|
|
702
|
|
703 # management methods
|
|
704 def manage_addMpiwgXmlTextServerForm(self):
|
|
705 """Form for adding"""
|
|
706 pt = PageTemplateFile("zpt/manage_addMpiwgXmlTextServer", globals()).__of__(self)
|
|
707 return pt()
|
|
708
|
|
709 def manage_addMpiwgXmlTextServer(self,id,title="",serverUrl="http://mpdl-text.mpiwg-berlin.mpg.de/mpdl/interface/",timeout=40,RESPONSE=None):
|
577
|
710 """add MpiwgXmlTextServer"""
|
564
|
711 newObj = MpiwgXmlTextServer(id=id,title=title,serverUrl=serverUrl,timeout=timeout)
|
|
712 self.Destination()._setObject(id, newObj)
|
|
713 if RESPONSE is not None:
|
|
714 RESPONSE.redirect('manage_main')
|
|
715
|
|
716 |