views.py 17.3 KB
Newer Older
1
2
3
"""
    Routes
"""
4
import copy
Pierre Dittgen's avatar
Pierre Dittgen committed
5
import itertools
6
import json
Christophe Benz's avatar
Christophe Benz committed
7
import logging
Pierre Dittgen's avatar
Pierre Dittgen committed
8
import os
9
import subprocess
Christophe Benz's avatar
Christophe Benz committed
10
import tempfile
11
from datetime import datetime
12
from io import BytesIO
13
from operator import itemgetter
14
15
from pathlib import Path
from urllib.parse import quote_plus
16

Pierre Dittgen's avatar
Pierre Dittgen committed
17
18
import requests
import toml
19
from backports.datetime_fromisoformat import MonkeyPatch
Pierre Dittgen's avatar
Pierre Dittgen committed
20
from commonmark import commonmark
21
from flask import make_response, redirect, render_template, request, url_for
Pierre Dittgen's avatar
Pierre Dittgen committed
22
23
from validata_core import compute_badge, csv_helpers, messages
from validata_core.loaders import custom_loaders
24

25
import tabulator
26
from validata_ui import app
Pierre Dittgen's avatar
Pierre Dittgen committed
27
from validata_ui.ui_util import flash_error, flash_warning
28
from validata_ui.validata_util import ValidataSource
29
from validata_ui.validate_helper import ValidatorHelper
30

31
32
MonkeyPatch.patch_fromisoformat()

Christophe Benz's avatar
Christophe Benz committed
33
34
log = logging.getLogger(__name__)

35

Pierre Dittgen's avatar
Pierre Dittgen committed
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# Get badge configuration file url from environment variable
badge_config = None
badge_config_url = os.environ.get('BADGE_CONFIG_URL')
if badge_config_url is None:
    log.warning("BADGE_CONFIG_URL environment variable is not set")
else:
    req = requests.get(badge_config_url)
    if not req.ok:
        log.warning("Can't retrieve badge config from [%s]", badge_config_url)
    else:
        badge_config = toml.loads(req.text)

# Gets shields io url from environment variable
shields_io_url = os.environ.get('SHIELDS_IO_URL')
if shields_io_url is None:
    shields_io_url = 'https://img.shields.io/'
elif not shields_io_url.endswith('/'):
    shields_io_url += '/'


56
def extract_source_data(source: ValidataSource, preview_rows_nb=5):
57
    """ Computes table preview """
58
59
60

    def stringify(val):
        """ Transform value into string """
Pierre Dittgen's avatar
Pierre Dittgen committed
61
        return '' if val is None else str(val)
62

63
64
    header = None
    rows = []
Pierre Dittgen's avatar
Pierre Dittgen committed
65
    nb_rows = 0
66

67
    options = {}
68
    if source.format == "csv":
69
        options['delimiter'] = csv_helpers.detect_dialect(source.source, format=source.format, scheme=source.scheme,
70
                                                          custom_loaders=custom_loaders).delimiter
71
    with tabulator.Stream(source.source, format=source.format, scheme=source.scheme, custom_loaders=custom_loaders,
72
                          **options) as stream:
73
74
        for row in stream:
            if header is None:
75
                header = ['' if v is None else v for v in row]
76
            else:
77
                rows.append(list(map(stringify, row)))
Pierre Dittgen's avatar
Pierre Dittgen committed
78
                nb_rows += 1
79
    preview_rows_nb = min(preview_rows_nb, nb_rows)
80
81
    return {'header': header,
            'rows_nb': nb_rows,
82
83
84
            'data_rows': rows,
            'preview_rows_nb': preview_rows_nb,
            'preview_rows': rows[:preview_rows_nb]}
85
86


Pierre Dittgen's avatar
Pierre Dittgen committed
87
88
def improve_errors(errors):
    """Add context to errors, converts markdown content to HTML"""
89

Pierre Dittgen's avatar
Pierre Dittgen committed
90
91
    def improve_err(err):
        """Adds context info based on row-nb presence and converts content to HTML"""
92

Pierre Dittgen's avatar
Pierre Dittgen committed
93
94
95
96
        # Context
        update_keys = {
            'context': 'body' if 'row-number' in err and not err['row-number'] is None else 'table',
        }
Pierre Dittgen's avatar
Pierre Dittgen committed
97

Pierre Dittgen's avatar
Pierre Dittgen committed
98
        # markdown to HTML (with default values for 'title' and 'content')
