automaton.py 23.8 KB
Newer Older
1
""" harvest_tools.automaton
2 3 4 5 6

"""
import re
import traceback

7

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

21

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

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

30 31 32 33
# search collection when using inspirehep
# require for "Hal Hidden"
REG_COLLECTION = re.compile(r"cc([A-Za-z ]+)(and|$)")

34

35
class Automaton(object):
36
    """Base class to search and process publications:
37

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

43 44
    Note:
        The parameters of the search are defined by the current ``request``.
45

46 47 48
    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
49 50 51 52 53 54 55
        #. 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.
56
        #. Check that the *oai* of the publication is defined and well formed.
LE GAC Renaud's avatar
LE GAC Renaud committed
57 58
           Recover it, if it is not the case. At this stage the OAI is always
           defined.
59 60
        #. Reject temporarily publication.
        #. Check that *authors* are defined.
61
           Reject the publication if it is not the case.
62
        #. Check that *my institute* is in the list of the institutes
63 64 65 66 67 68
           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.
69
        #. Check that the *collaboration*, if defined, is well formed.
70
           Reject the publication if it is not the case
71 72 73 74 75 76 77 78
        #. 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.
79
        automaton (unicode): the name of the automaton which
80 81 82
            will be used to process the data. Possible values are:
            ``articles``, ``notes``, ``preprints``, ``proceedings``,
            ``reports``, ``talks`` and ``theses``.
83 84 85 86 87 88 89 90 91 92
        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.
93

94 95 96 97 98
    """
    def __init__(self,
                 db,
                 id_team,
                 id_project,
99
                 automaton,
100 101 102 103 104 105 106 107 108 109
                 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
110
        self.controller = automaton
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
        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)

138 139 140 141 142
        # 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")

143 144 145
    def _insert_in_db(self, log_year="", **fields):
        """Insert the record in the database, handling database exception.

146 147
        Args:
            log_year (unicode): year of the record for the log
148

149 150 151
        Keyword Args:
            **fields: keyword arguments defining the record values to be
                inserted in the database.
152

153 154 155
        Returns:
            int: one when the record is inserted / updated in the database,
                zero otherwise.
156 157 158 159 160

        """
        db = self.db

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

LE GAC Renaud's avatar
LE GAC Renaud committed
165 166 167 168 169
            # 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
170

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

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

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

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

187 188
        Note:
            A new log entry is created when a record is found.
189

190
        Args:
191 192 193 194 195
            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*.
196
            rec_id (int): the record identifier in the store
197 198 199 200
            oai_url (unicode): the URL of the record in the store.

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

202
        Returns:
203 204
            int: the id of the record in the database when a record is found,
                0 otherwise.
205

206 207 208
        Raises:
            ValueError: when keyword arguments are not defined properly.

209 210
        """
        db = self.db
211
        harvester = self.harvester
212

213 214 215 216 217 218 219 220
        # 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

221 222 223 224
        # protection empty url
        if len(url) == 0:
            return 0

225 226 227
        # check the OAI
        query = db.publications.origin.contains(url)
        setrows = db(query)
228

229
        if setrows.count() == 0:
230
            return 0
231

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

239 240
        # Note:
        # The category for the publication and the harvester have to be equal.
241 242 243 244 245 246 247
        # 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
        #
248
        if publication.id_categories != harvester.id_categories:
249 250 251 252 253 254 255

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

            if is_preprint_to_article:
                return 0
256 257

        # log
258
        self.logs.append(Msg(harvester=harvester,
259 260 261 262 263 264
                             collection=title,
                             record_id=rec_id,
                             title=publication.title))

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

265
        return publication.id
266

267 268 269 270 271
    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.

272 273 274 275 276 277
        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"``.
278

279 280 281
        Returns:
            dict: the key are a sub-set of those defined in
                :py:meth:invenio_tools.InvenioStore.get_ids.
282 283 284 285

        """

        # INSPIREHEP store
LE GAC Renaud's avatar
LE GAC Renaud committed
286
        if collection.startswith("find"):
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301

            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
LE GAC Renaud's avatar
LE GAC Renaud committed
302 303
                       sf="year",  # sort by date
                       so="d")  # descending order
304

305 306 307 308 309 310 311 312 313
            # handle the cc keyword (true inspirehep collection)
            match = REG_COLLECTION.search(query)
            if match:
                dic["cc"] = match.group(1).strip()
                dic["p"] = REG_COLLECTION.sub("", query).strip()
                dic["p"] = dic["p"].replace("  ", " ")
                if dic["p"] == "find":
                    del dic["p"]

314 315 316 317 318 319 320 321 322 323 324 325 326
        # 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))
