/
wikidata_bot.py
730 lines (613 loc) · 22.4 KB
/
wikidata_bot.py
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
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
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""A `Wikidata bot <https://www.wikidata.org/wiki/Wikidata:Bots>`_ that adds, deletes, or deprecates referenced statements.
Here are typical output examples.
:func:`add_identifiers`
| *Claim:* `Joey Ramone <https://www.wikidata.org/wiki/Q312387>`_, `Discogs artist ID <https://www.wikidata.org/wiki/Property:P1953>`_, `264375 <https://www.discogs.com/artist/264375>`_
| *Reference:* `stated in <https://www.wikidata.org/wiki/Property:P248>`_, `Discogs <https://www.wikidata.org/wiki/Q504063>`_), (`retrieved <https://www.wikidata.org/wiki/Property:P813>`_, TIMESTAMP
:func:`add_people_statements`
| *Claim:* `Joey Ramone <https://www.wikidata.org/wiki/Q312387>`_, `member of <https://www.wikidata.org/wiki/Property:P463>`_, `Ramones <https://www.wikidata.org/wiki/Q483407>`_
| *Reference:* `stated in <https://www.wikidata.org/wiki/Property:P248>`_, `Discogs <https://www.wikidata.org/wiki/Q504063>`_), (`retrieved <https://www.wikidata.org/wiki/Property:P813>`_, TIMESTAMP
:func:`add_works_statements`
| *Claim:* `Leave Home <https://www.wikidata.org/wiki/Q1346637>`_, `performer <https://www.wikidata.org/wiki/Property:P175>`_, `Ramones <https://www.wikidata.org/wiki/Q483407>`_
| *Reference:* `stated in <https://www.wikidata.org/wiki/Property:P248>`_, `Discogs <https://www.wikidata.org/wiki/Q504063>`_), (`Discogs artist ID <https://www.wikidata.org/wiki/Property:P1953>`_, `264375 <https://www.discogs.com/artist/264375>`_), (`retrieved <https://www.wikidata.org/wiki/Property:P813>`_, TIMESTAMP
:func:`delete_or_deprecate_identifiers`
deletes or deprecates identifier statements.
"""
__author__ = 'Marco Fossati'
__email__ = 'fossati@spaziodati.eu'
__version__ = '1.0'
__license__ = 'GPL-3.0'
__copyright__ = 'Copyleft 2018, Hjfocs'
import json
import logging
from datetime import date
from re import search
from typing import Iterable
import click
import pywikibot
from pywikibot.data.api import APIError
from pywikibot.exceptions import NoPage
from soweego.commons import target_database
from soweego.commons.constants import QID_REGEX
from soweego.commons.keys import IMDB, TWITTER
from soweego.wikidata import vocabulary
LOGGER = logging.getLogger(__name__)
SITE = pywikibot.Site('wikidata', 'wikidata')
REPO = SITE.data_repository()
# (stated in, CATALOG) reference object
STATED_IN_REFERENCE = pywikibot.Claim(
REPO, vocabulary.STATED_IN, is_reference=True
)
# (retrieved, TIMESTAMP) reference object
TODAY = date.today()
TIMESTAMP = pywikibot.WbTime(
site=REPO,
year=TODAY.year,
month=TODAY.month,
day=TODAY.day,
precision='day',
)
RETRIEVED_REFERENCE = pywikibot.Claim(
REPO, vocabulary.RETRIEVED, is_reference=True
)
RETRIEVED_REFERENCE.setTarget(TIMESTAMP)
# We also support Twitter
SUPPORTED_TARGETS = target_database.supported_targets() ^ {TWITTER}
@click.command()
@click.argument('catalog', type=click.Choice(SUPPORTED_TARGETS))
@click.argument(
'entity', type=click.Choice(target_database.supported_entities())
)
@click.argument('invalid_identifiers', type=click.File())
@click.option(
'-s',
'--sandbox',
is_flag=True,
help='Perform all edits on the Wikidata sandbox item Q4115189.',
)
def delete_cli(catalog, entity, invalid_identifiers, sandbox):
"""Delete invalid identifiers.
INVALID_IDENTIFIERS must be a JSON file.
Format: { catalog_identifier: [ list of QIDs ] }
"""
if sandbox:
LOGGER.info('Running on the Wikidata sandbox item ...')
delete_or_deprecate_identifiers(
'delete', catalog, entity, json.load(invalid_identifiers), sandbox
)
@click.command()
@click.argument('catalog', type=click.Choice(SUPPORTED_TARGETS))
@click.argument(
'entity', type=click.Choice(target_database.supported_entities())
)
@click.argument('invalid_identifiers', type=click.File())
@click.option(
'-s',
'--sandbox',
is_flag=True,
help='Perform all edits on the Wikidata sandbox item Q4115189.',
)
def deprecate_cli(catalog, entity, invalid_identifiers, sandbox):
"""Deprecate invalid identifiers.
INVALID_IDENTIFIERS must be a JSON file.
Format: { catalog_identifier: [ list of QIDs ] }
"""
if sandbox:
LOGGER.info('Running on the Wikidata sandbox item ...')
delete_or_deprecate_identifiers(
'deprecate', catalog, entity, json.load(invalid_identifiers), sandbox
)
@click.command()
@click.argument('catalog', type=click.Choice(SUPPORTED_TARGETS))
@click.argument(
'entity', type=click.Choice(target_database.supported_entities())
)
@click.argument('identifiers', type=click.File())
@click.option(
'-s',
'--sandbox',
is_flag=True,
help='Perform all edits on the Wikidata sandbox item Q4115189.',
)
def identifiers_cli(catalog, entity, identifiers, sandbox):
"""Add identifiers.
IDENTIFIERS must be a JSON file.
Format: { QID: catalog_identifier }
If the identifier already exists, just add a reference.
Example:
$ echo '{ "Q446627": "266995" }' > rhell.json
$ python -m soweego ingester identifiers discogs musician rhell.json
Result:
claim (Richard Hell, Discogs artist ID, 266995)
reference (stated in, Discogs), (retrieved, today)
"""
if sandbox:
LOGGER.info('Running on the Wikidata sandbox item ...')
add_identifiers(json.load(identifiers), catalog, entity, sandbox)
@click.command()
@click.argument('catalog', type=click.Choice(SUPPORTED_TARGETS))
@click.argument('statements', type=click.File())
@click.option(
'-s',
'--sandbox',
is_flag=True,
help='Perform all edits on the Wikidata sandbox item Q4115189.',
)
def people_cli(catalog, statements, sandbox):
"""Add statements to Wikidata people.
STATEMENTS must be a CSV file.
Format: person_QID, PID, value
If the claim already exists, just add a reference.
Example:
$ echo Q312387,P463,Q483407 > joey.csv
$ python -m soweego ingester people discogs joey.csv
Result:
claim (Joey Ramone, member of, Ramones)
reference (stated in, Discogs), (retrieved, today)
"""
stated_in = target_database.get_catalog_qid(catalog)
if sandbox:
LOGGER.info('Running on the Wikidata sandbox item ...')
for statement in statements:
person, predicate, value = statement.rstrip().split(',')
if sandbox:
_add_or_reference(vocabulary.SANDBOX_1, predicate, value, stated_in)
else:
_add_or_reference(person, predicate, value, stated_in)
@click.command()
@click.argument('catalog', type=click.Choice(SUPPORTED_TARGETS))
@click.argument('statements', type=click.File())
@click.option(
'-s',
'--sandbox',
is_flag=True,
help='Perform all edits on the Wikidata sandbox item Q4115189.',
)
def works_cli(catalog, statements, sandbox):
"""Add statements to Wikidata works.
STATEMENTS must be a CSV file.
Format: work_QID, PID, person_QID, person_target_ID
If the claim already exists, just add a reference.
Example:
$ echo Q4354548,P175,Q5969,139984 > cmon.csv
$ python -m soweego ingester works discogs cmon.csv
Result:
claim (C'mon Everybody, performer, Eddie Cochran)
reference (stated in, Discogs), (Discogs artist ID, 139984), (retrieved, today)
"""
catalog_qid, is_imdb, person_pid = _get_works_args(catalog)
if sandbox:
LOGGER.info('Running on the Wikidata sandbox item ...')
for statement in statements:
work, predicate, person, person_tid = statement.rstrip().split(',')
if sandbox:
_add_or_reference_works(
vocabulary.SANDBOX_1,
predicate,
person,
catalog_qid,
person_pid,
person_tid,
is_imdb,
)
else:
_add_or_reference_works(
work,
predicate,
person,
catalog_qid,
person_pid,
person_tid,
is_imdb,
)
def add_identifiers(
identifiers: dict, catalog: str, entity: str, sandbox: bool
) -> None:
"""Add identifier statements to existing Wikidata items.
:param identifiers: a ``{QID: catalog_identifier}`` dictionary
:param catalog: ``{'discogs', 'imdb', 'musicbrainz', 'twitter'}``.
A supported catalog
:param entity: ``{'actor', 'band', 'director', 'musician', 'producer',
'writer', 'audiovisual_work', 'musical_work'}``.
A supported entity
:param sandbox: whether to perform edits on the
`Wikidata sandbox <https://www.wikidata.org/wiki/Q4115189>`_ item
"""
catalog_qid = target_database.get_catalog_qid(catalog)
catalog_pid = target_database.get_catalog_pid(catalog, entity)
for qid, tid in identifiers.items():
LOGGER.info('Processing %s match: %s -> %s', catalog, qid, tid)
if sandbox:
LOGGER.debug(
'Using Wikidata sandbox item %s as subject, instead of %s',
vocabulary.SANDBOX_1,
qid,
)
_add_or_reference(
vocabulary.SANDBOX_1, catalog_pid, tid, catalog_qid
)
else:
_add_or_reference(qid, catalog_pid, tid, catalog_qid)
def add_people_statements(
statements: Iterable, catalog: str, sandbox: bool
) -> None:
"""Add statements to existing Wikidata people.
Statements typically come from validation criteria 2 or 3
as per :func:`soweego.validator.checks.links` and
:func:`soweego.validator.checks.bio`.
:param statements: iterable of (subject, predicate, value) triples
:param catalog: ``{'discogs', 'imdb', 'musicbrainz', 'twitter'}``.
A supported catalog
:param sandbox: whether to perform edits on the
`Wikidata sandbox <https://www.wikidata.org/wiki/Q4115189>`_ item
"""
catalog_qid = target_database.get_catalog_qid(catalog)
for subject, predicate, value in statements:
LOGGER.info(
'Processing (%s, %s, %s) statement', subject, predicate, value
)
if sandbox:
_add_or_reference(
vocabulary.SANDBOX_1, predicate, value, catalog_qid
)
else:
_add_or_reference(subject, predicate, value, catalog_qid)
def add_works_statements(
statements: Iterable, catalog: str, sandbox: bool
) -> None:
"""Add statements to existing Wikidata works.
Statements typically come from
:func:`soweego.validator.enrichment.generate_statements`.
:param statements: iterable of
(work QID, predicate, person QID, person target ID) tuples
:param catalog: ``{'discogs', 'imdb', 'musicbrainz', 'twitter'}``.
A supported catalog
:param sandbox: whether to perform edits on the
`Wikidata sandbox <https://www.wikidata.org/wiki/Q4115189>`_ item
"""
catalog_qid, is_imdb, person_pid = _get_works_args(catalog)
for work, predicate, person, person_tid in statements:
LOGGER.info(
'Processing (%s, %s, %s) statement', work, predicate, person
)
if sandbox:
_add_or_reference_works(
vocabulary.SANDBOX_1,
predicate,
person,
catalog_qid,
person_pid,
person_tid,
is_imdb=is_imdb,
)
else:
_add_or_reference_works(
work,
predicate,
person,
catalog_qid,
person_pid,
person_tid,
is_imdb=is_imdb,
)
def delete_or_deprecate_identifiers(
action: str, catalog: str, entity: str, invalid: dict, sandbox: bool
) -> None:
"""Delete or deprecate invalid identifier statements
from existing Wikidata items.
Deletion candidates come from validation criterion 1
as per :func:`soweego.validator.checks.dead_ids`.
Deprecation candidates come from validation criteria 2 or 3
as per :func:`soweego.validator.checks.links` and
:func:`soweego.validator.checks.bio`.
:param action: {'delete', 'deprecate'}
:param catalog: ``{'discogs', 'imdb', 'musicbrainz', 'twitter'}``.
A supported catalog
:param entity: ``{'actor', 'band', 'director', 'musician', 'producer',
'writer', 'audiovisual_work', 'musical_work'}``.
A supported entity
:param invalid: a ``{invalid_catalog_identifier: [list of QIDs]}`` dictionary
:param sandbox: whether to perform edits on the
`Wikidata sandbox <https://www.wikidata.org/wiki/Q4115189>`_ item
"""
catalog_pid = target_database.get_catalog_pid(catalog, entity)
for tid, qids in invalid.items():
for qid in qids:
LOGGER.info(
'Will %s %s identifier: %s -> %s', action, catalog, tid, qid
)
if sandbox:
_delete_or_deprecate(
action, vocabulary.SANDBOX_1, tid, catalog, catalog_pid
)
else:
_delete_or_deprecate(action, qid, tid, catalog, catalog_pid)
def _add_or_reference_works(
work: str,
predicate: str,
person: str,
stated_in: str,
person_pid: str,
person_tid: str,
is_imdb=False,
) -> None:
# Parse value into an item in case of QID
qid = search(QID_REGEX, person)
if not qid:
LOGGER.warning(
"%s doesn't look like a QID, won't try to add the (%s, %s, %s) statement",
person,
work,
predicate,
person,
)
return
person = pywikibot.ItemPage(REPO, qid.group())
subject_item, claims = _essential_checks(
work,
predicate,
person,
stated_in,
person_pid=person_pid,
person_tid=person_tid,
)
if None in (subject_item, claims):
return
# IMDB-specific check: claims with same object item -> add reference
if is_imdb:
for pred in vocabulary.MOVIE_PIDS:
if _check_for_same_value(
claims,
work,
pred,
person,
stated_in,
person_pid=person_pid,
person_tid=person_tid,
):
return
_handle_addition(
claims,
subject_item,
predicate,
person,
stated_in,
person_pid=person_pid,
person_tid=person_tid,
)
def _add_or_reference(
subject: str, predicate: str, value: str, stated_in: str
) -> None:
subject_item, claims = _essential_checks(
subject, predicate, value, stated_in
)
if None in (subject_item, claims):
return
value = _parse_value(value)
# If 'official website' property has the same value -> add reference
# See https://www.wikidata.org/wiki/User_talk:Jura1#Thanks_for_your_feedback_on_User:Soweego_bot_task_2
if _check_for_same_value(
claims, subject, vocabulary.OFFICIAL_WEBSITE, value, stated_in
):
return
# Handle case-insensitive IDs: Facebook, Twitter
# See https://www.wikidata.org/wiki/Topic:Unym71ais48bt6ih
case_insensitive = predicate in (
vocabulary.FACEBOOK_PID,
vocabulary.TWITTER_USERNAME_PID,
)
_handle_addition(
claims,
subject_item,
predicate,
value,
stated_in,
case_insensitive=case_insensitive,
)
def _handle_addition(
claims,
subject_item,
predicate,
value,
stated_in,
case_insensitive=False,
person_pid=None,
person_tid=None,
):
given_predicate_claims = claims.get(predicate)
subject_qid = subject_item.getID()
# No claim with the given predicate -> add statement
if not given_predicate_claims:
LOGGER.debug('%s has no %s claim', subject_qid, predicate)
_add(subject_item, predicate, value, stated_in, person_pid, person_tid)
return
if case_insensitive:
value = value.lower()
existing_values = [
claim_value.getTarget().lower()
for claim_value in given_predicate_claims
# Yes, it happens: a claim with no value
if claim_value.getTarget()
]
else:
existing_values = [
claim_value.getTarget() for claim_value in given_predicate_claims
]
# No given value -> add statement
if value not in existing_values:
LOGGER.debug(
'%s has no %s claim with value %s', subject_qid, predicate, value
)
_add(subject_item, predicate, value, stated_in, person_pid, person_tid)
return
# Claim with the given predicate and value -> add reference
LOGGER.debug(
"%s has a %s claim with value '%s'", subject_qid, predicate, value
)
if case_insensitive:
for claim in given_predicate_claims:
if claim.getTarget().lower() == value:
_reference(claim, stated_in, person_pid, person_tid)
return
for claim in given_predicate_claims:
if claim.getTarget() == value:
_reference(claim, stated_in, person_pid, person_tid)
def _essential_checks(
subject, predicate, value, stated_in, person_pid=None, person_tid=None
):
item = pywikibot.ItemPage(REPO, subject)
# Handle redirects
while item.isRedirectPage():
item = item.getRedirectTarget()
try:
data = item.get()
except NoPage:
LOGGER.warning("%s doesn't exist anymore", subject)
return None, None
# No data at all
if not data:
LOGGER.warning('%s has no data at all', subject)
_add(item, predicate, value, stated_in, person_pid, person_tid)
return None, None
claims = data.get('claims')
# No claims
if not claims:
LOGGER.warning('%s has no claims', subject)
_add(item, predicate, value, stated_in, person_pid, person_tid)
return None, None
return item, claims
def _check_for_same_value(
subject_claims,
subject,
predicate,
value,
stated_in,
person_pid=None,
person_tid=None,
):
given_predicate_claims = subject_claims.get(predicate)
if given_predicate_claims:
for claim in given_predicate_claims:
if claim.getTarget() == value:
LOGGER.debug(
"%s has a %s claim with value '%s'",
subject,
predicate,
value,
)
_reference(claim, stated_in, person_pid, person_tid)
return True
return False
def _parse_value(value):
# It may not be a string
if not isinstance(value, str):
value = str(value)
# Build an item in case of QID
value_is_qid = search(QID_REGEX, value)
if value_is_qid:
return pywikibot.ItemPage(REPO, value_is_qid.group())
# Try to build a date
try:
date_value = date.fromisoformat(value)
# Precision hack: it's a year if both month and day are 1
precision = (
vocabulary.YEAR
if date_value.month == 1 and date_value.day == 1
else vocabulary.DAY
)
return pywikibot.WbTime(
date_value.year,
date_value.month,
date_value.day,
precision=precision,
)
# Otherwise return the value as is
except ValueError:
return value
def _get_works_args(catalog):
# Boolean to run IMDb-specific checks
is_imdb = catalog == IMDB
catalog_qid = target_database.get_catalog_qid(catalog)
person_pid = target_database.get_person_pid(catalog)
return catalog_qid, is_imdb, person_pid
def _add(subject_item, predicate, value, stated_in, person_pid, person_tid):
claim = pywikibot.Claim(REPO, predicate)
claim.setTarget(value)
subject_item.addClaim(claim)
LOGGER.debug('Added claim: %s', claim.toJSON())
_reference(claim, stated_in, person_pid, person_tid)
LOGGER.info(
'Added (%s, %s, %s) statement', subject_item.getID(), predicate, value
)
def _reference(claim, stated_in, person_pid, person_tid):
STATED_IN_REFERENCE.setTarget(pywikibot.ItemPage(REPO, stated_in))
if None in (person_pid, person_tid):
reference_log = (
f'({STATED_IN_REFERENCE.getID()}, {stated_in}), '
f'({RETRIEVED_REFERENCE.getID()}, {TODAY})'
)
try:
claim.addSources([STATED_IN_REFERENCE, RETRIEVED_REFERENCE])
LOGGER.info('Added %s reference node', reference_log)
except APIError as error:
LOGGER.warning(
'Could not add %s reference node: %s', reference_log, error
)
else:
tid_reference = pywikibot.Claim(REPO, person_pid, is_reference=True)
tid_reference.setTarget(person_tid)
reference_log = (
f'({STATED_IN_REFERENCE.getID()}, {stated_in}), '
f'({person_pid}, {person_tid}), '
f'({RETRIEVED_REFERENCE.getID()}, {TODAY})'
)
try:
claim.addSources(
[STATED_IN_REFERENCE, tid_reference, RETRIEVED_REFERENCE]
)
LOGGER.info('Added %s reference node', reference_log)
except APIError as error:
LOGGER.warning(
'Could not add %s reference node: %s', reference_log, error
)
def _delete_or_deprecate(action, qid, tid, catalog, catalog_pid) -> None:
item = pywikibot.ItemPage(REPO, qid)
item_data = item.get()
item_claims = item_data.get('claims')
# This should not happen:
# the input item is supposed to have at least an identifier claim.
# We never know, Wikidata is alive.
if not item_claims:
LOGGER.error(
'%s has no claims. Cannot %s %s identifier %s',
qid,
action,
catalog,
tid,
)
return
identifier_claims = item_claims.get(catalog_pid)
# Same comment as the previous one
if not identifier_claims:
LOGGER.error(
'%s has no %s claims. Cannot %s %s identifier %s',
qid,
catalog_pid,
action,
catalog,
tid,
)
return
for claim in identifier_claims:
if claim.getTarget() == tid:
if action == 'delete':
item.removeClaims([claim], summary='Invalid identifier')
elif action == 'deprecate':
claim.changeRank(
'deprecated', summary='Deprecate arguable claim'
)
LOGGER.debug('%s claim: %s', action.title() + 'd', claim.toJSON())
LOGGER.info(
'%s %s identifier statement from %s', action.title() + 'd', catalog, qid
)