id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
164,296 | import os
import re
import json
import pickle
import random
from template_config import *
from collections import defaultdict
from nltk.stem.porter import PorterStemmer
from nltk.stem.wordnet import WordNetLemmatizer
import nltk
def get_all_question_query_pairs(data):
question_query_pairs = []
for item in data... | null |
164,297 | import os
import re
import json
import pickle
import random
from template_config import *
from collections import defaultdict
from nltk.stem.porter import PorterStemmer
from nltk.stem.wordnet import WordNetLemmatizer
import nltk
The provided code snippet includes necessary dependencies for implementing the `is_value` ... | as values can either be a numerical digit or a string literal, then we can detect if a token is a value by matching with regex |
164,298 | import os
import re
import json
import pickle
import random
from template_config import *
from collections import defaultdict
from nltk.stem.porter import PorterStemmer
from nltk.stem.wordnet import WordNetLemmatizer
import nltk
def filter_string(cs):
return "".join([c.upper() for c in cs if c.isalpha() or c == ' ... | null |
164,299 | import os
import re
import json
import pickle
import random
from template_config import *
from collections import defaultdict
from nltk.stem.porter import PorterStemmer
from nltk.stem.wordnet import WordNetLemmatizer
import nltk
def tune_pattern_with_index(pattern):
general_pattern_list = []
for x in pattern.s... | null |
164,300 | import os
import re
import json
import pickle
import random
from template_config import *
from collections import defaultdict
from nltk.stem.porter import PorterStemmer
from nltk.stem.wordnet import WordNetLemmatizer
import nltk
def clean_select(clause, table_dict):
clause = [x[:-1]+"OLD}" if x[-1] == '}' else x+... | null |
164,301 | import json
import re
from nltk.metrics import accuracy
import os
from .utils import *
eval_type = 'dev'
import os
import json
def get_pattern_question(train_qq_pairs, tables):
pattern_question_dict = defaultdict(list)
detailed_pattern_question_dict = defaultdict(list)
... | null |
164,302 | import json
import re
from nltk.metrics import accuracy
import os
from .utils import *
import os
def test_path(path, verbose=True):
for subdir in os.listdir(path):
subpath = os.path.join(path, subdir, 'generator')
for iter in range(6):
working_path = os.path.join(subpath, str(iter))
... | null |
164,303 | import json
import re
from nltk.metrics import accuracy
import os
from .utils import *
import json
def load_jsonl(path):
data = []
with open(path, 'r', encoding='utf-8') as file:
for line in file:
sample = json.loads(line)
data.append(sample)
return data | null |
164,304 | import json
import re
from nltk.metrics import accuracy
import os
from .utils import *
import json
def load_json(path):
with open(path, 'r', encoding='utf-8') as file:
data = file.read()
return json.loads(data) | null |
164,305 | import json
import re
from nltk.metrics import accuracy
import os
from .utils import *
def statis_eval_json(data):
labels = [int(x['label']) for x in data]
print('True:', sum(labels))
print('False:', len(labels) - sum(labels)) | null |
164,306 | import json
import re
from nltk.metrics import accuracy
import os
from .utils import *
import re
def extract_coponents(data, clean_number=True, clean_coma=True, lower_case=True, strip_all=True):
# data [[template, [{template,question,"query","name dict":{}, "concise pattern"}]]
sql_dict = {}
for temp in d... | null |
164,307 | import json
import re
from nltk.metrics import accuracy
import os
from .utils import *
def debug(sam):
if sam['label'] == 1:
print(question)
print(sql)
print() | null |
164,308 | import json
import re
from nltk.metrics import accuracy
import os
from .utils import *
import json
def extract_translated_sqls(mapping_path, orgin_templates):
ret = {}
with open(mapping_path,'r',encoding='utf-8') as file:
data = json.loads(file.read())
for x, y in origin_templates.items():
... | null |
164,309 | import json
import re
from nltk.metrics import accuracy
import os
from .utils import *
def template_analysis(temp_dict):
# temp_dict {'path':[(temp, True/False)]}
for temp in temp_dict.values():
total_out = sum(x[1] == 0 for x in temp)
if total_out:
print(temp, total_out)
for x ... | null |
164,310 | import json
import re
from nltk.metrics import accuracy
import os
from .utils import *
import json
def pred_analysis(pred_dict, name):
selected_dict = [(x,y) for x,y in pred_dict.items() if name in x]
selected_dict.sort(key=lambda x: x[0])
previous_pred = None
previous_data = []
for i, (name, pred... | null |
164,311 | import json
import re
from nltk.metrics import accuracy
import os
from .utils import *
number_dict = {'2': 'two', '3': 'three', '4': 'four', '5': 'five', '6': 'six'}
agg_dict = {'count': ['more', 'number', 'how many', 'most', 'one', 'at least', 'only', 'more than', 'fewer than'],
'avg': ['average', 'mean'],
... | null |
164,312 | import os
from config import *
import random
import json
from tqdm import tqdm
from sql_formatter.formatting import translate_sql
import sqlite3
import multiprocessing
from multiprocessing import Manager
import time
random.seed(33)
def mkdir(path):
def read_json(path):
def write_json(path, data):
def preprocess_spider(... | null |
164,313 | import argparse
from utils import *
def get_arg():
parser = argparse.ArgumentParser()
parser.add_argument('--type', type=str, required=True, help='dataset type, ie. spider')
parser.add_argument('--input', type=str, required=True, help='input dir')
parser.add_argument('--output', type=str, required=True... | null |
164,314 | import json
import random
import csv
def load_json(path):
with open(path, 'r', encoding='utf-8') as file:
data = file.read()
return json.loads(data) | null |
164,315 | import json
import random
import csv
def random_choose(data, max_size):
new_dict = {}
for origin, mutated in data.items():
mutated = dict(random.sample(list(mutated.items()), min(len(mutated), max_size)))
new_dict[origin] = mutated
return new_dict | null |
164,316 | import json
import random
import csv
def write_json(path, data):
with open(path, 'w', encoding='utf-8') as file:
json.dump(data, file) | null |
164,317 | import json
import random
import csv
def load_csv(path):
data = []
for i, line in enumerate(csv.reader(open(labeled_path, encoding='utf-8'))):
if i == 0:
continue
data.append(line)
return data | null |
164,318 | from tqdm import tqdm
from sql_formatter.formatting import translate_sql
import json
import random
import multiprocessing
from multiprocessing import Manager
def translate_sql(sql):
formatter = Formatter()
if sql.split()[0] == '\"l' and sql.split()[-1] == 'r\"':
print("2:", sql)
translated_str... | null |
164,319 | import numpy
import re
import math
import pandas as pd
import numpy as np
import datetime
def fuzzy_match_filter(t, col, val, negate=False):
trim_t = t[col].str.replace(" ", "")
trim_val = val.replace(" ", "")
if negate:
res = t[~trim_t.str.contains(trim_val, regex=False)]
else:
res = ... | null |
164,320 | import numpy
import re
import math
import pandas as pd
import numpy as np
import datetime
month_map = {'january': 1, 'february': 2, 'march': 3, 'april': 4, 'may': 5, 'june': 6,
'july': 7, 'august': 8, 'september': 9, 'october': 10, 'november': 11, 'december': 12,
'jan': 1, 'feb': 2, 'mar': 3, ... | fuzzy compare and filter out rows. return empty pd if invalid type: eq, not_eq, greater, greater_eq, less, less_eq |
164,321 | import numpy
import re
import math
import pandas as pd
import numpy as np
import datetime
month_map = {'january': 1, 'february': 2, 'march': 3, 'april': 4, 'may': 5, 'june': 6,
'july': 7, 'august': 8, 'september': 9, 'october': 10, 'november': 11, 'december': 12,
'jan': 1, 'feb': 2, 'mar': 3, ... | null |
164,322 | import numpy
import re
import math
import pandas as pd
import numpy as np
import datetime
pat_num = r"([-+]?\s?\d*(?:\s?[:,.]\s?\d+)+\b|[-+]?\s?\d+\b|\d+\s?(?=st|nd|rd|th))"
pat_add = r"((?<==\s)\d+)"
The provided code snippet includes necessary dependencies for implementing the `agg` function. Write a Python function... | sum or avg for aggregation |
164,323 | import numpy
import re
import math
import pandas as pd
import numpy as np
import datetime
class ExeError(object):
def __init__(self, message="exe error"):
self.message = message
def hop_op(t, col):
if len(t) == 0:
return ExeError()
return t[col].values[0] | null |
164,324 | import numpy
import re
import math
import pandas as pd
import numpy as np
import datetime
month_map = {'january': 1, 'february': 2, 'march': 3, 'april': 4, 'may': 5, 'june': 6,
'july': 7, 'august': 8, 'september': 9, 'october': 10, 'november': 11, 'december': 12,
'jan': 1, 'feb': 2, 'mar': 3, ... | for max, min, argmax, argmin, nth_max, nth_min, nth_argmax, nth_argmin return string or rows |
164,325 | import numpy
import re
import math
import pandas as pd
import numpy as np
import datetime
def is_ascii(s):
return all(ord(c) < 128 for c in s) | null |
164,326 | import csv
from collections import defaultdict
import re
from .APIs import *
import nltk
from nltk.corpus import stopwords
from sklearn.metrics import classification_report, accuracy_score
def load_data():
reader = csv.reader(open("logic2text_labeled.csv", encoding='utf-8'))
data = []
for i, row in enumera... | null |
164,327 | import csv
from collections import defaultdict
import re
from .APIs import *
import nltk
from nltk.corpus import stopwords
from sklearn.metrics import classification_report, accuracy_score
def digit_match(x, nl):
found = 0
if x == '1':
found = 1
if int(x) <= 10:
if re.search(order_dict[int(x... | null |
164,328 | import csv
from collections import defaultdict
import re
from .APIs import *
import nltk
from nltk.corpus import stopwords
from sklearn.metrics import classification_report, accuracy_score
def count_label(data):
count = defaultdict(int)
labels = [x[-1] for x in data]
for label in labels:
count[labe... | null |
164,329 | import json
from tqdm import tqdm
from collections import defaultdict
from .TreeNode import *
class Node(object):
def __init__(self, full_table, dict_in):
def eval(self):
def to_nl(self):
def to_code(self):
def _mutate_dict(self, dict_in, alpha=0.5, beta=0.5, gamma=0.6, theta=0.15, omega=0.2):... | null |
164,334 | import numpy
import re
import math
import pandas as pd
import numpy as np
import datetime
class ExeError(object):
def __init__(self, message="exe error"):
def hop_op(t, col):
if len(t) == 0:
return ExeError()
return t[col].values[0] | null |
164,337 | import sys
import os
import json
import csv
import random
from tqdm import tqdm
from collections import defaultdict
import numpy as np
import pandas as pd
from logictools.TreeNode import *
The provided code snippet includes necessary dependencies for implementing the `execute_all` function. Write a Python function `de... | execute all logic forms |
164,345 | import logging
import math
import os
from dataclasses import dataclass, field
from typing import Optional
import torch
import json
from transformers import (
MODEL_WITH_LM_HEAD_MAPPING,
AutoTokenizer,
HfArgumentParser,
PreTrainedTokenizer,
set_seed,
)
from generator.models.relogic import RelogicModel
fr... | null |
164,346 | import logging
import math
import os
from dataclasses import dataclass, field
from typing import Optional
import torch
import json
from transformers import (
MODEL_WITH_LM_HEAD_MAPPING,
AutoTokenizer,
HfArgumentParser,
PreTrainedTokenizer,
set_seed,
)
from generator.models.relogic import RelogicModel
fr... | null |
164,347 | import logging
import math
import os
from dataclasses import dataclass, field
from typing import Optional
import torch
import json
from transformers import (
MODEL_WITH_LM_HEAD_MAPPING,
AutoTokenizer,
HfArgumentParser,
PreTrainedTokenizer,
set_seed,
)
from generator.models.relogic import RelogicModel
fr... | null |
164,348 | import logging
import math
import os
from dataclasses import dataclass, field
from typing import Optional
import torch
import json
from transformers import (
MODEL_WITH_LM_HEAD_MAPPING,
AutoTokenizer,
HfArgumentParser,
PreTrainedTokenizer,
set_seed,
)
from generator.models.relogic import RelogicModel
fr... | null |
164,349 | def reverse(sql,table):
temp = {}
temp['select'] = selectl(sql['select'],table)
temp['from'] = froml(sql['from'],table)
if len(sql['groupBy']) > 0:
temp['groupBy'] = groupbyl(sql['groupBy'],table)
else:
temp['groupBy'] = None
if len(sql['orderBy']) > 0:
temp['orderBy'] = ... | null |
164,354 | import traceback
import re
import sys
import json
import sqlite3
import sqlparse
import random
from os import listdir, makedirs
from collections import OrderedDict
from nltk import word_tokenize, tokenize
from os.path import isfile, isdir, join, split, exists, splitext
from utils.process_sql import get_sql
def get_sch... | null |
164,355 | def get_labels(sql_struct,slot,cur_nest):
if len(sql_struct['select']) > 0:
if cur_nest != '':
slot = get_select_labels(sql_struct['select'],slot,cur_nest+' SELECT')
else:
slot = get_select_labels(sql_struct['select'],slot,'SELECT')
if sql_struct['from']:
if cur_n... | null |
164,356 | def get_table_labels(sql_struct,slot,cur_nest):
if sql_struct['from']:
if cur_nest != '':
slot = get_from_table_labels(sql_struct['from'],slot,cur_nest)
else:
slot = get_from_table_labels(sql_struct['from'],slot,cur_nest)
if len(sql_struct['where']) > 0:
if cur_ne... | null |
164,372 | import math
import os
import numpy as np
from space.args import str2bool
from space.data.batch import batch
from space.data.dataset import LazyDataset
from space.data.sampler import RandomSampler
from space.data.sampler import SequentialSampler
from space.data.sampler import SortedSampler
def get_data_loader(batch_size... | null |
164,373 | import multiprocessing
import random
from itertools import chain
import os
import glob
import json
import numpy as np
import time
import re
from tqdm import tqdm
from space.args import str2bool
from space.data.tokenizer import Tokenizer
from space.utils import ontology
from space.utils.scores import tree_edit_score
def... | null |
164,374 | import os
import random
from collections import OrderedDict, defaultdict
from itertools import chain
import json
import sqlite3 as sql
import numpy as np
import spacy
from tqdm import tqdm
from nltk.tokenize import word_tokenize as nltk_word_tokenize
from nltk.stem import WordNetLemmatizer
from space.args import str2bo... | null |
164,377 | import json
import logging
import os
import sys
import time
from collections import OrderedDict
import torch
import numpy as np
from tqdm import tqdm
from transformers.optimization import AdamW, get_linear_schedule_with_warmup
from space.args import str2bool
from space.data.data_loader import DataLoader
from space.metr... | null |
164,378 | import json
import logging
import os
import sys
import time
from collections import OrderedDict
import torch
import numpy as np
from tqdm import tqdm
from transformers.optimization import AdamW, get_linear_schedule_with_warmup
from space.args import str2bool
from space.data.data_loader import DataLoader
from space.metr... | null |
164,379 | import json
import logging
import os
import sys
import time
from collections import OrderedDict
import torch
import numpy as np
from tqdm import tqdm
from transformers.optimization import AdamW, get_linear_schedule_with_warmup
from space.args import str2bool
from space.data.data_loader import DataLoader
from space.metr... | null |
164,380 | import math
import torch
import numpy as np
from space.args import str2bool
def repeat(var, times):
if isinstance(var, list):
return [repeat(x, times) for x in var]
elif isinstance(var, dict):
return {k: repeat(v, times) for k, v in var.items()}
elif isinstance(var, torch.Tensor):
v... | null |
164,381 | import math
import torch
import numpy as np
from space.args import str2bool
def gather(var, idx):
if isinstance(var, list):
return [gather(x, idx) for x in var]
elif isinstance(var, dict):
return {k: gather(v, idx) for k, v in var.items()}
elif isinstance(var, torch.Tensor):
out = v... | null |
164,382 | import logging
import json
import numpy as np
from collections import OrderedDict
from space.utils import ontology
def clean_replace(s, r, t, forward=True, backward=False):
def clean_replace_single(s, r, t, forward, backward, sidx=0):
# idx = s[sidx:].find(r)
idx = s.find(r)
if idx == -1:
... | null |
164,383 | import logging
import json
import numpy as np
from collections import OrderedDict
from space.utils import ontology
def py2np(list):
return np.array(list) | null |
164,384 | import logging
import json
import numpy as np
from collections import OrderedDict
from space.utils import ontology
def write_dict(fn, dic):
with open(fn, 'w') as f:
json.dump(dic, f, indent=2) | null |
164,388 | db_tokens = ['<sos_db>', '<eos_db>',
'[book_nores]', '[book_fail]', '[book_success]',
'[db_nores]', '[db_0]', '[db_1]', '[db_2]', '[db_3]']
def get_special_tokens(other_tokens):
special_tokens = ['<go_r>', '<go_b>', '<go_a>', '<go_d>',
'<eos_u>', '<eos_r>', '<eos_b>'... | null |
164,390 | import re
from space.utils import ontology
def my_clean_text(text):
text = re.sub(r'([a-zT]+)\.([a-z])', r'\1 . \2', text) # 'abc.xyz' -> 'abc . xyz'
text = re.sub(r'(\w+)\.\.? ', r'\1 . ', text) # if 'abc. ' -> 'abc . '
return text | null |
164,391 | import re
from space.utils import ontology
def clean_text(text):
text = text.strip()
text = text.lower()
text = text.replace(u"’", "'")
text = text.replace(u"‘", "'")
text = text.replace(';', ',')
text = text.replace('"', ' ')
text = text.replace('/', ' and ')
text = text.replace("don't"... | null |
164,392 | from space.utils.decorators import ignore_nodes
def jaccard_dis_sim(x, y):
"""
Jaccard Distance Similarity
"""
res = len(set.intersection(*[set(x), set(y)]))
union_cardinality = len(set.union(*[set(x), set(y)]))
if union_cardinality:
return res / float(union_cardinality), 1
else:
... | null |
164,393 | import json
import math
from collections import Counter
import numpy as np
from nltk.util import ngrams
from sklearn.metrics import f1_score
from space.utils import ontology, utils
from space.utils.clean_dataset import clean_slot_values
def setsub(a,b):
junks_a = []
useless_constraint = ['temperature','week','e... | null |
164,394 | import json
import math
from collections import Counter
import numpy as np
from nltk.util import ngrams
from sklearn.metrics import f1_score
from space.utils import ontology, utils
from space.utils.clean_dataset import clean_slot_values
def DAEvaluate(preds, labels):
preds = np.array(preds)
labels = np.array(l... | null |
164,403 | import argparse
import logging
import os
import random
import glob
import json
import math
import re
import numpy as np
import torch
from torch.utils.data import (DataLoader, RandomSampler, SequentialSampler)
from torch.utils.data.distributed import DistributedSampler
from tqdm import tqdm, trange
from transformers imp... | null |
164,406 | import os
import torch
from collections import OrderedDict
def get_match_value(name, state_dict_numpy):
"""
Need be overridden towards different models, here for UnifiedTransformer Model
"""
if name == 'bert.embeddings.word_embeddings.weight':
return state_dict_numpy['embedder.token_embedding.we... | null |
164,407 | import re
import ast
import json
import random
import bisect
import argparse
import pandas as pd
from tqdm import tqdm
from collections import defaultdict
from sacrebleu import corpus_bleu, sentence_bleu
import numpy as np
def get_turn_dst(test):
turn_dst = {}
for k in test.keys():
v = test[k]
... | null |
164,408 | import re
import ast
import json
import random
import bisect
import argparse
import pandas as pd
from tqdm import tqdm
from collections import defaultdict
from sacrebleu import corpus_bleu, sentence_bleu
import numpy as np
DB_PROMPT = {'restaurant': {'area': 'The area of restaurant is ',
'pr... | null |
164,409 | import re
import ast
import json
import random
import bisect
import argparse
import pandas as pd
from tqdm import tqdm
from collections import defaultdict
from sacrebleu import corpus_bleu, sentence_bleu
import numpy as np
def get_query_db(db, query):
query_dict = defaultdict(dict)
for k, v in query.items():
... | null |
164,410 | import re
import ast
import json
import random
import bisect
import argparse
import pandas as pd
from tqdm import tqdm
from collections import defaultdict
from sacrebleu import corpus_bleu, sentence_bleu
import numpy as np
INFORM_DOMAIN = ['restaurant', 'hotel', 'attraction', 'train']
inform_special_token = {'restaura... | null |
164,411 | import re
import ast
import json
import random
import bisect
import argparse
import pandas as pd
from tqdm import tqdm
from collections import defaultdict
from sacrebleu import corpus_bleu, sentence_bleu
import numpy as np
def get_db_key(dial_id, turn_id, db_query):
db_key = dial_id + '-' + str(turn_id)
dial_d... | null |
164,412 | import re
import ast
import json
import random
import bisect
import argparse
import pandas as pd
from tqdm import tqdm
from collections import defaultdict
from sacrebleu import corpus_bleu, sentence_bleu
import numpy as np
def calculate_bleu(input_data, reference_dialogs):
all_bleu = 0
turn_all = 0
for di... | null |
164,413 | import re
import ast
import json
import random
import bisect
import argparse
import pandas as pd
from tqdm import tqdm
from collections import defaultdict
from sacrebleu import corpus_bleu, sentence_bleu
import numpy as np
INFORM_DOMAIN = ['restaurant', 'hotel', 'attraction', 'train']
def case_delex(db, resp, dial_id,... | null |
164,414 | from transformers.optimization import AdamW, get_linear_schedule_with_warmup
from transformers import GPT2Tokenizer, GPT2LMHeadModel, GPT2Model
from eval import MultiWozEvaluator
from damd_net import DAMD, cuda_, get_one_hot_input
from reader import MultiWozReader
import utils
from torch.optim import Adam
import torch
... | null |
164,415 | import json
from sklearn.metrics import f1_score, accuracy_score
import sys
import numpy as np
from dst import ignore_none, default_cleaning, IGNORE_TURNS_TYPE2, paser_bs
import argparse
IGNORE_TURNS_TYPE2 = \
{
'PMUL1812': [1, 2]
}
def paser_bs(sent):
"""Convert compacted bs span to triple list... | null |
164,416 | import logging
import json
import numpy as np
from collections import OrderedDict
import ontology
The provided code snippet includes necessary dependencies for implementing the `top_k_top_p_filtering` function. Write a Python function `def top_k_top_p_filtering(logits, top_k=0, top_p=0.0, filter_value=-float('Inf'))` ... | Filter a distribution of logits using top-k and/or nucleus (top-p) filtering Args: logits: logits distribution shape (vocabulary size) top_k > 0: keep only top k tokens with highest probability (top-k filtering). top_p > 0.0: keep the top tokens with cumulative probability >= top_p (nucleus filtering). Nucleus filterin... |
164,417 | import logging
import json
import numpy as np
from collections import OrderedDict
import ontology
def py2np(list):
return np.array(list) | null |
164,418 | import logging
import json
import numpy as np
from collections import OrderedDict
import ontology
def write_dict(fn, dic):
with open(fn, 'w') as f:
json.dump(dic, f, indent=2) | null |
164,419 | import logging
import json
import numpy as np
from collections import OrderedDict
import ontology
def f1_score(label_list, pred_list):
tp = len([t for t in pred_list if t in label_list])
fp = max(0, len(pred_list) - tp)
fn = max(0, len(label_list) - tp)
precision = tp / (tp + fp + 1e-10)
recall = t... | null |
164,420 | import logging
import json
import numpy as np
from collections import OrderedDict
import ontology
def padSeqs_gpt(sequences, pad_id, maxlen=None):
lengths = []
for x in sequences:
lengths.append(len(x))
num_samples = len(sequences)
seq_mexlen = np.max(lengths)
# maxlen = 1024
if seq_m... | null |
164,421 | import logging
import json
import numpy as np
from collections import OrderedDict
import ontology
def padSeqs(sequences, maxlen=None, truncated = False, pad_method='post',
trunc_method='pre', dtype='int32', value=0.):
if not hasattr(sequences, '__len__'):
raise ValueError('`sequences`... | null |
164,422 | import logging
import json
import numpy as np
from collections import OrderedDict
import ontology
The provided code snippet includes necessary dependencies for implementing the `get_glove_matrix` function. Write a Python function `def get_glove_matrix(glove_path, vocab, initial_embedding_np)` to solve the following pr... | return a glove embedding matrix :param self: :param glove_file: :param initial_embedding_np: :return: np array of [V,E] |
164,423 | import logging
import json
import numpy as np
from collections import OrderedDict
import ontology
def position_encoding_init(self, n_position, d_pos_vec):
position_enc = np.array([[pos / np.power(10000, 2 * (j // 2) / d_pos_vec) for j in range(d_pos_vec)]
if pos != 0 else np.zeros(d_po... | null |
164,424 | import json, os, re, copy, zipfile
import spacy
import ontology, utils
from collections import OrderedDict
from tqdm import tqdm
from config import global_config as cfg
from db_ops import MultiWozDB
from clean_dataset import clean_slot_values, clean_text
def clean_slot_values(domain, slot, value):
value = clean_t... | null |
164,425 | import json, os, re, copy, zipfile
import spacy
import ontology, utils
from collections import OrderedDict
from tqdm import tqdm
from config import global_config as cfg
from db_ops import MultiWozDB
from clean_dataset import clean_slot_values, clean_text
def clean_slot_values(domain, slot, value):
value = clean_t... | null |
164,426 | import re
import ontology
def my_clean_text(text):
text = re.sub(r'([a-zT]+)\.([a-z])', r'\1 . \2', text) # 'abc.xyz' -> 'abc . xyz'
text = re.sub(r'(\w+)\.\.? ', r'\1 . ', text) # if 'abc. ' -> 'abc . '
return text | null |
164,427 | import re
import ontology
def clean_text(text):
text = text.strip()
text = text.lower()
text = text.replace(u"’", "'")
text = text.replace(u"‘", "'")
text = text.replace(';', ',')
text = text.replace('"', ' ')
text = text.replace('/', ' and ')
text = text.replace("don't", "do n't")
t... | null |
164,428 | import os, json, copy, re, zipfile
from collections import OrderedDict
from ontology import all_domains
data_path = './data/multi-woz/'
save_path = './data/multi-woz-analysis/'
save_path_exp = './data/multi-woz-processed/'
data_file = 'data.json'
domains = all_domains
def analysis():
compressed_raw_data = {}
g... | null |
164,429 | from eval import MultiWozEvaluator
from damd_net import DAMD, cuda_, get_one_hot_input
from dst_reader import MultiWozReader
from config import global_config as cfg
import utils
from torch.optim import Adam
import torch
import torch.nn as nn
import os
import random
import argparse
import time
import logging
import jso... | null |
164,430 | import copy, operator
from queue import PriorityQueue
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
from torch.autograd import Variable
from torch.distributions import Categorical
import utils
from config import global_config as cfg
def init_gru(gru):
def weight_reset(m):
... | null |
164,431 | import copy, operator
from queue import PriorityQueue
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
from torch.autograd import Variable
from torch.distributions import Categorical
import utils
from config import global_config as cfg
def cuda_(var):
# cfg.cuda_device[0]
ret... | null |
164,432 | import copy, operator
from queue import PriorityQueue
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
from torch.autograd import Variable
from torch.distributions import Categorical
import utils
from config import global_config as cfg
def cuda_(var):
# cfg.cuda_device[0]
ret... | :param raw_scores: list of tensor of size [B, Tdec, V], [B, Tdec, Tenc1], [B, Tdec, Tenc1] ... :param word_onehot_input: list of nparray of size [B, Tenci, V+Tenci] :param input_idx_oov: list of nparray of size [B, Tenc] :param vocab_size_oov: :returns: tensor of size [B, Tdec, vocab_size_oov] |
164,433 | import copy, operator
from queue import PriorityQueue
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
from torch.autograd import Variable
from torch.distributions import Categorical
import utils
from config import global_config as cfg
def cuda_(var):
def get_one_hot_input(x_input_np... | null |
164,451 | import os
import random
from collections import OrderedDict, defaultdict
from itertools import chain
import json
import sqlite3 as sql
import spacy
import numpy as np
from tqdm import tqdm
from nltk.tokenize import word_tokenize as nltk_word_tokenize
from nltk.stem import WordNetLemmatizer
from space.args import str2bo... | null |
164,456 | import json
import logging
import os
import sys
import time
from collections import OrderedDict
import torch
import torch.nn as nn
import math
import numpy as np
from tqdm import tqdm
from transformers.optimization import AdamW, get_linear_schedule_with_warmup
from dst import default_cleaning, IGNORE_TURNS_TYPE2, paser... | null |
164,457 | import json
import logging
import os
import sys
import time
from collections import OrderedDict
import torch
import torch.nn as nn
import math
import numpy as np
from tqdm import tqdm
from transformers.optimization import AdamW, get_linear_schedule_with_warmup
from dst import default_cleaning, IGNORE_TURNS_TYPE2, paser... | null |
164,458 | import math
import random
import warnings
import numpy as np
import torch
import torch.utils.checkpoint
from torch import nn
from typing import Optional, Tuple, Union
from transformers.activations import ACT2FN
from transformers.deepspeed import is_deepspeed_zero3_enabled
from transformers.modeling_outputs import BaseM... | Computes random mask spans for a given shape. Used to implement [SpecAugment: A Simple Data Augmentation Method for ASR](https://arxiv.org/abs/1904.08779). Note that this method is not optimized to run on TPU and should be run on CPU as part of the preprocessing during training. Args: shape: The shape for which to comp... |
164,459 | import math
import random
import warnings
import numpy as np
import torch
import torch.utils.checkpoint
from torch import nn
from typing import Optional, Tuple, Union
from transformers.activations import ACT2FN
from transformers.deepspeed import is_deepspeed_zero3_enabled
from transformers.modeling_outputs import BaseM... | null |
164,461 | import math
import torch
import numpy as np
from space.args import str2bool
def gather(var, idx):
if isinstance(var, list):
return [gather(x, idx) for x in var]
elif isinstance(var, dict):
return {k: gather(v, idx) for k, v in var.items()}
elif isinstance(var, torch.Tensor):
out = v... | null |
164,465 | import logging
import json
import numpy as np
from collections import OrderedDict
from space.utils import ontology
def f1_score(label_list, pred_list):
tp = len([t for t in pred_list if t in label_list])
fp = max(0, len(pred_list) - tp)
fn = max(0, len(label_list) - tp)
precision = tp / (tp + fp + 1e-1... | null |
164,472 | import re
from space.utils import ontology
def clean_text(text):
text = text.strip()
text = text.lower()
text = text.replace(u"’", "'")
text = text.replace(u"‘", "'")
text = text.replace(';', ',')
text = text.replace('"', ' ')
text = text.replace('/', ' and ')
text = text.replace("don't"... | null |
164,473 | from space.utils.decorators import ignore_nodes
def jaccard_dis_sim(x, y):
def clean_frame(frame):
def construct_frame_graph(frame):
def tree_edit_score(frame1, frame2):
# deal with empty frame
if not (frame1 and frame2):
return 0.
# clean frame
frame1 = clean_frame(frame=frame1)
frame2 = ... | null |
164,476 | import json
all_domain = [
"[taxi]","[police]","[hospital]","[hotel]","[attraction]","[train]","[restaurant]",'[profile]'
]
all_slots = all_reqslot + all_infslot
all_slots = set(all_slots)
The provided code snippet includes necessary dependencies for implementing the `paser_bs_old` function. Write a Python functi... | Convert compacted bs span to triple list Ex: |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.