-
Notifications
You must be signed in to change notification settings - Fork 190
/
_wikibase.py
2525 lines (2091 loc) · 86.2 KB
/
_wikibase.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
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
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
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
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
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Objects representing various types of Wikibase pages and structures.
This module also includes objects:
* Claim: an instance of a semantic assertion.
* MediaInfo: Interface for MediaInfo entities on image repository
* Property: a type of semantic data.
* WikibaseEntity: base interface for Wikibase entities.
"""
#
# (C) Pywikibot team, 2013-2024
#
# Distributed under the terms of the MIT license.
#
from __future__ import annotations
import json as jsonlib
import re
from collections import OrderedDict, defaultdict
from contextlib import suppress
from itertools import chain
from typing import TYPE_CHECKING, Any
import pywikibot
from pywikibot.exceptions import (
APIError,
EntityTypeUnknownError,
Error,
InterwikiRedirectPageError,
InvalidTitleError,
IsNotRedirectPageError,
IsRedirectPageError,
NoPageError,
NoSiteLinkError,
NoWikibaseEntityError,
WikiBaseError,
)
from pywikibot.family import Family
from pywikibot.page._collections import (
AliasesDict,
ClaimCollection,
LanguageDict,
SiteLinkCollection,
SubEntityCollection,
)
from pywikibot.page._decorators import allow_asynchronous
from pywikibot.page._filepage import FilePage
from pywikibot.page._page import BasePage
from pywikibot.site import DataSite, Namespace
from pywikibot.tools import cached, first_upper
__all__ = (
'Claim',
'ItemPage',
'LexemeForm',
'LexemePage',
'LexemeSense',
'MediaInfo',
'Property',
'PropertyPage',
'WikibaseEntity',
'WikibasePage',
)
if TYPE_CHECKING:
LANGUAGE_IDENTIFIER = str | pywikibot.site.APISite
ALIASES_TYPE = dict[LANGUAGE_IDENTIFIER, list[str]]
LANGUAGE_TYPE = dict[LANGUAGE_IDENTIFIER, str]
SITELINK_TYPE = (
pywikibot.page.BasePage
| pywikibot.page.BaseLink
| dict[str, str]
)
ENTITY_DATA_TYPE = dict[str, LANGUAGE_TYPE | ALIASES_TYPE | SITELINK_TYPE]
class WikibaseEntity:
"""
The base interface for Wikibase entities.
Each entity is identified by a data repository it belongs to
and an identifier.
:cvar DATA_ATTRIBUTES: dictionary which maps data attributes
(e.g., 'labels', 'claims') to appropriate collection classes
(e.g., :class:`LanguageDict<pywikibot.page._collections.LanguageDict>`,
:class:`ClaimCollection<pywikibot.page._collections.ClaimCollection>`)
:cvar entity_type: entity type identifier
:type entity_type: str
:cvar title_pattern: regular expression which matches all possible
entity ids for this entity type
:type title_pattern: str
"""
DATA_ATTRIBUTES: dict[str, Any] = {}
def __init__(self, repo, id_: str | None = None) -> None:
"""
Initializer.
:param repo: Entity repository.
:type repo: DataSite
:param id_: Entity identifier.
:type id_: str or None, -1 and None mean non-existing
"""
self.repo = repo
self.id = id_ if id_ is not None else '-1'
if self.id != '-1' and not self.is_valid_id(self.id):
raise InvalidTitleError(
f"'{self.id}' is not a valid {self.entity_type} page title")
def __repr__(self) -> str:
if self.id != '-1':
return 'pywikibot.page.{}({!r}, {!r})'.format(
self.__class__.__name__, self.repo, self.id)
return f'pywikibot.page.{self.__class__.__name__}({self.repo!r})'
@classmethod
def is_valid_id(cls, entity_id: str) -> bool:
"""
Whether the string can be a valid id of the entity type.
:param entity_id: The ID to test.
"""
if not hasattr(cls, 'title_pattern'):
return True
return bool(re.fullmatch(cls.title_pattern, entity_id))
def __getattr__(self, name):
if name in self.DATA_ATTRIBUTES:
if self.getID() == '-1':
self._initialize_empty()
return getattr(self, name)
return self.get()[name]
raise AttributeError("'{}' object has no attribute '{}'"
.format(self.__class__.__name__, name))
def _initialize_empty(self):
for key, cls in self.DATA_ATTRIBUTES.items():
setattr(self, key, cls.new_empty(self.repo))
def _defined_by(self, singular: bool = False) -> dict[str, str]:
"""
Internal function to provide the API parameters to identify the entity.
An empty dict is returned if the entity has not been created yet.
:param singular: Whether the parameter names should use the singular
form
:return: API parameters
"""
params = {}
if self.id != '-1':
if singular:
params['id'] = self.id
else:
params['ids'] = self.id
return params
def getID(self, numeric: bool = False) -> int | str:
"""
Get the identifier of this entity.
:param numeric: Strip the first letter and return an int
"""
if numeric:
return int(self.id[1:]) if self.id != '-1' else -1
return self.id
def get_data_for_new_entity(self) -> dict:
"""
Return data required for creation of a new entity.
Override it if you need.
"""
return {}
def toJSON(self, diffto: dict | None = None) -> dict:
"""
Create JSON suitable for Wikibase API.
When diffto is provided, JSON representing differences
to the provided data is created.
:param diffto: JSON containing entity data
"""
data = {}
for key in self.DATA_ATTRIBUTES:
attr = getattr(self, key, None)
if attr is None:
continue
if diffto:
value = attr.toJSON(diffto=diffto.get(key))
else:
value = attr.toJSON()
if value:
data[key] = value
return data
@classmethod
def _normalizeData(cls, data: dict) -> dict:
"""
Helper function to expand data into the Wikibase API structure.
:param data: The dict to normalize
:return: The dict with normalized data
"""
norm_data = {}
for key, attr in cls.DATA_ATTRIBUTES.items():
if key in data:
norm_data[key] = attr.normalizeData(data[key])
return norm_data
@property
def latest_revision_id(self) -> int | None:
"""
Get the revision identifier for the most recent revision of the entity.
:rtype: int or None if it cannot be determined
:raise NoWikibaseEntityError: if the entity doesn't exist
"""
if not hasattr(self, '_revid'):
# FIXME: unlike BasePage.latest_revision_id, this raises
# exception when entity is redirect, cannot use get_redirect
self.get()
return self._revid
@latest_revision_id.setter
def latest_revision_id(self, value: int | None) -> None:
self._revid = value
@latest_revision_id.deleter
def latest_revision_id(self) -> None:
if hasattr(self, '_revid'):
del self._revid
def exists(self) -> bool:
"""Determine if an entity exists in the data repository."""
if not hasattr(self, '_content'):
try:
self.get()
return True
except NoWikibaseEntityError:
return False
return 'missing' not in self._content
def get(self, force: bool = False) -> dict:
"""
Fetch all entity data and cache it.
:param force: override caching
:raise NoWikibaseEntityError: if this entity doesn't exist
:return: actual data which entity holds
"""
if force or not hasattr(self, '_content'):
identification = self._defined_by()
if not identification:
raise NoWikibaseEntityError(self)
try:
data = self.repo.loadcontent(identification)
except APIError as err:
if err.code == 'no-such-entity':
raise NoWikibaseEntityError(self)
raise
item_index, content = data.popitem()
self.id = item_index
self._content = content
if 'missing' in self._content:
raise NoWikibaseEntityError(self)
self.latest_revision_id = self._content.get('lastrevid')
data = {}
# This initializes all data
for key, cls in self.DATA_ATTRIBUTES.items():
value = cls.fromJSON(self._content.get(key, {}), self.repo)
setattr(self, key, value)
data[key] = value
# fixme: need better handling for this
if key in ['claims', 'statements']:
value.set_on_item(self)
return data
def editEntity(
self,
data: ENTITY_DATA_TYPE | None = None,
**kwargs
) -> None:
"""Edit an entity using Wikibase ``wbeditentity`` API.
This function is wrapped around by:
- :meth:`WikibasePage.editLabels`
- :meth:`WikibasePage.editDescriptions`
- :meth:`WikibasePage.editAliases`
- :meth:`ItemPage.setSitelinks`
.. seealso:: :meth:`WikibasePage.editEntity`
.. versionchanged:: 8.0.1
Copy snak IDs/hashes (:phab:`T327607`)
:param data: Data to be saved
"""
update_self = False
if data is None:
data = self.toJSON(diffto=getattr(self, '_content', None))
# We only want to copy the IDs from the updates
# if data was not passed in.
update_self = True
else:
data = self._normalizeData(data)
baserevid = getattr(self, '_revid', None)
updates = self.repo.editEntity(
self, data, baserevid=baserevid, **kwargs)
# the attribute may have been unset in ItemPage
if getattr(self, 'id', '-1') == '-1':
self.__init__(self.repo, updates['entity']['id'])
# the response also contains some data under the 'entity' key
# but it is NOT the actual content
# see also [[d:Special:Diff/1356933963]]
# TODO: there might be some circumstances under which
# the content can be safely reused
if hasattr(self, '_content'):
del self._content
self.latest_revision_id = updates['entity'].get('lastrevid')
if update_self and 'claims' in updates['entity']:
updated_claims = updates['entity']['claims']
for claim_prop_id, statements in updated_claims.items():
for claim_index, statement in enumerate(statements):
claim = self.claims[claim_prop_id][claim_index]
claim.snak = statement['id']
claim.on_item = self
updated_qualifiers = statement.get('qualifiers', {})
for qual_propid, qualifier in updated_qualifiers.items():
for qual_index, qual_statement in enumerate(qualifier):
target_qual_prop = claim.qualifiers[qual_propid]
target_qual = target_qual_prop[qual_index]
target_qual.hash = qual_statement['hash']
updated_references = statement.get('references', [])
for ref_grp_idx, ref_grp in enumerate(updated_references):
for ref_propid, reference in ref_grp['snaks'].items():
for ref_index, ref_stat in enumerate(reference):
target_ref_grp = claim.sources[ref_grp_idx]
target_ref_prop = target_ref_grp[ref_propid]
target_ref = target_ref_prop[ref_index]
target_ref.hash = ref_stat['hash']
def concept_uri(self) -> str:
"""
Return the full concept URI.
:raise NoWikibaseEntityError: if this entity's id is not known
"""
entity_id = self.getID()
if entity_id == '-1':
raise NoWikibaseEntityError(self)
return f'{self.repo.concept_base_uri}{entity_id}'
class MediaInfo(WikibaseEntity):
"""Interface for MediaInfo entities on Commons.
.. versionadded:: 6.5
"""
entity_type = 'mediainfo'
title_pattern = r'M[1-9]\d*'
DATA_ATTRIBUTES = {
'labels': LanguageDict,
'statements': ClaimCollection,
}
def __getattr__(self, name):
if name == 'claims': # T149410
return self.statements
if name in self.DATA_ATTRIBUTES:
if not self.exists():
self._assert_has_id()
self._initialize_empty()
return getattr(self, name)
return super().__getattr__(name)
def _assert_has_id(self):
if self.id != '-1':
return
if not self.file.exists():
exc = NoPageError(self.file)
raise NoWikibaseEntityError(self) from exc
self.id = 'M' + str(self.file.pageid)
def _defined_by(self, singular: bool = False) -> dict:
"""
Internal function to provide the API parameters to identify the entity.
.. versionadded:: 8.5
:param singular: Whether the parameter names should use the singular
form
:raise NoWikibaseEntityError: if this entity is associated with
a non-existing file
:return: API parameters
"""
self._assert_has_id()
return super()._defined_by(singular)
@property
def file(self) -> FilePage:
"""Get the file associated with the mediainfo."""
if not hasattr(self, '_file'):
if self.id == '-1':
# if the above doesn't apply, this entity is in an invalid
# state which needs to be raised as an exception, but also
# logged in case an exception handler is catching
# the generic Error
msg = f'{self.__class__.__name__} is in invalid state'
pywikibot.error(msg)
raise Error(msg)
# avoid recursion with self.getID()
page_id = int(self.id[1:])
result = list(self.repo.load_pages_from_pageids([page_id]))
if not result:
raise Error(f'There is no existing page with id "{page_id}"')
page = result.pop()
if page.namespace() != page.site.namespaces.FILE:
raise Error(f'Page with id "{page_id}" is not a file')
self._file = FilePage(page)
return self._file
def get(self, force: bool = False) -> dict:
"""Fetch all MediaInfo entity data and cache it.
.. note:: dicts returned by this method are references to content
of this entity and their modifying may indirectly cause
unwanted change to the live content
.. versionchanged:: 9.0
Added *pageid*, *ns*, *title*, *lastrevid*, *modified*, *id*
values to ``_content`` attribute when it is loaded.
:param force: override caching
:raise NoWikibaseEntityError: if this entity doesn't exist
:return: actual data which entity holds
"""
if force or not hasattr(self, '_content'):
if force:
self.file.clear_cache()
# accessing latest_revision loads the file data
try:
latest_revision = self.file.latest_revision
except NoPageError as exc:
raise NoWikibaseEntityError(self) from exc
except Error as exc:
error_message = str(exc)
if 'is not a file' in error_message:
raise NoWikibaseEntityError(self) from exc
raise Error(self) from exc
# Create _content. Format is same as with wbgetentities
# https://commons.wikimedia.org/w/api.php?action=wbgetentities&ids=M20985340
data = {
'title': self.file.title,
'lastrevid': latest_revision['revid'],
'modified': str(latest_revision['timestamp']),
'type': 'mediainfo',
'pageid': self.file.pageid,
'ns': self.file.namespace,
'id': 'M' + str(self.file.pageid),
'labels': {},
'statements': {}
}
# Update 'id', 'labels' and 'statements' if mediainfo is available.
# MediaInfo is returned only when it has values.
if 'mediainfo' in latest_revision.slots:
mediainfo_json = latest_revision.slots['mediainfo']['*']
mediainfo_data = jsonlib.loads(mediainfo_json)
data.update(mediainfo_data)
self._content = data
self.id = self._content['id']
self._assert_has_id()
# Do not pass the force parameter to the upper level because
# reloading files without MediaInfo will fail.
return super().get()
def getID(self, numeric: bool = False):
"""
Get the entity identifier.
:param numeric: Strip the first letter and return an int
:raise NoWikibaseEntityError: if this entity is associated with
a non-existing file
"""
self._assert_has_id()
return super().getID(numeric=numeric)
def editLabels(self, labels: LANGUAGE_TYPE, **kwargs) -> None:
"""Edit MediaInfo labels (eg. captions).
*labels* should be a dict, with the key as a language or a site
object. The value should be the string to set it to. You can set
it to ``''`` to remove the label.
Usage:
>>> repo = pywikibot.Site('commons','commons')
>>> page = pywikibot.FilePage(repo, 'File:Sandbox-Test.svg')
>>> item = page.data_item()
>>> item.editLabels({'en': 'Test file.'}) # doctest: +SKIP
.. versionadded:: 8.5
"""
data = {'labels': labels}
self.editEntity(data, **kwargs)
def addClaim(self, claim, bot: bool = True, **kwargs):
"""Add a claim to the MediaInfo.
.. versionadded:: 8.5
:param claim: The claim to add
:type claim: pywikibot.page.Claim
:param bot: Whether to flag as bot (if possible)
"""
if claim.on_item is not None:
raise ValueError(
'The provided Claim instance is already used in an entity')
self._assert_has_id()
self.repo.addClaim(self, claim, bot=bot, **kwargs)
claim.on_item = self
def removeClaims(self, claims, **kwargs) -> None:
"""Remove the claims from the MediaInfo.
.. versionadded:: 8.5
:param claims: list of claims to be removed
:type claims: list or pywikibot.Claim
"""
# this check allows single claims to be removed by pushing them into a
# list of length one.
if isinstance(claims, pywikibot.Claim):
claims = [claims]
data = self.repo.removeClaims(claims, **kwargs)
for claim in claims:
claim.on_item.latest_revision_id = data['pageinfo']['lastrevid']
claim.on_item = None
claim.snak = None
class WikibasePage(BasePage, WikibaseEntity):
"""
Mixin base class for Wikibase entities which are also pages (eg. items).
There should be no need to instantiate this directly.
"""
_cache_attrs = BasePage._cache_attrs + ('_content', )
def __init__(self, site, title: str = '', **kwargs) -> None:
"""
Initializer.
If title is provided, either ns or entity_type must also be provided,
and will be checked against the title parsed using the Page
initialisation logic.
:param site: Wikibase data site
:type site: pywikibot.site.DataSite
:param title: normalized title of the page
:type title: str
:keyword ns: namespace
:type ns: Namespace instance, or int
:keyword entity_type: Wikibase entity type
:type entity_type: str ('item' or 'property')
:raises TypeError: incorrect use of parameters
:raises ValueError: incorrect namespace
:raises pywikibot.exceptions.Error: title parsing problems
:raises NotImplementedError: the entity type is not supported
"""
if not isinstance(site, pywikibot.site.DataSite):
raise TypeError('site must be a pywikibot.site.DataSite object')
if title and ('ns' not in kwargs and 'entity_type' not in kwargs):
pywikibot.debug('{}.__init__: {} title {!r} specified without '
'ns or entity_type'
.format(type(self).__name__, site, title))
self._namespace = None
if 'ns' in kwargs:
if isinstance(kwargs['ns'], Namespace):
self._namespace = kwargs.pop('ns')
kwargs['ns'] = self._namespace.id
else:
# numerical namespace given
ns = int(kwargs['ns'])
if site.item_namespace.id == ns:
self._namespace = site.item_namespace
elif site.property_namespace.id == ns:
self._namespace = site.property_namespace
else:
raise ValueError(
f'{site!r}: Namespace "{int(ns)}" is not valid')
if 'entity_type' in kwargs:
entity_type = kwargs.pop('entity_type')
try:
entity_type_ns = site.get_namespace_for_entity_type(
entity_type)
except EntityTypeUnknownError:
raise ValueError(
f'Wikibase entity type "{entity_type}" unknown')
if self._namespace:
if self._namespace != entity_type_ns:
raise ValueError('Namespace "{}" is not valid for Wikibase'
' entity type "{}"'
.format(int(kwargs['ns']), entity_type))
else:
self._namespace = entity_type_ns
kwargs['ns'] = self._namespace.id
BasePage.__init__(self, site, title, **kwargs)
# If a title was not provided,
# avoid checks which may cause an exception.
if not title:
WikibaseEntity.__init__(self, site)
return
if self._namespace:
if self._link.namespace != self._namespace.id:
raise ValueError("'{}' is not in the namespace {}"
.format(title, self._namespace.id))
else:
# Neither ns or entity_type was provided.
# Use the _link to determine entity type.
ns = self._link.namespace
if self.site.item_namespace.id == ns:
self._namespace = self.site.item_namespace
elif self.site.property_namespace.id == ns:
self._namespace = self.site.property_namespace
else:
raise ValueError(
f'{self.site!r}: Namespace "{ns!r}" is not valid')
WikibaseEntity.__init__(
self,
# .site forces a parse of the Link title to determine site
self.site,
# Link.__init__, called from Page.__init__, has cleaned the title
# stripping whitespace and uppercasing the first letter according
# to the namespace case=first-letter.
self._link.title)
def namespace(self) -> int:
"""
Return the number of the namespace of the entity.
:return: Namespace id
"""
return self._namespace.id
def exists(self) -> bool:
"""Determine if an entity exists in the data repository."""
if not hasattr(self, '_content'):
try:
self.get(get_redirect=True)
return True
except NoPageError:
return False
return 'missing' not in self._content
def botMayEdit(self) -> bool:
"""
Return whether bots may edit this page.
Because there is currently no system to mark a page that it shouldn't
be edited by bots on Wikibase pages it always returns True. The content
of the page is not text but a dict, the original way (to search for a
template) doesn't apply.
:return: True
"""
return True
def get(self, force: bool = False, *args, **kwargs) -> dict:
"""
Fetch all page data, and cache it.
:param force: override caching
:raise NotImplementedError: a value in args or kwargs
:return: actual data which entity holds
.. note:: dicts returned by this method are references to content
of this entity and their modifying may indirectly cause
unwanted change to the live content
"""
if args or kwargs:
raise NotImplementedError(
'{}.get does not implement var args: {!r} and {!r}'.format(
self.__class__.__name__, args, kwargs))
# todo: this variable is specific to ItemPage
lazy_loading_id = not hasattr(self, 'id') and hasattr(self, '_site')
try:
data = WikibaseEntity.get(self, force=force)
except NoWikibaseEntityError:
if lazy_loading_id:
p = pywikibot.Page(self._site, self._title)
if not p.exists():
raise NoPageError(p)
# todo: raise a nicer exception here (T87345)
raise NoPageError(self)
if 'pageid' in self._content:
self._pageid = self._content['pageid']
return data
@property
def latest_revision_id(self) -> int:
"""
Get the revision identifier for the most recent revision of the entity.
:rtype: int
:raise pywikibot.exceptions.NoPageError: if the entity doesn't exist
"""
if not hasattr(self, '_revid'):
self.get()
return self._revid
@latest_revision_id.setter
def latest_revision_id(self, value) -> None:
self._revid = value
@latest_revision_id.deleter
def latest_revision_id(self) -> None:
# fixme: this seems too destructive in comparison to the parent
self.clear_cache()
@allow_asynchronous
def editEntity(
self,
data: ENTITY_DATA_TYPE | None = None,
**kwargs: Any
) -> None:
"""Edit an entity using Wikibase ``wbeditentity`` API.
This function is wrapped around by:
- :meth:`editLabels`
- :meth:`editDescriptions`
- :meth:`editAliases`
- :meth:`ItemPage.setSitelinks`
It supports *asynchronous* and *callback* keyword arguments. The
callback function is intended for use by bots that need to keep
track of which saves were successful. The minimal callback
function signature is::
def my_callback(page: WikibasePage, err: Optional[Exception]) -> Any:
The arguments are:
``page``
a :class:`WikibasePage` object
``err``
an Exception instance, which will be None if the page was
saved successfully
.. seealso:: :meth:`WikibaseEntity.editEntity`
:param data: Data to be saved
:keyword bool asynchronous: if True, launch a separate thread to
edit asynchronously
:keyword Callable[[WikibasePage, Optional[Exception]], Any] callback:
a callable object that will be called after the entity has
been updated. It must take two arguments, see above.
"""
# kept for the decorator which provides the keyword arguments
super().editEntity(data, **kwargs)
def editLabels(self, labels: LANGUAGE_TYPE, **kwargs) -> None:
"""Edit entity labels.
*labels* should be a dict, with the key as a language or a site
object. The value should be the string to set it to. You can set
it to ``''`` to remove the label.
Refer :meth:`editEntity` for *asynchronous* and *callback* usage.
Usage:
>>> repo = pywikibot.Site('wikidata:test')
>>> item = pywikibot.ItemPage(repo, 'Q68')
>>> item.editLabels({'en': 'Test123'}) # doctest: +SKIP
"""
data = {'labels': labels}
self.editEntity(data, **kwargs)
def editDescriptions(self, descriptions: LANGUAGE_TYPE, **kwargs) -> None:
"""Edit entity descriptions.
*descriptions* should be a dict, with the key as a language or a
site object. The value should be the string to set it to. You
can set it to ``''`` to remove the description.
Refer :meth:`editEntity` for *asynchronous* and *callback* usage.
Usage:
>>> repo = pywikibot.Site('wikidata:test')
>>> item = pywikibot.ItemPage(repo, 'Q68')
>>> item.editDescriptions({'en': 'Pywikibot test'}) # doctest: +SKIP
"""
data = {'descriptions': descriptions}
self.editEntity(data, **kwargs)
def editAliases(self, aliases: ALIASES_TYPE, **kwargs) -> None:
"""Edit entity aliases.
*aliases* should be a dict, with the key as a language or a site
object. The value should be a list of strings.
Refer :meth:`editEntity` for *asynchronous* and *callback* usage.
Usage:
>>> repo = pywikibot.Site('wikidata:test')
>>> item = pywikibot.ItemPage(repo, 'Q68')
>>> item.editAliases({'en': ['pwb test item']}) # doctest: +SKIP
"""
data = {'aliases': aliases}
self.editEntity(data, **kwargs)
def set_redirect_target(
self,
target_page,
create: bool = False,
force: bool = False,
keep_section: bool = False,
save: bool = True,
**kwargs
):
"""
Set target of a redirect for a Wikibase page.
Has not been implemented in the Wikibase API yet, except for ItemPage.
"""
raise NotImplementedError
@allow_asynchronous
def addClaim(self, claim, bot: bool = True, **kwargs):
"""
Add a claim to the entity.
:param claim: The claim to add
:type claim: pywikibot.page.Claim
:param bot: Whether to flag as bot (if possible)
:keyword asynchronous: if True, launch a separate thread to add claim
asynchronously
:type asynchronous: bool
:keyword callback: a callable object that will be called after the
claim has been added. It must take two arguments:
(1) a WikibasePage object, and (2) an exception instance,
which will be None if the entity was saved successfully. This is
intended for use by bots that need to keep track of which saves
were successful.
:type callback: callable
"""
if claim.on_item is not None:
raise ValueError(
'The provided Claim instance is already used in an entity')
self.repo.addClaim(self, claim, bot=bot, **kwargs)
claim.on_item = self
def removeClaims(self, claims, **kwargs) -> None:
"""
Remove the claims from the entity.
:param claims: list of claims to be removed
:type claims: list or pywikibot.Claim
"""
# this check allows single claims to be removed by pushing them into a
# list of length one.
if isinstance(claims, pywikibot.Claim):
claims = [claims]
data = self.repo.removeClaims(claims, **kwargs)
for claim in claims:
claim.on_item.latest_revision_id = data['pageinfo']['lastrevid']
claim.on_item = None
claim.snak = None
class ItemPage(WikibasePage):
"""
Wikibase entity of type 'item'.
A Wikibase item may be defined by either a 'Q' id (qid),
or by a site & title.
If an item is defined by site & title, once an item's qid has
been looked up, the item is then defined by the qid.
"""
_cache_attrs = WikibasePage._cache_attrs + (
'labels', 'descriptions', 'aliases', 'claims', 'sitelinks')
entity_type = 'item'
title_pattern = r'Q[1-9]\d*'
DATA_ATTRIBUTES = {
'labels': LanguageDict,
'descriptions': LanguageDict,
'aliases': AliasesDict,
'claims': ClaimCollection,
'sitelinks': SiteLinkCollection,
}
def __init__(self, site, title=None, ns=None) -> None:
"""
Initializer.
:param site: data repository
:type site: pywikibot.site.DataSite
:param title: identifier of item, "Q###",
-1 or None for an empty item.
:type title: str
:type ns: namespace
:type ns: Namespace instance, or int, or None
for default item_namespace
"""
if ns is None:
ns = site.item_namespace
# Special case for empty item.
if title is None or title == '-1':
super().__init__(site, '-1', ns=ns)
assert self.id == '-1'
return
# we don't want empty titles
if not title:
raise InvalidTitleError("Item's title cannot be empty")
super().__init__(site, title, ns=ns)
assert self.id == self._link.title
def _defined_by(self, singular: bool = False) -> dict:
"""
Internal function to provide the API parameters to identify the item.
The API parameters may be 'id' if the ItemPage has one,
or 'site'&'title' if instantiated via ItemPage.fromPage with
lazy_load enabled.
Once an item's Q## is looked up, that will be used for all future
requests.
An empty dict is returned if the ItemPage is instantiated without
either ID (internally it has id = '-1') or site&title.
:param singular: Whether the parameter names should use the
singular form
:return: API parameters
"""
params = {}
if singular:
id = 'id'
site = 'site'