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

"""
import re
import traceback

8

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

22

23 24 25
MSG_NO_CAT = 'Select a "category" !!!'
MSG_NO_PROJECT = 'Select a "project" !!!'
MSG_NO_TEAM = 'Select a "team" !!!'
26

27
MSG_NSERT_FAIL = "Fail to insert the new record in the database."
28
MSG_NO_OAI = "Reject no OAI identifier"
29
MSG_WELL_FORM_OAI = "Reject OAI is not well formed"
30

31

32
class Automaton(object):
33
    """Base class to search and process publications:
34

35
        * Decode the selector defining user criteria.
LE GAC Renaud's avatar
LE GAC Renaud committed
36
        * Search in the store publications matching user criteria.
37 38
        * Decode the XML string return by the store.
        * Insert new records in the database.
39

40 41
    Note:
        The parameters of the search are defined by the current ``request``.
42

43 44 45
    The logic implements in the ``Automaton`` class is the following:

        #. Ask to the store, all the `record_id` satisfying the user request.
LE GAC Renaud's avatar
LE GAC Renaud committed
46 47 48 49 50 51 52
        #. Reject `record_id` contains in the *origin* field of a
           database entry.
        #. Request to the store, the XML description of the publications
           and decode them.
        #. Reject the record for which the *secondary_oai_url* is contained in
           the *origin* field of a database entry. Update the *origin* field
           of the database record.
53
        #. Check that the *oai* of the publication is defined and well formed.
LE GAC Renaud's avatar
LE GAC Renaud committed
54 55
           Recover it, if it is not the case. At this stage the OAI is always
           defined.
56 57
        #. Reject temporarily publication.
        #. Check that *authors* are defined.
58
           Reject the publication if it is not the case.
59
        #. Check that *my institute* is in the list of the institutes
60 61 62 63 64 65
           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.
66
        #. Check that the *collaboration*, if defined, is well formed.
67
           Reject the publication if it is not the case
68 69 70 71 72 73 74 75
        #. Several check are applied depending on the publication type.
        #. At the end of this process, the publisher, the authors are
           formatted and the list of signatories of my institute extracted.

    Args:
        db (gluon.DAL): the database connection.
        id_team (int): the identifier of the team in the database.
        id_project (int): the identifier of the project in the database.
76
        automaton (unicode): the name of the automaton which
77 78 79
            will be used to process the data. Possible values are:
            ``articles``, ``notes``, ``preprints``, ``proceedings``,
            ``reports``, ``talks`` and ``theses``.
80 81 82 83 84 85 86 87 88 89
        id_category (int): the identifier of the category of publication
        year_start (int): starting year for the scan
        year_end (int): ending year of the scan
        dry_run (bool): new records are not inserted in the database
            when ``True``.
        debug (bool): activate the verbose mode when ``True``.

    Raises:
        ToolException: when the team or the project or the publication category
            is not defined.
90

91 92 93 94 95
    """
    def __init__(self,
                 db,
                 id_team,
                 id_project,
96
                 automaton,
97 98 99 100 101 102 103 104 105 106
                 id_category,
                 year_start=None,
                 year_end=None,
                 dry_run=True,
                 debug=False):

        self.collection_logs = []
        self.db = db
        self.id_team = id_team
        self.id_project = id_project
107
        self.controller = automaton
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
        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)

135 136 137 138 139
        # Identifier of the categories preprint and articles
        # Used by the method _is_record_in_db
        self._id_preprint = get_id(db.categories, code="PRE")
        self._id_article = get_id(db.categories, code="ACL")

140 141 142
    def _insert_in_db(self, log_year="", **fields):
        """Insert the record in the database, handling database exception.

143 144
        Args:
            log_year (unicode): year of the record for the log
145

146 147 148
        Keyword Args:
            **fields: keyword arguments defining the record values to be
                inserted in the database.
149

150 151 152
        Returns:
            int: one when the record is inserted / updated in the database,
                zero otherwise.
