automaton.py 19 KB
Newer Older
1
# -*- coding: utf-8 -*-
2
""" harvest_tools.automaton
3 4 5 6 7

"""
import re
import traceback

8

9
from base import MSG_FIX_ORIGIN, MSG_IN_DB, ToolException
10
from gluon.storage import Storage
11 12 13
from invenio_tools import (CheckAndFix,
                           InvenioStore,
                           Marc12,
14
                           OAI_URL)
15 16
from msg import Msg
from msgcollection import MsgCollection
17
from plugin_dbui import CALLBACK_ERRORS, get_create_id, get_id, UNDEF_ID
18

19

20 21 22
MSG_NO_CAT = 'Select a "category" !!!'
MSG_NO_PROJECT = 'Select a "project" !!!'
MSG_NO_TEAM = 'Select a "team" !!!'
23

24
MSG_NSERT_FAIL = "Fail to insert the new record in the database."
25
MSG_NO_OAI = "Reject no OAI identifier"
26
MSG_WELL_FORM_OAI = "Reject OAI is not well formed"
27

28

29
class Automaton(object):
30 31 32 33 34 35 36 37 38
    """Base class to search and process publications.
        - Decode the parameter of a selector defining user criteria.
        - Search for publications in the store, according to
          user criteria or process and XML string.
        - Load records in the database.

    The parameters of the search as well as the parameters of the harvester
    are defined by the current request.

39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
    The logic implements in the `Automaton` class is the following

        1. Ask to the store, all the `record_id` satisfying the user request.
        2. Reject `record_id` matching the `origin` field of a database entry.
        3. Request to the store, the XML description of the publication
           and decode it.
        4. Check that the *oai* of the publication is defined and well formed.
           Recover it if it is not the case. From time to time, the `id`
           encoded in the `oai` field is different from the `record` id.
           This happens when an old record is redirected to new one
           for obscure reasons. The record is ignore if a database entry
           is found with the bad OAI.
        5. Reject temporarily publication.
        6. Check that *authors* are defined.
           Reject the publication if it is not the case.
        7. Check that *my institute* is in the list of the institutes
           signing the publication. Reject the publication if it is
           not the case. When the affiliation are not defined,
           try to recover this case, by finding the author of my institute
           signing the publication. This recovery procedure uses
           the *author rescue list*. Reject the record when the recovery
           procedure failed.
        8. Check that the *collaboration*, if defined, is well formed.
           Reject the publication if it is not the case
        10. Several check are applied depending on the publication type.
        11. At the end of this process, the publisher, the authors are
            formatted and the list of signatories of my institute extracted.

67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
    """

    def __init__(self,
                 db,
                 id_team,
                 id_project,
                 controller,
                 id_category,
                 year_start=None,
                 year_end=None,
                 dry_run=True,
                 debug=False):
        """
        @note see C{build_harvester_tool} factory function building
              C{PublicationsTools}

        @type db: gluon.dal.DAL
        @param db:

        @type id_team: int
        @param id_team: Identifier of the team in the db

        @type id_project: int
        @param id_project: Identifier of the project in the db

        @type controller: unicode
        @param controller: Type of publication
                           (i.e. 'article', 'proceedings', ...)

        @type id_category: int
        @param id_category: Identifier of the category of publication
                            (i.e. ACL, ACTI, ...)

        @type year_start: int
        @keyword year_start: Start year of search (i.e. '2014')

        @type year_end: int
        @keyword year_end: End year of search (i.e. '2015')

        @type dry_run: boolean
        @keyword dry_run: True if no record is to be written to the db

        @type debug: bool
        @param debug: activate the debug mode

        """
        self.collection_logs = []
        self.db = db
        self.id_team = id_team
        self.id_project = id_project
        self.controller = controller
        self.id_category = id_category
        self.year_start = year_start
        self.year_end = year_end
        self.dry_run = dry_run
        self.dbg = debug
        self.logs = []

        self.check = CheckAndFix()
        self.marc12 = Marc12()

        # check parameters
        # protection team, project and/or category have to be defined
        if not self.id_team:
            raise ToolException(MSG_NO_TEAM)

        if not self.id_project:
            raise ToolException(MSG_NO_PROJECT)

        if not self.id_category:
            raise ToolException(MSG_NO_CAT)

        # Construct harvester Storage needed for the log
        self.harvester = Storage(id_teams=self.id_team,
                                 id_projects=self.id_project,
                                 controller=self.controller,
                                 id_categories=self.id_category)

