source: documentViewer/MpdlXmlTextServer.py @ 188:a7610241ae57

Last change on this file since 188:a7610241ae57 was 188:a7610241ae57, checked in by abukhman, 14 years ago

* empty log message *

File size: 18.5 KB
Line 
1
2from OFS.SimpleItem import SimpleItem
3from Products.PageTemplates.PageTemplateFile import PageTemplateFile
4from Ft.Xml import EMPTY_NAMESPACE, Parse
5
6import sys
7import logging
8import urllib
9import documentViewer
10from documentViewer import getTextFromNode, serializeNode
11
12class MpdlXmlTextServer(SimpleItem):
13    """TextServer implementation for MPDL-XML eXist server"""
14    meta_type="MPDL-XML TextServer"
15
16    manage_options=(
17        {'label':'Config','action':'manage_changeMpdlXmlTextServerForm'},
18       )+SimpleItem.manage_options
19   
20    manage_changeMpdlXmlTextServerForm = PageTemplateFile("zpt/manage_changeMpdlXmlTextServer", globals())
21       
22    def __init__(self,id,title="",serverUrl="http://mpdl-proto.mpiwg-berlin.mpg.de/mpdl/interface/", serverName=None, timeout=40):
23        """constructor"""
24        self.id=id
25        self.title=title
26        self.timeout = timeout
27        if serverName is None:
28            self.serverUrl = serverUrl
29        else:
30            self.serverUrl = "http://%s/mpdl/interface/"%serverName
31       
32    def getHttpData(self, url, data=None):
33        """returns result from url+data HTTP request"""
34        return documentViewer.getHttpData(url,data,timeout=self.timeout)
35   
36    def getServerData(self, method, data=None):
37        """returns result from text server for method+data"""
38        url = self.serverUrl+method
39        return documentViewer.getHttpData(url,data,timeout=self.timeout)
40
41    def getSearch(self, pn=1, pageinfo=None,  docinfo=None, query=None, queryType=None, lemma=None):
42        """get search list"""
43        docpath = docinfo['textURLPath'] 
44        url = docinfo['url']
45        logging.debug("documentViewer (gettoc) docpath: %s"%(docpath))
46        logging.debug("documentViewer (gettoc) url: %s"%(url))
47        pagesize = pageinfo['queryPageSize']
48        pn = pageinfo['searchPN']
49        sn = pageinfo['sn']
50        highlightQuery = pageinfo['highlightQuery']
51        query =pageinfo['query']
52        queryType =pageinfo['queryType']
53        viewMode=  pageinfo['viewMode']
54        tocMode = pageinfo['tocMode']
55        characterNormalization = pageinfo['characterNormalization']
56        tocPN = pageinfo['tocPN']
57        selfurl = self.absolute_url()
58       
59        data = self.getServerData("doc-query.xql","document=%s&mode=%s&queryType=%s&query=%s&queryResultPageSize=%s&queryResultPN=%s&sn=%s&viewMode=%s&highlightQuery=%s"%(docpath, 'text', queryType, urllib.quote(query), pagesize, pn, sn, viewMode,urllib.quote(highlightQuery)))
60        #page=self.template.fulltextclient.eval("/mpdl/interface/doc-query.xql","document=%s&mode=%s&queryType=%s&query=%s&queryResultPageSize=%s&queryResultPN=%s&sn=%s&viewMode=%s&highlightQuery=%s"%(docpath, 'text', queryType, query, pagesize, pn, sn, viewMode,highlightQuery) ,outputUnicode=False)               
61       
62        pagexml = data.replace('?document=%s'%str(docpath),'?url=%s'%url)
63        pagedom = Parse(pagexml)
64        if (queryType=="fulltext")or(queryType=="xpath")or(queryType=="xquery")or(queryType=="fulltextMorphLemma"):   
65            pagedivs = pagedom.xpath("//div[@class='queryResultPage']")
66            if len(pagedivs)>0:
67                pagenode=pagedivs[0]
68                links=pagenode.xpath("//a")
69                for l in links:
70                    hrefNode = l.getAttributeNodeNS(None, u"href")
71                    if hrefNode:
72                        href = hrefNode.nodeValue
73                        if href.startswith('page-fragment.xql'):
74                            selfurl = self.absolute_url()           
75                            pagexml=href.replace('mode=text','mode=texttool&viewMode=%s&queryType=%s&query=%s&queryResultPageSize=%s&queryResultPN=%s&tocMode=%s&searchPN=%s&tocPN=%s'%(viewMode,queryType,urllib.quote(query),pagesize,pn,tocMode,pn,tocPN))
76                            hrefNode.nodeValue = pagexml.replace('page-fragment.xql','%s'%selfurl)                                           
77                return serializeNode(pagenode)       
78        if (queryType=="fulltextMorph"):
79            pagedivs = pagedom.xpath("//div[@class='queryResult']")
80            if len(pagedivs)>0:
81                pagenode=pagedivs[0]
82                links=pagenode.xpath("//a")
83                for l in links:
84                    hrefNode = l.getAttributeNodeNS(None, u"href")
85                    if hrefNode:
86                        href = hrefNode.nodeValue
87                        if href.startswith('page-fragment.xql'):
88                            selfurl = self.absolute_url()       
89                            pagexml=href.replace('mode=text','mode=texttool&viewMode=%s&queryType=%s&query=%s&queryResultPageSize=%s&queryResultPN=%s&tocMode=%s&searchPN=%s&tocPN=%s'%(viewMode,queryType,urllib.quote(query),pagesize,pn,tocMode,pn,tocPN))
90                            hrefNode.nodeValue = pagexml.replace('page-fragment.xql','%s'%selfurl) 
91                        if href.startswith('../lt/lemma.xql'):
92                            hrefNode.nodeValue = href.replace('../lt/lemma.xql','%s/template/head_main_lemma_New'%(selfurl))       
93                            l.setAttributeNS(None, 'target', '_blank')
94                            l.setAttributeNS(None, 'onClick',"popupWin = window.open(this.href, 'contacts', 'location,width=500,height=600,top=180, left=400, scrollbars=1'); return false;")
95                            l.setAttributeNS(None, 'onClick', 'popupWin.focus();') 
96                pagedivs = pagedom.xpath("//div[@class='queryResultMorphExpansion']")               
97                return serializeNode(pagenode)       
98        if (queryType=="ftIndex")or(queryType=="ftIndexMorph"):
99            pagedivs= pagedom.xpath("//div[@class='queryResultPage']")
100            if len(pagedivs)>0:
101                pagenode=pagedivs[0]
102                links=pagenode.xpath("//a")
103                for l in links:
104                    hrefNode = l.getAttributeNodeNS(None, u"href")
105                    if hrefNode:
106                        href = hrefNode.nodeValue
107                        hrefNode.nodeValue=href.replace('mode=text','mode=texttool&viewMode=%s&tocMode=%s&tocPN=%s&pn=%s'%(viewMode,tocMode,tocPN,pn))             
108                        if href.startswith('../lt/lex.xql'):
109                            hrefNode.nodeValue = href.replace('../lt/lex.xql','%s/template/head_main_voc'%selfurl)         
110                            l.setAttributeNS(None, 'target', '_blank')
111                            l.setAttributeNS(None, 'onClick',"popupWin = window.open(this.href, 'contacts', 'location,width=500,height=600,top=180, left=400, scrollbars=1'); return false;")
112                            l.setAttributeNS(None, 'onClick', 'popupWin.focus();')
113                        if href.startswith('../lt/lemma.xql'):
114                            hrefNode.nodeValue = href.replace('../lt/lemma.xql','%s/template/head_main_lemma'%selfurl)       
115                            l.setAttributeNS(None, 'target', '_blank')
116                            l.setAttributeNS(None, 'onClick',"popupWin = window.open(this.href, 'contacts', 'location,width=500,height=600,top=180, left=400, scrollbars=1'); return false;")
117                            l.setAttributeNS(None, 'onClick', 'popupWin.focus();')
118                return serializeNode(pagenode)     
119        return "no text here"   
120                       
121    def getNumPages(self, docinfo):
122        """get list of pages from fulltext and put in docinfo"""
123        if 'numPages' in docinfo:
124            # already there
125            return docinfo
126       
127        xquery = '//pb'
128        text = self.getServerData("xquery.xql","document=%s&xquery=%s"%(docinfo['textURLPath'],xquery))
129        #text = self.template.fulltextclient.eval("/mpdl/interface/xquery.xql", "document=%s&xquery=%s"%(docinfo['textURLPath'],xquery))
130        docinfo['numPages'] = text.count("<pb ")
131        return docinfo
132       
133    def getTextPage(self, mode="text", pn=1, docinfo=None, pageinfo=None, highlightQuery=None,sn=None, viewMode=None, tocMode=None, tocPN=None, characterNormalization=""):
134        """returns single page from fulltext"""
135        docpath = docinfo['textURLPath']
136        path = docinfo['textURLPath']
137        url = docinfo['url']
138        viewMode= pageinfo['viewMode']
139        tocMode = pageinfo['tocMode']
140        characterNormalization=pageinfo['characterNormalization']
141        tocPN = pageinfo['tocPN']
142        selfurl = self.absolute_url()   
143        if mode == "text_dict":
144            textmode = "textPollux"
145        else:
146            textmode = mode
147        #logging.debug("documentViewer (characterNormalization) characterNormalization: %s"%(characterNormalization))
148        textParam = "document=%s&mode=%s&pn=%s&characterNormalization=%s"%(docpath,textmode,pn,characterNormalization)
149        if highlightQuery is not None:
150            textParam +="&highlightQuery=%s&sn=%s"%(urllib.quote(highlightQuery),sn)           
151       
152        pagexml = self.getServerData("page-fragment.xql",textParam)
153        #pagexml=self.template.fulltextclient.eval("/mpdl/interface/page-fragment.xql", textParam, outputUnicode=False)
154       
155        pagedom = Parse(pagexml)
156        # plain text mode
157        if mode == "text":
158            # first div contains text
159            pagedivs = pagedom.xpath("/div")
160            if len(pagedivs) > 0:     
161                pagenode = pagedivs[0]
162                links = pagenode.xpath("//a")
163                for l in links:
164                    hrefNode = l.getAttributeNodeNS(None, u"href")
165                    if hrefNode:
166                        href= hrefNode.nodeValue
167                        if href.startswith('#note-'):
168                            hrefNode.nodeValue = href.replace('#note-',"?url=%s&viewMode=%s&tocMode=%s&tocPN=%s&pn=%s#note-"%(url,viewMode,tocMode,tocPN,pn))
169                return serializeNode(pagenode)
170        if mode == "xml":
171              # first div contains text
172              pagedivs = pagedom.xpath("/div")
173              if len(pagedivs) > 0:
174                  pagenode = pagedivs[0]
175                  return serializeNode(pagenode)
176        if mode == "gis":
177              # first div contains text
178              pagedivs = pagedom.xpath("/div")
179              if len(pagedivs) > 0:
180                  pagenode = pagedivs[0]
181                  links =pagenode.xpath("//a")
182                  for l in links:
183                      hrefNode =l.getAttributeNodeNS(None, u"href")
184                      if hrefNode:
185                          href=hrefNode.nodeValue
186                          if href.startswith('http://chinagis.mpiwg-berlin.mpg.de'):
187                              hrefNode.nodeValue =href.replace('chinagis_REST','chinagis')
188                  return serializeNode(pagenode)
189                   
190        if mode == "pureXml":
191              # first div contains text
192              pagedivs = pagedom.xpath("/div")
193              if len(pagedivs) > 0:
194                  pagenode = pagedivs[0]
195                  return serializeNode(pagenode)     
196        # text-with-links mode
197        if mode == "text_dict":
198            # first div contains text
199            pagedivs = pagedom.xpath("/div")
200            if len(pagedivs) > 0:
201                pagenode = pagedivs[0]
202                # check all a-tags
203                links = pagenode.xpath("//a")
204                for l in links:
205                    hrefNode = l.getAttributeNodeNS(None, u"href")
206                    if hrefNode:
207                        # is link with href
208                        href = hrefNode.nodeValue
209                        if href.startswith('lt/lex.xql'):
210                            # is pollux link
211                            selfurl = self.absolute_url()
212                            # change href
213                            hrefNode.nodeValue = href.replace('lt/lex.xql','%s/template/head_main_voc'%selfurl)
214                            # add target
215                            l.setAttributeNS(None, 'target', '_blank')
216                            l.setAttributeNS(None, 'onClick',"popupWin = window.open(this.href, 'contacts', 'location,width=500,height=600,top=180, left=700, scrollbars=1'); return false;")
217                            l.setAttributeNS(None, 'onClick', 'popupWin.focus();')     
218                        if href.startswith('lt/lemma.xql'):   
219                            selfurl = self.absolute_url()
220                            hrefNode.nodeValue = href.replace('lt/lemma.xql','%s/template/head_main_lemma'%selfurl)
221                            l.setAttributeNS(None, 'target', '_blank')
222                            l.setAttributeNS(None, 'onClick',"popupWin = window.open(this.href, 'contacts', 'location,width=500,height=600,top=180, left=700, scrollbars=1'); return false;")
223                            l.setAttributeNS(None, 'onClick', 'popupWin.focus();')   
224                        if href.startswith('#note-'):
225                            hrefNode.nodeValue = href.replace('#note-',"?url=%s&viewMode=%s&tocMode=%s&tocPN=%s&pn=%s#note-"%(url,viewMode,tocMode,tocPN,pn))   
226                return serializeNode(pagenode)
227        return "no text here"
228
229    def getTranslate(self, query=None, language=None):
230        """translate into another languages"""
231        data = self.getServerData("lt/lex.xql","document=&language="+str(language)+"&query="+urllib.quote(query))
232        #pagexml=self.template.fulltextclient.eval("/mpdl/interface/lt/lex.xql","document=&language="+str(language)+"&query="+url_quote(str(query)))
233        return data
234   
235    def getLemma(self, lemma=None, language=None):
236        """simular words lemma """
237        data = self.getServerData("lt/lemma.xql","document=&language="+str(language)+"&lemma="+urllib.quote(lemma))
238        #pagexml=self.template.fulltextclient.eval("/mpdl/interface/lt/lemma.xql","document=&language="+str(language)+"&lemma="+url_quote(str(lemma)))
239        return data
240   
241    def getLemmaNew(self, query=None, language=None):
242        """simular words lemma """
243        data = self.getServerData("lt/lemma.xql","document=&language="+str(language)+"&lemma="+urllib.quote(query))
244        #pagexml=self.template.fulltextclient.eval("/mpdl/interface/lt/lemma.xql","document=&language="+str(language)+"&lemma="+url_quote(str(query)))
245        return data
246   
247    def getQuery (self,  docinfo=None, pageinfo=None, query=None, queryType=None, pn=1):
248         """number of"""
249         docpath = docinfo['textURLPath'] 
250         pagesize = pageinfo['queryPageSize']
251         pn = pageinfo['searchPN']
252         query =pageinfo['query']
253         queryType =pageinfo['queryType']
254         tocSearch = 0
255         tocDiv = None
256         
257         pagexml = self.getServerData("doc-query.xql","document=%s&mode=%s&queryType=%s&query=%s&queryResultPageSize=%s&queryResultPN=%s"%(docpath, 'text', queryType, urllib.quote(query), pagesize, pn))
258         #pagexml=self.template.fulltextclient.eval("/mpdl/interface/doc-query.xql","document=%s&mode=%s&queryType=%s&query=%s&queryResultPageSize=%s&queryResultPN=%s"%(docpath, 'text', queryType, query, pagesize, pn) ,outputUnicode=False)
259         pagedom = Parse(pagexml)
260         numdivs = pagedom.xpath("//div[@class='queryResultHits']")
261         tocSearch = int(getTextFromNode(numdivs[0]))
262         tc=int((tocSearch/10)+1)
263         logging.debug("documentViewer (gettoc) tc: %s"%(tc))
264         return tc
265
266    def getToc(self, mode="text", docinfo=None):
267        """loads table of contents and stores in docinfo"""
268        logging.debug("documentViewer (gettoc) mode: %s"%(mode))
269        if mode == "none":
270            return docinfo       
271        if 'tocSize_%s'%mode in docinfo:
272            # cached toc
273            return docinfo
274       
275        docpath = docinfo['textURLPath']
276        # we need to set a result set size
277        pagesize = 1000
278        pn = 1
279        if mode == "text":
280            queryType = "toc"
281        else:
282            queryType = mode
283        # number of entries in toc
284        tocSize = 0
285        tocDiv = None
286       
287        pagexml = self.getServerData("doc-query.xql","document=%s&queryType=%s&queryResultPageSize=%s&queryResultPN=%s"%(docpath,queryType, pagesize, pn))
288        #pagexml=self.template.fulltextclient.eval("/mpdl/interface/doc-query.xql", "document=%s&queryType=%s&queryResultPageSize=%s&queryResultPN=%s"%(docpath,queryType,pagesize,pn), outputUnicode=False)
289        # post-processing downloaded xml
290        pagedom = Parse(pagexml)
291        # get number of entries
292        numdivs = pagedom.xpath("//div[@class='queryResultHits']")
293        if len(numdivs) > 0:
294            tocSize = int(getTextFromNode(numdivs[0]))
295        docinfo['tocSize_%s'%mode] = tocSize
296        return docinfo
297   
298    def getTocPage(self, mode="text", pn=1, pageinfo=None, docinfo=None):
299        """returns single page from the table of contents"""
300        # TODO: this should use the cached TOC
301        if mode == "text":
302            queryType = "toc"
303        else:
304            queryType = mode
305        docpath = docinfo['textURLPath']
306        path = docinfo['textURLPath']       
307        pagesize = pageinfo['tocPageSize']
308        pn = pageinfo['tocPN']
309        url = docinfo['url']
310        selfurl = self.absolute_url() 
311        viewMode=  pageinfo['viewMode']
312        characterNormalization = pageinfo ['characterNormalization']
313        tocMode = pageinfo['tocMode']
314        tocPN = pageinfo['tocPN'] 
315       
316        data = self.getServerData("doc-query.xql","document=%s&queryType=%s&queryResultPageSize=%s&queryResultPN=%s&characterNormalization=%s"%(docpath,queryType, pagesize, pn,characterNormalization)) 
317        page = data.replace('page-fragment.xql?document=%s'%str(path),'%s?url=%s&viewMode=%s&tocMode=%s&tocPN=%s'%(selfurl,url, viewMode, tocMode, tocPN))
318        text = page.replace('mode=image','mode=texttool')
319        logging.debug("documentViewer (characterNormalization) characterNormalization: %s"%(characterNormalization))
320        #logging.debug("documentViewer (characterNormalization) text: %s"%(text))
321        return text
322   
323    def manage_changeMpdlXmlTextServer(self,title="",serverUrl="http://mpdl-proto.mpiwg-berlin.mpg.de/mpdl/interface/",timeout=40,RESPONSE=None):
324        """change settings"""
325        self.title=title
326        self.timeout = timeout
327        self.serverUrl = serverUrl
328        if RESPONSE is not None:
329            RESPONSE.redirect('manage_main')
330       
331# management methods
332def manage_addMpdlXmlTextServerForm(self):
333    """Form for adding"""
334    pt = PageTemplateFile("zpt/manage_addMpdlXmlTextServer", globals()).__of__(self)
335    return pt()
336
337def manage_addMpdlXmlTextServer(self,id,title="",serverUrl="http://mpdl-proto.mpiwg-berlin.mpg.de/mpdl/interface/",timeout=40,RESPONSE=None):
338    """add zogiimage"""
339    newObj = MpdlXmlTextServer(id,title,serverUrl,timeout)
340    self.Destination()._setObject(id, newObj)
341    if RESPONSE is not None:
342        RESPONSE.redirect('manage_main')
343
344
345   
Note: See TracBrowser for help on using the repository browser.