source: TI01-discovery/branches/ingestAutomation-upgrade/OAIBatch/PostgresRecord.py @ 4664

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI01-discovery/branches/ingestAutomation-upgrade/OAIBatch/PostgresRecord.py@4664
Revision 4664, 23.0 KB checked in by cbyrom, 11 years ago (diff)

Update code to reflect refactoring of ndgUtils.

Line 
1#!/usr/bin/env python
2'''
3Class representing the a document to be ingested into the postgres DB table
4C Byrom Apr 08
5'''
6try: #python 2.5
7    from xml.etree import cElementTree
8except ImportError:
9    try:
10        # if you've installed it yourself it comes this way
11        import cElementTree
12    except ImportError:
13        # if you've egged it this is the way it comes
14        from ndgUtils.elementtree import cElementTree
15
16import os, sys, logging, re
17import csml.csml2Moles.molesReadWrite as MRW
18from ndgUtils.ndgObject import ndgObject
19import ndgUtils.lib.fileutilities as FileUtilities
20from SpatioTemporalData import SpatioTemporalData
21import keywordAdder
22
23class PostgresRecord:
24    '''
25    Class representing the a document to be ingested into the postgres DB table
26    @param filename: Name of file to use a metadata record
27    @param ndg_dataprovider
28    @param datacentre_groups
29    @param datacentre_namespace
30    @param discovery_id
31    @param xq
32    @param doctype - type of doc to process
33    '''
34    # TODO MDIP transforms do not work very well for lots of files - so currently hiding these
35    documentTypes = ['MOLES', 'DIF', 'DC', 'ISO19139', 'MDIP']
36   
37    # vocab server - used for finding scope values in the moles files
38    ndg_data_provider_vocab = "http://vocab.ndg.nerc.ac.uk/term/N010"
39       
40    def __init__(self, filename, ndg_dataprovider, datacentre_groups, \
41                 datacentre_namespace, discovery_id, xq, docType):
42        logging.info("Setting up Postgres record for file, " + filename)
43        self.filename = filename
44   
45        # NB, if we're dealing with an NDG data provider, the details are slightly different
46        if ndg_dataprovider:
47            discObj=ndgObject(discovery_id)
48            self._local_id = discObj.localID
49            self._repository_local_id = discObj.repository
50        else:
51            self._local_id = discovery_id
52            self._repository_local_id = datacentre_namespace
53           
54        self._datacentre_groups = datacentre_groups
55        self._repository = datacentre_namespace
56        self.discovery_id = discovery_id
57        self._xq = xq
58        self.docType = docType
59
60        self._molesFormat = None    # initialise this, so we can guarantee a value - to avoid using getattr
61        self._allDocs = []  # array to store all the transformed docs - for easy retrieval by the DAO
62
63        # get the dir of the file - needed by the xquery to use as the target collection
64        tmp = filename.split('/')
65        self._dir = '/'.join(tmp[0:len(tmp)-1])
66        self.shortFilename = tmp[len(tmp)-1]
67       
68        # dir to store a temp copy of the moles file, when produced - for use by other transforms
69        self._molesDir = None
70        # object to hold the moles file - this will be loaded in when it is created - in order to extract
71        # spatiotemporal data, etc
72        self.dgMeta = None
73
74        # firstly load contents of file
75        self.originalFormat = file(filename).read()
76       
77        # escape any apostrophes
78        self.originalFormat = self.escapeSpecialCharacters(self.originalFormat)
79
80        # initialise the various record fields
81        self.db_id = None    # the DB ID of the record, for easy reference when it is created
82        self.molesFormat = None
83        self.dcFormat = None
84        self.mdipFormat = None
85        self.iso19139Format = None
86        self.scn = 1    # system change number - keeps track of number of mods to a particular row
87       
88        # spatiotemporal data object
89        self.stData = None
90       
91        # fields to hold author, parameter and scope data
92        self.authors = None
93        self.parameters = None
94        self.scope = None
95
96    def escapeSpecialCharacters(self, inputString):
97        '''
98        Adjust the input string to escape any characters that would interfere with string or DB
99        operations
100        @param inputString: string to correct
101        @return: corrected string
102        '''
103        return re.sub(r'\'', '\\\'', inputString)
104
105
106    def unescapeSpecialCharacters(self, inputString):
107        '''
108        Adjust the input string to remove escaped characters that would interfere with string or DB
109        operations
110        @param inputString: string to correct
111        @return: corrected string
112        '''
113        str = re.sub(r'%20', ' ', inputString)
114        return 
115   
116   
117    def doRecordTransforms(self):
118        '''
119        Run various transforms on the original doc, to populate the record with
120        the other types of doc used elsewhere
121        '''
122        logging.info("Running transforms for all document types")
123        for docType in self.documentTypes:
124            self.getDocumentFormat(docType)
125           
126        logging.info("Transforms complete")
127
128
129    def createMolesFile(self):
130        '''
131        Check if a moles file exists on the system; if not, assume the moles transform has not
132        been ran and then produce this file - to allow for use in the various xqueries
133        '''
134        logging.info("Creating moles file on system - for use with other xquery transforms")
135        self._molesDir = self._dir + "/moles/"
136        FileUtilities.setUpDir(self._molesDir)
137       
138        if self._molesFormat is None:
139            self.doMolesTransform()
140           
141        FileUtilities.createFile(self._molesDir + self.shortFilename, self._molesFormat)
142        logging.info("Moles file created - at %s" %self._molesDir)
143       
144        # now load this moles file, for use when parsing out spatiotemporal, author and parameters data later on       
145        molesFile = self._molesDir + self.shortFilename
146        logging.info('Retrieving spatiotemporal info from moles file, %s' %molesFile)
147       
148        # load in the moles file and put this into an object for direct access to the xml elements
149        self.dgMeta=MRW.dgMetadata()
150        try:
151            self.dgMeta.fromXML(cElementTree.ElementTree(file=molesFile).getroot())
152        except Exception, detail:
153            raise SystemError, 'Cannot parse the XML moles document %s. Detail:\n%s' %(molesFile, detail)
154
155           
156
157    def doTransform(self, xQueryType):
158        '''
159        Transform the record according to the specified XQuery type
160        @param xQueryType: XQuery doc to use to do the transform
161        @return: the metadata record in the required transformed format
162        '''
163        logging.info("Running XQuery transform, " + xQueryType + " to create transformed document")
164
165        # firstly, check if this is a moles -> something else query; if so, ensure there is a valid
166        # moles file available for the transform - and use the correct dir for the xquery collection
167        dir = self._dir
168        if xQueryType.find('moles2') > -1:
169            if self._molesDir is None:
170                self.createMolesFile()
171               
172            dir = self._molesDir
173           
174        # get the query and set this up to use properly
175        xquery = self._xq.actual(xQueryType, dir, self._repository_local_id, self._local_id)
176
177        # sort out the input ID stuff
178        xquery=xquery.replace('Input_Entry_ID', self.discovery_id)
179        xquery=xquery.replace('repository_localid', self._repository)
180
181        # strip out the eXist reference to the libraries; these files should be available in the
182        # running dir - as set up by oai_ingest.py
183        xquery=xquery.replace('xmldb:exist:///db/xqueryLib/Vocabs/', '')
184        xquery=xquery.replace('xmldb:exist:///db/xqueryLib/Utilities/', '')
185
186        # write the query to file, to make it easier to input
187        # NB, running directly at the command line leads to problems with the interpretation of $ characters
188        xqFile = "currentQuery.xq"
189        FileUtilities.createFile(xqFile, xquery)
190
191        # Now do the transform
192        os.putenv ('PATH', ':/usr/java/jdk1.5.0_03/bin:/usr/java/jdk1.5.0_03:/usr/java/jdk1.5.0_03/lib/tools.jar:/usr/local/WSClients/OAIBatch:/usr/local/exist-client/bin:/bin:/usr/bin:.')
193        xqCommand = "java -cp ./lib/saxon9.jar net.sf.saxon.Query " + xqFile + " !omit-xml-declaration=yes"
194        logging.debug("Running saxon command: " + xqCommand)
195        pipe = os.popen(xqCommand + " 2>&1")
196        output = pipe.read()
197        status = pipe.close()
198
199        if status is not None:
200            raise SystemError, 'Failed at running the XQuery'
201
202        # now remove the temp xquery file
203        status = os.unlink(xqFile)
204        if status is not None:
205            raise OSError, 'Failed to remove the temporary xquery file, ' + xqFile
206       
207        logging.info("Transform completed successfully")
208
209        return output
210
211
212    def doMolesTransform(self):
213        '''
214        Set up the basic moles doc - according to the type of document first ingested
215        '''
216        logging.info("Creating moles document - for use with other transforms")
217        xqName = None
218        if self.docType == "DIF":
219            xqName = "dif2moles"
220        elif self.docType == "MDIP":
221            xqName = "mdip2moles"
222        else:
223            raise TypeError, "ERROR: No XQuery exists to transform input document type, %s, into moles format" \
224                     %self.docType
225
226        # now run the appropriate transform and set the attribute
227        setattr(self, "_molesFormat", self.doTransform(xqName))
228
229        # add keywords, if required
230        if self._datacentre_groups:
231            self.addKeywords()
232       
233        # escape any apostrophes
234        self._molesFormat = self.escapeSpecialCharacters(self._molesFormat)
235
236        logging.info("moles document created")
237       
238
239    def addKeywords(self):
240        '''
241        If datacentre groups have been specified, these need to be added as keywords
242        - NB, this is rather clumsy approach but uses old code to achieve the result
243        '''
244        logging.info("Adding datacentre keywords to moles file")
245
246        # NB, use temporary directories to do the keyword additions
247        tmpDir = os.getcwd() + "/tmp/"
248        tmpKeywordsDir = os.getcwd() + "/keywordsAdded/"
249        FileUtilities.setUpDir(tmpDir)
250        FileUtilities.setUpDir(tmpKeywordsDir)
251        tmpFile = 'tmpFile.xml'
252        FileUtilities.createFile(tmpDir + tmpFile, self._molesFormat)
253
254        keywordAdder.main(tmpDir, tmpKeywordsDir, self._datacentre_groups)
255
256        # Now load in the converted file
257        f=open(tmpKeywordsDir + "/" + tmpFile, 'r')
258        self._molesFormat = f.read()
259        f.close
260       
261        # Finally, tidy up temp dirs
262        FileUtilities.cleanDir(tmpDir)
263        FileUtilities.cleanDir(tmpKeywordsDir)
264        logging.info("Completed adding keywords")
265       
266
267    def getDocumentFormat(self, docType):
268        '''
269        Lookup document format; if it is already defined then return it, else do the required XQuery
270        transform.  NB, transforms are ran on the molesFormat document - so ensure this is available
271        @param docType: format of document to return
272        '''
273        logging.info("Retrieving document type, " + docType)
274        xqName = {'DIF':'moles2dif', 'MOLES':'moles', 'DC':'moles2DC', 'MDIP':'moles2mdip', 'ISO19139':'moles2iso19139'}[docType]
275        attributeName = {'DIF':'_difFormat', 'MOLES':'_molesFormat', 'DC':'_dcFormat', 'MDIP':'_mdipFormat', 'ISO19139':'_iso19139Format'}[docType]
276       
277        # check we have the moles format available; if not create it
278        if self._molesFormat is None:
279            self.doMolesTransform()
280            self.createMolesFile()
281       
282        # check the document isn't already defined
283        try:
284            doc = getattr(self, attributeName)
285            if doc is not None:
286                logging.info("Found existing document - returning this now")
287                return doc
288        except:
289            logging.info("Document not available - creating new transformed document")
290
291        # the doc type doesn't exist - so run the xquery
292        transformedDoc = self.doTransform(xqName)
293        setattr(self, attributeName, transformedDoc)
294        return transformedDoc
295       
296   
297    def getAllDocs(self):
298        '''
299        Return a list of all the available doc types in the record
300        '''
301        # if the stored docs array is the same size as the array of all doc types
302        # assume all transforms have been done - and just return these
303        if len(self._allDocs) == len(self.documentTypes):
304            return self._allDocs
305       
306        for docType in self.documentTypes:
307            self._allDocs.append([docType, self.getDocumentFormat(docType)])
308
309        return self._allDocs
310       
311   
312    def getTemporalData(self):
313        '''
314        Retrieves the temporal data for the record; if this hasn't been discovered yet,
315        do the necessary parsing
316        @return: TimeRange object array with temporal data
317        '''
318        if self.stData is None:
319            self.getSpatioTemporalData()
320       
321        return self.stData.getTemporalData()
322       
323   
324    def getSpatialData(self):
325        '''
326        Retrieves the spatial data for the record; if this hasn't been discovered yet,
327        do the necessary parsing
328        @return: Coords object array with spatial data
329        '''
330        if self.stData is None:
331            self.getSpatioTemporalData()
332       
333        return self.stData.getSpatialData()
334       
335
336    def listify(self, item):
337        '''
338        listify checks if an item is a list, if it isn't it puts it
339        inside a list and returns it. Always returns a list object.
340        @param item: object to check
341        @return: item as a list object
342        '''
343        if type(item) is list:
344            return item
345        else:
346            return [item]
347       
348   
349    def getSpatioTemporalData(self):
350        '''
351        Extract spatio temporal data from the original document
352        '''
353        logging.info('Retrieving spatiotemporal info from moles file')
354        # initialise the various spatiotemporal arrays used to extract data to
355        self.stData = SpatioTemporalData()
356       
357        if self.dgMeta is None:
358            self.createMolesFile()
359           
360        # do quick checks to see if the relevant data exists
361        if not self.dgMeta.dgMetadataRecord.dgDataEntity.dgDataSummary:
362            logging.info("No data summary elements found - assuming no spatiotemporal data available")
363            return
364       
365        if not self.dgMeta.dgMetadataRecord.dgDataEntity.dgDataSummary.dgDataCoverage:
366            logging.info("No data coverage elements found - assuming no spatiotemporal data available")
367            return
368       
369        if not self.dgMeta.dgMetadataRecord.dgDataEntity.dgDataSummary.dgDataCoverage.dgSpatialCoverage:
370            logging.info("No spatial coverage elements found - assuming no spatial data available")
371        else:
372            self.getCoordData(self.dgMeta)
373
374        #SJD error with line below- this is where 23/09/08 edit in PostgresDAO fudge sorts...
375        if not self.dgMeta.dgMetadataRecord.dgDataEntity.dgDataSummary.dgDataCoverage.dgTemporalCoverage:
376            logging.info("No temporal coverage elements found - assuming no temporal data available")
377        else:
378            self.getTimeRangeData(self.dgMeta)
379
380   
381    def getAuthorsInfo(self):
382        '''
383        Extract authors info from the moles file
384        '''
385        logging.info('Retrieving authors info from moles file')
386       
387        if self.dgMeta is None:
388            self.createMolesFile()
389           
390        logging.info("Extracting author info")
391        creators = ""
392        authors = ""
393        try:
394            # TODO: check this is the correct path for author data - NB, this is not obvious from example files
395            # nb, if this is correct, need to escape out the %20 and %3 characters else it doesn't work - see unescape.. fn
396            creators = self.dgMeta.dgMetadataRecord.dgDataEntity.dgDataRoles.dgDataCreator.dgRoleHolder.dgMetadataID.localIdentifier
397            logging.info("Found creator information - adding this to authors record")
398           
399        except Exception, detail:
400            logging.info("Exception thrown whilst trying to find creator information:")
401            logging.info(detail)
402            logging.info("- this suggests document does not contain creator information.")
403
404        try:
405            authors = self.dgMeta.dgMetadataRecord.dgMetadataDescription.abstract.abstractOnlineReference.dgCitation.authors
406            logging.info("Found cited author information - adding this to authors record")
407           
408        except Exception, detail:
409            logging.info("Exception thrown whilst trying to find cited author information:")
410            logging.info(detail)
411            logging.info("- this suggests document does not contain cited author information.")
412       
413        self.authors = authors + " " + creators
414        return self.authors
415   
416   
417    def getParametersInfo(self):
418        '''
419        Extract parameters info from the moles file
420        '''
421        logging.info('Retrieving parameters info from moles file')
422       
423        if self.dgMeta is None:
424            self.createMolesFile()
425           
426        params = ""
427        try:
428            # TODO: check this is the correct path for parameters data - NB, this is not obvious from example files
429            parameters = self.dgMeta.dgMetadataRecord.dgDataEntity.dgDataSummary.dgParameterSummary.dgStdParameterMeasured
430            parameters_list = self.listify(parameters)
431            for parameter in parameters_list:
432                if parameters.dgValidTerm:
433                    logging.info("Found parameter information - adding this to record")
434                    params += " " + parameters.dgValidTerm
435           
436           
437        except Exception, detail:
438            logging.info("Exception thrown whilst trying to find parameter information:")
439            logging.info(detail)
440            logging.info("- this suggests document does not contain parameter information.")
441       
442        self.parameters = params
443        return self.parameters
444   
445   
446    def getScopeInfo(self):
447        '''
448        Extract scope info from the moles file
449        '''
450        logging.info('Retrieving scope info from moles file')
451       
452        if self.dgMeta is None:
453            self.createMolesFile()
454           
455        scope = ""
456        try:
457            keywords = self.dgMeta.dgMetadataRecord.dgStructuredKeyword
458            logging.info("Found keyword information - parsing this for scope")
459
460            keywords_list = self.listify(keywords)
461            for keyword in keywords_list:
462                if keyword.dgValidTermID:
463                    if keyword.dgValidTermID.ParentListID.strip().startswith(self.ndg_data_provider_vocab):
464                        logging.info("Found scope value - adding this to record")
465                        scope += " " + keyword.dgValidTerm.strip()
466           
467        except Exception, detail:
468            logging.info("Exception thrown whilst trying to find scope information:")
469            logging.info(detail)
470            logging.info("- this suggests document does not contain scope information.")
471
472        # NB, to_tsvector will remove any underscores -leading to, e.g. NERC_DDC becoming tokenised as 'NERC' and 'DDC'
473        # - to avoid this, use the following delimiter
474        self.scope = re.sub(r'_', 'UNDERSCORE', scope)
475        return self.scope
476           
477           
478    def getTimeRangeData(self, dgMeta):
479        '''
480        Parse an xml tree and add any time range data found
481        @param dgMeta: xml fragment for the time range
482        '''
483        logging.info("Extracting time range info")
484        try:
485            dates = dgMeta.dgMetadataRecord.dgDataEntity.dgDataSummary.dgDataCoverage.dgTemporalCoverage.DateRange
486           
487            if not dates:
488                logging.info("No temporal info found for document")
489               
490            dates_list = self.listify(dates)
491            for date in dates_list:
492                startdate=date.DateRangeStart
493                enddate= date.DateRangeEnd
494                if startdate==None or startdate=='None':
495                    startdate="null"
496                if enddate==None or enddate=='None':
497                    enddate="null"
498                   
499                self.stData.addTimeRange(startdate, enddate)
500                logging.info("Temporal info: startdate " + \
501                             startdate + ", enddate " + enddate) 
502        except Exception, detail:
503            logging.info("Document does not contain temporal info.")
504            logging.info(detail)
505
506       
507    def getCoordData(self, dgMeta):
508        '''
509        Parse an xml tree and add any coord data found
510        @param dgMeta: xml fragment for the bounding boxes
511        '''
512        logging.info("Extracting bounding box info")
513        try:
514
515            bboxes = dgMeta.dgMetadataRecord.dgDataEntity.dgDataSummary.dgDataCoverage.dgSpatialCoverage.BoundingBox
516           
517            if not bboxes:
518                logging.info("No bounding box info found for document")
519                return
520               
521            bbox_list=self.listify(bboxes)
522            #parse the list of coordinates
523            for bbox in bbox_list:
524                north = self.parseCoord(bbox.LimitNorth, 'S', 'N')
525                south = self.parseCoord(bbox.LimitSouth, 'S', 'N')
526                east = self.parseCoord(bbox.LimitEast, 'W', 'E')
527                west = self.parseCoord(bbox.LimitWest, 'W', 'E')
528                self.stData.addCoords(north, south, east, west)
529                logging.info("Spatial info: west= " + west + ",south " + south + ", east " + \
530                    east + ", north " + north + "")
531               
532        except Exception, detail:
533            logging.warning("Problem encountered whilst parsing bounding box info - this may lead \n" + \
534                            "to an incomplete set of metadata being ingested. \nDetail: %s" %detail)
535
536
537    def parseCoord(self, coordValue, minField, maxField):
538        '''
539        Take a coordinate value extracted from a molefile bbox limit - together with
540        the appropriate max/min limits and extract the correct value from it
541        @param coordValue: the contents of the bbox limit tage
542        @param minField: the expected min field of the coord range - i.e. 'W' or 'S'
543        @param maxField: the expected max field of the coord range - i.e. 'E' or 'N'
544        @return: coord - the value of the coordinate as a string   
545        '''
546        logging.debug("Parsing document coordinates")
547        try:
548            coord = coordValue.strip()
549            if coord.endswith(maxField):
550                coord=coordValue.split(maxField)[0]
551            elif coord.endswith(minField):
552                if coord.startswith('-'):
553                    coord = coordValue.split(minField)[0]
554                else:
555                    coord = "-" + coordValue.split(minField)[0]
556   
557            return '%s' % float(coord)
558        except:
559            raise SyntaxError, 'Will not process File: contains incorrect bounding box limit: ' + coordValue
560
561           
562    def hasNullCoords():
563        '''
564        Checks a record to determine whether it has any coordinates set to null
565        '''
566        if str(self.west)=='null' or \
567            str(self.south)=='null' or \
568            str(self.east)=='null' or \
569            str(self.north)=='null':
570            return True;
571        else:
572            return False;
573       
Note: See TracBrowser for help on using the repository browser.