Blame view

flaskr/controllers/main_controller.py 34.4 KB
3bb89452   Antoine Goutenoir   feat: add a world...
1
2
import csv
import re
80fd4654   Antoine Goutenoir   feat: improve err...
3
# from cStringIO import StringIO
b935618e   Antoine Goutenoir   Count the number ...
4
from copy import deepcopy
80fd4654   Antoine Goutenoir   feat: improve err...
5
6
from io import StringIO
from os import unlink, getenv
3bb89452   Antoine Goutenoir   feat: add a world...
7
from os.path import join
b935618e   Antoine Goutenoir   Count the number ...
8

7f5397c6   Antoine Goutenoir   fix: don't crash ...
9
import chardet
314c65e2   Antoine Goutenoir   Implement Scenari...
10
import geopy
3bb89452   Antoine Goutenoir   feat: add a world...
11
import pandas
314c65e2   Antoine Goutenoir   Implement Scenari...
12
import sqlalchemy
e2637443   Antoine Goutenoir   Send emails to ad...
13
14
15
16
from flask import (
    Blueprint,
    Response,
    render_template,
80fd4654   Antoine Goutenoir   feat: improve err...
17
    request,
e2637443   Antoine Goutenoir   Send emails to ad...
18
    flash,
e2637443   Antoine Goutenoir   Send emails to ad...
19
20
21
22
23
    redirect,
    url_for,
    abort,
    send_from_directory,
)
515628a0   Antoine Goutenoir   fix: remove dep o...
24
# from pandas.compat import StringIO as PandasStringIO
3bb89452   Antoine Goutenoir   feat: add a world...
25
26
from wtforms import validators
from yaml import safe_dump as yaml_dump
7b4d2926   Goutte   Rework the contro...
27

3bb89452   Antoine Goutenoir   feat: add a world...
28
from flaskr.content import content, base_url
e2637443   Antoine Goutenoir   Send emails to ad...
29
from flaskr.core import (
e2637443   Antoine Goutenoir   Send emails to ad...
30
31
32
    get_emission_models,
    increment_hit_counter,
)
ec076c05   Antoine Goutenoir   fix: disable cache
33
from flaskr.extensions import send_email
3bb89452   Antoine Goutenoir   feat: add a world...
34
35
36
from flaskr.forms import EstimateForm
from flaskr.geocoder import CachedGeocoder
from flaskr.models import db, Estimation, StatusEnum, ScenarioEnum
9e44bb98   Antoine Goutenoir   Support file uplo...
37

7b4d2926   Goutte   Rework the contro...
38
39
40
main = Blueprint('main', __name__)


2ac05e0c   Antoine Goutenoir   feat: rely on ful...
41
#OUT_ENCODING = 'utf-8'
9621b8a5   Antoine Goutenoir   Fix the CSV gener...
42
43


67f85bce   Antoine Goutenoir   Generate a CSV fi...
44
# -----------------------------------------------------------------------------
e2637443   Antoine Goutenoir   Send emails to ad...
45

6318fdba   Antoine Goutenoir   Change PI email.
46
pi_email = "didier.barret@gmail.com"  # todo: move to content YAML or .env
3e6505e2   Antoine Goutenoir   Add content to th...
47
# pi_email = "goutte@protonmail.com"
e2637443   Antoine Goutenoir   Send emails to ad...
48

78eb2a62   Antoine Goutenoir   Use the counter.
49
# -----------------------------------------------------------------------------
67f85bce   Antoine Goutenoir   Generate a CSV fi...
50
51


461850db   Antoine Goutenoir   Yet another joyfu...
52
@main.route('/favicon.ico')
ec076c05   Antoine Goutenoir   fix: disable cache
53
# @cache.cached(timeout=10000)
461850db   Antoine Goutenoir   Yet another joyfu...
54
55
56
57
58
59
60
def favicon():  # we want it served from the root, not from static/
    return send_from_directory(
        join(main.root_path, '..', 'static', 'img'),
        'favicon.ico', mimetype='image/vnd.microsoft.icon'
    )


7b4d2926   Goutte   Rework the contro...
61
@main.route('/')
b0ffb1ba   Antoine Goutenoir   Review actively.
62
63
@main.route('/home')
@main.route('/home.html')
38375935   Antoine Goutenoir   Remove the cache ...
64
# @cache.cached(timeout=1000)
7b4d2926   Goutte   Rework the contro...
65
def home():
4c862b54   Antoine Goutenoir   Add a grouped bar...
66
    models = get_emission_models()
a3e9d0fc   Antoine Goutenoir   Fix home plot leg...
67
68
69
    models_dict = {}
    for model in models:
        models_dict[model.slug] = model.__dict__
78eb2a62   Antoine Goutenoir   Use the counter.
70
    increment_hit_counter()
4c862b54   Antoine Goutenoir   Add a grouped bar...
71
72
    return render_template(
        'home.html',
a3e9d0fc   Antoine Goutenoir   Fix home plot leg...
73
        models=models_dict,
4c862b54   Antoine Goutenoir   Add a grouped bar...
74
        colors=[model.color for model in models],
a3e9d0fc   Antoine Goutenoir   Fix home plot leg...
75
        labels=[model.name for model in models],
4c862b54   Antoine Goutenoir   Add a grouped bar...
76
    )
7b4d2926   Goutte   Rework the contro...
77
78


9e44bb98   Antoine Goutenoir   Support file uplo...
79
def gather_addresses(from_list, from_file):
04d423cb   Antoine Goutenoir   Limit the amount ...
80
81
82
83
    """
    Gather a list of addresses from the provided list and file.
    If the file is provided the list is ignored.
    """
9e44bb98   Antoine Goutenoir   Support file uplo...
84
85
86
    addresses = []
    if from_file:
        file_mimetype = from_file.mimetype
7f5397c6   Antoine Goutenoir   fix: don't crash ...
87
88
89
90
91
92
93
94
        file_contents_raw = from_file.read()
        detected = chardet.detect(file_contents_raw)
        if detected['encoding']:
            file_contents = file_contents_raw.decode(
                encoding=detected['encoding']
            )
        else:
            file_contents = file_contents_raw.decode()
9e44bb98   Antoine Goutenoir   Support file uplo...
95
96
97
98

        rows_dicts = None

        if 'text/csv' == file_mimetype:
b777efad   Antoine Goutenoir   fix: allow CSV de...
99
100
101
            delimiter = ','
            if ';' in file_contents:
                delimiter = ';'
9e44bb98   Antoine Goutenoir   Support file uplo...
102
            rows_dicts = pandas \
b777efad   Antoine Goutenoir   fix: allow CSV de...
103
                .read_csv(StringIO(file_contents), delimiter=delimiter) \
9e44bb98   Antoine Goutenoir   Support file uplo...
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
                .rename(str.lower, axis='columns') \
                .to_dict(orient="row")

        # Here are just *some* of the mimetypes that Microsoft's
        # garbage spreadsheet files may have.
        # application/vnd.ms-excel (official)
        # application/msexcel
        # application/x-msexcel
        # application/x-ms-excel
        # application/x-excel
        # application/x-dos_ms_excel
        # application/xls
        # application/x-xls
        # application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
        # ... Let's check extension instead.

        elif from_file.filename.endswith('xls') \
                or from_file.filename.endswith('xlsx'):

            rows_dicts = pandas \
