-
Notifications
You must be signed in to change notification settings - Fork 8
/
core.py
1148 lines (972 loc) · 47.2 KB
/
core.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 -*-
"""Módulo principal de pydatajson
Contiene la clase DataJson que reúne los métodos públicos para trabajar con
archivos data.json.
"""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import with_statement
import json
import logging
import os.path
import sys
from collections import OrderedDict
from datetime import datetime
from openpyxl.styles import Alignment, Font
from six import string_types, iteritems
from six.moves.urllib_parse import urljoin
from pydatajson.response_formatters import format_response
from pydatajson.validation import Validator, \
DEFAULT_CATALOG_SCHEMA_FILENAME, ABSOLUTE_SCHEMA_DIR
from . import backup
from . import catalog_readme
from . import documentation, constants
from . import federation
from . import helpers
from . import indicators
from . import readers
from . import search
from . import time_series
from . import transformation
from . import writers
logger = logging.getLogger('pydatajson')
ABSOLUTE_PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))
CENTRAL_CATALOG = "http://datos.gob.ar/data.json"
MIN_DATASET_TITLE = 10
MIN_DATASET_DESCRIPTION = 20
class DataJson(dict):
"""Objeto que representa un catálogo de activos de datos."""
# Variables por default
CATALOG_FIELDS_PATH = os.path.join(ABSOLUTE_PROJECT_DIR, "fields")
def __init__(self, catalog=None, schema_filename=None, schema_dir=None,
default_values=None, catalog_format=None,
validator_class=Validator, verify_ssl=False,
requests_timeout=constants.REQUESTS_TIMEOUT,
url_check_timeout=constants.DEFAULT_CHECK_TIMEOUT):
"""Lee un catálogo y crea un objeto con funciones para manipularlo.
Salvo que se indique lo contrario, se utiliza como default el schema
de la versión 1.1 del Perfil de Metadatos de Argentina.
Args:
catalog (dict or str): Representación externa/interna de un
catálogo. Una representación _externa_ es un path local o una
URL remota a un archivo con la metadata de un catálogo, en
formato JSON o XLSX. La representación _interna_ de un catálogo
es un diccionario. Ejemplos: http://datos.gob.ar/data.json,
http://www.ign.gob.ar/descargas/geodatos/catalog.xlsx,
"/energia/catalog.xlsx".
schema_filename (str): Nombre del archivo que contiene el esquema
validador.
schema_dir (str): Directorio (absoluto) donde se encuentra el
esquema validador (y sus referencias, de tenerlas).
default_values (dict): Valores default para algunos de los campos
del catálogo::
{
"dataset_issued": "2017-06-22",
"distribution_issued": "2017-06-22"
}
"""
self.verify_ssl = verify_ssl
self.requests_timeout = requests_timeout
self.url_check_timeout = url_check_timeout
# se construye el objeto DataJson con la interfaz de un dicconario
if catalog:
# lee representaciones de un catálogo hacia un diccionario
catalog = readers.read_catalog(catalog,
default_values=default_values,
catalog_format=catalog_format,
verify=self.verify_ssl,
timeout=self.requests_timeout)
# copia todos los atributos del diccionario hacia el objeto
for key, value in iteritems(catalog):
self[key] = value
self.has_catalog = True
# indexa los ids de datasets, distribuciones y fields
self._build_index()
else:
self.has_catalog = False
schema_filename = schema_filename or DEFAULT_CATALOG_SCHEMA_FILENAME
schema_dir = schema_dir or ABSOLUTE_SCHEMA_DIR
self.validator = validator_class(schema_filename, schema_dir)
# asigno docstrings de los métodos modularizados
fn_doc = indicators.generate_catalogs_indicators.__doc__
self.generate_catalogs_indicators.__func__.__doc__ = fn_doc
# metodos para buscar entidades cuando DataJson tiene catalogo cargado
get_themes = search.get_themes
themes = property(get_themes)
get_datasets = search.get_datasets
datasets = property(get_datasets)
get_distributions = search.get_distributions
distributions = property(get_distributions)
get_fields = search.get_fields
fields = property(get_fields)
get_time_series = search.get_time_series
time_series = property(get_time_series)
get_dataset = search.get_dataset
get_distribution = search.get_distribution
get_field = search.get_field
get_theme = search.get_theme
get_field_location = search.get_field_location
get_catalog_metadata = search.get_catalog_metadata
# metodos para realizar operaciones de transformación de metadatos
generate_distribution_ids = transformation.generate_distribution_ids
# metodos para guardar el catálogo en otros formatos
to_xlsx = writers.write_xlsx_catalog
to_json = writers.write_json_catalog
# metodos para generar indicadores
generate_indicators = indicators.generate_indicators
# metodos para hacer backups
make_catalog_backup = backup.make_catalog_backup
# metodos para interactuar con un portal de CKAN
push_dataset_to_ckan = federation.push_dataset_to_ckan
harvest_dataset_to_ckan = federation.harvest_dataset_to_ckan
restore_dataset_to_ckan = federation.restore_dataset_to_ckan
harvest_catalog_to_ckan = federation.harvest_catalog_to_ckan
restore_catalog_to_ckan = federation.restore_catalog_to_ckan
restore_organization_to_ckan = federation.restore_organization_to_ckan
restore_organizations_to_ckan = federation.restore_organizations_to_ckan
push_theme_to_ckan = federation.push_theme_to_ckan
push_new_themes = federation.push_new_themes
remove_harvested_ds_from_ckan = federation.remove_harvested_ds_from_ckan
# metodos de README
generate_catalog_readme = catalog_readme.generate_catalog_readme
def _build_index(self):
"""Itera todos los datasets, distribucioens y fields indexandolos."""
datasets_index = {}
distributions_index = {}
fields_index = {}
# recorre todos los datasets
for dataset_index, dataset in enumerate(self.datasets):
if "identifier" in dataset:
datasets_index[dataset["identifier"]] = {
"dataset_index": dataset_index
}
# recorre las distribuciones del dataset
for distribution_index, distribution in enumerate(
dataset.get("distribution", [])):
if "identifier" in distribution:
distributions_index[distribution["identifier"]] = {
"distribution_index": distribution_index,
"dataset_identifier": dataset["identifier"]
}
# recorre los fields de la distribucion
for field_index, field in enumerate(
distribution.get("field", [])):
if "id" in field:
fields_index[field["id"]] = {
"field_index":
field_index,
"dataset_identifier":
dataset["identifier"],
"distribution_identifier":
distribution["identifier"]
}
setattr(self, "_distributions_index", distributions_index)
setattr(self, "_datasets_index", datasets_index)
setattr(self, "_fields_index", fields_index)
def get_distribution_time_index(self, distribution):
if isinstance(distribution, dict):
distribution = distribution
else:
distribution = self.get_distribution(distribution)
return time_series.get_distribution_time_index(distribution)
def get_distribution_time_index_frequency(self, distribution):
if isinstance(distribution, dict):
distribution = distribution
else:
distribution = self.get_distribution(distribution)
return time_series.get_distribution_time_index_frequency(distribution)
def remove_dataset(self, identifier):
for index, dataset in enumerate(self["dataset"]):
if dataset["identifier"] == identifier:
self["dataset"].pop(index)
logger.info("Dataset {} en posicion {} fue eliminado.".format(
identifier, index))
return
logger.warning("No se encontro el dataset {}.".format(identifier))
def remove_distribution(self, identifier, dataset_identifier=None):
for dataset in self["dataset"]:
for index, distribution in enumerate(dataset["distribution"]):
if (distribution["identifier"] == identifier and
(not dataset_identifier or
dataset["identifier"] == dataset_identifier)):
dataset["distribution"].pop(index)
logger.info("Distribution {} del dataset {}"
"en posicion {} fue eliminada.".format(
identifier, dataset["identifier"], index))
return
logger.warning("No se encontro la distribucion {}.".format(identifier))
def is_valid_catalog(self, catalog=None, broken_links=False):
"""Valida que un archivo `data.json` cumpla con el schema definido.
Chequea que el data.json tiene todos los campos obligatorios y que
tanto los campos obligatorios como los opcionales siguen la estructura
definida en el schema.
Args:
catalog (str o dict): Catálogo (dict, JSON o XLSX) a ser validado.
Si no se pasa, valida este catálogo.
broken_links(bool): Activa el checkeo de estados de urls
Returns:
bool: True si el data.json cumple con el schema, sino False.
"""
catalog = self._read_catalog(catalog) if catalog else self
return self.validator.is_valid(
catalog, broken_links=broken_links, verify_ssl=self.verify_ssl,
url_check_timeout=self.url_check_timeout)
@staticmethod
def _update_validation_response(error, response):
"""Actualiza la respuesta por default acorde a un error de
validación."""
new_response = response.copy()
# El status del catálogo entero será ERROR
new_response["status"] = "ERROR"
# Adapto la información del ValidationError recibido a los fines
# del validador de DataJsons
error_info = {
# Error Code 1 para "campo obligatorio faltante"
# Error Code 2 para "error en tipo o formato de campo"
"error_code": 1 if error.validator == "required" else 2,
"message": error.message,
"validator": error.validator,
"validator_value": error.validator_value,
"path": list(error.path),
# La instancia validada es irrelevante si el error es de tipo 1
"instance": (None if error.validator == "required" else
error.instance)
}
# Identifico a qué nivel de jerarquía sucedió el error.
if len(error.path) >= 2 and error.path[0] == "dataset":
# El error está a nivel de un dataset particular o inferior
position = new_response["error"]["dataset"][error.path[1]]
else:
# El error está a nivel de catálogo
position = new_response["error"]["catalog"]
position["status"] = "ERROR"
position["errors"].append(error_info)
return new_response
def validate_catalog(self, catalog=None, only_errors=False, fmt="dict",
export_path=None, broken_links=False):
"""Analiza un data.json registrando los errores que encuentra.
Chequea que el data.json tiene todos los campos obligatorios y que
tanto los campos obligatorios como los opcionales siguen la estructura
definida en el schema.
Args:
catalog (str o dict): Catálogo (dict, JSON o XLSX) a ser validado.
Si no se pasa, valida este catálogo.
only_errors (bool): Si es True sólo se reportan los errores.
fmt (str): Indica el formato en el que se desea el reporte.
"dict" es el reporte más verborrágico respetando la
estructura del data.json.
"list" devuelve un dict con listas de errores formateados para
generar tablas.
export_path (str): Path donde exportar el reporte generado (en
formato XLSX o CSV). Si se especifica, el método no devolverá
nada, a pesar de que se pase algún argumento en `fmt`.
Returns:
dict: Diccionario resumen de los errores encontrados::
{
"status": "OK", # resultado de la validación global
"error": {
"catalog": {
"status": "OK",
"errors": []
"title": "Título Catalog"},
"dataset": [
{
"status": "OK",
"errors": [],
"title": "Titulo Dataset 1"
},
{
"status": "ERROR",
"errors": [error1_info, error2_info, ...],
"title": "Titulo Dataset 2"
}
]
}
}
Donde errorN_info es un dict con la información del N-ésimo
error encontrado, con las siguientes claves: "path", "instance",
"message", "validator", "validator_value", "error_code".
"""
catalog = self._read_catalog(catalog) if catalog else self
validation = self.validator.validate_catalog(
catalog, only_errors, broken_links, self.verify_ssl,
self.url_check_timeout)
if export_path:
fmt = 'table'
return format_response(validation, export_path, fmt)
@staticmethod
def _stringify_list(str_or_list):
if isinstance(str_or_list, list):
strings = [s for s in str_or_list
if isinstance(s, string_types)]
stringified_list = ", ".join(strings)
elif isinstance(str_or_list, string_types):
stringified_list = str_or_list
else:
stringified_list = None
return stringified_list
@classmethod
def _dataset_report_helper(cls, dataset, catalog_homepage=None):
"""Toma un dict con la metadata de un dataset, y devuelve un dict coni
los valores que dataset_report() usa para reportar sobre él.
Args:
dataset (dict): Diccionario con la metadata de un dataset.
Returns:
dict: Diccionario con los campos a nivel dataset que requiere
dataset_report().
"""
publisher_name = helpers.traverse_dict(dataset, ["publisher", "name"])
languages = cls._stringify_list(dataset.get("language"))
super_themes = cls._stringify_list(dataset.get("superTheme"))
themes = cls._stringify_list(dataset.get("theme"))
def _stringify_distribution(distribution):
title = distribution.get("title")
url = distribution.get("downloadURL")
return "\"{}\": {}".format(title, url)
distributions = [d for d in dataset["distribution"]
if isinstance(d, dict)]
# crea lista de distribuciones
distributions_list = None
if isinstance(distributions, list):
distributions_strings = [
_stringify_distribution(d) for d in distributions
]
distributions_list = "\n\n".join(distributions_strings)
# crea lista de formatos
distributions_formats = json.dumps(
helpers.count_distribution_formats_dataset(dataset))
fields = OrderedDict()
fields["dataset_identifier"] = dataset.get("identifier")
fields["dataset_title"] = dataset.get("title")
fields["dataset_accrualPeriodicity"] = dataset.get(
"accrualPeriodicity")
fields["dataset_description"] = dataset.get("description")
fields["dataset_publisher_name"] = publisher_name
fields["dataset_superTheme"] = super_themes
fields["dataset_theme"] = themes
fields["dataset_landingPage"] = dataset.get("landingPage")
fields["dataset_landingPage_generated"] = cls._generate_landingPage(
catalog_homepage, dataset.get("identifier")
)
fields["dataset_issued"] = dataset.get("issued")
fields["dataset_modified"] = dataset.get("modified")
fields["distributions_formats"] = distributions_formats
fields["distributions_list"] = distributions_list
fields["dataset_license"] = dataset.get("license")
fields["dataset_language"] = languages
fields["dataset_spatial"] = dataset.get("spatial")
fields["dataset_temporal"] = dataset.get("temporal")
return fields
@classmethod
def _generate_landingPage(cls, catalog_homepage, dataset_identifier):
return urljoin(catalog_homepage,
"dataset/{}".format(dataset_identifier))
@staticmethod
def _catalog_report_helper(catalog, catalog_validation, url, catalog_id,
catalog_org):
"""Toma un dict con la metadata de un catálogo, y devuelve un dict con
los valores que catalog_report() usa para reportar sobre él.
Args:
catalog (dict): Diccionario con la metadata de un catálogo.
validation (dict): Resultado, únicamente a nivel catálogo, de la
validación completa de `catalog`.
Returns:
dict: Diccionario con los campos a nivel catálogo que requiere
catalog_report().
"""
fields = OrderedDict()
fields["catalog_metadata_url"] = url
fields["catalog_federation_id"] = catalog_id
fields["catalog_federation_org"] = catalog_org
fields["catalog_title"] = catalog.get("title")
fields["catalog_description"] = catalog.get("description")
fields["valid_catalog_metadata"] = (
1 if catalog_validation["status"] == "OK" else 0)
return fields
def _dataset_report(
self, dataset, dataset_validation, dataset_index,
catalog_fields, harvest='none', report=None, catalog_homepage=None
):
""" Genera una línea del `catalog_report`, correspondiente a un dataset
de los que conforman el catálogo analizado."""
# hace un breve análisis de qa al dataset
good_qa, notes = self._dataset_qa(dataset)
dataset_report = OrderedDict(catalog_fields)
dataset_report["valid_dataset_metadata"] = (
1 if dataset_validation["status"] == "OK" else 0)
dataset_report["dataset_index"] = dataset_index
if isinstance(harvest, list):
dataset_report["harvest"] = 1 if dataset["title"] in harvest else 0
elif harvest == 'all':
dataset_report["harvest"] = 1
elif harvest == 'none':
dataset_report["harvest"] = 0
elif harvest == 'valid':
dataset_report["harvest"] = (
int(dataset_report["valid_dataset_metadata"]))
elif harvest == 'good':
valid_metadata = int(dataset_report["valid_dataset_metadata"]) == 1
dataset_report["harvest"] = 1 if valid_metadata and good_qa else 0
elif harvest == 'report':
if not report:
raise ValueError("""
Usted eligio 'report' como criterio de harvest, pero no proveyo un valor para
el argumento 'report'. Por favor, intentelo nuevamente.""")
datasets_to_harvest = self._extract_datasets_to_harvest(report)
dataset_report["harvest"] = (
1 if (dataset_report["catalog_metadata_url"],
dataset.get("title")) in datasets_to_harvest
else 0)
else:
raise ValueError("""
{} no es un criterio de harvest reconocido. Pruebe con 'all', 'none', 'valid' o
'report'.""".format(harvest))
dataset_report.update(
self._dataset_report_helper(
dataset, catalog_homepage=catalog_homepage)
)
dataset_report["notas"] = "\n\n".join(notes)
return dataset_report.copy()
def _dataset_qa(self, dataset):
"""Chequea si el dataset tiene una calidad mínima para cosechar."""
# 1. VALIDACIONES
# chequea que haya por lo menos algún formato de datos reconocido
has_data_format = helpers.dataset_has_data_distributions(dataset)
# chequea que algunos campos tengan longitudes mínimas
has_title = "title" in dataset
has_description = "description" in dataset
if has_title:
has_min_title = len(dataset["title"]) >= MIN_DATASET_TITLE
else:
has_min_title = False
if has_description:
has_min_desc = len(
dataset["description"]) >= MIN_DATASET_DESCRIPTION
else:
has_min_desc = False
# 2. EVALUACION DE COSECHA: evalua si se cosecha o no el dataset
harvest = (has_title and has_description and
has_data_format and has_min_title and has_min_desc)
# 3. NOTAS: genera notas de validación
notes = []
if not has_data_format:
notes.append("No tiene distribuciones con datos.")
if not has_title:
notes.append("Dataset sin titulo {}".format(dataset))
else:
if not has_min_title:
notes.append("Titulo tiene menos de {} caracteres".format(
MIN_DATASET_TITLE))
if not has_description:
notes.append("Dataset sin descripcion {}".format(dataset))
else:
if not has_min_desc:
notes.append("Descripcion tiene menos de {} caracteres".format(
MIN_DATASET_DESCRIPTION))
return harvest, notes
def catalog_report(self, catalog, harvest='none', report=None,
catalog_id=None, catalog_homepage=None,
catalog_org=None):
"""Genera un reporte sobre los datasets de un único catálogo.
Args:
catalog (dict, str o unicode): Representación externa (path/URL) o
interna (dict) de un catálogo.
harvest (str): Criterio de cosecha ('all', 'none',
'valid', 'report' o 'good').
Returns:
list: Lista de diccionarios, con un elemento por cada dataset
presente en `catalog`.
"""
url = catalog if isinstance(catalog, string_types) else None
catalog = self._read_catalog(catalog)
validation = self.validate_catalog(catalog)
catalog_validation = validation["error"]["catalog"]
datasets_validations = validation["error"]["dataset"]
catalog_fields = self._catalog_report_helper(
catalog, catalog_validation, url, catalog_id, catalog_org
)
if "dataset" in catalog and isinstance(catalog["dataset"], list):
datasets = [d if isinstance(d, dict) else {} for d in
catalog["dataset"]]
else:
datasets = []
catalog_report = [
self._dataset_report(
dataset, datasets_validations[index], index,
catalog_fields, harvest, report=report,
catalog_homepage=catalog_homepage
)
for index, dataset in enumerate(datasets)
]
return catalog_report
def generate_datasets_report(
self, catalogs, harvest='valid', report=None,
export_path=None, catalog_ids=None, catalog_homepages=None,
catalog_orgs=None
):
"""Genera un reporte sobre las condiciones de la metadata de los
datasets contenidos en uno o varios catálogos.
Args:
catalogs (str, dict o list): Uno (str o dict) o varios (list de
strs y/o dicts) catálogos.
harvest (str): Criterio a utilizar para determinar el valor del
campo "harvest" en el reporte generado ('all', 'none',
'valid', 'report' o 'good').
report (str): Path a un reporte/config especificando qué
datasets marcar con harvest=1 (sólo si harvest=='report').
export_path (str): Path donde exportar el reporte generado (en
formato XLSX o CSV). Si se especifica, el método no devolverá
nada.
catalog_id (str): Nombre identificador del catálogo para federación
catalog_homepage (str): URL del portal de datos donde está
implementado el catálogo. Sólo se pasa si el portal es un CKAN
o respeta la estructura:
https://datos.{organismo}.gob.ar/dataset/{dataset_identifier}
Returns:
list: Contiene tantos dicts como datasets estén presentes en
`catalogs`, con la data del reporte generado.
"""
assert isinstance(catalogs, string_types + (dict, list))
if isinstance(catalogs, list):
assert not catalog_ids or len(catalogs) == len(catalog_ids)
assert not catalog_orgs or len(catalogs) == len(catalog_orgs)
assert not catalog_homepages or len(
catalogs) == len(catalog_homepages)
# Si se pasa un único catálogo, genero una lista que lo contenga
if isinstance(catalogs, string_types + (dict,)):
catalogs = [catalogs]
# convierto los catalogos a objetos DataJson
catalogs = list(map(readers.read_catalog_obj, catalogs))
if not catalog_ids:
catalog_ids = []
for catalog in catalogs:
catalog_ids.append(catalog.get("identifier", ""))
if isinstance(catalog_ids, string_types + (dict,)):
catalog_ids = [catalog_ids] * len(catalogs)
if not catalog_orgs or \
isinstance(catalog_orgs, string_types + (dict,)):
catalog_orgs = [catalog_orgs] * len(catalogs)
if not catalog_homepages or isinstance(catalog_homepages,
string_types + (dict,)):
catalog_homepages = [catalog_homepages] * len(catalogs)
catalogs_reports = [
self.catalog_report(
catalog, harvest, report, catalog_id=catalog_id,
catalog_homepage=catalog_homepage, catalog_org=catalog_org
)
for catalog, catalog_id, catalog_org, catalog_homepage in
zip(catalogs, catalog_ids, catalog_orgs, catalog_homepages)
]
full_report = []
for report in catalogs_reports:
full_report.extend(report)
if export_path:
# config styles para reportes en excel
alignment = Alignment(
wrap_text=True,
shrink_to_fit=True,
vertical="center"
)
column_styles = {
"dataset_title": {"width": 35},
"dataset_description": {"width": 35},
"dataset_publisher_name": {"width": 35},
"dataset_issued": {"width": 20},
"dataset_modified": {"width": 20},
"distributions_formats": {"width": 15},
"distributions_list": {"width": 90},
"notas": {"width": 50},
}
cell_styles = [
{"alignment": Alignment(vertical="center")},
{"row": 1, "font": Font(bold=True)},
{"col": "dataset_title", "alignment": alignment},
{"col": "dataset_description", "alignment": alignment},
{"col": "dataset_publisher_name", "alignment": alignment},
{"col": "distributions_formats", "alignment": alignment},
{"col": "distributions_list", "alignment": alignment},
{"col": "notas", "alignment": alignment},
]
# crea tabla
writers.write_table(table=full_report, path=export_path,
column_styles=column_styles,
cell_styles=cell_styles)
else:
return full_report
def generate_harvester_config(self, catalogs=None, harvest='valid',
report=None, export_path=None):
"""Genera un archivo de configuración del harvester a partir de un
reporte, o de un conjunto de catálogos y un criterio de cosecha
(`harvest`).
Args:
catalogs (str, dict o list): Uno (str o dict) o varios (list de
strs y/o dicts) catálogos.
harvest (str): Criterio para determinar qué datasets incluir en el
archivo de configuración generado ('all', 'none',
'valid', 'report' o 'good').
report (list o str): Tabla de reporte generada por
generate_datasets_report() como lista de diccionarios o archivo
en formato XLSX o CSV. Sólo se usa cuando `harvest=='report'`,
en cuyo caso `catalogs` se ignora.
export_path (str): Path donde exportar el reporte generado (en
formato XLSX o CSV). Si se especifica, el método no devolverá
nada.
Returns:
list of dicts: Un diccionario con variables de configuración
por cada dataset a cosechar.
"""
# Si se pasa un único catálogo, genero una lista que lo contenga
if isinstance(catalogs, string_types + (dict,)):
catalogs = [catalogs]
if harvest == 'report':
if not report:
raise ValueError("""
Usted eligio 'report' como criterio de harvest, pero no proveyo un valor para
el argumento 'report'. Por favor, intentelo nuevamente.""")
datasets_report = readers.read_table(report)
elif harvest in ['valid', 'none', 'all']:
# catalogs no puede faltar para estos criterios
assert isinstance(catalogs, string_types + (dict, list))
datasets_report = self.generate_datasets_report(catalogs, harvest)
else:
raise ValueError("""
{} no es un criterio de harvest reconocido. Pruebe con 'all', 'none', 'valid' o
'report'.""".format(harvest))
# define los campos del reporte que mantiene para el config file
config_keys = [
"catalog_federation_id", "catalog_federation_org",
"dataset_identifier"
]
# cambia algunos nombres de estos campos para el config file
config_translator = {
"catalog_federation_id": "catalog_id",
"catalog_federation_org": "dataset_organization"
}
translated_keys = [config_translator.get(k, k) for k in config_keys]
harvester_config = [
OrderedDict(
# Retengo únicamente los campos que necesita el harvester
[(config_translator.get(k, k), v)
for (k, v) in dataset.items() if k in config_keys]
)
# Para aquellost datasets marcados con 'harvest'==1
for dataset in datasets_report if bool(int(dataset["harvest"]))
]
# chequea que el archivo de configuración tiene todos los campos
required_keys = set(translated_keys)
for row in harvester_config:
row_keys = set(row.keys())
msg = "Hay una fila con claves {} y debe tener claves {}".format(
row_keys, required_keys)
assert row_keys == required_keys, msg
if export_path:
writers.write_table(harvester_config, export_path)
else:
return harvester_config
def generate_harvestable_catalogs(self, catalogs, harvest='all',
report=None, export_path=None):
"""Filtra los catálogos provistos según el criterio determinado en
`harvest`.
Args:
catalogs (str, dict o list): Uno (str o dict) o varios (list de
strs y/o dicts) catálogos.
harvest (str): Criterio para determinar qué datasets conservar de
cada catálogo ('all', 'none', 'valid' o 'report').
report (list o str): Tabla de reporte generada por
generate_datasets_report() como lista de diccionarios o archivo
en formato XLSX o CSV. Sólo se usa cuando `harvest=='report'`.
export_path (str): Path a un archivo JSON o directorio donde
exportar los catálogos filtrados. Si termina en ".json" se
exportará la lista de catálogos a un único archivo. Si es un
directorio, se guardará en él un JSON por catálogo. Si se
especifica `export_path`, el método no devolverá nada.
Returns:
list of dicts: Lista de catálogos.
"""
assert isinstance(catalogs, string_types + (dict, list))
# Si se pasa un único catálogo, genero una lista que lo contenga
if isinstance(catalogs, string_types + (dict,)):
catalogs = [catalogs]
harvestable_catalogs = [self._read_catalog(c) for c in catalogs]
catalogs_urls = [catalog if isinstance(catalog, string_types)
else None for catalog in catalogs]
# aplica los criterios de cosecha
if harvest == 'all':
pass
elif harvest == 'none':
for catalog in harvestable_catalogs:
catalog["dataset"] = []
elif harvest == 'valid':
report = self.generate_datasets_report(catalogs, harvest)
return self.generate_harvestable_catalogs(
catalogs=catalogs, harvest='report', report=report,
export_path=export_path)
elif harvest == 'report':
if not report:
raise ValueError("""
Usted eligio 'report' como criterio de harvest, pero no proveyo un valor para
el argumento 'report'. Por favor, intentelo nuevamente.""")
datasets_to_harvest = self._extract_datasets_to_harvest(report)
for idx_cat, catalog in enumerate(harvestable_catalogs):
catalog_url = catalogs_urls[idx_cat]
if ("dataset" in catalog and
isinstance(catalog["dataset"], list)):
catalog["dataset"] = [
dataset for dataset in catalog["dataset"]
if (catalog_url, dataset.get("title")) in
datasets_to_harvest
]
else:
catalog["dataset"] = []
else:
raise ValueError("""
{} no es un criterio de harvest reconocido. Pruebe con 'all', 'none', 'valid' o
'report'.""".format(harvest))
# devuelve los catálogos harvesteables
if export_path and os.path.isdir(export_path):
# Creo un JSON por catálogo
for idx, catalog in enumerate(harvestable_catalogs):
filename = os.path.join(export_path, "catalog_{}".format(idx))
writers.write_json(catalog, filename)
elif export_path:
# Creo un único JSON con todos los catálogos
writers.write_json(harvestable_catalogs, export_path)
else:
return harvestable_catalogs
def generate_datasets_summary(self, catalog, export_path=None):
"""Genera un informe sobre los datasets presentes en un catálogo,
indicando para cada uno:
- Índice en la lista catalog["dataset"]
- Título
- Identificador
- Cantidad de distribuciones
- Estado de sus metadatos ["OK"|"ERROR"]
Es utilizada por la rutina diaria de `libreria-catalogos` para reportar
sobre los datasets de los catálogos mantenidos.
Args:
catalog (str o dict): Path a un catálogo en cualquier formato,
JSON, XLSX, o diccionario de python.
export_path (str): Path donde exportar el informe generado (en
formato XLSX o CSV). Si se especifica, el método no devolverá
nada.
Returns:
list: Contiene tantos dicts como datasets estén presentes en
`catalogs`, con los datos antes mencionados.
"""
catalog = self._read_catalog(catalog)
# Trato de leer todos los datasets bien formados de la lista
# catalog["dataset"], si existe.
if "dataset" in catalog and isinstance(catalog["dataset"], list):
datasets = [d if isinstance(d, dict) else {} for d in
catalog["dataset"]]
else:
# Si no, considero que no hay datasets presentes
datasets = []
validation = self.validate_catalog(catalog)["error"]["dataset"]
def info_dataset(index, dataset):
"""Recolecta información básica de un dataset."""
info = OrderedDict()
info["indice"] = index
info["titulo"] = dataset.get("title")
info["identificador"] = dataset.get("identifier")
info["estado_metadatos"] = validation[index]["status"]
info["cant_errores"] = len(validation[index]["errors"])
info["cant_distribuciones"] = len(dataset["distribution"])
return info
summary = [info_dataset(i, ds) for i, ds in enumerate(datasets)]
if export_path:
writers.write_table(summary, export_path)
else:
return summary
@classmethod
def _extract_datasets_to_harvest(cls, report):
"""Extrae de un reporte los datos necesarios para reconocer qué
datasets marcar para cosecha en cualquier generador.
Args:
report (str o list): Reporte (lista de dicts) o path a uno.
Returns:
list: Lista de tuplas con los títulos de catálogo y dataset de cada
reporte extraído.
"""
assert isinstance(report, string_types + (list,))
# Si `report` es una lista de tuplas con longitud 2, asumimos que es un
# reporte procesado para extraer los datasets a harvestear. Se devuelve
# intacta.
if (isinstance(report, list) and all([isinstance(x, tuple) and
len(x) == 2 for x in report])):
return report
table = readers.read_table(report)
table_keys = table[0].keys()
expected_keys = ["catalog_metadata_url", "dataset_title",
"dataset_accrualPeriodicity"]
# Verifico la presencia de las claves básicas de un config de harvester
for key in expected_keys:
if key not in table_keys:
raise KeyError("""
El reporte no contiene la clave obligatoria {}. Pruebe con otro archivo.
""".format(key))
if "harvest" in table_keys:
# El archivo es un reporte de datasets.
datasets_to_harvest = [
(row["catalog_metadata_url"], row["dataset_title"]) for row in
table if int(row["harvest"])]
else:
# El archivo es un config de harvester.
datasets_to_harvest = [
(row["catalog_metadata_url"], row["dataset_title"]) for row in
table]
return datasets_to_harvest
def generate_catalogs_indicators(self, catalogs=None,
central_catalog=None,
identifier_search=False,
broken_links=False,
broken_links_threads=1):
catalogs = catalogs or self
return indicators.generate_catalogs_indicators(
catalogs, central_catalog, identifier_search=identifier_search,
validator=self.validator, broken_links=broken_links,
verify_ssl=self.verify_ssl,
url_check_timeout=self.url_check_timeout,
broken_links_threads=broken_links_threads)
def _count_fields_recursive(self, dataset, fields):
"""Cuenta la información de campos optativos/recomendados/requeridos
desde 'fields', y cuenta la ocurrencia de los mismos en 'dataset'.
Args:
dataset (dict): diccionario con claves a ser verificadas.
fields (dict): diccionario con los campos a verificar en dataset
como claves, y 'optativo', 'recomendado', o 'requerido' como
valores. Puede tener objetios anidados pero no arrays.
Returns:
dict: diccionario con las claves 'recomendado', 'optativo',
'requerido', 'recomendado_total', 'optativo_total',
'requerido_total', con la cantidad como valores.
"""
key_count = {
'recomendado': 0,
'optativo': 0,
'requerido': 0,
'total_optativo': 0,
'total_recomendado': 0,
'total_requerido': 0