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

"""
import re
import regex

8
from base import format_author_fr, search_synonym, ToolException
9
from exception import CheckException
10
from gluon import current
11
from invenio_tools import (DECODE_REF,
12 13 14 15 16 17 18 19
                           MSG_NO_CONF,
                           MSG_NO_THESIS,
                           OAI_URL,
                           RecordConf,
                           RecordThesis,
                           REG_AUTHOR,
                           REG_OAI,
                           REG_YEAR)
20
from itertools import imap
21
from pandas import DataFrame
22
from plugin_dbui import CLEAN_SPACES, get_id
23 24


25
DECODE_ARXIV = re.compile(r"arXiv:(\d{2})(\d{2})\.")
26 27 28 29

# Decode submitted date: DD MMM YYYY or DD MM YYY
DECODE_DD_MMM_YYYY = re.compile(r"(\d{1,2}) *([A-Za-z]{3}) *(\d{4})")
DECODE_DD_MM_YYYY = re.compile(r"(\d{1,2}) +(\d{1,2}) +(\d{4})")
30
DECODE_YYYY = re.compile(r"^(\d{4})$")
31

LE GAC Renaud's avatar
LE GAC Renaud committed
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
MONTHS = {u'Jan': '01',
          u'Feb': '02',
          u'Fev': '02',
          u'Mar': '03',
          u'Apr': '04',
          u'Avr': '04',
          u'May': '05',
          u'Mai': '05',
          u'Jun': '06',
          u'Jul': '07',
          u'Aug': '08',
          u'Sep': '09',
          u'Oct': '10',
          u'Nov': '11',
          u'Dec': '12'}
47

48 49
MSG_INVALID_HOST = "Invalid host"

50
MSG_NO_AUTHOR = "Reject no author(s)"
51
MSG_NO_CONF_DATE = "Reject no conference date"
52
MSG_NO_DATE = "Reject no submission date"
53
MSG_NO_MY_AUTHOR = "Reject no authors of my institute"
54 55
MSG_NO_REF = "Reject incomplete paper reference"
MSG_NO_YEAR = "Reject no publication year"
56

57
MSG_TEMPORARY_RECORD = "Temporary record"
58

59 60 61
MSG_TO_MANY_DATE = "Reject to many submit date"
MSG_TO_MANY_FAUTHOR = "Reject to many first author"
MSG_TO_MANY_YEAR = "Reject to many year"
62

63 64
MSG_WELL_FORMED_CONF_DATES = "Reject conference dates is not well formed"
MSG_WELL_FORMED_DATE = "Reject submission date is not well formed"
65

66
MSG_WELL_FORMED_EDITOR = "Reject editor is not well formed"
67

68 69
OAI_INVENIO = "oai:%s:%s"

70 71
REG_COLLABORATION = re.compile(regex.REG_COLLABORATION)
REG_CONF_DATES_1 = re.compile("(\d+) *-? *(\d+) *([A-Z][a-z]{2}) *(\d{4})")
72 73

REG_CONF_DATES_2 = \
LE GAC Renaud's avatar
LE GAC Renaud committed
74
    re.compile("(\d+) *([A-Z][a-z]{2}) *-? *(\d+) *([A-Z][a-z]{2}) *(\d{4})")
75

76 77 78
REG_CONF_DATES = re.compile(regex.REG_CONF_DATES)
REG_SUBMITTED = re.compile(regex.REG_SUBMITTED)

79 80
UNIVERSITY = "University"

81 82

class CheckAndFix(object):
83 84
    """A collection of tools to check and repair the content
    of the Marc12 record.
85

86 87
    """
    def __init__(self):
88

89
        self.db = current.db
90 91 92 93 94 95 96 97 98 99 100
        self.reg_institute = self._get_reg_institute()

        # private cache for my_author rescue list
        self.__par = None
        self.__reference = None

        # private cache for my authors list
        self.__my_authors = {}

    def _get_reg_institute(self):
        """
101
        Returns:
102 103
            unicode: the regular expression defining the affiliation
                of my institute.
104 105 106

        """
        # alias
107
        db = self.db
108 109 110
        app = current.app
        reg_institute = app.reg_institute

111 112
        # regular expression for the affiliation is not defined
        # build it using the affiliation keys.
113 114
        if not reg_institute:

115
            iterselect = db(db.affiliation_keys.id > 0).iterselect()
LE GAC Renaud's avatar
LE GAC Renaud committed
116 117 118
            reg_institute = \
                u"|".join(imap(
                    lambda row: u"^%(key_u)s%(key_v)s" % row, iterselect))
119 120 121 122 123 124

        return reg_institute

    def _get_author_rescue_list(self, record, id_project, id_team):
        """Get the rescue list for my authors.

