-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodel_wiki.py
2776 lines (2317 loc) · 115 KB
/
model_wiki.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
import pywikibot
import json
from exif import Image
import locale
from datetime import datetime
from dateutil import parser
import os
import logging
import pprint
import subprocess
from transliterate import translit
from pywikibot.specialbots import UploadRobot
from pywikibot import pagegenerators
from pywikibot import exceptions
import urllib
import wikitextparser as wtp
from simple_term_menu import TerminalMenu
import pickle
import re
import traceback
from tqdm import tqdm
import ast
import traceback
from num2words import num2words
from fileprocessor import Fileprocessor
class Model_wiki:
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)-8s %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
logger = logging.getLogger(__name__)
pp = pprint.PrettyPrinter(indent=4)
wiki_content_cache = dict()
cache_category_object_in_location = dict()
cache_settlement_for_object = dict()
wikidata_cache = dict()
wikidata_cache_filename = 'temp_wikidata_cache.dat'
optional_langs = ('de', 'fr', 'it', 'es', 'pt', 'uk', 'be', 'ja')
def __init__(self):
if not os.path.isfile('user-config.py'):
raise Exception('''Now you should enter Wikimedia user data in config. Call \n cp user-config.example.py user-config.py
\n open user-config.py in text editor, input username, and run this script next time''')
self.wikidata_cache = self.wikidata_cache_load(
wikidata_cache_filename=self.wikidata_cache_filename)
def reset_cache(self):
try:
os.unlink(self.wikidata_cache_filename)
except:
pass
self.wikidata_cache = self.wikidata_cache_load(
wikidata_cache_filename=self.wikidata_cache_filename)
def replace_file_commons(self, pagename, filepath):
assert pagename
# Login to your account
site = pywikibot.Site('commons', 'commons')
site.login()
site.get_tokens("csrf") # preload csrf token
# Replace the file
file_page = pywikibot.FilePage(site, pagename)
file_page.upload(source=filepath, comment='Replacing file',ignore_warnings=True, watch=True)
return
def wikidata_cache_load(self, wikidata_cache_filename):
if os.path.isfile(wikidata_cache_filename) == False:
cache = {'entities_simplified': {},
'commonscat_by_2_wikidata': {},
'cities_ids':{},
'commonscat_exists_set': set()}
return cache
else:
file = open(wikidata_cache_filename, 'rb')
# dump information to that file
cache = pickle.load(file)
# close the file
file.close()
return cache
def wikidata_cache_save(self, cache, wikidata_cache_filename) -> bool:
file = open(wikidata_cache_filename, 'wb')
# dump information to that file
pickle.dump(cache, file)
# close the file
file.close()
def wikipedia_get_page_content(self, page) -> str:
# check cache
import sys
pagename = page.title()
if pagename in self.wiki_content_cache:
return self.wiki_content_cache[pagename]
pagecode = page.text
self.wiki_content_cache[pagename] = pagecode
assert sys.getsizeof(pagecode) > 25
return pagecode
def is_change_need(self, pagecode, operation) -> bool:
operations = ('taken on', 'taken on location')
assert operation in operations
if operation == 'taken on':
if '{{Taken on'.upper() in pagecode.upper():
return False
else:
return True
return False
def page_name_canonical(self, pagecode) -> str:
# [[commons:File:Podolsk, Moscow Oblast, Russia - panoramio (152).jpg]]
# File:Podolsk, Moscow Oblast, Russia - panoramio (152).jpg
pagecode = str(pagecode)
pagecode = pagecode.replace('https://commons.wikimedia.org/wiki/', '')
pagecode = pagecode.replace('[[commons:', '').replace(']]', '')
return pagecode
def url_add_template_taken_on(self, pagename, location, dry_run=True,verbose=False,interactive=False):
assert pagename
location = location.title()
site = pywikibot.Site("commons", "commons")
site.login()
site.get_tokens("csrf") # preload csrf token
pagename = self.page_name_canonical(pagename)
if not pagename.startswith('File:'): pagename='File:'+pagename
page = pywikibot.Page(site, title=pagename)
self.page_template_taken_on(page, location, dry_run, verbose,interactive)
def category_add_template_wikidata_infobox(self,category:str):
if not category.startswith('Category:'):
category = 'Category:'+category
assert category
texts = dict()
site = pywikibot.Site("commons", "commons")
site.login()
site.get_tokens("csrf") # preload csrf token
category = self.page_name_canonical(category)
page = pywikibot.Page(site, title=category)
texts[0] = page.text
if 'wikidata infobox' in texts[0].lower():
return True
message = '{{Wikidata Infobox}}'
texts[1]=message+"\n"+page.text
page.text = texts[1]
page.save('add {{Wikidata Infobox}} template')
def category_dev(self, categoryname,start=None,total=None)->list:
counter = 0
site = pywikibot.Site("commons", "commons")
cat = pywikibot.Category(site, categoryname)
subcats_obj = pagegenerators.SubCategoriesPageGenerator(category=cat,recurse=False, start=start, total=total, content=True)
#subcats_obj = cat.subcategories(recurse=False)
print('===categories witout wikidata ibfobox===')
for subcat in subcats_obj:
counter = counter+1
if 'wikidata infobox' in str(subcat.text).lower():
continue
else:
print(str(counter)+' '+subcat.title().replace('Category:',''))
def category_add_template_taken_on(self, categoryname, location, dry_run=True, interactive=False):
assert categoryname
total_files = 0
site = pywikibot.Site("commons", "commons")
site.login()
site.get_tokens("csrf") # preload csrf token
category = pywikibot.Category(site, categoryname)
regex = '(?i)date.*=.*\d\d\d\d-\d\d-\d\d.*\}\}'
regex = '(?i)Information[\S\s]*date[\S\s]*=[\S\s]*\d\d\d\d-\d\d-\d\d.*\}\}'
gen1 = pagegenerators.CategorizedPageGenerator(
category, recurse=False, start=None, total=None, content=True, namespaces=None)
gen2 = pagegenerators.RegexBodyFilterPageGenerator(gen1, regex)
regex
gen2 = pagegenerators.RegexBodyFilterPageGenerator(gen1, regex)
for page in gen2:
print(page)
total_files = total_files+1
del gen1
del gen2
gen1 = pagegenerators.CategorizedPageGenerator(
category, recurse=False, start=None, total=None, content=True, namespaces=None)
gen2 = pagegenerators.RegexBodyFilterPageGenerator(gen1, regex)
gen2 = pagegenerators.RegexBodyFilterPageGenerator(gen1, regex)
logging.getLogger().setLevel(logging.DEBUG)
logging.getLogger('foo').debug('bah')
location = location.title()
pbar = tqdm(total=total_files)
for page in gen2:
self.page_template_taken_on(
page, location, dry_run, interactive, verbose=False, message=f'Set taken on location={location} for files in category {categoryname}')
pbar.update(1)
pbar.close()
def location_string_parse(self, text) -> tuple:
if text is None:
return None, None
text = text.strip()
if text is None or text == "":
return None, None
struct = re.split(" |,|\t|\|", text)
if len(struct) < 2:
return None, None
return float(struct[0]), float(struct[-1])
def create_wikidata_item(self,wd_object, local_wikidata_uuid=None):
'''
created with bing ai
https://www.bing.com/search?iscopilotedu=1&sendquery=1&q=%D0%A7%D1%82%D0%BE+%D1%82%D0%B0%D0%BA%D0%BE%D0%B5+%D0%BD%D0%BE%D0%B2%D1%8B%D0%B9+Bing%3F&showconv=1&filters=wholepagesharingscenario%3A%22Conversation%22&shareId=4d855391-009e-4938-81b4-8591617df8db&shtc=0&shsc=Codex_ConversationMode&form=EX0050&shid=b116c20e-9d13-494d-a4cc-8f8b3a8a6260&shtp=GetUrl&shtk=0J7Qt9C90LDQutC%2B0LzRjNGC0LXRgdGMINGBINGN0YLQuNC8INC%2B0YLQstC10YLQvtC8IEJpbmc%3D&shdk=0JLQvtGCINC%2B0YLQstC10YIsINC%2F0L7Qu9GD0YfQtdC90L3Ri9C5INGBINC%2F0L7QvNC%2B0YnRjNGOINC90L7QstC%2B0LPQviBCaW5nLCDQs9C70L7QsdCw0LvRjNC90L7QuSDRgdC40YHRgtC10LzRiyDQvtGC0LLQtdGC0L7QsiDQvdCwINCx0LDQt9C1INC40YHQutGD0YHRgdGC0LLQtdC90L3QvtCz0L4g0LjQvdGC0LXQu9C70LXQutGC0LAuINCp0LXQu9C60L3QuNGC0LUg0LTQu9GPINC%2F0YDQvtGB0LzQvtGC0YDQsCDQvtGC0LLQtdGC0LAg0YbQtdC70LjQutC%2B0Lwg0Lgg0L%2FQvtC%2F0YDQvtCx0YPQudGC0LUg0Y3RgtGDINGE0YPQvdC60YbQuNGOINGB0LDQvNC%2B0YHRgtC%2B0Y%2FRgtC10LvRjNC90L4u&shhk=KUktXhHaQFr142oHDgOzFPKk2Snr3G22dzXkpH3KtHg%3D&shth=OBFB.107AF8B2FB79BD01FFDCABA4D756224A
'''
# at frist create and print local UUID, user may use it as placeholder for wikidata id, because wikidata object create took 30-40 seconds long
# test is save possible
with open('local_wikidata_uuids.json', 'a') as file:
pass
import shortuuid,jsonlines
if local_wikidata_uuid is None:
local_wikidata_uuid='UUID'+str(shortuuid.uuid())
self.logger.info(f'Created UUID, you now can use it as placeholder for wikidata id place in filename')
self.logger.info(local_wikidata_uuid)
# create a site object for wikidata
site = pywikibot.Site("wikidata", "wikidata")
# create a new item
new_item = pywikibot.ItemPage(site)
# set the labels, descriptions and aliases from the wd_object
try:
new_item.editLabels(labels=wd_object["labels"], summary="Setting labels")
self.logger.info('created wikidata entity: '+str(new_item.getID()) + ' _place'+str(new_item.getID()))
#save local wikidata UUID
with jsonlines.open('local_wikidata_uuids.json', mode='a') as writer:
writer.write({'uuid':local_wikidata_uuid,'wdid':new_item.getID()})
new_item.editDescriptions(descriptions=wd_object["descriptions"], summary="Setting descriptions")
new_item.editAliases(aliases=wd_object["aliases"], summary="Setting aliases")
except:
self.logger.warning('prorably this object already created in wikidata. merge not implement yet')
pass
# iterate over the claims in the wd_object
for prop, value in wd_object["claims"].items():
# create a claim object for the property
claim = pywikibot.Claim(site, prop)
# check the type of the value
if isinstance(value, str) and self.is_wikidata_id(value):
# it is a wikidata item id
# get the item object for the value
target = pywikibot.ItemPage(site, value)
elif isinstance(value, dict) and self.is_wikidata_id(value.get('value',None)):
# it is a wikidata item id
# get the item object for the value
target = pywikibot.ItemPage(site, value.get('value'))
elif isinstance(value, dict):
# if the value is a dict, it is a special value type
# check the type of the value
if value["value"].get("latitude"):
# if the value has latitude, it is a coordinate type
# create a coordinate object for the value
target = pywikibot.Coordinate(
lat=value["value"]["latitude"],
lon=value["value"]["longitude"],
precision=value["value"]["precision"],
site=site,
#globe=value["value"]["globe"],
)
elif value["value"].get("time"):
# if the value has time, it is a time type
# create a time object for the value
target = pywikibot.WbTime(
year=int(value["value"]["time"]["year"]),
#month=value["value"]["time"]["month"],
#day=value["value"]["time"]["day"],
#hour=value["value"]["time"]["hour"],
#minute=value["value"]["time"]["minute"],
#second=value["value"]["time"]["second"],
precision=value["value"]["precision"],
#calendarmodel=value["value"]["calendarmodel"],
)
elif value["value"].get("amount"):
# if the value has amount, it is a quantity type
# create a quantity object for the value
target = pywikibot.WbQuantity(
amount=value["value"]["amount"],
unit=value["value"]["unit"],
error=value["value"].get("error"),
site=site
)
else:
# otherwise, the value is not supported
# raise an exception
raise ValueError(f"Unsupported value type: {value}")
else:
# otherwise, the value is not supported
# raise an exception
raise ValueError(f"Unsupported value type: {value}")
# set the target of the claim to the value object
claim.setTarget(target)
# check if the value has qualifiers
if isinstance(value, dict) and value.get("qualifiers"):
# iterate over the qualifiers
for qual_prop, qual_value in value["qualifiers"].items():
# create a qualifier object for the property
qualifier = pywikibot.Claim(site, qual_prop)
# check the type of the qualifier value
if isinstance(qual_value, str) and self.is_wikidata_id(qual_value):
# if the qualifier value is a wikidata item id
# get the item object for the qualifier value
qual_target = pywikibot.ItemPage(site, qual_value)
elif isinstance(qual_value, str):
# qualifier value is string
qual_target = qual_value
elif isinstance(qual_value, dict):
# if the qualifier value is a dict, it is a special value type
# check the type of the qualifier value
if qual_value["value"].get("latitude"):
# if the qualifier value has latitude, it is a coordinate type
# create a coordinate object for the qualifier value
qual_target = pywikibot.Coordinate(
lat=qual_value["value"]["latitude"],
lon=qual_value["value"]["longitude"],
precision=qual_value["value"]["precision"],
site=site,
#globe=qual_value["value"]["globe"],
)
elif qual_value["value"].get("time"):
# if the qualifier value has time, it is a time type
# create a time object for the qualifier value
qual_target = pywikibot.WbTime(
year=int(qual_value["value"]["time"]["year"]),
#month=qual_value["value"]["time"]["month"],
#day=qual_value["value"]["time"]["day"],
#hour=qual_value["value"]["time"]["hour"],
#minute=qual_value["value"]["time"]["minute"],
#second=qual_value["value"]["time"]["second"],
precision=qual_value["value"]["precision"],
#calendarmodel=qual_value["value"]["calendarmodel"],
)
elif qual_value["value"].get("amount"):
# if the qualifier value has amount, it is a quantity type
# create a quantity object for the qualifier value
qual_target = pywikibot.WbQuantity(
amount=qual_value["value"]["amount"],
unit=qual_value["value"]["unit"],
error=qual_value["value"].get("error"),
site=site
)
else:
# otherwise, the qualifier value is not supported
# raise an exception
raise ValueError(f"Unsupported qualifier value type: {qual_value}")
else:
# otherwise, the qualifier value is not supported
# raise an exception
raise ValueError(f"Unsupported qualifier value type: {qual_value}")
# set the target of the qualifier to the qualifier value object
qualifier.setTarget(qual_target)
# add the qualifier to the claim
claim.addQualifier(qualifier, summary="Adding qualifier")
# check if the value has references
if isinstance(value, dict) and value.get("references"):
# iterate over the references
for reference in value["references"]:
# create a list of source claims for the reference
source_claims = []
# iterate over the reference properties and values
for ref_prop, ref_value in reference.items():
# create a source claim object for the property
source_claim = pywikibot.Claim(site, ref_prop)
# check the type of the reference value
if isinstance(ref_value, str):
# if the reference value is a string, it is a wikidata item id or a url
# check if the reference value starts with http
if ref_value.startswith("http"):
# if the reference value is a url, create a url object for the reference value
ref_target = ref_value
#source_claim.is_reference=True ???
else:
# if the reference value is a wikidata item id, get the item object for the reference value
ref_target = pywikibot.ItemPage(site, ref_value)
elif isinstance(ref_value, dict):
# if the reference value is a dict, it is a special value type
# check the type of the reference value
if ref_value["value"].get("latitude"):
# if the reference value has latitude, it is a coordinate type
# create a coordinate object for the reference value
ref_target = pywikibot.Coordinate(
lat=ref_value["value"]["latitude"],
lon=ref_value["value"]["longitude"],
precision=ref_value["value"]["precision"],
globe=ref_value["value"]["globe"],
)
elif ref_value["value"].get("time"):
# if the reference value has time, it is a time type
# create a time object for the reference value
ref_target = pywikibot.WbTime(
year=int(ref_value["value"]["time"]["year"]),
#month=ref_value["value"]["time"]["month"],
#day=ref_value["value"]["time"]["day"],
#hour=ref_value["value"]["time"]["hour"],
#minute=ref_value["value"]["time"]["minute"],
#second=ref_value["value"]["time"]["second"],
precision=ref_value["value"]["precision"],
#calendarmodel=ref_value["value"]["calendarmodel"],
)
elif ref_value["value"].get("amount"):
# if the reference value has amount, it is a quantity type
# create a quantity object for the reference value
ref_target = pywikibot.WbQuantity(
amount=ref_value["value"]["amount"],
unit=ref_value["value"]["unit"],
error=ref_value["value"].get("error"),
site=site
)
else:
# otherwise, the reference value is not supported
# raise an exception
raise ValueError(f"Unsupported reference value type: {ref_value}")
else:
# otherwise, the reference value is not supported
# raise an exception
raise ValueError(f"Unsupported reference value type: {ref_value}")
# set the target of the source claim to the reference value object
source_claim.setTarget(ref_target)
# append the source claim to the source claims list
source_claims.append(source_claim)
# add the source claims as a reference to the claim
claim.addSources(source_claims, summary="Adding reference")
# add the claim to the new item
new_item.addClaim(claim, summary="Adding claim")
# return the new item id
return new_item.getID()
def claim_dict2pywikibot_claim(self,repo, claim):
"""
return new pywikibot claim object for add to wikidata using pywikibot from dict
"""
def create_or_update_geoobject(self, city_wdid, country_wdid, named_after_wdid, street_name_en, street_name_ru, maintype, wikidata_only, catname, wdid, coords, district, local_wikidata_uuid=None):
if wdid is None:
wdid = self.create_geoobject_wikidata(city=city_wdid,
name_en=street_name_en,
name_ru =street_name_ru,
named_after=named_after_wdid,
country=country_wdid,
coords=coords,
maintype=maintype,
district=district,
dry_mode=False,
local_wikidata_uuid = local_wikidata_uuid)
if wikidata_only !=True and catname is None:
street_category_result = self.create_category_by_wikidata(wdid, city_wdid)
print(street_category_result)
else:
if catname is not None and self.is_category_exists(catname):
self.wikidata_add_commons_category(wdid,catname)
self.category_add_template_wikidata_infobox(catname)
elif wdid is not None:
street_wd = self.get_wikidata_simplified(wdid)
# SET COORDINATES
self.wikidata_set_coords(wdid,coords=coords)
# CREATE CATEGORY IF NOT EXIST
if street_wd['commons'] is None:
# create street category
street_category_result = self.create_category_by_wikidata(wdid, city_wdid)
print(street_category_result)
else:
print('wikidata entity already has commons category')
#add wikidata infobox if needed
if catname is not None and self.is_category_exists(catname):
self.category_add_template_wikidata_infobox(catname)
def create_geoobject_wikidata(self,city,name_en,coords,name_ru=None,named_after=None, maintype='Q79007',country=None,district=None,dry_mode=False, local_wikidata_uuid = None)->str:
wikidata_template = """
{
"type": "item",
"labels": {
"en": ""
},
"descriptions": {
"en": ""
},
"aliases": {},
"claims": {
"P31": "Q79007",
"P625":{
"value":{
"latitude": 55.666,
"longitude": 37.666,
"precision": 0.0001,
"globe": "http://www.wikidata.org/entity/Q2"
}
}
}
}
"""
translate_variants=dict()
translate_variants['street']=['ulitsa']
translate_variants['Street']=['Ulitsa']
city_wd = self.get_wikidata_simplified(city)
street_type_wd = self.get_wikidata_simplified(maintype)
wd_object = json.loads(wikidata_template)
wd_object["labels"]["en"] = name_en
wd_object["descriptions"]["en"] = street_type_wd['labels']['en'] + ' in ' + city_wd['labels']['en']
if name_ru is not None:
wd_object["labels"]["ru"] = name_ru
wd_object["descriptions"]["ru"] = street_type_wd['labels']['ru'] + ' в ' + city_wd['labels']['ru']
wd_object["aliases"] = {"ru": list(), "en":list()}
wd_object["aliases"]["ru"].append(name_ru + ', ' + city_wd['labels']['ru'])
wd_object["aliases"]["en"].append(name_en + ', ' + city_wd['labels']['en'])
# ALIAS: to "Unylaya street" add alias "Unylaya ulitsa"
for k,v in translate_variants.items():
if name_ru is not None:
if k in name_ru: wd_object["aliases"]["en"].append(name_en.replace(k,v[0]))
#type
wd_object["claims"]["P31"] = street_type_wd['id']
# COORDINATES
if 'LINESTRING' in coords.upper():
#line with 3 points: write coordinates for start, middle, end of street
from model_geo import Model_Geo as Model_geo_ask
coords_list = Model_geo_ask.extract_wktlinestring_to_points(coords)
assert len(coords_list) in (2,3)
else:
lat=None
lon=None
lat, lon = self.location_string_parse(coords)
assert lat is not None
assert lon is not None
wd_object["claims"]["P625"]["value"]["latitude"] = round(
float(lat), 5
) # coords
wd_object["claims"]["P625"]["value"]["longitude"] = round(
float(lon), 5
) # coords
# State
country_claim=self.get_best_claim(city,'P17')
wd_object["claims"]["P17"] = country_claim
# located in adm
wd_object["claims"]["P131"] = city_wd['id']
if district is not None: wd_object["claims"]["P131"] = district
if named_after is not None: wd_object["claims"]["P138"] = named_after
if dry_mode:
print(json.dumps(wd_object, indent=1))
self.logger.info("dry mode, no creating wikidata entity")
return
new_item_id = self.create_wikidata_item(wd_object, local_wikidata_uuid = local_wikidata_uuid)
self.logger.info(f'new object created: https://www.wikidata.org/wiki/{new_item_id} ')
return new_item_id
def wikidata_set_coords(self,wdid,coords):
site = pywikibot.Site('wikidata', 'wikidata')
repo = site.data_repository()
item = pywikibot.ItemPage(site, wdid)
item.get() # load the item data
claims = item.claims # get the claims dictionary
if "P625" in claims:
print('no overwrite coordinates')
return None
lat=None
lon=None
lat, lon = self.location_string_parse(coords)
assert lat is not None
assert lon is not None
coordinateclaim = pywikibot.Claim(repo, 'P625') #Adding coordinate location (P625)
coordinate = pywikibot.Coordinate(lat=lat, lon=lon, precision=0.0001, site=site) #With location markes
coordinateclaim.setTarget(coordinate)
print('Adding coordinate claim')
item.addClaim(coordinateclaim, summary='Adding coordinate claim')
def wikidata_set_address(self,building_wdid,street_wdid,housenumber):
# Create a site object for wikidata
site = pywikibot.Site('wikidata', 'wikidata')
repo = site.data_repository()
# Create an item object from the item ID
item = pywikibot.ItemPage(site, building_wdid)
item.get() # load the item data
claims = item.claims # get the claims dictionary
#CLAIM
claim = pywikibot.Claim(repo, 'P669') #located_on_street
target = pywikibot.ItemPage(repo, street_wdid)
claim.setTarget(target) # Set the target value in the local object.
item.addClaim(claim, summary="Adding machine readable address for files names generation")
#QUALIFIER
qualifier = pywikibot.Claim(repo, 'P670')
qualifier.setTarget(housenumber)
claim.addQualifier(qualifier, summary='Adding a housenumber for files names generation')
del claim
del target
self.reset_cache()
def create_wikidata_building(self, data, dry_mode=False, local_wikidata_uuid = None):
assert "street_wikidata" in data
# get street data from wikidata
assert data["street_wikidata"] is not None
street_dict_wd = self.get_wikidata_simplified(data["street_wikidata"])
city_wd = self.get_wikidata_simplified(data["city"])
data["street_name_ru"] = street_dict_wd["labels"]["ru"]
data["street_name_en"] = street_dict_wd["labels"]["en"]
wikidata_template = """
{
"type": "item",
"labels": {
"ru": ""
},
"descriptions": {
"ru": ""
},
"aliases": {},
"claims": {
"P31": "Q41176",
"P17": "Q159",
"P625":{
"value":{
"latitude": 55.666,
"longitude": 37.666,
"precision": 0.0001,
"globe": "http://www.wikidata.org/entity/Q2"
}
}
}
}
"""
# sample
data["lat"], data["lon"] = self.location_string_parse(
data["latlonstr"])
assert data["lat"] is not None
assert data["lon"] is not None
assert data["street_name_ru"] is not None
assert data["street_name_en"] is not None
assert data["housenumber"] is not None
assert data["street_wikidata"] is not None
wd_object = json.loads(wikidata_template)
wd_object["labels"]["ru"] = data["street_name_ru"] + \
" " + data["housenumber"]
wd_object["labels"]["en"] = self.address_international(
city=city_wd['labels']['en'],
street=data["street_name_en"],
housenumber=data["housenumber"]).strip()
wd_object["descriptions"]["ru"] = "Здание в " + city_wd['labels']['ru']
wd_object["descriptions"]["en"] = "Building in " + city_wd['labels']['en']
wd_object["aliases"] = {"ru": list()}
wd_object["aliases"]["ru"].append(
city_wd['labels']['ru'] + ' ' + data["street_name_ru"] +
" дом " + data["housenumber"]
)
wd_object["claims"]["P625"]["value"]["latitude"] = round(
float(data["lat"]), 5
) # coords
wd_object["claims"]["P625"]["value"]["longitude"] = round(
float(data["lon"]), 5
) # coords
if data.get("coord_source", None) is not None and data["coord_source"].lower() == "yandex maps":
wd_object["claims"]["P625"]["references"] = list()
wd_object["claims"]["P625"]["references"].append(dict())
wd_object["claims"]["P625"]["references"][0]["P248"] = "Q4537980"
if data.get("coord_source", None) is not None and data["coord_source"].lower() == "osm":
wd_object["claims"]["P625"]["references"] = list()
wd_object["claims"]["P625"]["references"].append(dict())
wd_object["claims"]["P625"]["references"][0]["P248"] = "Q936"
if data.get("coord_source", None) is not None and data["coord_source"].lower() == "reforma":
wd_object["claims"]["P625"]["references"] = list()
wd_object["claims"]["P625"]["references"].append(dict())
wd_object["claims"]["P625"]["references"][0]["P248"] = "Q117323686"
wd_object["claims"]["P669"] = {
"value": data["street_wikidata"],
"qualifiers": {"P670": data["housenumber"]},
}
if "district_wikidata" in data:
wd_object["claims"]["P131"]={
"value": data["district_wikidata"]
}
if "project" in data:
wd_object["claims"]["P144"]={
"value": data["project"]
}
if "year" in data:
wd_object["claims"]["P729"] = {
"value": {"time": {"year":int(str(data["year"])[0:4])},"precision":9}}
if "year_source" or "year_url" in data:
wd_object["claims"]["P729"]["references"] = list()
wd_object["claims"]["P729"]["references"].append(dict())
if data.get("year_source") == "2gis":
wd_object["claims"]["P729"]["references"][0]["P248"] = "Q112119515"
if data.get("year_source") == "wikimapia":
wd_object["claims"]["P729"]["references"][0]["P248"] = "Q187491"
if 'https://2gis.ru' in data.get('year_url', ''):
wd_object["claims"]["P729"]["references"][0]["P248"] = "Q112119515"
if 'reformagkh.ru' in data.get('year_url', ''):
wd_object["claims"]["P729"]["references"][0]["P248"] = "Q117323686"
if "year_url" in data:
wd_object["claims"]["P729"]["references"][0]["P854"] = data[
"year_url"
]
if "levels" in data:
wd_object["claims"]["P1101"] = {
"value": {"amount": int(data["levels"]), "unit": None,"error":None}
}
if "levels_source" or "levels_url" in data:
wd_object["claims"]["P1101"]["references"] = list()
wd_object["claims"]["P1101"]["references"].append(dict())
if data.get("levels_source") == "2gis":
wd_object["claims"]["P1101"]["references"][0]["P248"] = "Q112119515"
if data.get("levels_source") == "wikimapia":
wd_object["claims"]["P1101"]["references"][0]["P248"] = "Q187491"
if 'https://2gis.ru' in data.get('levels_url', ''):
wd_object["claims"]["P1101"]["references"][0]["P248"] = "Q112119515"
if 'reformagkh.ru' in data.get('levels_url', ''):
wd_object["claims"]["P1101"]["references"][0]["P248"] = "Q117323686"
if "levels_url" in data:
wd_object["claims"]["P1101"]["references"][0]["P854"] = data["levels_url"]
if 'building' in data and data['building'] is not None:
wd_object["claims"]["P31"] = data['building']
if 'architect' in data and data['architect'] is not None:
wd_object["claims"]["P84"] = data['architect']
if 'architecture' in data and data['architecture'] is not None:
if data['architecture']=='Q34636': data['architecture']='Q1295040' # art noveau --> art noveau architecture
wd_object["claims"]["P149"] = data['architecture']
if dry_mode:
print(json.dumps(wd_object, indent=1))
self.logger.info("dry mode, no creating wikidata entity")
return
new_item_id = self.create_wikidata_item(wd_object, local_wikidata_uuid = local_wikidata_uuid)
print("created building https://www.wikidata.org/wiki/" + new_item_id)
print("created _place" + new_item_id)
if data.get('category') is not None:
self.wikidata_add_commons_category(new_item_id, data.get('category'))
self.category_add_template_wikidata_infobox(data.get('category'))
return new_item_id
def get_territorial_entity(self, wd_record) -> dict:
if 'P131' not in wd_record['claims']:
return None
object_wd = self.get_wikidata_simplified(
wd_record['claims']['P131'][0]['value'])
return object_wd
def validate_street_in_building_record(self, data):
assert data["street_wikidata"] is not None
wd_street = self.get_wikidata_simplified(data["street_wikidata"])
result = None
if 'commons' not in wd_street:
self.logger.debug(
"street "
+ wikidata_street_url
+ " must have wikimedia commons category"
)
return False
if result is None:
result = True
return True
def get_wikidata_simplified(self, entity_id) -> dict:
assert entity_id is not None
assert str(entity_id) != ''
# get all claims of this wikidata objects
if entity_id in self.wikidata_cache['entities_simplified']:
return self.wikidata_cache['entities_simplified'][entity_id]
site = pywikibot.Site("wikidata", "wikidata")
try:
entity = pywikibot.ItemPage(site, entity_id)
entity.get()
except:
traceback.print_exc()
self.logger.error('invalid wikidata entity. Open it in browser and try to fix. https://www.wikidata.org/wiki/' +
entity_id)
quit()
object_record = {'labels': {}}
labels_pywikibot = entity.labels.toJSON()
for lang in labels_pywikibot:
object_record['labels'][lang] = labels_pywikibot[lang]['value']
object_record['id'] = entity.getID()
claims = dict()
if 'claims' not in entity.toJSON():
raise ValueError(f'entitiy https://www.wikidata.org/wiki/{entity_id} must has some claims')
wb_claims = entity.toJSON()['claims']
for prop_id in wb_claims:
claims[prop_id] = list()
for claim in wb_claims[prop_id]:
claim_s=dict()
claim_s['rank']=claim.get('rank',None)
if prop_id=='P1101':
pass
if 'datatype' not in claim['mainsnak']:
pass
# this is 'somevalue' claim, skip, because it not simply
elif claim['mainsnak']['datatype'] == 'wikibase-item':
claim_s['value'] = 'Q'+str(claim['mainsnak']['datavalue']['value']['numeric-id'])
elif claim['mainsnak']['datatype'] == 'time':
claim_s['value'] = claim['mainsnak']['datavalue']['value']['time'][8:]
claim_s['precision'] = claim['mainsnak']['datavalue']['value']['precision']
elif claim['mainsnak']['datatype'] == 'external-id':
claim_s['value'] = str(claim['mainsnak']['datavalue']['value'])
elif claim['mainsnak']['datatype'] == 'string':
claim_s['value'] = str(claim['mainsnak']['datavalue']['value'])
elif claim['mainsnak']['datatype'] == 'quantity':
claim_s['value'] = str(claim['mainsnak']['datavalue']['value'])
elif claim['mainsnak']['datatype'] == 'monolingualtext':
claim_s['value'] = claim['mainsnak']['datavalue']['value']['text']
claim_s['language'] = str(claim['mainsnak']['datavalue']['value']['language'])
if 'qualifiers' in claim: claim_s['qualifiers'] = claim['qualifiers']
claims[prop_id].append(claim_s)
object_record['claims'] = claims
wb_sitelinks = entity.toJSON().get('sitelinks', dict())
commons_sitelink = ''
if 'commonswiki' in wb_sitelinks:
commons_sitelink = wb_sitelinks['commonswiki']['title']
if "P373" in object_record['claims']:
object_record['commons'] = object_record["claims"]["P373"][0]["value"]
elif 'commonswiki' in wb_sitelinks:
object_record['commons'] = wb_sitelinks['commonswiki']['title'].replace(
'Category:', '')
else:
object_record['commons'] = None
'''if "en" not in object_wd["labels"]:
self.logger.error('object https://www.wikidata.org/wiki/' +
wikidata+' must have english label')
return None
'''
self.wikidata_cache['entities_simplified'][entity_id] = object_record
self.wikidata_cache_save(
self.wikidata_cache, self.wikidata_cache_filename)
return object_record
def page_template_taken_on(self, page, location, dry_run=True, interactive=False, verbose=True,message='set Taken on location for manual set list of images'):
assert page
texts = dict()
page_not_need_change = False
texts[0] = page.text
if '.svg'.upper() in page.full_url().upper():
return False
if '.png'.upper() in page.full_url().upper():
return False
if '.ogg'.upper() in page.full_url().upper():
return False
if '{{Information'.upper() not in texts[0].upper():
self.logger.debug(
'template Information not exists in '+page.title())
return False
if '|location='.upper()+location.upper() in texts[0].upper():
self.logger.debug('|location='+location+' already in page')
page_not_need_change = True
texts[1] = texts[0]
else:
try:
texts[1] = self._text_add_template_taken_on(texts[0])
except:
raise ValueError('invalid page text in ' + page.full_url())
assert 'Taken on'.upper() in texts[1].upper() or 'Taken in'.upper() in texts[1].upper() or 'According to Exif data'.upper(
) in texts[1].upper(), 'wrong text in '+page.title()
datestr = self.get_date_from_pagetext(texts[1])
if datestr == False:
return False
if '/' in datestr:
raise ValueError(
'Slash symbols in date causes side-effects. Normalize date in '+page.full_url())
if len(datestr) < len('yyyy-mm-dd'):
return False
if len(datestr) > len('yyyy-mm-dd'):
return False
assert datestr, 'invalid date parce in '+page.full_url()
location_value_has_already = self._text_get_template_taken_on_location(
texts[1])
if location_value_has_already is None:
texts[2] = self._text_add_template_taken_on_location(
texts[1], location)
else:
texts[2] = self._text_get_template_replace_on_location(
texts[1], location)
if texts[2] == False:
return False
if '|location='+location+'}}' not in texts[2]:
return False
# Remove category
cat='Russia photographs taken on '+datestr
texts[2]=texts[2].replace("[[Category:"+cat+"]]",'')
texts[2]=texts[2].replace("[[Category:"+cat.replace(' ','_')+"]]",'')
date_obj = datetime.strptime(datestr, '%Y-%m-%d')
date_obj.strftime('%B %Y')
cat=date_obj.strftime('%B %Y')+' in '+location
texts[2]=texts[2].replace("[[Category:"+cat+"]]",'')
texts[2]=texts[2].replace("[[Category:"+cat.replace(' ','_')+"]]",'')