145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
    def _insert_in_db(self, log_year="", **fields):
        """Insert the record in the database, handling database exception.

        @type log_year: unicode
        @param log_year: year of the record for the log

        @type **fields: dict
        @param **fields:

        @rtype: int
        @return: one when the record is inserted / updated in the database
        zero otherwise.

        """
        db = self.db

        try:
            rec_id = db.publications.insert (**fields)
LE GAC Renaud's avatar
LE GAC Renaud committed
163 164
            if rec_id:
                return 1
165

LE GAC Renaud's avatar
LE GAC Renaud committed
166 167 168 169 170
            # operation can be reject by callbacks table._before_insert
            else:
                msg = MSG_NSERT_FAIL
                if CALLBACK_ERRORS in db.publications:
                    msg = db.publications._callback_errors
171

LE GAC Renaud's avatar
LE GAC Renaud committed
172 173 174
                # reduce the error message
                if isinstance(msg, list):
                    msg = "%s %s" % (msg[0], msg[-1])
175

LE GAC Renaud's avatar
LE GAC Renaud committed
176 177
                self.logs[-1].reject(msg, log_year)
                return 0
178

LE GAC Renaud's avatar
LE GAC Renaud committed
179 180 181 182
        # operation can be rejected by the database
        except Exception as dbe:
            self.logs[-1].reject(dbe.message, log_year)
            return 0
183

184
    def _is_record_in_db(self, rec_id, title):
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
        """Return C{True} if the record is already in the database.
        The search is based on the origin field.

        A new log entry is created

        @type rec_id: int
        @param rec_id: record identifier

        @type title: str
        @param title: title of the collection

        @rtype: bool

        """
        db = self.db
200
        harvester = self.harvester
201

202 203
        # check
        url = OAI_URL % (harvester.host, rec_id)
204 205 206 207 208 209 210
        db_id = get_id(db.publications, origin=url)

        if db_id is None:
            return False

        publication = db.publications[db_id]

211 212 213 214 215 216 217
        # same category for the publication and the harvester
        # keep the record if it is not the case
        # this is required to transform a preprint into article
        if publication.id_categories != harvester.id_categories:
            return False

        # log
218 219 220 221 222 223 224 225 226
        self.logs.append(Msg(harvester=self.harvester,
                             collection=title,
                             record_id=rec_id,
                             title=publication.title))

        self.logs[-1].idle(MSG_IN_DB, publication.year)

        return True

227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
    def _search_parameters(self, collection):
        """Build the keywords to steer the URL search in invenio store.
        The main parameter is the collection and the date range defined
        in the selector.

        @type collection: unicode
        @param collection: statement defining the collection in the
        store, I{i.e.} C{"find cn d0 and tc p and not tc c"} or
        C{"LHCb Papers"}. The syntax depends on the invenio store.

        @rtype: dict
        @return: the key are a sub-set of those defined in
        L{invenio_tools.InvenioStore.get_ids}.

        """

        # INSPIREHEP store
        if collection.startswith('find'):

            query = collection

            if self.year_start and not self.year_end:
                query += " and date %s" % self.year_start

            elif not self.year_start and self.year_end:
                query += " and date %s" % self.year_end

            elif self.year_start and self.year_end:
                query += " and date > %s and date < %s " \
                         % (self.year_start - 1, self.year_end + 1)

            dic = dict(p=query,  # query à la spires
                       rg=1000,  # maximum number of records returned
                       sf='year',  # sort by date
                       so='d')  # descending order

        # CERN INVENIO store
        else:

            if self.year_start and not self.year_end:
                rex = self.year_start

            elif not self.year_start and self.year_end:
                rex = self.year_end

            elif self.year_start and self.year_end:
                li = []
                for year in range(self.year_start, self.year_end + 1):
                    li.append(str(year))
                rex = '|'.join(li)

            dic = dict(cc=collection,  # collection
                       f1='year',  # search on year
                       m1='r',  # use regular expression
                       p1=rex,  # regular expression defining year
                       sf='year',  # sort by date
                       so='d')  # descending order
        return dic

