-
Notifications
You must be signed in to change notification settings - Fork 0
/
fileprocessor.py
2618 lines (2151 loc) · 108 KB
/
fileprocessor.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 exiftool
import locale
from PIL import Image as PILImage
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
import tempfile
import warnings
import shutil
from tqdm import tqdm
import contextlib
import io
import placejpgconfig
from iptcinfo3 import IPTCInfo
class Fileprocessor:
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)
langs_optional = placejpgconfig.langs_optional
langs_primary = placejpgconfig.langs_primary
exiftool_path = "exiftool"
# TIFF LARGER THAN THIS VALUE WILL BE COMPRESSED TO WEBP
tiff2webp_min_size_mb = 19
# Size of chunk for all uploads to wikimedia engine
chunk_size = 10240000
photographer = placejpgconfig.photographer
folder_keywords = ['commons_uploaded', 'commons_duplicates']
wikidata_cache = dict()
def convert_to_webp(self, filepath: str) -> str:
"""Convert image to webp.
Args:
source (pathlib.Path): Path to source image
Returns:
pathlib.Path: path to new image
"""
destination = os.path.splitext(filepath)[0]+'.webp'
image = PILImage.open(filepath) # Open image
image.save(destination, format="webp", lossless=False,
quality=98) # Convert image to webp
# copy metadata to webp require recent exiftool
try:
subprocess.check_output(["exiftool", "-ver"])
cmd = ['exiftool', '-charset', 'utf8', '-tagsfromfile',
filepath, '-overwrite_original', destination] # '-all:all' ,
subprocess.run(cmd)
except subprocess.CalledProcessError:
print("Exiftool is not installed. WEBP file created without exif tags")
return destination
def input2filelist(self, filepath,mode=None):
if os.path.isfile(filepath):
files = [filepath]
assert os.path.isfile(filepath)
uploaded_folder_path = os.path.join(
os.path.dirname(filepath), 'commons_uploaded')
elif os.path.isdir(filepath):
files = os.listdir(filepath)
files = [os.path.join(filepath, x) for x in files]
folder_keywords = self.folder_keywords
if mode=='replace_duplicates':
while 'commons_duplicates' in folder_keywords: folder_keywords.remove('commons_duplicates')
files = list(
filter(lambda name: not any(keyword in name for keyword in folder_keywords), files))
uploaded_folder_path = os.path.join(filepath, 'commons_uploaded')
else:
raise Exception("filepath should be file or directory")
return files, uploaded_folder_path
def prepare_wikidata_url(self, wikidata) -> str:
# convert string https://www.wikidata.org/wiki/Q4412648 to Q4412648
wikidata = str(wikidata).strip()
wikidata = wikidata.replace('https://www.wikidata.org/wiki/', '')
return wikidata
def upload_file(self, filepath, commons_name, description, verify_description=False,ignore_warning=False):
# The site object for Wikimedia Commons
site = pywikibot.Site("commons", "commons")
logging.basicConfig(level=logging.DEBUG, format='%(message)s')
# The upload robot object
bot = UploadRobot(
[filepath], # A list of files to upload
description=description, # The description of the file
# keep original names of urls and files, otherwise it will ask to enter a name for each file
use_filename=commons_name,
keep_filename=True, # Keep the filename as is
# Ask for verification of the description
verify_description=verify_description,
targetSite=site, # The site object for Wikimedia Commons
aborts=True, # List of the warning types to abort upload on
chunk_size=self.chunk_size,
summary='Upload with placejpg',
ignore_warning=ignore_warning
)
print()
print('=======================================================')
print(commons_name.center(60, '*'))
# Try to run the upload robot
try:
# bot.run()
# SAVE pywikibot screen output to move photos to subdirs by errors
f = io.StringIO()
with contextlib.redirect_stderr(f):
bot.run()
pywikibot_output = f.getvalue()
# print('>>>'+pywikibot_output+'<<<')
return pywikibot_output
except Exception as e:
# Handle API errors
print(f"API error: {e.code}: {e.info}")
return False
return None
def deprecated_get_wikidata_simplified(self, wikidata) -> dict:
warnings.warn('moved to model_wiki', DeprecationWarning, stacklevel=2)
# get all claims of this wikidata objects
if wikidata in self.wikidata_cache:
return self.wikidata_cache[wikidata]
cmd = ["wb", "gt", "--json", "--no-minimize", wikidata]
response = subprocess.run(cmd, capture_output=True)
object_wd = json.loads(response.stdout.decode())
object_record = {'names': {}}
try:
object_record['names'] = {
"en": object_wd["labels"]["en"],
"ru": object_wd["labels"]["ru"],
}
except:
raise ValueError('object https://www.wikidata.org/wiki/' +
wikidata+' must has name ru and name en')
for lang in self.langs_optional:
if lang in object_wd["labels"]:
object_record['names'][lang] = object_wd["labels"][lang]
if "P373" in object_wd["claims"]:
object_record['commons'] = object_wd["claims"]["P373"][0]["value"]
elif 'commonswiki' in object_wd["sitelinks"]:
object_record['commons'] = object_wd["sitelinks"]["commonswiki"]["title"].replace(
'Category:', '')
else:
object_record['commons'] = None
if "P31" in object_wd["claims"]:
object_record['instance_of_list'] = object_wd["claims"]["P31"]
self.wikidata_cache[wikidata] = object_record
return object_record
def is_wikidata_id(self, text) -> bool:
warnings.warn('moved to model_wiki', DeprecationWarning, stacklevel=2)
# check if string is valid wikidata id
if text.startswith('Q') and text[1:].isnumeric():
return True
else:
return False
def search_wikidata_by_string(self, text, stop_on_error=True) -> str:
warnings.warn('moved to model_wiki', DeprecationWarning, stacklevel=2)
cmd = ['wb', 'search', '--json', text]
response = subprocess.run(cmd, capture_output=True)
object_wd = json.loads(response.stdout.decode())
if stop_on_error:
if not len(object_wd) > 0:
raise ValueError('not found in wikidata: '+text)
self.logger.debug('found: '+text+' '+object_wd[0]['concepturi'])
return object_wd[0]['id']
def get_wikidata_labels(self, wikidata) -> dict:
warnings.warn('moved to model_wiki', DeprecationWarning, stacklevel=2)
cmd = ['wb', 'gt', '--props', 'labels', '--json', wikidata]
response = subprocess.run(cmd, capture_output=True)
object_wd = json.loads(response.stdout.decode())
return object_wd['labels']
def get_place_from_input(self,filename:str,street:str,geo_dict:dict,override_key='placeQ',geodata_attribute='wikidata',layer=None)->str:
'''
return wikidata id of photo place
diffirent input variants accepted:
* upload-vehicle.py --street Q12345678 EP2D-0030.jpg
return Q12345678
* upload-vehicle.py --street rail.gpkg EP2D-0030.jpg
read coordinates from EXIF, search by coordinates in rail.gpkg
open 1st layer in vector file, get 'wikidata' field value
* upload-vehicle.py --street rail.gpkg EP2D-0030_placeQ12345678.jpg
return Q12345678
'''
from model_wiki import Model_wiki as Model_wiki_ask
modelwiki = Model_wiki_ask()
# take place from filename if present
if os.path.basename(filename).find(override_key)>0:
street_wdid = self.get_placewikidatalist_from_string(
os.path.basename(filename))[0]
elif os.path.isfile(street):
if geo_dict is None:
self.logger.error(
filename + ' must have coordinates for search in geodata, or set --street')
return None
regions_filepath = street
from model_geo import Model_Geo as Model_geo_ask
modelgeo = Model_geo_ask()
if 'dest_lat' in geo_dict and 'dest_lon' in geo_dict:
lat=geo_dict.get("dest_lat")
lon=geo_dict.get("dest_lon")
else:
lat=geo_dict.get("lat")
lon=geo_dict.get("lon")
street_wdid = modelgeo.identify_deodata(lat, lon, regions_filepath, layer=layer, fieldname=geodata_attribute)
if street_wdid is None:
msg = f'file:{regions_filepath} https://geohack.toolforge.org/geohack.php?params={lat};{lon}_type:camera'
self.logger.error(filename.ljust(
40) + ' no found '+msg+'')
modelgeo.save_not_found_geom(lat,lon,filename)
return None
#street_wd = modelwiki.get_wikidata_simplified(street_wdid)
else:
# take street from user input
street_wdid = modelwiki.wikidata_input2id(street)
if street is not None:
assert street_wdid is not None
return street_wdid
def get_coordinate_from_string(self,filename)->list:
# COORDINATE
# search filename for pattern "LatLng(55.59818, 37.58834)"
import re
l=None
regex = "_LatLng(.*?)[)]"
test_str = os.path.basename(filename)
matches = re.finditer(regex, test_str, re.MULTILINE)
for match in matches:
l = match.group()[len('_LatLng('):-1]
parts=l.split(',')
lat=float(parts[0].strip())
lon=float(parts[1].strip())
return lat,lon
return None,None
def make_image_texts_vehicle(self, filename, vehicle, model=None, number=None, street=None, system=None, route=None, country=None, line=None, facing=None, colors=None, operator=None, operator_vehicle_category=None, secondary_wikidata_ids=None, digital_number=None, custom_categories=list(), suffix='', skip_unixtime=False) -> dict:
assert os.path.isfile(filename)
from model_wiki import Model_wiki as Model_wiki_ask
modelwiki = Model_wiki_ask()
categories = set()
need_create_categories = list()
location_of_creation = ''
vehicle_names = {'ru': {'tram': 'трамвай', 'trolleybus': 'троллейбус',
'bus': 'автобус', 'train': 'поезд', 'locomotive': 'локомотив', 'auto': 'автомобиль', 'plane': 'самолёт','metro':'метропоезд'}}
wikidata_4_structured_data = set()
if secondary_wikidata_ids is None: secondary_wikidata_ids = list()
train_synonims = ['train', 'locomotive', 'emu', 'dmu','metro']
# assert facing in ('Left','Right',None)
# obtain exif
dt_obj = self.image2datetime(filename)
geo_dict = self.image2coords(filename)
# STREET
# if street - vector file path: get street wikidata code by point in polygon
if street is not None:
street_wdid = self.get_place_from_input(filename,street,geo_dict)
if street_wdid is None:
self.logger.error('not set place/street')
return None
street_wd = modelwiki.get_wikidata_simplified(street_wdid)
street_names = street_wd["labels"]
wikidata_4_structured_data.add(street_wd['id'])
# add city/district to structured data
city_wd = modelwiki.get_territorial_entity(street_wd)
if city_wd is None:
msg = 'https://www.wikidata.org/wiki/' + \
str(street_wdid) + ' must have territorial entity'
self.logger.error(msg)
return None
wikidata_4_structured_data.add(city_wd['id'])
# Optionaly obtain country from gpkg file if country parameter is path to vector file (.gpkg)
if os.path.isfile(country):
country = self.get_place_from_input(filename,country,geo_dict,override_key='_location',geodata_attribute='name:en')
if country is None:
#place should taken from gpkg, but not found
return None
# TAKEN ON LOCATION
# search filename for pattern "_locationMoscow-Oblast"
import re
l=None
regex = "_location(.*?)[_.\b]"
test_str = os.path.basename(filename)
matches = re.finditer(regex, test_str, re.MULTILINE)
for match in matches:
l = match.group()[9:-1].replace('-',' ').title()
if l == 'location':
l = None
if l is not None: country=l
del l
# MODEL
if model is None:
# extract model "Q123456" from 16666_20070707_000_modelQ123456.jpg
import re
regex = "_model(.*?)[_.\b]"
test_str = os.path.basename(filename)
matches = re.finditer(regex, test_str, re.MULTILINE)
for match in matches:
model = match.group()[6:-1]
if model is not None:
model_wdid = modelwiki.wikidata_input2id(model)
model_wd = modelwiki.get_wikidata_simplified(model_wdid)
model_names = model_wd["labels"]
wikidata_4_structured_data.add(model_wd['id'])
# ROUTE
if route is None:
# extract route "34" from 3216_20070112_052_r34.jpg
import re
regex = "_r(.*?)[_.\b]"
test_str = os.path.basename(filename)
matches = re.finditer(regex, test_str, re.MULTILINE)
for match in matches:
result = match.group()[2:-1]
if 'eplace' in result:
continue
route = result
del result
if route == 'z':
route = None
# DIGITAL_NUMBER
if digital_number is None:
# extract number "1456" from 2TE10M-1456_20230122_444_dn1456.jpg
import re
regex = "_n(.*?)[_.\b]"
test_str = os.path.basename(filename)
matches = re.finditer(regex, test_str, re.MULTILINE)
for match in matches:
digital_number = match.group()[2:-1]
# LICENSE PLATE
license_plate=''
license_plate=self.get_licenceplate_from_string(filename)
# OPERATOR
if operator is not None:
operator_wd = modelwiki.get_wikidata_simplified(modelwiki.wikidata_input2id(operator))
wikidata_4_structured_data.add(operator_wd['id'])
# OPERATOR VEHICLE CATEGORY
if operator_vehicle_category is not None:
categories.add(operator_vehicle_category.replace('Category:',''))
# SYSTEM
if system=='FROMFILENAME':
# extract system "Q123456" from 16666_20070707_000_systemQ123456.jpg
import re
regex = "_system(.*?)[_.\b]"
test_str = os.path.basename(filename)
matches = re.finditer(regex, test_str, re.MULTILINE)
for match in matches:
system = match.group()[7:-1]
system_names = dict()
if system is not None:
system_wdid = modelwiki.wikidata_input2id(system)
system_wd = modelwiki.get_wikidata_simplified(system_wdid)
system_names = system_wd["labels"]
# GET "RZD" from "Russian Railways"
if 'P1813' in system_wd['claims']:
for abbr_record in system_wd['claims']['P1813']:
system_names[abbr_record['language']
] = abbr_record['value']
wikidata_4_structured_data.add(system_wd['id'])
system_territorial_entity = modelwiki.get_territorial_entity(
system_wd)
if system_territorial_entity is not None:
city_name_en = system_territorial_entity['labels']['en'] or ''
city_name_ru = system_territorial_entity['labels']['ru'] or ''
else:
city_name_en = None
city_name_ru = None
if system is None or (city_name_en is None or city_name_ru is None):
city_wd = modelwiki.get_territorial_entity(street_wd)
try:
city_name_en = city_wd['labels']['en']
city_name_ru = city_wd['labels']['ru']
except:
raise ValueError('object https://www.wikidata.org/wiki/' +
city_wd['id']+' must has name ru and name en')
if city_wd['id'] not in wikidata_4_structured_data:
wikidata_4_structured_data.add(city_wd['id'])
assert city_name_en is not None
# LINE
line_wdid = None
line_wd = None
line_names = dict()
if line is not None:
line_wdid = self.take_user_wikidata_id(line)
line_wd = modelwiki.get_wikidata_simplified(line_wdid)
line_names = line_wd["labels"]
wikidata_4_structured_data.add(line_wdid)
elif line is None and vehicle in train_synonims:
# GET RAILWAY LINE FROM WIKIDATA
if 'P81' in street_wd['claims'] and len(street_wd['claims']['P81']) == 1:
line_wd = modelwiki.get_wikidata_simplified(
street_wd['claims']['P81'][0]['value'])
line_wdid = line_wd['id']
# trollybus garage numbers. extract 3213 from 3213_20060702_162.jpg
if number == 'BEFORE_UNDERSCORE':
number = os.path.basename(
filename)[0:os.path.basename(filename).find('_')]
filename_base = os.path.splitext(os.path.basename(filename))[0]
filename_extension = os.path.splitext(os.path.basename(filename))[1]
placenames = {'ru': list(), 'en': list()}
if 'en' in line_names:
if len(line_names['en']) > 0:
placenames['en'].append(line_names['en'])
if 'street_names' in locals() and 'en' in street_names:
if street_names['en'] != '':
placenames['en'].append(street_names['en'])
if suffix != '':
suffix=f' {suffix}'
if skip_unixtime:
timestamp_format=''
else:
timestamp_format='%s'
if vehicle == 'auto' or (vehicle not in train_synonims and number is None):
objectname_en = '{city} {transport} {license_plate}'.format(
transport=vehicle,
city=city_name_en,
model=model_names['en'],
license_plate=license_plate
)
objectname_ru = '{city}, {transport} {model} {license_plate}'.format(
city=city_name_ru,
transport=vehicle_names['ru'][vehicle],
model=model_names.get('ru', model_names['en']),
license_plate=license_plate
)
if license_plate != '':
objectname_ru = ' '+objectname_ru
if vehicle != 'auto':
commons_filename = '{city} {transport} {license_plate} {dt} {timestamp} {place} {model}{suffix}{extension}'.format(
city=city_name_en,
transport=vehicle,
license_plate=license_plate,
dt=dt_obj.strftime("%Y-%m"),
timestamp = dt_obj.strftime(timestamp_format),
place=' '.join(placenames['en']),
model=model_names['en'],
suffix=suffix,
extension=filename_extension)
elif vehicle == 'auto':
commons_filename = '{transport} {model} {city} {place} {license_plate} {dt} {timestamp}{suffix}{extension}'.format(
city=city_name_en,
transport=vehicle,
license_plate=license_plate,
dt=dt_obj.strftime("%Y-%m"),
timestamp = dt_obj.strftime(timestamp_format),
place=' '.join(placenames['en']),
model=model_names['en'],
suffix=suffix,
extension=filename_extension)
elif vehicle not in train_synonims:
objectname_en = '{city} {transport} {number}'.format(
transport=vehicle,
city=city_name_en,
model=model_names['en'],
number=number
)
objectname_ru = '{city}, {transport} {model} {number}'.format(
city=city_name_ru,
transport=vehicle_names['ru'][vehicle],
model=model_names.get('ru', model_names['en']),
number=number
)
if license_plate != '':
objectname_ru = ' '+objectname_ru
commons_filename = '{city} {transport} {number} {dt} {timestamp} {place} {model}{suffix}{extension}'.format(
city=city_name_en,
transport=vehicle,
number=number,
dt=dt_obj.strftime("%Y-%m"),
timestamp = dt_obj.strftime(timestamp_format),
place=' '.join(placenames['en']),
model=model_names['en'],
suffix=suffix,
extension=filename_extension)
# filename for Moscow Trolleybus
if system_wdid == 'Q4304313':
commons_filename = '{city} {transport} {model} {number} {dt} {place}{suffix}{extension}'.format(
city=city_name_en,
transport=vehicle,
number=number,
dt=dt_obj.strftime("%Y-%m"),
timestamp = dt_obj.strftime(timestamp_format),
place=' '.join(placenames['en']),
model=model_names['en'],
suffix=suffix,
extension=filename_extension)
commons_filename = commons_filename.replace(' ',' ')
elif vehicle in train_synonims:
assert street_names is not None or line_names is not None
if 'en' not in system_names:
system_names['en'] = ''
if 'ru' not in system_names:
system_names['ru'] = ''
# {model} removed
number_lat = translit(number, "ru", reversed=True)
objectname_en = '{system}{number_lat}'.format(
system=system_names['en']+' ',
city=city_name_en,
model=model_names['en'],
number_lat=number_lat,
place=' '.join(placenames['en'])
)
commons_filename = '{system}{number_lat} {dt} {place} {timestamp}{suffix}{extension}'.format(
system=system_names['en']+' ',
number_lat=number_lat,
dt=dt_obj.strftime("%Y-%m"),
place=' '.join(placenames['en']),
timestamp=dt_obj.strftime("%s"),
suffix=suffix,
extension=filename_extension
)
objectname_ru = '{system}{number}'.format(
system=system_names['ru']+' ',
transport=vehicle_names['ru'][vehicle],
model=model_names.get('ru', model_names['en']),
number=number
)
locomotive_inscription = number_lat
locomotive_railway_code = system_names['en']
commons_filename = commons_filename.replace("/", " drob ")
text = ''
if vehicle in ('bus','trolleybus','tram'):
text = """== {{int:filedesc}} ==
{{Bus-Information
|description="""
else:
text = """== {{int:filedesc}} ==
{{Information
|description="""
captions = dict()
assert 'en' in street_names, 'https://www.wikidata.org/wiki/' + \
street_wdid + ' must have english name'
captions['en'] = objectname_en + ' at ' + street_names['en']
if route is not None:
captions['en'] += ' Line '+route
if line_wdid is not None:
assert 'en' in modelwiki.get_wikidata_simplified(line_wdid)[
'labels'], 'object https://www.wikidata.org/wiki/' + line_wdid + ' must has name en'
captions['en'] += ' ' + \
modelwiki.get_wikidata_simplified(line_wdid)['labels']['en']
text += "{{en|1=" + captions['en'] + '}}'+"\n"
lang='ru'
assert street_names.get(lang,'') != '', 'object https://www.wikidata.org/wiki/' + line_wdid + ' must has name'+lang
captions[lang] = objectname_ru + ' на ' + \
street_names[lang].replace(
'Улица', 'улица').replace('Проспект', 'проспект')
if route is not None:
captions[lang] += ' Маршрут '+route
if line_wdid is not None:
captions[lang] += ' ' + \
modelwiki.get_wikidata_simplified(line_wdid)['labels'][lang]
text += "{{"+lang+"|1=" + captions[lang] + '}}'+"\n"
if vehicle in ('bus','trolleybus','tram'):
text += " {{#property:P180|from=M{{PAGEID}} }} \n"
else:
if model is not None:
text += " {{on Wikidata|" + model_wdid.split('#')[0] + "}}\n"
text += " {{on Wikidata|" + street_wdid + "}}\n"
if type(secondary_wikidata_ids) == list and len(secondary_wikidata_ids) > 0:
for wdid in secondary_wikidata_ids:
if vehicle in ('bus','trolleybus','tram'):
pass
else:
text += " {{on Wikidata|" + wdid + "}}\n"
heritage_id = None
heritage_id = modelwiki.get_heritage_id(wdid)
if heritage_id is not None:
text += "{{Cultural Heritage Russia|" + heritage_id + "}}"
today = datetime.today()
if today.strftime('%Y-%m') == '2024-09':
text += "{{Wiki Loves Monuments 2024|ru}}"
text += "\n"
if vehicle in ('bus','trolleybus','tram') and model is not None:
text += "|Body={{on Wikidata|" + model_wdid.split('#')[0] + "}}\n"
if vehicle in ('bus','trolleybus','tram') and model is not None:
text += "|Place={{#invoke:Information|SDC_Location|icon=true}} {{#if:{{#property:P1071|from=M{{PAGEID}} }}|(<small>{{#invoke:PropertyChain|PropertyChain|qID={{#invoke:WikidataIB |followQid |props=P1071}}|pID=P131|endpID=P17}}</small>)}}\n"
if vehicle in ('bus','trolleybus','tram') and operator is not None:
text += "|Operator={{on Wikidata|" + operator_wd + "}}\n"
if vehicle in ('bus','trolleybus','tram'):
text += "|number_plate=\n"
text += "|depot=\n"
if number is not None:
text += "|fleet_number="+str(number)+"\n"
if license_plate != '':
text += "|license_plate="+str(license_plate)+"\n"
text += "|Chassis=\n"
text += "|Model_Year=\n"
text += self.get_date_information_part(dt_obj, country)
text += self.get_source_information_part(filename)
text += "}}\n"
tech_description, tech_categories = self.get_tech_description(filename, geo_dict)
assert None not in tech_categories, 'None value in '+str(tech_categories)
text +=tech_description+"\n"
categories.update(tech_categories)
if 'catid' in filename:
assert custom_categories is not None
if custom_categories is not None:
categories.update(custom_categories)
transports = {
'tram': 'Trams',
'trolleybus': 'Trolleybuses',
'bus': 'Buses',
'train': 'Rail vehicles',
'metro': 'Rail vehicles',
'locomotive': 'Locomotives',
'auto': 'Automobiles'
}
transports_color = {
'tram': 'Trams',
'trolleybus': 'Trolleybuses',
'bus': 'Buses',
'train': 'Rail vehicles',
'metro': 'Rail vehicles',
'locomotive': 'Rail vehicles',
'auto': 'Automobiles'
}
transports_wikidata = {
'tram': 'Q3407658',
'trolleybus': 'Q5639',
'bus': 'Q5638',
'train': 'Q1414135',
'subway':'Q1414135',
'locomotive': 'Q93301',
'auto': 'Q1420'
}
# CATEGORY FOR ROUTE
if route is not None:
cat="{transports} on route {route} in {city}".format(
transports=transports[vehicle],
route=route,
city=city_name_en)
cat_content='''
{{GeoGroup}}
[[Category:$vehicle routes designated $route|$city_name_en]]
[[Category:$transports in $city_name_en by route|$route]]'''
cat_content=cat_content.replace('$vehicle',vehicle.title())
cat_content=cat_content.replace('$route',route)
cat_content=cat_content.replace('$transports',transports[vehicle])
cat_content=cat_content.replace('$city_name_en',city_name_en)
need_create_categories.append({'name':cat,'content':cat_content})
categories.add(cat)
cat = 'Category:$transports in $city_name_en by route'.replace('$transports',transports[vehicle]).replace('$city_name_en',city_name_en)
cat_content='''
{{GeoGroup}}
[[Category:$transports in $city_name_en]]'''
cat_content=cat_content.replace('$vehicle',vehicle.title())
cat_content=cat_content.replace('$route',route)
cat_content=cat_content.replace('$transports',transports[vehicle])
cat_content=cat_content.replace('$city_name_en',city_name_en)
need_create_categories.append({'name':cat,'content':cat_content})
# CATEGORY BY PHOTOGRAPHER
cat = 'Photographs by {photographer}/{country}/{transport}'
cat = cat.format(photographer=self.photographer,
country=country,
transport=transports[vehicle].lower().capitalize())
categories.add(cat)
cat_content='''{{Usercat}}
[[Category:Photographs_by_'''+self.photographer+'/'+country+''']]'''
modelwiki.create_category(
cat, cat_content)
cat = 'Photographs by {photographer}/{country}'
cat = cat.format(photographer=self.photographer,
country=country,
transport=transports[vehicle].lower().capitalize())
cat_content='''{{Usercat}}
[[Category:Photographs_by_'''+self.photographer+''']]
[[Category:Photographs_of_'''+country+'''_by_photographer]]'''
modelwiki.create_category(
cat, cat_content)
trains_on_line_cat = None
trains_on_station_cat = None
if vehicle in train_synonims:
trains_on_station_cat = None
trains_on_station_cat = modelwiki.search_commonscat_by_2_wikidata(
street_wdid, 'Q870')
if trains_on_station_cat is None:
if street_wd['commons'] is not None:
cat = 'Category:Trains at '+street_wd['commons']
if modelwiki.is_category_exists(cat):
trains_on_station_cat = cat
del cat
if line_wd is not None:
trains_on_line_cat = modelwiki.search_commonscat_by_2_wikidata(
line_wdid, 'Q870')
if trains_on_line_cat is None:
if line_wd['commons'] is not None:
cat = 'Category:Trains on '+line_wd['commons']
if modelwiki.is_category_exists(cat):
trains_on_line_cat = cat
del cat
# TRAINS AT STATION
if trains_on_station_cat is not None:
categories.add(trains_on_station_cat)
if line_wdid is not None:
wikidata_4_structured_data.add(line_wdid)
wikidata_4_structured_data.add(street_wdid)
# TRAINS ON LINE
elif trains_on_line_cat is not None:
categories.add(trains_on_line_cat)
if line_wdid is not None:
wikidata_4_structured_data.add(line_wdid)
wikidata_4_structured_data.add(street_wdid)
if trains_on_station_cat is None:
# STATION
if street_wd['commons'] is None:
self.logger.error('https://www.wikidata.org/wiki/' +
street_wd['id'] + ' must have commons category')
return None
categories.add(street_wd['commons'])
wikidata_4_structured_data.add(street_wdid)
# LINE
if line_wd is not None:
wikidata_4_structured_data.add(line_wd['id'])
if trains_on_line_cat is None and line_wd['commons'] is not None:
categories.add(line_wd['commons'])
else:
if line_wd is not None:
if line_wd['commons'] is not None:
categories.add(line_wd['commons'])
if street_wd is not None and 'commons' in street_wd:
categories.add(street_wd['commons'])
assert None not in wikidata_4_structured_data, 'empty value added to structured data set:' + \
str(' '.join(list(wikidata_4_structured_data)))
# locale.setlocale(locale.LC_ALL, 'en_GB')
if vehicle == 'tram':
catname = "Railway photographs taken on "+dt_obj.strftime("%Y-%m-%d")
categories.add(catname)
if vehicle in train_synonims:
catname = "Railway photographs taken on " + \
dt_obj.strftime("%Y-%m-%d")
categories.add(catname)
modelwiki.create_category(
catname, '{{Railway photographs taken on navbox}}')
if isinstance(country, str) and len(country) > 3:
catname = dt_obj.strftime("%B %Y") + \
" in rail transport in "+country
categories.add(catname)
category_content = '{{GeoGroup|level=2}}{{railtransportmonth-country|'+dt_obj.strftime(
"%Y")[0:3]+'|'+dt_obj.strftime("%Y")[-1:]+'|'+dt_obj.strftime("%m")+'|'+country+'}}'
modelwiki.create_category(catname, category_content)
# FACING
# do not add facing category if this is interior
if 'Q60998096' in secondary_wikidata_ids:
facing = None
if facing is not None:
facing = facing.strip().capitalize()
# assert facing.strip().upper() in ('LEFT','RIGHT')
if facing == 'Left':
text += "[[Category:"+transports[vehicle] + \
" facing " + facing.lower() + "]]\n"
if facing == 'Right':
text += "[[Category:"+transports[vehicle] + \
" facing " + facing.lower() + "]]\n"
if facing == 'Side':
text += "[[Category:Side views of " + \
transports[vehicle].lower()+"]]\n"
if facing == 'Rear':
text += "[[Category:Rear views of " + \
transports[vehicle].lower()+"]]\n"
if facing == 'Front':
text += "[[Category:Front views of " + \
transports[vehicle].lower()+"]]\n"
if facing == 'Rear three-quarter'.capitalize():
text += "[[Category:Rear three-quarter views of " + \
transports[vehicle].lower()+"]]\n"
if facing == 'Three-quarter'.capitalize():
text += "[[Category:Three-quarter views of " + \
transports[vehicle].lower()+"]]\n"
if facing == 'Left':
wikidata_4_structured_data.add('Q119570753')
if facing == 'Right':
wikidata_4_structured_data.add('Q119570670')
if facing == 'Front':
wikidata_4_structured_data.add('Q1972238')
elif facing is None:
self.logger.info('🤏 direction of vehicle skipped')
# COLORS CATEGORY
if colors is None and 'color' in os.path.basename(filename):
colors = self.get_colorlist_from_string(os.path.basename(filename))
if colors is not None:
colorname = ''
if colors[0].upper() == 'RZDGREEN':
text += "[[Category:Trains in Russian railways green livery]]\n".format(
transports=transports_color[vehicle].lower(),
colorname=colorname)
elif colors[0].upper() == 'RZD':
text += "[[Category:Trains in Russian Railways livery]]\n".format(
transports=transports_color[vehicle].lower(),
colorname=colorname)
else:
colors.sort()
colorname = ' and '.join(colors)
colorname = colorname.lower().capitalize()
text += "[[Category:{colorname} {transports}]]\n".format(
transports=transports_color[vehicle].lower(),
colorname=colorname)
elif colors is None:
self.logger.info('🤏 colors of vehicle skipped')
# number
has_category_for_this_vehicle = False
if number is not None and number.isdigit():
number_filtered = number
if '-' in number_filtered:
number_filtered = number_filtered[number_filtered.index(
'-')+1:]
if digital_number is None:
digital_number = number_filtered
if number is not None and vehicle in ('bus','trolleybus','tram'):
cat = f'{city_name_en} {vehicle} {number}'
self.logger.info('search if exist optional category '+cat)
if modelwiki.is_category_exists(cat):
has_category_for_this_vehicle = True
categories.add(cat)
elif number is not None and vehicle in train_synonims:
# search for category for this railway locomotive
cat = f'{locomotive_railway_code} {locomotive_inscription}'
if modelwiki.is_category_exists(cat):
has_category_for_this_vehicle = True
categories.add(cat)
elif digital_number.isdigit():
catname = "Number "+digital_number+" on rail vehicles"
category_page_content = '{{NumbercategoryTrain|'+digital_number+'}}'
modelwiki.create_category(catname, category_page_content)
categories.add(catname)
# upper category
catname = 'Number '+digital_number+' on vehicles'
category_page_content = '{{Numbercategory-vehicle|'+digital_number + \
'|vehicle|Number '+digital_number+' on objects|Vehicle}}'
modelwiki.create_category(catname, category_page_content)
# upper category
catname = 'Number '+digital_number+' on objects'
category_page_content = '{{Number on object|n='+digital_number+'}}'
modelwiki.create_category(catname, category_page_content)
# end of search category for this vehicle
if number is not None and vehicle == 'bus' and digital_number.isdigit():
catname = f'Number {digital_number} on buses'
if not has_category_for_this_vehicle: categories.add(catname)
modelwiki.create_number_on_vehicles_category(vehicle='bus', number=digital_number)
elif number is not None and vehicle == 'trolleybus' and digital_number.isdigit():
catname = f'Number {digital_number} on trolleybuses'
if not has_category_for_this_vehicle: categories.add(catname)
modelwiki.create_number_on_vehicles_category(vehicle='trolleybus', number=digital_number)
elif number is not None and vehicle == 'tram' and digital_number.isdigit():
catname="Trams with fleet number "+digital_number
if not has_category_for_this_vehicle: categories.add(catname)
category_page_content = '{{' + \
f'Numbercategory-vehicle-fleet number|{digital_number}|Trams|Number {digital_number} on trams'+'|image=}}'
modelwiki.create_category(catname, category_page_content)
elif number is not None and vehicle != 'tram':
pass
if dt_obj is not None and vehicle not in train_synonims:
catname = "{transports} in {country} photographed in {year}".format(
transports=transports[vehicle],