code stringlengths 17 6.64M |
|---|
class TestMosesBleu(tf.test.TestCase):
'Tests using the Moses multi-bleu script to calcualte BLEU score\n '
def _test_multi_bleu(self, hypotheses, references, lowercase, expected_bleu):
'Runs a multi-bleu test.'
result = bleu.moses_multi_bleu(hypotheses=hypotheses, references=references, low... |
class TestTextMetricSpec(tf.test.TestCase):
'Abstract class for testing TextMetricSpecs\n based on hypotheses and references'
def _test_metric_spec(self, metric_spec, hyps, refs, expected_scores):
'Tests a MetricSpec'
predictions = {'predicted_tokens': tf.placeholder(dtype=tf.string)}
... |
class TestBleuMetricSpec(TestTextMetricSpec):
'Tests the `BleuMetricSpec`'
def test_bleu(self):
metric_spec = BleuMetricSpec({})
return self._test_metric_spec(metric_spec=metric_spec, hyps=['A B C D E F', 'A B C D E F'], refs=['A B C D E F', 'A B A D E F'], expected_scores=[100.0, 69.19])
|
class TestRougeMetricSpec(TestTextMetricSpec):
'Tests the `RougeMetricSpec`'
def test_rouge_1_f_score(self):
metric_spec = RougeMetricSpec({'rouge_type': 'rouge_1/f_score'})
self._test_metric_spec(metric_spec=metric_spec, hyps=['A B C D E F', 'A B C D E F'], refs=['A B C D E F', 'A B A D E F'... |
class TestRougeMetric(tf.test.TestCase):
'Tests the RougeMetric'
def test_rouge(self):
hypotheses = np.array(['The brown fox jumps over the dog 笑', 'The brown fox jumps over the dog 2 笑'])
references = np.array(['The quick brown fox jumps over the lazy dog 笑', 'The quick brown fox jumps over ... |
class EncoderDecoderTests(tf.test.TestCase):
'Base class for EncoderDecoder tests. Tests for specific classes should\n inherit from this and tf.test.TestCase.\n '
def setUp(self):
super(EncoderDecoderTests, self).setUp()
tf.logging.set_verbosity(tf.logging.INFO)
self.batch_size = 2
... |
class TestBasicSeq2Seq(EncoderDecoderTests):
'Tests the seq2seq.models.BasicSeq2Seq model.\n '
def setUp(self):
super(TestBasicSeq2Seq, self).setUp()
def create_model(self, mode, params=None):
params_ = BasicSeq2Seq.default_params().copy()
params_.update(TEST_PARAMS)
par... |
class TestAttentionSeq2Seq(EncoderDecoderTests):
'Tests the seq2seq.models.AttentionSeq2Seq model.\n '
def setUp(self):
super(TestAttentionSeq2Seq, self).setUp()
self.encoder_rnn_cell = tf.contrib.rnn.LSTMCell(32)
self.decoder_rnn_cell = tf.contrib.rnn.LSTMCell(32)
self.atten... |
def _clear_flags():
"Resets Tensorflow's FLAG values"
tf.app.flags.FLAGS = tf.app.flags._FlagValues()
tf.app.flags._global_parser = argparse.ArgumentParser()
|
class PipelineTest(tf.test.TestCase):
'Tests training and inference scripts.\n '
def setUp(self):
super(PipelineTest, self).setUp()
self.output_dir = tempfile.mkdtemp()
self.bin_folder = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../bin'))
tf.contrib.framewor... |
class PoolingEncoderTest(tf.test.TestCase):
'\n Tests the PoolingEncoder class.\n '
def setUp(self):
super(PoolingEncoderTest, self).setUp()
self.batch_size = 4
self.sequence_length = 16
self.input_depth = 10
self.mode = tf.contrib.learn.ModeKeys.TRAIN
def _test... |
class ExtendedMultiRNNCellTest(tf.test.TestCase):
'Tests the ExtendedMultiRNNCell'
def test_without_residuals(self):
inputs = tf.constant(np.random.randn(1, 2))
state = (tf.constant(np.random.randn(1, 2)), tf.constant(np.random.randn(1, 2)))
with tf.variable_scope('root', initializer=... |
class UnidirectionalRNNEncoderTest(tf.test.TestCase):
'\n Tests the UnidirectionalRNNEncoder class.\n '
def setUp(self):
super(UnidirectionalRNNEncoderTest, self).setUp()
tf.logging.set_verbosity(tf.logging.INFO)
self.batch_size = 4
self.sequence_length = 16
self.inp... |
class BidirectionalRNNEncoderTest(tf.test.TestCase):
'\n Tests the BidirectionalRNNEncoder class.\n '
def setUp(self):
super(BidirectionalRNNEncoderTest, self).setUp()
tf.logging.set_verbosity(tf.logging.INFO)
self.batch_size = 4
self.sequence_length = 16
self.input_... |
class StackBidirectionalRNNEncoderTest(tf.test.TestCase):
'\n Tests the StackBidirectionalRNNEncoder class.\n '
def setUp(self):
super(StackBidirectionalRNNEncoderTest, self).setUp()
tf.logging.set_verbosity(tf.logging.INFO)
self.batch_size = 4
self.sequence_length = 16
... |
class TestGetRNNCell(tf.test.TestCase):
'Tests the get_rnn_cell function.\n '
def test_single_layer(self):
cell = training_utils.get_rnn_cell(cell_class='BasicLSTMCell', cell_params={'num_units': 16}, num_layers=1)
self.assertIsInstance(cell, tf.contrib.rnn.BasicLSTMCell)
self.assert... |
class TestTrainOptions(tf.test.TestCase):
'Tests reading and writing of training options'
def setUp(self):
super(TestTrainOptions, self).setUp()
self.model_dir = tempfile.mkdtemp()
self.model_params = {'num_layers': 4}
self.model_class = 'AttentionSeq2Seq'
def test_read_w... |
class TestInputFn(tf.test.TestCase):
'Tests create_input_fn'
def _test_with_args(self, **kwargs):
'Helper function to test create_input_fn with keyword arguments'
(sources_file, targets_file) = test_utils.create_temp_parallel_data(sources=['Hello World .'], targets=['Goodbye .'])
pipe... |
class TestLRDecay(tf.test.TestCase):
'Tests learning rate decay function.\n '
def test_no_decay(self):
decay_fn = training_utils.create_learning_rate_decay_fn(decay_type=None, decay_steps=5, decay_rate=2.0)
self.assertEqual(decay_fn, None)
decay_fn = training_utils.create_learning_ra... |
def create_temp_parallel_data(sources, targets):
'\n Creates a temporary TFRecords file.\n\n Args:\n source: List of source sentences\n target: List of target sentences\n\n Returns:\n A tuple (sources_file, targets_file).\n '
file_source = tempfile.NamedTemporaryFile()
file_target = tempfile.... |
def create_temp_tfrecords(sources, targets):
'\n Creates a temporary TFRecords file.\n\n Args:\n source: List of source sentences\n target: List of target sentences\n\n Returns:\n A tuple (sources_file, targets_file).\n '
output_file = tempfile.NamedTemporaryFile()
writer = tf.python_io.TFRec... |
def create_temporary_vocab_file(words, counts=None):
'\n Creates a temporary vocabulary file.\n\n Args:\n words: List of words in the vocabulary\n\n Returns:\n A temporary file object with one word per line\n '
vocab_file = tempfile.NamedTemporaryFile()
if (counts is None):
for token in ... |
class VocabInfoTest(tf.test.TestCase):
'Tests VocabInfo class'
def setUp(self):
super(VocabInfoTest, self).setUp()
tf.logging.set_verbosity(tf.logging.INFO)
self.vocab_list = ['Hello', '.', 'Bye']
self.vocab_file = test_utils.create_temporary_vocab_file(self.vocab_list)
d... |
class CreateVocabularyLookupTableTest(tf.test.TestCase):
'\n Tests Vocabulary lookup table operations.\n '
def test_without_counts(self):
vocab_list = ['Hello', '.', '笑']
vocab_file = test_utils.create_temporary_vocab_file(vocab_list)
(vocab_to_id_table, id_to_vocab_table, _, vocab_... |
@six.add_metaclass(abc.ABCMeta)
class TrainingHook(tf.train.SessionRunHook, Configurable):
'Abstract base class for training hooks.\n '
def __init__(self, params, model_dir, run_config):
tf.train.SessionRunHook.__init__(self)
Configurable.__init__(self, params, tf.contrib.learn.ModeKeys.TRAI... |
class MetadataCaptureHook(TrainingHook):
'A hook to capture metadata for a single step.\n Useful for performance debugging. It performs a full trace and saves\n run_metadata and Chrome timeline information to a file.\n\n Args:\n step: The step number to trace. The hook is only enable for this step.\n '
... |
class TrainSampleHook(TrainingHook):
'Occasionally samples predictions from the training run and prints them.\n\n Params:\n every_n_secs: Sample predictions every N seconds.\n If set, `every_n_steps` must be None.\n every_n_steps: Sample predictions every N steps.\n If set, `every_n_secs` must be... |
class PrintModelAnalysisHook(TrainingHook):
'Writes the parameters of the model to a file and stdout.\n '
def __init__(self, params, model_dir, run_config):
super(PrintModelAnalysisHook, self).__init__(params, model_dir, run_config)
self._filename = os.path.join(self.model_dir, 'model_analys... |
class VariableRestoreHook(TrainingHook):
'A hooks that restored variables from a given checkpoints.\n\n Params:\n prefix: Variables matching this prefix are restored.\n checkpoint_path: Path to the checkpoint to restore variables from.\n '
def __init__(self, params, model_dir, run_config):
su... |
class DelayStartHook(TrainingHook, tf.train.GlobalStepWaiterHook):
'Delays the start of the current worker process until global step\n K * task_id is reached. K is a parameter.\n '
def __init__(self, params, model_dir, run_config):
TrainingHook.__init__(self, params, model_dir, run_config)
... |
class SyncReplicasOptimizerHook(TrainingHook):
'A SessionRunHook handles ops related to SyncReplicasOptimizer.'
def __init__(self, params, model_dir, run_config):
super(SyncReplicasOptimizerHook, self).__init__(params, model_dir, run_config)
self._sync_optimizer = None
self._num_token... |
class TrainOptions(object):
'A collection of options that are passed to the training script\n and can be saved to perform inference later.\n\n Args:\n task: Name of the training task class.\n task_params: A dictionary of parameters passed to the training task.\n '
def __init__(self, model_class, mod... |
def cell_from_spec(cell_classname, cell_params):
'Create a RNN Cell instance from a JSON string.\n\n Args:\n cell_classname: Name of the cell class, e.g. "BasicLSTMCell".\n cell_params: A dictionary of parameters to pass to the cell constructor.\n\n Returns:\n A RNNCell instance.\n '
cell_params =... |
def get_rnn_cell(cell_class, cell_params, num_layers=1, dropout_input_keep_prob=1.0, dropout_output_keep_prob=1.0, residual_connections=False, residual_combiner='add', residual_dense=False):
'Creates a new RNN Cell\n\n Args:\n cell_class: Name of the cell class, e.g. "BasicLSTMCell".\n cell_params: A dicti... |
def create_learning_rate_decay_fn(decay_type, decay_steps, decay_rate, start_decay_at=0, stop_decay_at=1000000000.0, min_learning_rate=None, staircase=False):
"Creates a function that decays the learning rate.\n\n Args:\n decay_steps: How often to apply decay.\n decay_rate: A Python number. The decay rate.... |
def create_input_fn(pipeline, batch_size, bucket_boundaries=None, allow_smaller_final_batch=False, scope=None):
'Creates an input function that can be used with tf.learn estimators.\n Note that you must pass "factory funcitons" for both the data provider and\n featurizer to ensure that everything will be cr... |
class DBEngine():
def __init__(self, fdb):
self.db = records.Database('sqlite:///{}'.format(fdb))
def execute_query(self, table_id, query, *args, **kwargs):
return self.execute(table_id, query.sel_index, query.agg_index, query.conditions, *args, **kwargs)
def execute(self, table_id, sel... |
def refractor_db_data(data_, table):
rec = {}
for table_name in table['table_names']:
rec[table_name] = []
for entry in table['column_names']:
if (entry[0] < 0):
continue
this_table = table['table_names'][entry[0]]
rec[this_table].append(entry[1])
res = {}
... |
def toksEQ(toks1, toks2):
str1 = ' '.join([wordnet_lemmatizer.lemmatize(tok) for tok in toks1])
str2 = ' '.join([wordnet_lemmatizer.lemmatize(tok) for tok in toks2])
return (str1 == str2)
|
def isNumber(val):
try:
int(val)
return True
except:
return False
|
def group_header(toks, idx, num_toks, header_toks):
for endIdx in reversed(range((idx + 1), (num_toks + 1))):
sub_toks = toks[idx:endIdx]
if (sub_toks in header_toks):
return (endIdx, sub_toks)
return (idx, None)
|
def group_val(toks, idx, num_toks, db_data):
for endIdx in reversed(range((idx + 1), (num_toks + 1))):
sub_toks = toks[idx:endIdx]
key = ' '.join(sub_toks)
if (key in db_data):
return (endIdx, sub_toks)
return (idx, None)
|
def group_table(toks, idx, num_toks, table_names):
table_toks = [name.split() for name in table_names]
for endIdx in reversed(range((idx + 1), (num_toks + 1))):
sub_toks = toks[idx:endIdx]
if (sub_toks in table_toks):
return (endIdx, sub_toks)
return (idx, None)
|
def parse_entry(entry, tables_dict, db_data_dict):
table = tables_dict[entry['db_id']]
db_data = {}
if (entry['db_id'] in db_data_dict):
db_data = db_data_dict[entry['db_id']]
question_toks = [tok.lower() for tok in entry['question_toks']]
question_toks_lem = [wordnet_lemmatizer.lemmatize(... |
def isNumber(val):
try:
int(val)
return True
except:
return False
|
def group_table(toks, idx, num_toks, table_names):
table_toks = [name.split() for name in table_names]
for endIdx in reversed(range((idx + 1), (num_toks + 1))):
sub_toks = toks[idx:endIdx]
if (sub_toks in table_toks):
return (endIdx, sub_toks)
return (idx, None)
|
def get_wikitable_name(table):
if ('page_title' in table):
return table['page_title'].lower().split()
if ('section_title' in table):
return table['section_title'].lower().split()
if ('caption' in table):
return table['caption'].lower().split()
return [DEFAULT_TABLENAME]
|
def parse_processed_wiki(entry):
table = wikitables_dict[entry['db_id']]
parsed_wikisql = wiki_dict[entry['question'].lower()]
entry.update(parsed_wikisql)
headers = table[HEADER]
table_name = get_wikitable_name(table)
for i in range(len(entry[TYPE])):
if (entry[TYPE][i] == ['column'])... |
def group_header(toks, idx, num_toks, header_toks):
for endIdx in reversed(range((idx + 1), (num_toks + 1))):
sub_toks = toks[idx:endIdx]
if (sub_toks in header_toks):
return (endIdx, sub_toks)
return (idx, None)
|
def group_val(toks, idx, num_toks, val2col):
if (toks[idx] in val2col):
return ((idx + 1), val2col[toks[idx]])
return (idx, None)
|
def refractor_db_data(data_, table):
rec = {}
for table_name in table['table_names']:
rec[table_name] = []
for entry in table['column_names']:
if (entry[0] < 0):
continue
this_table = table['table_names'][entry[0]]
rec[this_table].append(entry[1])
res = {}
... |
def toksEQ(toks1, toks2):
str1 = ' '.join([wordnet_lemmatizer.lemmatize(tok) for tok in toks1])
str2 = ' '.join([wordnet_lemmatizer.lemmatize(tok) for tok in toks2])
return (str1 == str2)
|
def isNumber(val):
try:
int(val)
return True
except:
return False
|
def group_header(toks, idx, num_toks, header_toks):
for endIdx in reversed(range((idx + 1), (num_toks + 1))):
sub_toks = toks[idx:endIdx]
if (sub_toks in header_toks):
return (endIdx, sub_toks)
return (idx, None)
|
def group_val(toks, idx, num_toks, db_data):
for endIdx in reversed(range((idx + 1), (num_toks + 1))):
sub_toks = toks[idx:endIdx]
key = ' '.join(sub_toks)
if (key in db_data):
return (endIdx, sub_toks)
return (idx, None)
|
def group_table(toks, idx, num_toks, table_names):
table_toks = [name.split() for name in table_names]
for endIdx in reversed(range((idx + 1), (num_toks + 1))):
sub_toks = toks[idx:endIdx]
if (sub_toks in table_toks):
return (endIdx, sub_toks)
return (idx, None)
|
def parse_entry(entry, tables_dict, db_data_dict):
table = tables_dict[entry['db_id']]
db_data = {}
if (entry['db_id'] in db_data_dict):
db_data = db_data_dict[entry['db_id']]
question_toks = [tok.lower() for tok in entry['question_toks']]
question_toks_lem = [wordnet_lemmatizer.lemmatize(... |
def isNumber(val):
try:
int(val)
return True
except:
return False
|
def group_table(toks, idx, num_toks, table_names):
table_toks = [name.split() for name in table_names]
for endIdx in reversed(range((idx + 1), (num_toks + 1))):
sub_toks = toks[idx:endIdx]
if (sub_toks in table_toks):
return (endIdx, sub_toks)
return (idx, None)
|
def get_wikitable_name(table):
if ('page_title' in table):
return table['page_title'].lower().split()
if ('section_title' in table):
return table['section_title'].lower().split()
if ('caption' in table):
return table['caption'].lower().split()
return [DEFAULT_TABLENAME]
|
def parse_processed_wiki(entry):
table = wikitables_dict[entry['db_id']]
parsed_wikisql = wiki_dict[entry['question'].lower()]
entry.update(parsed_wikisql)
headers = table[HEADER]
table_name = get_wikitable_name(table)
for i in range(len(entry[TYPE])):
if (entry[TYPE][i] == ['column'])... |
def group_header(toks, idx, num_toks, header_toks):
for endIdx in reversed(range((idx + 1), (num_toks + 1))):
sub_toks = toks[idx:endIdx]
if (sub_toks in header_toks):
return (endIdx, sub_toks)
return (idx, None)
|
def group_val(toks, idx, num_toks, val2col):
if (toks[idx] in val2col):
return ((idx + 1), val2col[toks[idx]])
return (idx, None)
|
class DBEngine():
def __init__(self, fdb):
self.db = records.Database('sqlite:///{}'.format(fdb))
def execute_query(self, table_id, query, *args, **kwargs):
return self.execute(table_id, query.sel_index, query.agg_index, query.conditions, *args, **kwargs)
def execute(self, table_id, sel... |
def condition_has_or(conds):
return ('or' in conds[1::2])
|
def condition_has_like(conds):
return (WHERE_OPS.index('like') in [cond_unit[1] for cond_unit in conds[::2]])
|
def condition_has_sql(conds):
for cond_unit in conds[::2]:
(val1, val2) = (cond_unit[3], cond_unit[4])
if ((val1 is not None) and (type(val1) is dict)):
return True
if ((val2 is not None) and (type(val2) is dict)):
return True
return False
|
def val_has_op(val_unit):
return (val_unit[0] != UNIT_OPS.index('none'))
|
def has_agg(unit):
return (unit[0] != AGG_OPS.index('none'))
|
def accuracy(count, total):
if (count == total):
return 1
return 0
|
def recall(count, total):
if (count == total):
return 1
return 0
|
def F1(acc, rec):
if ((acc + rec) == 0):
return 0
return (((2.0 * acc) * rec) / (acc + rec))
|
def get_scores(count, pred_total, label_total):
if (pred_total != label_total):
return (0, 0, 0)
elif (count == pred_total):
return (1, 1, 1)
return (0, 0, 0)
|
def eval_sel(pred, label):
pred_sel = pred['select'][1]
label_sel = label['select'][1]
label_wo_agg = [unit[1] for unit in label_sel]
pred_total = len(pred_sel)
label_total = len(label_sel)
cnt = 0
cnt_wo_agg = 0
for unit in pred_sel:
if (unit in label_sel):
cnt += ... |
def eval_where(pred, label):
pred_conds = [unit for unit in pred['where'][::2]]
label_conds = [unit for unit in label['where'][::2]]
label_wo_agg = [unit[2] for unit in label_conds]
pred_total = len(pred_conds)
label_total = len(label_conds)
cnt = 0
cnt_wo_agg = 0
for unit in pred_cond... |
def eval_group(pred, label):
pred_cols = [unit[1] for unit in pred['groupBy']]
label_cols = [unit[1] for unit in label['groupBy']]
pred_total = len(pred_cols)
label_total = len(label_cols)
cnt = 0
pred_cols = [(pred.split('.')[1] if ('.' in pred) else pred) for pred in pred_cols]
label_col... |
def eval_having(pred, label):
pred_total = label_total = cnt = 0
if (len(pred['groupBy']) > 0):
pred_total = 1
if (len(label['groupBy']) > 0):
label_total = 1
pred_cols = [unit[1] for unit in pred['groupBy']]
label_cols = [unit[1] for unit in label['groupBy']]
if ((pred_total =... |
def eval_order(pred, label):
pred_total = label_total = cnt = 0
if (len(pred['orderBy']) > 0):
pred_total = 1
if (len(label['orderBy']) > 0):
label_total = 1
if ((len(label['orderBy']) > 0) and (pred['orderBy'] == label['orderBy']) and (((pred['limit'] is None) and (label['limit'] is N... |
def eval_and_or(pred, label):
pred_ao = pred['where'][1::2]
label_ao = label['where'][1::2]
pred_ao = set(pred_ao)
label_ao = set(label_ao)
if (pred_ao == label_ao):
return (1, 1, 1)
return (len(pred_ao), len(label_ao), 0)
|
def get_nestedSQL(sql):
nested = []
for cond_unit in ((sql['from']['conds'][::2] + sql['where'][::2]) + sql['having'][::2]):
if (type(cond_unit[3]) is dict):
nested.append(cond_unit[3])
if (type(cond_unit[4]) is dict):
nested.append(cond_unit[4])
if (sql['intersect'... |
def eval_nested(pred, label):
label_total = 0
pred_total = 0
cnt = 0
if (pred is not None):
pred_total += 1
if (label is not None):
label_total += 1
if ((pred is not None) and (label is not None)):
partial_scores = Evaluator.eval_partial_match(pred, label)
cnt +... |
def eval_IUEN(pred, label):
(lt1, pt1, cnt1) = eval_nested(pred['intersect'], label['intersect'])
(lt2, pt2, cnt2) = eval_nested(pred['except'], label['except'])
(lt3, pt3, cnt3) = eval_nested(pred['union'], label['union'])
label_total = ((lt1 + lt2) + lt3)
pred_total = ((pt1 + pt2) + pt3)
cnt... |
def get_keywords(sql):
res = set()
if (len(sql['where']) > 0):
res.add('where')
if (len(sql['groupBy']) > 0):
res.add('group')
if (len(sql['having']) > 0):
res.add('having')
if (len(sql['orderBy']) > 0):
res.add(sql['orderBy'][0])
res.add('order')
if (sq... |
def eval_keywords(pred, label):
pred_keywords = get_keywords(pred)
label_keywords = get_keywords(label)
pred_total = len(pred_keywords)
label_total = len(label_keywords)
cnt = 0
for k in pred_keywords:
if (k in label_keywords):
cnt += 1
return (label_total, pred_total, ... |
def count_agg(units):
return len([unit for unit in units if has_agg(unit)])
|
def count_component1(sql):
count = 0
if (len(sql['where']) > 0):
count += 1
if (len(sql['groupBy']) > 0):
count += 1
if (len(sql['orderBy']) > 0):
count += 1
if (sql['limit'] is not None):
count += 1
if (len(sql['from']['table_units']) > 0):
count += (le... |
def count_component2(sql):
nested = get_nestedSQL(sql)
return len(nested)
|
def count_others(sql):
count = 0
agg_count = count_agg(sql['select'][1])
agg_count += count_agg(sql['where'][::2])
agg_count += count_agg(sql['groupBy'])
if (len(sql['orderBy']) > 0):
agg_count += count_agg(([unit[1] for unit in sql['orderBy'][1] if unit[1]] + [unit[2] for unit in sql['ord... |
class Evaluator():
'A simple evaluator'
def __init__(self, db_dir, kmaps, etype):
self.db_dir = db_dir
self.kmaps = kmaps
self.etype = etype
self.db_paths = {}
self.schemas = {}
for db_name in self.kmaps.keys():
db_path = os.path.join(db_dir, db_nam... |
def isValidSQL(sql, db):
conn = sqlite3.connect(db)
cursor = conn.cursor()
try:
cursor.execute(sql)
except:
return False
return True
|
def print_scores(scores, etype):
LEVELS = ['easy', 'medium', 'hard', 'extra', 'all']
PARTIAL_TYPES = ['select', 'select(no AGG)', 'where', 'where(no OP)', 'group(no Having)', 'group', 'order', 'and/or', 'IUEN', 'keywords']
print('{:20} {:20} {:20} {:20} {:20} {:20}'.format('', *LEVELS))
counts = [scor... |
def evaluate(gold, predict, db_dir, etype, kmaps):
with open(gold) as f:
glist = [l.strip().split('\t') for l in f.readlines() if (len(l.strip()) > 0)]
with open(predict) as f:
plist = [l.strip().split('\t') for l in f.readlines() if (len(l.strip()) > 0)]
evaluator = Evaluator(db_dir, kmap... |
def eval_exec_match(db, p_str, g_str, pred, gold):
'\n return 1 if the values between prediction and gold are matching\n in the corresponding index. Currently not support multiple col_unit(pairs).\n '
conn = sqlite3.connect(db)
cursor = conn.cursor()
try:
cursor.execute(p_str)
... |
def rebuild_cond_unit_val(cond_unit):
if ((cond_unit is None) or (not DISABLE_VALUE)):
return cond_unit
(not_op, op_id, val_unit, val1, val2) = cond_unit
if (type(val1) is not dict):
val1 = None
else:
val1 = rebuild_sql_val(val1)
if (type(val2) is not dict):
val2 = ... |
def rebuild_condition_val(condition):
if ((condition is None) or (not DISABLE_VALUE)):
return condition
res = []
for (idx, it) in enumerate(condition):
if ((idx % 2) == 0):
res.append(rebuild_cond_unit_val(it))
else:
res.append(it)
return res
|
def rebuild_sql_val(sql):
if ((sql is None) or (not DISABLE_VALUE)):
return sql
sql['from']['conds'] = rebuild_condition_val(sql['from']['conds'])
sql['having'] = rebuild_condition_val(sql['having'])
sql['where'] = rebuild_condition_val(sql['where'])
sql['intersect'] = rebuild_sql_val(sql[... |
def build_valid_col_units(table_units, schema):
col_ids = [table_unit[1] for table_unit in table_units if (table_unit[0] == TABLE_TYPE['table_unit'])]
prefixs = [col_id[:(- 2)] for col_id in col_ids]
valid_col_units = []
for value in list(schema.idMap.values()):
if (('.' in value) and (value[:... |
def rebuild_col_unit_col(valid_col_units, col_unit, kmap):
if (col_unit is None):
return col_unit
(agg_id, col_id, distinct) = col_unit
if ((col_id in kmap) and (col_id in valid_col_units)):
col_id = kmap[col_id]
if DISABLE_DISTINCT:
distinct = None
return (agg_id, col_id, ... |
def rebuild_val_unit_col(valid_col_units, val_unit, kmap):
if (val_unit is None):
return val_unit
(unit_op, col_unit1, col_unit2) = val_unit
col_unit1 = rebuild_col_unit_col(valid_col_units, col_unit1, kmap)
col_unit2 = rebuild_col_unit_col(valid_col_units, col_unit2, kmap)
return (unit_op... |
def rebuild_table_unit_col(valid_col_units, table_unit, kmap):
if (table_unit is None):
return table_unit
(table_type, col_unit_or_sql) = table_unit
if isinstance(col_unit_or_sql, tuple):
col_unit_or_sql = rebuild_col_unit_col(valid_col_units, col_unit_or_sql, kmap)
return (table_type,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.