aboutsummaryrefslogtreecommitdiffstats
path: root/extra/fixups/fixup_longtail_issnl_unique.py
blob: 2493a33264791998a9db2ccc815352fce2765ea7 (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
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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
#!/usr/bin/env python3

"""
This file must be moved to the fatcat:python/ directory (aka, not in
fatcat:extra/fixups) to run. It's a "one-off", so probably will bitrot pretty
quickly. There are no tests.

Example invocation:

    zcat /srv/fatcat/datasets/2018-09-23-0405.30-dumpgrobidmetainsertable.longtail_join.filtered.tsv.gz | ./fixup_longtail_issnl_unique.py /srv/fatcat/datasets/single_domain_issnl.tsv -

See also:
- bnewbold/scratch:mellon/201904_longtail_issn.md
- aitio:/rapida/OA-JOURNAL-TESTCRAWL-TWO-2018
- https://archive.org/details/OA-JOURNAL-TESTCRAWL-TWO-2018-extra
= https://archive.org/download/ia_longtail_dumpgrobidmetainsertable_2018-09-23/2018-09-23-0405.30-dumpgrobidmetainsertable.longtail_join.filtered.tsv.gz


"""

import os, sys, argparse
import json
import sqlite3
import itertools

import fatcat_client
from fatcat_tools import authenticated_api
from fatcat_tools.importers.common import EntityImporter, clean, LinePusher
from fatcat_tools.importers.arabesque import b32_hex


class LongtailIssnlSingleDomainFixup(EntityImporter):
    """
    Fixup script for bootstrap longtail OA release entities which don't have a
    container but are confidently associated with an ISSN-L based on file
    domain.

    Expected to be a one-time fixup impacting about 600k entities (around half
    the longtail OA batch).

    Reads in a mapping of unique domain-ISSNL mappings, and then iterates over
    the original matched import batch file. For each line in the later:
    
    - checks if in-scope based on domain-ISSNL map
    - uses API to lookup file (by SHA-1) and confirm domain in URL list
    - look up releases for file and retain the longtail-oa ones (an extra flag)
    - if release is longtail-oa and no container, set the container based on
      ISSN-L (using cached lookup)
    - use EntityImporter stuff to manage update/editgroup queue
    """

    def __init__(self, api, domain_issnl_tsv_file, **kwargs):

        eg_desc = kwargs.pop('editgroup_description',
            "Fixup for longtail OA releases that can be matched to specific container by file domain / ISSN-L mapping")
        eg_extra = kwargs.pop('editgroup_extra', dict())
        eg_extra['agent'] = eg_extra.get('agent', 'fatcat_tools.LongtailIssnlSingleDomainFixup')
        super().__init__(api,
            editgroup_description=eg_desc,
            editgroup_extra=eg_extra,
            **kwargs)

        self._domain_issnl_map = self.load_domain_issnl(domain_issnl_tsv_file)
        self._issnl_container_map = dict()

    def load_domain_issnl(self, tsv_file):
        print("Loading domain ISSN-L file...")
        m = dict()
        for l in tsv_file:
            l = l.strip().split('\t')
            assert len(l) == 2
            domain = l[0].lower()
            issnl = l[1]
            assert len(issnl) == 9 and issnl[4] == '-'
            m[domain] = issnl
        print("Got {} matchings.".format(len(m)))
        return m

    def want(self, raw_record):
        # do it all in parse_record()
        return True

    def parse_record(self, row):
        """
        TSV rows:
        - sha1 b32 key
        - JSON string: CDX-ish
            - surt
            - url
            - <etc>
        - mime
        - size (?)
        - JSON string: grobid metadata
        """

        # parse row
        row = row.split('\t')
        assert len(row) == 5
        sha1 = b32_hex(row[0][5:])
        cdx_dict = json.loads(row[1])
        url = cdx_dict['url']
        domain = url.split('/')[2].lower()

        # domain in scope?
        issnl = self._domain_issnl_map.get(domain)
        if not issnl:
            self.counts['skip-domain-scope'] += 1
            return None

        # lookup file
        #print(sha1)
        try:
            file_entity = self.api.lookup_file(sha1=sha1)
        except fatcat_client.rest.ApiException as err:
            if err.status == 404:
                self.counts['skip-file-not-found'] += 1
                return None
            else:
                raise err

        # container ident
        container_id = self.lookup_issnl(issnl)
        if not container_id:
            self.counts['skip-container-not-found'] += 1
            return None

        # confirm domain
        url_domain_match = False
        for furl in file_entity.urls:
            fdomain = furl.url.split('/')[2].lower()
            if domain == fdomain:
                url_domain_match = True
                break
        if not url_domain_match:
            self.counts['skip-no-domain-match'] += 1
            return None

        # fetch releases
        releases = self.api.get_file_releases(file_entity.ident)
        releases = [r for r in releases if (r.extra.get('longtail-oa') == True and r.container_id == None)]
        if not releases:
            self.counts['skip-no-releases'] += 1
            return None

        # set container_id
        for r in releases:
            r.container_id = container_id
        return releases

    def try_update(self, re_list):
        for re in re_list:
            self.api.update_release(re.ident, re, editgroup_id=self.get_editgroup_id())
            self.counts['update'] += 1
        return False

    def insert_batch(self, batch):
        raise NotImplementedError

def run_fixup(args):
    fmi = LongtailIssnlSingleDomainFixup(args.api,
        args.domain_issnl_tsv_file,
        edit_batch_size=args.batch_size)
    LinePusher(fmi, args.insertable_tsv_file).run()

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--api-host-url',
        default="http://localhost:9411/v0",
        help="connect to this host/port")
    parser.add_argument('--batch-size',
        help="size of batch to send",
        default=50, type=int)
    parser.add_argument('domain_issnl_tsv_file',
        help="domain/ISSNL mapping TSV file",
        type=argparse.FileType('r'))
    parser.add_argument('insertable_tsv_file',
        help="dumpgrobidmetainsertable TSV file to work over",
        default=sys.stdin, type=argparse.FileType('r'))

    auth_var = "FATCAT_AUTH_SANDCRAWLER"

    args = parser.parse_args()

    args.api = authenticated_api(
        args.api_host_url,
        # token is an optional kwarg (can be empty string, None, etc)
        token=os.environ.get(auth_var))
    run_fixup(args)

if __name__ == '__main__':
    main()