Pierre Dittgen's avatar
Pierre Dittgen committed
99

Pierre Dittgen's avatar
Pierre Dittgen committed
100
101
102
        # Set default title if no title
        if not 'title' in err:
            update_keys['title'] = '[{}]'.format(err['code'])
Pierre Dittgen's avatar
Pierre Dittgen committed
103

Pierre Dittgen's avatar
Pierre Dittgen committed
104
105
106
107
        # Convert message to markdown only if no content
        # => for pre-checks errors
        if 'message' in err and not 'content' in err:
            update_keys['message'] = commonmark(err['message'])
Pierre Dittgen's avatar
Pierre Dittgen committed
108

Pierre Dittgen's avatar
Pierre Dittgen committed
109
110
111
        # Else, default message
        elif not 'message' in err or err['message'] is None:
            update_keys['message'] = '[{}]'.format(err['code'])
Pierre Dittgen's avatar
Pierre Dittgen committed
112

Pierre Dittgen's avatar
Pierre Dittgen committed
113
114
115
        # Message content
        md_content = '*content soon available*' if not 'content' in err else err['content']
        update_keys['content'] = commonmark(md_content)
116

Pierre Dittgen's avatar
Pierre Dittgen committed
117
        return {**err, **update_keys}
118

Pierre Dittgen's avatar
Pierre Dittgen committed
119
    return list(map(improve_err, errors))
120
121


Pierre Dittgen's avatar
Pierre Dittgen committed
122
def create_validata_ui_report(validata_core_report, schema):
123
124
125
126
127
128
    """ Creates an error report easier to handle and display in templates:
        - only one table
        - errors are contextualized
        - error-counts is ok
        - errors are grouped by lines
        - errors are separated into "structure" and "body"
129
        - error messages are improved
130
    """
Pierre Dittgen's avatar
Pierre Dittgen committed
131
    report = copy.deepcopy(validata_core_report)
132
133
134
135
136
137
138
139
140

    # One table is enough
    del report['table-count']
    report['table'] = report['tables'][0]
    del report['tables']
    del report['table']['error-count']
    del report['table']['time']
    del report['table']['valid']
    del report['valid']
141
142
143
    # use _ instead of - to ease information picking in jinja2 template
    report['table']['row_count'] = report['table']['row-count']

Pierre Dittgen's avatar
Pierre Dittgen committed
144
145
146
147
    # Handy col_count info
    headers = report['table'].get('headers', [])
    report['table']['col_count'] = len(headers)

Pierre Dittgen's avatar
Pierre Dittgen committed
148
    # Computes column info
149
    schema_fields = schema.get('fields', [])
Pierre Dittgen's avatar
Pierre Dittgen committed
150
151
152
153
    fields_dict = {f['name']: (f.get('title', 'titre non défini'), f.get('description', '')) for f in schema_fields}
    report['table']['headers_title'] = [fields_dict[h][0] if h in fields_dict else 'colonne inconnue' for h in headers]
    report['table']['headers_description'] = [fields_dict[h][1]
                                              if h in fields_dict else 'Cette colonne n\'est pas définie dans le schema' for h in headers]
154

155
    # Provide better (french) messages
Pierre Dittgen's avatar
Pierre Dittgen committed
156
157
    errors = improve_errors(report['table']['errors'])
    del report['table']['errors']
158

159
160
161
162
163
164
165
    # Count errors
    report['error_count'] = len(errors)
    del report['error-count']

    # Then group them in 2 groups : structure and body
    report['table']['errors'] = {'structure': [], 'body': []}
    for err in errors:
166
        if err['tag'] == 'structure':
167
168
169
170
            report['table']['errors']['structure'].append(err)
        else:
            report['table']['errors']['body'].append(err)

Pierre Dittgen's avatar
Pierre Dittgen committed
171
    # Checks if there are structure errors different to invalid-column-delimiter
Pierre Dittgen's avatar
Pierre Dittgen committed
172
173
174
    structure_errors = report['table']['errors']['structure']
    report['table']['do_display_body_errors'] = len(structure_errors) == 0 or \
        all(err['code'] == 'invalid-column-delimiter' for err in structure_errors)
175

