-
Notifications
You must be signed in to change notification settings - Fork 0
/
Generator+Metadata.swift
359 lines (320 loc) · 12.2 KB
/
Generator+Metadata.swift
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
//
// Generator+Metadata.swift
// Generator
//
// Created by Lucka on 24/10/2024.
//
import Foundation
import OverpassKit
public extension Generator {
var missingWikidata: [ Region ] {
regions { $0.wikidataIdentifier == nil }
}
func ensureMetadata(
with api: Overpass, cooldown: Duration, including regions: Set<Region.Code>?
) async throws {
try await ensureCountries(with: api, cooldown: cooldown)
let filter = RegionFilter(regions)
if let filter {
countries = countries.filter(filter.filter(country:))
}
try await withThrowingTaskGroup(of: Void.self) { group in
for index in countries.indices {
group.addTask {
try await self.ensureSubdivisionsOfCountry(
at: index, with: api, cooldown: cooldown, filterBy: filter
)
}
}
try await group.waitForAll()
}
}
func loadMetadata(including regions: Set<Region.Code>? = nil) throws {
try loadCountries()
let filter = RegionFilter(regions)
if let filter {
countries = countries.filter(filter.filter(country:))
}
for index in countries.indices {
let countryCode = countries[index].code
guard !Self.countriesWithoutSubdivisionDefined.contains(countryCode.rawValue) else {
continue
}
countries[index].subdivisions = try loadSubdivisions(of: countryCode, filterBy: filter)
}
}
}
extension Generator {
nonisolated var countryMetadataFileURL: URL {
metadataDirectory
.appending(component: "countries")
.appendingPathExtension("json")
}
nonisolated var metadataSubdivisionsDirectory: URL {
metadataDirectory.appending(path: "subdivisions")
}
nonisolated var metadataDirectory: URL {
workingDirectory.appending(component: "metadata")
}
nonisolated func subdivisionMetadataFileURL(of regionCode: Region.Code) -> URL {
metadataSubdivisionsDirectory
.appending(component: regionCode.rawValue)
.appendingPathExtension("json")
}
}
fileprivate extension Generator {
enum MetadataError: Error {
case unableToFetchSubdivision(code: Region.Code)
case invalidTag(code: Region.Code, tag: String)
}
static let countriesWithoutSubdivisionDefined: Set<String> = [
"AI", "AQ", "AS", "AW", "AX",
"BL", "BM", "BV",
"CC", "CK", "CW", "CX",
"FK", "FO",
"GF", "GG", "GI", "GP", "GS", "GU",
"HK", "HM",
"IM", "IO",
"JE",
"KY",
"MF", "MO", "MP", "MQ", "MS",
"NC", "NF", "NU",
"PF", "PM", "PN", "PR",
"RE",
"SX",
"TC", "TF", "TK",
"VA", "VG", "VI",
"XK",
"YT"
]
func ensureCountries(with api: Overpass, cooldown: Duration) async throws {
let file = countryMetadataFileURL
guard !FileManager.default.fileExists(atPath: file.path()) else {
try loadCountries()
return
}
countries = try await fetchCountries(with: api, cooldown: cooldown)
let encoder = JSONEncoder()
encoder.outputFormatting = [
.prettyPrinted, .sortedKeys, .withoutEscapingSlashes
]
try encoder.encode(countries).write(to: file)
}
func ensureSubdivisionsOfCountry(
at index: Int, with api: Overpass, cooldown: Duration, filterBy filter: RegionFilter?
) async throws {
let country = countries[index]
guard !Self.countriesWithoutSubdivisionDefined.contains(country.code.rawValue) else {
return
}
let file = subdivisionMetadataFileURL(of: country.code)
guard !FileManager.default.fileExists(atPath: file.path()) else {
countries[index].subdivisions = try loadSubdivisions(of: country.code, filterBy: filter)
return
}
var subdivisions = try await fetchSubdivision(of: country, with: api, cooldown: cooldown)
guard !subdivisions.isEmpty else {
throw MetadataError.unableToFetchSubdivision(code: country.code)
}
let encoder = JSONEncoder()
encoder.outputFormatting = [ .prettyPrinted, .sortedKeys, .withoutEscapingSlashes ]
try encoder.encode(subdivisions).write(to: file)
if let filter {
subdivisions = subdivisions.filter(filter.filter(region:))
}
countries[index].subdivisions = subdivisions
}
func loadCountries() throws {
countries = try JSONDecoder()
.decode([ Region ].self, from: try .init(contentsOf: countryMetadataFileURL))
}
func loadSubdivisions(of countryCode: Region.Code, filterBy filter: RegionFilter?) throws -> [ Region ] {
var subdivisions = try JSONDecoder()
.decode(
[ Region ].self,
from: try .init(contentsOf: subdivisionMetadataFileURL(of: countryCode))
)
if let filter {
subdivisions = subdivisions.filter(filter.filter(region:))
}
return subdivisions
}
nonisolated func fetchCountries(
with api: Overpass, cooldown: Duration
) async throws -> [ Region ] {
/* Query countries */
/*
[out:json];
relation["admin_level"="2"]["ISO3166-1"]["type"!="land_area"]->.countries;
relation(r.countries:"subarea")->.subareas;
(
.countries;
relation.subareas["ISO3166-1"];
relation(r.subareas:"subarea")["ISO3166-1"];
relation["ISO3166-1"="AQ"]; // Antarctica
)->.countries;
foreach.countries
{
convert Country
::id = id(),
code = t["ISO3166-1"],
wikidata = t["wikidata"];
out;
};
out tags;
*/
try await taskGroup.addTask(cooldown: cooldown) {
try await api.query(Region.Element.self) {
Elements(.relation) {
FilterBy(tag: "admin_level", equals: "2")
FilterBy(tag: "ISO3166-1", exists: true)
FilterBy(tag: "type", notEquals: "land_area")
}
.as("countries")
Elements(.relation) {
Recurse(into: .relations, of: "countries", by: "subarea")
}
.as("subareas")
Union {
Elements(set: "countries")
Elements(.relation, in: "subareas") {
FilterBy(tag: "ISO3166-1", exists: true)
}
Elements(.relation) {
Recurse(into: .relations, of: "subareas", by: "subarea")
FilterBy(tag: "ISO3166-1", exists: true)
}
Elements(.relation) {
FilterBy(tag: "ISO3166-1", equals: "AQ")
}
}
.as("countries")
ForEach("countries") {
Convert(typeName: "Country") {
ConvertAsId()
ConvertAsTag("code", by: .tag("ISO3166-1"))
ConvertAsTag("wikidata", by: .tag("wikidata"))
}
Output()
}
Output(verbosity: .tags)
}
.map {
guard !$0.tags.wikidata.isEmpty else {
throw MetadataError.invalidTag(code: $0.tags.code, tag: "wikidata")
}
return .init(element: $0)
}
}
}
nonisolated func fetchSubdivision(
of country: Region, with api: Overpass, cooldown: Duration
) async throws -> [ Region ] {
/* Query first administrations */
/*
[out:json];
relation(id)->.country;
relation(r.country:"subarea")[!"ISO3166-1"]->.subareas;
// Virtual subareas contianing the real subdivisions, like RU and NO
relation.subareas[!"ISO3166-2"]->.virtual_subareas;
(
relation.subareas["ISO3166-2"];
relation(r.virtual_subareas:"subarea")[!"ISO3166-1"]["ISO3166-2"];
)->.regions;
// Use collections to present boundaries, like CD
if (regions.count(relations)==0) {
relation.subareas["collection"="boundary"]["boundary"!="historic"]->.collection;
relation(r.collection)[!"ISO3166-1"]["ISO3166-2"]->.regions;
};
foreach.regions
{
convert Region
::id = id(),
code = t["ISO3166-2"],
wikidata = t["wikidata"];
out;
};
out tags;
*/
try await taskGroup.addTask(cooldown: cooldown) {
try await api.query(Region.Element.self) {
Elements(.relation) {
FilterBy(id: country.id)
}
.as("country")
Elements(.relation) {
Recurse(into: .relations, of: "country", by: "subarea")
FilterBy(tag: "ISO3166-1", exists: false)
}
.as("subareas")
Elements(.relation, in: "subareas") {
FilterBy(tag: "ISO3166-2", exists: false)
}
.as("virtual_subareas")
Union {
Elements(.relation, in: "subareas") {
FilterBy(tag: "ISO3166-2", exists: true)
}
Elements(.relation) {
Recurse(into: .relations, of: "virtual_subareas")
FilterBy(tag: "ISO3166-1", exists: false)
FilterBy(tag: "ISO3166-2", exists: true)
}
}
.as("regions")
Optionally(.count(.relations, in: "regions").equals(0)) {
Elements(.relation, in: "subarea") {
FilterBy(tag: "collection", equals: "boundary")
FilterBy(tag: "boundary", notEquals: "historic")
}
.as("collection")
Elements(.relation) {
Recurse(into: .relations, of: "collection")
FilterBy(tag: "ISO3166-1", exists: false)
FilterBy(tag: "ISO3166-2", exists: true)
}
.as("regions")
}
ForEach("regions") {
Convert(typeName: "Region") {
ConvertAsId()
ConvertAsTag("code", by: .tag("ISO3166-2"))
ConvertAsTag("wikidata", by: .tag("wikidata"))
}
Output()
}
Output(verbosity: .tags)
}
.map {
guard !$0.tags.wikidata.isEmpty else {
throw MetadataError.invalidTag(code: $0.tags.code, tag: "wikidata")
}
return .init(element: $0)
}
}
}
}
fileprivate struct RegionFilter {
let countires: Set<Region.Code>
let regions: Set<Region.Code>
init?(_ regions: Set<Region.Code>?) {
guard let regions else {
return nil
}
self.countires = regions.reduce(into: .init()) { result, item in
switch item {
case .country(_):
result.insert(item)
case .subdivision(let countryCode, _):
result.insert(.country(code: countryCode))
}
}
self.regions = regions
}
func filter(country: Region) -> Bool {
countires.contains(country.code)
}
func filter(region: Region) -> Bool {
regions.contains { $0.contains(region.code) }
}
}