<commit_before>from __future__ import division
from collections import defaultdict
import shelve

from scipy.stats import entropy, kurtosis

from .. import NgramService, SUBSTITUTION_TOKEN, ListPacker


def parse_counts(filename):
    counts = {}
    with open(filename) as f:
        for l in f:
            line = l.strip().split('\t')
            found = line[3][1:-1].split(',')
            found_nums = [int(x[1:]) for x in found[0:][::2]]
            found_types = [x[:-1] for x in found[1:][::2]]
            counts[line[1] + " " + line[2]] = dict(zip(found_types, found_nums))
    return counts


class TypePredictor(object):
    type_hierarchy = None
    hbase_table = None
    dbpedia_types_db = None

    def __init__(self, hbase_table, type_hierarchy=None, dbpedia_types_db=None):
        self.type_hierarchy = type_hierarchy
        self.hbase_table = hbase_table
        if dbpedia_types_db:
            self.dbpedia_types_db = shelve.open(dbpedia_types_db, flag='r')

    def _resolve_entities(self, context):
        entity_idx = [x for x in context if x.startswith('<URI:')]
        if len(entity_idx) > 0:
            for entity_ind in entity_idx:
                uri = context[entity_ind][5:-1]
                if uri in self.dbpedia_types_db:
                    types = self.dbpedia_types_db[uri]
                    # most specific
                    context[entity_ind] = '<dbpedia:' + types[0] + '>'
        return context

    def _get_ngram_probs(self, context):
        # pre, post, mid bigrams
        context[2] = SUBSTITUTION_TOKEN
        context = self._resolve_entities(context)
        bigrams = [context[:3], context[-3:], context[1:4]]
        types = []
        for bigram in bigrams:
            type_values = NgramService.hbase_raw(self.hbase_table, " ".join(bigram), "ngram:value")
            if type_values:
                types.append(ListPacker.unpack(type_values))
        totals = [sum(int(x) for x in zip(*type_values)[1]) for type_values in types]
        bigram_probs = [[(entity_type, int(count)/totals[i]) for entity_type, count in type_values]
                        for i, type_values in enumerate(types)]<commit_msg>minor<commit_after>from __future__ import division
from collections import defaultdict
import shelve

from scipy.stats import entropy, kurtosis

from .. import NgramService, SUBSTITUTION_TOKEN, ListPacker


def parse_counts(filename):
    counts = {}
    with open(filename) as f:
        for l in f:
            line = l.strip().split('\t')
            found = line[3][1:-1].split(',')
            found_nums = [int(x[1:]) for x in found[0:][::2]]
            found_types = [x[:-1] for x in found[1:][::2]]
            counts[line[1] + " " + line[2]] = dict(zip(found_types, found_nums))
    return counts


class TypePredictor(object):
    type_hierarchy = None
    hbase_table = None
    dbpedia_types_db = None

    def __init__(self, hbase_table, type_hierarchy=None, dbpedia_types_db=None):
        self.type_hierarchy = type_hierarchy
        self.hbase_table = hbase_table
        if dbpedia_types_db:
            self.dbpedia_types_db = shelve.open(dbpedia_types_db, flag='r')

    def _resolve_entities(self, context):
        entity_idx = [i for i, x in enumerate(context) if x.startswith('<URI:')]
        if len(entity_idx) > 0:
            for entity_ind in entity_idx:
                uri = context[entity_ind][5:-1]
                if uri in self.dbpedia_types_db:
                    types = self.dbpedia_types_db[uri]
                    # most specific
                    context[entity_ind] = '<dbpedia:' + types[0] + '>'
        return context

    def _get_ngram_probs(self, context):
        # pre, post, mid bigrams
        context[2] = SUBSTITUTION_TOKEN
        context = self._resolve_entities(context)
        bigrams = [context[:3], context[-3:], context[1:4]]
        types = []
        for bigram in bigrams:
            type_values = NgramService.hbase_raw(self.hbase_table, " ".join(bigram), "ngram:value")
            if type_values:
                types.append(ListPacker.unpack(type_values))
        totals = [sum(int(x) for x in zip(*type_values)[1]) for type_values in types]
        bigram_probs = [[(entity_type, int(count)/totals[i]) for entity_type, count in type_values]
                        for i, type_values in enumerate(types)]
{'fraction_non_alphanumeric': 0.11374080882352941, 'fraction_numerical': 0.009650735294117647, 'mean_word_length': 2.4824, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, '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': '1062682', 'n_tokens_mistral': 1432, 'n_tokens_neox': 1399, 'n_words': 316}