-
Notifications
You must be signed in to change notification settings - Fork 8
/
commons_category_coords.py
234 lines (217 loc) · 6.71 KB
/
commons_category_coords.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
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Migrate coordinate templates used in categories
# 23 Dec 2020 Mike Peel Started
import pywikibot
import numpy as np
def get_precision(val):
# print(val)
if '.' in str(val):
val = val.split('.')[1]
length = len(val)
else:
length = 0
if length >= 5:
length = 5
# print(len(val))
return 10**-length
def calc_coord(params):
print(params)
lat = False
lon = False
precision = False
if any('globe' in s.lower() for s in params):
if not any('earth' in s.lower() for s in params):
return lat, lon, precision
if len(params) >= 8:
if 'S' in params[3] or 'N' in params[3]:
lat = float(params[0]) + (float(params[1])/60.0)+(float(params[2])/(60.0*60.0))
if 'S' in params[3]:
lat = -lat
lon = float(params[4]) + (float(params[5])/60.0)+(float(params[6])/(60.0*60.0))
if 'W' in params[7] or 'O' in params[7]:
lon = -lon
precision = get_precision(params[2])/(60.0*60.0)
if lat == False and len(params) > 2:
if ('S' in params[2] or 'N' in params[2]) and len(params) >= 5:
lat = float(params[0]) + (float(params[1])/60.0)
if 'S' in params[2]:
lat = -lat
lon = float(params[3]) + (float(params[4])/60.0)
if 'W' in params[5] or 'O' in params[5]:
lon = -lon
precision = get_precision(params[1])/(60.0)
elif (params[1] == 'N' or params[1] == 'S') and len(params) >= 3:
lat = float(params[0])
lon = float(params[2])
precision = get_precision(params[0])
if params[1] == 'S':
lat = -lat
if params[3] == 'W' or params[3] == 'O':
lon = -lon
elif '.' in params[0] and '.' in params[1]:
lat = float(params[0])
lon = float(params[1])
precision = get_precision(params[0])
else:
print(params)
print('Something odd in calc_coord (1)')
# return False, False, False
elif '.' in params[0] and '.' in params[1]:
lat = float(params[0])
lon = float(params[1])
precision = get_precision(params[0])
if lat == False:
print(params)
print('Something odd in calc_coord (2)')
# return False, False, False
# print(lon)
# print(lat)
# print(precision)
return lat, lon, precision
def check_match(lat1, lon1, prec1, lat2, lon2, prec2):
# prec = np.min[prec1, prec2])
# print(prec1)
# print(prec2)
# print(prec)
# From https://stackoverflow.com/questions/19412462/getting-distance-between-two-points-based-on-latitude-longitude
dlon = lon2 - lon1
dlat = lat2 - lat1
a = np.sin(dlat / 2)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon / 2)**2
c = 2 * np.arctan2(np.sqrt(a), np.sqrt(1 - a))
distance = 6373.0 * c
print(distance)
# print(6373.0*prec)
if distance < 10:
return True
else:
return False
commons = pywikibot.Site('commons', 'commons')
repo = commons.data_repository()
globe_item = pywikibot.ItemPage(repo, 'Q2')
coord_templates = ['Object location']
debug = False
remove_from_commons = False
numedited = 0
maxnumedited = 2000
template = pywikibot.Page(commons, 'Template:'+coord_templates[0])
targetcats = template.embeddedin(namespaces='14')
for cat in targetcats:
print('https://commons.wikimedia.org/wiki/'+cat.title().replace(" ","_"))
try:
wd_item = pywikibot.ItemPage.fromPage(cat)
item_dict = wd_item.get()
except:
print("No Wikidata sitelink found")
continue
try:
existing_id = item_dict['claims']['P301']
print('P301 exists, following that.')
for clm2 in existing_id:
wd_item = clm2.getTarget()
item_dict = wd_item.get()
qid = wd_item.title()
except:
null = 0
print('https://www.wikidata.org/wiki/'+wd_item.title())
ishuman = False
P31 = ''
try:
P31 = item_dict['claims']['P31']
except:
null = 0
if P31 != '':
for clm in P31:
# print(clm)
# print(clm.getTarget().title())
if clm.getTarget().title() == 'Q5' or clm.getTarget().title() == 'Q4830453' or clm.getTarget().title() == 'Q783794' or clm.getTarget().title() == 'Q22667' or clm.getTarget().title() == 'Q13406463' or clm.getTarget().title() == 'Q4167836':
ishuman = True
if ishuman:
print('Not importing coordinate for a human, business, company, railway, list, or category')
continue
coordinate = False
try:
P625 = item_dict['claims']['P625']
except:
P625 = ''
print(P625)
if P625 != '':
for clm in P625:
try:
coordinate = clm.getTarget()
print(coordinate)
print(coordinate.lat)
except:
P625 = 'Bad'
if P625 == 'Bad':
print('Problem with coordinates')
continue
count = 0
for template in cat.templatesWithParams():
for tpl in coord_templates:
if tpl in template[0].title():
count += 1
if count != 1:
print('Wrong number of coordinate templates (' + str(count) + '), skipping')
continue
done = False
for template in cat.templatesWithParams():
for tpl in coord_templates:
# print(tpl)
if not done:
if tpl in template[0].title():
# print(template)
print(template[0].title())
print(template[1])
if 'wikidata' not in str(template[1]) and 'Wikidata' not in str(template[1]):
try:
lat, lon, precision = calc_coord(template[1])
if not coordinate:
coordinateclaim = pywikibot.Claim(repo, u'P625')
coordinate = pywikibot.Coordinate(lat=lat, lon=lon, precision=precision, site=commons,globe_item=globe_item)
coordinateclaim.setTarget(coordinate)
test = 'y'
if debug:
test = input('Save coordinate?')
if test == 'y':
wd_item.addClaim(coordinateclaim, summary=u'Importing coordinate from Commons')
numedited += 1
done = True
test1 = check_match(lat, lon, precision, coordinate.lat, coordinate.lon, coordinate.precision)
except:
test1 = False
else:
test1 = True
if test1 and remove_from_commons:
edit_test = False
try:
template_string = '{{'+tpl+cat.text.split('{{'+tpl)[1].split('}}')[0]+"}}"
print(template_string)
target_text = cat.text.replace(template_string,'')
edit_test = True
except:
try:
template_string = '{{'+tpl.lower()+cat.text.split('{{'+tpl.lower())[1].split('}}')[0]+"}}"
print(template_string)
target_text = cat.text.replace(template_string,'')
edit_test = True
except:
edit_test = False
continue
if edit_test:
target_text = target_text.replace('\n\n\n','\n').rstrip('\n').lstrip('\n')
if 'Wikidata Infobox' not in target_text:
target_text = "{{Wikidata Infobox}}\n" + target_text
target_text = target_text.replace('\n\n\n','\n').strip().rstrip('\n').lstrip('\n')
print("New text:")
print(target_text)
test = 'y'
if debug:
test = input('Remove from Commons')
if test == 'y':
cat.text = target_text
cat.save('Coordinates now through the infobox')
numedited += 1
if numedited >= maxnumedited:
print(numedited)
exit()