125 126 127 128
        Args:
            record (RecordPubli): record describing a publication.
            id_project (int): identifier of the project in the database.
            id_team (int): identifier of the team in the database.
129

130 131
        Returns:
            list: empty when not defined
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174

        """
        year = record.year()

        # try to recover year when not defined
        if not year:
            # published article, proceeding
            if "773" in record and "y" in record["773"]:
                year = record["773"]["y"]

            # start date of a conference
            elif "111" in record and "x" in record["111"]:
                year = record["111"]["x"]

            # end date of a conference
            elif "111" in record and "z" in record["111"]:
                year = record["111"]["z"]

            # submitted date
            elif "269" in record and "c" in record["269"]:
                year = record["269"]["c"]

            else:
                return []

        #
        # NOTE
        # keep in mind that the CheckAndfix mechanism is not yet run
        # therefore year can be a list due to erratum, ...
        #
        if isinstance(year, list):
            year.sort()
            year = year[0]

        # the value can have several format 1992, 1992-12-31, ....
        m = REG_YEAR.search(year)
        if m:
            year = m.group(1)

        else:
            return []

        # caching
LE GAC Renaud's avatar
LE GAC Renaud committed
175
        t = (year, id_project, id_team)
176 177 178 179 180
        if t == self.__par:
            return self.__reference

        # extract the list from the database
        row = self.db.my_authors(year=year,
LE GAC Renaud's avatar
LE GAC Renaud committed
181 182
                                 id_projects=id_project,
                                 id_teams=id_team)
183 184 185 186 187 188 189

        if row:
            self.__reference = row['authors'].split(', ')
        else:
            self.__reference = []

        return self.__reference
190

191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
    def _is_synonym(self, tablename, value):
        """Check that the synonym field contains *value*.

        Args:
            tablename (unicode): name of the database table
            value (unicode): value to be searched

        Returns:
            bool: ``True`` if *one* row is found, ``False`` otherwise.

        """
        db = self.db
        table = db[tablename]

        query = table.synonyms.contains(value)
        if db(query).count() == 1:
            return True

        return False

211 212 213 214
    def _recover_submitted(self, record):
        """Recover submitted date using conference, preprint or thesis
        information.

215 216
        Args:
            record (RecordPubli): record describing a publication.
217

218 219
        Returns:
            unicode: empty when procedure failed
220 221 222

        """
        val = u''
223
        if isinstance(record, RecordConf):
224 225

            # INSPIREHEP start date encoded as 2014-12-31
226 227
            if "x" in record[u"111"]:
                val = record[u"111"]["x"]
228 229

            # CDS end date encoded as 20141231
230 231
            elif "z" in record[u"111"]:
                val = record[u"111"]["z"]
232 233
                val = "%s-%s-%s" % (val[0:4], val[4:6], val[6:8])

234
        elif isinstance(record, RecordThesis):
235 236 237 238 239 240 241 242 243 244 245 246 247
            val = record.these_defense()

        else:
            report = record.preprint_number()
            if report:
                m_arxiv = DECODE_ARXIV.match(report)
                if m_arxiv:
                    val = "20%s-%s" % (m_arxiv.group(1), m_arxiv.group(2))

        return val

    def _repair_paper_reference(self, record):
        """Repair paper reference.
248
        The recovery procedure use the "o" field (invenio)::
249

250 251
            Eur. Phys. J. C (2014) 74:2883
            Phys. Rev. Lett. 113, 032001 (2014)
252 253 254

        in order to extract editor, volume, year and page data.

255 256
        Args:
            record (RecordPubli): record describing a publication.
257

258 259
        Raises:
            CheckException: when the repair failed.
260 261 262

        """
        # standard case
263
        if isinstance(record[u"773"], dict):
264

265
            if "o" in record[u"773"]:
266
                for reg in DECODE_REF:
267
                    m = reg.match(record[u"773"]["o"])
268
                    if m:
269 270 271 272
                        record[u"773"]["p"] = m.group("p")
                        record[u"773"]["v"] = m.group("v")
                        record[u"773"]["y"] = m.group("y")
                        record[u"773"]["c"] = m.group("c")
273 274 275 276 277
                        return

            raise CheckException(MSG_NO_REF)

        # list case -- paper with erratum
278
        elif isinstance(record[u"773"], list):
279

280
            for i in range(len(record[u"773"])):
281

282
                if "o" in record[u"773"][i]:
283 284
                    fixed = False
                    for reg in DECODE_REF:
285
                        m = reg.match(record[u"773"][i]["o"])
286
                        if m:
287 288 289 290
                            record[u"773"][i]["p"] = m.group("p")
                            record[u"773"][i]["v"] = m.group("v")
                            record[u"773"][i]["y"] = m.group("y")
                            record[u"773"][i]["c"] = m.group("c")
291 292 293 294 295 296 297 298 299 300 301 302 303
                            fixed = True
                            break

                    if not fixed:
                        raise CheckException(MSG_NO_REF)
                else:
                    raise CheckException(MSG_NO_REF)

        # case not expected
        else:
            raise CheckException(MSG_NO_REF)

    def authors(self, record):
304
        """Check that author fields are defined.
305

306 307
        Args:
            record (RecordPubli): record describing a publication.
308

309 310 311
        Raises:
            CheckException: when there is no authors or more than
                one *first author*.
312 313 314

        """

315
        if not record.is_authors():
316 317
            raise CheckException(MSG_NO_AUTHOR)

318 319
        if isinstance(record.first_author(), list):
            raise CheckException(MSG_TO_MANY_FAUTHOR)
320 321 322 323

    def clean_erratum(self, record):
        """Clean record with erratum by removing them.

324 325 326
        Note:
            After this check the editor, volume, page and
            paper year field contains one entry.
327

328 329
        Args:
            record (RecordPubli): record describing a publication.
330 331 332 333 334 335 336

        """
        if not record.is_with_erratum():
            return

        # use the simplest algorithm by selecting the first entry in the list
        # fare to assume that the article is published first.
337
        record[u"773"] = record[u"773"][0]
338 339

        # treat year and submitted date
340
        for k in (u"260", u"269"):
341 342 343 344
            if k in record and isinstance(record[k], list):
                record[k] = record[k][0]

    def collaboration(self, record):
345 346
        """Check the collaboration.
        Have a look to the synonyms when the collaboration is not well formed.
347

348 349
        Args:
            record (RecordPubli): record describing a publication.
350

351
        Raises:
352
            CheckException: when the collaboration value is defined
353
                nor entered as a synonym.
354 355 356

        """
        val = record.collaboration()
357 358 359
        if not val:
            return

360
        db = self.db
361 362 363 364 365 366

        try:
            search_synonym(db.collaborations, "collaboration", val)
        except ToolException as e:
            raise CheckException(*e.args)

367
    def country(self, record):
368
        """Check conference country.
369
        Have a look to the synonyms when the country does not exist.
370

371 372
        Args:
            record (RecordConf): record describing a talk or a proceeding.
373

374
        Raises:
375
            CheckException: when the country is not defined
376
                nor entered as a synonym.
377 378

        """
379
        if not isinstance(record, RecordConf):
380 381
            return

382
        db = self.db
383
        val = record.conference_country()
384 385 386 387 388

        try:
            search_synonym(db.countries, "country", val)
        except ToolException as e:
            raise CheckException(*e.args)
389

390
    def conference_date(self, record, host):
391
        """Check conference date.
392

393 394
        Args:
            record (RecordConf): record describing a talk or a proceeding.
395 396
            host (str): possible values ares ``cds.cern.ch``
                or ``inspirehep.net``
397

398 399
        Raises:
            CheckException: when dates are not found or not well formed.
400 401 402 403 404 405

        """
        # conference information are available, i.e proceeding
        if not isinstance(record, RecordConf):
            return

406 407 408 409 410 411 412 413 414
        # inspirehep.net
        if host == "inspirehep.net":
            value = record.conference_dates()
            if len(value) == 0:
                raise CheckException(MSG_NO_CONF_DATE)

            return

        # cds.cern.ch
415
        if not (u"111" in record and "d" in record[u"111"]):
416
                raise CheckException(MSG_NO_CONF_DATE)
417

418
        value = record[u"111"]["d"]
419

420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
        m = REG_CONF_DATES.match(value)
        if not m:

            # 12 - 15 Mar 2014 or 29 Feb - 1 Mar 2014
            m1 = REG_CONF_DATES_1.match(value)
            m2 = REG_CONF_DATES_2.match(value)

            if m1:
                record[u"111"]["d"] = "%s-%s %s %s" % m1.groups()

            elif m2:
                record[u"111"]["d"] = "%s %s - %s %s %s" % m2.groups()

            else:
                raise CheckException(MSG_WELL_FORMED_CONF_DATES)

436
    def is_bad_oai_used(self, record):
437 438 439
        """Bad OAI is when the ``id`` in the OAI field is different from
        the ``record id``. This happens when an old record is redirected
        to new one.
440

441 442
        Args:
            record (RecordPubli): record describing a publication.
443

444 445 446
        Returns:
            bool: ``True`` when a record is found in the database with
                the bad OAI.
447

448 449 450 451
        """
        value = record.oai()
        match = REG_OAI.match(value)

452
        if match.group(2) != record.id():
453 454
            db = self.db

455
            # a record with the bad OAI exists in the database
456 457 458
            bad_oai_url = OAI_URL % (match.group(1), match.group(2))
            if get_id(db.publications, origin=bad_oai_url):
                return True
459

460
        return False
461

462 463 464
    def format_authors(self, record, func):
        """Format the author names using the function func.

465 466 467
        Args:
            record (RecordPubli): record describing a publication.
            func (reference): function used to format the author names.
468 469

        """
470
        for key in (u"100", u"700"):
471 472
            if key in record:
                if isinstance(record[key], list):
473
                    for i in xrange(len(record[key])):
474
                        if "a" in record[key][i]:
475 476 477 478 479 480 481 482 483 484 485

                            # PROTECTION
                            # see RecordPubli.author_as_list
                            value = record[key][i]["a"]
                            if isinstance(value, unicode):
                                record[key][i]["a"] = func(value)

                            elif isinstance(value, list):
                                for elt in value:
                                    if REG_AUTHOR.match(elt):
                                        record[key][i]["a"] = func(elt)
486 487

                else:
488
                    if "a" in record[key]:
489 490 491 492 493 494 495 496 497 498 499
                        value = record[key]["a"]

                        # PROTECTION
                        # see RecordPubli.authors_as_list
                        if isinstance(value, unicode):
                            record[key]["a"] = func(value)

                        elif isinstance(value, list):
                            for elt in value:
                                if REG_AUTHOR.match(elt):
                                    record[key][i]["a"] = func(elt)
500 501

    def format_editor(self, record):
502 503
        """Format the editor abbreviation. The encoding
        depends on the store::
504

505 506
            INVENIO:    Phys. Lett. B + volume 673
            INSPIREHEP: Phys.Lett + volume B673
507

508
        Standardise the answer as ``Phys. Lett. B``.
509

510 511
        Note:
            It is recommended to call this method when erratum are removed.
512

513 514
        Args:
            record (RecordPubli): record describing a publication.
515

516 517
        Raises:
            CheckException: when the editor is not well formed.
518 519 520 521 522 523

        """
        if not record.is_published():
            return

        # standard case
524 525
        if isinstance(record[u"773"], dict):
            if "p" in record[u"773"] and "v" in record[u"773"]:
526

527 528
                editor = record[u"773"]["p"]
                volume = record[u"773"]["v"]
529 530 531 532 533 534 535 536 537 538 539

                # add space after the dot  Phys.Rev -> Phys. Rev
                editor = re.sub(r'\.([A-Z])', r'. \1', editor)

                # get the volume letter
                m = re.match(r'([A-Z]+) *(\d+)', volume)
                if m and m.group(1) != editor[-1]:
                    editor = "%s %s" % (editor, m.group(1))
                    volume = m.group(2)

                # remove stupid mistake
540
                editor = CLEAN_SPACES(editor)
541

542 543
                record[u"773"]["p"] = editor
                record[u"773"]["v"] = volume
544 545

        # list case -- publication with erratum
546
        elif isinstance(record[u"773"], list):
547

548 549
            editors = record._get(u"773", 'p', force_list=True)
            volumes = record._get(u"773", 'v', force_list=True)
550 551 552 553 554 555 556 557 558 559 560 561 562 563

            if len(editors) != len(volumes):
                raise CheckException(MSG_WELL_FORMED_EDITOR)

            for i in range(len(editors)):
                # add space after the dot  Phys.Rev -> Phys. Rev
                editor = re.sub(r'\.([A-Z])', r'. \1', editors[i])

                # get the volume letter
                m = re.match(r'([A-Z]+) *(\d+)', volumes[i])
                if m and m.group(1) != editor[-1]:
                    editor = "%s %s" % (editor, m.group(1))
                    volume = m.group(2)

564
                editor = CLEAN_SPACES(editor)
565

566 567
                record[u"773"][i]["p"] = editor
                record[u"773"][i]["v"] = volume
568

569 570 571
    def format_universities(self, record):
        """Format the name of the university for PhD:

