aboutsummaryrefslogtreecommitdiffstats
path: root/python/scripts/oai2ingestrequest.py
blob: 9607b8589f8ae95a7a5f0ff592bf900dc4fe3411 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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
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
#!/usr/bin/env python3
"""
Transform an OAI-PMH bulk dump (JSON) into ingest requests.

Eg: https://archive.org/details/oai_harvest_20200215
"""

import argparse
import json
import sys

import urlcanon

DOMAIN_BLOCKLIST = [
    # large OA publishers (we get via DOI)
    # large repos and aggregators (we crawl directly)
    "://arxiv.org/",
    "://europepmc.org/",
    "ncbi.nlm.nih.gov/",
    "semanticscholar.org/",
    "://doi.org/",
    "://dx.doi.org/",
    "zenodo.org/",
    "figshare.com/",
    "://archive.org/",
    ".archive.org/",
    "://127.0.0.1/",
    # OAI specific additions
    "://hdl.handle.net/",
]

RELEASE_STAGE_MAP = {
    "info:eu-repo/semantics/draftVersion": "draft",
    "info:eu-repo/semantics/submittedVersion": "submitted",
    "info:eu-repo/semantics/acceptedVersion": "accepted",
    "info:eu-repo/semantics/publishedVersion": "published",
    "info:eu-repo/semantics/updatedVersion": "updated",
}


def canon(s):
    parsed = urlcanon.parse_url(s)
    return str(urlcanon.whatwg(parsed))


def transform(obj):
    """
    Transforms from a single OAI-PMH object to zero or more ingest requests.
    Returns a list of dicts.
    """

    requests = []
    if not obj.get("oai") or not obj["oai"].startswith("oai:"):
        return []
    if not obj.get("urls"):
        return []

    # look in obj['formats'] for PDF?
    if obj.get("formats"):
        # if there is a list of formats, and it does not contain PDF, then
        # skip. Note that we will continue if there is no formats list.
        has_pdf = False
        for f in obj["formats"]:
            if "pdf" in f.lower():
                has_pdf = True
        if not has_pdf:
            return []

    doi = None
    if obj.get("doi"):
        doi = obj["doi"][0].lower().strip()
        if not doi.startswith("10."):
            doi = None

    # infer release stage and/or type from obj['types']
    release_stage = None
    for t in obj.get("types", []):
        if t in RELEASE_STAGE_MAP:
            release_stage = RELEASE_STAGE_MAP[t]

    # TODO: infer rel somehow? Eg, repository vs. OJS publisher
    rel = None

    for url in obj["urls"]:
        skip = False
        for domain in DOMAIN_BLOCKLIST:
            if domain in url:
                skip = True
        if skip:
            continue
        try:
            base_url = canon(url)
        except UnicodeEncodeError:
            continue

        request = {
            "base_url": base_url,
            "ingest_type": "pdf",
            "link_source": "oai",
            "link_source_id": obj["oai"].lower(),
            "ingest_request_source": "metha-bulk",
            "release_stage": release_stage,
            "rel": rel,
            "ext_ids": {
                "doi": doi,
                "oai": obj["oai"].lower(),
            },
            "edit_extra": {},
        }
        requests.append(request)

    return requests


def run(args):
    for l in args.json_file:
        if not l.strip():
            continue
        row = json.loads(l)

        requests = transform(row) or []
        for r in requests:
            print("{}".format(json.dumps(r, sort_keys=True)))


def main():
    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument(
        "json_file",
        help="OAI-PMH dump file to use (usually stdin)",
        type=argparse.FileType("r"),
    )
    subparsers = parser.add_subparsers()

    args = parser.parse_args()

    run(args)


if __name__ == "__main__":
    main()