python_code
stringlengths
0
187k
repo_name
stringlengths
8
46
file_path
stringlengths
6
135
# pylint: disable=no-self-use,invalid-name from allennlp_models.rc.tools.squad import normalize_answer as _normalize_answer_squad from allennlp_models.rc.tools.orb_utils import get_metric_squad, get_metric_drop from allennlp_models.rc.tools.narrativeqa import get_metric_score as get_metric_narrativeqa from tests impor...
allennlp-models-main
tests/rc/evaluations/orb_test.py
import pytest from allennlp_models.rc.dataset_readers.utils import char_span_to_token_span @pytest.mark.parametrize( "token_offsets, character_span, expected_result", [ ([(0, 3), (4, 4), (5, 8)], (5, 8), ((2, 2), False)), ([(0, 3), (4, 4), (5, 8)], (4, 8), ((1, 2), False)), ([(0, 3), ...
allennlp-models-main
tests/rc/dataset_readers/utils_test.py
from allennlp.common.params import Params from allennlp.common.util import ensure_list from allennlp.data import DatasetReader import pytest from allennlp_models.rc import TransformerSquadReader from tests import FIXTURES_ROOT class TestTransformerSquadReader: def test_from_params(self): with pytest.warn...
allennlp-models-main
tests/rc/dataset_readers/transformer_squad_test.py
allennlp-models-main
tests/rc/dataset_readers/__init__.py
import pytest from allennlp.common import Params from allennlp.common.util import ensure_list from allennlp_models.rc import DropReader from tests import FIXTURES_ROOT class TestDropReader: def test_read_from_file(self): reader = DropReader() instances = ensure_list(reader.read(FIXTURES_ROOT / "...
allennlp-models-main
tests/rc/dataset_readers/drop_test.py
import pytest from allennlp.data.tokenizers import WhitespaceTokenizer from allennlp.data.token_indexers import SingleIdTokenIndexer from tests import FIXTURES_ROOT import re from typing import List from allennlp_models.rc.dataset_readers.record_reader import RecordTaskReader """ Tests for the ReCoRD reader from Supe...
allennlp-models-main
tests/rc/dataset_readers/record_reader_test.py
import pytest from allennlp.common import Params from allennlp.common.util import ensure_list from allennlp_models.rc import QangarooReader from tests import FIXTURES_ROOT class TestQangarooReader: def test_read_from_file(self): reader = QangarooReader() instances = ensure_list(reader.read(FIXTU...
allennlp-models-main
tests/rc/dataset_readers/qangaroo_test.py
from allennlp.common import Params from allennlp.common.util import ensure_list from allennlp.data import DatasetReader import pytest from allennlp_models.rc import SquadReader from allennlp_models.rc.dataset_readers.squad import SQUAD2_NO_ANSWER_TOKEN from tests import FIXTURES_ROOT class TestSquadReader: def t...
allennlp-models-main
tests/rc/dataset_readers/squad_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_models.rc import ReadingComprehensionPredictor from tests import FIXTURES_ROOT class TestBidafPredictor(AllenNlpTestCase): def...
allennlp-models-main
tests/rc/predictors/bidaf_test.py
allennlp-models-main
tests/rc/predictors/__init__.py
from allennlp.common.testing import AllenNlpTestCase from allennlp.data import Vocabulary from allennlp_models.rc import TransformerSquadReader from allennlp_models.rc import TransformerQA from allennlp_models.rc import TransformerQAPredictor class TestTransformerQAPredictor(AllenNlpTestCase): def setup_method(s...
allennlp-models-main
tests/rc/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-models-main
tests/rc/predictors/dialog_qa_test.py
from flaky import flaky import pytest import numpy from numpy.testing import assert_almost_equal import torch from allennlp.commands.train import train_model_from_file from allennlp.common import Params from allennlp.common.checks import ConfigurationError from allennlp.common.testing import AllenNlpTestCase, ModelTes...
allennlp-models-main
tests/rc/models/bidaf_test.py
import numpy import torch from flaky import flaky from allennlp.common.testing import ModelTestCase from allennlp.data import Batch from allennlp_models.rc import BidafEnsemble from tests import FIXTURES_ROOT class BidafEnsembleTest(ModelTestCase): def setup_method(self): super().setup_method() ...
allennlp-models-main
tests/rc/models/bidaf_ensemble_test.py
from numpy.testing import assert_almost_equal import torch from allennlp.common.testing import AllenNlpTestCase from allennlp_models.rc.models.utils import get_best_span class TestRcUtil(AllenNlpTestCase): def test_get_best_span(self): span_begin_probs = torch.FloatTensor([[0.1, 0.3, 0.05, 0.3, 0.25]]).l...
allennlp-models-main
tests/rc/models/utils_test.py
from allennlp.common.testing import ModelTestCase from tests import FIXTURES_ROOT from allennlp_models.rc import NumericallyAugmentedQaNet class NumericallyAugmentedQaNetTest(ModelTestCase): def setup_method(self): super().setup_method() self.set_up_model( FIXTURES_ROOT / "rc" / "naq...
allennlp-models-main
tests/rc/models/naqanet_test.py
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 import Batch from allennlp.models import Model from allennlp_models import rc ...
allennlp-models-main
tests/rc/models/qanet_test.py
allennlp-models-main
tests/rc/models/__init__.py
import numpy from numpy.testing import assert_almost_equal from allennlp.commands.train import train_model_from_file from allennlp.common.testing import ModelTestCase, AllenNlpTestCase, requires_gpu from allennlp.data import Batch from tests import FIXTURES_ROOT import pytest import torch import allennlp_models.rc c...
allennlp-models-main
tests/rc/models/transformer_qa_test.py
from allennlp.common.testing import ModelTestCase from allennlp.data import Batch import torch import allennlp_models.rc from tests import FIXTURES_ROOT class DialogQATest(ModelTestCase): def setup_method(self): super().setup_method() self.set_up_model( FIXTURES_ROOT / "rc" / "dialog_...
allennlp-models-main
tests/rc/models/dialog_qa_test.py
from allennlp.common import Params from allennlp.common.util import ensure_list from allennlp_models.rc import QuACReader from tests import FIXTURES_ROOT class TestQuACReader: def test_read(self): params = Params({"num_context_answers": 2}) reader = QuACReader.from_params(params) instance...
allennlp-models-main
tests/rc/models/quac_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_models.rc from tests import FIXTURES_ROOT class TestHotflip: def test_using_squad_model(self):...
allennlp-models-main
tests/rc/interpret/bidaf_hotflip_test.py
allennlp-models-main
tests/rc/interpret/__init__.py
allennlp-models-main
tests/rc/modules/__init__.py
import torch from torch.nn.parallel.data_parallel import DataParallel from allennlp.common.testing import AllenNlpTestCase, requires_multi_gpu from allennlp_models.rc.modules.seq2seq_encoders.stacked_self_attention import ( StackedSelfAttentionEncoder, ) class TestStackedSelfAttention(AllenNlpTestCase): def...
allennlp-models-main
tests/rc/modules/seq2seq_encoders/stacked_self_attention_test.py
import torch from allennlp.common.testing import AllenNlpTestCase from allennlp.common.params import Params from allennlp_models.rc import QaNetEncoder class QaNetEncoderTest(AllenNlpTestCase): def test_qanet_encoder_can_build_from_params(self): params = Params( { "input_dim"...
allennlp-models-main
tests/rc/modules/seq2seq_encoders/qanet_encoder_test.py
allennlp-models-main
tests/rc/modules/seq2seq_encoders/__init__.py
import numpy import torch from allennlp.common.testing import AllenNlpTestCase from allennlp.common.params import Params from allennlp_models.rc.modules.seq2seq_encoders.multi_head_self_attention import ( MultiHeadSelfAttention, ) class MultiHeadSelfAttentionTest(AllenNlpTestCase): def test_multi_head_self_...
allennlp-models-main
tests/rc/modules/seq2seq_encoders/multi_head_self_attention_test.py
allennlp-models-main
tests/generation/__init__.py
import tempfile import pytest from allennlp.common.checks import ConfigurationError from allennlp.common.util import ensure_list from allennlp_models.generation import Seq2SeqDatasetReader from tests import FIXTURES_ROOT class TestSeq2SeqDatasetReader: def test_default_format(self): reader = Seq2SeqData...
allennlp-models-main
tests/generation/dataset_readers/seq2seq_test.py
allennlp-models-main
tests/generation/dataset_readers/__init__.py
import numpy as np import torch from allennlp.common import Params from allennlp.common.testing import AllenNlpTestCase from allennlp.common.util import ensure_list from allennlp.data import DatasetReader from allennlp.data.fields import TensorField from allennlp.data.vocabulary import Vocabulary, DEFAULT_OOV_TOKEN f...
allennlp-models-main
tests/generation/dataset_readers/copynet_test.py
from allennlp.common.testing import AllenNlpTestCase from allennlp.models.archival import load_archive from allennlp.predictors import Predictor from allennlp_models.generation.predictors import Seq2SeqPredictor from tests import FIXTURES_ROOT class TestSeq2SeqPredictor(AllenNlpTestCase): def test_uses_named_inp...
allennlp-models-main
tests/generation/predictors/seq2seq_test.py
allennlp-models-main
tests/generation/predictors/__init__.py
from allennlp.common.testing import ModelTestCase from tests import FIXTURES_ROOT from allennlp_models import generation # noqa: F401 class T5Test(ModelTestCase): def setup_method(self): super().setup_method() self.set_up_model( FIXTURES_ROOT / "generation" / "t5" / "experiment.json...
allennlp-models-main
tests/generation/models/t5_test.py
allennlp-models-main
tests/generation/models/__init__.py
import numpy as np import pytest import torch from _pytest.mark import param from allennlp.commands.train import train_model_from_file from allennlp.common import Params from allennlp.common.testing import ModelTestCase, requires_gpu from allennlp.data import Batch, DatasetReader from allennlp.models import Model from ...
allennlp-models-main
tests/generation/models/copynet_test.py
import json import numpy import pytest import torch from allennlp.models import Model from allennlp.common import Params from allennlp.commands.train import train_model_from_file from allennlp.common.testing import ModelTestCase, requires_gpu from allennlp.nn.beam_search import BeamSearch from allennlp.nn.util import...
allennlp-models-main
tests/generation/models/simple_seq2seq_test.py
import pytest from allennlp.common import Params from allennlp.common.testing import ModelTestCase from allennlp.models import Model from allennlp_models import generation # noqa: F401 from tests import FIXTURES_ROOT class BartTest(ModelTestCase): def setup_method(self): super().setup_method() se...
allennlp-models-main
tests/generation/models/bart_test.py
import json from allennlp.common.testing import ModelTestCase from tests import FIXTURES_ROOT class ComposedSeq2SeqTest(ModelTestCase): def setup_method(self): super().setup_method() self.set_up_model( FIXTURES_ROOT / "generation" / "composed" / "experiment.json", FIXTURE...
allennlp-models-main
tests/generation/models/composed_seq2seq_test.py
allennlp-models-main
tests/generation/modules/__init__.py
allennlp-models-main
tests/generation/modules/seq_decoders/__init__.py
from typing import Any, Iterable, Dict import pytest import torch from allennlp.common import Lazy, Params from allennlp.common.checks import ConfigurationError from allennlp.common.testing import AllenNlpTestCase from allennlp.common.util import END_SYMBOL, prepare_environment, START_SYMBOL from allennlp.data.vocab...
allennlp-models-main
tests/generation/modules/seq_decoders/auto_regressive_test.py
import torch from allennlp.common.testing import AllenNlpTestCase from allennlp_models.generation import StackedSelfAttentionDecoderNet class TestStackedSelfAttentionDecoderNet(AllenNlpTestCase): def test_stacked_self_attention_decoder_net_init(self): decoder_inout_dim = 10 decoder_net = Stacked...
allennlp-models-main
tests/generation/modules/decoder_nets/stacked_self_attention_test.py
allennlp-models-main
tests/generation/modules/decoder_nets/__init__.py
import torch from allennlp.common.testing import AllenNlpTestCase from allennlp.modules.attention import DotProductAttention from allennlp_models.generation.modules.decoder_nets.lstm_cell import LstmCellDecoderNet class TestLstmCellDecoderNet(AllenNlpTestCase): def test_lstm_cell_decoder_net_init(self): ...
allennlp-models-main
tests/generation/modules/decoder_nets/lstm_cell_test.py
allennlp-models-main
tests/coref/__init__.py
import torch from allennlp.common.testing import ( multi_device, AllenNlpTestCase, global_distributed_metric, run_distributed_test, ) from allennlp_models.coref.metrics.conll_coref_scores import ConllCorefScores class ConllCorefScoresTest(AllenNlpTestCase): @multi_device def test_get_predict...
allennlp-models-main
tests/coref/metrics/conll_coref_scores_test.py
allennlp-models-main
tests/coref/metrics/__init__.py
import torch from allennlp.common.testing import ( AllenNlpTestCase, global_distributed_metric, run_distributed_test, ) from allennlp_models.coref.metrics.mention_recall import MentionRecall class MentionRecallTest(AllenNlpTestCase): def test_mention_recall(self): metric = MentionRecall() ...
allennlp-models-main
tests/coref/metrics/mention_recall_test.py
from typing import List, Tuple from allennlp.common.util import ensure_list from allennlp.common.testing import AllenNlpTestCase from allennlp_models.coref import WinobiasReader from tests import FIXTURES_ROOT class TestWinobiasReader: span_width = 5 def test_read_from_file(self): conll_reader = Wi...
allennlp-models-main
tests/coref/dataset_readers/winobias_test.py
from typing import List, Tuple import pytest from allennlp.common.util import ensure_list from allennlp.common.testing import AllenNlpTestCase from allennlp_models.coref import PrecoReader from tests import FIXTURES_ROOT class TestPrecoReader: span_width = 5 @pytest.mark.parametrize("remove_singleton_clus...
allennlp-models-main
tests/coref/dataset_readers/preco_test.py
allennlp-models-main
tests/coref/dataset_readers/__init__.py
from typing import List, Tuple from allennlp.data.tokenizers import PretrainedTransformerTokenizer from allennlp.common.util import ensure_list from allennlp.common.testing import AllenNlpTestCase from allennlp_models.coref import ConllCorefReader from tests import FIXTURES_ROOT class TestCorefReader: span_widt...
allennlp-models-main
tests/coref/dataset_readers/coref_test.py
allennlp-models-main
tests/coref/predictors/__init__.py
import spacy from allennlp.common.testing import AllenNlpTestCase from allennlp.models.archival import load_archive from allennlp.predictors import Predictor from allennlp_models.coref import CorefPredictor from tests import FIXTURES_ROOT class TestCorefPredictor(AllenNlpTestCase): def test_uses_named_inputs(s...
allennlp-models-main
tests/coref/predictors/coref_test.py
allennlp-models-main
tests/coref/models/__init__.py
import torch from allennlp.common.testing import ModelTestCase from allennlp_models import coref # noqa: F401 from tests import FIXTURES_ROOT class CorefTest(ModelTestCase): def setup_method(self): super().setup_method() self.set_up_model( FIXTURES_ROOT / "coref" / "experiment.json"...
allennlp-models-main
tests/coref/models/coref_test.py
allennlp-models-main
tests/coref/interpret/__init__.py
from pytest import approx from allennlp.common.testing import AllenNlpTestCase from allennlp.interpret.saliency_interpreters import SimpleGradient from allennlp.models.archival import load_archive from allennlp.predictors import Predictor from tests import FIXTURES_ROOT class TestInterpret(AllenNlpTestCase): de...
allennlp-models-main
tests/coref/interpret/interpret_test.py
#!/usr/bin/env python """ Ensures models are automatically found by allennlp. """ import logging from allennlp.common.plugins import import_plugins from allennlp.models import Model logging.basicConfig(level=logging.INFO) import_plugins() Model.by_name("copynet_seq2seq")
allennlp-models-main
scripts/ensure_models_found.py
""" Run this script to update the list of pre-trained models in the README based on the current model cards. """ from typing import List import json import glob AUTO_GENERATED_SECTION_START = "<!-- This section is automatically generated" AUTO_GENERATED_SECTION_END = "<!-- End automatically generated section -->" ...
allennlp-models-main
scripts/update_readme_model_list.py
#!/usr/bin/env python """ This script is used to populate the table of contents for the API in the mkdocs config file. """ import argparse from pathlib import Path from typing import Any, List from ruamel.yaml import YAML from allennlp_models.version import VERSION API_TOC_KEY = "Models" def parse_args(): p...
allennlp-models-main
scripts/build_docs_config.py
#!/usr/bin/env python """ Ensures allennlp and models versions are the same. """ from allennlp.version import VERSION as CORE_VERSION from allennlp_models.version import VERSION as MODELS_VERSION assert CORE_VERSION == MODELS_VERSION, f"core: {CORE_VERSION}, models: {MODELS_VERSION}"
allennlp-models-main
scripts/ensure_versions_match.py
#!/usr/bin/env python3 import argparse from typing import Dict def parse_args(): parser = argparse.ArgumentParser() parser.add_argument("version_type", choices=["stable", "latest", "current"]) parser.add_argument("--minimal", action="store_true", default=False) parser.add_argument("--as-range", actio...
allennlp-models-main
scripts/get_version.py
import argparse import random from utils import read_csv, write_array2tsv, head_based_split, count_relation def load_conceptnet(args): random.seed(args.random_seed) cn_train_file = args.data_folder + args.data_file cn_train_data = read_csv(cn_train_file, delimiter="\t") train_data = [[l[1], l[0], l[...
comet-atomic-2020-master
split/split_conceptnet.py
from utils import read_csv, write_tsv def tuple_key(d): return d[0] + d[1] + d[2] def main(): folder = "./data/transomcs/" file = folder + "TransOMCS_full.txt" data = read_csv(file, delimiter="\t") confidences = {} for d in data: key = tuple_key(d) confidences[key] = float(...
comet-atomic-2020-master
split/filter_human_eval_tuples_with_updated_transomcs.py
import argparse import random from utils import read_csv, write_array2tsv def load_atomic(args): random.seed(args.random_seed) atomic_split_folder = args.data_folder + "original_split/" atomic_file = args.data_folder + args.data_file atomic_data = read_csv(atomic_file, delimiter="\t", skip_header=T...
comet-atomic-2020-master
split/split_atomic.py
comet-atomic-2020-master
split/__init__.py
import argparse import random from utils import read_csv, write_array2tsv, head_based_split def load_transomcs(args): import matplotlib.pyplot as plt random.seed(args.random_seed) data_file = args.data_folder + args.data_file data = read_csv(data_file, delimiter="\t") selection = [[l[0], l[1],...
comet-atomic-2020-master
split/split_transomcs.py
import json import sys import csv import operator import random def read_csv(input_file, quotechar='"', delimiter=",", skip_header=False): """Reads a tab separated value file.""" with open(input_file, "r") as f: reader = csv.reader(f, delimiter=delimiter, quotechar=quotechar, quoting=csv.QUOTE_ALL, sk...
comet-atomic-2020-master
split/utils.py
import argparse import random from utils import read_csv, write_jsonl def sample_kg(args): random.seed(args.random_seed) data_file = args.input_file data = read_csv(data_file, delimiter="\t") prefixes = {} for l in data: prefix = l[0] + " " + l[1] if prefix not in prefixes.keys...
comet-atomic-2020-master
split/sample_prefixes.py
import argparse import random from utils import read_csv, write_array2tsv, head_based_split, get_head_set def load_atomic2020(args): random.seed(args.random_seed) atomic2020_v1_file = args.data_folder + "atomic_original_tuples.tsv" atomic2020_addl_file = args.data_folder + "atomic_additional_tuples.tsv"...
comet-atomic-2020-master
split/split_atomic2020.py
comet-atomic-2020-master
mosaic/__init__.py
# Importing stock libraries import numpy as np import pandas as pd import torch import torch.nn.functional as F from torch.utils.data import Dataset, DataLoader, RandomSampler, SequentialSampler # Importing the T5 modules from huggingface/transformers from transformers import T5Tokenizer, T5ForConditionalGeneration #...
comet-atomic-2020-master
mosaic/infra/logging.py
# Importing stock libraries import numpy as np import pandas as pd import torch import torch.nn.functional as F from torch.utils.data import Dataset, DataLoader, RandomSampler, SequentialSampler # Importing the T5 modules from huggingface/transformers from transformers import T5Tokenizer, T5ForConditionalGeneration #...
comet-atomic-2020-master
mosaic/infra/modeling.py
# Importing stock libraries import numpy as np import pandas as pd import torch import torch.nn.functional as F from torch.utils.data import Dataset, DataLoader, RandomSampler, SequentialSampler # Importing the T5 modules from huggingface/transformers from transformers import T5Tokenizer, T5ForConditionalGeneration #...
comet-atomic-2020-master
mosaic/datasets/KGDataset.py
comet-atomic-2020-master
mosaic/datasets/__init__.py
from nltk import pos_tag, word_tokenize from nltk.corpus import stopwords from nltk.stem import WordNetLemmatizer import csv import argparse import os exact2tokenized = {} tokenized2pos = {} pos2content = {} def main(): print('\n#######################') print('Preprocess Part 2') print('################...
comet-atomic-2020-master
human_eval/coverage/preprocess_kb_triples_part2.py
import pandas as pd from collections import OrderedDict import csv import os import argparse def main(): print('\n#######################') print('Calculate Coverage') print('#######################') # OUTPUT DIR output_dir = os.path.join(args.data_dir, 'output-x') print("Outputting matche...
comet-atomic-2020-master
human_eval/coverage/calculate_coverage.py
import pandas as pd import string import argparse import os str2exact = {} def main(): print('\n#######################') print('Preprocess Part 1') print('#######################') data_dir = [(os.path.join(args.data_dir,'atomic2020.tsv'),'atomic2020'), (os.path.join(args.data_dir,'c...
comet-atomic-2020-master
human_eval/coverage/preprocess_kb_triples_part1.py
import argparse import logging import os from pathlib import Path from typing import Any, Dict import pytorch_lightning as pl from pytorch_lightning.utilities import rank_zero_info from transformers import ( AdamW, AutoConfig, AutoModel, AutoModelForPreTraining, AutoModelForQuestionAnswering, ...
comet-atomic-2020-master
models/comet_atomic2020_bart/lightning_base.py
import itertools import json import linecache import os import pickle import warnings from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import numpy as np import torch from rouge_score import rouge_scorer, scoring from sacrebleu import corpus_bleu from ...
comet-atomic-2020-master
models/comet_atomic2020_bart/utils.py
import logging import os from pathlib import Path import numpy as np import pytorch_lightning as pl import torch from pytorch_lightning.callbacks import ModelCheckpoint from pytorch_lightning.utilities import rank_zero_only def count_trainable_parameters(model): model_parameters = filter(lambda p: p.requires_gra...
comet-atomic-2020-master
models/comet_atomic2020_bart/callbacks.py
import json import torch import argparse from tqdm import tqdm from pathlib import Path from transformers import AutoModelForSeq2SeqLM, AutoTokenizer from utils import calculate_rouge, use_task_specific_params, calculate_bleu_score, trim_batch def chunks(lst, n): """Yield successive n-sized chunks from lst.""" ...
comet-atomic-2020-master
models/comet_atomic2020_bart/generation_example.py
import argparse import glob import logging import os import time import warnings from collections import defaultdict from pathlib import Path from typing import Dict, List, Tuple import numpy as np import pytorch_lightning as pl import torch from torch.utils.data import DataLoader from lightning_base import BaseTrans...
comet-atomic-2020-master
models/comet_atomic2020_bart/finetune.py
import argparse import gc import os from pathlib import Path from typing import List import pytorch_lightning as pl import torch from torch import nn from torch.nn import functional as F from lightning_base import generic_train from transformers import AdamW, BartConfig, BartForConditionalGeneration, T5Config, T5ForC...
comet-atomic-2020-master
models/comet_atomic2020_bart/distillation.py
# Importing stock libraries import json from typing import List import numpy as np import pandas as pd import torch import torch.nn.functional as F from torch.utils.data import Dataset, DataLoader, RandomSampler, SequentialSampler # Importing the T5 modules from huggingface/transformers from transformers import T5Tok...
comet-atomic-2020-master
models/gpt2_zeroshot/gpt2-zeroshot.py
# Importing stock libraries import numpy as np import pandas as pd import torch import torch.nn.functional as F from torch.utils.data import Dataset, DataLoader, RandomSampler, SequentialSampler import json from typing import List # Importing the GPT2 modules from huggingface/transformers from transformers import GPT2...
comet-atomic-2020-master
models/comet_atomic2020_gpt2/comet_gpt2.py
import csv relations = set() with open('../old_data/atomic2020_train.tsv') as file: reader = csv.DictReader(file, delimiter='\t') for row in reader: relations.add(row['relation']) with open('../old_data/atomic_train.tsv') as file: reader = csv.DictReader(file, delimiter='\t') for row in reader...
comet-atomic-2020-master
scripts/retrieve_special_tokens.py
import sys import csv writer = csv.DictWriter(open('../data/atomic_test.tsv', 'w'), delimiter='\t', fieldnames=['relation', 'head_event', 'tail_event']) writer.writeheader() with open(sys.argv[1]) as file: reader = csv.DictReader(file, delimiter='\t', fieldnames=['head', 'relation', 'tail', 'id1', 'id2', 'score']...
comet-atomic-2020-master
scripts/convert_atomic.py
import sys import csv writer = csv.DictWriter(open(f'../data/{sys.argv[1].split("/")[-1].split("_")[0]}_{sys.argv[1].split("/")[-1].split("_")[-1].split(".")[0]}.tsv', 'w'), delimiter='\t', fieldnames=['relation', 'head_event', 'tail_event']) writer.writeheader() with open(sys.argv[1]) as file: reader = csv.DictR...
comet-atomic-2020-master
scripts/convert_ronan.py
import pandas as pd import transformers import os from transformers import T5Tokenizer train_dataset = pd.read_csv('../data/atomic2020_train.tsv', encoding='latin-1', sep="\t") train_dataset = train_dataset[['head_event','tail_event','relation']] train_dataset.head_event = train_dataset.head_event + ' ' + train_datas...
comet-atomic-2020-master
scripts/calculate_max_len.py
import sys import csv writer = csv.DictWriter(open('../data/conceptnet_dev.tsv', 'w'), delimiter='\t', fieldnames=['relation', 'head', 'tail']) writer.writeheader() with open(sys.argv[1]) as file: reader = csv.DictReader(file, delimiter='\t', fieldnames=['relation', 'head', 'tail', 'score']) for row in reader...
comet-atomic-2020-master
scripts/convert_conceptnet.py
import json import sys import csv import operator import random def read_csv(input_file, quotechar='"', delimiter=",", skip_header=False): """Reads a tab separated value file.""" with open(input_file, "r") as f: reader = csv.reader(f, delimiter=delimiter, quotechar=quotechar, quoting=csv.QUOTE_ALL, sk...
comet-atomic-2020-master
system_eval/utils.py
import argparse import numpy as np from nltk.translate.bleu_score import sentence_bleu from utils import read_jsonl, remove_prefix, write_jsonl from evaluation.eval import QGEvalCap from tabulate import tabulate import json import os from collections import defaultdict import random def get_reference_sentences(filenam...
comet-atomic-2020-master
system_eval/automatic_eval.py
comet-atomic-2020-master
system_eval/evaluation/__init__.py
from evaluation.bleu.bleu import Bleu from evaluation.meteor.meteor_nltk import Meteor from evaluation.rouge.rouge import Rouge from evaluation.cider.cider import Cider from evaluation.bert_score.bert_score import BertScore from collections import defaultdict from argparse import ArgumentParser import sys import json ...
comet-atomic-2020-master
system_eval/evaluation/eval.py
# Filename: cider.py # # Description: Describes the class to compute the CIDEr (Consensus-Based Image Description Evaluation) Metric # by Vedantam, Zitnick, and Parikh (http://arxiv.org/abs/1411.5726) # # Creation Date: Sun Feb 8 14:16:54 2015 # # Authors: Ramakrishna Vedantam <vrama91@vt.edu> and Tsung...
comet-atomic-2020-master
system_eval/evaluation/cider/cider.py
__author__ = 'tylin'
comet-atomic-2020-master
system_eval/evaluation/cider/__init__.py