515628a0   Antoine Goutenoir   fix: remove dep o...
124
                .read_excel(StringIO(file_contents)) \
9e44bb98   Antoine Goutenoir   Support file uplo...
125
126
127
128
129
                .rename(str.lower, axis='columns') \
                .to_dict(orient="row")

        # Python 3.7 only
        # elif from_file.filename.endswith('ods'):
9e44bb98   Antoine Goutenoir   Support file uplo...
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
        #     rows_dicts = read_ods(PandasStringIO(file_contents), 1) \
        #         .rename(str.lower, axis='columns') \
        #         .to_dict(orient="row")

        if rows_dicts is not None:
            for row_dict in rows_dicts:
                if 'address' in row_dict:
                    addresses.append(row_dict['address'])
                    continue
                address = None
                if 'city' in row_dict:
                    address = row_dict['city']
                if 'country' in row_dict:
                    if address is None:
                        address = row_dict['country']
                    else:
                        address += "," + row_dict['country']
                if address is not None:
                    addresses.append(address)
                else:
f2fbbb72   Antoine Goutenoir   Display a nice er...
150
151
152
                    raise validators.ValidationError(
                        "We could not find Address data in the spreadsheet."
                    )
9e44bb98   Antoine Goutenoir   Support file uplo...
153
        else:
f2fbbb72   Antoine Goutenoir   Display a nice er...
154
155
156
            raise validators.ValidationError(
                "We could not find any data in the spreadsheet."
            )
9e44bb98   Antoine Goutenoir   Support file uplo...
157
158
159
160

    else:
        addresses = from_list.replace("\r", '').split("\n")

68da7cd4   Antoine Goutenoir   Improve robustnes...
161
    clean_addresses = []
88c95474   Antoine Goutenoir   Improve perfs of ...
162
163
    # Ignore inevitable copy/paste bloopers
    to_ignore = re.compile(r"City\s*,\s*Country", re.I & re.U)
68da7cd4   Antoine Goutenoir   Improve robustnes...
164
165
166
    for address in addresses:
        if not address:
            continue
f0903e16   Antoine Goutenoir   chore: move to py...
167
168
169
        # if type(address).__name__ == 'str':
        #     address = str(address).encode('utf-8')
        address = str(address)
88c95474   Antoine Goutenoir   Improve perfs of ...
170
171
        if to_ignore.match(address) is not None:
            continue
8ba63c8d   Antoine Goutenoir   Ignore "City,Coun...
172
        clean_addresses.append(address)
68da7cd4   Antoine Goutenoir   Improve robustnes...
173
174
175
176
    addresses = clean_addresses

    # Remove empty lines (if any) and white characters
    addresses = [a.strip() for a in addresses if a]
8ec0ce68   Antoine Goutenoir   Improve robustnes...
177

9e44bb98   Antoine Goutenoir   Support file uplo...
178
179
180
    return "\n".join(addresses)


7b4d2926   Goutte   Rework the contro...
181
@main.route("/estimate", methods=["GET", "POST"])
b0ffb1ba   Antoine Goutenoir   Review actively.
182
@main.route("/estimate.html", methods=["GET", "POST"])
e2637443   Antoine Goutenoir   Send emails to ad...
183
def estimate():  # register new estimation request, more accurately
04d423cb   Antoine Goutenoir   Limit the amount ...
184
    maximum_travels_to_compute = 1000000
77e86148   Antoine Goutenoir   Fake support for ...
185
    models = get_emission_models()
7b4d2926   Goutte   Rework the contro...
186
187
    form = EstimateForm()

f2fbbb72   Antoine Goutenoir   Display a nice er...
188
    def show_form():
a7e8b345   Antoine Goutenoir   refactor: rename ...
189
        return render_template("estimation-request.html", form=form, models=models)
f2fbbb72   Antoine Goutenoir   Display a nice er...
190

7b4d2926   Goutte   Rework the contro...
191
192
    if form.validate_on_submit():

7b4d2926   Goutte   Rework the contro...
193
        estimation = Estimation()
a4c03d8e   Antoine Goutenoir   Add the controlle...
194
        # estimation.email = form.email.data
8ae021a2   Antoine Goutenoir   Merge shelved cha...
195
        estimation.run_name = form.run_name.data
7b4d2926   Goutte   Rework the contro...
196
197
        estimation.first_name = form.first_name.data
        estimation.last_name = form.last_name.data
16f69d07   Antoine Goutenoir   Add an (unsecured...
198
        estimation.institution = form.institution.data
24f55cde   Antoine Goutenoir   Geocode destinati...
199
        estimation.status = StatusEnum.pending
f2fbbb72   Antoine Goutenoir   Display a nice er...
200
201
202
203
204
205
206

        try:
            estimation.origin_addresses = gather_addresses(
                form.origin_addresses.data,
                form.origin_addresses_file.data
            )
        except validators.ValidationError as e:
b777efad   Antoine Goutenoir   fix: allow CSV de...
207
            form.origin_addresses_file.errors.append(str(e))
f2fbbb72   Antoine Goutenoir   Display a nice er...
208
            return show_form()
7f5397c6   Antoine Goutenoir   fix: don't crash ...
209
210
211
212
213
214
        except UnicodeDecodeError as e:
            form.origin_addresses_file.errors.append(
                "We only accept UTF-8 and UTF-16 encoded files, \n" +
                "or files we can detect encoding from."
            )
            return show_form()
f2fbbb72   Antoine Goutenoir   Display a nice er...
215
216
217
218
219
220
221

        try:
            estimation.destination_addresses = gather_addresses(
                form.destination_addresses.data,
                form.destination_addresses_file.data
            )
        except validators.ValidationError as e:
b777efad   Antoine Goutenoir   fix: allow CSV de...
222
            form.destination_addresses_file.errors.append(str(e))
f2fbbb72   Antoine Goutenoir   Display a nice er...
223
            return show_form()
7f5397c6   Antoine Goutenoir   fix: don't crash ...
224
225
226
227
228
229
        except UnicodeDecodeError as e:
            form.origin_addresses_file.errors.append(
                "We only accept UTF-8 and UTF-16 encoded files, \n" +
                "or files we can detect encoding from."
            )
            return show_form()
f2fbbb72   Antoine Goutenoir   Display a nice er...
230

4276f1aa   Antoine Goutenoir   Support train emi...
231
        estimation.use_train_below_km = form.use_train_below_km.data
f2fbbb72   Antoine Goutenoir   Display a nice er...
232

77e86148   Antoine Goutenoir   Fake support for ...
233
        models_slugs = []
04d423cb   Antoine Goutenoir   Limit the amount ...
234
        models_count = 0
77e86148   Antoine Goutenoir   Fake support for ...
235
        for model in models:
35fbac1f   Antoine Goutenoir   Fix a blooper.
236
            if getattr(form, 'use_model_%s' % model.slug).data:
77e86148   Antoine Goutenoir   Fake support for ...
237
                models_slugs.append(model.slug)
04d423cb   Antoine Goutenoir   Limit the amount ...
238
                models_count += 1
6b9c0dd2   Antoine Goutenoir   Force Unicode.
239
        estimation.models_slugs = u"\n".join(models_slugs)
7b4d2926   Goutte   Rework the contro...
240

04d423cb   Antoine Goutenoir   Limit the amount ...
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
        travels_to_compute = \
            models_count * \
            (estimation.origin_addresses.count("\n") + 1) * \
            (estimation.destination_addresses.count("\n") + 1)
        if travels_to_compute > maximum_travels_to_compute:
            message = """
            Too many travels to compute. (%d > %d)
            We're working on increasing this limitation.
            Please contact us directly if you wish to boost this issue
            or get a dedicated estimation.
            """ % (travels_to_compute, maximum_travels_to_compute)
            form.origin_addresses.errors.append(message)
            form.destination_addresses.errors.append(message)
            # form.origin_addresses_file.errors.append(message)
            # form.destination_addresses_file.errors.append(message)
            return show_form()

7b4d2926   Goutte   Rework the contro...
258
259
260
        db.session.add(estimation)
        db.session.commit()

e2637443   Antoine Goutenoir   Send emails to ad...
261
262
        send_email(
            to_recipient=pi_email,
3e6505e2   Antoine Goutenoir   Add content to th...
263
            subject="[TCFM] New Estimation Request: %s" % estimation.public_id,
07c07af5   Antoine Goutenoir   Add an email temp...
264
265
266
267
268
            message=render_template(
                'email/run_requested.html',
                base_url=base_url,
                estimation=estimation,
            )
e2637443   Antoine Goutenoir   Send emails to ad...
269
270
        )

7b4d2926   Goutte   Rework the contro...
271
        flash("Estimation request submitted successfully.", "success")
a4c03d8e   Antoine Goutenoir   Add the controlle...
272
273
274
        return redirect(url_for(
            endpoint=".consult_estimation",
            public_id=estimation.public_id,
91751451   Antoine Goutenoir   Shift the API to ...
275
            extension='html'
a4c03d8e   Antoine Goutenoir   Add the controlle...
276
        ))
7b4d2926   Goutte   Rework the contro...
277

f2fbbb72   Antoine Goutenoir   Display a nice er...
278
    return show_form()
7b4d2926   Goutte   Rework the contro...
279

4392f295   Goutte   Update the Estima...
280

15e57dca   Antoine Goutenoir   Naming things and...
281
@main.route("/invalidate")
4276f1aa   Antoine Goutenoir   Support train emi...
282
@main.route("/invalidate.html")
15e57dca   Antoine Goutenoir   Naming things and...
283
284
285
286
287
288
289
290
291
292
def invalidate():
    stuck_estimations = Estimation.query \
        .filter_by(status=StatusEnum.working) \
        .all()

    for estimation in stuck_estimations:
        estimation.status = StatusEnum.failure
        estimation.errors = "Invalidated. Try again."
        db.session.commit()

8ae021a2   Antoine Goutenoir   Merge shelved cha...
293
294
295
296
297
298
299
300
301
302
303
    return "Estimations invalidated: %d" % len(stuck_estimations)


@main.route("/invalidate-geocache")
@main.route("/invalidate-geocache.html")
def invalidate_geocache():
    geocache = 'geocache.db'

    unlink(geocache)

    return "Geocache invalidated."
15e57dca   Antoine Goutenoir   Naming things and...
304
305


4392f295   Goutte   Update the Estima...
306
@main.route("/compute")
51f564d3   Antoine Goutenoir   Add a big chunk o...
307
def compute():  # process the queue of estimation requests
24f55cde   Antoine Goutenoir   Geocode destinati...
308

04d423cb   Antoine Goutenoir   Limit the amount ...
309
    # maximum_addresses_to_compute = 30000
dca2b847   Antoine Goutenoir   Cap the amount of...
310

24f55cde   Antoine Goutenoir   Geocode destinati...
311
312
313
314
    def _respond(_msg):
        return "<pre>%s</pre>" % _msg

    def _handle_failure(_estimation, _failure_message):
a4c03d8e   Antoine Goutenoir   Add the controlle...
315
        _estimation.status = StatusEnum.failure
70aa301f   Antoine Goutenoir   Implement another...
316
        _estimation.errors = _failure_message
24f55cde   Antoine Goutenoir   Geocode destinati...
317
        db.session.commit()
3e6505e2   Antoine Goutenoir   Add content to th...
318
319
320
321
322
323
324
325
326
        send_email(
            to_recipient=pi_email,
            subject="[TCFM] Run failed: %s" % _estimation.public_id,
            message=render_template(
                'email/run_failed.html',
                base_url=base_url,
                estimation=_estimation,
            )
        )
24f55cde   Antoine Goutenoir   Geocode destinati...
327

72460978   Antoine Goutenoir   Use warnings inst...
328
    def _handle_warning(_estimation, _warning_message):
3d8865da   Antoine Goutenoir   Improve warnings ...
329
330
331
        if not _estimation.warnings:
            _estimation.warnings = _warning_message
        else:
ac935afa   Antoine Goutenoir   Make warnings mor...
332
            _estimation.warnings += _warning_message
3d8865da   Antoine Goutenoir   Improve warnings ...
333
334
            # _estimation.warnings = u"%s\n%s" % \
            #                        (_estimation.warnings, _warning_message)
72460978   Antoine Goutenoir   Use warnings inst...
335
336
        db.session.commit()

3d8865da   Antoine Goutenoir   Improve warnings ...
337
    estimation = None
59125398   Antoine Goutenoir   Improve resilience.
338
339
    try:
        response = ""
4392f295   Goutte   Update the Estima...
340

59125398   Antoine Goutenoir   Improve resilience.
341
342
343
        count_working = Estimation.query \
            .filter_by(status=StatusEnum.working) \
            .count()
03c194bf   Antoine Goutenoir   Actually implemen...
344

59125398   Antoine Goutenoir   Improve resilience.
345
346
        if 0 < count_working:
            return _respond("Already working on estimation.")
03c194bf   Antoine Goutenoir   Actually implemen...
347

59125398   Antoine Goutenoir   Improve resilience.
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
        try:
            estimation = Estimation.query \
                .filter_by(status=StatusEnum.pending) \
                .order_by(Estimation.id.asc()) \
                .first()
        except sqlalchemy.orm.exc.NoResultFound:
            return _respond("No estimation in the queue.")
        except Exception as e:
            return _respond("Database error: %s" % (e,))

        if not estimation:
            return _respond("No estimation in the queue.")

        estimation.status = StatusEnum.working
        db.session.commit()
51f564d3   Antoine Goutenoir   Add a big chunk o...
363

59125398   Antoine Goutenoir   Improve resilience.
364
365
366
        response += u"Processing estimation `%s`...\n" % (
            estimation.public_id
        )
24f55cde   Antoine Goutenoir   Geocode destinati...
367

6b9c0dd2   Antoine Goutenoir   Force Unicode.
368
369
        # GEOCODE ADDRESSES ###################################################

59125398   Antoine Goutenoir   Improve resilience.
370
371
        failed_addresses = []
        geocoder = CachedGeocoder()
03c194bf   Antoine Goutenoir   Actually implemen...
372

e2637443   Antoine Goutenoir   Send emails to ad...
373
        # GEOCODE ORIGINS #####################################################
24f55cde   Antoine Goutenoir   Geocode destinati...
374

59125398   Antoine Goutenoir   Improve resilience.
375
        origins_addresses = estimation.origin_addresses.strip().split("\n")
dca2b847   Antoine Goutenoir   Cap the amount of...
376
        origins_addresses_count = len(origins_addresses)
59125398   Antoine Goutenoir   Improve resilience.
377
        origins = []
24f55cde   Antoine Goutenoir   Geocode destinati...
378

04d423cb   Antoine Goutenoir   Limit the amount ...
379
380
381
382
383
384
385
        # if origins_addresses_count > maximum_addresses_to_compute:
        #     errmsg = u"Too many origins. (%d > %d) \n" \
        #              u"Please contact us " \
        #              u"for support of more origins." % \
        #              (origins_addresses_count, maximum_addresses_to_compute)
        #     _handle_failure(estimation, errmsg)
        #     return _respond(errmsg)
dca2b847   Antoine Goutenoir   Cap the amount of...
386
387

        for i in range(origins_addresses_count):
51f564d3   Antoine Goutenoir   Add a big chunk o...
388

59125398   Antoine Goutenoir   Improve resilience.
389
            origin_address = origins_addresses[i].strip()
3d8865da   Antoine Goutenoir   Improve warnings ...
390
391
392
393

            if not origin_address:
                continue

59125398   Antoine Goutenoir   Improve resilience.
394
395
            if origin_address in failed_addresses:
                continue
51f564d3   Antoine Goutenoir   Add a big chunk o...
396

59125398   Antoine Goutenoir   Improve resilience.
397
            try:
bd79940b   Antoine Goutenoir   chore: move to py...
398
                origin = geocoder.geocode(origin_address)
59125398   Antoine Goutenoir   Improve resilience.
399
            except geopy.exc.GeopyError as e:
3d8865da   Antoine Goutenoir   Improve warnings ...
400
401
402
                warning = u"Ignoring origin `%s` " \
                          u"since we failed to geocode it.\n%s\n" % (
                            origin_address, e,
59125398   Antoine Goutenoir   Improve resilience.
403
                )
3d8865da   Antoine Goutenoir   Improve warnings ...
404
405
                response += warning
                _handle_warning(estimation, warning)
59125398   Antoine Goutenoir   Improve resilience.
406
407
                failed_addresses.append(origin_address)
                continue
51f564d3   Antoine Goutenoir   Add a big chunk o...
408

59125398   Antoine Goutenoir   Improve resilience.
409
            if origin is None:
3d8865da   Antoine Goutenoir   Improve warnings ...
410
411
412
                warning = u"Ignoring origin `%s` " \
                          u"since we failed to geocode it.\n" % (
                            origin_address,
59125398   Antoine Goutenoir   Improve resilience.
413
                )
3d8865da   Antoine Goutenoir   Improve warnings ...
414
415
                response += warning
                _handle_warning(estimation, warning)
59125398   Antoine Goutenoir   Improve resilience.
416
417
                failed_addresses.append(origin_address)
                continue
51f564d3   Antoine Goutenoir   Add a big chunk o...
418

59125398   Antoine Goutenoir   Improve resilience.
419
            origins.append(origin)
51f564d3   Antoine Goutenoir   Add a big chunk o...
420

3d8865da   Antoine Goutenoir   Improve warnings ...
421
            response += u"Origin `%s` geocoded to `%s` (%f, %f).\n" % (
59125398   Antoine Goutenoir   Improve resilience.
422
423
                origin_address, origin.address,
                origin.latitude, origin.longitude,
51f564d3   Antoine Goutenoir   Add a big chunk o...
424
            )
51f564d3   Antoine Goutenoir   Add a big chunk o...
425

e2637443   Antoine Goutenoir   Send emails to ad...
426
        # GEOCODE DESTINATIONS ################################################
51f564d3   Antoine Goutenoir   Add a big chunk o...
427

59125398   Antoine Goutenoir   Improve resilience.
428
        destinations_addresses = estimation.destination_addresses.strip().split("\n")
dca2b847   Antoine Goutenoir   Cap the amount of...
429
        destinations_addresses_count = len(destinations_addresses)
59125398   Antoine Goutenoir   Improve resilience.
430
        destinations = []
51f564d3   Antoine Goutenoir   Add a big chunk o...
431

04d423cb   Antoine Goutenoir   Limit the amount ...
432
433
434
435
436
437
438
439
440
441
        # if destinations_addresses_count > maximum_addresses_to_compute:
        #     errmsg = u"Too many destinations. (%d > %d) \n" \
        #              u"Please contact us " \
        #              u"for support of that many destinations." \
        #              % (
        #                  destinations_addresses_count,
        #                  maximum_addresses_to_compute,
        #              )
        #     _handle_failure(estimation, errmsg)
        #     return _respond(errmsg)
dca2b847   Antoine Goutenoir   Cap the amount of...
442
443

        for i in range(destinations_addresses_count):
51f564d3   Antoine Goutenoir   Add a big chunk o...
444

59125398   Antoine Goutenoir   Improve resilience.
445
            destination_address = destinations_addresses[i].strip()
3d8865da   Antoine Goutenoir   Improve warnings ...
446
447
448
449

            if not destination_address:
                continue

59125398   Antoine Goutenoir   Improve resilience.
450
451
            if destination_address in failed_addresses:
                continue
24f55cde   Antoine Goutenoir   Geocode destinati...
452

59125398   Antoine Goutenoir   Improve resilience.
453
            try:
bd79940b   Antoine Goutenoir   chore: move to py...
454
                destination = geocoder.geocode(destination_address)
59125398   Antoine Goutenoir   Improve resilience.
455
            except geopy.exc.GeopyError as e:
3d8865da   Antoine Goutenoir   Improve warnings ...
456
457
458
                warning = u"Ignoring destination `%s` " \
                          u"since we failed to geocode it.\n%s\n" % (
                            destination_address, e,
59125398   Antoine Goutenoir   Improve resilience.
459
                )
3d8865da   Antoine Goutenoir   Improve warnings ...
460
461
                response += warning
                _handle_warning(estimation, warning)
59125398   Antoine Goutenoir   Improve resilience.
462
463
                failed_addresses.append(destination_address)
                continue
24f55cde   Antoine Goutenoir   Geocode destinati...
464

59125398   Antoine Goutenoir   Improve resilience.
465
            if destination is None:
3d8865da   Antoine Goutenoir   Improve warnings ...
466
467
468
                warning = u"Ignoring destination `%s` " \
                          u"since we failed to geocode it.\n" % (
                            destination_address,
59125398   Antoine Goutenoir   Improve resilience.
469
                )
3d8865da   Antoine Goutenoir   Improve warnings ...
470
471
                response += warning
                _handle_warning(estimation, warning)
59125398   Antoine Goutenoir   Improve resilience.
472
473
                failed_addresses.append(destination_address)
                continue
24f55cde   Antoine Goutenoir   Geocode destinati...
474

59125398   Antoine Goutenoir   Improve resilience.
475
            # print(repr(destination.raw))
24f55cde   Antoine Goutenoir   Geocode destinati...
476

59125398   Antoine Goutenoir   Improve resilience.
477
478
            destinations.append(destination)

3d8865da   Antoine Goutenoir   Improve warnings ...
479
            response += u"Destination `%s` geocoded to `%s` (%f, %f).\n" % (
59125398   Antoine Goutenoir   Improve resilience.
480
481
                destination_address, destination.address,
                destination.latitude, destination.longitude,
24f55cde   Antoine Goutenoir   Geocode destinati...
482
            )
24f55cde   Antoine Goutenoir   Geocode destinati...
483

8ae021a2   Antoine Goutenoir   Merge shelved cha...
484
485
        geocoder.close()

e2637443   Antoine Goutenoir   Send emails to ad...
486
        # GTFO IF NO ORIGINS OR NO DESTINATIONS ###############################
314c65e2   Antoine Goutenoir   Implement Scenari...
487

59125398   Antoine Goutenoir   Improve resilience.
488
        if 0 == len(origins):
3d8865da   Antoine Goutenoir   Improve warnings ...
489
            response += u"Failed to geocode ALL the origin(s).\n"
59125398   Antoine Goutenoir   Improve resilience.
490
491
492
            _handle_failure(estimation, response)
            return _respond(response)
        if 0 == len(destinations):
3d8865da   Antoine Goutenoir   Improve warnings ...
493
            response += u"Failed to geocode ALL the destination(s).\n"
59125398   Antoine Goutenoir   Improve resilience.
494
495
            _handle_failure(estimation, response)
            return _respond(response)
24f55cde   Antoine Goutenoir   Geocode destinati...
496

e2637443   Antoine Goutenoir   Send emails to ad...
497
        # GRAB AND CONFIGURE THE EMISSION MODELS ##############################
24f55cde   Antoine Goutenoir   Geocode destinati...
498

59125398   Antoine Goutenoir   Improve resilience.
499
500
        emission_models = estimation.get_models()
        # print(emission_models)
51f564d3   Antoine Goutenoir   Add a big chunk o...
501

59125398   Antoine Goutenoir   Improve resilience.
502
503
504
505
        extra_config = {
            'use_train_below_distance': estimation.use_train_below_km,
            # 'use_train_below_distance': 300,
        }
70aa301f   Antoine Goutenoir   Implement another...
506

e2637443   Antoine Goutenoir   Send emails to ad...
507
        # PREPARE RESULT DICTIONARY THAT WILL BE STORED #######################
59125398   Antoine Goutenoir   Improve resilience.
508
509
510

        results = {}

e2637443   Antoine Goutenoir   Send emails to ad...
511
        # UTILITY PRIVATE FUNCTION(S) #########################################
59125398   Antoine Goutenoir   Improve resilience.
512

2ac05e0c   Antoine Goutenoir   feat: rely on ful...
513
514
515
516
517
518
519
        # _locations
        def _get_location_key(_location):
            return "%s, %s" % (
                _get_city_key(_location),
                _get_country_key(_location),
            )

e2e42156   Antoine Goutenoir   Add the country t...
520
        def _get_city_key(_location):
59125398   Antoine Goutenoir   Improve resilience.
521
522
523
524
525
526
527
528
529
530
531
            return _location.address.split(',')[0]

            # _city_key = _location.address
            # # if 'address100' in _location.raw['address']:
            # #     _city_key = _location.raw['address']['address100']
            # if 'city' in _location.raw['address']:
            #     _city_key = _location.raw['address']['city']
            # elif 'state' in _location.raw['address']:
            #     _city_key = _location.raw['address']['state']
            # return _city_key

e2e42156   Antoine Goutenoir   Add the country t...
532
533
534
        def _get_country_key(_location):
            return _location.address.split(',')[-1]

59125398   Antoine Goutenoir   Improve resilience.
535
536
537
538
539
540
541
542
        def compute_one_to_many(
                _origin,
                _destinations,
                _extra_config=None
        ):
            _results = {}
            footprints = {}

2ac05e0c   Antoine Goutenoir   feat: rely on ful...
543
            destinations_by_key = {}
59125398   Antoine Goutenoir   Improve resilience.
544
545
546
547
548
549
550
551
552
553
554
555
556
557

            cities_sum_foot = {}
            cities_sum_dist = {}
            cities_dict_first_model = None
            for model in emission_models:
                cities_dict = {}
                for _destination in _destinations:
                    footprint = model.compute_travel_footprint(
                        origin_latitude=_origin.latitude,
                        origin_longitude=_origin.longitude,
                        destination_latitude=_destination.latitude,
                        destination_longitude=_destination.longitude,
                        extra_config=_extra_config,
                    )
51f564d3   Antoine Goutenoir   Add a big chunk o...
558

2ac05e0c   Antoine Goutenoir   feat: rely on ful...
559
560
                    _key = _get_location_key(_destination)
                    destinations_by_key[_key] = _destination
59125398   Antoine Goutenoir   Improve resilience.
561
562
563

                    if _key not in cities_dict:
                        cities_dict[_key] = {
2ac05e0c   Antoine Goutenoir   feat: rely on ful...
564
565
                            'location': _get_location_key(_destination),
                            'city': _get_city_key(_destination),
e2e42156   Antoine Goutenoir   Add the country t...
566
                            'country': _get_country_key(_destination),
59125398   Antoine Goutenoir   Improve resilience.
567
                            'address': _destination.address,
82cd86ae   Antoine Goutenoir   feat: add the lat...
568
569
                            'latitude': _destination.latitude,
                            'longitude': _destination.longitude,
59125398   Antoine Goutenoir   Improve resilience.
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
                            'footprint': 0.0,
                            'distance': 0.0,
                            'train_trips': 0,
                            'plane_trips': 0,
                        }
                    cities_dict[_key]['footprint'] += footprint['co2eq_kg']
                    cities_dict[_key]['distance'] += footprint['distance_km']
                    cities_dict[_key]['train_trips'] += footprint['train_trips']
                    cities_dict[_key]['plane_trips'] += footprint['plane_trips']
                    if _key not in cities_sum_foot:
                        cities_sum_foot[_key] = 0.0
                    cities_sum_foot[_key] += footprint['co2eq_kg']
                    if _key not in cities_sum_dist:
                        cities_sum_dist[_key] = 0.0
                    cities_sum_dist[_key] += footprint['distance_km']

                cities = sorted(cities_dict.values(), key=lambda c: c['footprint'])

                footprints[model.slug] = {
                    'cities': cities,
                }

                if cities_dict_first_model is None:
                    cities_dict_first_model = deepcopy(cities_dict)

            _results['footprints'] = footprints

            total_foot = 0.0
            total_dist = 0.0
            total_train_trips = 0
            total_plane_trips = 0

            cities_mean_dict = {}
            for city in cities_sum_foot.keys():
                city_mean_foot = 1.0 * cities_sum_foot[city] / len(emission_models)
                city_mean_dist = 1.0 * cities_sum_dist[city] / len(emission_models)
                city_train_trips = cities_dict_first_model[city]['train_trips']
                city_plane_trips = cities_dict_first_model[city]['plane_trips']
                cities_mean_dict[city] = {
2ac05e0c   Antoine Goutenoir   feat: rely on ful...
609
610
611
612
613
614
                    'location': _get_location_key(destinations_by_key[city]),
                    'city': _get_city_key(destinations_by_key[city]),
                    'country': _get_country_key(destinations_by_key[city]),
                    'address': destinations_by_key[city].address,
                    'latitude': destinations_by_key[city].latitude,
                    'longitude': destinations_by_key[city].longitude,
59125398   Antoine Goutenoir   Improve resilience.
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
                    'footprint': city_mean_foot,
                    'distance': city_mean_dist,
                    'train_trips': city_train_trips,
                    'plane_trips': city_plane_trips,
                }
                total_foot += city_mean_foot
                total_dist += city_mean_dist
                total_train_trips += city_train_trips
                total_plane_trips += city_plane_trips

            cities_mean = [cities_mean_dict[k] for k in cities_mean_dict.keys()]
            cities_mean = sorted(cities_mean, key=lambda c: c['footprint'])

            _results['mean_footprint'] = {  # DEPRECATED?
                'cities': cities_mean
584b13cc   Antoine Goutenoir   Order the results...
630
            }
59125398   Antoine Goutenoir   Improve resilience.
631
            _results['cities'] = cities_mean
1d48272e   Antoine Goutenoir   Compute the mean ...
632

59125398   Antoine Goutenoir   Improve resilience.
633
634
            _results['total'] = total_foot  # DEPRECATED
            _results['footprint'] = total_foot
584b13cc   Antoine Goutenoir   Order the results...
635

59125398   Antoine Goutenoir   Improve resilience.
636
637
638
            _results['distance'] = total_dist
            _results['train_trips'] = total_train_trips
            _results['plane_trips'] = total_plane_trips
70aa301f   Antoine Goutenoir   Implement another...
639

59125398   Antoine Goutenoir   Improve resilience.
640
            return _results
24f55cde   Antoine Goutenoir   Geocode destinati...
641

e2637443   Antoine Goutenoir   Send emails to ad...
642
        # SCENARIO A : One Origin, At Least One Destination ###################
59125398   Antoine Goutenoir   Improve resilience.
643
        #
e2637443   Antoine Goutenoir   Send emails to ad...
644
        # We compute the sum of each of the travels' footprint,
59125398   Antoine Goutenoir   Improve resilience.
645
646
647
648
649
650
651
652
653
        # for each of the Emission Models, and present a mean of all Models.
        #
        if 1 == len(origins):
            estimation.scenario = ScenarioEnum.one_to_many
            results = compute_one_to_many(
                _origin=origins[0],
                _destinations=destinations,
                _extra_config=extra_config,
            )
94ae2730   Antoine Goutenoir   Ignore duplicates...
654

e2637443   Antoine Goutenoir   Send emails to ad...
655
        # SCENARIO B : At Least One Origin, One Destination ###################
59125398   Antoine Goutenoir   Improve resilience.
656
657
658
659
660
661
662
        #
        # Same as A for now.
        #
        elif 1 == len(destinations):
            estimation.scenario = ScenarioEnum.many_to_one
            results = compute_one_to_many(
                _origin=destinations[0],
314c65e2   Antoine Goutenoir   Implement Scenari...
663
                _destinations=origins,
8a693e06   Antoine Goutenoir   Glue the extra co...
664
                _extra_config=extra_config,
314c65e2   Antoine Goutenoir   Implement Scenari...
665
            )
314c65e2   Antoine Goutenoir   Implement Scenari...
666

e2637443   Antoine Goutenoir   Send emails to ad...
667
        # SCENARIO C : At Least One Origin, At Least One Destination ##########
59125398   Antoine Goutenoir   Improve resilience.
668
669
        #
        # Run Scenario A for each Destination, and expose optimum Destination.
2ac05e0c   Antoine Goutenoir   feat: rely on ful...
670
        # Skip destinations already visited.  (collapse duplicate destinations)
59125398   Antoine Goutenoir   Improve resilience.
671
672
673
        #
        else:
            estimation.scenario = ScenarioEnum.many_to_many
2ac05e0c   Antoine Goutenoir   feat: rely on ful...
674
            unique_location_keys = []
59125398   Antoine Goutenoir   Improve resilience.
675
676
            result_cities = []
            for destination in destinations:
2ac05e0c   Antoine Goutenoir   feat: rely on ful...
677
                location_key = _get_location_key(destination)
e2e42156   Antoine Goutenoir   Add the country t...
678
679
                city_key = _get_city_key(destination)
                country_key = _get_country_key(destination)
59125398   Antoine Goutenoir   Improve resilience.
680

2ac05e0c   Antoine Goutenoir   feat: rely on ful...
681
                if location_key in unique_location_keys:
59125398   Antoine Goutenoir   Improve resilience.
682
683
                    continue
                else:
2ac05e0c   Antoine Goutenoir   feat: rely on ful...
684
                    unique_location_keys.append(location_key)
1d48272e   Antoine Goutenoir   Compute the mean ...
685

59125398   Antoine Goutenoir   Improve resilience.
686
687
688
689
690
691
                city_results = compute_one_to_many(
                    _origin=destination,
                    _destinations=origins,
                    _extra_config=extra_config,
                )
                city_results['city'] = city_key
e2e42156   Antoine Goutenoir   Add the country t...
692
                city_results['country'] = country_key
2ac05e0c   Antoine Goutenoir   feat: rely on ful...
693
                city_results['location'] = location_key
59125398   Antoine Goutenoir   Improve resilience.
694
                city_results['address'] = destination.address
82cd86ae   Antoine Goutenoir   feat: add the lat...
695
696
                city_results['latitude'] = destination.latitude
                city_results['longitude'] = destination.longitude
59125398   Antoine Goutenoir   Improve resilience.
697
698
699
700
701
702
703
                result_cities.append(city_results)

            result_cities = sorted(result_cities, key=lambda c: int(c['footprint']))
            results = {
                'cities': result_cities,
            }

e2637443   Antoine Goutenoir   Send emails to ad...
704
        # WRITE RESULTS INTO THE DATABASE #####################################
a4c03d8e   Antoine Goutenoir   Add the controlle...
705

59125398   Antoine Goutenoir   Improve resilience.
706
        estimation.status = StatusEnum.success
e2637443   Antoine Goutenoir   Send emails to ad...
707
        # Don't use YAML, it is too slow for big data.
f48f4a8f   Antoine Goutenoir   Optimize a bottle...
708
        # estimation.output_yaml = u"%s" % yaml_dump(results)
3d8865da   Antoine Goutenoir   Improve warnings ...
709
        estimation.informations = response
f48f4a8f   Antoine Goutenoir   Optimize a bottle...
710
        estimation.set_output_dict(results)
59125398   Antoine Goutenoir   Improve resilience.
711
712
        db.session.commit()

e2637443   Antoine Goutenoir   Send emails to ad...
713
714
715
716
717
        # SEND AN EMAIL #######################################################

        send_email(
            to_recipient=pi_email,
            subject="[TCFM] Run completed: %s" % estimation.public_id,
3e6505e2   Antoine Goutenoir   Add content to th...
718
719
720
721
722
            message=render_template(
                'email/run_completed.html',
                base_url=base_url,
                estimation=estimation,
            )
e2637443   Antoine Goutenoir   Send emails to ad...
723
724
725
        )

        # FINALLY, RESPOND ####################################################
a4c03d8e   Antoine Goutenoir   Add the controlle...
726

3e6505e2   Antoine Goutenoir   Add content to th...
727
        # YAML is too expensive, let's not
f48f4a8f   Antoine Goutenoir   Optimize a bottle...
728
        # response += yaml_dump(results) + "\n"
a4c03d8e   Antoine Goutenoir   Add the controlle...
729

59125398   Antoine Goutenoir   Improve resilience.
730
        return _respond(response)
4392f295   Goutte   Update the Estima...
731

59125398   Antoine Goutenoir   Improve resilience.
732
    except Exception as e:
e144bb1b   Antoine Goutenoir   Fix encoding.
733
        errmsg = u"Computation failed : %s" % (e,)
80fd4654   Antoine Goutenoir   feat: improve err...
734
735
736
        if 'production' != getenv('FLASK_ENV', 'production'):
            import traceback
            errmsg = u"%s\n\n%s" % (errmsg, traceback.format_exc())
59125398   Antoine Goutenoir   Improve resilience.
737
738
739
        if estimation:
            _handle_failure(estimation, errmsg)
        return _respond(errmsg)
a4c03d8e   Antoine Goutenoir   Add the controlle...
740
741


b9fc86c3   Antoine Goutenoir   Secure the admin ...
742
743
@main.route("/estimation/<public_id>.<extension>")
def consult_estimation(public_id, extension):
a4c03d8e   Antoine Goutenoir   Add the controlle...
744
745
746
747
748
749
750
    try:
        estimation = Estimation.query \
            .filter_by(public_id=public_id) \
            .one()
    except sqlalchemy.orm.exc.NoResultFound:
        return abort(404)
    except Exception as e:
2ac05e0c   Antoine Goutenoir   feat: rely on ful...
751
        # log? (or not)
a4c03d8e   Antoine Goutenoir   Add the controlle...
752
753
754
755
756
757
        return abort(500)

    # allowed_formats = ['html']
    # if format not in allowed_formats:
    #     abort(404)

b9fc86c3   Antoine Goutenoir   Secure the admin ...
758
    if extension in ['xhtml', 'html', 'htm']:
e721cb31   Antoine Goutenoir   Provide a YAML fi...
759

e1e633fa   Antoine Goutenoir   chore: improve er...
760
        if estimation.status in estimation.unavailable_statuses:
a4c03d8e   Antoine Goutenoir   Add the controlle...
761
762
763
764
765
            return render_template(
                "estimation-queue-wait.html",
                estimation=estimation
            )
        else:
e1e633fa   Antoine Goutenoir   chore: improve er...
766
767
768
769
            try:
                estimation_output = estimation.get_output_dict()
            except Exception as e:
                return abort(404)
40382971   Antoine Goutenoir   Add the sum of es...
770
            estimation_sum = 0
37e28f2c   Antoine Goutenoir   Improve resilience.
771
772
773
            if estimation_output:
                for city in estimation_output['cities']:
                    estimation_sum += city['footprint']
40382971   Antoine Goutenoir   Add the sum of es...
774

a4c03d8e   Antoine Goutenoir   Add the controlle...
775
776
            return render_template(
                "estimation.html",
91751451   Antoine Goutenoir   Shift the API to ...
777
                estimation=estimation,
40382971   Antoine Goutenoir   Add the sum of es...
778
779
                estimation_output=estimation_output,
                estimation_sum=estimation_sum,
a4c03d8e   Antoine Goutenoir   Add the controlle...
780
781
            )

b9fc86c3   Antoine Goutenoir   Secure the admin ...
782
    elif extension in ['yaml', 'yml']:
e721cb31   Antoine Goutenoir   Provide a YAML fi...
783

e1e633fa   Antoine Goutenoir   chore: improve er...
784
785
        if not estimation.is_available():
            return abort(404)
e721cb31   Antoine Goutenoir   Provide a YAML fi...
786

f48f4a8f   Antoine Goutenoir   Optimize a bottle...
787
788
        return u"%s" % yaml_dump(estimation.get_output_dict())
        # return estimation.output_yaml
e721cb31   Antoine Goutenoir   Provide a YAML fi...
789

b9fc86c3   Antoine Goutenoir   Secure the admin ...
790
    elif 'csv' == extension:
a4c03d8e   Antoine Goutenoir   Add the controlle...
791

e1e633fa   Antoine Goutenoir   chore: improve er...
792
793
        if not estimation.is_available():
            return abort(404)
e721cb31   Antoine Goutenoir   Provide a YAML fi...
794

a4c03d8e   Antoine Goutenoir   Add the controlle...
795
796
        si = StringIO()
        cw = csv.writer(si, quoting=csv.QUOTE_ALL)
b935618e   Antoine Goutenoir   Count the number ...
797
        cw.writerow([
2ac05e0c   Antoine Goutenoir   feat: rely on ful...
798
            u"location",
e2e42156   Antoine Goutenoir   Add the country t...
799
            u"city", u"country", u"address",
82cd86ae   Antoine Goutenoir   feat: add the lat...
800
            u"latitude", u"longitude",
29a1d1c1   Antoine Goutenoir   Rename columns in...
801
802
803
804
            u"co2_kg",
            u"distance_km",
            u"plane trips_amount",
            u'train trips_amount',
b935618e   Antoine Goutenoir   Count the number ...
805
        ])
a4c03d8e   Antoine Goutenoir   Add the controlle...
806
807

        results = estimation.get_output_dict()
5634c975   Antoine Goutenoir   Expose travel dis...
808
809
        for city in results['cities']:
            cw.writerow([
2ac05e0c   Antoine Goutenoir   feat: rely on ful...
810
811
812
813
814
                # city['location'].encode(OUT_ENCODING),
                city['location'],
                city['city'],
                city['country'],
                city['address'],
67db4e6a   Antoine Goutenoir   fix: backward-com...
815
816
                city.get('latitude', 0.0),
                city.get('longitude', 0.0),
5634c975   Antoine Goutenoir   Expose travel dis...
817
818
                round(city['footprint'], 3),
                round(city['distance'], 3),
b935618e   Antoine Goutenoir   Count the number ...
819
820
                city['plane_trips'],
                city['train_trips'],
5634c975   Antoine Goutenoir   Expose travel dis...
821
822
            ])

67f85bce   Antoine Goutenoir   Generate a CSV fi...
823
824
825
826
827
828
829
830
        # return si.getvalue().strip('\r\n')
        return Response(
            response=si.getvalue().strip('\r\n'),
            headers={
                'Content-type': 'text/csv',
                'Content-disposition': "attachment; filename=%s.csv"%public_id,
            },
        )
a4c03d8e   Antoine Goutenoir   Add the controlle...
831
832

    else:
e1e633fa   Antoine Goutenoir   chore: improve er...
833
        return abort(404)
b9fc86c3   Antoine Goutenoir   Secure the admin ...
834
835


3bb89452   Antoine Goutenoir   feat: add a world...
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
def get_locations(addresses):
    geocoder = CachedGeocoder()

    warnings = []
    addresses_count = len(addresses)
    failed_addresses = []
    locations = []

    for i in range(addresses_count):

        address = addresses[i].strip()
        unicode_address = address.encode('utf-8')

        if not address:
            continue

        if address in failed_addresses:
            continue

        try:
            location = geocoder.geocode(unicode_address)
        except geopy.exc.GeopyError as e:
            warning = u"Ignoring address `%s` " \
                      u"since we failed to geocode it.\n%s\n" % (
                          address, e,
                      )
            warnings.append(warning)
            failed_addresses.append(address)
            continue

        if location is None:
            warning = u"Ignoring address `%s` " \
                      u"since we failed to geocode it.\n" % (
                          address,
                      )
            warnings.append(warning)
            failed_addresses.append(address)
            failed_addresses.append(address)
            continue

        print("Geocoded Location:\n", repr(location.raw))
        locations.append(location)

        # response += u"Location `%s` geocoded to `%s` (%f, %f).\n" % (
        #     location_address, location.address,
        #     location.latitude, location.longitude,
        # )

    return locations, warnings


@main.route("/estimation/<public_id>/trips_to_destination_<destination_index>.csv")
def get_trips_csv(public_id, destination_index=0):
    destination_index = int(destination_index)
    try:
        estimation = Estimation.query \
            .filter_by(public_id=public_id) \
            .one()
    except sqlalchemy.orm.exc.NoResultFound:
        return abort(404)
    except Exception as e:
        return abort(500)

e1e633fa   Antoine Goutenoir   chore: improve er...
899
900
    if not estimation.is_available():
        return abort(404)
3bb89452   Antoine Goutenoir   feat: add a world...
901
902
903
904
905
906
907
908
909
910
911
912

    si = StringIO()
    cw = csv.writer(si, quoting=csv.QUOTE_ALL)
    cw.writerow([
        u"origin_lon",
        u"origin_lat",
        u"destination_lon",
        u"destination_lat",
    ])
    results = estimation.get_output_dict()

    if not 'cities' in results:
e1e633fa   Antoine Goutenoir   chore: improve er...
913
        return abort(500)
3bb89452   Antoine Goutenoir   feat: add a world...
914
915
916
917

    cities_length = len(results['cities'])

    if 0 == cities_length:
e1e633fa   Antoine Goutenoir   chore: improve er...
918
        return abort(500, Response("No cities in results."))
3bb89452   Antoine Goutenoir   feat: add a world...
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

    destination_index = min(destination_index, cities_length - 1)
    destination_index = max(destination_index, 0)

    city = results['cities'][destination_index]
    # >>> yaml_dump(city)
    # address: Paris, Ile - de - France, Metropolitan
    # France, France
    # city: Paris
    # country: ' France'
    # distance: 1752.7481921181325
    # footprint: 824.9628320703453
    # plane_trips: 1
    # train_trips: 0

    geocoder = CachedGeocoder()
    try:
        city_location = geocoder.geocode(city['address'].encode('utf-8'))
    except geopy.exc.GeopyError as e:
        return Response(
            response=si.getvalue().strip('\r\n'),
        )

    other_locations, _warnings = get_locations(estimation.origin_addresses.split("\n"))
    # destination_locations = get_locations(estimation.destination_addresses.split("\n"))
    for other_location in other_locations:
        cw.writerow([
            u"%.8f" % city_location.longitude,
            u"%.8f" % city_location.latitude,
            u"%.8f" % other_location.longitude,
            u"%.8f" % other_location.latitude,
        ])

    filename = "trips_to_destination_%d.csv" % destination_index
    return Response(
        response=si.getvalue().strip('\r\n'),
        headers={
            'Content-type': 'text/csv',
            'Content-disposition': 'attachment; filename=%s' % filename,
        },
    )


67f85bce   Antoine Goutenoir   Generate a CSV fi...
962
963
@main.route("/scaling_laws.csv")
def get_scaling_laws_csv():
a728e600   Antoine Goutenoir   Allow configurati...
964
    distances = content.laws_plot.distances
67f85bce   Antoine Goutenoir   Generate a CSV fi...
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
    models = get_emission_models()

    si = StringIO()
    cw = csv.writer(si, quoting=csv.QUOTE_ALL)

    header = ['distance'] + [model.slug for model in models]
    cw.writerow(header)

    for distance in distances:
        row = [distance]
        for model in models:
            row.append(model.compute_airplane_distance_footprint(distance))
        cw.writerow(row)

    return Response(
        response=si.getvalue().strip('\r\n'),
        headers={
            'Content-type': 'text/csv',
            'Content-disposition': 'attachment; filename=scaling_laws.csv',
        },
    )


2ac05e0c   Antoine Goutenoir   feat: rely on ful...
988
989
990
991
992
993
994
995
996
997
@main.route('/geocode')
@main.route('/geocode.html')
def query_geocode():
    requested = request.args.getlist('address')
    if not requested:
        requested = request.args.getlist('address[]')
    if not requested:
        requested = request.args.getlist('a')
    if not requested:
        requested = request.args.getlist('a[]')
5bde6c52   Antoine Goutenoir   chore: review
998
    # requested = _collect_request_args_list(('address', 'a'))
2ac05e0c   Antoine Goutenoir   feat: rely on ful...
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
    if not requested:
        return Response(
            response="""
<p>
Usage example: <a href="/geocode.html?address=Toulouse,France&amp;address=Paris,France">/geocode?address=Toulouse,France</a>
</p>

<p>
Please do not request this endpoint more than every two seconds.
</p>
2ac05e0c   Antoine Goutenoir   feat: rely on ful...
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
"""
        )

    response = u""

    geocoder = CachedGeocoder()
    for address in requested:
        location = geocoder.geocode(address)

        response += """
<pre>
Requested: `%s'
Geocoded: `%s'
Longitude: `%f`
Latitude: `%f`
Altitude: `%f` (unreliable)
</pre>
""" % (address, location, location.longitude, location.latitude, location.altitude)

    return Response(response=response)


b9fc86c3   Antoine Goutenoir   Secure the admin ...
1031
@main.route("/test")
c2a01bd2   Antoine Goutenoir   Prepare mail flas...
1032
# @basic_auth.required
b9fc86c3   Antoine Goutenoir   Secure the admin ...
1033
def dev_test():
e2637443   Antoine Goutenoir   Send emails to ad...
1034
    # email_content = render_template(
3e6505e2   Antoine Goutenoir   Add content to th...
1035
    #     'email/run_completed.html',
e2637443   Antoine Goutenoir   Send emails to ad...
1036
1037
1038
1039
1040
1041
1042
1043
1044
    #     # run=run,
    # )
    # send_email(
    #     'goutte@protonmail.com',
    #     subject=u"[TCFC] New run request",
    #     message=email_content
    # )

    return "ok"