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