LE GAC Renaud's avatar
LE GAC Renaud committed
327
                rex = "|".join(li)
328 329

            dic = dict(cc=collection,  # collection
LE GAC Renaud's avatar
LE GAC Renaud committed
330 331
                       f1="year",  # search on year
                       m1="r",  # use regular expression
332
                       p1=rex,  # regular expression defining year
LE GAC Renaud's avatar
LE GAC Renaud committed
333 334
                       sf="year",  # sort by date
                       so="d")  # descending order
335 336
        return dic

LE GAC Renaud's avatar
LE GAC Renaud committed
337
    def check_record(self, record):
338 339
        """Check the content of the record in order to fix non-conformities.
        Return ``False`` when non-conformities are found and can not be
340 341
        corrected.

342 343 344
        Note:
            Some checks depend on the type of publications and have to be
            implemented in inherited class.
345

346 347 348 349
        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.
350

351 352
        Args:
            record (Record): Marc12 record describing the publication.
353

354 355 356
        Returns:
            bool: ``False`` when a non-conformity is found and can not be
                corrected.
357 358 359

        """
        if self.dbg:
360
            print("check record")
361 362

        try:
363 364
            self.check.recover_oai(record, self.harvester.host)

365 366 367 368
            if self.check.is_bad_oai_used(record):
                self.logs[-1].idle(MSG_IN_DB, record.year())
                return False

369 370
            self.check.temporary_record(record)
            self.check.authors(record)
371
            self.check.my_affiliation(record, self.id_project, self.id_team)
372 373 374
            self.check.collaboration(record)

        except Exception as e:
375
            self.logs[-1].reject(e, record=record)
376 377 378 379
            return False

        return True

380
    def get_record_by_fields(self, oai_url, year, **kwargs):
381 382
        """Get database record matching fields values defined
        in the keyword arguments.
383

384
        Note:
385 386
            This method is required to deal with publication entered by hand
            and found later by an harvester.
387

388 389 390 391 392 393 394 395 396 397 398 399
        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.
400

401 402 403 404 405
        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.
406 407 408

        """
        if self.dbg:
409
            print("get existing record by fields")
410

411
        # alias
412
        db = self.db
413
        logs = self.logs
414

415 416 417
        # add the publication year to search criteria
        if year:
            kwargs["year"] = year
418 419 420 421 422 423 424

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

        # fix origin field
425 426
        publication = db.publications[rec_id]
        ok = publication.origin and publication.origin == oai_url
427 428
        if not ok:
            if not self.dry_run:
429
                publication = dict(origin=oai_url)
430

431
            logs[-1].modify(MSG_FIX_ORIGIN, year)
432 433
            return (rec_id, 1)

434
        logs[-1].idle(MSG_IN_DB, year)
435 436
        return (rec_id, 0)

437 438
    def insert_record(self, record):
        """Insert the record in the database.
439

440 441 442
        Note:
            This method depend on the type of publications.
            It has to be implemented for each inherited class.
443

444 445
        Args:
            record (Record): Marc12 record describing the publication.
446

447 448 449
        Returns:
            int: one when the record is inserted / updated in the database,
                zero otherwise.
450 451 452 453 454

        """
        return 0

    def process_xml(self, xml):
455 456 457 458 459 460 461
        """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.
462

463 464
        Raises:
           ToolException: when project, team or category identifier
465
              are not defined.
466
           StoreException: when something goes wrong interrogating the
467
              store.
468 469 470 471
           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.
472 473 474

        """
        if self.dbg:
475 476
            print("start processing", self.__class__.__name__)
            print("decode request")
477 478

        if self.dbg:
479
            print("get harvest parameters")
480 481 482 483 484

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

485
    def process_url(self, host, collection):
486 487
        """Retrieve the XML string from the invenio store and
        insert corresponding records in the database.
488

489
        Args:
490 491
            host (str):
                host name to query for publications, either
492
                ``cds.cern.ch`` or ``inspirehep.net``.
493

494 495
            collection (str):
                the collection to be interrogated.
496

497
        Raises:
498 499 500 501 502 503 504 505 506 507 508 509
           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.
510 511 512

        """
        if self.dbg:
513
            print("process URL search")
514 515 516

        # extend harvester for logs
        self.harvester.host = host
517
        self.harvester.collection = collection
518 519 520 521

        store = InvenioStore(host)

        # alias
522
        collection_logs = self.collection_logs
523
        controller = self.controller
524 525 526
        decode_xml = self.decode_xml
        is_record_in_db = self._is_record_in_db
        logs = self.logs
527 528
        project = self.db.projects[self.id_project].project

529
        # extract the list of publications from the store for the collection
