<commit_before># -*- coding: utf-8 -*-

import io
from zipfile import ZipFile
import zipfile
import urllib.request
import csv
from email.utils import parsedate_to_datetime

import pandas

from .. import constants
from ._commons import Fetcher, Category, Dataset, Provider, ElasticIndex

def load_zip_file(url):
    response = urllib.request.urlopen(url)
    zfile = zipfile.ZipFile(io.BytesIO(response.read()))
    filename = zfile.namelist()[0]
    return zfile.read(filename)
    
class BIS(Fetcher):
    
    def __init__(self, db=None, es_client=None, settings=None):
        super().__init__(provider_name='BIS', db=db)
        self.provider = Provider(name=self.provider_name, website='http://www.bis.org', db=db)
        self.es_client = es_client
        self.settings = settings or {}

    def upsert_dataset(self, id):
        if id == 'LBS-DISS':
            url = self.settings.get("BIS_LBS_DISS_URL", constants.BIS_LBS_DISS_URL)
            self.upsert_lbs_diss(url, id)
            es = ElasticIndex(db=self.db, es_client=self.es_client)
            es.make_index(self.provider_name, id)
        else:
            raise Exception("This dataset is unknown" + id)
        
    def upsert_categories(self):
        document = Category(provider=self.provider_name, 
                            name='Locational Banking Statistics - disseminated data', 
                            categoryCode='LBS-DISS',
                            exposed=True,
                            db=self.db)
        
        return document.update_database()
            
    def upsert_lbs_diss(self, url, dataset_code):
        
        dataset = Dataset(self.provider_name, dataset_code, db=self.db)
        
        fetcher_data = LBS_DISS_Data(dataset, url)
        
        dataset.name = 'Locational Banking Statistics - disseminated data'
        dataset.doc_href = 'http://www.bis.org'
        dataset.last_update = fetcher_data.release_date
        
        #TODO: dataset.attribute_list.update_entry('flags','e','Estimated') ???
        
        dataset.series.data_iterator = fetcher_data
        dataset.update_database()
        

class LBS_DISS_Data():
    
    def __init__(self, dataset, url):
        
        self.provider_name = dataset.provider_name
        self.dataset_code = dataset.dataset_code
        self.dimension_list = dataset.dimension_list
        self.attribute_list = dataset.attribute_list
        
        csv_text = load_zip_file(url)
        csv_file = io.TextIOWrapper(io.BytesIO(csv_text), newline="\n")
        next(csv_file)
        self.release_date = parsedate_to_datetime(csv_file.readline().replace("Retrieved on,", ""))
        next(csv_file)
        next(csv_file)
        self.sheet = csv.DictReader(csv_file)
        
        self.dimension_keys = self.sheet.fieldnames[:13]
        <commit_msg>fix BIS fetcher<commit_after># -*- coding: utf-8 -*-

import io
from zipfile import ZipFile
import zipfile
import urllib.request
import csv
import datetime

import pandas

from .. import constants
from ._commons import Fetcher, Category, Dataset, Provider, ElasticIndex

def load_zip_file(url):
    response = urllib.request.urlopen(url)
    zfile = zipfile.ZipFile(io.BytesIO(response.read()))
    filename = zfile.namelist()[0]
    return zfile.read(filename)
    
class BIS(Fetcher):
    
    def __init__(self, db=None, es_client=None, settings=None):
        super().__init__(provider_name='BIS', db=db)
        self.provider = Provider(name=self.provider_name, website='http://www.bis.org', db=db)
        self.es_client = es_client
        self.settings = settings or {}

    def upsert_dataset(self, id):
        if id == 'LBS-DISS':
            url = self.settings.get("BIS_LBS_DISS_URL", constants.BIS_LBS_DISS_URL)
            self.upsert_lbs_diss(url, id)
            es = ElasticIndex(db=self.db, es_client=self.es_client)
            es.make_index(self.provider_name, id)
        else:
            raise Exception("This dataset is unknown" + id)
        
    def upsert_categories(self):
        document = Category(provider=self.provider_name, 
                            name='Locational Banking Statistics - disseminated data', 
                            categoryCode='LBS-DISS',
                            exposed=True,
                            db=self.db)
        
        return document.update_database()
            
    def upsert_lbs_diss(self, url, dataset_code):
        
        dataset = Dataset(self.provider_name, dataset_code, db=self.db)
        
        fetcher_data = LBS_DISS_Data(dataset, url)
        
        dataset.name = 'Locational Banking Statistics - disseminated data'
        dataset.doc_href = 'http://www.bis.org/statistics/bankstats.htm'
        dataset.last_update = fetcher_data.release_date
        
        dataset.series.data_iterator = fetcher_data
        dataset.update_database()
        

class LBS_DISS_Data():
    """
    @see: http://www.bis.org/statistics/dsd_lbs.pdf
    """
    
    def __init__(self, dataset, url):
        
        self.provider_name = dataset.provider_name
        self.dataset_code = dataset.dataset_code
        self.dimension_list = dataset.dimension_list
        self.attribute_list = dataset.attribute_list
        
        csv_text = load_zip_file(url)
        csv_file = io.TextIOWrapper(io.BytesIO(csv_text), newline="\n")
        next(csv_file)
        txt_date = csv_file.readline().replace("Retrieved on,", "").strip()
        self.release_date = datetime.datetime.strptime(txt_date, "%a %b %d %H:%M:%S %Z %Y")
        next(csv_file)
        next(csv_file)
        self.sheet = csv.DictReader(csv_file)
        
        self.dimension_keys = self.sheet.fieldnames[:13]
        
{'fraction_non_alphanumeric': 0.10391882435269419, 'fraction_numerical': 0.0013995801259622112, 'mean_word_length': 2.370872641509434, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 5, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5488599', 'n_tokens_mistral': 1780, 'n_tokens_neox': 1731, 'n_words': 313}