-
Notifications
You must be signed in to change notification settings - Fork 0
/
create_isbn_edition.py
1630 lines (1368 loc) · 62.8 KB
/
create_isbn_edition.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 = """Pywikibot client to load ISBN linked data into Wikidata
Pywikibot script to get ISBN data from a digital library,
and create or amend the related Wikidata item for edition
(with the P212, ISBN number, as unique external ID).
Use digital libraries to get ISBN data in JSON format,
and integrate the results into Wikidata.
ISBN data should only be used for editions,
and not for written works.
Then the resulting item number can be used
e.g. to generate Wikipedia references using template Cite_Q.
Parameters:
All parameters are optional.
P1: digital library (default wiki "-")
bnf Catalogue General (France)
bol Bol.com
dnb Deutsche National Library
goob Google Books
kb National Library of the Netherlands
loc Library of Congress US
mcues Ministerio de Cultura (Spain)
openl OpenLibrary.org
porbase urn.porbase.org Portugal
sbn Servizio Bibliotecario Nazionale (Italy)
wiki wikipedia.org
worldcat WorldCat (wc)
P2: ISO 639-1 language code
Default LANG; e.g. en, nl, fr, de, es, it, etc.
P1 sets default, linked to digital library.
P3 P4...: P/Q pairs to add additional claims (repeated)
e.g. P921 Q107643461 (main subject: database management
linked to P2163 Fast ID 888037)
stdin: list of ISBN numbers
(International standard book number; version 10 or 13)
Free text is accepted (e.g. Wikipedia references list,
or publication list).
Identification is done via an ISBN regex expression.
Functionality:
* Both ISBN-10 and ISBN-13 numbers are accepted as input.
* Only ISBN-13 numbers are stored.
ISBN-10 numbers are only used for identification purposes;
they are not stored.
* The ISBN number is used as a primary key
(no 2 items can have the same P212 ISBN number).
The item update is not performed when there is no unique match.
Only editions are updated or created.
* Individual statements are added or merged incrementally;
existing data is not overwritten.
* Authors and publishers are searched to get their item number
(unknown of ambiguous items are skipped).
* Book title and subtitle are separated with either
'.', ':', or '-' (in that order)
* Detect author, illustrator, writer preface, afterwork instances
* Add profession "author" to individual authors
* This script can be run incrementally.
Examples:
# Default library (Google Books), language (LANG), no additional statements
pwb create_isbn_edition <<EOF
9789042925564
EOF
# Wikimedia, language English, main subject: database management
pwb create_isbn_edition wiki en P921 Q107643461 <<EOF
978-0-596-10089-6
EOF
Data quality:
* ISBN numbers (P212) are only assigned to editions.
* A written work should not have an ISBN number (P212).
* For targets of P629 (edition of) amend
"is an Q47461344 (written work) instance"
and "inverse P747 (work has edition)" statements
* Use https://query.wikidata.org/querybuilder/ to identify P212 duplicates
Merge duplicate items before running the script again.
* The following properties should only be used for written works,
not for editions:
P5331: OCLC work ID (editions should only have P243)
P8383: Goodreads-identificatiecode for work
(editions should only have P2969).
Return status:
The following status codes are returned to the shell:
3 Invalid or missing parameter
4 Library not installed
12 Item does not exist
20 Network error
Standard ISBN properties for editions:
P31:Q3331189: instance of edition (mandatory statement)
P50: author
P123: publisher
P212: canonical ISBN number (with dashes; searchable via Wikidata Query)
P407: language of work (Qnumber linked to ISO 639-1 language code)
P577: date of publication (year)
P1476: book title
P1680: subtitle
Other ISBN properties:
P921: main subject (inverse lookup from external Fast ID P2163)
P629: work for edition
P747: edition of work
Qualifiers:
P248: Source
P813: Retrieval date
P1545: (author) sequence number
External identifiers:
P243: OCLC ID
P1036: Dewey Decimal Classification
P2163: Fast ID (inverse lookup via Wikidata Query) -> P921: main subject
(not implemented)
P2969: Goodreads-identificatiecode
(only for written works)
P5331: OCLC work ID (editions should only have P243)
(not implemented)
P8383: Goodreads-identificatiecode for work (not yet implemented; editions should only have P2969)
(not implemented)
P213: ISNI ID
P496: ORCID ID
P675: Google Books-identificatiecode
Unavailable properties from digital library:
(not implemented by isbnlib)
P98: Editor
P110: Illustrator/photographer
P291: place of publication
P1104: number of pages
: edition format (hardcover, paperback)
Author:
Geert Van Pamel, 2022-08-04, MIT License, User:Geertivp
Documentation:
https://en.wikipedia.org/wiki/ISBN
https://pypi.org/project/isbnlib/
https://buildmedia.readthedocs.org/media/pdf/isbnlib/v3.4.5/isbnlib.pdf
https://www.wikidata.org/wiki/Property:P212
http://www.isbn.org/standards/home/isbn/international/hyphenation-instructions.asp
https://isbntools.readthedocs.io/en/latest/info.html
https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes
https://www.wikidata.org/wiki/Wikidata:List_of_properties/work
https://www.wikidata.org/wiki/Template:Book_properties
https://www.wikidata.org/wiki/Template:Bibliographic_properties
https://www.wikidata.org/wiki/Wikidata:WikiProject_Source_MetaData
https://www.wikidata.org/wiki/Help:Sources
https://www.wikidata.org/wiki/Q22696135 (Wikidata references module)
https://www.geeksforgeeks.org/searching-books-with-python/
http://classify.oclc.org/classify2/ClassifyDemo
https://doc.wikimedia.org/pywikibot/master/api_ref/pywikibot.html
https://www.mediawiki.org/wiki/API:Search
https://www.mediawiki.org/wiki/Wikibase/API
Prerequisites:
pywikibot
Install the following ISBN lib packages:
https://pypi.org/project/isbnlib/
https://pypi.org/search/?q=isbnlib
pip install isbnlib (mandatory)
(optional)
pip install isbnlib-bnf
pip install isbnlib-bol
pip install isbnlib-dnb
pip install isbnlib-kb
pip install isbnlib-loc
pip install isbnlib-worldcat2
etc.
Restrictions:
* Better use the ISO 639-1 language code parameter as a default
The language code is not always available from the digital library;
therefore we need a default.
* Publisher unknown:
* Missing P31:Q2085381 statement, missing subclass in script
* Missing alias
* Create publisher
* Unknown author: create author as a person
Known problems:
* Unknown ISBN, e.g. 9789400012820
* If there is no ISBN data available for an edition
either returns no output (goob = Google Books),
or an error message (wiki, openl).
The script is taking care of both.
Try another library instance.
* Only 6 specific ISBN attributes are listed by the webservice(s)
missing are e.g.: place of publication, number of pages
* Some digital libraries have more registrations than others
* Some digital libraries have data quality problems
* Not all ISBN atttributes have data values
(authors, publisher, date of publication, language can be missing at the digital library).
* How to add still more digital libraries?
* This would require an additional isbnlib module
* Does the KBR has a public ISBN service (Koninklijke Bibliotheek van België)?
* The script uses multiple webservice calls (script might take time, but it is automated)
* Need to manually amend ISBN items that have no author, publisher, or other required data
* You could use another digital library
* Which other services to use?
* BibTex service is currently unavailable
* Filter for work properties:
https://www.wikidata.org/wiki/Q63413107
['9781282557246', '9786612557248', '9781847196057', '9781847196040']
P5331: OCLC identification code for work 793965595 (should only have P243)
P8383: Goodreads identification code for work 13957943 (should only have P2969)
* ERROR: an HTTP error has ocurred ((503) Service Unavailable)
* error: externally-managed-environment
pip install isbnlib-kb
error: externally-managed-environment
× This environment is externally managed
╰─> To install Python packages system-wide, try apt install
python3-xyz, where xyz is the package you are trying to
install.
If you wish to install a non-Debian-packaged Python package,
create a virtual environment using python3 -m venv path/to/venv.
Then use path/to/venv/bin/python and path/to/venv/bin/pip. Make
sure you have python3-full installed.
If you wish to install a non-Debian packaged Python application,
it may be easiest to use pipx install xyz, which will manage a
virtual environment for you. Make sure you have pipx installed.
See /usr/share/doc/python3.11/README.venv for more information.
note: If you believe this is a mistake, please contact your Python installation or OS distribution provider. You can override this, at the risk of breaking your Python installation or OS, by passing --break-system-packages.
hint: See PEP 668 for the detailed specification.
You need to install a local python environment:
https://pip.pypa.io/warnings/venv
https://docs.python.org/3/tutorial/venv.html
sudo -s
apt install python3-full
python3 -m venv /opt/python
/opt/python/bin/pip install pywikibot
/opt/python/bin/pip install isbnlib-kb
/opt/python/bin/python ../userscripts/create_isbn_edition.py kb
To do:
* Implement a webservice at toolforge.org, based on this shell script
Have an input text box and an "Execute" button
Then have a transaction log
Not implemented (yet):
* Amazone author ID https://www.wikidata.org/wiki/Property:P4862
Algorithm:
Get parameters from shell
Validate parameters
Get ISBN data
Convert ISBN data:
Reverse names when Lastname, Firstname
Get additional data
Register ISBN data into Wikidata:
Add source reference when creating the item:
(digital library instance, retrieval date)
Create or amend items or claims:
Number the authors in order of appearence
Check data consistency
Correct data quality problems:
OCLC Work ID for Written work
Written work instance statement
Inverse relationship written work -> edition
Move/register OCLC work ID to/with written work
Manually corrections:
Create missing (referenced) items
(authors, publishers, written works, main subject/FAST ID)
Resolve ambiguous values
Environment:
The python script can run on the following platforms:
Linux client
Google Chromebook (Linux container)
Toolforge portal
PAWS
LANG: default ISO 639-1 language code
Source code:
https://github.com/geertivp/Pywikibot/blob/main/create_isbn_edition.py
https://gerrit.wikimedia.org/r/c/pywikibot/core/+/826631
https://gerrit.wikimedia.org/r/c/pywikibot/core/+/826631/3/scripts/create_isbn_edition.py
https://gerrit.wikimedia.org/r/plugins/gitiles/pywikibot/core/+/refs/heads/stable/scripts/create_isbn_edition.py
https://phabricator.wikimedia.org/T314942
Applications:
Generate a book reference
Example: {{Cite Q|Q63413107}} (only available at wp.en)
Use the Visual editor reference with Qnumber
See also:
https://www.wikidata.org/wiki/Wikidata:WikiProject_Books
https://www.wikidata.org/wiki/Q21831105 (WikiProject Books)
https://meta.wikimedia.org/wiki/WikiCite
https://phabricator.wikimedia.org/tag/wikicite/
https://www.wikidata.org/wiki/Q21831105 (WikiCite)
https://www.wikidata.org/wiki/Q22321052 (Cite_Q)
https://www.mediawiki.org/wiki/Global_templates
https://www.wikidata.org/wiki/Wikidata:WikiProject_Source_MetaData
https://meta.wikimedia.org/wiki/WikiCite/Shared_Citations
https://www.wikidata.org/wiki/Q36524 (Authority control)
https://meta.wikimedia.org/wiki/Community_Wishlist_Survey_2021/Wikidata/Bibliographical_references/sources_for_wikidataitems
Wikidata Query:
List of editions about musicians: https://w.wiki/5aaz
List of editions having an ISBN number: https://w.wiki/5akq
Related projects:
https://phabricator.wikimedia.org/T282719
https://phabricator.wikimedia.org/T214802
https://phabricator.wikimedia.org/T208134
https://phabricator.wikimedia.org/T138911
https://phabricator.wikimedia.org/T20814
https://en.wikipedia.org/wiki/User:Citation_bot
https://zenodo.org/record/55004#.YvwO4hTP1D8
Other systems:
https://isbn.org/ISBN_converter
https://en.wikipedia.org/wiki/bibliographic_database
https://www.titelbank.nl/pls/ttb/f?p=103:4012:::NO::P4012_TTEL_ID:3496019&cs=19BB8084860E3314502A1F777F875FE61
https://isbndb.com/apidocs/v2
https://isbndb.com/book/9780404150006
Documentation:
https://en.wikipedia.org/wiki/ISBN
https://en.wikipedia.org/wiki/Wikipedia:Book_sources
https://en.wikipedia.org/wiki/Wikipedia:ISBN
https://www.boek.nl/nur
https://isbnlib.readthedocs.io/_/downloads/en/latest/pdf/
https://www.wikidata.org/wiki/Special:BookSources/978-94-014-9746-6
Goodreads:
https://github.com/akkana/scripts/blob/master/bookfind.py
https://www.kaggle.com/code/hoshi7/goodreads-analysis-and-recommending-books?scriptVersionId=18346227
https://help.goodreads.com/s/question/0D51H00005FzcX1SAJ/how-can-i-search-by-isbn
https://help.goodreads.com/s/article/Librarian-Manual-ISBN-10-ISBN-13-and-ASINS
https://www.goodreads.com/book/show/203964185-de-nieuwe-wereldeconomie
"""
import isbnlib # ISBN library
import os # Operating system
import pdb # Python debugger
import pywikibot # API interface to Wikidata
import re # Regular expressions (very handy!)
import sys # System calls
import traceback # Traceback
import unidecode # Unicode
from datetime import date, datetime # now, strftime, delta time, total_seconds
from pywikibot.data import api
# Global variables
modnm = 'Pywikibot create_isbn_edition' # Module name (using the Pywikibot package)
pgmid = '2024-11-11 (gvp)' # Program ID and version
pgmlic = 'MIT License'
creator = 'User:Geertivp'
MAINLANG = 'en:mul'
MULANG = 'mul'
exitfatal = True # Exit on fatal error (can be disabled with -p; please take care)
exitstat = 0 # (default) Exit status
# Wikidata transaction comment
transcmt = '#pwb Create ISBN edition'
INSTANCEPROP = 'P31'
AUTHORPROP = 'P50'
EDITORPROP = 'P98'
PROFESSIONPROP = 'P106'
ILLUSTRATORPROP = 'P110'
PUBLISHERPROP = 'P123'
#STYLEPROP = 'P135'
#GENREPROP = 'P136'
#BASEDONPROP = 'P144'
#PREVSERIALPROP = 'P155'
#NEXTSERIALPROP = 'P156'
#PRIZEPROP = 'P166'
#SERIALPROP = 'P179'
#COLLIONPROP = 'P195'
ISBNPROP = 'P212'
ISNIIDPROP = 'P213'
#BNFIDPROP = 'P268'
PLACEPUBPROP = 'P291'
OCLDIDPROP = 'P243'
REFPROP = 'P248'
#EDITIONIDPROP = 'P393'
EDITIONLANGPROP = 'P407'
WIKILANGPROP = 'P424'
#ORIGCOUNTRYPROP = 'P495'
ORCIDIDPROP = 'P496'
PUBYEARPROP = 'P577'
WRITTENWORKPROP = 'P629'
#OPENLIBIDPROP = 'P648'
#TRANSLATORPROP = 'P655'
#PERSONPROP = 'P674'
GOOGLEBOOKIDPROP = 'P675'
#INTARCHIDPROP = 'P724'
EDITIONPROP = 'P747'
#CONTRIBUTORPROP = 'P767'
REFDATEPROP = 'P813'
#STORYLOCPROP = 'P840'
#PRINTEDBYPROP = 'P872'
MAINSUBPROP = 'P921'
#INSPIREDBYPROP = 'P941'
ISBN10PROP = 'P957'
#SUDOCIDPROP = 'P1025'
DEWCLASIDPROP = 'P1036'
#EULIDPROP = 'P1084'
#LIBTHINGIDPROP = 'P1085'
NUMBEROFPAGESPROP = 'P1104'
#LCOCLCCNIDPROP = 'P1144'
#LIBCONGRESSIDPROP = 'P1149'
#BNIDPROP = 'P1143'
#UDCPROP = 'P1190'
#DNBIDPROP = 'P1292'
DESCRIBEDBYPROP = 'P1343'
EDITIONTITLEPROP = 'P1476'
SEQNRPROP = 'P1545'
EDITIONSUBTITLEPROP = 'P1680'
#ASSUMEDAUTHORPROP = 'P1779'
#RSLBOOKIDPROP = 'P1815'
#RSLEDIDPROP = 'P1973'
#GUTENBERGIDPROP = 'P2034'
FASTIDPROP = 'P2163'
#NUMPARTSPROP = 'P2635'
PREFACEBYPROP = 'P2679'
AFTERWORDBYPROP = 'P2680'
GOODREADSIDPROP = 'P2969'
#CZLIBIDPROP = 'P3184'
#BABELIOIDPROP = 'P3631'
#ESTCIDPROP = 'P3939'
OCLCWORKIDPROP = 'P5331'
#K10IDPROP = 'P6721'
#CREATIVEWORKTYPE = 'P7937'
LIBCONGEDPROP = 'P8360'
GOODREADSWORKIDPROP = 'P8383'
# Instances
AUTHORINSTANCE = 'Q482980'
ILLUSTRATORINSTANCE = 'Q15296811'
WRITERINSTANCE = 'Q36180'
authorprop_list = {
AUTHORPROP,
EDITORPROP,
ILLUSTRATORPROP,
PREFACEBYPROP,
AFTERWORDBYPROP,
}
# Profession author instances
author_profession = {
AUTHORINSTANCE,
ILLUSTRATORINSTANCE,
WRITERINSTANCE,
}
# List of digital library synonyms
bookliblist = {
'-': 'wiki',
'dnl': 'dnb',
'google': 'goob',
'gb': 'goob',
'isbn': 'isbndb',
'kbn': 'kb',
'wc': 'worldcat',
'wcat': 'worldcat',
'wikipedia': 'wiki',
'wp': 'wiki',
}
# List of of digital libraries
# You can better run the script repeatedly with difference library sources.
# Content and completeness differs amongst libraryies.
bib_source = {
# database ID, item number, label, default language
'bnf': ('Q193563', 'Catalogue General (France)', 'fr', 'isbnlib-bnf'),
'bol': ('Q609913', 'Bol.Com', 'en', 'isbnlib-bol'),
'dnb': ('Q27302', 'Deutsche National Library', 'de', 'isbnlib-dnb'),
'goob': ('Q206033', 'Google Books', 'en', 'isbnlib'), ## lib
'isbndb': ('Q117793433', 'isbndb.com', 'en', 'isbnlib'), # A (paying) api key is needed
'kb': ('Q1526131', 'Koninklijke Bibliotheek (Nederland)', 'nl', 'isbnlib-kb'),
#'kbr': ('Q383931', 'Koninklijke Bibliotheek (België)', 'nl', 'isbnlib-'), # Not implemented in Belgium
'loc': ('Q131454', 'Library of Congress (US)', 'en', 'isbnlib-loc'),
'mcues': ('Q750403', 'Ministerio de Cultura (Spain)', 'es', 'isbnlib-mcues'),
'openl': ('Q1201876', 'OpenLibrary.org', 'en', 'isbnlib-'), ## lib
'porbase': ('Q51882885', 'Portugal (urn.porbase.org)', 'pt', 'isbnlib-porbase'),
'sbn': ('Q576951', 'Servizio Bibliotecario Nazionale (Italië)', 'it', 'isbnlib-sbn'),
'wiki': ('Q121093616', 'Wikipedia.org', 'en', 'isbnlib'), ## lib
'worldcat': ('Q76630151', 'WorldCat (worldcat2)', 'en', 'isbnlib-worldcat2'),
# isbnlib-oclc
# https://github.com/swissbib
# others to be added
}
# Remap obsolete or non-standard language codes
langcode = {
'dut': 'nl',
'eng': 'en',
'frans': 'fr',
'fre': 'fr',
'iw': 'he',
'nld': 'nl',
}
# Instance validation rules for properties
propreqinst = {
AUTHORPROP: {'Q5'}, # Author requires human
EDITIONLANGPROP: {'Q34770', 'Q33742', 'Q1288568'}, # Edition language requires at least one of (living, natural) language
INSTANCEPROP: {'Q24017414'}, # Is an instance of an edition
PUBLISHERPROP: {'Q41298', 'Q479716', 'Q1114515', 'Q1320047', 'Q2085381'}, # Publisher requires type of publisher
WRITTENWORKPROP: ['Q47461344', 'Q7725634'], # Written work (requires list)
}
# Statement property target validation rules
propreqobjectprop = {
MAINSUBPROP: {FASTIDPROP}, # Main subject statement requires an object with FAST ID property
}
# Required statement for edition
# Additional statements can be added via command line parameters
target = {
INSTANCEPROP: 'Q3331189', # Is an instance of an edition
# other statements to add
}
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_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 one of the preferred labels
for lang in main_languages:
if lang in header:
return header[lang]
# Return any other available label
for lang in header:
return header[lang]
return '-'
def get_item_header_lang(header, lang):
"""
Get the item header (label, description, alias in user language)
:param header: item label, description, or alias language list (string or list)
:param lang: language code
:return: label, description, or alias in the first available language (string)
"""
# Try to get any explicit language code
if lang in header:
return header[lang]
return get_item_header(header)
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_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', MAINLANG))).split(':')
main_languages = [lang.split('_')[0] for lang in mainlang]
# Cleanup language list (remove non-ISO codes)
for lang in main_languages:
if len(lang) > 3:
main_languages.remove(lang)
for lang in MAINLANG.split(':'):
if lang not in main_languages:
main_languages.append(lang)
return main_languages
def item_is_in_list(statement_list, itemlist):
"""
Verify if statement list contains at least one item from the itemlist
param: statement_list: Statement list
param: itemlist: List of values (string)
return: Matching or empty string
"""
for seq in statement_list:
try:
isinlist = seq.getTarget().getID()
if isinlist in itemlist:
return isinlist
except:
pass # Ignore NoneType error
return ''
def item_has_label(item, label) -> str:
"""
Verify if the item has a label
Parameters:
item: Item
label: Item label (string)
Returns:
Matching string
"""
label = unidecode.unidecode(label).casefold()
for lang in item.labels:
if unidecode.unidecode(item.labels[lang]).casefold() == label:
return item.labels[lang]
for lang in item.aliases:
for seq in item.aliases[lang]:
if unidecode.unidecode(seq).casefold() == label:
return seq
return '' # Must return "False" when no label
def is_in_value_list(statement_list, valuelist) -> bool:
"""Verify if statement list contains at least one value from the valuelist.
:param statement_list: Statement list of values
:param valuelist: List of values (string)
:return: True when match, False otherwise
"""
for seq in statement_list:
if seq.getTarget() in valuelist:
isinlist = True
break
else:
isinlist = False
return isinlist
def get_canon_name(baselabel) -> str:
"""Get standardised name
:param baselabel: input label
:return cononical label
Algorithm:
remove () suffix
reverse , name parts
"""
suffix = SUFFRE.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(',',' ') # Remove remaining ","
# Remove redundant spaces
baselabel = ' '.join(baselabel.split())
return baselabel
def get_item_list(item_name: str, instance_id) -> set():
"""Get list of items by name, belonging to an instance (list)
:param item_name: Item name (string)
:param instance_id: Instance ID (set, or list)
:return: Set of items
Normally we should have one single best match.
The caller should take care of homonyms.
See https://www.wikidata.org/w/api.php?action=help&modules=wbsearchentities
"""
pywikibot.debug('Search label: {}'.format(item_name.encode('utf-8')))
item_list = set() # Empty set
params = {'action': 'wbsearchentities',
'search': item_name, # Get item list from label
'type': 'item',
'language': mainlang, # Labels are in native language
'uselang': mainlang, # (primary) Search language
'strictlanguage': False, # All languages are searched
'format': 'json',
'limit': 20} # Should be reasonable value
request = api.Request(site=repo, parameters=params)
result = request.submit()
pywikibot.debug(result)
if 'search' in result:
# Ignore accents and case
item_name_canon = unidecode.unidecode(item_name).casefold()
for row in result['search']: # Loop though items
##print(row)
item = get_item_page(row['id'])
# Matching instance
if INSTANCEPROP in item.claims and item_is_in_list(item.claims[INSTANCEPROP], instance_id):
# Search all languages
for lang in item.labels:
if item_name_canon == unidecode.unidecode(item.labels[lang]).casefold():
item_list.add(item) # Label match
break
for lang in item.aliases:
for seq in item.aliases[lang]:
if item_name_canon == unidecode.unidecode(seq).casefold():
item_list.add(item) # Alias match
break
pywikibot.log(item_list)
# Convert set to list; keep sort order (best matches first)
return item_list
def get_item_with_prop_value (prop: str, propval: str) -> set():
"""Get list of items that have a property/value statement
:param prop: Property ID (string)
:param propval: Property value (string)
:return: List of items (Q-numbers)
See https://www.mediawiki.org/wiki/API:Search
"""
pywikibot.debug('Search statement: {}:{}'.format(prop, propval))
item_name_canon = unidecode.unidecode(propval).casefold()
item_list = set() # Empty set
params = {'action': 'query', # Statement search
'list': 'search',
'srsearch': prop + ':' + propval,
'srwhat': 'text',
'format': 'json',
'srlimit': 50} # Should be reasonable value
request = api.Request(site=repo, parameters=params)
result = request.submit()
# https://www.wikidata.org/w/api.php?action=query&list=search&srwhat=text&srsearch=P212:978-94-028-1317-3
# https://www.wikidata.org/w/index.php?search=P212:978-94-028-1317-3
if 'query' in result and 'search' in result['query']:
# Loop though items
for row in result['query']['search']:
qnumber = row['title']
item = get_item_page(qnumber)
if prop in item.claims:
for seq in item.claims[prop]:
if unidecode.unidecode(seq.getTarget()).casefold() == item_name_canon:
item_list.add(item) # Found match
break
# Convert set to list
pywikibot.log(item_list)
return item_list
def amend_isbn_edition(isbn_number) -> int:
"""Amend the ISBN registration in Wikidata.
It is registering the ISBN-13 data via P212,
depending on the data obtained from the chosen digital library.
:param isbn_number: ISBN number
(string; 10 or 13 digits with optional hyphens)
:result: Status (int)
0: Amended (found or created)
1: Not found
2: Ambiguous
3: Other error
"""
try:
global proptyx
# targetx is not global (to allow for language specific editions)
##print(isbn_number)
isbn_number = isbn_number.strip()
if not isbn_number:
return 3 # Do nothing when the ISBN number is missing
# Validate ISBN data
pywikibot.info('')
# Some digital library services raise failure;
try:
# Get ISBN basic data
isbn_data = isbnlib.meta(isbn_number, service=booklib)
# {'ISBN-13': '9789042925564', 'Title': 'De Leuvense Vaart - Van De Vaartkom Tot Wijgmaal. Aspecten Uit De Industriele Geschiedenis Van Leuven', 'Authors': ['A. Cresens'], 'Publisher': 'Peeters Pub & Booksellers', 'Year': '2012', 'Language': 'nl'}
"""
Keywords:
'ISBN-13': '9789042925564'
'Title': 'De Leuvense Vaart - Van De Vaartkom Tot Wijgmaal. Aspecten Uit De Industriele Geschiedenis Van Leuven',
'Authors': ['A. Cresens'],
'Publisher': 'Peeters Pub & Booksellers',
'Year': '2012',
'Language': 'nl'
"""
except isbnlib._exceptions.NotRecognizedServiceError as error:
fatal_error(4, '{}\n\tpip install isbnlib-xxx'.format(error))
except Exception as error:
# When the book is unknown, the function returns
pywikibot.error('{} not found, {}'.format(isbnlib.mask(isbn_number), error))
##pdb.set_trace()
#raise
#raise ValueError(error)
return 1
# Others return an empty result
if not isbn_data:
pywikibot.error('Unknown ISBN book number {}'
.format(isbnlib.mask(isbn_number)))
return 1
# Show the raw results
# Can be very useful in troubleshooting
for seq in isbn_data:
pywikibot.info('{}:\t{}'.format(seq, isbn_data[seq]))
# Set default language from book library
# Mainlang was set to default digital library language code
booklang = mainlang
if isbn_data['Language']:
# Get the book language from the ISBN book number
# Can overwrite the default language
booklang = isbn_data['Language'].strip().lower()
# Replace obsolete or non-standard codes
if booklang in langcode:
booklang = langcode[booklang]
# Get Wikidata language code
lang_list = get_item_list(booklang, propreqinst[EDITIONLANGPROP])
## Hardcoded parameter
# https://realpython.com/python-sets/
lang_list -= {'Q3504110'} # Remove duplicate "En" language
if not lang_list:
# Can' t store unknown language (need to update mapping table...)
pywikibot.error('Unknown language {}'.format(booklang))
return 3
elif len(lang_list) == 1:
# Set edition language item number
lang_item = lang_list.pop()
target[EDITIONLANGPROP] = lang_item.getID()
else:
# Ambiguous language
pywikibot.error('Ambiguous language {} {}'
.format(booklang, [lang_item.getID() for lang_item in lang_list]))
return 3
# Require short Wikipedia language code
if len(booklang) > 3:
# Get official language code
if WIKILANGPROP in lang_item.claims:
booklang = lang_item.claims[WIKILANGPROP][0].getTarget()
# Get edition title
edition_title = isbn_data['Title'].strip()
# Split (sub)title with first matching delimiter
# By priority of parsing strings:
for seq in ['|', '. ', ' - ', ': ', '; ', ', ']:
titles = edition_title.split(seq)
if len(titles) > 1:
break
# Print book titles
for seq in titles: # Print (sub)title(s)
pywikibot.info(seq)
# Get main title and subtitle
objectname = titles[0].strip()
if len(titles) > 1:
# Redundant "subtitles" are ignored
subtitle = titles[1].strip()
subtitle = subtitle[0].upper() + subtitle[1:] # Upcase first character
else:
# If there was no delimiter, there is no subtitle
subtitle = ''
# Get formatted ISBN number
isbn_number = isbn_data['ISBN-13'] # Numeric format