forked from wikimedia/pywikibot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path__init__.py
1382 lines (1125 loc) · 47.1 KB
/
__init__.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
"""The initialization file for the Pywikibot framework."""
#
# (C) Pywikibot team, 2008-2021
#
# Distributed under the terms of the MIT license.
#
import atexit
import datetime
import math
import re
import sys
import threading
import time
from contextlib import suppress
from decimal import Decimal
from queue import Queue
from typing import Any, Optional, Union
from urllib.parse import urlparse
from warnings import warn
from pywikibot import config as _config
from pywikibot import exceptions
from pywikibot.__metadata__ import (
__copyright__,
__description__,
__download_url__,
__license__,
__maintainer__,
__maintainer_email__,
__name__,
__url__,
__version__,
)
from pywikibot._wbtypes import WbRepresentation as _WbRepresentation
from pywikibot.backports import (
cache,
removesuffix,
Callable,
Dict,
List,
Tuple,
)
from pywikibot.bot import (
Bot,
CurrentPageBot,
WikidataBot,
calledModuleName,
handle_args,
input,
input_choice,
input_yn,
show_help,
ui,
)
from pywikibot.diff import PatchManager
from pywikibot.family import AutoFamily, Family
from pywikibot.i18n import translate
from pywikibot.logging import (
critical,
debug,
error,
exception,
log,
output,
stdout,
warning,
)
from pywikibot.site import APISite, BaseSite, DataSite
from pywikibot.tools import classproperty
from pywikibot.tools import normalize_username
from pywikibot.tools.formatter import color_format
TO_DECIMAL_TYPE = Union[int, float, str, 'Decimal', None]
# TODO: replace these after T286867
STR_OR_TIMESTAMP = Any # Union[str, 'Timestamp']
OPT_STR_OR_SITE = Any # Union[str, 'pywikibot.site.BaseSite', None]
OPT_STR_OR_ITEM_PAGE = Any # Union[str, 'pywikibot.page.ItemPage', None]
OPT_STR_OR_FAMILY = Any # Union[str, 'pywikibot.family.Family', None]
TIMESTAMP_CLASS = Any # Type['Timestamp']
COORDINATE_CLASS = Any # Type['Coordinate']
WB_TIME_CLASS = Any # Type['WbTime']
WB_QUANTITY_CLASS = Any # Type['WbQuantity']
WB_MONOLINGUAL_TEXT_CLASS = Any # Type['WbMonolingualText']
WB_DATA_PAGE_CLASS = Any # Type['_WbDataPage']
WB_GEO_SHAPE_CLASS = Any # Type['WbGeoShape']
WB_TABULAR_DATA_CLASS = Any # Type['WbTabularData']
WB_UNKNOWN_CLASS = Any # Type['WbUnknown']
__all__ = (
'__copyright__', '__description__', '__download_url__', '__license__',
'__maintainer__', '__maintainer_email__', '__name__', '__url__',
'__version__',
'Bot', 'calledModuleName', 'Category', 'Claim', 'Coordinate', 'critical',
'CurrentPageBot', 'debug', 'error', 'exception', 'FilePage', 'handle_args',
'html2unicode', 'input', 'input_choice', 'input_yn', 'ItemPage', 'Link',
'log', 'MediaInfo', 'output', 'Page', 'PropertyPage', 'showDiff',
'show_help', 'Site', 'SiteLink', 'stdout', 'Timestamp', 'translate', 'ui',
'unicode2html', 'UploadWarning', 'url2unicode', 'User', 'warning',
'WbGeoShape', 'WbMonolingualText', 'WbQuantity', 'WbTabularData', 'WbTime',
'WbUnknown', 'WikidataBot',
)
# argvu is set by pywikibot.bot when it's imported
if not hasattr(sys.modules[__name__], 'argvu'):
argvu = [] # type: List[str]
class Timestamp(datetime.datetime):
"""Class for handling MediaWiki timestamps.
This inherits from datetime.datetime, so it can use all of the methods
and operations of a datetime object. To ensure that the results of any
operation are also a Timestamp object, be sure to use only Timestamp
objects (and datetime.timedeltas) in any operation.
Use Timestamp.fromISOformat() and Timestamp.fromtimestampformat() to
create Timestamp objects from MediaWiki string formats.
As these constructors are typically used to create objects using data
passed provided by site and page methods, some of which return a Timestamp
when previously they returned a MediaWiki string representation, these
methods also accept a Timestamp object, in which case they return a clone.
Use Site.server_time() for the current time; this is more reliable
than using Timestamp.utcnow().
"""
mediawikiTSFormat = '%Y%m%d%H%M%S'
_ISO8601Format_new = '{0:+05d}-{1:02d}-{2:02d}T{3:02d}:{4:02d}:{5:02d}Z'
def clone(self) -> datetime.datetime:
"""Clone this instance."""
return self.replace(microsecond=self.microsecond)
@classproperty
def ISO8601Format(cls: TIMESTAMP_CLASS) -> str:
"""ISO8601 format string class property for compatibility purpose."""
return cls._ISO8601Format()
@classmethod
def _ISO8601Format(cls: TIMESTAMP_CLASS, sep: str = 'T') -> str:
"""ISO8601 format string.
:param sep: one-character separator, placed between the date and time
:return: ISO8601 format string
"""
assert len(sep) == 1
return '%Y-%m-%d{}%H:%M:%SZ'.format(sep)
@classmethod
def fromISOformat(cls: TIMESTAMP_CLASS, ts: STR_OR_TIMESTAMP,
sep: str = 'T') -> 'Timestamp':
"""Convert an ISO 8601 timestamp to a Timestamp object.
:param ts: ISO 8601 timestamp or a Timestamp object already
:param sep: one-character separator, placed between the date and time
:return: Timestamp object
"""
# If inadvertently passed a Timestamp object, use replace()
# to create a clone.
if isinstance(ts, cls):
return ts.clone()
return cls.strptime(ts, cls._ISO8601Format(sep))
@classmethod
def fromtimestampformat(cls: TIMESTAMP_CLASS, ts: STR_OR_TIMESTAMP
) -> 'Timestamp':
"""Convert a MediaWiki internal timestamp to a Timestamp object."""
# If inadvertently passed a Timestamp object, use replace()
# to create a clone.
if isinstance(ts, cls):
return ts.clone()
if len(ts) == 8: # year, month and day are given only
ts += '000'
return cls.strptime(ts, cls.mediawikiTSFormat)
def isoformat(self, sep: str = 'T') -> str: # type: ignore[override]
"""
Convert object to an ISO 8601 timestamp accepted by MediaWiki.
datetime.datetime.isoformat does not postfix the ISO formatted date
with a 'Z' unless a timezone is included, which causes MediaWiki
~1.19 and earlier to fail.
"""
return self.strftime(self._ISO8601Format(sep))
def totimestampformat(self) -> str:
"""Convert object to a MediaWiki internal timestamp."""
return self.strftime(self.mediawikiTSFormat)
def __str__(self) -> str:
"""Return a string format recognized by the API."""
return self.isoformat()
def __add__(self, other: datetime.timedelta) -> 'Timestamp':
"""Perform addition, returning a Timestamp instead of datetime."""
newdt = super().__add__(other)
if isinstance(newdt, datetime.datetime):
return Timestamp(newdt.year, newdt.month, newdt.day, newdt.hour,
newdt.minute, newdt.second, newdt.microsecond,
newdt.tzinfo)
return newdt
def __sub__(self, other: datetime.timedelta # type: ignore[override]
) -> 'Timestamp':
"""Perform subtraction, returning a Timestamp instead of datetime."""
newdt = super().__sub__(other)
if isinstance(newdt, datetime.datetime):
return Timestamp(newdt.year, newdt.month, newdt.day, newdt.hour,
newdt.minute, newdt.second, newdt.microsecond,
newdt.tzinfo)
return newdt
class Coordinate(_WbRepresentation):
"""Class for handling and storing Coordinates."""
_items = ('lat', 'lon', 'entity')
def __init__(self, lat: float, lon: float, alt: Optional[float] = None,
precision: Optional[float] = None,
globe: Optional[str] = None, typ: str = '',
name: str = '', dim: Optional[int] = None,
site: Optional[DataSite] = None,
globe_item: OPT_STR_OR_ITEM_PAGE = None,
primary: bool = False) -> None:
"""
Represent a geo coordinate.
:param lat: Latitude
:param lon: Longitude
:param alt: Altitude
:param precision: precision
:param globe: Which globe the point is on
:param typ: The type of coordinate point
:param name: The name
:param dim: Dimension (in meters)
:param site: The Wikibase site
:param globe_item: The Wikibase item for the globe, or the entity URI
of this Wikibase item. Takes precedence over 'globe'
if present.
:param primary: True for a primary set of coordinates
"""
self.lat = lat
self.lon = lon
self.alt = alt
self._precision = precision
self._entity = globe_item
self.type = typ
self.name = name
self._dim = dim
self.site = site or Site().data_repository()
self.primary = primary
if globe:
globe = globe.lower()
elif not globe_item:
globe = self.site.default_globe()
self.globe = globe
@property
def entity(self) -> str:
"""Return the entity uri of the globe."""
if not self._entity:
if self.globe not in self.site.globes():
raise exceptions.CoordinateGlobeUnknownError(
'{} is not supported in Wikibase yet.'
.format(self.globe))
return self.site.globes()[self.globe]
if isinstance(self._entity, ItemPage):
return self._entity.concept_uri()
return self._entity
def toWikibase(self) -> Dict[str, Any]:
"""
Export the data to a JSON object for the Wikibase API.
FIXME: Should this be in the DataSite object?
:return: Wikibase JSON
"""
return {'latitude': self.lat,
'longitude': self.lon,
'altitude': self.alt,
'globe': self.entity,
'precision': self.precision,
}
@classmethod
def fromWikibase(cls: COORDINATE_CLASS, data: Dict[str, Any],
site: Optional[DataSite] = None) -> 'Coordinate':
"""
Constructor to create an object from Wikibase's JSON output.
:param data: Wikibase JSON
:param site: The Wikibase site
"""
if site is None:
site = Site().data_repository()
globe = None
if data['globe']:
globes = {}
for name, entity in site.globes().items():
globes[entity] = name
globe = globes.get(data['globe'])
return cls(data['latitude'], data['longitude'],
data['altitude'], data['precision'],
globe, site=site, globe_item=data['globe'])
@property
def precision(self) -> Optional[float]:
"""
Return the precision of the geo coordinate.
The precision is calculated if the Coordinate does not have a
precision, and self._dim is set.
When no precision and no self._dim exists, None is returned.
The biggest error (in degrees) will be given by the longitudinal error;
the same error in meters becomes larger (in degrees) further up north.
We can thus ignore the latitudinal error.
The longitudinal can be derived as follows:
In small angle approximation (and thus in radians):
M{Δλ ≈ Δpos / r_φ}, where r_φ is the radius of earth at the given
latitude.
Δλ is the error in longitude.
M{r_φ = r cos φ}, where r is the radius of earth, φ the latitude
Therefore::
precision = math.degrees(
self._dim/(radius*math.cos(math.radians(self.lat))))
"""
if self._dim is None and self._precision is None:
return None
if self._precision is None and self._dim is not None:
radius = 6378137 # TODO: Support other globes
self._precision = math.degrees(
self._dim / (radius * math.cos(math.radians(self.lat))))
return self._precision
@precision.setter
def precision(self, value: float) -> None:
self._precision = value
def precisionToDim(self) -> Optional[int]:
"""
Convert precision from Wikibase to GeoData's dim and return the latter.
dim is calculated if the Coordinate doesn't have a dimension, and
precision is set. When neither dim nor precision are set, ValueError
is thrown.
Carrying on from the earlier derivation of precision, since
precision = math.degrees(dim/(radius*math.cos(math.radians(self.lat))))
we get::
dim = math.radians(
precision)*radius*math.cos(math.radians(self.lat))
But this is not valid, since it returns a float value for dim which is
an integer. We must round it off to the nearest integer.
Therefore::
dim = int(round(math.radians(
precision)*radius*math.cos(math.radians(self.lat))))
"""
if self._dim is None and self._precision is None:
raise ValueError('No values set for dim or precision')
if self._dim is None and self._precision is not None:
radius = 6378137
self._dim = int(
round(
math.radians(self._precision) * radius * math.cos(
math.radians(self.lat))
)
)
return self._dim
def get_globe_item(self, repo: Optional[DataSite] = None,
lazy_load: bool = False) -> 'ItemPage':
"""
Return the ItemPage corresponding to the globe.
Note that the globe need not be in the same data repository as the
Coordinate itself.
A successful lookup is stored as an internal value to avoid the need
for repeated lookups.
:param repo: the Wikibase site for the globe, if different from that
provided with the Coordinate.
:param lazy_load: Do not raise NoPage if ItemPage does not exist.
:return: pywikibot.ItemPage
"""
if isinstance(self._entity, ItemPage):
return self._entity
repo = repo or self.site
return ItemPage.from_entity_uri(repo, self.entity, lazy_load)
class WbTime(_WbRepresentation):
"""A Wikibase time representation."""
PRECISION = {'1000000000': 0,
'100000000': 1,
'10000000': 2,
'1000000': 3,
'100000': 4,
'10000': 5,
'millenia': 6,
'century': 7,
'decade': 8,
'year': 9,
'month': 10,
'day': 11,
'hour': 12,
'minute': 13,
'second': 14
}
FORMATSTR = '{0:+012d}-{1:02d}-{2:02d}T{3:02d}:{4:02d}:{5:02d}Z'
_items = ('year', 'month', 'day', 'hour', 'minute', 'second',
'precision', 'before', 'after', 'timezone', 'calendarmodel')
def __init__(self,
year: Optional[int] = None,
month: Optional[int] = None,
day: Optional[int] = None,
hour: Optional[int] = None,
minute: Optional[int] = None,
second: Optional[int] = None,
precision: Union[int, str, None] = None,
before: int = 0,
after: int = 0,
timezone: int = 0,
calendarmodel: Optional[str] = None,
site: Optional[DataSite] = None) -> None:
"""Create a new WbTime object.
The precision can be set by the Wikibase int value (0-14) or by a human
readable string, e.g., 'hour'. If no precision is given, it is set
according to the given time units.
Timezone information is given in three different ways depending on the
time:
* Times after the implementation of UTC (1972): as an offset from UTC
in minutes;
* Times before the implementation of UTC: the offset of the time zone
from universal time;
* Before the implementation of time zones: The longitude of the place
of the event, in the range −180° to 180°, multiplied by 4 to convert
to minutes.
:param year: The year as a signed integer of between 1 and 16 digits.
:param month: Month
:param day: Day
:param hour: Hour
:param minute: Minute
:param second: Second
:param precision: The unit of the precision of the time.
:param before: Number of units after the given time it could be, if
uncertain. The unit is given by the precision.
:param after: Number of units before the given time it could be, if
uncertain. The unit is given by the precision.
:param timezone: Timezone information in minutes.
:param calendarmodel: URI identifying the calendar model
:param site: The Wikibase site
"""
if year is None:
raise ValueError('no year given')
self.precision = self.PRECISION['second']
if second is None:
self.precision = self.PRECISION['minute']
second = 0
if minute is None:
self.precision = self.PRECISION['hour']
minute = 0
if hour is None:
self.precision = self.PRECISION['day']
hour = 0
if day is None:
self.precision = self.PRECISION['month']
day = 1
if month is None:
self.precision = self.PRECISION['year']
month = 1
self.year = year
self.month = month
self.day = day
self.hour = hour
self.minute = minute
self.second = second
self.after = after
self.before = before
self.timezone = timezone
if calendarmodel is None:
if site is None:
site = Site().data_repository()
if site is None:
raise ValueError('Site {} has no data repository'
.format(Site()))
calendarmodel = site.calendarmodel()
self.calendarmodel = calendarmodel
# if precision is given it overwrites the autodetection above
if precision is not None:
if (isinstance(precision, int)
and precision in self.PRECISION.values()):
self.precision = precision
elif precision in self.PRECISION:
assert isinstance(precision, str)
self.precision = self.PRECISION[precision]
else:
raise ValueError('Invalid precision: "{}"'.format(precision))
@classmethod
def fromTimestr(cls: WB_TIME_CLASS,
datetimestr: str,
precision: Union[int, str] = 14,
before: int = 0,
after: int = 0,
timezone: int = 0,
calendarmodel: Optional[str] = None,
site: Optional[DataSite] = None) -> 'WbTime':
"""Create a new WbTime object from a UTC date/time string.
The timestamp differs from ISO 8601 in that:
* The year is always signed and having between 1 and 16 digits;
* The month, day and time are zero if they are unknown;
* The Z is discarded since time zone is determined from the timezone
param.
:param datetimestr: Timestamp in a format resembling ISO 8601,
e.g. +2013-01-01T00:00:00Z
:param precision: The unit of the precision of the time.
:param before: Number of units after the given time it could be, if
uncertain. The unit is given by the precision.
:param after: Number of units before the given time it could be, if
uncertain. The unit is given by the precision.
:param timezone: Timezone information in minutes.
:param calendarmodel: URI identifying the calendar model
:param site: The Wikibase site
"""
match = re.match(r'([-+]?\d+)-(\d+)-(\d+)T(\d+):(\d+):(\d+)Z',
datetimestr)
if not match:
raise ValueError("Invalid format: '{}'".format(datetimestr))
t = match.groups()
return cls(int(t[0]), int(t[1]), int(t[2]),
int(t[3]), int(t[4]), int(t[5]),
precision, before, after, timezone, calendarmodel, site)
@classmethod
def fromTimestamp(cls: WB_TIME_CLASS, timestamp: 'Timestamp',
precision: Union[int, str] = 14,
before: int = 0, after: int = 0,
timezone: int = 0, calendarmodel: Optional[str] = None,
site: Optional[DataSite] = None) -> 'WbTime':
"""
Create a new WbTime object from a pywikibot.Timestamp.
:param timestamp: Timestamp
:param precision: The unit of the precision of the time.
:param before: Number of units after the given time it could be, if
uncertain. The unit is given by the precision.
:param after: Number of units before the given time it could be, if
uncertain. The unit is given by the precision.
:param timezone: Timezone information in minutes.
:param calendarmodel: URI identifying the calendar model
:param site: The Wikibase site
"""
return cls.fromTimestr(timestamp.isoformat(), precision=precision,
before=before, after=after,
timezone=timezone, calendarmodel=calendarmodel,
site=site)
def toTimestr(self, force_iso: bool = False) -> str:
"""
Convert the data to a UTC date/time string.
See fromTimestr() for differences between output with and without
force_iso.
:param force_iso: whether the output should be forced to ISO 8601
:return: Timestamp in a format resembling ISO 8601
"""
if force_iso:
return Timestamp._ISO8601Format_new.format(
self.year, max(1, self.month), max(1, self.day),
self.hour, self.minute, self.second)
return self.FORMATSTR.format(self.year, self.month, self.day,
self.hour, self.minute, self.second)
def toTimestamp(self) -> Timestamp:
"""
Convert the data to a pywikibot.Timestamp.
:raises ValueError: instance value cannot be represented using
Timestamp
"""
if self.year <= 0:
raise ValueError('You cannot turn BC dates into a Timestamp')
return Timestamp.fromISOformat(
self.toTimestr(force_iso=True).lstrip('+'))
def toWikibase(self) -> Dict[str, Any]:
"""
Convert the data to a JSON object for the Wikibase API.
:return: Wikibase JSON
"""
json = {'time': self.toTimestr(),
'precision': self.precision,
'after': self.after,
'before': self.before,
'timezone': self.timezone,
'calendarmodel': self.calendarmodel
}
return json
@classmethod
def fromWikibase(cls: WB_TIME_CLASS, data: Dict[str, Any],
site: Optional[DataSite] = None) -> 'WbTime':
"""
Create a WbTime from the JSON data given by the Wikibase API.
:param data: Wikibase JSON
:param site: The Wikibase site
"""
return cls.fromTimestr(data['time'], data['precision'],
data['before'], data['after'],
data['timezone'], data['calendarmodel'], site)
class WbQuantity(_WbRepresentation):
"""A Wikibase quantity representation."""
_items = ('amount', 'upperBound', 'lowerBound', 'unit')
@staticmethod
def _require_errors(site: Optional[DataSite]) -> bool:
"""
Check if Wikibase site is so old it requires error bounds to be given.
If no site item is supplied it raises a warning and returns True.
:param site: The Wikibase site
"""
if not site:
warning(
"WbQuantity now expects a 'site' parameter. This is needed to "
'ensure correct handling of error bounds.')
return False
return site.mw_version < '1.29.0-wmf.2'
@staticmethod
def _todecimal(value: TO_DECIMAL_TYPE) -> Optional[Decimal]:
"""
Convert a string to a Decimal for use in WbQuantity.
None value is returned as is.
:param value: decimal number to convert
"""
if isinstance(value, Decimal):
return value
if value is None:
return None
return Decimal(str(value))
@staticmethod
def _fromdecimal(value: Optional[Decimal]) -> Optional[str]:
"""
Convert a Decimal to a string representation suitable for WikiBase.
None value is returned as is.
:param value: decimal number to convert
"""
return format(value, '+g') if value is not None else None
def __init__(self, amount: TO_DECIMAL_TYPE,
unit: OPT_STR_OR_ITEM_PAGE = None,
error: Union[TO_DECIMAL_TYPE,
Tuple[TO_DECIMAL_TYPE, TO_DECIMAL_TYPE]] = None,
site: Optional[DataSite] = None) -> None:
"""
Create a new WbQuantity object.
:param amount: number representing this quantity
:param unit: the Wikibase item for the unit or the entity URI of this
Wikibase item.
:param error: the uncertainty of the amount (e.g. ±1)
:param site: The Wikibase site
"""
if amount is None:
raise ValueError('no amount given')
self.amount = self._todecimal(amount)
self._unit = unit
self.site = site or Site().data_repository()
# also allow entity URIs to be provided via unit parameter
if isinstance(unit, str) \
and unit.partition('://')[0] not in ('http', 'https'):
raise ValueError("'unit' must be an ItemPage or entity uri.")
if error is None and not self._require_errors(site):
self.upperBound = self.lowerBound = None
else:
if error is None:
upperError = lowerError = Decimal(0) # type: Optional[Decimal]
elif isinstance(error, tuple):
upperError = self._todecimal(error[0])
lowerError = self._todecimal(error[1])
else:
upperError = lowerError = self._todecimal(error)
assert upperError is not None and lowerError is not None
assert self.amount is not None
self.upperBound = self.amount + upperError
self.lowerBound = self.amount - lowerError
@property
def unit(self) -> str:
"""Return _unit's entity uri or '1' if _unit is None."""
if isinstance(self._unit, ItemPage):
return self._unit.concept_uri()
return self._unit or '1'
def get_unit_item(self, repo: Optional[DataSite] = None,
lazy_load: bool = False) -> 'ItemPage':
"""
Return the ItemPage corresponding to the unit.
Note that the unit need not be in the same data repository as the
WbQuantity itself.
A successful lookup is stored as an internal value to avoid the need
for repeated lookups.
:param repo: the Wikibase site for the unit, if different from that
provided with the WbQuantity.
:param lazy_load: Do not raise NoPage if ItemPage does not exist.
:return: pywikibot.ItemPage
"""
if not isinstance(self._unit, str):
return self._unit
repo = repo or self.site
self._unit = ItemPage.from_entity_uri(repo, self._unit, lazy_load)
return self._unit
def toWikibase(self) -> Dict[str, Any]:
"""
Convert the data to a JSON object for the Wikibase API.
:return: Wikibase JSON
"""
json = {'amount': self._fromdecimal(self.amount),
'upperBound': self._fromdecimal(self.upperBound),
'lowerBound': self._fromdecimal(self.lowerBound),
'unit': self.unit
}
return json
@classmethod
def fromWikibase(cls: WB_QUANTITY_CLASS, data: Dict[str, Any],
site: Optional[DataSite] = None) -> 'WbQuantity':
"""
Create a WbQuantity from the JSON data given by the Wikibase API.
:param data: Wikibase JSON
:param site: The Wikibase site
"""
amount = cls._todecimal(data['amount'])
upperBound = cls._todecimal(data.get('upperBound'))
lowerBound = cls._todecimal(data.get('lowerBound'))
bounds_provided = (upperBound is not None and lowerBound is not None)
error = None
if bounds_provided or cls._require_errors(site):
error = (upperBound - amount, amount - lowerBound)
if data['unit'] == '1':
unit = None
else:
unit = data['unit']
return cls(amount, unit, error, site)
class WbMonolingualText(_WbRepresentation):
"""A Wikibase monolingual text representation."""
_items = ('text', 'language')
def __init__(self, text: str, language: str):
"""
Create a new WbMonolingualText object.
:param text: text string
:param language: language code of the string
"""
if not text or not language:
raise ValueError('text and language cannot be empty')
self.text = text
self.language = language
def toWikibase(self) -> Dict[str, Any]:
"""
Convert the data to a JSON object for the Wikibase API.
:return: Wikibase JSON
"""
json = {'text': self.text,
'language': self.language
}
return json
@classmethod
def fromWikibase(cls: WB_MONOLINGUAL_TEXT_CLASS, data: Dict[str, Any],
site: Optional[DataSite] = None) -> 'WbMonolingualText':
"""
Create a WbMonolingualText from the JSON data given by Wikibase API.
:param data: Wikibase JSON
:param site: The Wikibase site
"""
return cls(data['text'], data['language'])
class _WbDataPage(_WbRepresentation):
"""
A Wikibase representation for data pages.
A temporary implementation until T162336 has been resolved.
Note that this class cannot be used directly
"""
_items = ('page', )
@classmethod
def _get_data_site(cls: WB_DATA_PAGE_CLASS, repo_site: DataSite
) -> APISite:
"""
Return the site serving as a repository for a given data type.
Must be implemented in the extended class.
:param repo_site: The Wikibase site
"""
raise NotImplementedError
@classmethod
def _get_type_specifics(cls: WB_DATA_PAGE_CLASS, site: DataSite
) -> Dict[str, Any]:
"""
Return the specifics for a given data type.
Must be implemented in the extended class.
The dict should have three keys:
* ending: str, required filetype-like ending in page titles.
* label: str, describing the data type for use in error messages.
* data_site: APISite, site serving as a repository for
the given data type.
:param site: The Wikibase site
"""
raise NotImplementedError
@staticmethod
def _validate(page: 'Page', data_site: 'BaseSite', ending: str,
label: str) -> None:
"""
Validate the provided page against general and type specific rules.
:param page: Page containing the data.
:param data_site: The site serving as a repository for the given
data type.
:param ending: Required filetype-like ending in page titles.
E.g. '.map'
:param label: Label describing the data type in error messages.
"""
if not isinstance(page, Page):
raise ValueError(
'Page {} must be a pywikibot.Page object not a {}.'
.format(page, type(page)))
# validate page exists
if not page.exists():
raise ValueError('Page {} must exist.'.format(page))
# validate page is on the right site, and that site supports the type
if not data_site:
raise ValueError(
'The provided site does not support {}.'.format(label))
if page.site != data_site:
raise ValueError(
'Page must be on the {} repository site.'.format(label))
# validate page title fulfills hard-coded Wikibase requirement
# pcre regexp: '/^Data:[^\\[\\]#\\\:{|}]+\.map$/u' for geo-shape
# pcre regexp: '/^Data:[^\\[\\]#\\\:{|}]+\.tab$/u' for tabular-data
# As we have already checked for existence the following simplified
# check should be enough.
if not page.title().startswith('Data:') \
or not page.title().endswith(ending):
raise ValueError(
"Page must be in 'Data:' namespace and end in '{}' "
'for {}.'.format(ending, label))
def __init__(self, page: 'Page', site: Optional[DataSite] = None) -> None:
"""
Create a new _WbDataPage object.
:param page: page containing the data
:param site: The Wikibase site
"""
site = site or page.site.data_repository()
specifics = type(self)._get_type_specifics(site)
_WbDataPage._validate(page, specifics['data_site'],
specifics['ending'], specifics['label'])
self.page = page
def __hash__(self) -> int:
"""Override super.hash() as toWikibase is a string for _WbDataPage."""
return hash(self.toWikibase())
def toWikibase(self) -> str:
"""
Convert the data to the value required by the Wikibase API.
:return: title of the data page incl. namespace
"""
return self.page.title()
@classmethod
def fromWikibase(cls: WB_DATA_PAGE_CLASS, page_name: str,
site: Optional[DataSite]) -> '_WbDataPage':
"""
Create a _WbDataPage from the JSON data given by the Wikibase API.
:param page_name: page name from Wikibase value
:param site: The Wikibase site
"""
# TODO: This method signature does not match our parent class (which
# takes a dictionary argument rather than a string). We should either
# change this method's signature or rename this method.
data_site = cls._get_data_site(site)
page = Page(data_site, page_name)
return cls(page, site)
class WbGeoShape(_WbDataPage):
"""A Wikibase geo-shape representation."""
@classmethod
def _get_data_site(cls: WB_GEO_SHAPE_CLASS, site: DataSite) -> APISite:
"""
Return the site serving as a geo-shape repository.
:param site: The Wikibase site
"""
return site.geo_shape_repository()
@classmethod
def _get_type_specifics(cls: WB_GEO_SHAPE_CLASS, site: DataSite
) -> Dict[str, Any]:
"""
Return the specifics for WbGeoShape.
:param site: The Wikibase site