python_code stringlengths 0 187k | repo_name stringlengths 8 46 | file_path stringlengths 6 135 |
|---|---|---|
import logging
import random
from typing import Dict, Callable, Tuple, Union, List, Any, Optional, Sequence
import ai2thor.controller
import lru
import numpy as np
from allenact.utils.system import ImportChecker
from allenact_plugins.ithor_plugin.ithor_environment import IThorEnvironment
from allenact_plugins.ithor_pl... | ai2thor-rearrangement-main | rearrange/utils.py |
import enum
import math
import pprint
import random
import traceback
from collections import OrderedDict
from typing import Dict, Any, Tuple, Optional, Callable, List, Union, Sequence
import ai2thor
import ai2thor.controller
import ai2thor.fifo_server
import ai2thor.server
import ai2thor.wsgi_server
import numpy as np... | ai2thor-rearrangement-main | rearrange/environment.py |
from typing import cast, Dict, Any
import torch
from allenact.algorithms.onpolicy_sync.losses import PPO
from allenact.algorithms.onpolicy_sync.losses.abstract_loss import (
AbstractActorCriticLoss,
)
from allenact.algorithms.onpolicy_sync.policy import ObservationType
from allenact.base_abstractions.distribution... | ai2thor-rearrangement-main | rearrange/losses.py |
import copy
import platform
from abc import abstractmethod
from typing import Optional, List, Sequence, Dict, Any, Tuple
import ai2thor.platform
import gym.spaces
import stringcase
import torch
import torchvision.models
from torch import nn, cuda, optim
from torch.optim.lr_scheduler import LambdaLR
import datagen.dat... | ai2thor-rearrangement-main | baseline_configs/rearrange_base.py |
ai2thor-rearrangement-main | baseline_configs/__init__.py | |
import os
from typing import Type, Optional
import gym
import torch
from torch import nn
from allenact.base_abstractions.sensor import SensorSuite, Sensor, ExpertActionSensor
from allenact.embodiedai.mapping.mapping_models.active_neural_slam import (
ActiveNeuralSLAM,
)
from allenact.utils.misc_utils import multi... | ai2thor-rearrangement-main | baseline_configs/two_phase/two_phase_rgb_resnet_frozen_map_ppowalkthrough_ilunshuffle.py |
ai2thor-rearrangement-main | baseline_configs/two_phase/__init__.py | |
from abc import ABC
from typing import Optional, Sequence, Dict, Type, Union
import gym
import gym.spaces
from torch import nn
from allenact.base_abstractions.sensor import SensorSuite, Sensor
try:
from allenact.embodiedai.sensors.vision_sensors import DepthSensor
except ImportError:
raise ImportError("Pleas... | ai2thor-rearrangement-main | baseline_configs/two_phase/two_phase_rgb_base.py |
from baseline_configs.two_phase.two_phase_rgb_ppowalkthrough_ilunshuffle import (
TwoPhaseRGBPPOWalkthroughILUnshuffleExperimentConfig,
)
class TwoPhaseRGBResNetPPOWalkthroughILUnshuffleExperimentConfig(
TwoPhaseRGBPPOWalkthroughILUnshuffleExperimentConfig
):
CNN_PREPROCESSOR_TYPE_AND_PRETRAINING = ("RN18... | ai2thor-rearrangement-main | baseline_configs/two_phase/two_phase_rgb_resnet_ppowalkthrough_ilunshuffle.py |
from typing import Dict, Any
from allenact.algorithms.onpolicy_sync.losses.imitation import Imitation
from allenact.algorithms.onpolicy_sync.losses.ppo import PPOConfig
from allenact.base_abstractions.sensor import ExpertActionSensor
from allenact.utils.experiment_utils import LinearDecay, PipelineStage
from baseline_... | ai2thor-rearrangement-main | baseline_configs/two_phase/two_phase_rgb_ppowalkthrough_ilunshuffle.py |
from typing import Dict, Any, cast
import gym
import torch
from allenact.algorithms.onpolicy_sync.losses import PPO
from allenact.algorithms.onpolicy_sync.losses.ppo import PPOConfig
from allenact.base_abstractions.sensor import SensorSuite
from allenact.embodiedai.mapping.mapping_losses import (
BinnedPointCloud... | ai2thor-rearrangement-main | baseline_configs/walkthrough/walkthrough_rgb_mapping_ppo.py |
ai2thor-rearrangement-main | baseline_configs/walkthrough/__init__.py | |
from typing import Optional, Sequence, Dict
from allenact.base_abstractions.sensor import SensorSuite, Sensor
try:
from allenact.embodiedai.sensors.vision_sensors import DepthSensor
except ImportError:
raise ImportError("Please update to allenact>=0.4.0.")
from baseline_configs.rearrange_base import Rearrang... | ai2thor-rearrangement-main | baseline_configs/walkthrough/walkthrough_rgb_base.py |
from baseline_configs.walkthrough.walkthrough_rgb_ppo import (
WalkthroughPPOExperimentConfig,
)
class WalkthroughRGBResNetPPOExperimentConfig(WalkthroughPPOExperimentConfig):
CNN_PREPROCESSOR_TYPE_AND_PRETRAINING = ("RN18", "imagenet")
@classmethod
def tag(cls) -> str:
return "WalkthroughRGB... | ai2thor-rearrangement-main | baseline_configs/walkthrough/walkthrough_rgb_resnet_ppo.py |
from typing import Dict, Any
from allenact.algorithms.onpolicy_sync.losses import PPO
from allenact.algorithms.onpolicy_sync.losses.ppo import PPOConfig
from allenact.utils.experiment_utils import LinearDecay, PipelineStage
from baseline_configs.walkthrough.walkthrough_rgb_base import (
WalkthroughBaseExperimentCo... | ai2thor-rearrangement-main | baseline_configs/walkthrough/walkthrough_rgb_ppo.py |
import os
from typing import Sequence
import gym
import torch
from torch import nn
from allenact.base_abstractions.sensor import SensorSuite, Sensor
from allenact.embodiedai.mapping.mapping_models.active_neural_slam import (
ActiveNeuralSLAM,
)
from allenact.utils.misc_utils import multiprocessing_safe_download_f... | ai2thor-rearrangement-main | baseline_configs/one_phase/one_phase_rgb_resnet_frozen_map_dagger.py |
from typing import Tuple, Sequence, Optional, Dict, Any
import torch
from allenact.algorithms.onpolicy_sync.losses.imitation import Imitation
from allenact.base_abstractions.sensor import ExpertActionSensor, Sensor
from allenact.utils.experiment_utils import PipelineStage
from allenact.utils.misc_utils import all_uni... | ai2thor-rearrangement-main | baseline_configs/one_phase/one_phase_rgb_il_base.py |
from baseline_configs.one_phase.one_phase_rgb_il_base import (
OnePhaseRGBILBaseExperimentConfig,
)
class OnePhaseRGBResNetDaggerExperimentConfig(OnePhaseRGBILBaseExperimentConfig):
CNN_PREPROCESSOR_TYPE_AND_PRETRAINING = ("RN18", "imagenet")
IL_PIPELINE_TYPE = "40proc"
@classmethod
def tag(cls) ... | ai2thor-rearrangement-main | baseline_configs/one_phase/one_phase_rgb_resnet_dagger.py |
ai2thor-rearrangement-main | baseline_configs/one_phase/__init__.py | |
from baseline_configs.one_phase.one_phase_rgb_il_base import (
OnePhaseRGBILBaseExperimentConfig,
)
class OnePhaseRGBClipResNet50DaggerExperimentConfig(OnePhaseRGBILBaseExperimentConfig):
CNN_PREPROCESSOR_TYPE_AND_PRETRAINING = ("RN50", "clip")
IL_PIPELINE_TYPE = "40proc"
@classmethod
def tag(cls... | ai2thor-rearrangement-main | baseline_configs/one_phase/one_phase_rgb_clipresnet50_dagger.py |
import warnings
from abc import ABC
from typing import Optional, Dict, Sequence
from allenact.base_abstractions.sensor import SensorSuite, Sensor
try:
from allenact.embodiedai.sensors.vision_sensors import (
DepthSensor,
IMAGENET_RGB_MEANS,
IMAGENET_RGB_STDS,
)
except ImportError:
... | ai2thor-rearrangement-main | baseline_configs/one_phase/one_phase_rgb_base.py |
from typing import Dict, Any
from allenact.algorithms.onpolicy_sync.losses import PPO
from allenact.algorithms.onpolicy_sync.losses.ppo import PPOConfig
from allenact.utils.experiment_utils import LinearDecay, PipelineStage
from baseline_configs.one_phase.one_phase_rgb_base import (
OnePhaseRGBBaseExperimentConfig... | ai2thor-rearrangement-main | baseline_configs/one_phase/one_phase_rgb_ppo.py |
from baseline_configs.one_phase.one_phase_rgb_il_base import (
OnePhaseRGBILBaseExperimentConfig,
)
class OnePhaseRGBDaggerExperimentConfig(OnePhaseRGBILBaseExperimentConfig):
CNN_PREPROCESSOR_TYPE_AND_PRETRAINING = None
IL_PIPELINE_TYPE = "40proc"
@classmethod
def tag(cls) -> str:
return... | ai2thor-rearrangement-main | baseline_configs/one_phase/one_phase_rgb_dagger.py |
from baseline_configs.one_phase.one_phase_rgb_ppo import OnePhaseRGBPPOExperimentConfig
class OnePhaseRGBResNetPPOExperimentConfig(OnePhaseRGBPPOExperimentConfig):
CNN_PREPROCESSOR_TYPE_AND_PRETRAINING = ("RN18", "imagenet")
@classmethod
def tag(cls) -> str:
return "OnePhaseRGBResNetPPO"
| ai2thor-rearrangement-main | baseline_configs/one_phase/one_phase_rgb_resnet_ppo.py |
from baseline_configs.one_phase.one_phase_rgb_il_base import (
OnePhaseRGBILBaseExperimentConfig,
)
class OnePhaseRGBResNetDaggerExperimentConfig(OnePhaseRGBILBaseExperimentConfig):
CNN_PREPROCESSOR_TYPE_AND_PRETRAINING = ("RN50", "imagenet")
IL_PIPELINE_TYPE = "40proc"
@classmethod
def tag(cls) ... | ai2thor-rearrangement-main | baseline_configs/one_phase/one_phase_rgb_resnet50_dagger.py |
"""A script for generating rearrangement datasets."""
import argparse
import json
import math
import multiprocessing as mp
import os
import platform
import queue
import random
import time
import warnings
from collections import defaultdict
from typing import List, Set, Dict, Optional, Any, cast
import compress_pickle... | ai2thor-rearrangement-main | datagen/datagen_runner.py |
ai2thor-rearrangement-main | datagen/__init__.py | |
OBJECT_TYPES_TO_NOT_MOVE = {
"Apple",
"Bread",
"Cloth",
"HandTowel",
"HandTowelHolder",
"Towel",
"TowelHolder",
"KeyChain",
"Lettuce",
"Pillow",
"Potato",
"Tomato",
}
OBJECT_TYPES_THAT_CAN_HAVE_IDENTICAL_MESHES = [
"AluminumFoil",
"CD",
"Dumbbell",
"Ladle"... | ai2thor-rearrangement-main | datagen/datagen_constants.py |
import json
import os
from collections import defaultdict
import compress_pickle
from allenact.utils.misc_utils import partition_sequence
from rearrange.constants import STARTER_DATA_DIR
def combine(task_limit_for_train: int = 10000):
stages = ("train", "val", "test")
all_data = defaultdict(lambda: [])
... | ai2thor-rearrangement-main | datagen/create_combined_dataset.py |
import random
from collections import defaultdict
from typing import List, Dict, Set, Optional, Any
from ai2thor.controller import Controller
from datagen.datagen_constants import OBJECT_TYPES_THAT_CAN_HAVE_IDENTICAL_MESHES
from rearrange_constants import OPENNESS_THRESHOLD
def get_scenes(stage: str) -> List[str]:
... | ai2thor-rearrangement-main | datagen/datagen_utils.py |
""" Modified from the official evaluation script for v1.0 of the ROPES dataset to add consistency metric"""
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 an... | contrast-sets-main | ropes/evaluate_contrast_set.py |
import argparse
import csv
import json
import os
import numpy as np
from sklearn.metrics import f1_score, accuracy_score
from perspectrum_model import PerspectrumTransformerModel
def evaluate(model_dir, data_path, result_path, cuda=False, **kwargs):
result = _evaluate_stance(model_dir, data_path, cuda)
for... | contrast-sets-main | perspectrum/run_evaluation.py |
import torch
from typing import List
from transformers import (WEIGHTS_NAME, BertConfig,
BertForSequenceClassification, BertTokenizer,
RobertaConfig,
RobertaForSequenceClassification,
RobertaTokenizer,
... | contrast-sets-main | perspectrum/perspectrum_model.py |
from typing import List, Dict, Tuple
from collections import defaultdict
import json
import argparse
"""Script to measure consistency among MTMSN predictions."""
def read_json(input_json):
with open(input_json, "r") as f:
json_data = json.load(f)
return json_data
def make_qid2f1_map(predictions_jso... | contrast-sets-main | DROP/consistency.py |
import json
import sys
import hashlib
from collections import defaultdict
import argparse
def merge_data(args):
all_data = defaultdict(lambda: defaultdict(lambda: {'qas': []})) # {(title, url) -> {context_id -> {}}}
for filename in args.files_to_merge:
file_data = json.load(open(filename))["data"]
... | contrast-sets-main | quoref/merge_perturbed_files.py |
import re
import json
import random
import hashlib
import argparse
import datetime
from collections import defaultdict
def get_answers(context):
print("Enter answer spans below. You can copy text from the context and paste here.")
print("Hit enter if you are done inputting all answer spans")
new_answers =... | contrast-sets-main | quoref/interface.py |
"""
This evaluation script modifies code for the official Quoref evaluator (``allennlp/tools/quoref_eval.py``) to deal
with evaluating on contrast sets.
"""
import json
from typing import Dict, Tuple, List, Any, Set
import argparse
from collections import defaultdict
import numpy as np
from allennlp.tools import drop_... | contrast-sets-main | quoref/compute_metrics.py |
import argparse
import json
from collections import defaultdict
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='Evaluation for NLVR2 contrast set')
parser.add_argument('--prediction-path', help='Prediction path')
args = parser.parse_args()
# prediction file is expect... | contrast-sets-main | nlvr2/eval.py |
import sys
import conllu
import json
from collections import defaultdict
import IPython as ipy
def read_data(filename):
data = open(filename).read()
texts = [t for t in data.split("\n\n") if t.strip() != ""]
trees = []
for text in texts:
trees += conllu.parse(text)
return trees
def count_a... | contrast-sets-main | UD_English/stats.py |
import sys
import json
from collections import defaultdict
import IPython as ipy
def eval_target_predictions(predict_originals_file, predict_altered_file, gold_file):
with open(gold_file,'r') as f:
true_attachments = json.loads(f.read())
predictions_orig = []
with open(predict_originals_file,'r')... | contrast-sets-main | UD_English/eval_json_predictions.py |
def helper(arr):
corr = 0
for a in arr:
if a == 1:
corr += 1
return 1.0*corr/len(arr)
if __name__ == "__main__":
output_labels = {"BEFORE": 0, "AFTER": 1, "EQUAL": 2, "VAGUE": 3}
with open('proposed_elmo_lr0.001.merged.output','r') as f:
content = f.readlines()
... | contrast-sets-main | MATRES/consistency_analysis.py |
import pandas as pd
import nltk
from nltk.stem import WordNetLemmatizer
from nltk.corpus import wordnet
lemmatizer = WordNetLemmatizer()
# function to convert nltk tag to wordnet tag
def nltk_tag_to_wordnet_tag(nltk_tag):
if nltk_tag.startswith('J'):
return wordnet.ADJ
elif nltk_tag.startswith('V'):
... | contrast-sets-main | MATRES/AnnotationCSV2XML.py |
import torch
import argparse
from Code.utils.constants import GAIN, BIAS
def get_args():
parser = argparse.ArgumentParser(description='RL')
# dataset
parser.add_argument(
'--output-dir', type=str, default='outputs')
parser.add_argument(
'--dataset-train', type=str, default='data/train... | clarifydelphi-main | Code/arguments.py |
import os
os.environ['TRANSFORMERS_CACHE'] = 'cache/'
import torch
import torch.nn.functional as F
from typing import Union, List, Dict
from transformers import T5ForConditionalGeneration, T5Tokenizer
from Code.utils.constants import NEGATIVE_INF
from Code.utils.utils import logits_to_entropy, mask_pad
class Policy:... | clarifydelphi-main | Code/policy.py |
import torch
import numpy as np
import csv
import pandas as pd
from tqdm import tqdm
from Code.policy import Policy
from torch.utils.data import DataLoader
from Code.lean_main import PromptDataset, PromptCollator
def expand(tensor, num_repeat):
return torch.reshape(tensor[:, None].expand(-1, num_repeat, -1), [bat... | clarifydelphi-main | Code/sample_clarifyd.py |
import os
import sys
import torch
import json
import time
import logging
import random
import argparse
import numpy as np
import itertools
from datetime import datetime
from tqdm import tqdm
from torch.utils.data import Dataset, DataLoader
from torch.optim import Adam, Optimizer
from torch.optim.lr_scheduler import La... | clarifydelphi-main | Code/lean_main.py |
import torch
from transformers import T5Tokenizer
from Code.model.t5 import T5ForTokenRegression
from Code.utils.utils import mask_pad
from IPython import embed
class Value:
def __init__(self, model_type, device):
self.model = T5ForTokenRegression.from_pretrained(model_type)
self.device = device
... | clarifydelphi-main | Code/value.py |
import os
import sys
import torch
import json
import time
import logging
import random
import argparse
import numpy as np
import itertools
from datetime import datetime
from tqdm import tqdm
from torch.utils.data import Dataset, DataLoader
from torch.optim import Adam, Optimizer
from torch.optim.lr_scheduler import La... | clarifydelphi-main | Code/main.py |
import json
import math
import os
import re
import numpy as np
from tqdm import tqdm
import logging
from torch.utils.data import DataLoader
from typing import Optional, List, Iterable, Dict, Any
from Code.policy import Policy
from Code.model.delphi import DelphiScorer
from Code.utils.utils import batchify, load_jsonl
f... | clarifydelphi-main | Code/reward.py |
from pathlib import Path
import yaml
NEGATIVE_INF = -100000.0
# Config
CONFIG_FILE = Path('config.yml')
#reward
GAIN = 4.072529137302586
BIAS = -0.45725615025178 | clarifydelphi-main | Code/utils/constants.py |
import json
from pathlib import Path
from typing import TypeVar, Iterable, List, Union, Any
import numpy as np
import torch
from tqdm.auto import tqdm
import os
import collections
from utils.constants import NEGATIVE_INF
T = TypeVar('T')
def reduce_sum(value, mask, axis=None):
if axis is None:
return tor... | clarifydelphi-main | Code/utils/utils.py |
import torch
from torch import nn
from torch.nn import MSELoss
from transformers.models.t5.modeling_t5 import T5PreTrainedModel, T5Stack
from transformers.modeling_outputs import TokenClassifierOutput
from transformers.utils.model_parallel_utils import assert_device_map, get_device_map
from Code.utils.utils import redu... | clarifydelphi-main | Code/model/t5.py |
import sys
sys.path.append(".")
import torch
from scipy.special import softmax
from transformers import T5Tokenizer, T5ForConditionalGeneration, T5Config
class DelphiScorer:
def __init__(self, device_id="cuda:0", model="t5-11b", parallel=False):
CUDA_DEVICE = device_id if torch.cuda.is_available() else '... | clarifydelphi-main | Code/model/delphi.py |
from overrides import overrides
from allennlp.common.util import JsonDict
from allennlp.data import Instance
from allennlp.predictors.predictor import Predictor
@Predictor.register('bert-for-qa')
class BertQAPredictor(Predictor):
"""
Predictor for the :class:`~allennlp.models.reading_comprehension.BertForQues... | allennlp-bert-qa-wrapper-master | pretrained_bert/predictor.py |
from pretrained_bert.model import BertForQuestionAnswering
from pretrained_bert.dataset_reader import SquadReaderForPretrainedBert
from pretrained_bert.predictor import BertQAPredictor
| allennlp-bert-qa-wrapper-master | pretrained_bert/__init__.py |
from typing import Dict, List
import collections
import logging
import math
import torch
from overrides import overrides
from pytorch_pretrained_bert import BertForQuestionAnswering as HuggingFaceBertQA
from pytorch_pretrained_bert import BertConfig
from pytorch_pretrained_bert.tokenization import BasicTokenizer
from... | allennlp-bert-qa-wrapper-master | pretrained_bert/model.py |
import json
import logging
import collections
from typing import List
import torch
from overrides import overrides
from pytorch_pretrained_bert import BertTokenizer
from allennlp.common.file_utils import cached_path
from allennlp.data.fields import MetadataField
from allennlp.data.instance import Instance
from allenn... | allennlp-bert-qa-wrapper-master | pretrained_bert/dataset_reader.py |
import setuptools
setuptools.setup(
name="bart_score",
version="0.1.0",
description="BARTScore: Evaluating Generated Text as Text Generation",
author="John Giorgi",
url="https://github.com/allenai/BARTScore",
python_requires=">=3.6",
packages=setuptools.find_packages(),
install_requires... | BARTScore-main | setup.py |
#!/usr/bin/env python3
import argparse
import hashlib
import logging
import os
import sys
from typing import List, Dict, Iterator, Any, Tuple
import numpy as np
import sentencepiece as spm
import torch
from fairseq import checkpoint_utils, utils
from fairseq.data import LanguagePairDataset
from sacrebleu import get_s... | BARTScore-main | WMT/prism.py |
import os
import pickle
import sys
import nltk
from mosestokenizer import *
from nltk import word_tokenize
from nltk.tokenize import sent_tokenize
nltk.download('stopwords')
detokenizer = MosesDetokenizer('en')
def read_file_to_list(file_name):
lines = []
with open(file_name, 'r', encoding='utf8') as f:
... | BARTScore-main | WMT/utils.py |
import torch
import torch.nn as nn
import traceback
from transformers import BartTokenizer, BartForConditionalGeneration
class BARTScorer:
def __init__(self, device='cuda:0', max_length=1024, checkpoint='facebook/bart-large-cnn'):
# Set up model
self.device = device
self.max_length = max_l... | BARTScore-main | WMT/bart_score.py |
import argparse
import os
import time
import numpy as np
from utils import *
from tqdm import tqdm
REF_HYPO = read_file_to_list('files/tiny_ref_hypo_prompt.txt')
class Scorer:
""" Support BLEU, CHRF, BLEURT, PRISM, COMET, BERTScore, BARTScore """
def __init__(self, file_path, device='cuda:0'):
""" f... | BARTScore-main | WMT/score.py |
from bart_score.utils import *
from copy import deepcopy
from tqdm import trange
from tqdm import tqdm
from typing import Optional, List
class SUMStat:
""" A class used to get stats of SUM trained data """
def __init__(self, path):
self.path = path
self.data = read_pickle(path)
self.s... | BARTScore-main | bart_score/analysis.py |
from bart_score.scorer import BARTScorer | BARTScore-main | bart_score/__init__.py |
import pickle
import jsonlines
import nltk
from nltk.tokenize import sent_tokenize
from nltk import word_tokenize
import numpy as np
from tabulate import tabulate
from mosestokenizer import *
import random
from random import choices
import os
import sys
import re
from collections import defaultdict as ddict
from scipy.... | BARTScore-main | bart_score/utils.py |
import torch
import torch.nn as nn
import traceback
from transformers import BartTokenizer, BartForConditionalGeneration
from typing import List
import numpy as np
class BARTScorer:
def __init__(self, device='cuda:0', max_length=1024, checkpoint='facebook/bart-large-cnn'):
# Set up model
self.devi... | BARTScore-main | bart_score/scorer.py |
#!/usr/bin/env python3
import argparse
import hashlib
import logging
import os
import sys
from typing import List, Dict, Iterator, Any, Tuple
import numpy as np
import sentencepiece as spm
import torch
from fairseq import checkpoint_utils, utils
from fairseq.data import LanguagePairDataset
from sacrebleu import get_s... | BARTScore-main | D2T/prism.py |
from __future__ import absolute_import, division, print_function
import numpy as np
import torch
import string
from pyemd import emd
from torch import nn
from math import log
from itertools import chain
from pytorch_pretrained_bert import BertTokenizer, BertModel
from pytorch_pretrained_bert.modeling import BertPreTra... | BARTScore-main | D2T/moverscore.py |
import os
import pickle
import sys
import nltk
from mosestokenizer import *
from nltk import word_tokenize
from nltk.tokenize import sent_tokenize
nltk.download('stopwords')
detokenizer = MosesDetokenizer('en')
def read_file_to_list(file_name):
lines = []
with open(file_name, 'r', encoding='utf8') as f:
... | BARTScore-main | D2T/utils.py |
import torch
import torch.nn as nn
import traceback
from transformers import BartTokenizer, BartForConditionalGeneration
class BARTScorer:
def __init__(self, device='cuda:0', max_length=1024, checkpoint='facebook/bart-large-cnn'):
# Set up model
self.device = device
self.max_length = max_l... | BARTScore-main | D2T/bart_score.py |
import argparse
import os
import time
import numpy as np
from utils import *
SRC_HYPO = read_file_to_list('files/src_hypo_prompt.txt')
REF_HYPO = read_file_to_list('files/ref_hypo_prompt.txt')
class Scorer:
""" Support ROUGE-1,2,L, BERTScore, MoverScore, PRISM, BARTScore """
def __init__(self, file_path, de... | BARTScore-main | D2T/score.py |
BARTScore-main | D2T/gehrmann_rouge_opennmt/__init__.py | |
#!/usr/bin/env python
from __future__ import print_function, division
import argparse, os, re, time
import pdb
from gehrmann_rouge_opennmt.rouge_baselines.g_rouge import rouge
from gehrmann_rouge_opennmt.rouge_baselines.util import has_repeat, n_grams
from functools import reduce
import numpy as np
def split_sente... | BARTScore-main | D2T/gehrmann_rouge_opennmt/rouge_baselines/baseline.py |
from __future__ import print_function
import pdb
from six.moves import xrange
# from pyrouge import Rouge155
from gehrmann_rouge_opennmt.rouge_baselines.Rouge155 import Rouge155
import tempfile, os, glob, shutil
import numpy as np
import random
def evaluate_rouge(summaries, references, remove_temp=False, rouge_args... | BARTScore-main | D2T/gehrmann_rouge_opennmt/rouge_baselines/util.py |
BARTScore-main | D2T/gehrmann_rouge_opennmt/rouge_baselines/__init__.py | |
from __future__ import print_function, unicode_literals, division
import os
import pdb
import re
import codecs
import platform
from subprocess import check_output
from tempfile import mkdtemp
from functools import partial
try:
from configparser import ConfigParser
except ImportError:
from ConfigParser import... | BARTScore-main | D2T/gehrmann_rouge_opennmt/rouge_baselines/Rouge155.py |
# -*- coding: utf-8 -*-
# Copyright 2017 Google Inc.
#
# 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 ... | BARTScore-main | D2T/gehrmann_rouge_opennmt/rouge_baselines/g_rouge.py |
BARTScore-main | D2T/gehrmann_rouge_opennmt/rouge_baselines/pyrouge/__init__.py | |
from setuptools import setup
import os
from pyrouge.utils.file_utils import list_files
data_files = list_files('pyrouge/tests/data')
data_files = [p.replace('pyrouge/tests/', '') for p in data_files]
script_files = [os.path.join('bin', s) for s in os.listdir('bin')]
setup(
name='pyrouge',
version='0.1.3',
... | BARTScore-main | D2T/gehrmann_rouge_opennmt/rouge_baselines/pyrouge/setup.py |
BARTScore-main | D2T/gehrmann_rouge_opennmt/rouge_baselines/pyrouge/bin/__init__.py | |
# from pyrouge.Rouge155 import Rouge155
| BARTScore-main | D2T/gehrmann_rouge_opennmt/rouge_baselines/pyrouge/pyrouge/__init__.py |
import unittest
from pyrouge.tests.Rouge155_test import PyrougeTest
loader = unittest.TestLoader()
suite = unittest.TestSuite()
suite.addTest(loader.loadTestsFromTestCase(PyrougeTest))
unittest.TextTestRunner().run(suite)
| BARTScore-main | D2T/gehrmann_rouge_opennmt/rouge_baselines/pyrouge/pyrouge/test.py |
from __future__ import print_function, unicode_literals, division
import os
import re
import codecs
import platform
from subprocess import check_output
from tempfile import mkdtemp
from functools import partial
try:
from configparser import ConfigParser
except ImportError:
from ConfigParser import ConfigPars... | BARTScore-main | D2T/gehrmann_rouge_opennmt/rouge_baselines/pyrouge/pyrouge/Rouge155.py |
from __future__ import print_function, unicode_literals, division
import unittest
import os
import re
from subprocess import check_output
from tempfile import mkdtemp
from pyrouge import Rouge155
from pyrouge.utils.file_utils import str_from_file, xml_equal
module_path = os.path.dirname(__file__)
os.chdir(module_p... | BARTScore-main | D2T/gehrmann_rouge_opennmt/rouge_baselines/pyrouge/pyrouge/tests/Rouge155_test.py |
BARTScore-main | D2T/gehrmann_rouge_opennmt/rouge_baselines/pyrouge/pyrouge/tests/__init__.py | |
import unittest
import pyrouge.test
from pyrouge.test.Rouge155_test import PyrougeTest
loader = unittest.TestLoader()
suite = unittest.TestSuite()
suite.addTest(loader.loadTestsFromTestCase(PyrougeTest))
unittest.TextTestRunner().run(suite)
| BARTScore-main | D2T/gehrmann_rouge_opennmt/rouge_baselines/pyrouge/pyrouge/tests/__main__.py |
from __future__ import print_function, unicode_literals, division
from pyrouge.utils import log
from pyrouge.utils.string_utils import cleanup
from pyrouge.utils.file_utils import DirectoryProcessor
class PunktSentenceSplitter:
"""
Splits sentences using the NLTK Punkt sentence tokenizer. If installed,
P... | BARTScore-main | D2T/gehrmann_rouge_opennmt/rouge_baselines/pyrouge/pyrouge/utils/sentence_splitter.py |
import logging
def get_console_logger(name, level=logging.INFO):
logFormatter = logging.Formatter(
"%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s")
logger = logging.getLogger(name)
if not logger.handlers:
logger.setLevel(level)
ch = logging.StreamHandler()
... | BARTScore-main | D2T/gehrmann_rouge_opennmt/rouge_baselines/pyrouge/pyrouge/utils/log.py |
BARTScore-main | D2T/gehrmann_rouge_opennmt/rouge_baselines/pyrouge/pyrouge/utils/__init__.py | |
import argparse
io_parser = argparse.ArgumentParser(add_help=False)
io_parser.add_argument(
'-i', '--input-files-dir',
help="Path of the directory containing the files to be converted.",
type=str, action="store", dest="input_dir",
required=True
)
io_parser.add_argument(
'-o', '--output-files-di... | BARTScore-main | D2T/gehrmann_rouge_opennmt/rouge_baselines/pyrouge/pyrouge/utils/argparsers.py |
from __future__ import print_function, unicode_literals, division
import re
def remove_newlines(s):
p = re.compile("[\n|\r\n|\n\r]")
s = re.sub(p, " ", s)
s = remove_extraneous_whitespace(s)
return s
def remove_extraneous_whitespace(s):
p = re.compile("(\s+)")
s = re.sub(p, " ", s)
retu... | BARTScore-main | D2T/gehrmann_rouge_opennmt/rouge_baselines/pyrouge/pyrouge/utils/string_utils.py |
from __future__ import print_function, unicode_literals, division
import os
import re
import codecs
import logging
import xml.etree.ElementTree as et
from gehrmann_rouge_opennmt.rouge_baselines.pyrouge.pyrouge.utils import log
class DirectoryProcessor:
@staticmethod
def process(input_dir, output_dir, funct... | BARTScore-main | D2T/gehrmann_rouge_opennmt/rouge_baselines/pyrouge/pyrouge/utils/file_utils.py |
#!/usr/bin/env python3
import argparse
import hashlib
import logging
import os
import sys
from typing import List, Dict, Iterator, Any, Tuple
import numpy as np
import sentencepiece as spm
import torch
from fairseq import checkpoint_utils, utils
from fairseq.data import LanguagePairDataset
from sacrebleu import get_s... | BARTScore-main | SUM/prism.py |
from __future__ import absolute_import, division, print_function
import numpy as np
import torch
import string
from pyemd import emd
from torch import nn
from math import log
from itertools import chain
from pytorch_pretrained_bert import BertTokenizer, BertModel
from pytorch_pretrained_bert.modeling import BertPreTra... | BARTScore-main | SUM/moverscore.py |
import os
import pickle
import sys
import nltk
from mosestokenizer import *
from nltk import word_tokenize
from nltk.tokenize import sent_tokenize
nltk.download('stopwords')
detokenizer = MosesDetokenizer('en')
def read_file_to_list(file_name):
lines = []
with open(file_name, 'r', encoding='utf8') as f:
... | BARTScore-main | SUM/utils.py |
import torch
import torch.nn as nn
import traceback
from transformers import BartTokenizer, BartForConditionalGeneration
class BARTScorer:
def __init__(self, device='cuda:0', max_length=1024, checkpoint='facebook/bart-large-cnn'):
# Set up model
self.device = device
self.max_length = max_l... | BARTScore-main | SUM/bart_score.py |
import argparse
import os
import time
import numpy as np
from utils import *
from tqdm import tqdm
SRC_HYPO = read_file_to_list('files/src_hypo_prompt.txt')
REF_HYPO = read_file_to_list('files/ref_hypo_prompt.txt')
class Scorer:
""" Support ROUGE-1,2,L, BERTScore, MoverScore, PRISM, BARTScore """
def __init... | BARTScore-main | SUM/score.py |
BARTScore-main | SUM/gehrmann_rouge_opennmt/__init__.py | |
#!/usr/bin/env python
from __future__ import print_function, division
import argparse, os, re, time
import pdb
from gehrmann_rouge_opennmt.rouge_baselines.g_rouge import rouge
from gehrmann_rouge_opennmt.rouge_baselines.util import has_repeat, n_grams
from functools import reduce
import numpy as np
def split_sente... | BARTScore-main | SUM/gehrmann_rouge_opennmt/rouge_baselines/baseline.py |
from __future__ import print_function
import pdb
from six.moves import xrange
# from pyrouge import Rouge155
from gehrmann_rouge_opennmt.rouge_baselines.Rouge155 import Rouge155
import tempfile, os, glob, shutil
import numpy as np
import random
def evaluate_rouge(summaries, references, remove_temp=False, rouge_args... | BARTScore-main | SUM/gehrmann_rouge_opennmt/rouge_baselines/util.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.