python_code
stringlengths
0
187k
repo_name
stringlengths
8
46
file_path
stringlengths
6
135
""" This script handles the skimage exif problem. """ from PIL import Image import numpy as np ORIENTATIONS = { # used in apply_orientation 2: (Image.FLIP_LEFT_RIGHT,), 3: (Image.ROTATE_180,), 4: (Image.FLIP_TOP_BOTTOM,), 5: (Image.FLIP_LEFT_RIGHT, Image.ROTATE_90), 6: (Image.ROTATE_270,), 7...
colorization-master
caffe-colorization/examples/web_demo/exifutil.py
import os import time import cPickle import datetime import logging import flask import werkzeug import optparse import tornado.wsgi import tornado.httpserver import numpy as np import pandas as pd from PIL import Image import cStringIO as StringIO import urllib import exifutil import caffe REPO_DIRNAME = os.path.abs...
colorization-master
caffe-colorization/examples/web_demo/app.py
#!/usr/bin/env python """ Form a subset of the Flickr Style data, download images to dirname, and write Caffe ImagesDataLayer training file. """ import os import urllib import hashlib import argparse import numpy as np import pandas as pd from skimage import io import multiprocessing # Flickr returns a special image i...
colorization-master
caffe-colorization/examples/finetune_flickr_style/assemble_data.py
#!/usr/bin/env python """ Takes as arguments: 1. the path to a JSON file (such as an IPython notebook). 2. the path to output file If 'metadata' dict in the JSON file contains 'include_in_docs': true, then copies the file to output file, appending the 'metadata' property as YAML front-matter, adding the field 'categor...
colorization-master
caffe-colorization/scripts/copy_notebook.py
#!/usr/bin/python2 # # Copyright (c) 2009 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of...
colorization-master
caffe-colorization/scripts/cpp_lint.py
#!/usr/bin/env python import os import sys import time import yaml import urllib import hashlib import argparse required_keys = ['caffemodel', 'caffemodel_url', 'sha1'] def reporthook(count, block_size, total_size): """ From http://blog.moleculea.com/2012/10/04/urlretrieve-progres-indicator/ """ glob...
colorization-master
caffe-colorization/scripts/download_model_binary.py
""" Generate data used in the HDF5DataLayer and GradientBasedSolver tests. """ import os import numpy as np import h5py script_dir = os.path.dirname(os.path.abspath(__file__)) # Generate HDF5DataLayer sample_data.h5 num_cols = 8 num_rows = 10 height = 6 width = 5 total_size = num_cols * num_rows * height * width da...
colorization-master
caffe-colorization/src/caffe/test/test_data/generate_sample_data.py
import sys import argparse import caffe from caffe import score, surgery # score, surgery function from caffe-fcn import numpy as np import os import warnings print sys.argv def parse_args(): parser = argparse.ArgumentParser(description='') # ***** FLAGS ***** parser.add_argument('--gpu', dest='gpu', he...
colorization-master
feature_learning_tests/segmentation/solve.py
from __future__ import division import caffe import numpy as np def transplant(new_net, net): for p in net.params: if p not in new_net.params: print 'dropping', p continue for i in range(len(net.params[p])): if net.params[p][i].data.shape != new_net.params[p][i]....
colorization-master
feature_learning_tests/segmentation/caffe/surgery.py
from __future__ import division import caffe import numpy as np import os import sys from datetime import datetime from PIL import Image def fast_hist(a, b, n): k = (a >= 0) & (a < n) return np.bincount(n * a[k].astype(int) + b[k], minlength=n**2).reshape(n, n) def compute_hist(net, save_dir, dataset, layer='...
colorization-master
feature_learning_tests/segmentation/caffe/score.py
import caffe import os import string import numpy as np import argparse import matplotlib.pyplot as plt def parse_args(): parser = argparse.ArgumentParser(description='Convert conv layers into FC layers') parser.add_argument('--gpu', dest='gpu', help='gpu id', type=int, default=0) parser.add_argument('--p...
colorization-master
resources/conv_into_fc.py
# ************************************** # ***** Richard Zhang / 2016.08.06 ***** # ************************************** import numpy as np import warnings import os import sklearn.neighbors as nn import caffe from skimage import color # ************************ # ***** CAFFE LAYERS ***** # ************************ ...
colorization-master
resources/caffe_traininglayers.py
# ************************************** # ***** Richard Zhang / 2016.06.04 ***** # ************************************** # Absorb batch norm into convolution layers # This script only supports the conv-batchnorm configuration # Currently unsupported: # - deconv layers # - fc layers # - batchnorm before linear la...
colorization-master
resources/batch_norm_absorb.py
from __future__ import print_function, division INPUT_LAYERS = ['Data', 'ImageData'] # Layers that only support elwise ELWISE_LAYERS = ['Deconvolution'] # Layers that support parameters PARAMETER_LAYERS = ['Convolution', 'InnerProduct']+ELWISE_LAYERS # All supported layers SUPPORTED_LAYERS = ['ReLU', 'Sigmoid', 'LRN',...
colorization-master
resources/magic_init/magic_init_mod.py
from __future__ import print_function from magic_init import * class BCOLORS: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' class NOCOLORS: HEADER = '' OKBLUE = '' OKGREEN = '' WARNING = '' FAIL...
colorization-master
resources/magic_init/measure_stat.py
import caffe def parseProtoString(s): from google.protobuf import text_format from caffe.proto import caffe_pb2 as pb proto_net = pb.NetParameter() text_format.Merge(s, proto_net) return proto_net def get_param(l, exclude=set(['top', 'bottom', 'name', 'type'])): if not hasattr(l,'ListFields'): if hasattr(l,'...
colorization-master
resources/magic_init/load.py
import numpy as np import os import skimage.color as color import matplotlib.pyplot as plt import scipy.ndimage.interpolation as sni import caffe import argparse def parse_args(): parser = argparse.ArgumentParser(description='iColor: deep interactive colorization') parser.add_argument('-img_in',dest='img_in',h...
colorization-master
colorization/colorize.py
#!/usr/bin/python import os import sys import argparse import numpy as np from skimage import color, io import scipy.ndimage.interpolation as sni import caffe def parse_args(argv): parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.ArgumentDefault...
colorization-master
colorization/demo/batch_process.py
import sys import argparse import caffe from caffe import score, surgery # score, surgery function from caffe-fcn import numpy as np import os import warnings print sys.argv def parse_args(): parser = argparse.ArgumentParser(description='') # ***** FLAGS ***** parser.add_argument('--gpu', dest='gpu', he...
colorization-master
colorization/feature_learning_tests/segmentation/solve.py
from __future__ import division import caffe import numpy as np def transplant(new_net, net): for p in net.params: if p not in new_net.params: print 'dropping', p continue for i in range(len(net.params[p])): if net.params[p][i].data.shape != new_net.params[p][i]....
colorization-master
colorization/feature_learning_tests/segmentation/caffe/surgery.py
from __future__ import division import caffe import numpy as np import os import sys from datetime import datetime from PIL import Image def fast_hist(a, b, n): k = (a >= 0) & (a < n) return np.bincount(n * a[k].astype(int) + b[k], minlength=n**2).reshape(n, n) def compute_hist(net, save_dir, dataset, layer='...
colorization-master
colorization/feature_learning_tests/segmentation/caffe/score.py
import caffe import os import string import numpy as np import argparse import matplotlib.pyplot as plt def parse_args(): parser = argparse.ArgumentParser(description='Convert conv layers into FC layers') parser.add_argument('--gpu', dest='gpu', help='gpu id', type=int, default=0) parser.add_argument('--p...
colorization-master
colorization/resources/conv_into_fc.py
# ************************************** # ***** Richard Zhang / 2016.08.06 ***** # ************************************** import numpy as np import warnings import os import sklearn.neighbors as nn import caffe from skimage import color # ************************ # ***** CAFFE LAYERS ***** # ************************ ...
colorization-master
colorization/resources/caffe_traininglayers.py
# ************************************** # ***** Richard Zhang / 2016.06.04 ***** # ************************************** # Absorb batch norm into convolution layers # This script only supports the conv-batchnorm configuration # Currently unsupported: # - deconv layers # - fc layers # - batchnorm before linear la...
colorization-master
colorization/resources/batch_norm_absorb.py
from __future__ import print_function, division INPUT_LAYERS = ['Data', 'ImageData'] # Layers that only support elwise ELWISE_LAYERS = ['Deconvolution'] # Layers that support parameters PARAMETER_LAYERS = ['Convolution', 'InnerProduct']+ELWISE_LAYERS # All supported layers SUPPORTED_LAYERS = ['ReLU', 'Sigmoid', 'LRN',...
colorization-master
colorization/resources/magic_init/magic_init_mod.py
from __future__ import print_function from magic_init import * class BCOLORS: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' class NOCOLORS: HEADER = '' OKBLUE = '' OKGREEN = '' WARNING = '' FAIL...
colorization-master
colorization/resources/magic_init/measure_stat.py
import caffe def parseProtoString(s): from google.protobuf import text_format from caffe.proto import caffe_pb2 as pb proto_net = pb.NetParameter() text_format.Merge(s, proto_net) return proto_net def get_param(l, exclude=set(['top', 'bottom', 'name', 'type'])): if not hasattr(l,'ListFields'): if hasattr(l,'...
colorization-master
colorization/resources/magic_init/load.py
from __future__ import print_function import platform import sys import argparse import qdarkstyle from PyQt4.QtGui import QApplication, QIcon from PyQt4.QtCore import Qt from ui import gui_design from data import colorize_image as CI sys.path.append('./caffe_files') def parse_args(): parser = argparse.ArgumentP...
colorization-master
interactive-deep-colorization/ideepcolor.py
from PyQt4.QtCore import * from PyQt4.QtGui import * import cv2 import numpy as np class GUI_VIS(QWidget): def __init__(self, win_size=256, scale=2.0): QWidget.__init__(self) self.result = None self.win_width = win_size self.win_height = win_size self.scale = scale ...
colorization-master
interactive-deep-colorization/ui/gui_vis.py
colorization-master
interactive-deep-colorization/ui/__init__.py
from PyQt4.QtCore import * from PyQt4.QtGui import * import numpy as np class GUIPalette(QWidget): def __init__(self, grid_sz=(6, 3)): QWidget.__init__(self) self.color_width = 25 self.border = 6 self.win_width = grid_sz[0] * self.color_width + (grid_sz[0]+1) * self.border ...
colorization-master
interactive-deep-colorization/ui/gui_palette.py
from PyQt4.QtCore import * from PyQt4.QtGui import * from . import gui_draw from . import gui_vis from . import gui_gamut from . import gui_palette import time class GUIDesign(QWidget): def __init__(self, color_model, dist_model=None, img_file=None, load_size=256, win_size=256, save_all=True): ...
colorization-master
interactive-deep-colorization/ui/gui_design.py
import numpy as np from PyQt4.QtCore import * from PyQt4.QtGui import * import cv2 class UserEdit(object): def __init__(self, mode, win_size, load_size, img_size): self.mode = mode self.win_size = win_size self.img_size = img_size self.load_size = load_size print('image_siz...
colorization-master
interactive-deep-colorization/ui/ui_control.py
from __future__ import print_function import inspect, re import numpy as np import cv2 import os import collections try: import pickle as pickle except ImportError: import pickle def debug_trace(): from PyQt4.QtCore import pyqtRemoveInputHook from pdb import set_trace pyqtRemoveInputHook() se...
colorization-master
interactive-deep-colorization/ui/utils.py
import numpy as np import time import cv2 from PyQt4.QtCore import * from PyQt4.QtGui import * try: from PyQt4.QtCore import QString except ImportError: QString = str from .ui_control import UIControl from data import lab_gamut from skimage import color import os import datetime import glob import sys import m...
colorization-master
interactive-deep-colorization/ui/gui_draw.py
import cv2 from PyQt4.QtCore import * from PyQt4.QtGui import * from data import lab_gamut import numpy as np class GUIGamut(QWidget): def __init__(self, gamut_size=110): QWidget.__init__(self) self.gamut_size = gamut_size self.win_size = gamut_size * 2 # divided by 4 self.setFixe...
colorization-master
interactive-deep-colorization/ui/gui_gamut.py
import numpy as np import itertools import time import datetime def check_value(inds, val): # Check to see if an array is a single element equaling a particular value # Good for pre-processing inputs in a function if(np.array(inds).size==1): if(inds==val): return True return False def flatten_nd_array(pts_...
colorization-master
interactive-deep-colorization/caffe_files/util.py
colorization-master
interactive-deep-colorization/caffe_files/__init__.py
import numpy as np import warnings import os import sklearn.neighbors as nn import caffe from skimage import color import matplotlib.pyplot as plt import color_quantization as cq # *************************************** # ***** LAYERS FOR GLOBAL HISTOGRAM ***** # *************************************** class Spatial...
colorization-master
interactive-deep-colorization/caffe_files/caffe_traininglayers.py
import numpy as np from IPython.core.debugger import Pdb as pdb import sklearn.neighbors as nn import util import caffe class NNEncode(): # Encode points as a linear combination of unordered points # using NN search and RBF kernel def __init__(self,NN,sigma,km_filepath='./data/color_bins/pts_in_hull.npy',cc=-1): ...
colorization-master
interactive-deep-colorization/caffe_files/color_quantization.py
import numpy as np import scipy as sp import cv2 import matplotlib.pyplot as plt from skimage import color import caffe from sklearn.cluster import KMeans from skimage.io import imread from skimage.io import imsave from skimage import color import os import sys import ntpath import datetime from scipy.ndimage.interpola...
colorization-master
interactive-deep-colorization/data/colorize_image.py
colorization-master
interactive-deep-colorization/data/__init__.py
import numpy as np import scipy as sp from skimage import color from pdb import set_trace as st import warnings def qcolor2lab_1d(qc): # take 1d numpy array and do color conversion c = np.array([qc.red(), qc.green(), qc.blue()], np.uint8) return rgb2lab_1d(c) def rgb2lab_1d(in_rgb): # take 1d numpy...
colorization-master
interactive-deep-colorization/data/lab_gamut.py
from setuptools import setup, find_packages import sys import os # PEP0440 compatible formatted version, see: # https://www.python.org/dev/peps/pep-0440/ # # release markers: # X.Y # X.Y.Z # For bugfix releases # # pre-release markers: # X.YaN # Alpha release # X.YbN # Beta release # X.YrcN # Release ...
allennlp-reading-comprehension-master
setup.py
_MAJOR = "0" _MINOR = "0" _REVISION = "1-unreleased" VERSION_SHORT = "{0}.{1}".format(_MAJOR, _MINOR) VERSION = "{0}.{1}.{2}".format(_MAJOR, _MINOR, _REVISION)
allennlp-reading-comprehension-master
allennlp_rc/version.py
import allennlp_rc.dataset_readers import allennlp_rc.models import allennlp_rc.predictors
allennlp-reading-comprehension-master
allennlp_rc/__init__.py
import json import logging from typing import Dict, List from overrides import overrides from allennlp.common.file_utils import cached_path from allennlp.data.dataset_readers.dataset_reader import DatasetReader from allennlp.data.instance import Instance from allennlp.data.fields import Field, TextField, ListField, M...
allennlp-reading-comprehension-master
allennlp_rc/dataset_readers/qangaroo.py
""" Utilities for reading comprehension dataset readers. """ from collections import Counter, defaultdict import logging import string from typing import Any, Dict, List, Tuple, Optional from allennlp.data.fields import ( Field, TextField, IndexField, MetadataField, LabelField, ListField, ...
allennlp-reading-comprehension-master
allennlp_rc/dataset_readers/util.py
import json import logging from typing import Any, Dict, List, Tuple, Optional, Iterable from allennlp.common.util import sanitize_wordpiece from allennlp.data.fields import MetadataField, TextField, SpanField from overrides import overrides from allennlp.common.file_utils import cached_path, open_compressed from all...
allennlp-reading-comprehension-master
allennlp_rc/dataset_readers/transformer_squad.py
from allennlp_rc.dataset_readers.drop import DropReader from allennlp_rc.dataset_readers.qangaroo import QangarooReader from allennlp_rc.dataset_readers.quac import QuACReader from allennlp_rc.dataset_readers.squad import SquadReader from allennlp_rc.dataset_readers.triviaqa import TriviaQaReader from allennlp_rc.datas...
allennlp-reading-comprehension-master
allennlp_rc/dataset_readers/__init__.py
import json import logging from typing import Any, Dict, List, Tuple, Optional from overrides import overrides from allennlp.common.file_utils import cached_path from allennlp.data.dataset_readers.dataset_reader import DatasetReader from allennlp.data.instance import Instance from allennlp.data.token_indexers import ...
allennlp-reading-comprehension-master
allennlp_rc/dataset_readers/squad.py
import json import logging from typing import Any, Dict, List, Tuple from overrides import overrides from allennlp.common.file_utils import cached_path from allennlp.data.dataset_readers.dataset_reader import DatasetReader from allennlp.data.instance import Instance from allennlp.data.token_indexers import SingleIdTo...
allennlp-reading-comprehension-master
allennlp_rc/dataset_readers/quac.py
import itertools import json import logging import string from collections import defaultdict from typing import Dict, List, Union, Tuple, Any from overrides import overrides from word2number.w2n import word_to_num from allennlp.common.file_utils import cached_path from allennlp.data.fields import ( Field, Te...
allennlp-reading-comprehension-master
allennlp_rc/dataset_readers/drop.py
import json import logging import os import tarfile from typing import Dict, List, Tuple from overrides import overrides from allennlp.common.file_utils import cached_path from allennlp.data.dataset_readers.dataset_reader import DatasetReader from allennlp.data.instance import Instance from allennlp.data.token_indexe...
allennlp-reading-comprehension-master
allennlp_rc/dataset_readers/triviaqa.py
import json from overrides import overrides from allennlp.common.util import JsonDict from allennlp.data import DatasetReader, Instance from allennlp.data.tokenizers.spacy_tokenizer import SpacyTokenizer from allennlp.predictors.predictor import Predictor from allennlp.models import Model @Predictor.register("dialog...
allennlp-reading-comprehension-master
allennlp_rc/predictors/dialog_qa.py
from allennlp_rc.predictors.reading_comprehension import ReadingComprehensionPredictor from allennlp_rc.predictors.dialog_qa import DialogQAPredictor from allennlp_rc.predictors.transformer_qa import TransformerQAPredictor
allennlp-reading-comprehension-master
allennlp_rc/predictors/__init__.py
from copy import deepcopy from typing import Dict, List from overrides import overrides import numpy from allennlp.common.util import JsonDict from allennlp.data import Instance from allennlp.predictors.predictor import Predictor from allennlp.data.fields import ( IndexField, ListField, LabelField, Sp...
allennlp-reading-comprehension-master
allennlp_rc/predictors/reading_comprehension.py
from typing import List, Dict, Any from allennlp.models import Model from overrides import overrides from allennlp.common.util import JsonDict, sanitize from allennlp.data import Instance, DatasetReader from allennlp.predictors.predictor import Predictor @Predictor.register("transformer_qa") class TransformerQAPred...
allennlp-reading-comprehension-master
allennlp_rc/predictors/transformer_qa.py
import logging from typing import Any, Dict, List, Optional import numpy as np from overrides import overrides import torch import torch.nn.functional as F from torch.nn.functional import nll_loss from allennlp.common.checks import check_dimensions_match from allennlp.data import Vocabulary from allennlp.models.model ...
allennlp-reading-comprehension-master
allennlp_rc/models/dialog_qa.py
import torch def get_best_span(span_start_logits: torch.Tensor, span_end_logits: torch.Tensor) -> torch.Tensor: """ This acts the same as the static method ``BidirectionalAttentionFlow.get_best_span()`` in ``allennlp/models/reading_comprehension/bidaf.py``. We keep it here so that users can directly i...
allennlp-reading-comprehension-master
allennlp_rc/models/util.py
from typing import Any, Dict, List, Optional import torch from torch.nn.functional import nll_loss from allennlp.data import Vocabulary from allennlp.models.model import Model from allennlp.modules import Highway from allennlp.modules import Seq2SeqEncoder, TextFieldEmbedder from allennlp.modules.matrix_attention.mat...
allennlp-reading-comprehension-master
allennlp_rc/models/qanet.py
from allennlp_rc.models.bidaf import BidirectionalAttentionFlow from allennlp_rc.models.bidaf_ensemble import BidafEnsemble from allennlp_rc.models.dialog_qa import DialogQA from allennlp_rc.models.naqanet import NumericallyAugmentedQaNet from allennlp_rc.models.qanet import QaNet from allennlp_rc.models.transformer_qa...
allennlp-reading-comprehension-master
allennlp_rc/models/__init__.py
import logging from typing import Any, Dict, List, Optional import torch from torch.nn.functional import nll_loss from allennlp.common.checks import check_dimensions_match from allennlp.data import Vocabulary from allennlp.models.model import Model from allennlp.modules import Highway from allennlp.modules import Seq...
allennlp-reading-comprehension-master
allennlp_rc/models/bidaf.py
from typing import Dict, List, Any from overrides import overrides import torch from allennlp.common.checks import ConfigurationError from allennlp.models.ensemble import Ensemble from allennlp.models.archival import load_archive from allennlp.models.model import Model from allennlp.common import Params from allennlp...
allennlp-reading-comprehension-master
allennlp_rc/models/bidaf_ensemble.py
from typing import Any, Dict, List, Optional import logging import torch from allennlp.data import Vocabulary from allennlp.models.model import Model from allennlp.modules import Highway from allennlp.nn.activations import Activation from allennlp.modules.feedforward import FeedForward from allennlp.modules import Se...
allennlp-reading-comprehension-master
allennlp_rc/models/naqanet.py
import logging from typing import Any, Dict, List, Optional import numpy as np import torch from allennlp.common.util import sanitize_wordpiece from allennlp.modules.text_field_embedders import BasicTextFieldEmbedder from allennlp.modules.token_embedders import PretrainedTransformerEmbedder from allennlp.nn.util impor...
allennlp-reading-comprehension-master
allennlp_rc/models/transformer_qa.py
""" Evaluation script for NarrativeQA dataset. """ import nltk try: nltk.data.find("tokenizers/punkt") except LookupError: nltk.download("punkt") nltk.download("wordnet") import rouge from nltk.translate.bleu_score import sentence_bleu from nltk.tokenize import word_tokenize from nltk.translate.meteor_sc...
allennlp-reading-comprehension-master
allennlp_rc/eval/narrativeqa_eval.py
""" Official evaluation script for v1.1 of the SQuAD dataset. """ from __future__ import print_function from collections import Counter import string import re import argparse import json import sys def normalize_answer(s): """Lower text and remove punctuation, articles and extra whitespace.""" def remove_ar...
allennlp-reading-comprehension-master
allennlp_rc/eval/squad_eval.py
from allennlp_rc.eval.drop_em_and_f1 import DropEmAndF1 from allennlp_rc.eval.squad_em_and_f1 import SquadEmAndF1
allennlp-reading-comprehension-master
allennlp_rc/eval/__init__.py
"""Official evaluation script for ORB. Usage: python evaluation_script.py --dataset_file <file_path> --prediction_file <file_path> --metrics_output_file <file_path> """ # pylint: disable=unused-import from __future__ import absolute_import from __future__ import division from __future__ impor...
allennlp-reading-comprehension-master
allennlp_rc/eval/orb_eval.py
from typing import List, Tuple from allennlp_rc.eval.squad_eval import exact_match_score, f1_score from allennlp_rc.eval.drop_eval import get_metrics as drop_metrics from allennlp_rc.eval.narrativeqa_eval import get_metric_score as get_metric_narrativeqa from allennlp_rc.eval.squad2_eval import get_metric_score as get_...
allennlp-reading-comprehension-master
allennlp_rc/eval/orb_utils.py
""" This evaluation script relies heavily on the one for DROP (``allennlp/tools/drop_eval.py``). We need a separate script for Quoref only because the data formats are slightly different. """ import json from typing import Dict, Tuple, List, Any, Optional import argparse import numpy as np from allennlp_rc.eval impor...
allennlp-reading-comprehension-master
allennlp_rc/eval/quoref_eval.py
"""Official evaluation script for SQuAD version 2.0. """ import collections import re import string def make_qid_to_has_ans(dataset): qid_to_has_ans = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: qid_to_has_ans[qa["id"]] = bool(qa["answers...
allennlp-reading-comprehension-master
allennlp_rc/eval/squad2_eval.py
from typing import Tuple from allennlp.training.metrics.metric import Metric from overrides import overrides from allennlp_rc.eval import squad_eval @Metric.register("squad") class SquadEmAndF1(Metric): """ This :class:`Metric` takes the best span string computed by a model, along with the answer string...
allennlp-reading-comprehension-master
allennlp_rc/eval/squad_em_and_f1.py
#!/usr/bin/python from collections import defaultdict from typing import Any, Dict, List, Set, Tuple, Union, Optional import json import argparse import string import re import numpy as np from scipy.optimize import linear_sum_assignment # From here through _normalize_answer was originally copied from: # https://wo...
allennlp-reading-comprehension-master
allennlp_rc/eval/drop_eval.py
from typing import Tuple, List, Union from allennlp.training.metrics.metric import Metric from overrides import overrides from allennlp_rc.eval.drop_eval import get_metrics as drop_em_and_f1, answer_json_to_strings from allennlp_rc.eval.squad_eval import metric_max_over_ground_truths @Metric.register("drop") class ...
allennlp-reading-comprehension-master
allennlp_rc/eval/drop_em_and_f1.py
import pathlib PROJECT_ROOT = (pathlib.Path(__file__).parent / "..").resolve() # pylint: disable=no-member TESTS_ROOT = PROJECT_ROOT / "tests" FIXTURES_ROOT = PROJECT_ROOT / "test_fixtures"
allennlp-reading-comprehension-master
tests/__init__.py
from allennlp_rc import version class TestVersion: def test_version_exists(self): assert version.VERSION.startswith(version.VERSION_SHORT)
allennlp-reading-comprehension-master
tests/version_test.py
import pytest from allennlp.common import Params from allennlp.common.util import ensure_list from allennlp_rc.dataset_readers import TriviaQaReader from tests import FIXTURES_ROOT class TestTriviaQaReader: @pytest.mark.parametrize("lazy", (True, False)) def test_read(self, lazy): params = Params( ...
allennlp-reading-comprehension-master
tests/dataset_readers/triviaqa_test.py
import pytest from allennlp.common import Params from allennlp.common.util import ensure_list from allennlp_rc.dataset_readers import TransformerSquadReader from tests import FIXTURES_ROOT class TestTransformerSquadReader: def test_read_from_file(self): reader = TransformerSquadReader() instance...
allennlp-reading-comprehension-master
tests/dataset_readers/transformer_squad_test.py
allennlp-reading-comprehension-master
tests/dataset_readers/__init__.py
import pytest from allennlp.common import Params from allennlp.common.util import ensure_list from allennlp_rc.dataset_readers import DropReader from tests import FIXTURES_ROOT class TestDropReader: @pytest.mark.parametrize("lazy", (True, False)) def test_read_from_file(self, lazy): reader = DropRea...
allennlp-reading-comprehension-master
tests/dataset_readers/drop_test.py
import pytest from allennlp.common.testing import AllenNlpTestCase from allennlp.data.tokenizers import SpacyTokenizer from allennlp_rc.dataset_readers import util class TestReadingComprehensionUtil(AllenNlpTestCase): def test_char_span_to_token_span_handles_easy_cases(self): # These are _inclusive_ span...
allennlp-reading-comprehension-master
tests/dataset_readers/util_test.py
import pytest from allennlp.common import Params from allennlp.common.util import ensure_list from allennlp_rc.dataset_readers import QuACReader from tests import FIXTURES_ROOT class TestQuACReader: @pytest.mark.parametrize("lazy", (True, False)) def test_read(self, lazy): params = Params({"lazy": l...
allennlp-reading-comprehension-master
tests/dataset_readers/quac_test.py
import pytest from allennlp.common import Params from allennlp.common.util import ensure_list from allennlp_rc.dataset_readers import QangarooReader from tests import FIXTURES_ROOT class TestQangarooReader: @pytest.mark.parametrize("lazy", (True, False)) def test_read_from_file(self, lazy): reader =...
allennlp-reading-comprehension-master
tests/dataset_readers/qangaroo_test.py
import pytest from allennlp.common import Params from allennlp.common.util import ensure_list from allennlp_rc.dataset_readers import SquadReader from tests import FIXTURES_ROOT class TestSquadReader: @pytest.mark.parametrize("lazy", (True, False)) def test_read_from_file(self, lazy): reader = Squad...
allennlp-reading-comprehension-master
tests/dataset_readers/squad_test.py
allennlp-reading-comprehension-master
tests/predictors/__init__.py
from allennlp.common.testing import AllenNlpTestCase from allennlp.data import Vocabulary from allennlp_rc.dataset_readers import TransformerSquadReader from allennlp_rc.models import TransformerQA from allennlp_rc.predictors import TransformerQAPredictor class TestTransformerQAPredictor(AllenNlpTestCase): def s...
allennlp-reading-comprehension-master
tests/predictors/transformer_qa_test.py
from allennlp.models.archival import load_archive from allennlp.predictors import Predictor from tests import FIXTURES_ROOT class TestDialogQAPredictor: def test_uses_named_inputs(self): inputs = { "paragraphs": [ { "qas": [ { ...
allennlp-reading-comprehension-master
tests/predictors/dialog_qa_test.py
from pytest import approx from allennlp.common.testing import AllenNlpTestCase from allennlp.models.archival import load_archive from allennlp.predictors import Predictor from allennlp_rc import predictors from tests import FIXTURES_ROOT class TestBidafPredictor(AllenNlpTestCase): def test_uses_named_inputs(sel...
allennlp-reading-comprehension-master
tests/predictors/reading_comprehension_test.py
from flaky import flaky import pytest import numpy from numpy.testing import assert_almost_equal import torch from allennlp.common import Params from allennlp.common.checks import ConfigurationError from allennlp.common.testing import ModelTestCase from allennlp.data import DatasetReader, Vocabulary from allennlp.data...
allennlp-reading-comprehension-master
tests/models/bidaf_test.py
import numpy import torch from flaky import flaky from allennlp.common.testing import ModelTestCase from allennlp.data.dataset import Batch from allennlp_rc.models.bidaf_ensemble import BidafEnsemble, ensemble from tests import FIXTURES_ROOT class BidafEnsembleTest(ModelTestCase): def setUp(self): super...
allennlp-reading-comprehension-master
tests/models/bidaf_ensemble_test.py
from flaky import flaky from allennlp.common.testing import ModelTestCase from tests import FIXTURES_ROOT import allennlp_rc class NumericallyAugmentedQaNetTest(ModelTestCase): def setUp(self): super().setUp() self.set_up_model( FIXTURES_ROOT / "naqanet" / "experiment.json", FIXTURE...
allennlp-reading-comprehension-master
tests/models/naqanet_test.py
import torch import pytest from flaky import flaky import numpy from numpy.testing import assert_almost_equal from allennlp.common import Params from allennlp.common.testing import ModelTestCase from allennlp.data import DatasetReader, Vocabulary from allennlp.data.dataset import Batch from allennlp.data import DataLo...
allennlp-reading-comprehension-master
tests/models/qanet_test.py
allennlp-reading-comprehension-master
tests/models/__init__.py
from flaky import flaky import numpy from numpy.testing import assert_almost_equal from allennlp.common.testing import ModelTestCase from allennlp.data.dataset import Batch from tests import FIXTURES_ROOT import allennlp_rc # noqa F401: Needed to register the registrables. class TransformerQaTest(ModelTestCase): ...
allennlp-reading-comprehension-master
tests/models/transformer_qa_test.py
from numpy.testing import assert_almost_equal import torch from allennlp.common.testing import AllenNlpTestCase from allennlp_rc.models.util import get_best_span from tests import FIXTURES_ROOT class TestRcUtil(AllenNlpTestCase): def test_get_best_span(self): span_begin_probs = torch.FloatTensor([[0.1, 0...
allennlp-reading-comprehension-master
tests/models/util_test.py
from allennlp.common.testing import ModelTestCase from allennlp.data.dataset import Batch from tests import FIXTURES_ROOT import allennlp_rc class DialogQATest(ModelTestCase): def setUp(self): super().setUp() self.set_up_model( FIXTURES_ROOT / "dialog_qa" / "experiment.json", ...
allennlp-reading-comprehension-master
tests/models/dialog_qa_test.py
from allennlp.interpret.attackers import Hotflip from allennlp.interpret.attackers.hotflip import DEFAULT_IGNORE_TOKENS from allennlp.models import load_archive from allennlp.predictors import Predictor import allennlp_rc from tests import FIXTURES_ROOT class TestHotflip: def test_using_squad_model(self): ...
allennlp-reading-comprehension-master
tests/interpret/hotflip_test.py
allennlp-reading-comprehension-master
tests/interpret/__init__.py