Pierre Dittgen's avatar
Pierre Dittgen committed
176
177
178
179
180
181
182
183
184
    # Checks if a column comparison is needed
    header_errors = ('missing-headers', 'extra-headers', 'wrong-headers-order')
    structure_errors = [{**err, 'in_column_comp': err['code'] in header_errors} for err in structure_errors]
    report['table']['errors']['structure'] = structure_errors
    column_comparison_needed = any(err['in_column_comp'] == True for err in structure_errors)
    column_comparison_table = []
    if column_comparison_needed:
        column_comparison_table = []
        field_names = [f['name'] for f in schema_fields]
185
        has_case_errors = False
Pierre Dittgen's avatar
Pierre Dittgen committed
186
187
        for t in itertools.zip_longest(headers, field_names, fillvalue=''):
            status = 'ok' if t[0] == t[1] else 'ko'
188
189
            if not has_case_errors and status == 'ko' and t[0].lower() == t[1].lower():
                has_case_errors = True
Pierre Dittgen's avatar
Pierre Dittgen committed
190
            column_comparison_table.append((*t, status))
191
192
193
194
195
        info = {}
        info['table'] = column_comparison_table
        info['has_missing'] = len(headers) < len(field_names)
        info['has_case_errors'] = has_case_errors
        report['table']['column_comparison_info'] = info
Pierre Dittgen's avatar
Pierre Dittgen committed
196
197
    report['table']['column_comparison_needed'] = column_comparison_needed

Pierre Dittgen's avatar
Pierre Dittgen committed
198
199
200
201
    # Group body errors by row id
    rows = []
    current_row_id = 0
    for err in report['table']['errors']['body']:
202
203
        if not 'row-number' in err:
            print('ERR', err)
Pierre Dittgen's avatar
Pierre Dittgen committed
204
205
206
207
208
209
210
211
212
213
214
215
216
        row_id = err['row-number']
        del err['row-number']
        del err['context']
        if row_id != current_row_id:
            current_row_id = row_id
            rows.append({'row_id': current_row_id, 'errors': {}})

        column_id = err.get('column-number')
        if column_id is not None:
            del err['column-number']
            rows[-1]['errors'][column_id] = err
        else:
            rows[-1]['errors']['row'] = err
Pierre Dittgen's avatar
Pierre Dittgen committed
217
    report['table']['errors']['body_by_rows'] = rows
Pierre Dittgen's avatar
Pierre Dittgen committed
218

219
220
221
222
223
224
225
226
227
    # Sort by error names in statistics
    stats = report['table']['error-stats']
    code_title_map = messages.ERROR_MESSAGE_DEFAULT_TITLE
    for key in ('structure-errors', 'value-errors'):
        # convert dict into tuples with french title instead of error code
        # and sorts by title
        stats[key]['count-by-code'] = sorted([(code_title_map.get(k, k), v) for k, v in stats[key]['count-by-code'].items()],
                                             key=itemgetter(0))

Pierre Dittgen's avatar
Pierre Dittgen committed
228
229
230
    return report


Pierre Dittgen's avatar
Pierre Dittgen committed
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
def compute_badge_message_and_color(badge):
    """Computes message and color from badge information"""
    structure = badge['structure']
    body = badge.get('body')

    # Bad structure, stop here
    if structure == 'KO':
        return (
            'structure invalide', 'red')

    # No body error
    if body == 'OK':
        return ('structure invalide', 'orange') if structure == 'WARN' else ('valide', 'green')

    # else compute quality ratio percent
    p = (1 - badge['ratio']) * 100.0
    msg = 'cellules valides : {:.1f}%'.format(p)
    return (msg, 'red') if body == 'KO' else (msg, 'orange')


def get_badge_url_and_message(badge):
    """Gets badge url from badge information"""

    msg, color = compute_badge_message_and_color(badge)
    return ('{}static/v1.svg?label=Validata&message={}&color={}'
            .format(shields_io_url, quote_plus(msg), color), msg)


259
def validate(schema_code, source: ValidataSource):
260
261
    """ Validate source and display report """

Pierre Dittgen's avatar
Pierre Dittgen committed
262
    try:
Pierre Dittgen's avatar
Pierre Dittgen committed
263
        validata_core_report = ValidatorHelper.validate(
264
265
            schema_code=schema_code,
            force_strings=True,
266
            **source.get_tabulator_params()
267
        )
268
269
270
271
272
273

        # Validator.validate() doesn't throw FormatError if source.format is None
        # Just do it manually
        if source.format is None:
            raise tabulator.exceptions.FormatError()

Pierre Dittgen's avatar
Pierre Dittgen committed
274
275
276
    except tabulator.exceptions.FormatError:
        flash_error('Erreur : format de fichier non supporté')
        return redirect(url_for('scdl_validator', val_code=schema_code))