572 573
            * Fix the name of Aix-Marseille University
            * Replace U. by University
574

575 576
        Args:
            record (RecordThesis): record describing a thesis.
577 578 579

        """
        # protection
580
        if not isinstance(record, RecordThesis):
581 582
            return

LE GAC Renaud's avatar
LE GAC Renaud committed
583
        is_cppm = self._get_reg_institute().find("CPPM") != -1
584

585
        # CPPM: fix the name of Aix-Marseille university
586
        if is_cppm:
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621

            year = REG_YEAR.search(record.these_defense()).group(1)
            if int(year) < 2012:
                university = u"Université de la Méditerrannée Aix-Marseille II"
            else:
                university = u"Aix Marseille Université"

            if u'502' in record and "b" in record[u'502']:
                if isinstance(record[u'502']['b'], unicode):
                    if "Marseille" in record[u'502']['b']:
                        record[u'502']['b'] = university

                elif isinstance(record[u'502']['b'], list):
                    for i in xrange(len(record[u'502']['b'])):
                        if "Marseille" in record[u'502']['b'][i]:
                            record[u'502']['b'][i] = university

        # Other: replace U. by University
        else:
            university = current.T(UNIVERSITY).decode("utf8")

            if u'502' in record and "b" in record[u'502']:
                if isinstance(record[u'502']['b'], unicode):
                    value = record[u'502']['b']
                    if "U." in value:
                        value = value.replace('U.', university)
                        record[u'502']['b'] = value

                elif isinstance(record[u'502']['b'], list):
                    for i in xrange(len(record[u'502']['b'])):
                        value = record[u'502']['b'][i]
                        if "U." in value:
                            value = value.replace('U.', university)
                            record[u'502']['b'][i] = value

622 623
    def get_my_authors(self, record, cmpFct=None):
        """Get authors of my institutes signing the record.
624 625
        The information is append to the Record object via the attribute
        ``my_authors``.
626

627 628 629 630 631
        Args:
            record (RecordPubli): record describing a publication.
            cmpFct (reference): extract the family name from the full name.
                It is used to sort my author list according to the
                author family name.
632

633 634
        Returns:
            unicode: the list of authors separated by comma
635

636 637
        Raises:
            CheckException: when the list is empty
638 639 640 641

        """
        # might have been computed when affiliation is checked
        rec_id = record.id()
LE GAC Renaud's avatar
LE GAC Renaud committed
642
        if rec_id in self.__my_authors:
643 644 645 646 647 648 649 650 651 652 653 654
            li = self.__my_authors[rec_id]
            li.sort(key=cmpFct)
            value = u', '.join(li)

        # find authors of my institute signing the record
        else:
            reg_institute = self.reg_institute
            value = record.find_authors_by_affiliation(reg_institute, cmpFct)

        if not value:
            raise CheckException(MSG_NO_MY_AUTHOR)

LE GAC Renaud's avatar
LE GAC Renaud committed
655
        record.my_authors = value
656

657 658 659
    def is_conference(self, record):
        """Check that the record described a conference talk / proceeding.

660 661
        Args:
            record (RecordPubli): record describing a publication.
662

663 664
        Raises:
            CheckException: when the record is not associated to a conference.
665 666 667 668 669 670

        """
        if not isinstance(record, RecordConf):
            raise CheckException(MSG_NO_CONF)

    def is_thesis(self, record):
671
        """Check that the record described a thesis.
672

673 674
        Args:
            record (RecordPubli): record describing a publication.
675

676 677
        Raises:
            CheckException: when the record does not describe a thesis.
678 679 680 681 682

        """
        if not isinstance(record, RecordThesis):
            raise CheckException(MSG_NO_THESIS)

683 684 685 686 687
    def my_affiliation(self,
                       record,
                       id_project,
                       id_team,
                       func=format_author_fr):
688 689 690 691
        """Check that authors of my institute are signatories.

        Launch a recovery procedure when affiliations are not defined.
        It is based on the author rescue list stored in the database.