530 531 532
        # the search is perform on a range of creation date
        # if not defined all element are return
        #
533
        # The method uses here minimise the memory usage
534 535
        # on the server as well as on the client side

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

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

544 545
        try:
            rec_ids = store.get_ids(**kwargs)
546

547 548 549 550
        except Exception as error:
            collection_logs[-1].url = store.last_search_url()
            collection_logs[-1].error = error
            return
551

552 553
        collection_logs[-1].url = store.last_search_url()
        collection_logs[-1].found = len(rec_ids)
554

555 556
        if not rec_ids:
            return
557

558
        if self.dbg:
559
            print("%i records found in %s" % (len(rec_ids), collection))
560 561

        for rec_id in rec_ids:
562 563

            if self.dbg:
564
                print("\nprocessing record", rec_id)
565 566 567 568 569

            try:
                db_id = is_record_in_db(title, host=host, rec_id=rec_id)
                if db_id:
                    if self.dbg:
570
                        print("record in db", rec_id, "->", db_id)
571
                    continue
572 573 574 575 576

                xml = store.get_record(rec_id)
                decode_xml(xml)

            except Exception as e:
577
                print(traceback.format_exc())
578 579 580 581 582 583
                url = OAI_URL % (host, rec_id)
                logs.append(Msg(harvester=self.harvester,
                                collection=title,
                                record_id=rec_id,
                                title=url))
                logs[-1].reject(e)
584 585

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

588 589
        Args:
            xml (unicode): MARC XML string
590 591

        """
592

593
        if self.dbg:
594
            print("process xml record")
595

596
        # alias
597
        db = self.db
598 599
        check_record = self.check_record
        insert_record = self.insert_record
600
        is_record_in_db = self._is_record_in_db
601 602
        logs = self.logs

603 604 605
        # NOTE
        # BaseException and inherited class
        # are caught by the previous stage
606 607 608 609 610 611
        records = self.marc12(xml)

        # process individual record
        for record in records:

            if self.dbg:
612 613
                print("record decoded")
                print(record.title())
614

615 616
            # reject the record using the secondary OAI
            # require to cover the case:
617
            # - scan store A. Only OAI_A is defined.
618
            # - later scan store B. OAI_B and OAI_A are found.
619 620 621 622 623 624 625 626
            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)
627 628

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

631 632
                continue

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

639 640
            # check that the record is well formed
            # repair non-conformity as far as possible
641
            if not check_record(record):
642
                if self.dbg:
643
                    print("record rejected", logs[-1].txt)
644 645 646
                continue

            if self.dbg:
647
                print("insert record in the database")
648

649
            # insert the record in the database
650
            insert_record(record)
651 652

            if self.dbg:
653
                print(logs[-1].action.upper(), logs[-1].txt)
654 655 656 657

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

658 659 660 661 662 663
        Returns:
            dict:
                * ``collection_logs`` list of :class:MsgCollection
                * ``controller`` unicode
                * ``logs`` list of :class:Msg
                * ``selector`` :py:class:plugin_dbui.Selector
664 665 666 667 668 669

        """

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

    def search_collaboration(self, value):
LE GAC Renaud's avatar
LE GAC Renaud committed
672
        """Get the database collaboration identifier using synonyms.
673 674 675 676 677 678

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

        Returns:
            int:
LE GAC Renaud's avatar
LE GAC Renaud committed
679
                * the id of the collaboration record.
680 681
                * UNDEF_ID if value is not defined.

682
        Raises:
683 684
            ToolException: when more than one synonym is found or when the
                collaboration is not defined.
685 686

        """
687

688
        return search_synonym(self.db.collaborations, "collaboration", value)
689 690

    def search_country(self, value):
LE GAC Renaud's avatar
LE GAC Renaud committed
691
        """Get the database country identifier using synonyms.
692 693 694 695 696 697

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

        Returns:
            int:
LE GAC Renaud's avatar
LE GAC Renaud committed
698
                * the id of the country record.
699 700
                * UNDEF_ID if value is not defined.

701
        Raises:
702 703
            ToolException: when more than one synonym is found ot when
                the country is not defined.
704 705

        """
706
        return search_synonym(self.db.countries, "country", value)
707 708

    def search_publisher(self, value):
LE GAC Renaud's avatar
LE GAC Renaud committed
709
        """Get the database publisher identifier using synonyms.
710 711 712 713 714 715

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

        Returns:
            int:
LE GAC Renaud's avatar
LE GAC Renaud committed
716
                * the id of the publisher record.
717 718
                * UNDEF_ID if value is not defined.

719
        Raises:
720 721
            ToolException: when more than one synonym is found or when
                the publisher is not defined.
722 723

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