153 154 155 156 157

        """
        db = self.db

        try:
LE GAC Renaud's avatar
LE GAC Renaud committed
158
            rec_id = db.publications.insert(**fields)
LE GAC Renaud's avatar
LE GAC Renaud committed
159 160
            if rec_id:
                return 1
161

LE GAC Renaud's avatar
LE GAC Renaud committed
162 163 164 165 166
            # 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
167

LE GAC Renaud's avatar
LE GAC Renaud committed
168 169 170
                # reduce the error message
                if isinstance(msg, list):
                    msg = "%s %s" % (msg[0], msg[-1])
171

LE GAC Renaud's avatar
LE GAC Renaud committed
172 173
                self.logs[-1].reject(msg, log_year)
                return 0
174

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

180
    def _is_record_in_db(self, title, host=None, rec_id=None, oai_url=None):
181
        """Return ``True`` when the record is already in the database.
182
        The search is based on the origin field and on the primary OAI.
183

184 185
        Note:
            A new log entry is created when a record is found.
186

187
        Args:
188 189 190 191 192
            title (unicode): the title of the publication.

        Keyword Args:
            host (unicode): the store. possible values are ``cds.cern.ch`` or
                ``inspirehep.net``. To be used with *rec_id*.
193
            rec_id (int): the record identifier in the store
194 195 196 197
            oai_url (unicode): the URL of the record in the store.

                Note:
                    Either use *host* and *rec_id* or *oai_url*
198

199
        Returns:
200 201
            int: the id of the record in the database when a record is found,
                0 otherwise.
202

203 204 205
        Raises:
            ValueError: when keyword arguments are not defined properly.

206 207
        """
        db = self.db
208
        harvester = self.harvester
209

210 211 212 213 214 215 216 217
        # build the OAI URL
        if host is not None and rec_id is not None and oai_url is None:
            url = OAI_URL % (host, rec_id)
        elif host is None and rec_id is None and oai_url is not None:
            url = oai_url
        else:
            raise ValueError

218 219 220 221
        # protection empty url
        if len(url) == 0:
            return 0

222 223 224
        # check the OAI
        query = db.publications.origin.contains(url)
        setrows = db(query)
225

226
        if setrows.count() == 0:
227
            return 0
228

229
        # one record found
230 231
        columns = [db.publications.id,
                   db.publications.id_categories,
232 233 234
                   db.publications.title,
                   db.publications.year]
        publication = setrows.select(*columns).first()
235

236 237
        # Note:
        # The category for the publication and the harvester have to be equal.
238 239 240 241 242 243 244
        # However, keep the record if it is a preprint when the harvester
        # looks for articles. This is required to transform a preprint
        # into article
        #
        # Category can disagree when the publication is an article and
        # the harvester look for preprint. In that case, keep the article
        #
245
        if publication.id_categories != harvester.id_categories:
246 247 248 249 250 251 252

            is_preprint_to_article = \
                publication.id_categories == self._id_preprint \
                and harvester.id_categories == self._id_article

            if is_preprint_to_article:
                return 0
253 254

        # log
255
        self.logs.append(Msg(harvester=harvester,
256 257 258 259 260 261
                             collection=title,
                             record_id=rec_id,
                             title=publication.title))

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

262
        return publication.id
263

264 265 266 267 268
    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.

269 270 271 272 273 274
        Args:
            collection (unicode): string defining the collection in the
                store. The syntax depends on the invenio store:

                    * ``"find cn d0 and tc p and not tc c"``
                    * ``"LHCb Papers"``.
275

276 277 278
        Returns:
            dict: the key are a sub-set of those defined in
                :py:meth:invenio_tools.InvenioStore.get_ids.
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324

        """

        # 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
325
    def check_record(self, record):
326 327
        """Check the content of the record in order to fix non-conformities.
        Return ``False`` when non-conformities are found and can not be
328 329
        corrected.

330 331 332
        Note:
            Some checks depend on the type of publications and have to be
            implemented in inherited class.
333

334 335 336 337
        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.
338

339 340
        Args:
            record (Record): Marc12 record describing the publication.
341

342 343 344
        Returns:
            bool: ``False`` when a non-conformity is found and can not be
                corrected.
345 346 347 348 349 350

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

        try:
351 352
            self.check.recover_oai(record, self.harvester.host)

353 354 355 356
            if self.check.is_bad_oai_used(record):
                self.logs[-1].idle(MSG_IN_DB, record.year())
                return False

357 358
            self.check.temporary_record(record)
            self.check.authors(record)
359
            self.check.my_affiliation(record, self.id_project, self.id_team)
360 361 362
            self.check.collaboration(record)

        except Exception as e:
363
            self.logs[-1].reject(e, record=record)
364 365 366 367
            return False

        return True

368
    def get_record_by_fields(self, oai_url, year, **kwargs):
369 370
        """Get database record matching fields values defined
        in the keyword arguments.