692

693 694 695 696
        Args:
            record (RecordPubli): record describing a publication.
            id_project (int): identifier of the project in the database
            id_team (int): identifier of the team in the database
697
            func (reference): function used to format the author names.
698

699 700
        Raises:
            CheckException: when there is no authors from my institute.
701 702

        """
703 704 705
        value = record.find_affiliation(self.reg_institute)
        if value:
            return value
706

707 708 709 710 711
        # affiliation is not defined
        # try to recover using the authors rescue list
        rescue_list = self._get_author_rescue_list(record, id_project, id_team)
        if not rescue_list:
            raise CheckException(MSG_NO_MY_AUTHOR)
712

713
        # format the author in the same way as the rescue list
714
        # compute the intersection between the authors and the rescue list
715 716 717 718 719 720 721
        df = (DataFrame(record.authors_as_list(), columns=["raw_author"])
              .assign(format_author=lambda x:
                      x.raw_author.apply(lambda y: func(y)))
              .set_index("format_author"))

        rescue_list = [el.decode("utf-8") for el in rescue_list]
        intersection = df.index & rescue_list
722

723
        if intersection.size == 0:
724
            raise CheckException(MSG_NO_MY_AUTHOR)
725

726
        # cache the result for a latter use
727
        self.__my_authors[record.id()] = intersection.values.tolist()
728 729 730 731 732

    def paper_reference(self, record):
        """Check that editor, page, volume and paper year are defined
        for a published paper. Repair it as far as possible.

733 734 735
        Note:
            It is recommended to call this method when the
            erratum are removed.
736

737 738
        Args:
            record (RecordPubli): record describing a publication.
739

740 741
        Raises:
            CheckException: when the paper reference is not well formed.
742 743 744 745 746 747

        """
        if not record.is_published():
            return

        # list of reference (paper with erratum)
748 749
        refs = record[u"773"]
        if not isinstance(record[u"773"], list):
750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777
            refs = [refs]

        # INSPIREHEP
        # fix the following case:
        #    {'p': u'Phys.Lett.B'},
        #    {'y': u'2013', 'p': u'Phys.Lett.B', 'c': u'6-12', 'v': u'B720'}

        if len(refs) == 2 and record.host().startswith('inspirehep'):
            nkeys = [len(di) for di in refs]
            if nkeys.count(1):
                index = nkeys.index(1)
                if 'p' in refs[index]:
                    refs.pop(index)

        # do we have all fields defining a reference
        # editor, volume, year and page
        for ref in refs:

            # proceeding can only contains "w" and "y" keys
            if "w" in ref:
                continue

            # check full reference
            for k in ("p", "v", "y", "c"):
                if k not in ref:
                    self._repair_paper_reference(record)
                    return

778 779 780 781 782 783 784 785
    def publisher(self, record):
        """Check publisher.
        Have a look to the synonyms when the publisher does not exist.

        Args:
            record (RecordPubli): record describing a publication.

        Raises:
786
            CheckException: when the publisher is not defined
787
                nor entered as a synonym.
788 789 790 791 792 793 794 795

        """
        db = self.db
        val = record.paper_editor()
        if not val:
            return

        # erratum -- check the first entry
796
        if isinstance(val, list):
797 798
            val = val[0]

799 800 801 802 803
        # convert ToolException to CheckExcpetion
        try:
            search_synonym(db.publishers, "abbreviation", val)
        except ToolException as e:
            raise CheckException(*e.args)
804

805 806 807 808
    def recover_oai(self, record, host):
        """Recover the OAI identifier when it is not defined
        or not well form.

809 810 811 812
        Args:
            record (RecordPubli): record describing a publication.
            host (unicode): possible values ares ``cds.cern.ch``
                or ``inspirehep.net``
813 814

        """
LE GAC Renaud's avatar
LE GAC Renaud committed
815 816 817 818 819 820 821
        # Note:
        # For the record cds 1951625, possible values are:
        # oai:cds.cern.ch:1951625 (if it does not exist in inspirehep)
        # oai:cds.cern.ch:1951625, oai:inspirehep.net:1319638 (if it exist
        # in both store)
        # In all the case the first OAI corresponds to the record.id()
        #
822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839
        oai = record.oai()
        if oai is not None and REG_OAI.match(oai):
            return

        if host == "cds.cern.ch":
            field, subfield = u"0248", "a"

        elif host == "inspirehep.net":
            field, subfield = u"909CO", "o"

        else:
            raise ValueError(MSG_INVALID_HOST)

        if field not in record:
            record[field] = dict()

        record[field][subfield] = OAI_INVENIO % (host, record.id())

840
    def submitted(self, record):
841
        """Standardise the submitted date as ``YYYY-MM`` or ``YYYY-MM-DD``.
