code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
# Read config file. This has to get updated via git project_root = utils.get_project_root() infofile = os.path.join(project_root, "raw-datasets/info.yml") logging.info("Read '%s'...", infofile) with open(infofile, 'r') as ymlfile: datasets = yaml.load(ymlfile) for dataset in dataset...
def main()
Main part of the download script.
3.521956
3.430156
1.026763
logging.info("Load language model...") ngram_arpa_t = pkg_resources.resource_filename('hwrt', 'misc/ngram.arpa.tar.bz2') with tarfile.open(ngram_arpa_t, 'r:bz2') as tar: tarfolder = tempfile.mkdtemp() tar.extractall(path=tarfolder) ...
def load_model()
Load a n-gram language model for mathematics in ARPA format which gets shipped with hwrt. Returns ------- A NgramLanguageModel object
2.848988
2.552281
1.116252
data_found = False end_found = False in_ngram_block = 0 for i, line in enumerate(arpa_str.split("\n")): if not end_found: if not data_found: if "\\data\\" in line: data_found = True else: ...
def load_from_arpa_str(self, arpa_str)
Initialize N-gram model by reading an ARPA language model string. Parameters ---------- arpa_str : str A string in ARPA language model file format
2.680537
2.664107
1.006167
w1, w2, w3 = trigram # if w1 not in self.ngrams[1]['data']: # w1 = "<unk>" # if w2 not in self.ngrams[1]['data']: # w2 = "<unk>" # if w3 not in self.ngrams[1]['data']: # w3 = "<unk>" if w1 in self.ngrams[3]['data']: if w2 i...
def get_trigram_log_prob(self, trigram)
Calcualate the probability P(w1, w2, w3), given this language model. Parameters ---------- trigram tuple with exactly 3 elements Returns ------- numeric The log likelihood of P(w3 | (w1, w2))
2.221692
2.309551
0.961958
if len(sentence) == 1: return Decimal(10)**self.get_unigram_log_prob(sentence) elif len(sentence) == 2: return Decimal(10)**self.get_bigram_log_prob(sentence) else: log_prob = Decimal(0.0) for w1, w2, w3 in zip(sentence, sentence[1:], sent...
def get_probability(self, sentence)
Calculate the probability of a sentence, given this language model. Get P(sentence) = P(w1, w2, w3, ..., wn) = P(w1, w2, w3) * P(w2, w3, w4) *...* P(wn-2, wn-1, wn) Parameters ---------- sentence : list A list of strings / tokens.
2.102746
2.128919
0.987706
results = [] if sample_dir[-1] == "/": sample_dir = sample_dir[:-1] for filename in glob.glob("%s/*.inkml" % sample_dir): results.append(evaluate_inkml(filename)) return results
def evaluate_dir(sample_dir)
Evaluate all recordings in `sample_dir`. Parameters ---------- sample_dir : string The path to a directory with *.inkml files. Returns ------- list of dictionaries Each dictionary contains the keys 'filename' and 'results', where 'results' itself is a list of dictionari...
2.808362
2.468252
1.137794
logging.info("Start evaluating '%s'...", inkml_file_path) ret = {'filename': inkml_file_path} recording = inkml.read(inkml_file_path) results = evaluate(json.dumps(recording.get_sorted_pointlist()), result_format='LaTeX') ret['results'] = results return ret
def evaluate_inkml(inkml_file_path)
Evaluate an InkML file. Parameters ---------- inkml_file_path : string path to an InkML file Returns ------- dictionary The dictionary contains the keys 'filename' and 'results', where 'results' itself is a list of dictionaries. Each of the results has the keys ...
6.221733
5.775275
1.077305
with open(filename, 'w') as f: for result in evaluation_results: for i, entry in enumerate(result['results']): if entry['semantics'] == ',': result['results']['semantics'] = 'COMMA' f.write("%s, " % result['filename']) f.write(", "...
def generate_output_csv(evaluation_results, filename='results.csv')
Generate the evaluation results in the format Parameters ---------- evaluation_results : list of dictionaries Each dictionary contains the keys 'filename' and 'results', where 'results' itself is a list of dictionaries. Each of the results has the keys 'latex' and 'probability' ...
3.068081
2.623578
1.169426
percentage_done = float(current) / total sys.stdout.write("\r%0.2f%% " % (percentage_done * 100)) if start_time is not None: current_running_time = time.time() - start_time remaining_seconds = current_running_time / percentage_done tmp = datetime.timedelta(seconds=remaining_seco...
def print_status(total, current, start_time=None)
Show how much work was done / how much work is remaining. Parameters ---------- total : float The total amount of work current : float The work that has been done so far start_time : int The start time in seconds since 1970 to estimate the remaining time.
2.419489
2.726433
0.887419
arg = os.path.abspath(arg) if not os.path.exists(arg): parser.error("The file %s does not exist!" % arg) else: return arg
def is_valid_file(parser, arg)
Check if arg is a valid file that already exists on the file system.
1.727249
1.686476
1.024176
arg = os.path.abspath(arg) if not os.path.isdir(arg): parser.error("The folder %s does not exist!" % arg) else: return arg
def is_valid_folder(parser, arg)
Check if arg is a valid file that already exists on the file system.
2.005036
1.961608
1.022139
home = os.path.expanduser("~") rcfile = os.path.join(home, ".hwrtrc") if not os.path.isfile(rcfile): create_project_configuration(rcfile) with open(rcfile, 'r') as ymlfile: cfg = yaml.load(ymlfile) return cfg
def get_project_configuration()
Get project configuration as dictionary.
2.649705
2.616772
1.012585
home = os.path.expanduser("~") project_root_folder = os.path.join(home, "hwr-experiments") config = {'root': project_root_folder, 'nntoolkit': None, 'dropbox_app_key': None, 'dropbox_app_secret': None, 'dbconfig': os.path.join(home, "hwrt-config/d...
def create_project_configuration(filename)
Create a project configuration file which contains a configuration that might make sense.
4.84163
4.969381
0.974292
cfg = get_project_configuration() # At this point it can be sure that the configuration file exists # Now make sure the project structure exists for dirname in ["raw-datasets", "preprocessed", "feature-files", "models", ...
def get_project_root()
Get the project root folder as a string.
2.808228
2.766161
1.015208
cfg = get_project_configuration() if 'templates' not in cfg: home = os.path.expanduser("~") rcfile = os.path.join(home, ".hwrtrc") cfg['templates'] = pkg_resources.resource_filename('hwrt', 'templates/') with open(rc...
def get_template_folder()
Get path to the folder where th HTML templates are.
3.044858
3.028971
1.005245
cfg = get_project_configuration() if 'dbconfig' in cfg: if os.path.isfile(cfg['dbconfig']): return cfg['dbconfig'] else: logging.info("File '%s' was not found. Adjust 'dbconfig' in your " "~/.hwrtrc file.", cfg['dbcon...
def get_database_config_file()
Get the absolute path to the database configuration file.
4.006072
3.900489
1.027069
db_config = get_database_config_file() if db_config is None: return None with open(db_config, 'r') as ymlfile: cfg = yaml.load(ymlfile) return cfg
def get_database_configuration()
Get database configuration as dictionary.
2.466646
2.295117
1.074736
answer = input_string(question) if answer == "" or answer == "yes": return default else: return int(answer)
def input_int_default(question="", default=0)
A function that works for both, Python 2.x and Python 3.x. It asks the user for input and returns it as a string.
4.200651
5.481508
0.766331
with open(os.path.join(folder, "run.log"), "w") as f: datestring = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S") f.write("timestamp: '%s'" % datestring)
def create_run_logfile(folder)
Create a 'run.log' within folder. This file contains the time of the latest successful run.
2.565168
2.673759
0.959386
folder = os.path.join(get_project_root(), "raw-datasets") files = [os.path.join(folder, name) for name in os.listdir(folder) if name.endswith(".pickle")] default = -1 for i, filename in enumerate(files): if os.path.basename(currently) == os.path.basename(filename): ...
def choose_raw_dataset(currently="")
Let the user choose a raw dataset. Return the absolute path.
2.754347
2.686948
1.025084
ms = t % 1000 t -= ms t /= 1000 s = t % 60 t -= s t /= 60 minutes = t % 60 t -= minutes t /= 60 if t != 0: return "%ih, %i minutes %is %ims" % (t, minutes, s, ms) elif minutes != 0: return "%i minutes %is %ims" % (minutes, s, ms) elif s != 0: ...
def get_readable_time(t)
Format the time to a readable format. Parameters ---------- t : int Time in ms Returns ------- string The time splitted to highest used time (minutes, hours, ...)
2.02063
2.276223
0.887711
project_root = get_project_root() models_dir = os.path.join(project_root, "models") curr_dir = os.getcwd() if os.path.commonprefix([models_dir, curr_dir]) == models_dir and \ curr_dir != models_dir: latest_model = curr_dir else: latest_model = get_latest_folder(models_dir...
def default_model()
Get a path for a default value for the model. Start searching in the current directory.
2.739662
2.664475
1.028218
# Copy model file shutil.copyfile(model_src, model_use) # Adjust model file with open(model_src) as f: content = f.read() content = content.replace("logreg", "sigmoid") with open(model_use, "w") as f: f.write(content)
def create_adjusted_model_for_percentages(model_src, model_use)
Replace logreg layer by sigmoid to get probabilities.
2.751535
2.267692
1.213364
import h5py logging.info("Start creating of %s hdf file", output_filename) x = [] y = [] for features, label in data: assert len(features) == feature_count, \ "Expected %i features, got %i features" % \ (feature_count, len(features)) x.append(features) ...
def create_hdf5(output_filename, feature_count, data)
Create a HDF5 feature files. Parameters ---------- output_filename : string name of the HDF5 file that will be created feature_count : int dimension of all features combined data : list of tuples list of (x, y) tuples, where x is the feature vector of dimension ``fea...
2.412055
2.441787
0.987824
folders = [] folder = model_folder while os.path.isdir(folder): folders.append(folder) # Get info.yml with open(os.path.join(folder, "info.yml")) as ymlfile: content = yaml.load(ymlfile) folder = os.path.join(get_project_root(), content['data-source']) re...
def get_recognizer_folders(model_folder)
Get a list of folders [preprocessed, feature-files, model].
3.287205
3.170342
1.036861
# Extract tar with tarfile.open(model_file) as tar: tarfolder = tempfile.mkdtemp() tar.extractall(path=tarfolder) from . import features from . import preprocessing # Get the preprocessing with open(os.path.join(tarfolder, "preprocessing.yml"), 'r') as ymlfile: pre...
def load_model(model_file)
Load a model by its file. This includes the model itself, but also the preprocessing queue, the feature list and the output semantics.
2.724421
2.370433
1.149334
handwriting = handwritten_data.HandwrittenData(recording, raw_data_id=recording_id) handwriting.preprocessing(preprocessing_queue) x = handwriting.feature_extraction(feature_list) import nntoolkit.evaluate model_output = nntoolkit.evaluate.get_...
def evaluate_model_single_recording_preloaded(preprocessing_queue, feature_list, model, output_semantics, recording, ...
Evaluate a model for a single recording, after everything has been loaded. Parameters ---------- preprocessing_queue : list List of all preprocessing objects. feature_list : list List of all feature objects. model : dict Neural network model. output_semantics : list ...
4.924876
5.257783
0.936683
get_bin = lambda x, n: x >= 0 and str(bin(x))[2:].zfill(n) or "-" + str(bin(x))[3:].zfill(n) possible_splits = [] for i in range(2**(n - 1)): possible_splits.append(get_bin(i, n - 1)) return possible_splits
def get_possible_splits(n)
Parameters ---------- n : int n strokes were make
2.867687
3.085719
0.929342
import json import nntoolkit.evaluate recording = json.loads(recording) logging.info(("## start (%i strokes)" % len(recording)) + "#" * 80) hypotheses = [] # [[{'score': 0.123, symbols: [123, 123]}] # split0 # []] # Split i... for split in get_possible_splits(len(rec...
def evaluate_model_single_recording_preloaded_multisymbol(preprocessing_queue, feature_list, model, output_semantics, ...
Evaluate a model for a single recording, after everything has been loaded. Multiple symbols are recognized. Parameters ---------- preprocessing_queue : list List of all preprocessing objects. feature_list : list List of all feature objects. model : dict Neural network mo...
4.496156
4.395566
1.022884
(preprocessing_queue, feature_list, model, output_semantics) = load_model(model_file) logging.info("multiple symbol mode") logging.info(recording) results = evaluate_model_single_recording_preloaded(preprocessing_queue, feature_list, ...
def evaluate_model_single_recording_multisymbol(model_file, recording)
Evaluate a model for a single recording where possibly multiple symbols are. Parameters ---------- model_file : string Model file (.tar) recording : The handwritten recording.
5.866188
6.593698
0.889666
(preprocessing_queue, feature_list, model, output_semantics) = load_model(model_file) results = evaluate_model_single_recording_preloaded(preprocessing_queue, feature_list, model, ...
def evaluate_model_single_recording(model_file, recording)
Evaluate a model for a single recording. Parameters ---------- model_file : string Model file (.tar) recording : The handwritten recording.
5.400069
5.927436
0.911029
logging.info("Create running model...") model_src = get_latest_model(target_folder, "model") model_file_pointer = tempfile.NamedTemporaryFile(delete=False) model_use = model_file_pointer.name model_file_pointer.close() logging.info("Adjusted model is in %s.", model_use) create_adjusted_...
def _evaluate_model_single_file(target_folder, test_file)
Evaluate a model for a single recording. Parameters ---------- target_folder : string Folder where the model is test_file : string The test file (.hdf5)
3.847209
4.01894
0.95727
from . import preprocess_dataset from . import features for target_folder in get_recognizer_folders(model_folder): # The source is later than the target. That means we need to # refresh the target if "preprocessed" in target_folder: logging.info("Start applying prep...
def evaluate_model(recording, model_folder, verbose=False)
Evaluate model for a single recording.
4.933834
4.914001
1.004036
index2latex = {} translation_csv = os.path.join(get_project_root(), model_description["data-source"], "index2formula_id.csv") with open(translation_csv) as csvfile: csvreader = csv.DictReader(csvfile, delimiter=',', quotechar...
def get_index2latex(model_description)
Get a dictionary that maps indices to LaTeX commands. Parameters ---------- model_description : string A model description file that points to a feature folder where an `index2formula_id.csv` has to be. Returns ------- dictionary : Maps indices to LaTeX commands
2.862363
3.035188
0.94306
index2latex = {} translation_csv = os.path.join(get_project_root(), model_description["data-source"], "index2formula_id.csv") with open(translation_csv) as csvfile: csvreader = csv.DictReader(csvfile, delimiter=',', quotechar...
def get_index2data(model_description)
Get a dictionary that maps indices to a list of (1) the id in the hwrt symbol database (2) the latex command (3) the unicode code point (4) a font family and (5) a font style. Parameters ---------- model_description : string A model description file that points to a feature folder where an ...
3.432614
2.833246
1.211548
import pymysql import pymysql.cursors cfg = get_database_configuration() mysql = cfg['mysql_online'] connection = pymysql.connect(host=mysql['host'], user=mysql['user'], passwd=mysql['passwd'], db...
def get_online_symbol_data(database_id)
Get from the server.
3.467564
3.350982
1.03479
evaluation_file = evaluate_model(raw_data_json, model_folder, verbose) with open(os.path.join(model_folder, "info.yml")) as ymlfile: model_description = yaml.load(ymlfile) index2latex = get_index2latex(model_description) # Map line to probabilites for LaTeX commands with open(evaluati...
def classify_single_recording(raw_data_json, model_folder, verbose=False)
Get the classification as a list of tuples. The first value is the LaTeX code, the second value is the probability.
3.631438
3.255692
1.115412
object_list = [] for feature in description: for feat, params in feature.items(): feat = get_class(feat, config_key, module) if params is None: object_list.append(feat()) else: parameters = {} for dicts in params: ...
def get_objectlist(description, config_key, module)
Take a description and return a list of classes. Parameters ---------- description : list of dictionaries Each dictionary has only one entry. The key is the name of a class. The value of that entry is a list of dictionaries again. Those dictionaries are paramters. Returns -...
2.888868
2.794806
1.033656
clsmembers = inspect.getmembers(module, inspect.isclass) for string_name, act_class in clsmembers: if string_name == name: return act_class # Check if the user has specified a plugin and if the class is in there cfg = get_project_configuration() if config_key in cfg: ...
def get_class(name, config_key, module)
Get the class by its name as a string.
3.346393
3.265319
1.024829
environment = get_project_configuration()['environment'] cfg = get_database_configuration() if environment == 'production': mysql = cfg['mysql_online'] else: mysql = cfg['mysql_dev'] return mysql
def get_mysql_cfg()
Get the appropriate MySQL configuration
4.832527
4.953829
0.975513
w = [Decimal(el) for el in w] e = numpy.exp(numpy.array(w) / Decimal(t)) dist = e / numpy.sum(e) return dist
def softmax(w, t=1.0)
Calculate the softmax of a list of numbers w. Parameters ---------- w : list of numbers Returns ------- a list of the same length as w of non-negative numbers Examples -------- >>> softmax([0.1, 0.2]) array([ 0.47502081, 0.52497919]) >>> softmax([-0.1, 0.2]) array([ 0...
4.601695
8.000845
0.575151
home = os.path.expanduser("~") cache_dir = os.path.join(home, '.hwrt-beam-cache') if not os.path.exists(cache_dir): os.makedirs(cache_dir) return cache_dir
def get_beam_cache_directory()
Get a directory where pickled Beam Data can be stored. Create that directory, if it doesn't exist. Returns ------- str Path to the directory
2.297632
2.90775
0.790175
beam_dir = get_beam_cache_directory() beam_filename = os.path.join(beam_dir, secret_uuid) if os.path.isfile(beam_filename): with open(beam_filename, 'rb') as handle: beam = pickle.load(handle) return beam else: return None
def get_beam(secret_uuid)
Get a beam from the session with `secret_uuid`. Parameters ---------- secret_uuid : str Returns ------- The beam object if it exists, otherwise `None`.
2.218211
2.488164
0.891505
try: uuid_obj = UUID(uuid_to_test, version=version) except ValueError: return False return str(uuid_obj) == uuid_to_test
def is_valid_uuid(uuid_to_test, version=4)
Check if uuid_to_test is a valid UUID. Parameters ---------- uuid_to_test : str version : {1, 2, 3, 4} Returns ------- `True` if uuid_to_test is a valid UUID, otherwise `False`. Examples -------- >>> is_valid_uuid('c9bf9e57-1685-4c89-bafb-ff5af830be8a') True >>> is_val...
1.815567
3.893508
0.466306
n = len(table) for i, row in enumerate(table): assert len(row) == n for j, el in enumerate(row): if i == j: table[i][i] = 0.0 elif i > j: table[i][j] = 1-table[j][i] return table
def prepare_table(table)
Make the table 'symmetric' where the lower left part of the matrix is the reverse probability
2.585958
2.483372
1.041309
if l: prev = None for t in clusters(l[1:], K): tup = sorted(t) if tup != prev: prev = tup for i in range(K): yield tup[:i] + [[l[0]] + tup[i], ] + tup[i+1:] else: yield [[] for _ in range(K)]
def clusters(l, K)
Partition list ``l`` in ``K`` partitions. >>> l = [0, 1, 2] >>> list(clusters(l, K=3)) [[[0], [1], [2]], [[], [0, 1], [2]], [[], [1], [0, 2]], [[0], [], [1, 2]], [[], [0], [1, 2]], [[], [], [0, 1, 2]]] >>> list(clusters(l, K=2)) [[[0, 1], [2]], [[1], [0, 2]], [[0], [1, 2]], [[], [0, 1, 2]]] >>> ...
4.142281
4.221272
0.981287
for c in clusters(l, K): if all(x for x in c): yield c
def neclusters(l, K)
Partition list ``l`` in ``K`` partitions, without empty parts. >>> l = [0, 1, 2] >>> list(neclusters(l, 2)) [[[0, 1], [2]], [[1], [0, 2]], [[0], [1, 2]]] >>> list(neclusters(l, 1)) [[[0, 1, 2]]]
5.161931
9.526237
0.541865
for K in range(1, len(l)+1): gen = neclusters(l, K) for el in gen: yield el
def all_segmentations(l)
Get all segmentations of a list ``l``. This gets bigger fast. See https://oeis.org/A000110 For len(l) = 14 it is 190,899,322 >>> list(all_segmentations([0, 1, 2])) [[[0, 1, 2]], [[0, 1], [2]], [[1], [0, 2]], [[0], [1, 2]], [[0], [1], [2]]]
9.854729
11.085986
0.888936
for i, symbol in enumerate(segmentation): for sid in symbol: if sid == stroke_id: return i return -1
def find_index(segmentation, stroke_id)
>>> find_index([[0, 1, 2], [3, 4], [5, 6, 7]], 0) 0 >>> find_index([[0, 1, 2], [3, 4], [5, 6, 7]], 1) 0 >>> find_index([[0, 1, 2], [3, 4], [5, 6, 7]], 5) 2 >>> find_index([[0, 1, 2], [3, 4], [5, 6, 7]], 6) 2
3.508881
5.236714
0.670054
index1 = find_index(segmentation, s1) index2 = find_index(segmentation, s2) return index1 == index2
def q(segmentation, s1, s2)
Test if ``s1`` and ``s2`` are in the same symbol, given the ``segmentation``.
2.961777
3.328477
0.889829
stroke_nr = sum(1 for symbol in segmentation for stroke in symbol) score = 1 for i in range(stroke_nr): for j in range(i+1, stroke_nr): qval = q(segmentation, i, j) if qval: score *= table[i][j] else: score *= table[j][i] r...
def score_segmentation(segmentation, table)
Get the score of a segmentation.
4.133727
4.053183
1.019872
stroke_count = list(range(len(table))) topf = TopFinder(n) for curr_segmentation in all_segmentations(stroke_count): curr_seg_score = score_segmentation(curr_segmentation, table) topf.push(curr_segmentation, curr_seg_score) for el, score in topf: yield [normalize_segmentati...
def get_top_segmentations(table, n)
Parameters ---------- table : matrix of probabilities Each cell (i, j) of `table` gives the probability that i and j are in the same symbol. n : int Number of best segmentations which get returned
6.404339
7.336749
0.872912
insert_pos = 0 for index, el in enumerate(self.tops): if not self.find_min and el[1] >= value: insert_pos = index+1 elif self.find_min and el[1] <= value: insert_pos = index+1 self.tops.insert(insert_pos, [element, value]) ...
def push(self, element, value)
Push an ``element`` into the datastrucutre together with its value and only save it if it currently is one of the top n elements. Drop elements if necessary.
3.052208
3.185766
0.958077
out = StringIO() np.save(out, arr) return b64encode(out.getvalue())
def _array2cstr(arr)
Serializes a numpy array to a compressed base64 string
3.868518
3.252303
1.18947
if type(d) == list: return np.asarray([_str2array(s) for s in d]) ins = StringIO(d) return np.loadtxt(ins)
def _str2array(d)
Reconstructs a numpy array from a plain-text string
4.000284
3.797537
1.053389
with open('output_semantics.csv', 'wb') as csvfile: model_description_file = os.path.join(model_folder, "info.yml") with open(model_description_file, 'r') as ymlfile: model_description = yaml.load(ymlfile) logging.info("Start fetching translation dict...") translati...
def create_output_semantics(model_folder, outputs)
Create a 'output_semantics.csv' file which contains information what the output of the single output neurons mean. Parameters ---------- model_folder : str folder where the model description file is outputs : int number of output neurons
3.928499
3.739719
1.05048
a = yaml.load(open(utils.get_latest_in_folder(model_folder, ".json"))) layers = [] filenames = ["model.yml", "input_semantics.csv", "output_semantics.csv", "preprocessing.yml", "features.yml"] # Create input_semantics.csv inputs = a['layers'][0]['_props']['n_visible'] wit...
def main(model_folder)
Parameters ---------- model_folder : str Path to a folder in which a model (json file) is.
2.147357
2.165372
0.99168
d = dict() if hasattr(element, 'text') and element.text is not None: d['text'] = element.text d.update(element.items()) # element's attributes for c in list(element): # element's children if c.tag not in d: d[c.tag] = elementtree_to_dict(c) # an element with ...
def elementtree_to_dict(element)
Convert an xml ElementTree to a dictionary.
3.054962
2.962564
1.031189
if not text.endswith(suffix): return text return text[:len(text)-len(suffix)]
def strip_end(text, suffix)
Strip `suffix` from the end of `text` if `text` has that suffix.
2.404337
2.453615
0.979916
return utils.get_objectlist(model_description_multiply, config_key='data_multiplication', module=sys.modules[__name__])
def get_data_multiplication_queue(model_description_multiply)
Get features from a list of dictionaries >>> l = [{'Multiply': [{'nr': 1}]}, \ {'Rotate': [{'minimum':-30}, {'maximum': 30}, {'step': 5}]}] >>> get_data_multiplication_queue(l) [Multiply (1 times), Rotate (-30.00, 30.00, 5.00)]
8.159001
12.38709
0.65867
global __formula_to_dbid_cache if __formula_to_dbid_cache is None: mysql = utils.get_mysql_cfg() connection = pymysql.connect(host=mysql['host'], user=mysql['user'], passwd=mysql['passwd'], ...
def formula_to_dbid(formula_str, backslash_fix=False)
Convert a LaTeX formula to the database index. Parameters ---------- formula_str : string The formula as LaTeX code. backslash_fix : boolean If this is set to true, then it will be checked if the same formula exists with a preceeding backslash. Returns ------- int :...
2.164736
2.202399
0.982899
global username2id if username not in username2id: mysql = utils.get_mysql_cfg() connection = pymysql.connect(host=mysql['host'], user=mysql['user'], passwd=mysql['passwd'], db=mys...
def getuserid(username, copyright_str)
Get the ID of the user with `username` from write-math.com. If he doesn't exist by now, create it. Add `copyright_str` as a description. Parameters ---------- username : string Name of a user. copyright_str : string Description text of a user in Markdown format. Returns ---...
2.912531
2.996359
0.972023
mysql = utils.get_mysql_cfg() connection = pymysql.connect(host=mysql['host'], user=mysql['user'], passwd=mysql['passwd'], db=mysql['db'], charset='utf8mb4', ...
def insert_recording(hw)
Insert recording `hw` into database.
2.961528
2.930675
1.010528
mysql = utils.get_mysql_cfg() connection = pymysql.connect(host=mysql['host'], user=mysql['user'], passwd=mysql['passwd'], db=mysql['db'], charset='utf8mb4', ...
def insert_symbol_mapping(raw_data_id, symbol_id, user_id, strokes)
Insert data into `wm_strokes_to_symbol`. Parameters ---------- raw_data_id : int user_id : int strokes: list of int
2.23401
2.213932
1.009069
bad_names = ['celsius', 'degree', 'ohm', 'venus', 'mars', 'astrosun', 'fullmoon', 'leftmoon', 'female', 'male', 'checked', 'diameter', 'sun', 'Bowtie', 'sqrt', 'cong', 'copyright', 'dag', 'parr', 'notin', 'dotsc', 'mathds', 'mathfrak'] if ...
def filter_label(label, replace_by_similar=True)
Some labels currently don't work together because of LaTeX naming clashes. Those will be replaced by simple strings.
8.896795
8.369127
1.063049
# Prepare files csv_file = dam.prepare_file(basename + '.csv') raw_file = dam.prepare_file(basename + '.raw') csv_file = open(csv_file, 'a') raw_file = open(raw_file, 'a') csv_file.write("label,mean,std\n") # Write header raw_file.write("latex,raw_data_id,value\n") # Write header ...
def analyze_feature(raw_datasets, feature, basename="aspect_ratios")
Apply ``feature`` to all recordings in ``raw_datasets``. Store the results in two files. One file stores the raw result, the other one groups the results by symbols and stores the mean, standard deviation and the name of the symbol as a csv file. Parameters ---------- raw_datasets : List of dic...
3.093862
3.095568
0.999449
# Load from pickled file logging.info("Start loading data '%s' ...", handwriting_datasets_file) loaded = pickle.load(open(handwriting_datasets_file)) raw_datasets = loaded['handwriting_datasets'] logging.info("%i datasets loaded.", len(raw_datasets)) logging.info("Start analyzing...") ...
def main(handwriting_datasets_file, analyze_features)
Start the creation of the wanted metric.
4.108563
4.063853
1.011002
project_root = utils.get_project_root() # Get latest (raw) dataset dataset_folder = os.path.join(project_root, "raw-datasets") latest_dataset = utils.get_latest_in_folder(dataset_folder, "raw.pickle") from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter parser = ArgumentPars...
def get_parser()
Return the parser object for this script.
3.218911
3.161695
1.018096
if latex.startswith('{') and latex.endswith('}'): opened = 1 matches = True for char in latex[1:-1]: if char == '{': opened += 1 elif char == '}': opened -= 1 if opened == 0: matches = False if m...
def remove_matching_braces(latex)
If `latex` is surrounded by matching braces, remove them. They are not necessary. Parameters ---------- latex : string Returns ------- string Examples -------- >>> remove_matching_braces('{2+2}') '2+2' >>> remove_matching_braces('{2+2') '{2+2'
2.025486
2.378892
0.851441
tex_file = os.path.splitext(ink_filename)[0] + ".tex" with open(tex_file) as f: tex_content = f.read().strip() pattern = re.compile(r"\\begin\{displaymath\}(.*?)\\end\{displaymath\}", re.DOTALL) matches = pattern.findall(tex_content) if len(matches) == 0: ...
def get_latex(ink_filename)
Get the LaTeX string from a file by the *.ink filename.
2.592472
2.600594
0.996877
global missing_stroke_segmentation, double_segmentation segmentation = [] symbol_stream = [] needed = list(range(len(recording))) annotations = filter(lambda n: n.startswith('SYMBOL '), annotations) for line in annotations: tmp = line.split("<")[1] tmp, symbol_string = tmp.s...
def get_segmentation(recording, annotations, internal_id=None)
Parameters ---------- recording : A HandwrittenData object annotations : list of strings internal_id : string An identifier for the dataset, e.g. 'user1/200922-947-111.ink'. Returns ------- tuple : segmentation and list of symbol ids (of write-math.com)
5.738522
5.767139
0.995038
stroke_count = 0 stroke_point_count = -1 recording = [] current_stroke = [] time = 0 got_annotations = False annotations = [] formula_in_latex = get_latex(filename) with open(filename) as f: contents = f.read().strip() lines = contents.split("\n") for i, line i...
def parse_scg_ink_file(filename)
Parse a SCG INK file. Parameters ---------- filename : string The path to a SCG INK file. Returns ------- HandwrittenData The recording as a HandwrittenData object.
3.002078
2.987849
1.004762
recordings = [] for filename in glob.glob(os.path.join(folder, '*.ink')): recording = parse_scg_ink_file(filename) recordings.append(recording) return recordings
def read_folder(folder)
Read all files of `folder` and return a list of HandwrittenData objects. Parameters ---------- folder : string Path to a folder Returns ------- list : A list of all .ink files in the given folder.
4.1683
4.257831
0.978973
pointlist = self.get_pointlist() times = [point['time'] for stroke in pointlist for point in stroke] times_min = max(min(times), 0) # Make sure this is not None for i, stroke in enumerate(pointlist): for j, point in enumerate(stroke): if point['time'...
def fix_times(self)
Some recordings have wrong times. Fix them so that nothing after loading a handwritten recording breaks.
3.435629
3.235851
1.061739
try: pointlist = json.loads(self.raw_data_json) except Exception as inst: logging.debug("pointStrokeList: strokelistP") logging.debug(self.raw_data_json) logging.debug("didn't work") raise inst if len(pointlist) == 0: ...
def get_pointlist(self)
Get a list of lists of tuples from JSON raw data string. Those lists represent strokes with control points. Returns ------- list : A list of strokes. Each stroke is a list of dictionaries {'x': 123, 'y': 42, 'time': 1337}
7.082423
6.258873
1.131581
pointlist = self.get_pointlist() for i in range(len(pointlist)): pointlist[i] = sorted(pointlist[i], key=lambda p: p['time']) pointlist = sorted(pointlist, key=lambda stroke: stroke[0]['time']) return pointlist
def get_sorted_pointlist(self)
Make sure that the points and strokes are in order. Returns ------- list A list of all strokes in the recording. Each stroke is represented as a list of dicts {'time': 123, 'x': 45, 'y': 67}
2.692276
2.319686
1.160621
assert type(pointlist) is list, \ "pointlist is not of type list, but %r" % type(pointlist) assert len(pointlist) >= 1, \ "The pointlist of formula_id %i is %s" % (self.formula_id, self.get_pointlist()) self.r...
def set_pointlist(self, pointlist)
Overwrite pointlist. Parameters ---------- pointlist : a list of strokes; each stroke is a list of points The inner lists represent strokes. Every stroke consists of points. Every point is a dictinary with 'x', 'y', 'time'.
4.31789
4.559971
0.946912
pointlist = self.get_pointlist() # Initialize bounding box parameters to save values minx, maxx = pointlist[0][0]["x"], pointlist[0][0]["x"] miny, maxy = pointlist[0][0]["y"], pointlist[0][0]["y"] mint, maxt = pointlist[0][0]["time"], pointlist[0][0]["time"] # ...
def get_bounding_box(self)
Get the bounding box of a pointlist.
1.957247
1.845584
1.060503
# bitmap_width = int(self.get_width()*size) + 2 # bitmap_height = int(self.get_height()*size) + 2 img = Image.new('L', (size, size), 'black') draw = ImageDraw.Draw(img, 'L') bb = self.get_bounding_box() for stroke in self.get_sorted_pointlist(): for p...
def get_bitmap(self, time=None, size=32, store_path=None)
Get a bitmap of the object at a given instance of time. If time is `None`,`then the bitmap is generated for the last point in time. Parameters ---------- time : int or None size : int Size in pixels. The resulting bitmap will be (size x size). store_path : No...
2.104298
2.105562
0.9994
assert type(algorithms) is list for algorithm in algorithms: algorithm(self)
def preprocessing(self, algorithms)
Apply preprocessing algorithms. Parameters ---------- algorithms : a list objects Preprocessing allgorithms which get applied in order. Examples -------- >>> import preprocessing >>> a = HandwrittenData(...) >>> preprocessing_queue = [(prepro...
6.243903
9.830832
0.635135
assert type(algorithms) is list features = [] for algorithm in algorithms: new_features = algorithm(self) assert len(new_features) == algorithm.get_dimension(), \ "Expected %i features from algorithm %s, got %i features" % \ (algor...
def feature_extraction(self, algorithms)
Get a list of features. Every algorithm has to return the features as a list.
2.813248
2.659752
1.057711
# prevent the following error: # '_tkinter.TclError: no display name and no $DISPLAY environment # variable' # import matplotlib # matplotlib.use('GTK3Agg', warn=False) import matplotlib.pyplot as plt pointlist = self.get_pointlist() if 'pen...
def show(self)
Show the data graphically in a new pop-up window.
3.127826
3.087583
1.013034
pointlist = self.get_pointlist() single_dots = 0 for stroke in pointlist: if len(stroke) == 1: single_dots += 1 return single_dots
def count_single_dots(self)
Count all strokes of this recording that have only a single dot.
3.125286
2.350985
1.329352
xsum, ysum, counter = 0., 0., 0 for stroke in self.get_pointlist(): for point in stroke: xsum += point['x'] ysum += point['y'] counter += 1 return (xsum / counter, ysum / counter)
def get_center_of_mass(self)
Get a tuple (x,y) that is the center of mass. The center of mass is not necessarily the same as the center of the bounding box. Imagine a black square and a single dot wide outside of the square.
3.118213
3.060889
1.018728
symbol_stream = getattr(self, 'symbol_stream', [None for symbol in self.segmentation]) single_symbols = [] pointlist = self.get_sorted_pointlist() for stroke_indices, label in zip(self.segmentation, symbol_stream): ...
def to_single_symbol_list(self)
Convert this HandwrittenData object into a list of HandwrittenData objects. Each element of the list is a single symbol. Returns ------- list of HandwrittenData objects
5.34698
5.184721
1.031296
N = 10 count = 0 while True: lines = _run_git_command_lines(['log', '--oneline', '-n', str(N), '--skip', str(count), '--', '.'], cwd=path) for line in lines: ...
def git_log_iterator(path)
yield commits using git log -- <dir>
3.293143
3.071544
1.072146
addon_dir = os.path.realpath(addon_dir) last_version = read_manifest(addon_dir).get('version', '0.0.0') last_version_parsed = parse_version(last_version) if not is_git_controlled(addon_dir): return last_version if get_git_uncommitted(addon_dir): uncommitted = True count ...
def get_git_postversion(addon_dir)
return the addon version number, with a developmental version increment if there were git commits in the addon_dir after the last version change. If the last change to the addon correspond to the version number in the manifest it is used as is for the python package version. Otherwise a counter is incr...
3.047121
2.979557
1.022676
odoo_version_info = None addons = os.listdir(addons_dir) for addon in addons: addon_dir = os.path.join(addons_dir, addon) if is_installable_addon(addon_dir): manifest = read_manifest(addon_dir) _, _, addon_odoo_version_info = _get_version( addon_d...
def _get_odoo_version_info(addons_dir, odoo_version_override=None)
Detect Odoo version from an addons directory
2.733913
2.664481
1.026058
version = manifest.get('version') if not version: warn("No version in manifest in %s" % addon_dir) version = '0.0.0' if not odoo_version_override: if len(version.split('.')) < 5: raise DistutilsSetupError("Version in manifest must have at least " ...
def _get_version(addon_dir, manifest, odoo_version_override=None, git_post_version=True)
Get addon version information from an addon directory
2.303878
2.296586
1.003175
manifest = read_manifest(addon_dir) _, _, odoo_version_info = _get_version(addon_dir, manifest, odoo_version_override, git_post_version=False) return _get_install_requires(od...
def get_install_requires_odoo_addon(addon_dir, no_depends=[], depends_override={}, external_dependencies_override={}, odoo_version_override=None)
Get the list of requirements for an addon
3.617202
3.711943
0.974477
addon_dirs = [] addons = os.listdir(addons_dir) for addon in addons: addon_dir = os.path.join(addons_dir, addon) if is_installable_addon(addon_dir): addon_dirs.append(addon_dir) install_requires = set() for addon_dir in addon_dirs: r = get_install_requires_od...
def get_install_requires_odoo_addons(addons_dir, depends_override={}, external_dependencies_override={}, odoo_version_override=None)
Get the list of requirements for a directory containing addons
1.908885
1.88952
1.010248
res = set() for odoo_version_info in ODOO_VERSION_INFO.values(): addons_ns = odoo_version_info['addons_ns'] addons_dir = os.path.join(*addons_ns.split('.')) if os.path.isdir(addons_dir): if not odoo_version_info['namespace_packages'] or \ os.path.isfi...
def _find_addons_dir()
Try to find the addons dir / namespace package Returns addons_dir, addons_ns
2.63436
2.414068
1.091253
return make_declarative_base(self.session, Model=self.Model, metadata=metadata)
def make_declarative_base(self, metadata=None)
Override parent function with alchy's
6.294416
6.330903
0.994237
doc = doc_obj._data.copy() for key, prop in list(doc_obj._base_properties.items()): prop.validate(doc.get(key), key) raw_value = prop.get_python_value(doc.get(key)) if prop.unique: self.check_unique(doc_obj, key, raw_value) value =...
def prep_doc(self, doc_obj)
This method Validates, gets the Python value, checks unique indexes, gets the db value, and then returns the prepared doc dict object. Useful for save and backup functions. @param doc_obj: @return:
3.308271
3.128918
1.057321
'''Load Zappa settings, set defaults if needed, and apply to the Zappa object''' settings_all = json.load(zappa_settings) settings = settings_all[environment] # load defaults for missing options for key,value in DEFAULT_SETTINGS.items(): settings[key] = settings.get(key, value) if '~'...
def apply_zappa_settings(zappa_obj, zappa_settings, environment)
Load Zappa settings, set defaults if needed, and apply to the Zappa object
3.423621
3.058213
1.119484
print(("Deploying " + environment)) zappa, settings, lambda_name, zip_path = \ _package(environment, zappa_settings) s3_bucket_name = settings['s3_bucket'] try: # Load your AWS credentials from ~/.aws/credentials zappa.load_credentials() # Make sure the necessary...
def deploy(environment, zappa_settings)
Package, create and deploy to Lambda.
4.061677
4.037831
1.005905
print(("Updating " + environment)) # Package dependencies, and the source code into a zip zappa, settings, lambda_name, zip_path = \ _package(environment, zappa_settings) s3_bucket_name = settings['s3_bucket'] try: # Load your AWS credentials from ~/.aws/credentials ...
def update(environment, zappa_settings)
Update an existing deployment.
5.176693
5.066352
1.021779
def print_logs(logs): for log in logs: timestamp = log['timestamp'] message = log['message'] if "START RequestId" in message: continue if "REPORT RequestId" in message: continue if "END RequestId" in message: ...
def tail(environment, zappa_settings)
Stolen verbatim from django-zappa: https://github.com/Miserlou/django-zappa/blob/master/django_zappa/management/commands/tail.py
2.950381
2.837748
1.039691
queryset = kwargs.pop('object_list') page_template = kwargs.pop('page_template', None) context_object_name = self.get_context_object_name(queryset) context = {'object_list': queryset, 'view': self} context.update(kwargs) if context_object_name is not None: ...
def get_context_data(self, **kwargs)
Get the context for this view. Also adds the *page_template* variable in the context. If the *page_template* is not given as a kwarg of the *as_view* method then it is generated using app label, model name (obviously if the list is a queryset), *self.template_name_suffix* and *...
2.485405
2.622378
0.947768
request = self.request querystring_key = request.REQUEST.get('querystring_key', PAGE_LABEL) if request.is_ajax() and querystring_key == self.key: return [self.page_template] return super( AjaxMultipleObjectTemplateResponseMixin, self).get_template_names()
def get_template_names(self)
Switch the templates for Ajax requests.
5.819942
4.949917
1.175766