371

372
        Note:
373 374
            This method is required to deal with publication entered by hand
            and found later by an harvester.
375

376 377 378 379 380 381 382 383 384 385 386 387
        Args:
            oai_url (unicode): the oai_url, *e.g*
                ``http://cds.cern.ch/record/123456``. The origin field
                of the existing database record is update to **oai_url**
                when a match is found.

            year (int): the year of the publication. It is used
                by the search algorithm and by the logger.

        Keyword Args:
            kwargs (unicode): a series of key, value pair where the
                key is the name of a publications database field.
388

389 390 391 392 393
        Returns:
            tuple: ``(id, status)`` which contains the ``id`` of the record.
            The ``id`` is equal to ``None`` when there is no matching.
            The ``status`` is equal to one when the existing record was
            modified zero otherwise.
394 395 396

        """
        if self.dbg:
397
            print "get existing record by fields"
398

399
        # alias
400
        db = self.db
401
        logs = self.logs
402

403 404 405
        # add the publication year to search criteria
        if year:
            kwargs["year"] = year
406 407 408 409 410 411 412

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

        # fix origin field
413 414
        publication = db.publications[rec_id]
        ok = publication.origin and publication.origin == oai_url
415 416
        if not ok:
            if not self.dry_run:
417
                publication = dict(origin=oai_url)
418

419
            logs[-1].modify(MSG_FIX_ORIGIN, year)
420 421
            return (rec_id, 1)

422
        logs[-1].idle(MSG_IN_DB, year)
423 424
        return (rec_id, 0)

425 426
    def insert_record(self, record):
        """Insert the record in the database.
427

428 429 430
        Note:
            This method depend on the type of publications.
            It has to be implemented for each inherited class.
431

432 433
        Args:
            record (Record): Marc12 record describing the publication.
434

435 436 437
        Returns:
            int: one when the record is inserted / updated in the database,
                zero otherwise.
438 439 440 441 442

        """
        return 0

    def process_xml(self, xml):
443 444 445 446 447 448 449
        """Decode the XML string and insert the corresponding records
        in the database.


        Args:
            xml (unicode): XML string encoding the publication records.
                The format follows the MARC12 standard.
450

451 452
        Raises:
           ToolException: when project, team or category identifier
453
              are not defined.
454
           StoreException: when something goes wrong interrogating the
455
              store.
456 457 458 459
           Marc12Exception: when something goes wrong decoding the XML
              string return by the store.
           CheckException: when the record has non-conformities.
           Exception: when the python code crashes.
460 461 462 463 464 465 466 467 468 469 470 471 472 473

        """
        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):
474 475
        """Retrieve the XML string from the invenio store and
        insert corresponding records in the database.
476

477 478 479
        Args:
            host (unicode): host name to query for publications, either
                ``cds.cern.ch`` or ``inspirehep.net``.
480

481
            collections (unicode): list of collection to be interrogated.
482

483 484 485 486 487 488 489
        Raises:
           StoreException: when something goes wrong interrogating the
              store.
           Marc12Exception: when something goes wrong decoding the XML
              string return by the store.
           CheckException: when the record has non-conformities.
           Exception: when the python code crashes.
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504

        """
        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
505
        collection_logs = self.collection_logs
506
        controller = self.controller
507 508 509
        decode_xml = self.decode_xml
        is_record_in_db = self._is_record_in_db
        logs = self.logs
510 511 512 513 514 515
        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
        #
516
        # The method uses here minimise the memory usage
517 518 519 520 521 522 523
        # 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)
524
            collection_logs.append(MsgCollection(title=title))
525 526 527 528 529 530 531 532

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

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

            except Exception as error:
533 534
                collection_logs[-1].url = store.last_search_url()
                collection_logs[-1].error = error
535 536
                continue

537 538
            collection_logs[-1].url = store.last_search_url()
            collection_logs[-1].found = len(rec_ids)
539 540 541 542 543 544 545 546 547 548 549 550 551

            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:
552 553 554 555
                    db_id = is_record_in_db(title, host=host, rec_id=rec_id)
                    if db_id:
                        if self.dbg:
                            print "record in db", rec_id, "->", db_id
556 557
                        continue

558
                    xml = store.get_record(rec_id)
559
                    decode_xml(xml)
560

561
                except Exception as e:
562 563
                    print traceback.format_exc()
                    url = OAI_URL % (host, rec_id)
564 565 566 567 568
                    logs.append(Msg(harvester=self.harvester,
                                    collection=title,
                                    record_id=rec_id,
                                    title=url))
                    logs[-1].reject(e)
569 570

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

573 574
        Args:
            xml (unicode): MARC XML string
575 576

        """