842 843
        Look for alternative when it is not defined.

844 845
        Note:
            After this check the year submitted contains one entry.
846

847 848
        Args:
            record (RecordPubli): record describing a publication.
849

850 851 852
        Raises:
            CheckException: when the date is not well formed or when more
                than one date are found.
853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869

        """
        dates = record.submitted()

        # recover missing date using conference, preprint, thesis information
        if not dates:
            val = self._recover_submitted(record)
            if not val:
                raise CheckException(MSG_NO_DATE)
            dates.append(val)

        # check that date are well formed
        for i in range(len(dates)):

            # 22 Mar 2011
            m = DECODE_DD_MMM_YYYY.match(dates[i])
            if m:
870 871
                data = (m.group(3), MONTHS[m.group(2)], int(m.group(1)))
                dates[i] = '%s-%s-%02i' % data
872 873 874 875 876
                continue

            # 22 03 2011
            m = DECODE_DD_MM_YYYY.match(dates[i])
            if m:
LE GAC Renaud's avatar
LE GAC Renaud committed
877
                data = (m.group(3), int(m.group(2)), int(m.group(1)))
878
                dates[i] = '%s-%02i-%02i' % data
879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897
                continue

            # 2011
            m_year = DECODE_YYYY.match(dates[i])
            if m_year:
                dates[i] = self._recover_submitted(record)

            # check the minimum requirement is 2001-05
            if not REG_SUBMITTED.match(dates[i]):
                raise CheckException(MSG_WELL_FORMED_DATE)

        # protection against list of identical date
        if len(dates) > 1:
            dates = list(set(dates))

        # Only one date
        if len(dates) != 1:
            raise CheckException(MSG_TO_MANY_DATE)

898
        if u"269" not in record or isinstance(record[u"269"], list):
899 900 901 902 903 904 905
            record[u"269"] = dict()

        record[u"269"]["c"] = dates[0]

    def temporary_record(self, record):
        """Some records are marked temporary.

906 907
        Args:
            record (RecordPubli): record describing a publication.
908

909 910
        Raises:
            CheckException: when the record is marked temporary
911 912 913

        """
        # found on INSPIREHEP (see record 1317573)
914 915
        if u"500" in record and "a" in record[u"500"]:
            if record[u"500"]["a"] == u"*Temporary record*":
916 917 918
                raise CheckException(MSG_TEMPORARY_RECORD)

    def year(self, record):
919
        """Standardise the the year as ``YYYY`` and look for alternative when
920 921
        it is not defined.

922 923
        Note:
            The method assumes that the erratum are removed.
924

925 926 927 928
        Note:
            It is recommended to call this method after
            the ``submitted`` one, since the submitted field is used in
            the recovery procedure.
929

930 931
        Note:
            After this check the year field contains one entry.
932

933 934
        Args:
            record (RecordPubli): record describing a publication.
935

936 937
        Raises:
            CheckException: when there is a list of year or when empty.
938 939 940 941 942

        """
        val = ''

        # protection against "publication date YYYY-MM-DD"
943
        li = record._get(u"260", 'c', force_list=True)
944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969
        li = [el for el in li if REG_YEAR.match(el)]

        if len(li) == 1:
            val = li[0]
        elif len(li) > 1:
            raise CheckException(MSG_TO_MANY_YEAR)

        # alternative: look to the year in the publication reference
        if not val:
            val = record.paper_year()

        # alternative: look to the submitted date
        if not val:
            val = record.submitted()

        # protection against remaining list
        if isinstance(val, list):
            if len(val) == 1:
                val = val[0]
            else:
                raise CheckException(MSG_TO_MANY_YEAR)

        # the value can have several format 1992, 1992-12-31, .... standardize
        if val:
            m = REG_YEAR.search(val)
            if m:
970 971
                if u"260" in record and isinstance(record[u"260"], dict):
                    record[u"260"]["c"] = m.group(1)
972
                else:
973
                    record[u"260"] = {"c": m.group(1)}
974 975 976
                return

        raise CheckException(MSG_NO_YEAR)