source: documentViewer/MpdlXmlTextServer.py @ 517:aaacdf551f6f

Last change on this file since 517:aaacdf551f6f was 517:aaacdf551f6f, checked in by casties, 12 years ago

remove global info from processPageInfo.

File size: 21.3 KB
Line 
1from OFS.SimpleItem import SimpleItem
2from Products.PageTemplates.PageTemplateFile import PageTemplateFile
3
4import xml.etree.ElementTree as ET
5
6import re
7import logging
8import urllib
9import urlparse
10import base64
11
12from SrvTxtUtils import getInt, getText, getHttpData
13
14def serialize(node):
15    """returns a string containing an XML snippet of node"""
16    s = ET.tostring(node, 'UTF-8')
17    # snip off XML declaration
18    if s.startswith('<?xml'):
19        i = s.find('?>')
20        return s[i+3:]
21
22    return s
23
24
25class MpdlXmlTextServer(SimpleItem):
26    """TextServer implementation for MPDL-XML eXist server"""
27    meta_type="MPDL-XML TextServer"
28
29    manage_options=(
30        {'label':'Config','action':'manage_changeMpdlXmlTextServerForm'},
31       )+SimpleItem.manage_options
32   
33    manage_changeMpdlXmlTextServerForm = PageTemplateFile("zpt/manage_changeMpdlXmlTextServer", globals())
34       
35    def __init__(self,id,title="",serverUrl="http://mpdl-text.mpiwg-berlin.mpg.de/mpdl/interface/", serverName=None, timeout=40):
36        """constructor"""
37        self.id=id
38        self.title=title
39        self.timeout = timeout
40        if serverName is None:
41            self.serverUrl = serverUrl
42        else:
43            self.serverUrl = "http://%s/mpdl/interface/"%serverName
44       
45    def getHttpData(self, url, data=None):
46        """returns result from url+data HTTP request"""
47        return getHttpData(url,data,timeout=self.timeout)
48   
49    def getServerData(self, method, data=None):
50        """returns result from text server for method+data"""
51        url = self.serverUrl+method
52        return getHttpData(url,data,timeout=self.timeout)
53
54
55    def getPlacesOnPage(self, docinfo=None, pn=None):
56        """Returns list of GIS places of page pn"""
57        docpath = docinfo.get('textURLPath',None)
58        if not docpath:
59            return None
60
61        places=[]
62        text=self.getServerData("xpath.xql", "document=%s&xpath=//place&pn=%s"%(docpath,pn))
63        dom = ET.fromstring(text)
64        result = dom.findall(".//resultPage/place")
65        for l in result:
66            id = l.get("id")
67            name = l.text
68            place = {'id': id, 'name': name}
69            places.append(place)
70
71        return places
72   
73         
74    def getTextInfo(self, mode='', docinfo=None):
75        """reads document info, including page concordance, from text server"""
76        logging.debug("getDocInfo")
77        #TODO: check cached info
78        docpath = docinfo.get('textURLPath', None)
79        if docpath is None:
80            logging.error("getTextInfo: no textURLPath!")
81            return docinfo
82               
83        # we need to set a result set size
84        pagesize = 10000
85        pn = 1
86        # fetch docinfo
87        pagexml = self.getServerData("doc-info.xql","document=%s&info=%s&pageSize=%s&pn=%s"%(docpath,mode,pagesize,pn))
88        dom = ET.fromstring(pagexml)
89        # all info in tag <document>
90        doc = dom.find("document")
91        if doc is None:
92            logging.error("getTextInfo: unable to find document-tag!")
93        else:
94            # go through all child elements
95            for tag in doc:
96                name = tag.tag
97                # numTextPages
98                if name == 'countPages':
99                    np = getInt(tag.text)                   
100                    if np > 0:
101                        docinfo['numTextPages'] = np
102                   
103                # numFigureEntries
104                elif name == 'countFigureEntries':
105                    docinfo['numFigureEntries'] = getInt(tag.text)
106                   
107                # numTocEntries
108                elif name == 'countTocEntries':
109                    # WTF: s1 = int(s)/30+1
110                    docinfo['numTocEntries'] = getInt(tag.text)
111                   
112                # numPlaces
113                elif name == 'countPlaces':
114                    docinfo['numPlaces'] = getInt(tag.text)
115                   
116                # pageNumbers
117                elif name == 'pageNumbers':
118                    # contains tags with page numbers
119                    # <pn><n>4</n><no>4</no><non/></pn>
120                    # n=scan number, no=original page no, non=normalized original page no
121                    # pageNumbers is a dict indexed by scan number
122                    pages = {}
123                    for pn in tag:
124                        page = {}
125                        n = 0
126                        for p in pn:
127                            if p.tag == 'n':
128                                n = getInt(p.text)
129                                page['n'] = n
130                            elif p.tag == 'no':
131                                page['no'] = p.text
132                            elif p.tag == 'non':
133                                page['non'] = p.text
134                               
135                        if n > 0:
136                            pages[n] = page
137                       
138                    docinfo['pageNumbers'] = pages
139                    #logging.debug("got pageNumbers=%s"%repr(pages))
140                               
141                # toc
142                elif name == 'toc':
143                    # contains tags with table of contents
144                    # TODO: implement
145                    pass
146
147        return docinfo
148       
149         
150    def processPageInfo(self, dom, docinfo, pageinfo):
151        """processes page info divs from dom and stores in docinfo and pageinfo"""
152        # assume first second level div is pageMeta
153        alldivs = dom.find("div")
154       
155        if alldivs is None or alldivs.get('class', '') != 'pageMeta':
156            logging.error("processPageInfo: pageMeta div not found!")
157            return
158       
159        for div in alldivs:
160            dc = div.get('class')
161           
162            # pageNumberOrig 
163            if dc == 'pageNumberOrig':
164                pageinfo['pageNumberOrig'] = div.text
165               
166            # pageNumberOrigNorm
167            elif dc == 'pageNumberOrigNorm':
168                pageinfo['pageNumberOrigNorm'] = div.text
169               
170            # pageHeaderTitle
171            elif dc == 'pageHeaderTitle':
172                pageinfo['pageHeaderTitle'] = div.text
173                       
174        #logging.debug("processPageInfo: pageinfo=%s"%repr(pageinfo))
175        return
176         
177           
178    def getTextPage(self, mode="text", pn=1, docinfo=None, pageinfo=None):
179        """returns single page from fulltext"""
180       
181        logging.debug("getTextPage mode=%s, pn=%s"%(mode,pn))
182        # check for cached text -- but ideally this shouldn't be called twice
183        if pageinfo.has_key('textPage'):
184            logging.debug("getTextPage: using cached text")
185            return pageinfo['textPage']
186       
187        docpath = docinfo['textURLPath']
188        # just checking
189        if pageinfo['current'] != pn:
190            logging.warning("getTextPage: current!=pn!")
191           
192        # stuff for constructing full urls
193        selfurl = docinfo['viewerUrl']
194        textParams = {'document': docpath,
195                      'pn': pn}
196        if 'characterNormalization' in pageinfo:
197            textParams['characterNormalization'] = pageinfo['characterNormalization']
198       
199        if not mode:
200            # default is dict
201            mode = 'text'
202
203        modes = mode.split(',')
204        # check for multiple layers
205        if len(modes) > 1:
206            logging.debug("getTextPage: more than one mode=%s"%mode)
207           
208        # search mode
209        if 'search' in modes:
210            # add highlighting
211            highlightQuery = pageinfo.get('highlightQuery', None)
212            if highlightQuery:
213                textParams['highlightQuery'] = highlightQuery
214                textParams['highlightElement'] = pageinfo.get('highlightElement', '')
215                textParams['highlightElementPos'] = pageinfo.get('highlightElementPos', '')
216               
217            # ignore mode in the following
218            modes.remove('search')
219                           
220        # other modes don't combine
221        if 'dict' in modes:
222            # dict is called textPollux in the backend
223            textmode = 'textPollux'
224        elif len(modes) == 0:
225            # text is default mode
226            textmode = 'text'
227        else:
228            # just take first mode
229            textmode = modes[0]
230       
231        textParams['mode'] = textmode
232       
233        # fetch the page
234        pagexml = self.getServerData("page-fragment.xql",urllib.urlencode(textParams))
235        dom = ET.fromstring(pagexml)
236        # extract additional info
237        self.processPageInfo(dom, docinfo, pageinfo)
238        # page content is in <div class="pageContent">
239        pagediv = None
240        # ElementTree 1.2 in Python 2.6 can't do div[@class='pageContent']
241        # so we look at the second level divs
242        alldivs = dom.findall("div")
243        for div in alldivs:
244            dc = div.get('class')
245            # page content div
246            if dc == 'pageContent':
247                pagediv = div
248                break
249       
250        # plain text mode
251        if textmode == "text":
252            # get full url assuming documentViewer is parent
253            selfurl = self.getLink()
254            if pagediv is not None:
255                links = pagediv.findall(".//a")
256                for l in links:
257                    href = l.get('href')
258                    if href and href.startswith('#note-'):
259                        href = href.replace('#note-',"%s#note-"%selfurl)
260                        l.set('href', href)
261
262                return serialize(pagediv)
263           
264        # text-with-links mode
265        elif textmode == "textPollux":
266            if pagediv is not None:
267                viewerurl = docinfo['viewerUrl']
268                selfurl = self.getLink()
269                # check all a-tags
270                links = pagediv.findall(".//a")
271                for l in links:
272                    href = l.get('href')
273                   
274                    if href:
275                        # is link with href
276                        linkurl = urlparse.urlparse(href)
277                        #logging.debug("getTextPage: linkurl=%s"%repr(linkurl))
278                        if linkurl.path.endswith('GetDictionaryEntries'):
279                            #TODO: replace wordInfo page
280                            # is dictionary link - change href (keeping parameters)
281                            #l.set('href', href.replace('http://mpdl-proto.mpiwg-berlin.mpg.de/mpdl/interface/lt/wordInfo.xql','%s/template/viewer_wordinfo'%viewerurl))
282                            # add target to open new page
283                            l.set('target', '_blank')
284                                                         
285                        # TODO: is this needed?
286#                        if href.startswith('http://mpdl-proto.mpiwg-berlin.mpg.de/mpdl/lt/lemma.xql'):
287#                            selfurl = self.absolute_url()
288#                            l.set('href', href.replace('http://mpdl-proto.mpiwg-berlin.mpg.de/mpdl/lt/lemma.xql','%s/head_main_lemma'%selfurl))
289#                            l.set('target', '_blank')
290#                            l.set('onclick',"popupWin = window.open(this.href, 'InfoWindow', 'menubar=no, location,width=500,height=600,top=180, left=700, toolbar=no, scrollbars=1'); return false;")
291#                            l.set('ondblclick', 'popupWin.focus();')   
292                   
293                        if href.startswith('#note-'):
294                            # note link
295                            l.set('href', href.replace('#note-',"%s#note-"%selfurl))
296                             
297                return serialize(pagediv)
298           
299        # xml mode
300        elif textmode == "xml":
301            if pagediv is not None:
302                return serialize(pagediv)
303           
304        # pureXml mode
305        elif textmode == "pureXml":
306            if pagediv is not None:
307                return serialize(pagediv)
308                 
309        # gis mode
310        elif textmode == "gis":
311            if pagediv is not None:
312                # check all a-tags
313                links = pagediv.findall(".//a")
314                # add our URL as backlink
315                selfurl = self.getLink()
316                doc = base64.b64encode(selfurl)
317                for l in links:
318                    href = l.get('href')
319                    if href:
320                        if href.startswith('http://mappit.mpiwg-berlin.mpg.de'):
321                            l.set('href', re.sub(r'doc=[\w+/=]+', 'doc=%s'%doc, href))
322                            l.set('target', '_blank')
323                           
324                return serialize(pagediv)
325                   
326        return None
327   
328
329    def getSearchResults(self, mode, query=None, pageinfo=None, docinfo=None):
330        """loads list of search results and stores XML in docinfo"""
331       
332        logging.debug("getSearchResults mode=%s query=%s"%(mode, query))
333        if mode == "none":
334            return docinfo
335             
336        cachedQuery = docinfo.get('cachedQuery', None)
337        if cachedQuery is not None:
338            # cached search result
339            if cachedQuery == '%s_%s'%(mode,query):
340                # same query
341                return docinfo
342           
343            else:
344                # different query
345                del docinfo['resultSize']
346                del docinfo['resultXML']
347       
348        # cache query
349        docinfo['cachedQuery'] = '%s_%s'%(mode,query)
350       
351        # fetch full results
352        docpath = docinfo['textURLPath']
353        params = {'document': docpath,
354                  'mode': 'text',
355                  'queryType': mode,
356                  'query': query,
357                  'queryResultPageSize': 1000,
358                  'queryResultPN': 1,
359                  'characterNormalization': pageinfo.get('characterNormalization', 'reg')}
360        pagexml = self.getServerData("doc-query.xql",urllib.urlencode(params))
361        #pagexml = self.getServerData("doc-query.xql","document=%s&mode=%s&queryType=%s&query=%s&queryResultPageSize=%s&queryResultPN=%s&s=%s&viewMode=%s&characterNormalization=%s&highlightElementPos=%s&highlightElement=%s&highlightQuery=%s"%(docpath, 'text', queryType, urllib.quote(query), pagesize, pn, s, viewMode,characterNormalization, highlightElementPos, highlightElement, urllib.quote(highlightQuery)))
362        dom = ET.fromstring(pagexml)
363        # page content is in <div class="queryResultPage">
364        pagediv = None
365        # ElementTree 1.2 in Python 2.6 can't do div[@class='queryResultPage']
366        alldivs = dom.findall("div")
367        for div in alldivs:
368            dc = div.get('class')
369            # page content div
370            if dc == 'queryResultPage':
371                pagediv = div
372               
373            elif dc == 'queryResultHits':
374                docinfo['resultSize'] = getInt(div.text)
375
376        if pagediv is not None:
377            # store XML in docinfo
378            docinfo['resultXML'] = ET.tostring(pagediv, 'UTF-8')
379
380        return docinfo
381   
382
383    def getResultsPage(self, mode="text", query=None, pn=None, start=None, size=None, pageinfo=None, docinfo=None):
384        """returns single page from the table of contents"""
385        logging.debug("getResultsPage mode=%s, pn=%s"%(mode,pn))
386        # get (cached) result
387        self.getSearchResults(mode=mode, query=query, pageinfo=pageinfo, docinfo=docinfo)
388           
389        resultxml = docinfo.get('resultXML', None)
390        if not resultxml:
391            logging.error("getResultPage: unable to find resultXML")
392            return "Error: no result!"
393       
394        if size is None:
395            size = pageinfo.get('resultPageSize', 10)
396           
397        if start is None:
398            start = (pn - 1) * size
399
400        fullresult = ET.fromstring(resultxml)
401       
402        if fullresult is not None:
403            # paginate
404            first = start-1
405            len = size
406            del fullresult[:first]
407            del fullresult[len:]
408            tocdivs = fullresult
409           
410            # check all a-tags
411            links = tocdivs.findall(".//a")
412            for l in links:
413                href = l.get('href')
414                if href:
415                    # assume all links go to pages
416                    linkUrl = urlparse.urlparse(href)
417                    linkParams = urlparse.parse_qs(linkUrl.query)
418                    # take some parameters
419                    params = {'pn': linkParams['pn'],
420                              'highlightQuery': linkParams.get('highlightQuery',''),
421                              'highlightElement': linkParams.get('highlightElement',''),
422                              'highlightElementPos': linkParams.get('highlightElementPos','')
423                              }
424                    url = self.getLink(params=params)
425                    l.set('href', url)
426                       
427            return serialize(tocdivs)
428       
429        return "ERROR: no results!"
430
431
432    def getToc(self, mode="text", docinfo=None):
433        """loads table of contents and stores XML in docinfo"""
434        logging.debug("getToc mode=%s"%mode)
435        if mode == "none":
436            return docinfo
437             
438        if 'tocSize_%s'%mode in docinfo:
439            # cached toc
440            return docinfo
441       
442        docpath = docinfo['textURLPath']
443        # we need to set a result set size
444        pagesize = 1000
445        pn = 1
446        if mode == "text":
447            queryType = "toc"
448        else:
449            queryType = mode
450        # number of entries in toc
451        tocSize = 0
452        tocDiv = None
453        # fetch full toc
454        pagexml = self.getServerData("doc-query.xql","document=%s&queryType=%s&queryResultPageSize=%s&queryResultPN=%s"%(docpath,queryType, pagesize, pn))
455        dom = ET.fromstring(pagexml)
456        # page content is in <div class="queryResultPage">
457        pagediv = None
458        # ElementTree 1.2 in Python 2.6 can't do div[@class='queryResultPage']
459        alldivs = dom.findall("div")
460        for div in alldivs:
461            dc = div.get('class')
462            # page content div
463            if dc == 'queryResultPage':
464                pagediv = div
465               
466            elif dc == 'queryResultHits':
467                docinfo['tocSize_%s'%mode] = getInt(div.text)
468
469        if pagediv is not None:
470            # store XML in docinfo
471            docinfo['tocXML_%s'%mode] = ET.tostring(pagediv, 'UTF-8')
472
473        return docinfo
474   
475    def getTocPage(self, mode="text", pn=None, start=None, size=None, pageinfo=None, docinfo=None):
476        """returns single page from the table of contents"""
477        logging.debug("getTocPage mode=%s, pn=%s"%(mode,pn))
478        if mode == "text":
479            queryType = "toc"
480        else:
481            queryType = mode
482           
483        # check for cached TOC
484        if not docinfo.has_key('tocXML_%s'%mode):
485            self.getToc(mode=mode, docinfo=docinfo)
486           
487        tocxml = docinfo.get('tocXML_%s'%mode, None)
488        if not tocxml:
489            logging.error("getTocPage: unable to find tocXML")
490            return "Error: no table of contents!"
491       
492        if size is None:
493            size = pageinfo.get('tocPageSize', 30)
494           
495        if start is None:
496            start = (pn - 1) * size
497
498        fulltoc = ET.fromstring(tocxml)
499       
500        if fulltoc is not None:
501            # paginate
502            first = (start - 1) * 2
503            len = size * 2
504            del fulltoc[:first]
505            del fulltoc[len:]
506            tocdivs = fulltoc
507           
508            # check all a-tags
509            links = tocdivs.findall(".//a")
510            for l in links:
511                href = l.get('href')
512                if href:
513                    # take pn from href
514                    m = re.match(r'page-fragment\.xql.*pn=(\d+)', href)
515                    if m is not None:
516                        # and create new url (assuming parent is documentViewer)
517                        url = self.getLink('pn', m.group(1))
518                        l.set('href', url)
519                    else:
520                        logging.warning("getTocPage: Problem with link=%s"%href)
521                       
522            # fix two-divs-per-row with containing div
523            newtoc = ET.Element('div', {'class':'queryResultPage'})
524            for (d1,d2) in zip(tocdivs[::2],tocdivs[1::2]):
525                e = ET.Element('div',{'class':'tocline'})
526                e.append(d1)
527                e.append(d2)
528                newtoc.append(e)
529               
530            return serialize(newtoc)
531       
532        return "ERROR: no table of contents!"
533   
534   
535    def manage_changeMpdlXmlTextServer(self,title="",serverUrl="http://mpdl-text.mpiwg-berlin.mpg.de/mpdl/interface/",timeout=40,RESPONSE=None):
536        """change settings"""
537        self.title=title
538        self.timeout = timeout
539        self.serverUrl = serverUrl
540        if RESPONSE is not None:
541            RESPONSE.redirect('manage_main')
542       
543# management methods
544def manage_addMpdlXmlTextServerForm(self):
545    """Form for adding"""
546    pt = PageTemplateFile("zpt/manage_addMpdlXmlTextServer", globals()).__of__(self)
547    return pt()
548
549def manage_addMpdlXmlTextServer(self,id,title="",serverUrl="http://mpdl-text.mpiwg-berlin.mpg.de/mpdl/interface/",timeout=40,RESPONSE=None):
550#def manage_addMpdlXmlTextServer(self,id,title="",serverUrl="http://mpdl-text.mpiwg-berlin.mpg.de:30030/mpdl/interface/",timeout=40,RESPONSE=None):   
551    """add zogiimage"""
552    newObj = MpdlXmlTextServer(id,title,serverUrl,timeout)
553    self.Destination()._setObject(id, newObj)
554    if RESPONSE is not None:
555        RESPONSE.redirect('manage_main')
556       
557       
Note: See TracBrowser for help on using the repository browser.