forked from osm-fr/osmose-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Analyser_Merge.py
1661 lines (1468 loc) · 68.1 KB
/
Analyser_Merge.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/env python
#-*- coding: utf-8 -*-
###########################################################################
## ##
## Copyrights Frédéric Rodrigo 2012 ##
## ##
## This program is free software: you can redistribute it and/or modify ##
## it under the terms of the GNU General Public License as published by ##
## the Free Software Foundation, either version 3 of the License, or ##
## (at your option) any later version. ##
## ##
## This program is distributed in the hope that it will be useful, ##
## but WITHOUT ANY WARRANTY; without even the implied warranty of ##
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ##
## GNU General Public License for more details. ##
## ##
## You should have received a copy of the GNU General Public License ##
## along with this program. If not, see <http://www.gnu.org/licenses/>. ##
## ##
###########################################################################
import io
import bz2
import datetime
import gzip
import csv
import psycopg2.extras
import psycopg2.extensions
import os
import os.path
import time
import zipfile
import tempfile
import json
import re
import fnmatch
import shutil
import subprocess
import pathlib
from typing import Optional, Dict, Union, Callable
from collections import defaultdict
from .Analyser_Osmosis import Analyser_Osmosis
from modules.OsmoseTranslation import T_
from modules.Stablehash import stablehash64, hexastablehash
from modules import downloader
from modules import PointInPolygon
from modules import SourceVersion
from modules import DictCursorUnicode
from functools import reduce
try:
from pyproj import Transformer
except ImportError:
# No available in pyproj < 2.1
Transformer = None # type: ignore
GENERATE_DELETE_TAG = u"DELETE TAG aechohve0Eire4ooyeyaey1gieme0xoo"
# Checking existence of schema before CREATE SCHEMA is necessary on databases,
# like france_local_db, where user osmose doesn't have the rights to create a
# schema.
sql_schema = """
DO language 'plpgsql' $$
BEGIN
IF NOT EXISTS (SELECT * FROM information_schema.schemata WHERE schema_name = '{schema}' ) THEN
CREATE SCHEMA {schema};
END IF;
END $$
"""
sql00 = """
CREATE TEMP TABLE {official}_temp (
ref varchar(65534),
tags jsonb,
tags1 jsonb,
fields jsonb,
geom geometry(geometry, {proj})
)
"""
sql01_ref = """
SELECT
{distinct}
{geom} AS _geom,
*
FROM
"{table}"
WHERE
{where}
{order_by}
"""
sql01_geo = """
SELECT
{distinct}
{geom} AS _geom,
*
FROM
"{table}"
WHERE
({validationGeomSQL}) AND
{where}
{order_by}
"""
sql02 = """
INSERT INTO
{official}_temp
VALUES (
%(ref)s,
%(tags)s::jsonb,
%(tags1)s::jsonb,
%(fields)s::jsonb,
CASE WHEN {geom} IS NOT NULL THEN
ST_Transform(ST_Force2D({geom}), {proj})
ELSE NULL END
)
"""
sql02b = """
DROP TABLE IF EXISTS {official} CASCADE;
CREATE TABLE {official} AS
SELECT
ref,
tags,
tags1,
fields,
geom
FROM
{official}_temp
GROUP BY
ref,
tags,
tags1,
fields,
geom
"""
sql03a = """
CREATE INDEX ir_{official} ON {official}(ref)
"""
sql03b = """
CREATE INDEX ig_{official} ON {official} USING GIST(geom)
"""
sql10 = """
CREATE TEMP TABLE missing_official AS
SELECT
official.ref,
ST_AsText(ST_Transform(official.geom, 4326)),
official.tags,
official.fields,
official.geom
FROM
{official} AS official
LEFT JOIN osm_item ON
{joinClause}
WHERE
osm_item.id IS NULL
"""
sql11 = """
CREATE INDEX missing_official_index_ref ON missing_official(ref);
CREATE INDEX missing_official_index_geom ON missing_official USING GIST(geom);
"""
sql12 = """
SELECT * FROM missing_official;
"""
sql20 = """
CREATE TEMP TABLE missing_osm AS
SELECT
osm_item.id,
osm_item.type,
CASE
WHEN osm_item.geom IS NOT NULL THEN ST_AsText(ST_Transform(osm_item.geom, 4326))
ELSE ST_AsText(any_locate(osm_item.type, osm_item.id))
END,
osm_item.tags,
osm_item.geom,
osm_item.shape,
osm_item.ref
FROM
osm_item
LEFT JOIN {official} AS official ON
{joinClause}
WHERE
official.ref IS NULL
"""
sql21 = """
CREATE INDEX missing_osm_index_shape ON missing_osm USING GIST(shape)
"""
sql22 = """
SELECT DISTINCT ON(id, type)
*
FROM
missing_osm
ORDER BY
id, type
"""
sql30 = """
CREATE TEMP TABLE possible_merge AS
SELECT
DISTINCT ON (id)
missing_osm.id,
missing_osm.type,
CASE
WHEN missing_osm.geom IS NOT NULL THEN ST_AsText(ST_Transform(missing_osm.geom, 4326))
ELSE ST_AsText(any_locate(missing_osm.type, missing_osm.id))
END,
missing_official.tags AS official_tags,
missing_official.fields AS official_fields,
missing_osm.tags AS osm_tags
FROM
missing_official
JOIN missing_osm ON
{joinClause}
ORDER BY
missing_osm.id
{orderBy}
"""
sql31 = """
CREATE INDEX possible_merge_index_id_type ON possible_merge(id, type)
"""
sql32 = """
SELECT * FROM possible_merge
"""
sql40 = """
CREATE TEMP TABLE match AS
SELECT
osm_item.id,
osm_item.type,
official.tags || official.tags1 || osm_item.tags AS tags,
ST_Transform(osm_item.geom, 4326) AS geom
FROM
osm_item
JOIN {official} AS official ON
{joinClause}
"""
sql41 = """
(
SELECT
'osm+opendata' AS osmose,
id::bigint AS osm_id,
type::varchar AS osm_type,
tags::jsonb,
ST_X(ST_Transform(geom, 4326))::float AS lon,
ST_Y(ST_Transform(geom, 4326))::float AS lat
FROM
match
) UNION ALL (
SELECT
'opendata' AS osmose,
NULL::bigint AS osm_id,
NULL::varchar AS osm_type,
tags::jsonb,
ST_X(ST_Transform(geom, 4326))::float AS lon,
ST_Y(ST_Transform(geom, 4326))::float AS lat
FROM
missing_official
) UNION ALL (
SELECT
CASE
WHEN possible_merge.id IS NOT NULL THEN 'osm~opendata'
ELSE 'osm'
END AS osmose,
missing_osm.id::bigint AS osm_id,
missing_osm.type::varchar AS osm_type,
CASE
WHEN possible_merge.id IS NOT NULL THEN possible_merge.official_tags || possible_merge.osm_tags || missing_osm.tags
ELSE missing_osm.tags
END AS tags,
ST_X(ST_Transform(missing_osm.geom, 4326))::float AS lon,
ST_Y(ST_Transform(missing_osm.geom, 4326))::float AS lat
FROM
missing_osm
LEFT JOIN possible_merge ON
possible_merge.id = missing_osm.id AND
possible_merge.type = missing_osm.type
ORDER BY
possible_merge.id IS NULL
)
"""
sql50 = """
SELECT
osm_item.id,
ST_AsText(ST_Transform(osm_item.geom, 4326)),
ST_AsText(ST_Transform(official.geom, 4326))
FROM
{official} AS official
JOIN osm_item ON
{joinClause} AND
NOT official.geom && osm_item.geom
"""
sql60 = """
SELECT
osm_item.id,
osm_item.type,
ST_AsText(ST_Transform(osm_item.geom, 4326)),
official.tags,
osm_item.tags,
official.fields AS official_fields
FROM
{official} AS official
JOIN osm_item ON
{joinClause}
WHERE
official.tags1
-- Remove tags already existing in OSM, except tags to delete
- (SELECT coalesce(array_agg(key), array[]::text[]) FROM jsonb_object_keys(osm_item.tags) AS t(key) WHERE official.tags1->>key != '""" + GENERATE_DELETE_TAG + """')
-- Remove tags to delete not existing in OSM
- (SELECT coalesce(array_agg(key), array[]::text[]) FROM jsonb_each(official.tags1) WHERE value->>0 = '""" + GENERATE_DELETE_TAG + """' AND NOT osm_item.tags?key)
- 'source'::text
!= '{{}}'::jsonb
"""
class Source:
def __init__(self, attribution = None, millesime = None, encoding = "utf-8", file = None, fileUrl = None, post: Optional[Dict[str, str]] = None, fileUrlCache = 30, zip = None, extract = None, bz2 = False, gzip = False, filter = None):
"""
Describe the source file.
@param attribution: Author of the data, for the OSM source tag
@param millesime: date of the last release
@param encoding: file charset encoding
@param file: file name in storage
@param urlFile: remote URL of source file
@param fileUrlCache: days for file in cache
@param post: post key-value to the URL to get the file to download
@param zip: extract a file from zip. Unix filename pattern matching.
@param extract: extract file from any archive format
@param gzip: uncompress from bz2
@param gzip: uncompress from gzip
@param filter: lambda expression applied on text file before loading
"""
self.attribution = attribution
self.millesime = millesime
self.encoding = encoding
self.file = file
self.fileUrl = fileUrl
self.post = post
self.fileUrlCache = fileUrlCache
self.zip = zip
self.extract = extract
self.bz2 = bz2
self.gzip = gzip
self.filter = filter
if self.file and self.fileUrl:
raise ValueError("file and fileUrl should not be both set")
if self.file:
if not os.path.isabs(self.file):
self.file = "merge_data/" + self.file
if self.attribution and "{0}" in self.attribution:
self.attribution_re = re.compile(self.attribution.replace("{0}", ".*"))
def zipFile(self):
if not self.zip:
return None
if self.file:
f = open(self.file, 'rb')
elif self.fileUrl:
f = downloader.urlopen(self.fileUrl, self.fileUrlCache, mode='rb', post=self.post)
z = zipfile.ZipFile(f, 'r')
print(z.namelist())
filename = next(filter(lambda zipinfo: fnmatch.fnmatch(zipinfo.filename, self.zip), z.infolist()))
return filename
def time(self):
if self.file:
return int(os.path.getmtime(self.file)+.5)
elif self.fileUrl:
if self.zipFile():
date_time = self.zipFile().date_time
return int(time.mktime(date_time + (0, 0, -1))+.5)
else:
return int(downloader.urlmtime(self.fileUrl, self.fileUrlCache, self.post)+.5)
def path(self):
if self.file:
return self.file
elif self.fileUrl:
# Do nothing about ZIP
return downloader.path(self.fileUrl, self.fileUrlCache, post=self.post)
def open(self, binary = False):
if self.file:
f = open(self.file, 'rb')
elif self.fileUrl:
f = downloader.urlopen(self.fileUrl, self.fileUrlCache, mode='rb', post=self.post)
if self.zipFile():
z = zipfile.ZipFile(f, 'r').open(self.zipFile().filename)
f = io.BytesIO(z.read())
f.seek(0)
elif self.extract:
import libarchive.public # type: ignore
with libarchive.public.memory_reader(f.read()) as archive:
f = io.BytesIO()
for entry in archive:
if pathlib.Path(entry.pathname).match(self.extract):
for block in entry.get_blocks():
f.write(block)
break
f.seek(0)
elif self.bz2:
f = io.BytesIO(bz2.decompress(f.read()))
f.seek(0)
elif self.gzip:
f = gzip.GzipFile(fileobj=f)
if not binary:
f = io.StringIO(f.read().decode(self.encoding, 'ignore'))
f.seek(0)
if self.filter:
f = io.StringIO(self.filter(f.read()))
f.seek(0)
return f
def _get_millesime(self) -> Optional[str]:
if not self.millesime and self.fileUrl:
cached_millesime = downloader.get_millesime(self.fileUrl, self.fileUrlCache, self.post)
if cached_millesime:
self.millesime = cached_millesime
else:
self.millesime = self.get_millesime()
downloader.set_millesime(self.fileUrl, self.millesime)
if self.millesime is None or type(self.millesime) is str:
return self.millesime
return self.millesime.strftime("%Y-%m")
def get_millesime(self) -> Optional[datetime.datetime]:
"""To be overwritten by sources with dynamic millesime"""
return None
def as_tag_value(self):
if "{0}" in self.attribution:
return self.attribution.format(self._get_millesime())
else:
return " - ".join(filter(lambda x: x is not None, [self.attribution, self._get_millesime()]))
def match_attribution(self, s):
if "{0}" not in self.attribution:
return self.attribution in s
else:
return self.attribution_re.match(s)
class SourceDataGouv(Source):
def __init__(self, dataset: str, resource: str, data_gouv_api_base: str = "https://www.data.gouv.fr/api/1", data_gouv_dataset_base: str = "https://www.data.gouv.fr/fr/datasets/r/", **kwargs):
self.dataset = dataset
self.resource = resource
self.data_gouv_api_base = data_gouv_api_base
kwargs.update({
"fileUrl": data_gouv_dataset_base + resource,
"millesime": None,
})
super().__init__(**kwargs)
def get_millesime(self) -> datetime.datetime:
response = downloader.request_get(f"{self.data_gouv_api_base}/datasets/{self.dataset}/resources/{self.resource}/")
response.raise_for_status()
return datetime.datetime.fromisoformat(response.json()["last_modified"])
class SourcePublicLu(SourceDataGouv):
def __init__(self, dataset: str, resource: str, **kwargs):
super().__init__(dataset, resource, data_gouv_api_base="https://data.public.lu/api/1", data_gouv_dataset_base="https://data.public.lu/fr/datasets/r/", **kwargs)
class SourceOpenDataSoft(Source):
url_re = re.compile(r"(https?://.+)/explore/dataset/([^/?#]+)")
def __init__(self,
url: str,
format: str = "csv",
**kwargs):
url_match = self.url_re.match(url)
if url_match is None:
raise ValueError(f"Invalid url: {url}")
self.base_url, self.dataset = url_match.groups()
kwargs.update({
"fileUrl": f"{self.base_url}/explore/dataset/{self.dataset}/download/?format={format}&csv_separator=,&use_labels_for_header=true",
"millesime": None,
})
super().__init__(**kwargs)
def get_millesime(self) -> datetime.datetime:
response = downloader.request_get(f"{self.base_url}/api/datasets/1.0/{self.dataset}")
response.raise_for_status()
return datetime.datetime.fromisoformat(response.json()["metas"]["data_processed"])
class SourceDataFair(Source):
def __init__(self,
url: str,
file_name: str,
format: str = "csv",
**kwargs):
self.url_base = url.replace("/datasets/", "/data-fair/api/v1/datasets/")
self.file_name = file_name
kwargs.update({
"fileUrl": self.url_base + "/data-files/" + file_name,
"millesime": None,
})
super().__init__(**kwargs)
def get_millesime(self) -> datetime.datetime:
response = downloader.request_get(self.url_base + "/data-files")
response.raise_for_status()
return datetime.datetime.fromisoformat(next(filter(lambda f: f["name"] == self.file_name, response.json()))["updatedAt"][0:10])
class SourceHttpLastModified(Source):
"""Get URL from Last-Modified HTTP headers"""
def get_millesime(self):
return datetime.datetime.strptime(
downloader.requests_retry_session().head(self.fileUrl).headers['Last-Modified'],
downloader.HTTP_DATE_FMT,
)
class SourceIGN(Source):
def __init__(self, dep_code, **kwargs):
response = downloader.request_get("https://geoservices.ign.fr/bdtopo")
response.raise_for_status()
if len(str(dep_code)) == 2:
dep_code = f"0{dep_code}"
match = re.search(
fr"https://data.geopf.fr/telechargement/download/BDTOPO/BDTOPO_3-3_TOUSTHEMES_GPKG_[A-Z0-9]+_D{dep_code}_[-0-9]+/BDTOPO_3-3_TOUSTHEMES_GPKG_[A-Z0-9]+_D{dep_code}_([-0-9]+).7z",
response.text
)
url, date = match[0], match[1]
kwargs.update({
"fileUrl": url,
"millesime": date,
"extract": "**/*.gpkg",
"attribution": "IGN",
})
super().__init__(**kwargs)
class Parser:
def __init__(self, srid: Optional[int] = None, source = None):
"""
@param srid: overwrite the projection of geometry, by default projection comes from parsed content, or if no fallback to 4326.
@param source: source file reader
"""
self._srid = srid
self.source = source
def header(self):
pass
def import_(self, table, osmosis):
pass
def close(self):
pass
def source_srid(self):
return self._srid or 4326
def imported_srid(self):
return self.source_srid()
class CSV(Parser):
def __init__(self, source, separator = ',', null = '', header = True, quote = '"', csv = True, skip_first_lines = 0, fields = None, srid: Optional[int] = None):
"""
Describe the CSV file format, mainly for postgres COPY command in order to load data, but also for other thing, like load header.
Setting param as None disable parameter into the COPY command.
@param source: source file reader
@param separator: one char separator
@param null: string loaded à NULL
@param header: CSV have header row
@param quote: one char string delimiter
@param csv: load file as CSV on COPY command
@param skip_first_lines: skip lines before reading CSV content
@param fields: array of fields to load. Default to All. Usefull for big dataset.
"""
super().__init__(srid = srid, source = source)
self.separator = separator
self.null = null
self.have_header = header
self.quote = quote
self.csv = csv
self.skip_first_lines = skip_first_lines
self.fields = fields
self.f = None
def header(self):
self.f = self.source.open()
for _ in range(self.skip_first_lines):
self.f.__next__()
if self.have_header:
return next(csv.reader(self.f, delimiter=self.separator, quotechar=self.quote))
def import_(self, table, osmosis):
self.f = self.f or self.source.open()
for _ in range(self.skip_first_lines):
self.f.__next__()
copy = "COPY {0} FROM STDIN WITH {1} {2} {3} {4} {5}".format(
table,
("DELIMITER AS '{0}'".format(self.separator)) if self.separator is not None else "",
("NULL AS '{0}'".format(self.null)) if self.null is not None else "",
"CSV" if self.csv else "",
"HEADER" if self.csv and self.header else "",
("QUOTE '{0}'".format(self.quote)) if self.csv and self.quote else "")
osmosis.giscurs.copy_expert(copy, self.f)
if self.fields:
osmosis.run0("CREATE TABLE {0}_fields AS SELECT {1} FROM {0}".format(
table,
', '.join(map(lambda field: '"' + field + '"', self.fields)))
)
osmosis.run0("DROP TABLE {0}".format(table))
osmosis.run0("ALTER TABLE {0}_fields RENAME TO {0}".format(table))
def close(self):
self.f.close()
class GTFS(CSV):
def __init__(self, source):
"""
Load GTFS file data.
@param source: source file reader
"""
super().__init__(source, srid = 4326)
source.zip = "stops.txt"
CSV.__init__(self, source)
def flattenjson(b):
"""
Converts multi-level JSON properties into single level
Columns names are separated by a "."
Based on Alec McGail implementation, see https://stackoverflow.com/a/28246154
@param b: source JSON object
@return flattened JSON object
"""
val = {}
for i in b.keys():
if isinstance( b[i], dict ):
get = flattenjson(b[i])
for j in get.keys():
val[ i + "." + j ] = get[j]
elif isinstance( b[i], list):
val[i] = "[" + ",".join(map(str, b[i])) + "]"
else:
val[i] = b[i]
return val
def removequotesjson(s):
"""
Removes trailing and leading char " if any in given string
@param s : source string
@return same string without trailing/leading " char
"""
try:
return s.strip('"')
except AttributeError:
return s
class JSON(Parser):
def __init__(self, source, extractor = lambda json: json, srid: Optional[int] = None):
"""
Load JSON file data.
@param source: source file reader
@param extractor: lambda returning an interable
"""
super().__init__(srid = srid, source = source)
self.extractor = extractor
self.json = None
def header(self):
self.json = list(map(flattenjson, self.extractor(json.loads(self.source.open().read()))))
columns = set()
# Read all entries because structure can vary
for feature in self.json:
columns = columns.union(list(flattenjson(feature).keys()))
columns = list(columns)
return columns
def import_(self, table, osmosis):
self.json = self.json or map(flattenjson, self.extractor(json.loads(self.source.open().read())))
for row in self.json:
osmosis.giscurs.execute("insert into \"{0}\" (\"{1}\") values ({2})".format(
table, '", "'.join(row.keys()), (u'%s, ' * len(row.keys()))[:-2]),
list(map(removequotesjson, row.values())))
class GeoJSON(Parser):
def __init__(self, source, extractor = lambda json: json):
"""
Load GeoJSON file data.
@param source: source file reader
@param extractor: lambda returning an interable
"""
super().__init__(srid = 4326, source = source)
self.extractor = extractor
self.json = self.extractor(json.loads(self.source.open().read()))
try:
self._srid = int(self.json['crs']['properties']['name'].split(':')[1])
except:
pass
def header(self):
columns = set()
# Read all entries because structure can vary
for feature in self.json['features']:
columns = columns.union(list(flattenjson(feature['properties']).keys()))
columns = list(columns)
columns.append(u"geom_x")
columns.append(u"geom_y")
return columns
def import_(self, table, osmosis):
for row in self.json['features']:
if row['geometry'] and row['geometry']['coordinates'] and len(row['geometry']['coordinates']) > 0:
row['properties'] = flattenjson(row['properties'])
columns = list(row['properties'].keys())
values = list(map(removequotesjson, map(lambda column: row['properties'][column], columns)))
columns.append(u"geom_x")
columns.append(u"geom_y")
if row['geometry']['type'] in ('Point', 'MultiPoint', 'LineString', 'MultiLineString'):
if row['geometry']['type'] == 'Point':
values.append(row['geometry']['coordinates'][0])
values.append(row['geometry']['coordinates'][1])
elif row['geometry']['type'] in ('MultiPoint', 'LineString'):
npt = len(row['geometry']['coordinates'])//2
values.append(row['geometry']['coordinates'][npt][0])
values.append(row['geometry']['coordinates'][npt][1])
else:
npt = len(row['geometry']['coordinates'][0])//2
values.append(row['geometry']['coordinates'][0][npt][0])
values.append(row['geometry']['coordinates'][0][npt][1])
osmosis.giscurs.execute(u"insert into \"{0}\" (\"{1}\") values ({2})".format(
table, u'", "'.join(columns), (u'%s, ' * len(columns))[:-2]),
values)
class GDAL(Parser):
def __init__(self, source, zip = None, layer = None, fields = None, srid: Optional[int] = None):
"""
Load any GDAL supported format.
@param source: source file reader
@param zip: use path in zip file.
@param layer: layer to use when source is multi-layer.
@param fields: array of fields to load. Default to All. Usefull for big dataset.
"""
super().__init__(srid = srid, source = source)
self.zip = zip
self.layer = layer
self.fields = fields
def __del__(self):
try:
os.remove(self.tmp_file.name)
except:
pass
def header(self):
return True
def import_(self, table, osmosis):
try:
self.tmp_file = tempfile.NamedTemporaryFile(suffix = '.zip' if self.zip else '', mode = 'wb', delete = False)
shutil.copyfileobj(self.source.open(binary = True), self.tmp_file, 20*1024*1024)
self.tmp_file.close()
if self.zip:
# Resolve pattern filename into the zip archive.
z = zipfile.ZipFile(self.tmp_file.name, 'r')
info = next(filter(lambda zipinfo: fnmatch.fnmatch(zipinfo.filename, self.zip), z.infolist()))
if info:
self.zip = info.filename
self.source_layer = [
('/vsizip/' if self.zip else '' ) + self.tmp_file.name + (('/' + self.zip) if self.zip else ''),
]
if self.layer:
self.source_layer.append(f"'{self.layer}'")
if not self._srid:
projjson = json.loads(subprocess.run(["gdalsrsinfo", "-e", "-o", "PROJJSON", self.source_layer[0]], stdout=subprocess.PIPE).stdout.decode('utf-8'))
if not projjson and len(self.source_layer) >= 2:
projjson = json.loads(subprocess.run(["gdalsrsinfo", "-e", "-o", "PROJJSON", *self.source_layer], stdout=subprocess.PIPE).stdout.decode('utf-8'))
if projjson['id']['authority'] == 'EPSG':
self._srid = int(projjson['id']['code'])
elif projjson['id']['authority'] == 'IGNF' and projjson['id']['code'] == 'LAMB93':
self._srid = 2154
except Exception as e:
os.remove(self.tmp_file.name)
raise e
wkt = PointInPolygon.PointInPolygon(self.polygon_id).polygon.as_simplified_wkt(self.source_srid(), self.proj) if self.polygon_id else None
select = "-select '{}'".format(','.join(self.fields)) if self.fields else ''
gdal = "ogr2ogr -f PostgreSQL 'PG:{}' -lco SCHEMA={} -nln '{}' {} -nlt PROMOTE_TO_MULTI -lco OVERWRITE=yes -lco GEOMETRY_NAME=geom -lco OVERWRITE=YES -lco LAUNDER=NO -skipfailures {} -s_srs EPSG:{} -t_srs EPSG:{} '{}' {}".format(
osmosis.config.osmosis_manager.db_string,
osmosis.config.osmosis_manager.db_user,
table,
f"-clipsrc '{wkt}'" if wkt else '',
select,
self.source_srid(),
self.proj,
self.source_layer[0],
self.source_layer[1] if len(self.source_layer) >= 2 else '',
)
print(gdal)
if os.system(gdal):
raise Exception("ogr2ogr error")
def imported_srid(self):
return self.proj
SHP = GDAL
GPKG = GDAL
class Load(object):
def __init__(self, geom = ("NULL",), table_name = None, create = None,
select = {}, unique = None, where = lambda res: True, map = lambda i: i, geomFunction = lambda i: i, validationGeomSQL = "1=1"):
"""
Describ the conversion of data set loaded with COPY into the database into an other table more usable for processing.
@param geom: the name of geom column, can be a SQL expression formatted as ("SQL CODE",)
@param table_name: override the default table name
@param create: the data base table description, generated by default from file header et format
@param select: dict reformatted as SQL to filter row import before conversion, prefer this as the where parameter
@param unique: keep only one distinct record by list of column
@param where: lambda expression taking row as dict and returning boolean to determine whether or not inserting the row into the table
@param map: lambda returning adict from adict to replace the record
@param geomFunction: lambda expression for convert geom content column before reprojection, identity by default
@param validationGeomSQL: SQL where clause to pre-validate geometry
"""
self.geom = geom
self.table_name = table_name
self.create = create
self.select = select
self.unique = unique
self.where = where
self.map = map
self.geomFunction = geomFunction
self.validationGeomSQL = validationGeomSQL
def spatialGeom(self, geom):
"""
SQL to get the geometry
"""
return f"ST_GeomFromEWKT('{geom}')"
def run(self, osmosis, conflate, db_schema, default_table_base_name, version):
"""
@return if data loaded in data base
"""
table_base_name = self.table_name or default_table_base_name
table = DictCursorUnicode.identifier(table_base_name)
osmosis.run("CREATE TABLE IF NOT EXISTS meta (name character varying(255) NOT NULL, update integer, bbox character varying(1024) )")
# Official data table cache
country_hash = osmosis.config.db_schema.split('_')[-1][0:10] + hexastablehash(osmosis.config.db_schema)[-4:]
if len(default_table_base_name + '_' + country_hash) <= 63-2-3: # 63 max postgres relation name, 3 is index name prefix
tableOfficial = default_table_base_name + '_' + country_hash + "_o"
else:
tableOfficial = (default_table_base_name + '_' + country_hash)[-(63-2-3-4):] + '_o' + hexastablehash(default_table_base_name)[-4:]
self.data = False
def setData(res):
self.data = res
osmosis.run0("SELECT bbox FROM meta WHERE name='{0}' AND bbox IS NOT NULL AND update IS NOT NULL AND update={1}".format(tableOfficial, version), lambda res: setData(res))
if not self.data:
osmosis.logger.log("Load raw data into database")
if not self.create:
header = self.parser.header()
if header:
if header is not True:
header_without_duplicate = []
for i, v in enumerate(header):
totalcount = header.count(v)
count = header[:i].count(v)
header_without_duplicate.append(v + str(count + 1) if totalcount > 1 and count > 0 else v)
self.create = ",".join(map(lambda c: "\"{0}\" VARCHAR".format(DictCursorUnicode.identifier(c)), header_without_duplicate))
else:
raise AssertionError("No table schema provided")
# Create schema if not exists and ensure is flushed before running import internaly or with external tools
osmosis.run(sql_schema.format(schema = db_schema))
osmosis.giscurs.execute("COMMIT")
osmosis.giscurs.execute("BEGIN")
if self.create:
osmosis.run("CREATE TEMP TABLE \"{0}\" ({1})".format(table, self.create))
self.parser.import_(table, osmosis)
self.parser.close()
# Convert
osmosis.logger.log("Convert raw data to tags")
osmosis.run(sql_schema.format(schema = db_schema))
osmosis.run(sql00.format(official = tableOfficial, proj = self.proj))
giscurs = osmosis.gisconn.cursor(cursor_factory=psycopg2.extras.DictCursor)
mult_space = re.compile(r'\s+')
def insertOfficial(res):
if not self.where(res):
return
res = self.map(res)
geom = self.geomFunction(res['_geom'])
res = {k: v for k, v in res.items() if k not in ['_geom', 'geom', 'geometry']}
if geom and geom[0] and geom[1]:
for k in res.keys():
try:
res[k] = mult_space.sub(' ', res[k].strip()) # Strip and remove duplicate space
except AttributeError:
pass
tags = conflate.mapping.tagFactory(res)
tags[1].update(tags[0])
giscurs.execute(sql02.format(official = tableOfficial, proj = self.proj, geom = self.spatialGeom(geom)), {
"ref": tags[1].get(conflate.osmRef) if conflate.osmRef != "NULL" else None,
"tags": tags[1],
"tags1": tags[0],
"fields": dict(zip(dict(res).keys(), map(lambda s: (s is None and None) or u'{0}'.format(s), dict(res).values()))),
})
if isinstance(self.geom, tuple):
self.geom = self.geom[0]
else:
self.geom = "ST_AsEWKT(\"{0}\")".format(self.geom)
if self.unique:
l = ','.join(map(lambda v: '"{0}"'.format(v), self.unique))
distinct = "DISTINCT ON ({0})".format(l)
order_by = "ORDER BY {0}".format(l)
else:
distinct = order_by = ""
osmosis.run0((sql01_ref if conflate.osmRef != "NULL" else sql01_geo).format(table = table, geom = self.geom, validationGeomSQL = self.validationGeomSQL, where = Select.where_attributes(self.select), distinct = distinct, order_by = order_by), insertOfficial)
osmosis.run(sql02b.format(official = tableOfficial))
if self.parser.imported_srid():
giscurs.execute("SELECT ST_AsText(ST_Transform(ST_Envelope(ST_SetSRID(ST_Extent(ST_Transform(ST_Expand(geom, {distance}), 4326)), 4326)), {proj})) FROM {table}".format(
table = tableOfficial,
proj = self.proj,
distance = conflate.conflationDistance or 0))
self.bbox = giscurs.fetchone()[0]
else:
self.bbox = None
osmosis.run(sql03a.format(official = tableOfficial))
osmosis.run(sql03b.format(official = tableOfficial))
giscurs.close()
osmosis.run("DELETE FROM meta WHERE name='{0}'".format(tableOfficial))
if self.bbox is not None:
osmosis.run("INSERT INTO meta VALUES ('{0}', {1}, '{2}')".format(tableOfficial, version, self.bbox))
osmosis.run("DROP TABLE \"{0}\"".format(table))
osmosis.run0("COMMIT")
osmosis.run0("BEGIN")
else:
self.bbox = self.data[0]
if not (self.parser.imported_srid() and not self.bbox): # Abort condition
return tableOfficial
@staticmethod
def float_comma(val):
"""Convert decimal comma separeted to dot."""
if val is not None:
return float(val.replace(',', '.'))
@staticmethod
def degree(val):
"""Convert coordinate in degree, minute, second to decimal degrees."""
if val is not None and u'°' in val:
# 01°13'23,8 -> 1,334388
return reduce(lambda sum, i: sum * 60 + i, map(lambda i: float(i.replace(u',', u'.')), filter(lambda i: i != '', val.replace(u'°', u"'").split(u"'"))), 0) / 3600
else:
return val
class Load_XY(Load):
pip = None
def __init__(self, x = ("NULL",), y = ("NULL",), table_name = None, create = None,
select = {}, unique = None, where = lambda res: True, map = lambda i: i, xFunction = lambda i: i, yFunction = lambda i: i):
"""
Describ the conversion of data set loaded with COPY into the database into an other table more usable for processing.
@param x: the name of x column, as or converted to longitude, can be a SQL expression formatted as ("SQL CODE",)
@param y: the name of y column, as or converted to latitude, can be a SQL expression formatted as ("SQL CODE",)
@param table_name: override the default table name
@param create: the data base table description, generated by default from file header et format
@param select: dict reformatted as SQL to filter row import before conversion, prefer this as the where parameter
@param unique: keep only one distinct record by list of column