LE GAC Renaud's avatar
LE GAC Renaud committed
286
    def check_record(self, record):
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
        """Check the content of the record in order to fix non conformities.
        Return False when a non conformities has been found and can not be
        corrected.

        @note: Some checks depend on the type of publications and have to be
        implemented in inherited class.

        @note: The order of the checks matter. It should be oai,
        temporary record, authors, my authors and then a series of checks
        specific to the publication type.

        @type record: L{Record}
        @param record:

        @rtype: bool
        @return: C{False} when a non conformity is found and can not be
        corrected.

        """
        if self.dbg:
            print "check record"

        try:
310 311
            self.check.recover_oai(record, self.harvester.host)

312 313 314 315
            if self.check.is_bad_oai_used(record):
                self.logs[-1].idle(MSG_IN_DB, record.year())
                return False

316 317
            self.check.temporary_record(record)
            self.check.authors(record)
318
            self.check.my_affiliation(record, self.id_project, self.id_team)
319 320 321 322 323 324 325 326
            self.check.collaboration(record)

        except Exception as e:
            self.logs[-1].reject(e, record.year())
            return False

        return True

327
    def get_record_by_fields(self, **kwargs):
328
        """Get database record matching fields defined in the keyword arguments.
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345

            - Fix the field origin when a match is found.
            - Actions are logged.

        @keyword oai_url: typical value is "http://cds.cern.ch/record/123456"
        @keyword year:

        @note: this method can be customised in inherited class
        to perform dedicated action.

        @rtype: tuple
        @return: the tuple (id, status). The id of the record or None.
        The status is equal to one when the existing record was modified
        zero otherwise

        """
        if self.dbg:
346
            print "get existing record by fields"
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371

        db = self.db

        # origin can't be used for the search
        oai_url = kwargs["oai_url"]
        del kwargs["oai_url"]

        # look for an existing record
        rec_id = get_id(db.publications, **kwargs)
        if not rec_id:
            return (None, 0)

        # fix origin field
        ok = db.publications[rec_id].origin and \
             db.publications[rec_id].origin == oai_url
        if not ok:
            if not self.dry_run:
                db.publications[rec_id] = dict(origin=oai_url)

            self.logs[-1].modify(MSG_FIX_ORIGIN, kwargs["year"])
            return (rec_id, 1)

        self.logs[-1].idle(MSG_IN_DB, kwargs["year"])
        return (rec_id, 0)

372 373 374
    def get_create_collaboration(self, value):
        """Get the database collaboration identifier.
        Create it, if if does not exist.
375 376 377 378 379 380 381 382 383 384 385 386 387

        @type value: str or None
        @param value: the name of the collaboration.

        @rtype: int
        @return: the id of the collaboration, UNDEF_ID when not defined

        """
        if not value:
            return UNDEF_ID

        return get_create_id(self.db.collaborations, collaboration=value)

388 389 390
    def get_create_publisher(self, value):
        """Get the database publisher identifier.
        Create it, if it does not exit.
391 392 393 394 395 396 397 398 399 400 401 402 403

        @type value: str or None
        @param value: the abbreviation of the publisher name.

        @rtype: int
        @return: the id of the publisher, UNDEF_ID when not defined

        """
        if not value:
            return UNDEF_ID

        return get_create_id(self.db.publishers, abbreviation=value)

404 405
    def insert_record(self, record):
        """Insert the record in the database.
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423

        @note: This method depend on the type of publications.
        It has to be implemented for each inherited class.

        @type record: L{Record}
        @param record:

        @rtype: int
        @return: one when the record is inserted / updated in the database
        zero otherwise.

        """
        return 0

    def process_xml(self, xml):
        """Decode the xml and load it in the database.

        @raise Exception: the type of exception depends on what happen:
424
            - L{ToolException} when project, team or category identifier
425
              are not defined.
426 427 428
            - C{StoreException} when something goes wrong interrogating the
              store.
            - C{Marc12Exception} when something goes wrong decoding the XML
429 430 431 432 433
              string return by the store
            - C{CheckException} if the L{Record} is not valid
            - C{Exception} if the python code crash

        @type xml: unicode
434
        @keyword xml: marc12 XML encoding of the publication record
435 436 437 438 439 440 441 442 443 444 445 446 447 448

        """
        if self.dbg:
            print "start processing", self.__class__.__name__
            print "decode request"

        if self.dbg:
            print "get harvest parameters"

        # decode the XML request
        self.collection_logs.append(MsgCollection(found=1))
        self.decode_xml(xml)

    def process_url(self, host, collections):