577

578 579 580
        if self.dbg:
            print "process xml record"

581
        # alias
582
        db = self.db
583 584
        check_record = self.check_record
        insert_record = self.insert_record
585
        is_record_in_db = self._is_record_in_db
586 587
        logs = self.logs

588 589 590
        # NOTE
        # BaseException and inherited class
        # are caught by the previous stage
591 592 593 594 595 596 597
        records = self.marc12(xml)

        # process individual record
        for record in records:

            if self.dbg:
                print "record decoded"
598
                print record.title()
599

600 601
            # reject the record using the secondary OAI
            # require to cover the case:
602
            # - scan store A. Only OAI_A is defined.
603
            # - later scan store B. OAI_B and OAI_A are found.
604 605 606 607 608 609 610 611
            rec_id = is_record_in_db(record.title(),
                                     oai_url=record.secondary_oai_url())
            if rec_id:
                # update the oai_url for later uses.
                if not self.dry_run:
                    tp = (record.secondary_oai_url(), record.primary_oai_url())
                    oai_url = "%s, %s" % tp
                    db.publications[rec_id] = dict(origin=oai_url)
612 613 614 615

                if self.dbg:
                    print "record in db (secondary oai) ->", rec_id

616 617
                continue

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

624 625
            # check that the record is well formed
            # repair non-conformity as far as possible
626
            if not check_record(record):
627 628
                if self.dbg:
                    print "record rejected", logs[-1].txt
629 630 631
                continue

            if self.dbg:
632
                print "insert record in the database"
633

634
            # insert the record in the database
635
            insert_record(record)
636 637

            if self.dbg:
638
                print logs[-1].action.upper(), logs[-1].txt
639 640 641 642

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

643 644 645 646 647 648
        Returns:
            dict:
                * ``collection_logs`` list of :class:MsgCollection
                * ``controller`` unicode
                * ``logs`` list of :class:Msg
                * ``selector`` :py:class:plugin_dbui.Selector
649 650 651 652 653 654

        """

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

    def search_collaboration(self, value):
LE GAC Renaud's avatar
LE GAC Renaud committed
657
        """Get the database collaboration identifier using synonyms.
658 659 660 661 662 663

        Args:
            value (unicode): the name of the collaboration.

        Returns:
            int:
LE GAC Renaud's avatar
LE GAC Renaud committed
664
                * the id of the collaboration record.
665 666
                * UNDEF_ID if value is not defined.

667
        Raises:
668 669
            ToolException: when more than one synonym is found or when the
                collaboration is not defined.
670 671

        """
672

673
        return search_synonym(self.db.collaborations, "collaboration", value)
674 675

    def search_country(self, value):
LE GAC Renaud's avatar
LE GAC Renaud committed
676
        """Get the database country identifier using synonyms.
677 678 679 680 681 682

        Args:
            value (unicode): the name of the country.

        Returns:
            int:
LE GAC Renaud's avatar
LE GAC Renaud committed
683
                * the id of the country record.
684 685
                * UNDEF_ID if value is not defined.

686
        Raises:
687 688
            ToolException: when more than one synonym is found ot when
                the country is not defined.
689 690

        """
691
        return search_synonym(self.db.countries, "country", value)
692 693

    def search_publisher(self, value):
LE GAC Renaud's avatar
LE GAC Renaud committed
694
        """Get the database publisher identifier using synonyms.
695 696 697 698 699 700

        Args:
            value (unicode): the abbreviation of the publisher.

        Returns:
            int:
LE GAC Renaud's avatar
LE GAC Renaud committed
701
                * the id of the publisher record.
702 703
                * UNDEF_ID if value is not defined.

704
        Raises:
705 706
            ToolException: when more than one synonym is found or when
                the publisher is not defined.
707 708

        """
709
        return search_synonym(self.db.publishers, "abbreviation", value)