source: documentViewer/MpdlXmlTextServer.py @ 197:9226f1b456eb

Last change on this file since 197:9226f1b456eb was 197:9226f1b456eb, checked in by abukhman, 14 years ago

* empty log message *

File size: 19.1 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        xquery = '//pb'
127        text = self.getServerData("xquery.xql","document=%s&xquery=%s"%(docinfo['textURLPath'],xquery))
128        docinfo['numPages'] = text.count("<pb ")
129        return docinfo
130     
131    def getNumTextPages (self, docinfo):
132        """get list of pages from fulltext (texts without images) and put in docinfo"""
133        if 'numPages' in docinfo:
134            # allredy there
135            return docinfo
136        xpath ='/count(//pb)'
137        text=self.getServerData("xpath.xql", "document=%s&xpath=%s"%(docinfo['textURLPath'], xpath))
138        logging.debug("documentViewer (text) text: %s"%(text))
139        #docinfo['numPages']=text('resultPage')
140        pagedom = Parse(text)
141        docinfo['numPages']= pagedom.xpath("//resultPage")
142        #logging.debug("documentViewer (characterNormalization) docinfo['numPages']: %s"%(docinfo['numPages']))
143        return docinfo
144       
145    def getTextPage(self, mode="text", pn=1, docinfo=None, pageinfo=None, highlightQuery=None,sn=None, viewMode=None, tocMode=None, tocPN=None, characterNormalization=""):
146        """returns single page from fulltext"""
147        docpath = docinfo['textURLPath']
148        path = docinfo['textURLPath']
149        url = docinfo['url']
150        viewMode= pageinfo['viewMode']
151        tocMode = pageinfo['tocMode']
152        characterNormalization=pageinfo['characterNormalization']
153        tocPN = pageinfo['tocPN']
154        selfurl = self.absolute_url()   
155        if mode == "text_dict":
156            textmode = "textPollux"
157        else:
158            textmode = mode
159        #logging.debug("documentViewer (characterNormalization) characterNormalization: %s"%(characterNormalization))
160        textParam = "document=%s&mode=%s&pn=%s&characterNormalization=%s"%(docpath,textmode,pn,characterNormalization)
161        if highlightQuery is not None:
162            textParam +="&highlightQuery=%s&sn=%s"%(urllib.quote(highlightQuery),sn)           
163       
164        pagexml = self.getServerData("page-fragment.xql",textParam)
165        #pagexml=self.template.fulltextclient.eval("/mpdl/interface/page-fragment.xql", textParam, outputUnicode=False)
166       
167        pagedom = Parse(pagexml)
168        # plain text mode
169        if mode == "text":
170            # first div contains text
171            pagedivs = pagedom.xpath("/div")
172            if len(pagedivs) > 0:     
173                pagenode = pagedivs[0]
174                links = pagenode.xpath("//a")
175                for l in links:
176                    hrefNode = l.getAttributeNodeNS(None, u"href")
177                    if hrefNode:
178                        href= hrefNode.nodeValue
179                        if href.startswith('#note-'):
180                            hrefNode.nodeValue = href.replace('#note-',"?url=%s&viewMode=%s&tocMode=%s&tocPN=%s&pn=%s#note-"%(url,viewMode,tocMode,tocPN,pn))
181                return serializeNode(pagenode)
182        if mode == "xml":
183              # first div contains text
184              pagedivs = pagedom.xpath("/div")
185              if len(pagedivs) > 0:
186                  pagenode = pagedivs[0]
187                  return serializeNode(pagenode)
188        if mode == "gis":
189              # first div contains text
190              pagedivs = pagedom.xpath("/div")
191              if len(pagedivs) > 0:
192                  pagenode = pagedivs[0]
193                  links =pagenode.xpath("//a")
194                  for l in links:
195                      hrefNode =l.getAttributeNodeNS(None, u"href")
196                      if hrefNode:
197                          href=hrefNode.nodeValue
198                          if href.startswith('http://chinagis.mpiwg-berlin.mpg.de'):
199                              hrefNode.nodeValue =href.replace('chinagis_REST','chinagis')
200                              l.setAttributeNS(None, 'target', '_blank')
201                  return serializeNode(pagenode)
202                   
203        if mode == "pureXml":
204              # first div contains text
205              pagedivs = pagedom.xpath("/div")
206              if len(pagedivs) > 0:
207                  pagenode = pagedivs[0]
208                  return serializeNode(pagenode)     
209        # text-with-links mode
210        if mode == "text_dict":
211            # first div contains text
212            pagedivs = pagedom.xpath("/div")
213            if len(pagedivs) > 0:
214                pagenode = pagedivs[0]
215                # check all a-tags
216                links = pagenode.xpath("//a")
217                for l in links:
218                    hrefNode = l.getAttributeNodeNS(None, u"href")
219                    if hrefNode:
220                        # is link with href
221                        href = hrefNode.nodeValue
222                        if href.startswith('lt/lex.xql'):
223                            # is pollux link
224                            selfurl = self.absolute_url()
225                            # change href
226                            hrefNode.nodeValue = href.replace('lt/lex.xql','%s/template/head_main_voc'%selfurl)
227                            # add target
228                            l.setAttributeNS(None, 'target', '_blank')
229                            l.setAttributeNS(None, 'onClick',"popupWin = window.open(this.href, 'contacts', 'location,width=500,height=600,top=180, left=700, scrollbars=1'); return false;")
230                            l.setAttributeNS(None, 'onClick', 'popupWin.focus();')     
231                        if href.startswith('lt/lemma.xql'):   
232                            selfurl = self.absolute_url()
233                            hrefNode.nodeValue = href.replace('lt/lemma.xql','%s/template/head_main_lemma'%selfurl)
234                            l.setAttributeNS(None, 'target', '_blank')
235                            l.setAttributeNS(None, 'onClick',"popupWin = window.open(this.href, 'contacts', 'location,width=500,height=600,top=180, left=700, scrollbars=1'); return false;")
236                            l.setAttributeNS(None, 'onClick', 'popupWin.focus();')   
237                        if href.startswith('#note-'):
238                            hrefNode.nodeValue = href.replace('#note-',"?url=%s&viewMode=%s&tocMode=%s&tocPN=%s&pn=%s#note-"%(url,viewMode,tocMode,tocPN,pn))   
239                return serializeNode(pagenode)
240        return "no text here"
241
242    def getTranslate(self, query=None, language=None):
243        """translate into another languages"""
244        data = self.getServerData("lt/lex.xql","document=&language="+str(language)+"&query="+urllib.quote(query))
245        #pagexml=self.template.fulltextclient.eval("/mpdl/interface/lt/lex.xql","document=&language="+str(language)+"&query="+url_quote(str(query)))
246        return data
247   
248    def getLemma(self, lemma=None, language=None):
249        """simular words lemma """
250        data = self.getServerData("lt/lemma.xql","document=&language="+str(language)+"&lemma="+urllib.quote(lemma))
251        #pagexml=self.template.fulltextclient.eval("/mpdl/interface/lt/lemma.xql","document=&language="+str(language)+"&lemma="+url_quote(str(lemma)))
252        return data
253   
254    def getLemmaNew(self, query=None, language=None):
255        """simular words lemma """
256        data = self.getServerData("lt/lemma.xql","document=&language="+str(language)+"&lemma="+urllib.quote(query))
257        #pagexml=self.template.fulltextclient.eval("/mpdl/interface/lt/lemma.xql","document=&language="+str(language)+"&lemma="+url_quote(str(query)))
258        return data
259   
260    def getQuery (self,  docinfo=None, pageinfo=None, query=None, queryType=None, pn=1):
261         """number of"""
262         docpath = docinfo['textURLPath'] 
263         pagesize = pageinfo['queryPageSize']
264         pn = pageinfo['searchPN']
265         query =pageinfo['query']
266         queryType =pageinfo['queryType']
267         tocSearch = 0
268         tocDiv = None
269         
270         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))
271         #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)
272         pagedom = Parse(pagexml)
273         numdivs = pagedom.xpath("//div[@class='queryResultHits']")
274         tocSearch = int(getTextFromNode(numdivs[0]))
275         tc=int((tocSearch/10)+1)
276         logging.debug("documentViewer (gettoc) tc: %s"%(tc))
277         return tc
278
279    def getToc(self, mode="text", docinfo=None):
280        """loads table of contents and stores in docinfo"""
281        logging.debug("documentViewer (gettoc) mode: %s"%(mode))
282        if mode == "none":
283            return docinfo       
284        if 'tocSize_%s'%mode in docinfo:
285            # cached toc
286            return docinfo
287       
288        docpath = docinfo['textURLPath']
289        # we need to set a result set size
290        pagesize = 1000
291        pn = 1
292        if mode == "text":
293            queryType = "toc"
294        else:
295            queryType = mode
296        # number of entries in toc
297        tocSize = 0
298        tocDiv = None
299       
300        pagexml = self.getServerData("doc-query.xql","document=%s&queryType=%s&queryResultPageSize=%s&queryResultPN=%s"%(docpath,queryType, pagesize, pn))
301        #pagexml=self.template.fulltextclient.eval("/mpdl/interface/doc-query.xql", "document=%s&queryType=%s&queryResultPageSize=%s&queryResultPN=%s"%(docpath,queryType,pagesize,pn), outputUnicode=False)
302        # post-processing downloaded xml
303        pagedom = Parse(pagexml)
304        # get number of entries
305        numdivs = pagedom.xpath("//div[@class='queryResultHits']")
306        if len(numdivs) > 0:
307            tocSize = int(getTextFromNode(numdivs[0]))
308        docinfo['tocSize_%s'%mode] = tocSize
309        return docinfo
310   
311    def getTocPage(self, mode="text", pn=1, pageinfo=None, docinfo=None):
312        """returns single page from the table of contents"""
313        # TODO: this should use the cached TOC
314        if mode == "text":
315            queryType = "toc"
316        else:
317            queryType = mode
318        docpath = docinfo['textURLPath']
319        path = docinfo['textURLPath']       
320        pagesize = pageinfo['tocPageSize']
321        pn = pageinfo['tocPN']
322        url = docinfo['url']
323        selfurl = self.absolute_url() 
324        viewMode=  pageinfo['viewMode']
325        characterNormalization = pageinfo ['characterNormalization']
326        tocMode = pageinfo['tocMode']
327        tocPN = pageinfo['tocPN'] 
328       
329        data = self.getServerData("doc-query.xql","document=%s&queryType=%s&queryResultPageSize=%s&queryResultPN=%s&characterNormalization=%s"%(docpath,queryType, pagesize, pn,characterNormalization)) 
330        page = data.replace('page-fragment.xql?document=%s'%str(path),'%s?url=%s&viewMode=%s&tocMode=%s&tocPN=%s'%(selfurl,url, viewMode, tocMode, tocPN))
331        text = page.replace('mode=image','mode=texttool')
332        logging.debug("documentViewer (characterNormalization) characterNormalization: %s"%(characterNormalization))
333        #logging.debug("documentViewer (characterNormalization) text: %s"%(text))
334        return text
335   
336    def manage_changeMpdlXmlTextServer(self,title="",serverUrl="http://mpdl-proto.mpiwg-berlin.mpg.de/mpdl/interface/",timeout=40,RESPONSE=None):
337        """change settings"""
338        self.title=title
339        self.timeout = timeout
340        self.serverUrl = serverUrl
341        if RESPONSE is not None:
342            RESPONSE.redirect('manage_main')
343       
344# management methods
345def manage_addMpdlXmlTextServerForm(self):
346    """Form for adding"""
347    pt = PageTemplateFile("zpt/manage_addMpdlXmlTextServer", globals()).__of__(self)
348    return pt()
349
350def manage_addMpdlXmlTextServer(self,id,title="",serverUrl="http://mpdl-proto.mpiwg-berlin.mpg.de/mpdl/interface/",timeout=40,RESPONSE=None):
351    """add zogiimage"""
352    newObj = MpdlXmlTextServer(id,title,serverUrl,timeout)
353    self.Destination()._setObject(id, newObj)
354    if RESPONSE is not None:
355        RESPONSE.redirect('manage_main')
356
357
358   
Note: See TracBrowser for help on using the repository browser.