449
        """Retrieve the XML from the invenio store and load it in the database
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481

        @raise Exception: depending on what happen, can be StoreException,
        Marc12ZException, ...

        @type host: unicode
        @keyword host: Web host name to query for publication

        @type collections: unicode
        @keyword collections: Request string to send to the host to get the
                              publications

        """
        if self.dbg:
            print "process URL search"

        # extend harvester for logs
        self.harvester.host = host
        self.harvester.collections = collections

        store = InvenioStore(host)

        # list of collections
        collections = re.sub(' *, *', ',', collections).split(',')

        # alias
        controller = self.controller
        project = self.db.projects[self.id_project].project

        # extract the list of publications from the store for each collection
        # the search is perform on a range of creation date
        # if not defined all element are return
        #
482
        # The method use here minimize the memory usage
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
        # on the server as well as on the client side

        for collection in collections:

            # log collection information
            # A collection is identified as "Project Controller collection"
            title = "%s / %s / %s" % (project, controller, collection)
            self.collection_logs.append(MsgCollection(title=title))

            # search record in the harvester repository
            kwargs = self._search_parameters(collection)

            try:
                rec_ids = store.get_ids(**kwargs)

            except Exception as error:
                self.collection_logs[-1].url = store.last_search_url()
                self.collection_logs[-1].error = error
                continue

            self.collection_logs[-1].url = store.last_search_url()
            self.collection_logs[-1].found = len(rec_ids)

            if not rec_ids:
                continue

            if self.dbg:
                print '%i records found in %s' % (len(rec_ids), collection)

            for rec_id in rec_ids:

                if self.dbg:
                    print "\nprocessing record", rec_id

                try:
518
                    if self._is_record_in_db(rec_id, title):
519 520
                        continue

521 522 523
                    xml = store.get_record(rec_id)
                    self.decode_xml(xml)

524
                except Exception as e:
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
                    print traceback.format_exc()
                    url = OAI_URL % (host, rec_id)
                    self.logs.append(Msg(harvester=self.harvester,
                                         collection=title,
                                         record_id=rec_id,
                                         title=url))
                    self.logs[-1].reject(e)

    def decode_xml(self, xml):
        """Decode the MARC XML string and load records in the database.

        @type xml: unicode
        @param xml: MARC XML string

        """
        if self.dbg:
            print "process xml record"

543 544 545
        # NOTE
        # BaseException and inherited class
        # are caught by the previous stage
546 547 548 549 550 551 552 553 554 555 556 557 558 559
        records = self.marc12(xml)

        # process individual record
        for record in records:

            if self.dbg:
                print "record decoded"

            # start the log for the record
            self.logs.append(Msg(harvester=self.harvester,
                                 collection=self.collection_logs[-1].title,
                                 record_id=record.id(),
                                 title=record.title()))

560 561 562
            # check that the record is well formed
            # repair non-conformity as far as possible
            if not self.check_record(record):
563 564 565
                continue

            if self.dbg:
566
                print "insert record in the database"
567

568 569
            # insert the record in the database
            self.insert_record(record)
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589

            if self.dbg:
                print self.logs[-1].action.upper(), self.logs[-1].txt

    def report(self):
        """Build the processing report.

        @rtype: dict
        @return:
            - C{collection_logs} (list) one L{MsgCollection}) for each
                                        collection
            - C{controller} (str)
            - C{logs} (list) one L{Msg} for each publication
            - C{selector} (Selector)

        """

        return dict(collection_logs=self.collection_logs,
                    controller=self.controller,
                    logs=self.logs)