-
Notifications
You must be signed in to change notification settings - Fork 0
/
add_label.py
2456 lines (2109 loc) · 111 KB
/
add_label.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
#!/usr/bin/python3
codedoc = """
copy_label.py - Amend Wikikdata, Wikimedia Commons, and Wikipedia; autocorrect, and register missing statements.
This is a complex script, updating at the same time Wikidata, Wikimedia Commons, and Wikipedia.
It takes advantage of the integration and the interrelations amongst those platforms.
It takes care of local languages; avoiding hard-coding, reading configuration data from Wikidata.
It completely works multi-lingual. It avoids problems with non-roman languages or conventions of central-European languages.
Wikidata:
It performs quality checks and amends missing data and claims.
* Correct Norwegian language mismatches (no-nb language mapping mismatch between Wikipedia and Wikidata).
* Wikipedia site links are merged as aliases.
* Copy human labels to other languages
* Add missing Wikidata statements
* Symmetric "Equal to" statements are added.
* "Not-equal to" statements are generated when there are homonyms detected.
* Reflexive "Not-equal to" statements are removed.
* Symmetric "Not-equal to" statements are added.
* Person's native language and languages used are completed.
* Redundant aliases are removed.
* Any alias for which there is no label are moved to label.
* Unregistered Wikipedia site links for which there exist language labels are added to Wikidata.
* Unrecognized Unicodes are not processed.
* Non-western encoded languages are skipped (but Wikipedia sitelinks are processed).
* Automatic case matching (language specific first captital handling like e.g. in German).
Wikimedia Commons:
It derives SDC P180 depict statements from P18 and related Wikidata statements.
It generates Commonscat statements both in Wikidata, Wikimedia Commons, and Wikipedia.
* Register missing Wikimedia Commons Categories
* A {{Wikidata Infobox}} is added to Commons Category pages
Wikipedia:
Based on metadata in Wikidata, it automatically updates Wikipedia.
* Add infoboxes
* Add a first image (based on P18 in Wikidata).
* Add Appendix (references)
* Add Wikipedia Authority control templates for humans
* Add DEFAULTSORT for humans (lastname, firstname)
* Amend Wikipedia pages for all languages with Commonscat templates
* Add Wikipedia categories
Parameters:
P1: source language code (default: LANGUAGE, LC_ALL, LANG environment variables)
P2...: additional language codes for site-link check and label replication
Take care to only include Western (Roman) languages.
stdin: list of Q-numbers to process (extracted via regular expression)
Duplicate and incompatible instances or subclases are ignored.
Flags:
-c Force copy (bypass instance validation restriction)
-d Debug mode
-h Show help
-i Copy instance labels to item descriptions
-l Disable language labels update
-p Proceed after error
-q Quiet mode
-r Repeat modus
-t Test modus (read only check)
Filters:
Western languags are "whitelisted".
Non-Western languages and some countries are "blacklisted" to avoid erronuous updates
(due to e.g. East European languistic conventions).
The following Q-numbers are (partially) ignored when copying labels: (sitelinks are processed)
Duplicate Q-numbers
Subclasses are ignored
Some instances are excluded
Items having non-roman language labels, descriptions or aliases
Return status:
The following status codes are returned to the shell:
0 Normal termination
1 Help requested (-h)
3 Invalid or missing parameter
10 Homonym
11 Redirect
12 Item does not exist
14 No revision ID
20 General error (Maxlag error, network error)
130 Ctrl-c pressed, program interrupted
Error handling:
This script should normally not stack dump, unless a severe (network or server) error occurs.
Any error will be returned into the return status, and the error description.
It has intelligent error handling with self-healing code when possible.
Wikidata run-time errors and timeouts are properly handled and reported.
Processing typically continues after a 60s retry/timeout.
Data quality ensurance:
It does not create duplicate statements.
It does not create contradictory statements.
It does not break constraints.
It does not overrule statements.
Volume processing:
For high volumes a Bot account is required; the maximum speed is 1 transaction/second.
The Wikidata user is responsible to adhere to:
https://www.wikidata.org/wiki/Wikidata:Bots
https://www.wikidata.org/wiki/Wikidata:Creating_a_bot
https://www.mediawiki.org/wiki/Manual:Pywikibot/user-config.py
For non-bot accounts there is a maximum of 1 transaction per minute.
Responsibilities:
The person running this script is the sole responsible for any erronuous updates the script is performing.
This script is offered to the user as best-effort.
The author does not accept any responsibility for any bugs in the script.
Bugs should be reported to the author, to be able to ameliorate the script.
Prequisites:
Install Pywikibot client software
See https://www.wikidata.org/wiki/Wikidata:Pywikibot_-_Python_3_Tutorial
Principles:
Use data instead of code.
Use Wikidata data instead of hard-coding.
Only use hard-coding if there is no other solution.
Use a clear and simple data model.
Keep the logic and code simple.
Use standard properties and statements.
Be universal, with respect of local conventions.
Be independant of language.
Augment data quality.
Use standard coding.
Author:
Geert Van Pamel, 2021-01-30, MIT License, User:Geertivp
Documentation:
https://doc.wikimedia.org/pywikibot/stable/api_ref/pywikibot.html
https://doc.wikimedia.org/pywikibot/stable/api_ref/pywikibot.page.html
https://doc.wikimedia.org/pywikibot/master/api_ref/pywikibot.site.html
https://www.wikidata.org/wiki/Wikidata:Wikidata_curricula/Activities/Pywikibot/Missing_label_in_target_language
https://www.mediawiki.org/wiki/Manual:Pywikibot/Wikidata
https://www.wikidata.org/wiki/Wikidata:Pywikibot_-_Python_3_Tutorial/Setting_statements
https://public.paws.wmcloud.org/47732266/03%20-%20Wikidata.ipynb
https://stackoverflow.com/questions/36406862/check-whether-an-item-with-a-certain-label-and-description-already-exists-on-wik
https://www.mediawiki.org/wiki/Wikibase/API
https://www.wikidata.org/w/api.php?action=help&modules=wbsearchentities
https://stackoverflow.com/questions/761804/how-do-i-trim-whitespace-from-a-string
https://doc.wikimedia.org/pywikibot/master/api_ref/pywikibot.html
https://docs.python.org/3/library/datetime.html
https://docs.python.org/3/library/re.html
https://byabbe.se/2020/09/15/writing-structured-data-on-commons-with-python
https://doc.wikimedia.org/pywikibot/master/_modules/cosmetic_changes.html#CosmeticChangesToolkit.translateMagicWords
Error handling:
pywikibot.exceptions.OtherPageSaveError
WARNING: API error failed-save: The save has failed.
Error processing Q752115, Edit to page [[wikidata:Q752115]] failed:
1/ There already exist a Wikipedia article with the same name linked to another item.
This automatically adds a missing "not equal to" statement https://www.wikidata.org/wiki/Property:P1889
2/ There exist another language label with an identical description.
3/ Conflicting Commons Category page
4/ Conflicting sitelink
Example query to replicate person names:
This script has as stdin (standard input) a list of Q-numbers (which are obtained via a regular expression).
Example queries:
SELECT ?item ?itemLabel WHERE {
?item wdt:P31 wd:Q5;
wdt:P27 wd:Q31; # Q29999
rdfs:label ?itemLabel.
FILTER((LANG(?itemLabel)) = "nl")
MINUS {
?item rdfs:label ?lang_label.
FILTER((LANG(?lang_label)) = "da")
}
}
ORDER BY (?itemLabel)
# Uses 50% less elapsed time
SELECT ?item ?itemLabel WHERE {
?item wdt:P31 wd:Q5;
wdt:P27 wd:Q29999;
rdfs:label ?itemLabel.
FILTER((LANG(?itemLabel)) = "nl")
FILTER(NOT EXISTS {
?item rdfs:label ?lang_label.
FILTER(LANG(?lang_label) = "da")
})
}
ORDER BY (?itemLabel)
# Get all items linked to WMBE WikiProjects that have missing labels
SELECT distinct ?item WHERE {
?item wdt:P31 wd:Q5;
wdt:P6104 ?wikiproject.
?wikiproject wdt:P31 wd:Q16695773;
wdt:P664 wd:Q18398868.
MINUS {
?item rdfs:label ?label.
FILTER((LANG(?label)) = "da")
}
}
SELECT DISTINCT ?item ?itemLabel WHERE {
?item wdt:P31 wd:Q5;
rdfs:label ?itemLabel;
wdt:P6104 ?wikiproject.
FILTER((LANG(?itemLabel)) = "nl")
MINUS {
?item rdfs:label ?label.
FILTER((LANG(?label)) = "da")
}
}
ORDER BY (?itemLabel)
SELECT DISTINCT ?item WHERE {
?item wdt:P6104 ?wikiproject.
?wikiproject wdt:P31 wd:Q16695773;
wdt:P664 wd:Q18398868.
}
Testing and debugging:
Unexisting item: Q41360837
Known problems:
WARNING: API error badtoken: Invalid CSRF token.
Restart the script.
Remote end closed connection without response
Restart the script.
Wikidata requires a bot flag.
Some Wikipedia platforms require a bot flag. Others are more flexible.
You might require repeat mode (-r) to update Wikipedia.
Similer projects:
Add Names as labels: https://www.wikidata.org/wiki/Q21640602
"""
# List the required modules
import json # json data structures
import os # Operating system: getenv
import pywikibot # API interface to Wikidata
import re # Regular expressions (very handy!)
import sys # System: argv, exit (get the parameters, terminate the program)
import time # sleep
import unidecode # Unicode
from datetime import datetime # now, strftime, delta time, total_seconds
from datetime import timedelta
# Global variables
modnm = 'Pywikibot copy_label' # Module name (using the Pywikibot package)
pgmid = '2023-09-13 (gvp)' # Program ID and version
pgmlic = 'MIT License'
creator = 'User:Geertivp'
"""
Static definitions
"""
# Functional configuration flags
# Restrictions: cannot disable both labels and wikipedia. We need at least one of the options.
# Defaults: transparent and safe
forcecopy = False # Force copy
lead_lower = False # Leading lowercase
lead_upper = False # Leading uppercase
overrule = False # Overrule
repeatmode = False # Repeat mode
repldesc = False # Replicate instance description labels
uselabels = True # Use the language labels (disable with -l)
# Technical configuration flags
errorstat = True # Show error statistics (disable with -e)
exitfatal = True # Exit on fatal error (can be disabled with -p; please take care)
shell = True # Shell available (command line parameters are available; automatically overruled by PAWS)
verbose = True # Can be set with -q or -v (better keep verbose to monitor the bot progress)
# Technical parameters
"""
Default error penalty wait factor (can be overruled with -f).
Larger values ensure that maxlag errors are avoided, but temporarily delay processing.
It is advised not to overrule this value.
"""
exitstat = 0 # (default) Exit status
errwaitfactor = 4 # Extra delay after error; best to keep the default value (maximum delay of 4 x 150 = 600 s = 10 min)
maxdelay = 150 # Maximum error delay in seconds (overruling any extreme long processing delays)
# To be set in user-config.py (which parameters is PAWS using?)
"""
maxlag = 5 # avoid overloading the servers
max_retries = 4 # avoid overloading the servers
maxthrottle = 60 # ?
noisysleep = 60.0 # avoid the majority/all of the confusing sleep messages (noisy sleep)
put_throttle = 1 # maximum transaction speed (bot account required)
retry_max = 320 # avoid overloading the servers
retry_wait = 30 # avoid overloading the servers
"""
# Wikidata transaction comment
BOTFLAG = True # Should be False for non-bot accounts
transcmt = '#pwb Copy label'
# Language settings
ENLANG = 'en'
enlang_list = [ENLANG]
# Namespaces
# https://www.mediawiki.org/wiki/Help:Namespaces
# https://nl.wikipedia.org.org/w/api.php?action=query&meta=siteinfo&siprop=namespaces&formatversion=2
MAINNAMESPACE = 0
FILENAMESPACE = 6
TEMPLATENAMESPACE = 10
CATEGORYNAMESPACE = 14
# Properties
VIDEOPROP = 'P10'
MAPPROP = 'P15'
COUNTRYPROP = 'P17'
IMAGEPROP = 'P18'
FATHERPROP = 'P22'
MOTHERPROP = 'P25'
MARIAGEPARTNERPROP = 'P26'
NATIONALITYPROP = 'P27'
INSTANCEPROP = 'P31'
CHILDPROP = 'P40'
FLAGPROP = 'P41'
BORDERPEERPROP = 'P47'
AUDIOPROP = 'P51'
COATOFARMSPROP = 'P94'
NOBLENAMEPROP = 'P97'
NATIVELANGPROP = 'P103'
SIGNATUREPROP = 'P109'
MANAGEITEMPROP = 'P121'
PROPERTYOFPROP = 'P127'
OPERATORPROP = 'P137'
LOGOPROP = 'P154'
DEPICTSPROP = 'P180'
LOCATORMAPPROP = 'P242'
SUBCLASSPROP = 'P279'
FOREIGNSCRIPTPROP = 'P282'
MAINSUBJECTPROP = 'P301'
PARTOFPROP = 'P361'
COMMONSCATPROP = 'P373'
PARTNERPROP = 'P451'
EQTOPROP = 'P460'
COUNTRYORIGPROP = 'P495'
BIRTHDATEPROP = 'P569'
DEATHDATEPROP = 'P570'
CONTAINSPROP = 'P527'
FOUNDINGDATEPROP = 'P571'
DISSOLVDATEPROP = 'P576'
STARTDATEPROP = 'P580'
ENDDATEPROP = 'P582'
TIMEPROP = 'P585'
"""
P585 {
"after": 0,
"before": 0,
"calendarmodel": "http://www.wikidata.org/entity/Q1985727",
"precision": 11,
"time": "+00000001879-06-19T00:00:00Z",
"timezone": 0
}
"""
QUALIFYFROMPROP = 'P642'
OPERATINGDATEPROP = 'P729'
SERVICEENDDATEPROP = 'P730'
LASTNAMEPROP = 'P734'
FIRSTNAMEPROP = 'P735'
MAINCATEGORYPROP = 'P910'
VOYAGEBANPROP = 'P948'
COMMONSGALLARYPROP = 'P935'
VOICERECORDPROP = 'P990'
PDFPROP = 'P996'
JURISDICTIONPROP = 'P1001'
CAMERALOCATIONPROP = 'P1259'
EARLYTIMEPROP = 'P1319'
LATETIMEPROP = 'P1326'
BUSINESSPARTNERPROP = 'P1327'
REPLACESPROP = 'P1365'
REPLACEDBYPROP = 'P1366'
LANGKNOWPROP = 'P1412'
GRAVEPROP = 'P1442'
COMMONSCREATORPROP = 'P1472'
NATIVENAMEPROP = 'P1559'
COMMONSINSTPROP = 'P1612'
PLACENAMEPROP = 'P1766'
PLAQUEPROP = 'P1801'
HASPROPERTYPROP = 'P1830'
NOTEQTOPROP = 'P1889'
COLLAGEPROP = 'P2716'
ICONPROP = 'P2910'
WORKINGLANGPROP = 'P2936'
PARTITUREPROP = 'P3030'
DESIGNPLANPROP = 'P3311'
KEYRELATIONPROP = 'P3342'
SIBLINGPROP = 'P3373'
NIGHTVIEWPROP = 'P3451'
OBJECTROLEPROP = 'P3831'
PANORAMAPROP = 'P4640'
WINTERVIEWPROP = 'P5252'
DIAGRAMPROP = 'P5555'
INTERIORPROP = 'P5775'
VERSOPROP = 'P7417'
RECTOPROP = 'P7418'
FRAMEWORKPROP = 'P7420'
VIEWPROP = 'P8517'
AERIALVIEWPROP = 'P8592'
PARENTPROP = 'P8810'
FAVICONPROP = 'P8972'
OBJECTLOCATIONPROP = 'P9149'
COLORWORKPROP = 'P10093'
# List of media properties (audio, image, video)
media_props = {
AERIALVIEWPROP,
COATOFARMSPROP,
COLLAGEPROP,
COLORWORKPROP,
DESIGNPLANPROP,
DIAGRAMPROP,
FAVICONPROP,
FLAGPROP,
FRAMEWORKPROP,
GRAVEPROP,
ICONPROP,
IMAGEPROP,
INTERIORPROP,
LOCATORMAPPROP,
LOGOPROP,
MAPPROP,
NIGHTVIEWPROP,
PANORAMAPROP,
PARTITUREPROP,
PDFPROP,
PLACENAMEPROP,
PLAQUEPROP,
RECTOPROP,
SIGNATUREPROP,
VERSOPROP,
VIDEOPROP,
VIEWPROP,
VOICERECORDPROP,
VOYAGEBANPROP,
WINTERVIEWPROP,
}
# To generate compound SDC depict statements
# for indirect media file references
# using 'of' qualifier
depict_item_type = {
COATOFARMSPROP: 'Q14659',
COLLAGEPROP: 'Q170593',
DESIGNPLANPROP: 'Q611203',
FAVICONPROP: 'Q2130',
FLAGPROP: 'Q14660',
GRAVEPROP: 'Q173387',
ICONPROP: 'Q138754',
LOCATORMAPPROP: 'Q6664848',
LOGOPROP: 'Q1886349',
MAPPROP: 'Q2298569',
PANORAMAPROP: 'Q658252',
PLACENAMEPROP: 'Q55498668',
PLAQUEPROP: 'Q721747',
SIGNATUREPROP: 'Q188675',
VIDEOPROP: 'Q98069877',
VOICERECORDPROP: 'Q53702817',
VOYAGEBANPROP: 'Q22920576',
}
# List of conflicting properties
conflicting_statement = {
EQTOPROP: NOTEQTOPROP,
# others to be added
}
# Mandatory relationships
# Get list via P1696 (could we possibly generate this dictionary dynamically?)
# https://www.wikidata.org/wiki/Property:P1696 (inverse property)
# https://www.wikidata.org/wiki/Property:P7087 (inverse label)
mandatory_relation = {
# Symmetric
BUSINESSPARTNERPROP: BUSINESSPARTNERPROP,
BORDERPEERPROP: BORDERPEERPROP,
EQTOPROP: EQTOPROP,
MARIAGEPARTNERPROP: MARIAGEPARTNERPROP,
NOTEQTOPROP: NOTEQTOPROP,
PARTNERPROP: PARTNERPROP,
SIBLINGPROP: SIBLINGPROP,
# Reciproque bidirectional
CONTAINSPROP: PARTOFPROP, PARTOFPROP: CONTAINSPROP,
MAINCATEGORYPROP: MAINSUBJECTPROP, MAINSUBJECTPROP: MAINCATEGORYPROP,
MANAGEITEMPROP: OPERATORPROP, OPERATORPROP: MANAGEITEMPROP,
REPLACESPROP: REPLACEDBYPROP, REPLACEDBYPROP: REPLACESPROP,
PROPERTYOFPROP: HASPROPERTYPROP, HASPROPERTYPROP: PROPERTYOFPROP,
# Reciproque unidirectional (mind the 1:M relationship)
FATHERPROP: CHILDPROP, #CHILDPROP: FATHERPROP,
MOTHERPROP: CHILDPROP, #CHILDPROP: MOTHERPROP,
PARENTPROP: CHILDPROP, #CHILDPROP: PARENTPROP,
# others to be added
}
# Instances
HUMANINSTANCE = 'Q5'
ESPERANTOLANGINSTANCE = 'Q143'
WIKIMEDIACATINSTANCE = 'Q4167836'
# Specific sequence to be aligned with sitelink_dict_list
instance_types = [
{HUMANINSTANCE}, # Human
{'Q185187', 'Q38720'}, # Mills
]
# Allow to copy the description from one instance to another
copydesc_item_list = {
WIKIMEDIACATINSTANCE, # https://www.wikidata.org/wiki/Q121065933
}
# human, last name, male first name, female first name, neutral first name, affixed family name, family, personage
human_type_list = {HUMANINSTANCE, 'Q101352', 'Q12308941', 'Q11879590', 'Q3409032', 'Q66480858', 'Q8436', 'Q95074'}
# last name, affixed family name, compound, toponiem
lastname_type_list = {'Q101352', 'Q66480858', 'Q60558422', 'Q17143070'}
# Add labels for all those (Roman) languages
# Do not add Central European languages like cs, hu, pl, sk, etc. because of special language rules
# Not Hungarian, Czech, Polish, Slovak, etc
all_languages = ['af', 'an', 'ast', 'ca', 'cy', 'da', 'de', 'en', 'es', 'fr', 'ga', 'gl', 'io', 'it', 'jut', 'nb', 'nl', 'nn', 'pms', 'pt', 'sc', 'sco', 'sje', 'sl', 'sq', 'sv']
# Filter the extension of nat_languages
lang_type_list = {'Q1288568', 'Q33742', 'Q34770'} # levende taal, natuurlijke taal, taal
# Initial list of natural languages
# Others will be added automatically during script execution
nat_languages = {'Q150', 'Q188', 'Q652', 'Q1321', 'Q1860', 'Q7411'}
# Languages using uppercase nouns
## Check if we can inherit this set from namespace or language properties??
upper_pref_lang = {'als', 'atj', 'bar', 'bat-smg', 'bjn', 'co?', 'dag', 'de', 'de-at', 'de-ch', 'diq', 'eu?', 'ext', 'fiu-vro', 'frp', 'ffr?', 'gcr', 'gsw', 'ha', 'hif?', 'ht', 'ik?', 'kaa?', 'kab', 'kbp?', 'ksh', 'lb', 'lfn?', 'lg', 'lld', 'mwl', 'nan', 'nds', 'nds-nl?', 'om?', 'pdc?', 'pfl', 'rmy', 'rup', 'sgs', 'shi', 'sn', 'tum', 'vec', 'vmf', 'vro', 'wo?'}
# Avoid risk for non-roman languages or rules
veto_countries = {
'Q148', 'Q159', 'Q15180', # China, Russia
}
# Veto languages
# Skip non-standard character encoding; see also ROMANRE (other name rules)
# see https://en.wikipedia.org/wiki/Wikipedia:Naming_conventions_(Cyrillic)
veto_languages = {'aeb', 'aeb-arab', 'aeb-latn', 'ar', 'arc', 'arq', 'ary', 'arz', 'bcc', 'be' ,'be-tarask', 'bg', 'bn', 'bgn', 'bqi', 'cs', 'ckb', 'cv', 'dv', 'el', 'fa', 'fi', 'gan', 'gan-hans', 'gan-hant', 'glk', 'gu', 'he', 'hi', 'hu', 'hy', 'ja', 'ka', 'khw', 'kk', 'kk-arab', 'kk-cn', 'kk-cyrl', 'kk-kz', 'kk-latn', 'kk-tr', 'ko', 'ks', 'ks-arab', 'ks-deva', 'ku', 'ku-arab', 'ku-latn', 'ko', 'ko-kp', 'lki', 'lrc', 'lzh', 'luz', 'mhr', 'mk', 'ml', 'mn', 'mzn', 'ne', 'new', 'or', 'os', 'ota', 'pl', 'pnb', 'ps', 'ro', 'ru', 'rue', 'sd', 'sdh', 'sh', 'sk', 'sr', 'sr-ec', 'ta', 'te', 'tg', 'tg-cyrl', 'tg-latn', 'th', 'ug', 'ug-arab', 'ug-latn', 'uk', 'ur', 'vep', 'vi', 'yi', 'yue', 'zg-tw', 'zh', 'zh-cn', 'zh-hans', 'zh-hant', 'zh-hk', 'zh-mo', 'zh-my', 'zh-sg', 'zh-tw'}
# Lookup table for language qnumbers (static update)
# How could we build this automatically?
lang_qnumbers = {'aeb':'Q56240', 'aeb-arab':'Q64362981', 'aeb-latn':'Q64362982', 'ar':'Q13955', 'arc':'Q28602', 'arq':'Q56499', 'ary':'Q56426', 'arz':'Q29919', 'bcc':'Q12634001', 'be':'Q9091', 'be-tarask':'Q8937989', 'bg':'Q7918', 'bn':'Q9610', 'bgn':'Q12645561', 'bqi':'Q257829', 'cs':'Q9056', 'ckb':'Q36811', 'cv':'Q33348', 'da':'Q9035', 'de':'Q188', 'dv':'Q32656', 'el':'Q9129', 'en':'Q1860', 'es':'Q1321', 'fa':'Q9168', 'fi':'Q1412', 'fr':'Q150', 'gan':'Q33475', 'gan-hans':'Q64427344', 'gan-hant':'Q64427346', 'gl':'Q9307', 'glk':'Q33657', 'gu':'Q5137', 'he':'Q9288', 'hi':'Q1568', 'hu':'Q9067', 'hy':'Q8785', 'it':'Q652', 'ja':'Q5287', 'ka':'Q8108', 'khw':'Q938216', 'kk':'Q9252', 'kk-arab':'Q90681452', 'kk-cn':'Q64427349', 'kk-cyrl':'Q90681280', 'kk-kz':'Q64427350', 'kk-latn':'Q64362993', 'kk-tr':'Q64427352', 'ko':'Q9176', 'ko-kp':'Q18784', 'ks':'Q33552', 'ks-arab':'Q64362994', 'ks-deva':'Q64362995', 'ku':'Q36368', 'ku-arab':'Q3678406', 'ku-latn':'Q64362997', 'lki':'Q18784', 'lrc':'Q19933293', 'lzh':'Q37041', 'luz':'Q12952748', 'mhr':'Q12952748', 'mk':'Q9296', 'ml':'Q36236', 'mn':'Q9246', 'mzn':'Q13356', 'ne':'Q33823', 'new':'Q33979', 'nl':'Q7411', 'no':'Q9043', 'or':'Q33810', 'os':'Q33968', 'ota':'Q36730', 'pl':'Q809', 'pnb':'Q1389492', 'ps':'Q58680', 'pt':'Q5146', 'ro':'Q7913', 'ru':'Q7737', 'rue':'Q26245', 'sd':'Q33997', 'sdh':'Q1496597', 'sh':'Q9301', 'sk':'Q9058', 'sl':'Q9063', 'sr':'Q9299', 'sr-ec':'Q21161942', 'sv':'Q9027', 'ta':'Q5885', 'te':'Q8097', 'tg':'Q9260', 'tg-cyrl':'Q64363004', 'tg-latn':'Q64363005', 'th':'Q9217', 'ug':'Q13263', 'ug-arab':'Q2374532', 'ug-latn':'Q986283', 'uk':'Q8798', 'ur':'Q1617', 'vep':'Q32747', 'vi':'Q9199', 'yi':'Q8641', 'yue':'Q9186', 'zh':'Q7850', 'zh-cn':'Q24841726', 'zh-hant':'Q18130932', 'zh-hans':'Q13414913', 'zh-hk':'Q100148307', 'zh-mo':'Q64427357', 'zh-my':'Q13646143', 'zh-sg':'Q1048980', 'zh-tw':'Q4380827'}
# Automatically augmented from veto_languages using lang_qnumbers mapping
veto_languages_id = {'Q7737', 'Q8798'}
# Accepted language scripts (e.g. Latin)
script_whitelist = {'Q8229'}
## Skip not yet fully described Wikipedia family members
new_wikis = {'altwiki', 'amiwiki', 'anpwiki', 'arywiki', 'avkwiki', 'guwwiki', 'kcgwiki', 'lldwiki', 'madwiki', 'mniwiki', 'pwnwiki', 'shiwiki', 'skrwiki', 'taywiki'}
new_wikis = {}
# Infobox without Wikidata functionality (to avoid empty emptyboxes)
veto_infobox = {'afwiki', 'enwiki', 'hrwiki', 'idwiki', 'iswiki', 'jawiki', 'kowiki', 'mrwiki', 'plwiki', 'shwiki', 'trwiki', 'warwiki', 'yowiki', 'zhwiki'}
# List of languages wanting to use the <references /> tag
veto_references = {'bgwiki', 'cswiki', 'fywiki', 'itwiki', 'nowiki', 'svwiki'}
# Avoid duplicate Commonscat templates (Commonscat included from templates)
veto_commonscat = {'fawiki', 'huwiki', 'hywiki', 'nowiki', 'plwiki', 'ukwiki', 'zeawiki'}
# Veto DEFAULTSORT
veto_defaultsort = {'nnwiki'}
# List of Wikipedia's that do not support bot updates (for different reasons)
veto_sitelinks = {
# Requires CAPTCHA => blocking bot scripts (?)
'eswiki', 'fawiki', 'jawiki', 'ptwiki', 'ruwiki', 'simplewiki', 'ttwiki', 'viwiki', 'wuuwiki', 'zhwiki',
# Blocked (requires mandatory bot flag)
'iswiki', # https://is.wikipedia.org/w/index.php?title=Kerfissíða:Aðgerðaskrár/block&page=User%3AGeertivpBot
'itwiki', # https://it.wikipedia.org/wiki/Special:Log/block?page=User:GeertivpBot
'slwiki', # Requires wikibot flag
'svwiki', # Infobox
'zh-yuewiki', # https://zh-yue.wikipedia.org/w/index.php?title=Special:日誌/block&page=User%3AGeertivpBot
# To proactively request a bot flag before updating statements
'enwiki',
# Bot approval pending
#'fiwiki',
# https://fi.wikipedia.org/wiki/Käyttäjä:GeertivpBot
# https://meta.wikimedia.org/wiki/User_talk:Geertivp#c-01miki10-20230714212500-Please_request_a_bot_flag_%40_fiwiki
# Unblocked (after an issue was fixed)
#'nowiki', # https://no.wikipedia.org/wiki/Brukerdiskusjon:GeertivpBot
# Unidentified problem
#'be-taraskwiki', # instantiated using different code "be-x-old" ??
# Non-issues (temporary or specific problems)
# 'cswiki',
# WARNING: Add Commonscat Fremantle Highway (ship, 2013) to cswiki
# ERROR: Error processing Q121093616, Edit to page [[cs:MV Fremantle Highway]] failed:
# Editing restricted by {{bots}}, {{nobots}} or site's equivalent of {{in use}} template
# https://cs.wikipedia.org/wiki/MV_Fremantle_Highway
# {{Pracuje se|2 dní}}
# Page is protected against (bot) updates. We can ignore this temporary restriction.
# https://cs.wikipedia.org/wiki/Speciální:Příspěvky/GeertivpBot
# others to be added
}
# List of recognized infoboxes
# Using this list, language templates are generated
sitelink_dict_list = [
# Required to be in sequence
# See also instance_types
'Q6249834', # infoboxlist[0] Infobox person (to generate Infobox template on Wikipedia), 39 s, 68 s
'Q13383928', # infoboxlist[1] Infobox Infobox windmill
'Q47517487', # infoboxlist[2] Wikidata infobox
'Q17534637', # infoboxlist[3] Infobox person Wikidata (overrule)
# Not required to be in sequence
# ... other infoboxes to be added...
# Human
'Q5615832', # Infobox author, 21 s, 22 s
'Q5616161', # Infobox musical artist, 4 s
'Q5624818', # Infobox scientist, 2 s
'Q5626285', # Infobox monarch
'Q5904762', # Infobox sportsperson
'Q5914426', # Infobox artist, 1 s
'Q5929832', # Infobox military person
'Q6424841', # Infobox politician
'Q6583638', # Infobox cyclist, 1 s
'Q14358369', # Infobox actor
'Q14458505', # Infobox journalist
# Non-human
'Q52496', # Taxobox, 8 s
'Q5683132', # Infobox place, 10 s
'Q5747491', # Taxobox begin
'Q6055178', # Infobox park
'Q6630855', # Infobox food, 3 s
'Q5896997', # Infobox world heritage
'Q5906647', # Infobox building
'Q5901151', # Infobox sport
'Q6190581', # Infobox organization
'Q6434929', # Multiple image, 9 s
'Q13553651', # Infobox (overrule)
# others to be added
# Shouldn't we add these to all non-human Wikipedia pages missing an Infobox?
'Q5626735', # Infobox generic, 12 s
# Redundant language codes rue, sv; .update() overrules => which one to give preference?
# https://favtutor.com/blogs/merge-dictionaries-python
'Q20702632', # Databox (nl; still experimental) => seems to work pretty well... {{#invoke:Databox|databox}}, 1 s
'Q42054995', # Universal infobox
]
# Allows to extract GEO coordinates
location_target = [
('Camera location', CAMERALOCATIONPROP), # Geolocation of camera view point
('Object location', OBJECTLOCATIONPROP), # Geolocation of object
]
def fatal_error(errcode, errtext):
"""
A fatal error has occurred.
We will print the error message, and exit with an error code.
"""
global exitstat
exitstat = max(exitstat, errcode)
pywikibot.critical(errtext)
if exitfatal: # unless we ignore fatal errors
sys.exit(exitstat)
else:
pywikibot.warning('Proceed after fatal error')
def get_canon_name(baselabel) -> str:
"""Get standardised name
:param baselabel: input label
:return cononical label
Algorithm:
remove () suffix
reverse , name parts
"""
suffix = PSUFFRE.search(baselabel) # Remove () suffix, if any
if suffix:
baselabel = baselabel[:suffix.start()] # Get canonical form
colonloc = baselabel.find(':')
commaloc = NAMEREVRE.search(baselabel)
# Reorder "lastname, firstname" and concatenate with space
if colonloc < 0 and commaloc:
baselabel = baselabel[commaloc.start() + 1:] + ' ' + baselabel[:commaloc.start()]
baselabel = baselabel.replace(',',' ') # Multiple ,
baselabel = ' '.join(baselabel.split()) # Remove redundant spaces
return baselabel
def get_property_label(propx) -> str:
"""
Get the label of a property.
:param propx: property (string or property)
:return property label (string)
Except: undefined property
"""
if isinstance(propx, str):
propty = pywikibot.PropertyPage(repo, propx)
else:
propty = propx
# Return preferred label
for lang in main_languages:
if lang in propty.labels:
return propty.labels[lang]
# Return any other label
for lang in propty.labels:
return propty.labels[lang]
return '-'
def get_item_header(header):
"""
Get the item header (label, description, alias in user language)
:param header: item label, description, or alias language list (string or list)
:return: label, description, or alias in the first available language (string)
"""
# Return preferred label
for lang in main_languages:
if lang in header:
return header[lang]
# Return any other label
for lang in header:
return header[lang]
return '-'
def get_item_page(qnumber) -> pywikibot.ItemPage:
"""
Get the item; handle redirects.
"""
if isinstance(qnumber, str):
item = pywikibot.ItemPage(repo, qnumber)
try:
item.get()
except pywikibot.exceptions.IsRedirectPageError:
# Resolve a single redirect error
item = item.getRedirectTarget()
label = get_item_header(item.labels)
pywikibot.warning('Item {} ({}) redirects to {}'
.format(label, qnumber, item.getID()))
qnumber = item.getID()
else:
item = qnumber
qnumber = item.getID()
while item.isRedirectPage():
## Should fix the sitelinks
item = item.getRedirectTarget()
label = get_item_header(item.labels)
pywikibot.warning('Item {} ({}) redirects to {}'
.format(label, qnumber, item.getID()))
qnumber = item.getID()
return item
def get_item_label_dict(qnumber) -> {}:
"""
Get the Wikipedia labels in all languages for a Qnumber.
:param qnumber: list number
:return: label dict set(including aliases; index by ISO language code)
Example of usage:
Image namespace name (Q478798).
"""
prevnow = datetime.now() # Refresh the timestamp to time the following transaction
labeldict = {}
item = get_item_page(qnumber)
# Get target labels
for lang in item.labels:
#if 'x_' not in lang: # Ignore special languages
labeldict[lang] = set()
labeldict[lang].add(item.labels[lang])
if lang in item.aliases:
for val in item.aliases[lang]:
labeldict[lang].add(val)
now = datetime.now() # Refresh the timestamp to time the following transaction
isotime = now.strftime("%Y-%m-%d %H:%M:%S") # Needed to format output
pywikibot.info('{}\tLoading item {} ({}) took {:d} seconds'
.format(isotime, get_item_header(qnumber.labels), qnumber, int((prevnow - now).total_seconds())))
return labeldict
def get_wikipedia_sitelink_template_dict(qnumber) -> {}:
"""
Get the Wikipedia template names in all languages for a Qnumber.
:param qnumber: sitelink list
:return: template dict (index by sitelang)
Functionality:
Filter for Wikipedia and the template namespace.
Example of usage:
Generate {{Commonscat}} statements for Q48029.
"""
prevnow = datetime.now() # Start of transaction
sitedict = {}
item = get_item_page(qnumber)
# Get target sitelinks
for sitelang in item.sitelinks:
if 'x_' not in sitelang: # Ignore special languages
try:
sitelink = item.sitelinks[sitelang]
if (str(sitelink.site.family) == 'wikipedia'
and sitelink.namespace == TEMPLATENAMESPACE):
sitedict[sitelang] = sitelink.title
except Exception as error:
pywikibot.error(error) # Site error
now = datetime.now() # Refresh the timestamp to time the following transaction
isotime = now.strftime("%Y-%m-%d %H:%M:%S") # Needed to format output
pywikibot.info('{}\tLoading template {} ({}) took {:d} seconds for {:d} items'
.format(isotime, get_item_header(qnumber.labels), qnumber, int((now - prevnow).total_seconds()), len(sitedict)))
return sitedict
def get_language_preferences() -> []:
"""
Get the list of preferred languages,
using environment variables LANG, LC_ALL, and LANGUAGE.
'en' is always appended.
Format: string delimited by ':'.
Main_sublange code,
Result:
List of ISO 639-1 language codes
Documentation:
https://www.gnu.org/software/gettext/manual/html_node/Locale-Environment-Variables.html
https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes
"""
mainlang = os.getenv('LANGUAGE',
os.getenv('LC_ALL',
os.getenv('LANG', ENLANG))).split(':')
main_languages = [lang.split('_')[0] for lang in mainlang]
# Cleanup language list
for lang in main_languages:
if len(lang) > 3:
main_languages.remove(lang)
# Make sure that at least 'en' is available
if ENLANG not in main_languages:
main_languages.append(ENLANG)
return main_languages
def get_prop_val_str(item, proplist) -> str:
## not used... can be removed
"""Get property value string
:param item: Wikidata item
:param proplist: Search list of properties
:return: concatenated list of values
"""
item_prop_val = ''
for prop in proplist:
if prop in item.claims:
for seq in item.claims[prop]:
item_prop_val += seq.getTarget() + '/'
break
return item_prop_val
def get_prop_val_object_label(item, proplist) -> str:
"""Get property value label
:param item: Wikidata item
:param proplist: Search list of properties
:return: concatenated list of value labels
"""
item_prop_val = ''
for prop in proplist:
if prop in item.claims:
for seq in item.claims[prop]:
val = seq.getTarget()
try:
item_prop_val += get_item_header(val.labels) + '/'
except Exception as error:
pywikibot.error(error) # Site error
break
return item_prop_val
def get_prop_val_year(item, proplist) -> str:
"""Get death date (normally only one)
:param item: Wikidata item
:param proplist: Search list of date properties
:return: first matching date
"""
item_prop_val = ''
for prop in proplist:
if prop in item.claims:
for seq in item.claims[prop]:
val = seq.getTarget()
try:
item_prop_val += str(val.year) + '/'
except Exception as error:
pywikibot.error(error) # Site error
break
return item_prop_val
def get_sdc_item(sdc_data) -> pywikibot.ItemPage:
"""
Get the item from the SDC statement.
"""
# Get item
qnumber = sdc_data['datavalue']['value']['id']
item = get_item_page(qnumber)
return item
def is_foreign_lang(lang_list) -> bool:
""" Check if foreign language"""
isforeign = False
for seq in lang_list:
if not ROMANRE.search(seq):
isforeign = True
break
return isforeign
def is_veto_lang_label(lang_list) -> bool:
"""
Check if language is blacklisted
"""
isveto = False
for seq in lang_list:
val = seq.getTarget()
if (val.language in veto_languages_id
or not ROMANRE.search(val.text)):
isveto = True
break