Last active
October 9, 2017 12:15
-
-
Save amatmv/07c16238284256009e7f0588e04832a3 to your computer and use it in GitHub Desktop.
Update XML with REE comers info with the info of the CNMC
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
import click | |
import csv | |
import re | |
import os | |
import subprocess | |
from xml.etree.ElementTree import Element, SubElement | |
from xml.etree import ElementTree as ET | |
from xml.dom import minidom | |
import sys | |
from fuzzywuzzy import process, utils | |
import unicodedata | |
import difflib | |
import pprint | |
######################################### INFORMATION ############################ | |
# Script that takes the CNMC list of comers in csv format and tries to combine the | |
# information that gives with the XML with the REE information. | |
# The CNMC provides more information and the main goal is to assign the CNMC | |
# identification code to the companies that already are in the XMl | |
### FORMAT OF THE CNMC CSV: | |
# 0 - CODIGO CNMC; | |
# 1 - RAZON SOCIAL; | |
# 2 - DOMICILIO SOCIAL; | |
# 3 - C.P; | |
# 4 - MUNICIPIO; | |
# 5 - PROVINCIA; | |
# 6 - TLF; | |
# 7 - ÁMBITO ACTUACION; | |
# 8 - C.I.F.; | |
# 9 - FECHA INICIO; | |
# 10 - FECHA BAJA; | |
# 11 - PG. WEB | |
MATCHING_MIN_RATIO = 92 | |
AMBIT_CODES = [ | |
'N', # 'Nacional' | |
'P', # 'Peninsular' | |
'AL', # 'Alicante' | |
'AN', # 'Andorra' | |
'AR', # 'Aragón' | |
'B', # 'Barcelona' | |
'CAT', # 'Cataluña' | |
'GE', # 'Gerona' | |
'MU', # 'Murcia' | |
'RI', # 'La Rioja' | |
'T', # 'Tarragona' | |
'V', # 'Comunidad Valenciana' | |
'MM', # 'Mallorca-Menorca' | |
'IF', # 'Ibiza-Formentera' | |
'GC', # 'Gran Canaria' | |
'TF', # 'Tenerife' | |
'FL', # 'Fuerteventura-Lanzarote' | |
'PA', # 'La Palma' | |
'LG', # 'La Gomera' | |
'HI', # 'El Hierro' | |
'CE', # 'Ceuta' | |
'ML', # 'Melilla' | |
] | |
PROVINCIES = { | |
'Albacete': '02', | |
'Alicante': '03', | |
'Almeria': '04', | |
'Álava': '01', | |
'Asturias': '33', | |
'Principado de Asturias': '33', | |
'Badajoz': '06', | |
'Islas Baleares': '07', | |
'Barcelona': '08', | |
'Vizcaya': '48', | |
'Bizkaia': '48', | |
'Burgos': '09', | |
'Cantabria': '39', | |
'Castellón': '12', | |
'Ceuta': '51', | |
'Ciudad Real': '13', | |
'La Coruña': '15', | |
'Cuenca': '16', | |
'Cáceres': '10', | |
'Cádiz': '11', | |
'Córdoba': '14', | |
'Desconocida': '00', | |
'Extranjero': '60', | |
'Guipúzcoa': '20', | |
'Gerona': '17', | |
'Granada': '18', | |
'Guadalajara': '19', | |
'Huelva': '21', | |
'Huesca': '22', | |
'Jaén': '23', | |
'Jaen': '23', | |
'León': '24', | |
'Lérida': '25', | |
'Lugo': '27', | |
'Madrid': '28', | |
'Melilla': '52', | |
'Murcia': '30', | |
'Málaga': '29', | |
'Navarra': '31', | |
'Ourense': '32', | |
'Palencia': '34', | |
'Las Palmas': '35', | |
'Pontevedra': '36', | |
'La Rioja': '26', | |
'Salamanca': '37', | |
'Tenerife': '38', | |
'Santa Cruz de Tenerife': '38', | |
'Segovia': '40', | |
'Sevilla': '41', | |
'Soria': '42', | |
'Tarragona': '43', | |
'Teruel': '44', | |
'Toledo': '45', | |
'Valencia': '46', | |
'Valladolid': '47', | |
'Zamora': '49', | |
'Zaragoza': '50', | |
'Sevila': '05' | |
} | |
@click.command() | |
@click.option( | |
'-i', | |
'--csv-file', | |
default='201709_Listado Comercializadores_CNMC.csv', | |
help=u'Nom del fitxer de la CNMC, en format .csv a parsejar per a actualitzar la informació de les comercialitzadores. Default: "201509_Listado Comercializadores_CNMC.csv"' | |
) | |
@click.option( | |
'-f', | |
'--xml-file', | |
default='res_participant_comer_data.xml', | |
help=u'Nom del fitxer de la CNMC, en format .csv a parsejar. Default: "201509_Listado Comercializadores_CNMC.csv"' | |
) | |
@click.option( | |
'-o', | |
'--output-xml', | |
default='res_participant_comer_data.xml', | |
help=u'Nom del fitxer de sortida on anirà, en format XML, la informació de les comercialitzadores. Default: "res_participant_comer_data"' | |
) | |
def parser(**kwargs): | |
ree_info = {} | |
cnmc_info = {} | |
empreses = {} | |
foreign_companies = [] | |
uncertain_matchings = {} | |
adresses = {} | |
def str_prep(str): | |
str_tr = ''.join((c for c in unicodedata.normalize('NFD', str) | |
if unicodedata.category(c) != 'Mn')) | |
return str_tr.lower().replace('.', '').replace(',', '') | |
def prettify(elem): | |
rough_string = ET.tostring(elem) | |
reparsed = minidom.parseString(rough_string) | |
return reparsed.toprettyxml(indent=" ") | |
def best_match(cnmc_register, empreses): | |
def get_key_by_ree_name(empresa): | |
for record, value in empreses_unicode.items(): | |
if value == empresa: | |
return record | |
cnmc_name = cnmc_register[1] | |
empreses_unicode = {record: str_prep(unicode(empresa)) for (record, empresa) in empreses.items()} | |
name_utf = str_prep(unicode(cnmc_name)) | |
uncertain_matchings_list = [] | |
best = difflib.get_close_matches(name_utf, empreses_unicode.values()) | |
if best: | |
if difflib.SequenceMatcher(None, name_utf, best[0]).ratio() > 0.5: | |
return get_key_by_ree_name(best[0]) | |
uncertain_matchings_list.append(best[0]) | |
new_best = process.extract(name_utf, empreses_unicode.values(), limit=5) | |
if new_best[0][1] >= MATCHING_MIN_RATIO: | |
return get_key_by_ree_name(new_best[0][0]) | |
if difflib.SequenceMatcher(None, name_utf, new_best[0][0]).ratio()*new_best[0][1] >= 60 and difflib.SequenceMatcher(None, ''.join(name_utf.split()[0]), ''.join(new_best[0][0].split()[0])).ratio() > 0.8: | |
return get_key_by_ree_name(new_best[0][0]) | |
uncertain_matchings_list.append(new_best[0][0]) | |
if uncertain_matchings_list: | |
# print "participant of:", new_best[0][0], " =", get_key_by_ree_name(new_best[0][0]) | |
uncertain_matchings.update({get_key_by_ree_name(new_best[0][0]): [uncertain_matchings_list, cnmc_register]}) | |
return None | |
def xml_dict(root_element): | |
dic = {} | |
for record in root_element.iterfind('record'): | |
field_dict = {} | |
for field in record.findall('field'): | |
field_dict[field.attrib['name']] = field.text | |
if field.attrib['name'] == 'name': | |
empreses[record.attrib['id']] = field.text | |
dic[record.attrib['id']] = field_dict | |
return dic | |
def update_info(ree_matching, cnmc_company_register): | |
ree_info[ree_matching].update({ | |
'ref2': cnmc_company_register[0], | |
'vat': cnmc_company_register[8], | |
'website': cnmc_company_register[11], | |
'ambit': cnmc_company_register[7], | |
'state': cnmc_company_register[5] | |
}) | |
def ask(string): | |
r = raw_input(string) | |
return not r or r == 'y' or r == 'Y' | |
def update_foreign_companies(): | |
for l in foreign_companies: | |
best = best_match(l, empreses) | |
if best is not None: | |
update_info(best, l) | |
# <record model="res.partner.address" id="res_partner_address_comer_0762"> | |
# <field name="partner_id" ref="res_partner_comer_0762"/> | |
# <field name="name">SOM ENERGÍA, S.C.C.L.</field> | |
# <field name="state_id" search="[('code', '=', '17')]"/> | |
# <field name="id_municipi" search="[('ine', '=', '17079')]"/> | |
# <field name="phone">900103605</field> | |
# <!-- tipovia, nombre via, número, escalera, planta, puerta, cp --> | |
# <field name="tv" search="[('codi', '=', 'CL')]"/> | |
# <field name="nv">PIC DE PEGUERA</field> | |
# <field name="pnp">15</field> | |
# <field name="es">A</field> | |
# <field name="pt">1</field> | |
# <field name="pu">16</field> | |
# <field name="zip">17003</field> | |
# </record> | |
def create_address_record(parent, cnmc_record, info): | |
ree_code = cnmc_record[12:] | |
print info | |
address_record = SubElement(parent, 'record', { | |
'model': 'res.partner.address', | |
'id': 'res_partner_address_comer_{}'.format(ree_code) | |
}) | |
# Participant | |
participant = { | |
'name': 'participant_id', | |
'ref': 'participant_{}'.format(ree_code) | |
} | |
child = SubElement(address_record, 'field', participant) | |
# Name of the comer | |
child = SubElement(address_record, 'field', {'name':'name'}) | |
child.text = cnmc_record[9] | |
# State | |
print info.keys() | |
child = SubElement(address_record, 'field', { | |
'state_id': '[(\'code\', \'=\', \'{}\')]'.format(PROVINCIES[info['state']])} | |
) | |
# <field search="[('codi','=','13')]" model='res.comunitat_autonoma' name='comunitat_autonoma'/> | |
def make_xml_from_dict(): | |
top = Element('openerp') | |
print "KEYS:", len(ree_info.keys()) | |
for record in ree_info.keys(): | |
top.insert(0,ET.Comment(record)) | |
child = SubElement(top, 'record', { | |
'model': 'giscedata.participant', | |
'id': record | |
}) | |
for field in ree_info[record].keys(): | |
if field not in ('ambit', 'state'): | |
second_child = SubElement(child, 'field', {'name': field}) | |
second_child.text = ree_info[record][field] | |
second_child = SubElement(child, 'field', { | |
'name': 'category_id', | |
'eval': '[(6, 0, [res_partner_cat_comer])]' | |
} | |
) | |
if 'ambit' in ree_info[record].keys(): | |
for ambit in ree_info[record]['ambit'].split(';'): | |
if ambit in AMBIT_CODES: | |
second_child = SubElement(child, 'field', { | |
'name': 'country_id', | |
'ref': 'base.es' | |
}) | |
break | |
for record in ree_info.keys(): | |
create_address_record(top, record, ree_info[record]) | |
with open('sortida.xml', 'w+') as xml_output: | |
xml_output.write(prettify(top)) | |
xml_output.close() | |
############################################################## | |
######################### PARSER ############################# | |
############################################################## | |
with open(kwargs['xml_file'], 'r') as comer_data: | |
xml = ET.parse(comer_data) | |
root_element = xml.getroot() | |
ree_info = xml_dict(root_element) | |
with open(kwargs['csv_file'], 'r') as f: | |
cnmc_comers = csv.reader(f, delimiter=';') | |
good = wrong = total = foreign_counter = 0 | |
for l in cnmc_comers: | |
if l[5] not in ('Extranjero', 'PROVINCIA'): | |
best = best_match(l, empreses) | |
if best is None: | |
wrong += 1 | |
else: | |
update_info(best, l) | |
good += 1 | |
else: | |
foreign_companies.append(l) | |
foreign_counter += 1 | |
total += 1 | |
print "==================================================================" | |
print "Total of registers processed:", total | |
print "Correctly matched and combined:", good | |
print "Registers that could't be matched:", wrong | |
print "==================================================================" | |
print "The REE file has some foreign companies." | |
if ask("Do you want to update the foreign companies of the xml?(Y/n)\n> "): | |
update_foreign_companies() | |
print "LIST OF UNCERTAIN MATCHINGS WITH -RELATIVELY- ELEVATED MATCHING RATIO:" | |
for key in uncertain_matchings.keys(): | |
print "For the company \'", key, "\' there are:" | |
for value in uncertain_matchings[key][0]: | |
print " - ", value | |
if ask("Do you want to resolve manually the uncertain matchings?(Y/n)\n> "): | |
for company in uncertain_matchings.keys(): | |
print "For the company ->", company, ", the most similar matching are:\n", uncertain_matchings[company][0][0].decode(encoding='utf-8') | |
r = raw_input("Do you want to combine the information? If so, which of them? (0-" + str(len(uncertain_matchings[company][0])-1) + "/N)") | |
if r >= 0 and r <= len(uncertain_matchings[company][0])-1: | |
update_info(company, uncertain_matchings[company][r]) | |
del(uncertain_matchings[company]) | |
for uncertain_company in uncertain_matchings.keys():'' | |
update_info(uncertain_company, uncertain_matchings[uncertain_company][1]) | |
make_xml_from_dict() | |
if __name__ == '__main__': | |
parser() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment