generate_geo_jsons.py 2.92 KB
Newer Older
Pierre Dittgen's avatar
Pierre Dittgen committed
1
2
3
4
5
6
7
#!/usr/bin/env python3
"""
    Generates GeoJSON files
"""
import argparse
import io
import sqlite3
8
9
10
11
from pathlib import Path

import ujson as json

Pierre Dittgen's avatar
Pierre Dittgen committed
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
import metrics_common as mc

GEOJSON_HEADER = """
{
    "type": "FeatureCollection",
    "features": [
"""

GEOJSON_FOOTER = """
     ]
}
"""


def compute_description(row, met_cursor):
    """ Compute (sort of) wiki description """

    data = {
        'nom': row['nom'],
        'type': row['type'],
        'metrics': mc.compute_metrics_tree(row['siren'], met_cursor)
    }

    fd = io.StringIO()
    mc.write_md_content(data, fd, with_title=False, mode='geo')
    fd.seek(0)
    desc = fd.read()
    fd.close()
    return desc


def manage_geom(geo_string):
    """ return geometry data """
    # decode
    return json.loads(geo_string)


def output_feature(fd, row, metrics_cursor):
    """ Outputs feature information """

    props = {
        'name': row['nom'],
        'description': compute_description(row, metrics_cursor)
    }

    feature_data = {
        'id': row['siren'],
        'properties': props,
        'type': 'Feature',
        'geometry': manage_geom(row['coords']),
    }

64
    fd.write(json.dumps(feature_data, ensure_ascii=False, sort_keys=True, double_precision=2))
Pierre Dittgen's avatar
Pierre Dittgen committed
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


def generate_geojson_file(category, conn, geojson_filepath: Path):
    """ Generates GeoJSON files """
    metrics_cursor = conn.cursor()

    cursor = conn.cursor()
    type_constraints = "= '{}'".format(category) if category != 'EPCI' else "IN ('CA', 'CC', 'CU', 'MET', 'EPT')"
    sql_select = """SELECT * FROM orga_geometry
                      WHERE type {}
                         AND NOT coords IS NULL
                         AND coords != ''""".format(type_constraints)
    cursor.execute(sql_select)
    rows = cursor.fetchall()

    metrics_cursor = conn.cursor()

    with geojson_filepath.open(mode='wt', encoding='utf-8') as gj_fd:

        gj_fd.write(GEOJSON_HEADER)

        sep = ""
        for row in rows:
            gj_fd.write(sep)
            output_feature(gj_fd, row, metrics_cursor)
            sep = ",\n"

        gj_fd.write(GEOJSON_FOOTER)


def main():
    """ Generates Geo JSON file """
    parser = argparse.ArgumentParser()
    parser.add_argument('db_file', type=Path, help='SQLite database file')
    parser.add_argument('output_dir', type=Path, help='Where to generate GeoJSON files')
    args = parser.parse_args()

    if not args.db_file.is_file():
        parser.error('SQLite DB file [{}] not found'.format(str(args.db_file)))
    if not args.output_dir.is_dir():
        parser.error('GeoJSON output dir [{}] not found'.format(str(args.output_dir)))

    conn = sqlite3.connect(str(args.db_file))
    conn.row_factory = sqlite3.Row

    for cat in ('REG', 'DEP', 'COM', 'EPCI', 'AGCT', 'OACT', 'DSPT'):

        geojson_filepath = args.output_dir / 'odservatoire_{}.json'.format(cat.lower())
        generate_geojson_file(cat, conn, geojson_filepath)


if __name__ == '__main__':
    main()