277

Pierre Dittgen's avatar
Pierre Dittgen committed
278
279
280
281
    # Computes badge from report and badge configuration
    badge = compute_badge(validata_core_report, badge_config)
    badge_url, badge_msg = get_badge_url_and_message(badge)

282
283
284
285
286
287
288
289
    source_errors = [err for err in validata_core_report['tables'][0]['errors'] if err['code'] == 'source-error']
    if source_errors:
        err = source_errors[0]
        msg = "l'encodage du fichier est invalide. Veuillez le corriger" if 'charmap' in err[
            'message'] else err['message']
        flash_error('Erreur de source : {}'.format(msg))
        return redirect(url_for('scdl_validator', val_code=schema_code))

290
    source_data = extract_source_data(source)
291

Pierre Dittgen's avatar
Pierre Dittgen committed
292
    # handle report date
293
    report_datetime = datetime.fromisoformat(validata_core_report['date']).astimezone()
294

Pierre Dittgen's avatar
Pierre Dittgen committed
295
296
    # Enhance validata_core_report
    validata_report = create_validata_ui_report(validata_core_report, ValidatorHelper.schema(schema_code).descriptor)
Pierre Dittgen's avatar
Pierre Dittgen committed
297

Pierre Dittgen's avatar
Pierre Dittgen committed
298
    # Display report to the user
Pierre Dittgen's avatar
Pierre Dittgen committed
299
    val_info = ValidatorHelper.schema_info(schema_code)
300
    return render_template('validation_report.html', title='Rapport de validation',
301
                           val_info=ValidatorHelper.schema_info(schema_code), report=validata_report,
302
                           validation_date=report_datetime.strftime('le %d/%m/%Y à %Hh%M'),
303
                           source=source, source_type=source.type, source_data=source_data,
304
                           print_mode=request.args.get('print', 'false') == 'true',
Pierre Dittgen's avatar
Pierre Dittgen committed
305
                           badge_url=badge_url, badge_msg=badge_msg,
306
                           report_str=json.dumps(validata_report, sort_keys=True, indent=2),
Pierre Dittgen's avatar
Pierre Dittgen committed
307
                           breadcrumbs=[{'url': url_for('home'), 'title': 'Accueil'},
Pierre Dittgen's avatar
Pierre Dittgen committed
308
309
                                        {'url': url_for('scdl_validator', val_code=schema_code),
                                         'title': val_info['title']}])
310
311


312
313
314
315
316
317
318
319
def bytes_data(f):
    """ Gets bytes data from Werkzeug FileStorage instance """
    iob = BytesIO()
    f.save(iob)
    iob.seek(0)
    return iob.getvalue()


320
321
322
323
324
325
# Routes


@app.route('/')
def home():
    """ Home page """
Pierre Dittgen's avatar
Pierre Dittgen committed
326
    validators = ValidatorHelper.schema_info_list()
Christophe Benz's avatar
Christophe Benz committed
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
    external_validators = [
        {
            "title": "INSPIRE",
            "description": "proposé par la Commission Européenne pour tester des ressources géographiques (données, services ou métadonnées)",
            "url": "http://inspire-sandbox.jrc.ec.europa.eu/validator/"
        },
        {
            "title": "BAL",
            "description": "proposé par la mission Etalab pour tester des données Adresse produites localement (format BAL 1.1)",
            "url": "https://adresse.data.gouv.fr/bases-locales/validateur"
        },
        {
            "title": "CVDTC",
            "description": "proposé par l'AFIMB dans le cadre du projet Chouette pour tester des données de transport collectif (GTFS ou NEPTUNE)",
            "url": "http://www.conversion-validation-donnees-tc.org/"
        },
    ]
Christophe Benz's avatar
Christophe Benz committed
344
    flash_warning('Ce service est fourni en mode beta - certains problèmes peuvent subsister - nous mettons tout en œuvre pour améliorer son fonctionnement en continu.')
Christophe Benz's avatar
Christophe Benz committed
345
    return render_template('home.html', title='Accueil', validators=validators, external_validators=external_validators)
346
347
348
349
350
351
352
353


@app.route('/validators')
def validators():
    """ No validators page """
    return redirect(url_for('home'))


354
355
356
@app.route('/pdf/<val_code>')
def pdf_report(val_code):
    """PDF report generation"""
357
    err_prefix = 'Erreur de génération du rapport PDF'
