python_code
stringlengths
0
4.04M
repo_name
stringlengths
7
58
file_path
stringlengths
5
147
import logging import os import json import time from copy import deepcopy from collections import defaultdict import torch import numpy as np from torch.utils.data import DataLoader from torch.utils.data.sampler import WeightedRandomSampler from stratification.utils.utils import NumpyEncoder, get_unique_str, keys_to...
hidden-stratification-master
stratification/harness.py
import os import torch from stratification.harness import GEORGEHarness from stratification.utils.utils import set_seed, init_cuda from stratification.utils.parse_args import get_config from stratification.cluster.models.cluster import GaussianMixture from stratification.cluster.models.reduction import UMAPReducer d...
hidden-stratification-master
stratification/demo.py
import os import logging from functools import partial import numpy as np import sklearn.metrics import torch import torch.optim as optimizers import torch.optim.lr_scheduler as schedulers import torch.nn.functional as F from progress.bar import IncrementalBar as ProgressBar from stratification.classification.utils i...
hidden-stratification-master
stratification/classification/george_classification.py
hidden-stratification-master
stratification/classification/__init__.py
import torch from sklearn.metrics import roc_auc_score class AverageMeter: """Computes and stores the average and current value Imported from https://github.com/pytorch/examples/blob/master/imagenet/main.py#L247-L262 """ def __init__(self): self.reset() def reset(self): self.va...
hidden-stratification-master
stratification/classification/utils.py
import logging import torch import numpy as np class LossComputer: def __init__(self, criterion, is_robust, n_groups, group_counts, robust_step_size, stable=True, size_adjustments=None, auroc_version=False, class_map=None, use_cuda=True): self.criterion = criterion self.is_robust...
hidden-stratification-master
stratification/classification/losses/loss_computer.py
from .loss_computer import init_criterion
hidden-stratification-master
stratification/classification/losses/__init__.py
import os import logging import random from collections import defaultdict, Counter import itertools from PIL import Image import numpy as np import pandas as pd import torch from torchvision import transforms from stratification.classification.datasets.base import GEORGEDataset class ISICDataset(GEORGEDataset): ...
hidden-stratification-master
stratification/classification/datasets/isic.py
from .base import GEORGEDataset, DATA_SPLITS, LABEL_TYPES from .celebA import CelebADataset from .isic import ISICDataset from .waterbirds import WaterbirdsDataset from .mnist import MNISTDataset
hidden-stratification-master
stratification/classification/datasets/__init__.py
import os import torch import pandas as pd from PIL import Image import logging import numpy as np import torchvision.transforms as transforms from .base import GEORGEDataset class CelebADataset(GEORGEDataset): """ CelebA dataset (already cropped and centered). Note: idx and filenames are off by one. ...
hidden-stratification-master
stratification/classification/datasets/celebA.py
import argparse import collections import os import random import shutil import pandas as pd import requests from PIL import Image from tqdm import tqdm from stratification.utils.utils import flatten_dict def main(): parser = argparse.ArgumentParser(description='Downloads the ISIC dataset') parser.add_argum...
hidden-stratification-master
stratification/classification/datasets/isic_download.py
import itertools import os import logging from collections import Counter from PIL import Image import numpy as np import pandas as pd import torch from torchvision import transforms from stratification.classification.datasets.base import GEORGEDataset class WaterbirdsDataset(GEORGEDataset): """Waterbirds Datas...
hidden-stratification-master
stratification/classification/datasets/waterbirds.py
import logging import os import torch from torch.utils.data import Dataset import numpy as np import random DATA_SPLITS = ['train', 'train_clean', 'val', 'test'] LABEL_TYPES = ['superclass', 'subclass', 'true_subclass', 'alt_subclass'] class GEORGEDataset(Dataset): """ Lightweight class that enforces design...
hidden-stratification-master
stratification/classification/datasets/base.py
import os import logging import codecs import random from collections import defaultdict from PIL import Image import numpy as np import pandas as pd import torch from torchvision import transforms from torchvision.datasets.utils import download_and_extract_archive from .base import GEORGEDataset class MNISTDataset...
hidden-stratification-master
stratification/classification/datasets/mnist.py
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
hidden-stratification-master
stratification/classification/models/bit_pytorch_models.py
from .lenet import LeNet4 from .shallow_cnn import ShallowCNN from .pt_resnet import PyTorchResNet from .bit_pytorch_models import BiTResNet
hidden-stratification-master
stratification/classification/models/__init__.py
import torch.nn as nn from collections import OrderedDict class LeNet4(nn.Module): """ Adapted from https://github.com/activatedgeek/LeNet-5 """ def __init__(self, **kwargs): super().__init__() in_channels = kwargs.get('num_channels', 1) classes = kwargs.get('num_classes', 10)...
hidden-stratification-master
stratification/classification/models/lenet.py
import torch.nn as nn from collections import OrderedDict class ShallowCNN(nn.Module): def __init__(self, **kwargs): super().__init__() in_channels = kwargs.get('num_channels', 1) classes = kwargs.get('num_classes', 10) self.convnet = nn.Sequential( OrderedDict([('c1',...
hidden-stratification-master
stratification/classification/models/shallow_cnn.py
import logging import torch import torch.nn as nn from torchvision.models.utils import load_state_dict_from_url __all__ = ['PyTorchResNet'] model_urls = { 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth', } def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1): """3x3 con...
hidden-stratification-master
stratification/classification/models/pt_resnet.py
from copy import deepcopy import os from collections import defaultdict import logging import torch import numpy as np import stratification.cluster.models.reduction as reduction_models from stratification.utils.logger import init_logger class GEORGEReducer: """Executes the cluster stage of the GEORGE algorith...
hidden-stratification-master
stratification/cluster/george_reduce.py
hidden-stratification-master
stratification/cluster/__init__.py
from collections import Counter import numpy as np from stratification.cluster.fast_sil import silhouette_samples def get_k_from_model(model): if hasattr(model, 'n_clusters'): return model.n_clusters elif hasattr(model, 'n_components'): return model.n_components else: raise NotImpl...
hidden-stratification-master
stratification/cluster/utils.py
from copy import deepcopy import os from collections import defaultdict import json import logging import torch import numpy as np from stratification.cluster.models.cluster import DummyClusterer from stratification.cluster.utils import get_cluster_mean_loss, get_cluster_composition, get_k_from_model from stratifica...
hidden-stratification-master
stratification/cluster/george_cluster.py
'''The functions in this file are adapted from scikit-learn (https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/cluster/_unsupervised.py) to use CUDA for Silhouette score computation.''' import numpy as np from sklearn.utils import gen_batches, get_chunk_n_rows from sklearn.metrics.cluster._unsup...
hidden-stratification-master
stratification/cluster/fast_sil.py
from numba.core.errors import NumbaWarning import numpy as np from sklearn.decomposition import PCA from umap import UMAP import warnings __all__ = ['HardnessAugmentedReducer', 'NoOpReducer', 'PCAReducer', 'UMAPReducer'] class Reducer: def __init__(self, **kwargs): raise NotImplementedError() def fi...
hidden-stratification-master
stratification/cluster/models/reduction.py
try: from libKMCUDA import kmeans_cuda _LIBKMCUDA_FOUND = True except ModuleNotFoundError: _LIBKMCUDA_FOUND = False from functools import partial import logging import numpy as np from sklearn.cluster import KMeans from sklearn.mixture import GaussianMixture from stratification.cluster.utils import silhou...
hidden-stratification-master
stratification/cluster/models/cluster.py
import os import sys import logging from collections import defaultdict from datetime import datetime import pandas as pd from .utils import flatten_dict class EpochCSVLogger: '''Save training process without relying on fixed column names''' def __init__(self, fpath, title=None, resume=False): self.f...
hidden-stratification-master
stratification/utils/logger.py
import os import random from collections import defaultdict import json import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import sklearn.metrics as skl import pickle import torch def visualize_clusters_by_group(activations, cluster_assignments, group_assignments, ...
hidden-stratification-master
stratification/utils/visualization.py
import ast import uuid import datetime import subprocess import random import time import json from functools import singledispatch from datetime import datetime, timedelta from collections import MutableMapping import numpy as np import torch tenmin_td = timedelta(minutes=10) hour_td = timedelta(hours=1) def forma...
hidden-stratification-master
stratification/utils/utils.py
import json import argparse from jsonargparse import ActionJsonSchema, namespace_to_dict from .utils import ScientificNotationDecoder, convert_value, set_by_dotted_path from .schema import schema def get_config(args_list=None): """ """ # load and validate config file parser = argparse.ArgumentParser(...
hidden-stratification-master
stratification/utils/parse_args.py
schema = { 'type': 'object', 'required': ['exp_dir', 'mode', 'dataset', 'classification_config', 'reduction_config', 'cluster_config'], 'properties': { 'seed': { 'type': 'number', 'default': -1 }, 'deterministic': { 'type': 'boolean', ...
hidden-stratification-master
stratification/utils/schema.py
import warnings warnings.filterwarnings("ignore") # Suppress warnings from FlyingSquid import numpy as np from flyingsquid.label_model import LabelModel def run_embroid(votes, nn_info, knn=10, thresholds=[[0.5, 0.5]]): """ Implements Embroid. Parameters ---------- votes : ndarray of shape (n_s...
embroid-main
embroid.py
from distutils.util import convert_path from setuptools import find_packages, setup main_ns = {} ver_path = convert_path("bootleg/_version.py") with open(ver_path) as ver_file: exec(ver_file.read(), main_ns) NAME = "bootleg" DESCRIPTION = "Bootleg NED System" URL = "https://github.com/HazyResearch/bootleg" EMAIL...
bootleg-master
setup.py
"""Emmental task constants.""" CANDGEN_TASK = "CANDGEN" BATCH_CANDS_LABEL = "gold_unq_eid_idx"
bootleg-master
cand_gen/task_config.py
import logging import multiprocessing import os import re import shutil import tempfile import time import traceback import warnings import numpy as np import torch import ujson from tqdm.auto import tqdm from bootleg import log_rank_0_debug, log_rank_0_info from bootleg.dataset import convert_examples_to_features_an...
bootleg-master
cand_gen/dataset.py
"""Bootleg run command.""" import argparse import logging import os import subprocess import sys from copy import copy import emmental import torch from emmental.learner import EmmentalLearner from emmental.model import EmmentalModel from rich.logging import RichHandler from transformers import AutoTokenizer from bo...
bootleg-master
cand_gen/train.py
"""Bootleg run command.""" import argparse import logging import os import subprocess import sys from collections import defaultdict from copy import copy from pathlib import Path import emmental import faiss import numpy as np import torch import ujson from emmental.model import EmmentalModel from rich.logging impor...
bootleg-master
cand_gen/eval.py
"""Data""" import logging import os from emmental import Meta from emmental.data import EmmentalDataLoader, emmental_collate_fn from torch.utils.data import DistributedSampler, RandomSampler from bootleg import log_rank_0_info from bootleg.data import bootleg_collate_fn from cand_gen.dataset import CandGenContextData...
bootleg-master
cand_gen/data.py
import torch import torch.nn.functional as F from emmental.scorer import Scorer from emmental.task import Action, EmmentalTask from torch import nn from transformers import AutoModel from bootleg.layers.bert_encoder import Encoder from bootleg.scorer import BootlegSlicedScorer from cand_gen.task_config import CANDGEN_...
bootleg-master
cand_gen/tasks/candgen_task.py
import torch.nn.functional as F from emmental.scorer import Scorer from emmental.task import Action, EmmentalTask from torch import nn from transformers import AutoModel from bootleg.layers.bert_encoder import Encoder from cand_gen.task_config import CANDGEN_TASK class ContextGenOutput: """Context gen for output...
bootleg-master
cand_gen/tasks/context_gen_task.py
import torch.nn.functional as F from emmental.scorer import Scorer from emmental.task import Action, EmmentalTask from torch import nn from transformers import AutoModel from bootleg.layers.bert_encoder import Encoder from cand_gen.task_config import CANDGEN_TASK class EntityGenOutput: """Entity gen for output."...
bootleg-master
cand_gen/tasks/entity_gen_task.py
""" Merge contextual candidates for NED. This file 1. Reads in raw wikipedia sentences from /lfs/raiders7/0/lorr1/sentences 2. Reads in map of WPID-Title-QID from /lfs/raiders7/0/lorr1/title_to_all_ids.jsonl 3. Computes frequencies for alias-QID over Wikipedia. Keeps only alias-QID mentions which occur > args.min_freq...
bootleg-master
cand_gen/utils/merge_contextual_cands.py
"""Parses a Booleg input config into a DottedDict of config values (with defaults filled in) for running a model.""" import argparse import os from bootleg.utils.classes.dotted_dict import create_bool_dotted_dict from bootleg.utils.parser.emm_parse_args import ( parse_args as emm_parse_args, parse_args_to_con...
bootleg-master
cand_gen/utils/parser/parser_utils.py
"""Bootleg default configuration parameters. In the json file, everything is a string or number. In this python file, if the default is a boolean, it will be parsed as such. If the default is a dictionary, True and False strings will become booleans. Otherwise they will stay string. """ import multiprocessing config_...
bootleg-master
cand_gen/utils/parser/candgen_args.py
"""Test entity.""" import os import shutil import unittest from pathlib import Path import torch from bootleg.layers.alias_to_ent_encoder import AliasEntityTable from bootleg.symbols.entity_symbols import EntitySymbols from bootleg.symbols.kg_symbols import KGSymbols from bootleg.symbols.type_symbols import TypeSymbo...
bootleg-master
tests/test_entity/test_entity.py
"""Test entity profile.""" import os import shutil import unittest from pathlib import Path import emmental import numpy as np import torch import ujson from pydantic import ValidationError from bootleg.run import run_model from bootleg.symbols.entity_profile import EntityProfile from bootleg.utils.parser import pars...
bootleg-master
tests/test_entity/test_entity_profile.py
"""End2end test.""" import os import shutil import unittest import emmental import ujson from bootleg.run import run_model from bootleg.utils import utils from bootleg.utils.parser import parser_utils class TestEnd2End(unittest.TestCase): """Test end to end.""" def setUp(self) -> None: """Set up.""...
bootleg-master
tests/test_end_to_end/test_end_to_end.py
"""Test mention extraction.""" import os import tempfile import unittest from pathlib import Path import ujson from bootleg.symbols.entity_symbols import EntitySymbols class MentionExtractionTest(unittest.TestCase): """Mention extraction test.""" def setUp(self) -> None: """Set up.""" self....
bootleg-master
tests/test_end_to_end/test_mention_extraction.py
"""Test generate entities.""" import os import shutil import unittest import emmental import numpy as np import torch import ujson import bootleg.extract_all_entities as extract_all_entities import bootleg.run as run from bootleg.utils import utils from bootleg.utils.parser import parser_utils class TestGenEntities...
bootleg-master
tests/test_end_to_end/test_gen_entities.py
"""Test annotator.""" import os import shutil import unittest import emmental import torch from bootleg import extract_all_entities from bootleg.end2end.bootleg_annotator import BootlegAnnotator from bootleg.run import run_model from bootleg.utils import utils from bootleg.utils.parser import parser_utils class Tes...
bootleg-master
tests/test_end_to_end/test_annotator.py
"""Test scorer.""" import unittest import numpy as np from bootleg.scorer import BootlegSlicedScorer class BootlegMockScorer(BootlegSlicedScorer): """Bootleg mock scorer class.""" def __init__(self, train_in_candidates): """Mock initializer.""" self.mock_slices = { 0: {"all": [1...
bootleg-master
tests/test_scorer/test_scorer.py
"""Test eval utils.""" import os import shutil import tempfile import unittest import jsonlines import numpy as np import torch import ujson from bootleg.symbols.entity_symbols import EntitySymbols from bootleg.utils import eval_utils from bootleg.utils.classes.nested_vocab_tries import ( TwoLayerVocabularyScoreT...
bootleg-master
tests/test_utils/test_eval_utils.py
"""Test preprocessing utils.""" import os import tempfile import unittest from pathlib import Path import ujson from bootleg.symbols.entity_symbols import EntitySymbols class PreprocessingUtils(unittest.TestCase): """Preprocessing utils test.""" def setUp(self) -> None: """Set up.""" self.t...
bootleg-master
tests/test_utils/test_preprocessing.py
"""Test class utils.""" import tempfile import unittest from bootleg.end2end.annotator_utils import DownloadProgressBar from bootleg.utils.classes.nested_vocab_tries import ( ThreeLayerVocabularyTrie, TwoLayerVocabularyScoreTrie, VocabularyTrie, ) class UtilClasses(unittest.TestCase): """Class util t...
bootleg-master
tests/test_utils/test_util_classes.py
"""Test entity dataset.""" import os import shutil import unittest import ujson from transformers import AutoTokenizer from bootleg.dataset import BootlegDataset from bootleg.symbols.constants import SPECIAL_TOKENS from bootleg.symbols.entity_symbols import EntitySymbols from bootleg.symbols.type_symbols import TypeS...
bootleg-master
tests/test_data/test_entity_data.py
"""Test slice data.""" import os import shutil import unittest import numpy as np import torch from bootleg.slicing.slice_dataset import BootlegSliceDataset from bootleg.symbols.constants import FINAL_LOSS from bootleg.symbols.entity_symbols import EntitySymbols from bootleg.utils import utils from bootleg.utils.pars...
bootleg-master
tests/test_data/test_slice_data.py
"""Test data.""" import os import shutil import unittest from collections import defaultdict import numpy as np import torch from transformers import AutoTokenizer from bootleg.dataset import BootlegDataset, extract_context from bootleg.symbols.constants import SPECIAL_TOKENS from bootleg.symbols.entity_symbols impor...
bootleg-master
tests/test_data/test_data.py
"""Test entity embedding generation.""" import os import shutil import unittest import emmental import torch import cand_gen.eval as eval import cand_gen.train as train from bootleg.utils import utils from cand_gen.utils.parser import parser_utils class TestGenEntities(unittest.TestCase): """Test entity generat...
bootleg-master
tests/test_cand_gen/test_eval.py
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If ex...
bootleg-master
docs/source/conf.py
"""Bootleg run command.""" import argparse import itertools import logging import os import shutil import subprocess import sys import warnings from copy import copy import emmental import numpy as np import torch from emmental.learner import EmmentalLearner from emmental.model import EmmentalModel from rich.logging ...
bootleg-master
bootleg/run.py
"""Bootleg version.""" __version__ = "1.1.1dev0"
bootleg-master
bootleg/_version.py
"""Emmental task constants.""" NED_TASK = "NED" BATCH_CANDS_LABEL = "gold_unq_eid_idx" CANDS_LABEL = "gold_cand_K_idx"
bootleg-master
bootleg/task_config.py
"""Print functions for distributed computation.""" import torch def log_rank_0_info(logger, message): """If distributed is initialized log info only on rank 0.""" if torch.distributed.is_initialized(): if torch.distributed.get_rank() == 0: logger.info(message) else: logger.info...
bootleg-master
bootleg/__init__.py
"""Bootleg NED Dataset.""" import logging import multiprocessing import os import re import shutil import sys import time import traceback import warnings from collections import defaultdict import numpy as np import torch import ujson from emmental.data import EmmentalDataset from tqdm.auto import tqdm from bootleg ...
bootleg-master
bootleg/dataset.py
"""Bootleg run command.""" import argparse import logging import os import subprocess import sys from copy import copy import emmental import numpy as np import torch from emmental.model import EmmentalModel from rich.logging import RichHandler from transformers import AutoTokenizer from bootleg import log_rank_0_in...
bootleg-master
bootleg/extract_all_entities.py
"""Bootleg data creation.""" import copy import logging import os from collections import defaultdict from typing import Any, Dict, List, Tuple, Union import torch from emmental import Meta from emmental.data import EmmentalDataLoader, emmental_collate_fn from emmental.utils.utils import list_to_tensor from torch.util...
bootleg-master
bootleg/data.py
"""Bootleg scorer.""" import logging from collections import Counter from typing import Dict, List, Optional from numpy import ndarray logger = logging.getLogger(__name__) class BootlegSlicedScorer: """Sliced NED scorer init. Args: train_in_candidates: are we training assuming that all gold qids ar...
bootleg-master
bootleg/scorer.py
"""Task init."""
bootleg-master
bootleg/tasks/__init__.py
"""NED task definitions.""" import torch import torch.nn.functional as F from emmental.scorer import Scorer from emmental.task import Action, EmmentalTask from torch import nn from transformers import AutoModel from bootleg.layers.bert_encoder import Encoder from bootleg.layers.static_entity_embeddings import EntityEm...
bootleg-master
bootleg/tasks/ned_task.py
"""Entity gen task definitions.""" import torch.nn.functional as F from emmental.scorer import Scorer from emmental.task import Action, EmmentalTask from torch import nn from transformers import AutoModel from bootleg.layers.bert_encoder import Encoder from bootleg.task_config import NED_TASK class EntityGenOutput: ...
bootleg-master
bootleg/tasks/entity_gen_task.py
"""AliasEntityTable class.""" import logging import os import time import numpy as np import torch import torch.nn as nn from tqdm.auto import tqdm from bootleg import log_rank_0_debug from bootleg.utils import data_utils, utils from bootleg.utils.model_utils import get_max_candidates logger = logging.getLogger(__na...
bootleg-master
bootleg/layers/alias_to_ent_encoder.py
"""Entity embeddings.""" import logging import numpy as np import torch logger = logging.getLogger(__name__) class EntityEmbedding(torch.nn.Module): """Static entity embeddings class. Args: entity_emb_file: numpy file of entity embeddings """ def __init__(self, entity_emb_file): ""...
bootleg-master
bootleg/layers/static_entity_embeddings.py
"""Layer init."""
bootleg-master
bootleg/layers/__init__.py
"""BERT encoder.""" import torch from torch import nn class Encoder(nn.Module): """ Encoder module. Return the CLS token of Transformer. Args: transformer: transformer out_dim: out dimension to project to """ def __init__(self, transformer, out_dim): """BERT Encoder ...
bootleg-master
bootleg/layers/bert_encoder.py
"""Model utils.""" import logging from bootleg import log_rank_0_debug logger = logging.getLogger(__name__) def count_parameters(model, requires_grad, logger): """Count the number of parameters. Args: model: model to count requires_grad: whether to look at grad or no grad params log...
bootleg-master
bootleg/utils/model_utils.py
"""Util init."""
bootleg-master
bootleg/utils/__init__.py
"""Bootleg data utils.""" import os from bootleg.symbols.constants import FINAL_LOSS, SPECIAL_TOKENS from bootleg.utils import utils def correct_not_augmented_dict_values(gold, dict_values): """ Correct gold label dict values in data prep. Modifies the dict_values to only contain those mentions that are...
bootleg-master
bootleg/utils/data_utils.py
"""Bootleg utils.""" import collections import json import logging import math import os import pathlib import shutil import time import unicodedata from itertools import chain, islice import marisa_trie import ujson import yaml from bootleg import log_rank_0_info from bootleg.symbols.constants import USE_LOWER, USE_...
bootleg-master
bootleg/utils/utils.py
import logging import string from collections import namedtuple from typing import List, Tuple, Union import nltk import spacy from spacy.cli.download import download as spacy_download from bootleg.symbols.constants import LANG_CODE from bootleg.utils.utils import get_lnrm logger = logging.getLogger(__name__) span_...
bootleg-master
bootleg/utils/mention_extractor_utils.py
"""Bootleg eval utils.""" import glob import logging import math import multiprocessing import os import shutil import time from collections import defaultdict import emmental import numpy as np import pandas as pd import torch import torch.nn.functional as F import ujson from emmental.utils.utils import array_to_nump...
bootleg-master
bootleg/utils/eval_utils.py
"""Classes init."""
bootleg-master
bootleg/utils/classes/__init__.py
"""Dotted dict class.""" import keyword import re import string import ujson class DottedDict(dict): """ Dotted dictionary. Override for the dict object to allow referencing of keys as attributes, i.e. dict.key. """ def __init__(self, *args, **kwargs): """Dotted dict initializer.""" ...
bootleg-master
bootleg/utils/classes/dotted_dict.py
"""Nested vocab tries.""" import itertools import logging import os from pathlib import Path from typing import Any, Callable, Dict, List, Set, Tuple, Union import marisa_trie import numpy as np import ujson from numba import njit from tqdm.auto import tqdm from bootleg.utils.utils import dump_json_file, load_json_fi...
bootleg-master
bootleg/utils/classes/nested_vocab_tries.py
""" JSON with comments class. An example of how to remove comments and trailing commas from JSON before parsing. You only need the two functions below, `remove_comments()` and `remove_trailing_commas()` to accomplish this. This script serves as an example of how to use them but feel free to just copy & paste them in...
bootleg-master
bootleg/utils/classes/comment_json.py
"""Emmental dataset and dataloader.""" import logging from typing import Any, Dict, Optional, Tuple, Union from emmental import EmmentalDataset from torch import Tensor logger = logging.getLogger(__name__) class RangedEmmentalDataset(EmmentalDataset): """ RangedEmmentalDataset dataset. An advanced data...
bootleg-master
bootleg/utils/classes/emmental_data.py
""" Bootleg parser utils. Parses a Booleg input config into a DottedDict of config values (with defaults filled in) for running a model. """ import argparse import fileinput import os import ujson import bootleg.utils.classes.comment_json as comment_json from bootleg.utils.classes.dotted_dict import DottedDict, cre...
bootleg-master
bootleg/utils/parser/parser_utils.py
"""Parser init."""
bootleg-master
bootleg/utils/parser/__init__.py
"""Overrides the Emmental parse_args.""" import argparse from argparse import ArgumentParser from typing import Any, Dict, Optional, Tuple from emmental.utils.utils import ( nullable_float, nullable_int, nullable_string, str2bool, str2dict, ) from bootleg.utils.classes.dotted_dict import DottedDic...
bootleg-master
bootleg/utils/parser/emm_parse_args.py
"""Bootleg default configuration parameters. In the json file, everything is a string or number. In this python file, if the default is a boolean, it will be parsed as such. If the default is a dictionary, True and False strings will become booleans. Otherwise they will stay string. """ import multiprocessing config_...
bootleg-master
bootleg/utils/parser/bootleg_args.py
""" Compute statistics over data. Helper file for computing various statistics over our data such as mention frequency, mention text frequency in the data (even if not labeled as an anchor), ... etc. """ import argparse import logging import multiprocessing import os import time from collections import Counter impo...
bootleg-master
bootleg/utils/preprocessing/compute_statistics.py
"""Preprocessing init."""
bootleg-master
bootleg/utils/preprocessing/__init__.py
""" Sample eval data. This will sample a jsonl train or eval data based on the slices in the data. This is useful for subsampling a smaller eval dataset.py. The output of this file is a files with a subset of sentences from the input file samples such that for each slice in --args.slice, a minimum of args.min_sample_...
bootleg-master
bootleg/utils/preprocessing/sample_eval_data.py
""" Compute QID counts. Helper function that computes a dictionary of QID -> count in training data. If a QID is not in this dictionary, it has a count of zero. """ import argparse import multiprocessing import os import shutil import tempfile from collections import defaultdict from pathlib import Path import ujso...
bootleg-master
bootleg/utils/preprocessing/convert_to_char_spans.py
""" Compute QID counts. Helper function that computes a dictionary of QID -> count in training data. If a QID is not in this dictionary, it has a count of zero. """ import argparse import multiprocessing from collections import defaultdict import ujson from tqdm.auto import tqdm from bootleg.utils import utils d...
bootleg-master
bootleg/utils/preprocessing/get_train_qid_counts.py
"""BootlegAnnotator.""" import logging import os import tarfile import urllib from pathlib import Path from typing import Any, Dict, Union import emmental import numpy as np import torch from emmental.model import EmmentalModel from tqdm.auto import tqdm from transformers import AutoTokenizer from bootleg.dataset imp...
bootleg-master
bootleg/end2end/bootleg_annotator.py
"""End2End init."""
bootleg-master
bootleg/end2end/__init__.py
"""Annotator utils.""" import progressbar class DownloadProgressBar: """Progress bar.""" def __init__(self): """Progress bar initializer.""" self.pbar = None def __call__(self, block_num, block_size, total_size): """Call.""" if not self.pbar: self.pbar = prog...
bootleg-master
bootleg/end2end/annotator_utils.py
""" Extract mentions. This file takes in a jsonlines file with sentences and extract aliases and spans using a pre-computed alias table. """ import argparse import logging import multiprocessing import os import time import jsonlines import numpy as np from tqdm.auto import tqdm from bootleg.symbols.constants import...
bootleg-master
bootleg/end2end/extract_mentions.py
"""KG symbols class.""" import copy import os import re from typing import Dict, List, Optional, Set, Union from tqdm.auto import tqdm from bootleg.symbols.constants import edit_op from bootleg.utils import utils from bootleg.utils.classes.nested_vocab_tries import ThreeLayerVocabularyTrie def _convert_to_trie(qid2...
bootleg-master
bootleg/symbols/kg_symbols.py
"""Entity profile.""" import logging from pathlib import Path from typing import Dict, List, Optional, Tuple import ujson from pydantic import BaseModel, ValidationError from tqdm.auto import tqdm from bootleg.symbols.constants import check_qid_exists, edit_op from bootleg.symbols.entity_symbols import EntitySymbols ...
bootleg-master
bootleg/symbols/entity_profile.py