358
359

    if not ValidatorHelper.schema_exist(val_code):
360
361
        flash_error(err_prefix + ': schéma inconnu')
        return redirect(url_for('scdl_validator', val_code=val_code))
362
363
364

    url_param = request.args.get('url')
    if not url_param:
365
366
        flash_error(err_prefix + ': URL non fournie')
        return redirect(url_for('scdl_validator', val_code=val_code))
367
368
369
370

    validation_url = '{}?input=url&print=true&url={}'.format(url_for('scdl_validator', val_code=val_code, _external=True),
                                                             quote_plus(url_param))

Christophe Benz's avatar
Christophe Benz committed
371
372
    with tempfile.NamedTemporaryFile(prefix='validata_{}_report_'.format(val_code), suffix='.pdf') as tmpfile:
        tmp_pdf_report = Path(tmpfile.name)
373
374
375
376
377

    cmd = ['chromium', '--headless', '--disable-gpu',
           '--print-to-pdf={}'.format(str(tmp_pdf_report)), validation_url]
    result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    if result.returncode != 0:
378
379
        flash_error(err_prefix)
        log.error("Command %r returned an error: %r", cmd, result.stdout.decode('utf-8'))
380
381
        if tmp_pdf_report.exists():
            tmp_pdf_report.unlink()
382
        return redirect(url_for('scdl_validator', val_code=val_code))
383

Pierre Dittgen's avatar
Pierre Dittgen committed
384
385
    pdf_filename = 'Rapport de validation {} {}.pdf'.format(val_code,
                                                            datetime.now().strftime('%d-%m-%Y %Hh%M'))
Christophe Benz's avatar
Christophe Benz committed
386
    response = make_response(tmp_pdf_report.read_bytes())
Pierre Dittgen's avatar
Pierre Dittgen committed
387
    response.headers.set('Content-disposition', 'attachment', filename=pdf_filename)
388
389
390
391
392
393
394
395
    response.headers.set('Content-type', 'application/pdf')
    response.headers.set('Content-length', tmp_pdf_report.stat().st_size)

    tmp_pdf_report.unlink()

    return response


396
397
398
399
400
401
402
403
404
405
@app.route('/validators/<val_code>', methods=['GET', 'POST'])
def scdl_validator(val_code):
    """ Validator page """

    if not ValidatorHelper.schema_exist(val_code):
        flash_error('Validateur [{}] inconnu'.format(val_code))
        return redirect(url_for('home'))

    if request.method == 'GET':

Pierre Dittgen's avatar
Pierre Dittgen committed
406
        val_info = ValidatorHelper.schema_info(val_code)
407
408
409
410
        input_param = request.args.get('input')

        # First form display
        if input_param is None or input_param not in ('url', 'example'):
411
            return render_template('validation_form.html', title=val_info['title'],
412
413
414
415
416
                                   val_info=val_info,
                                   breadcrumbs=[{'url': url_for('home'), 'title': 'Accueil'}, ])

        # Process URL
        else:
417
418
            url_param = request.args.get('url')
            if url_param is None or url_param == '':
419
420
                flash_error("Vous n'avez pas indiqué d'url à valider")
                return redirect(url_for('scdl_validator', val_code=val_code))
421
422
            try:
                return validate(val_code, ValidataSource('url', url_param, url_param))
423
424
425
426
            except tabulator.exceptions.FormatError as e:
                flash_error('Erreur : Format de ressource non supporté')
                log.info(e)
                return redirect(url_for('scdl_validator', val_code=val_code))
427
428
429
430
            except tabulator.exceptions.HTTPError as e:
                flash_error('Erreur : impossible d\'accéder au fichier source en ligne')
                log.info(e)
                return redirect(url_for('scdl_validator', val_code=val_code))
431
432
433
434

    else:  # POST
        input_param = request.form.get('input')
        if input_param is None:
Pierre Dittgen's avatar
Pierre Dittgen committed
435
            flash_error('Aucun fichier à valider')
436
437
438
439
440
441
442
443
            return redirect(url_for('scdl_validator', val_code=val_code))

        # File validation
        if input_param == 'file':
            f = request.files.get('file')
            if f is None:
                flash_warning("Vous n'avez pas indiqué de fichier à valider")
                return redirect(url_for('scdl_validator', val_code=val_code))
444

445
            return validate(val_code, ValidataSource('file', f.filename, bytes_data(f)))
446
447

        return 'Bizarre, vous avez dit bizarre ?'