code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if times is None: times = [] for stroke in pointlist: stroke_info = {"start": stroke[0]['time'], "end": stroke[-1]['time'], "pen_down": True} # set up variables for interpolation x, y, t = [], ...
def _calculate_pen_down_strokes(self, pointlist, times=None)
Calculate the intervall borders 'times' that contain the information when a stroke started, when it ended and how it should be interpolated.
2.066916
2.027161
1.019611
if times is None: times = [] for i in range(len(pointlist) - 1): stroke_info = {"start": pointlist[i][-1]['time'], "end": pointlist[i + 1][0]['time'], "pen_down": False} x, y, t = [], [], [] fo...
def _calculate_pen_up_strokes(self, pointlist, times=None)
'Pen-up' strokes are virtual strokes that were not drawn. It models the time when the user moved from one stroke to the next.
2.181539
2.163656
1.008266
new_stroke = [] stroke = sorted(stroke, key=lambda p: p['time']) x, y, t = [], [], [] for point in stroke: x.append(point['x']) y.append(point['y']) t.append(point['time']) x, y = numpy.array(x), numpy.array(y) failed = Fals...
def _space(self, hwr_obj, stroke, kind)
Do the interpolation of 'kind' for 'stroke
2.263814
2.245991
1.007936
assert len(self.theta) == len(points), \ "points has length %i, but should have length %i" % \ (len(points), len(self.theta)) new_point = {'x': 0, 'y': 0, 'time': 0} for key in new_point: new_point[key] = self.theta[0] * points[0][key] + \ ...
def _calculate_average(self, points)
Calculate the arithmetic mean of the points x and y coordinates seperately.
2.376412
2.394134
0.992598
latest_model = utils.get_latest_in_folder(model_folder, ".json") if (latest_model == "") or override: logging.info("Create a base model...") model_src = os.path.join(model_folder, "model-0.json") command = "%s make %s %s > %s" % (utils.get_nntoolkit(), ...
def create_model(model_folder, model_type, topology, override)
Create a model if it doesn't exist already. Parameters ---------- model_folder : The path to the folder where the model is described with an `info.yml` model_type : MLP topology : Something like 160:500:369 - that means the first layer has 160 neurons, the second lay...
4.038495
4.659181
0.866782
model_description_file = os.path.join(model_folder, "info.yml") # Read the model description file with open(model_description_file, 'r') as ymlfile: model_description = yaml.load(ymlfile) project_root = utils.get_project_root() # Read the feature description file feature_folder = o...
def main(model_folder, override=False)
Parse the info.yml from ``model_folder`` and create the model file.
2.999721
2.915142
1.029014
project_root = utils.get_project_root() # Get latest model folder models_folder = os.path.join(project_root, "models") latest_model = utils.get_latest_folder(models_folder) # Get command line arguments from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter parser = Argumen...
def get_parser()
Return the parser object for this script.
2.881166
2.820771
1.021411
url = "http://www.martin-thoma.de/write-math/classify/index.php" headers = {'User-Agent': 'Mozilla/5.0', 'Content-Type': 'application/x-www-form-urlencoded'} payload = {'drawnJSON': raw_data_json} s = requests.Session() req = requests.Request('POST', url, headers=headers, data=p...
def submit_recording(raw_data_json)
Submit a recording to the database on write-math.com. Parameters ---------- raw_data_json : str Raw data in JSON format Raises ------ requests.exceptions.ConnectionError If the internet connection is lost.
3.60567
3.136599
1.149548
import nntoolkit.evaluate classification = nntoolkit.evaluate.show_results(results, n) return "<pre>" + classification.replace("\n", "<br/>") + "</pre>"
def show_results(results, n=10)
Show the TOP n results of a classification. >>> results = [{'\\alpha': 0.67}, {'\\propto': 0.25}] >>> show_results(results)
8.0563
9.768346
0.824735
global n if request.method == 'GET' and request.args.get('heartbeat', '') != "": return request.args.get('heartbeat', '') if request.method == 'POST': logging.warning('POST to /interactive is deprecated. ' 'Use /worker instead') else: # Page where the...
def interactive()
Interactive classifier.
7.790013
8.056228
0.966955
s = [] last = -1 for res in results[:min(len(results), n)]: if res['probability'] < last*0.5 and res['probability'] < 0.05: break if res['probability'] < 0.01: break s.append(res) last = res['probability'] return json.dumps(s)
def get_json_result(results, n=10)
Return the top `n` results as a JSON list. >>> results = [{'probability': 0.65, ... 'whatever': 'bar'}, ... {'probability': 0.21, ... 'whatever': 'bar'}, ... {'probability': 0.05, ... 'whatever': 'bar'},] >>> get_json_result(results, ...
3.101845
3.079519
1.00725
global n global use_segmenter_flag if request.method == 'POST': raw_data_json = request.form['classify'] try: secret_uuid = request.form['secret'] except: logging.info("No secret uuid given. Create one.") secret_uuid = str(uuid.uuid4()) ...
def worker()
Implement a worker for write-math.com.
4.275753
4.308654
0.992364
result = [] strokes = sorted(strokes) for stroke_index in strokes: result.append(pointlist[stroke_index]) return result
def _get_part(pointlist, strokes)
Get some strokes of pointlist Parameters ---------- pointlist : list of lists of dicts strokes : list of integers Returns ------- list of lists of dicts
3.046691
3.231745
0.942739
translate = {} model_path = pkg_resources.resource_filename('hwrt', 'misc/') translation_csv = os.path.join(model_path, 'latex2writemathindex.csv') arguments = {'newline': '', 'encoding': 'utf8'} with open(translation_csv, 'rt', **arguments) as csvfile: contents = csvfile.read() lin...
def _get_translate()
Get a dictionary which translates from a neural network output to semantics.
3.649655
3.669917
0.994479
semantics = el['semantics'].split(";")[1] if semantics not in translate: logging.debug("Could not find '%s' in translate.", semantics) logging.debug("el: %s", el) return None else: writemathid = translate[semantics] return writemathid
def get_writemath_id(el, translate)
Parameters ---------- el : dict with key 'semantics' results element Returns ------- int or None: ID of the symbol on write-math.com
4.403862
4.651439
0.946774
new_results = [] # Read csv translate = _get_translate() for i, el in enumerate(results): writemathid = get_writemath_id(el, translate) if writemathid is None: continue new_results.append({'symbolnr': el['symbolnr'], 'semantics': writ...
def fix_writemath_answer(results)
Bring ``results`` into a format that is accepted by write-math.com. This means using the ID for the formula that is used by the write-math server. Examples -------- >>> results = [{'symbolnr': 214, ... 'semantics': '\\triangleq', ... 'probability': 0.03}, ...] >>> fi...
4.711713
3.833649
1.229041
global n cmd = utils.get_project_configuration() if 'worker_api_key' not in cmd: return ("You need to define a 'worker_api_key' in your ~/") chunk_size = 1000 logging.info("Start working with n=%i", n) for _ in range(chunk_size): # contact the write-math server and get so...
def work()
Implement a worker for write-math.com.
4.333424
4.090349
1.059426
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter parser = ArgumentParser(description=__doc__, formatter_class=ArgumentDefaultsHelpFormatter) parser.add_argument("-n", dest="n", default=10, type=int, help="Show...
def get_parser()
Return the parser object for this script.
3.222441
3.122367
1.032051
global n global use_segmenter_flag n = n_output use_segmenter_flag = use_segmenter logging.info("Start webserver...") app.run(port=port)
def main(port=8000, n_output=10, use_segmenter=False)
Main function starting the webserver.
3.738078
3.287315
1.137122
folders = [] 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(utils.get_project_root(), content['data-source']) raw_source_file = fol...
def update_if_outdated(folder)
Check if the currently watched instance (model, feature or preprocessing) is outdated and update it eventually.
3.477608
3.340402
1.041075
update_if_outdated(model_folder) model_description_file = os.path.join(model_folder, "info.yml") # Read the model description file with open(model_description_file, 'r') as ymlfile: model_description = yaml.load(ymlfile) # Get the data paths (hdf5 files) project_root = utils.get_pr...
def generate_training_command(model_folder)
Generate a string that contains a command with all necessary parameters to train the model.
2.439548
2.460746
0.991386
os.chdir(model_folder) training = generate_training_command(model_folder) if training is None: return -1 logging.info(training) os.chdir(model_folder) os.system(training)
def train_model(model_folder)
Train the model in ``model_folder``.
3.971726
4.175509
0.951196
model_description_file = os.path.join(model_folder, "info.yml") # Read the model description file with open(model_description_file, 'r') as ymlfile: model_description = yaml.load(ymlfile) # Analyze model logging.info(model_description['model']) data = {} data['training'] = os....
def main(model_folder)
Main part of the training script.
2.533254
2.55153
0.992837
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter parser = ArgumentParser(description=__doc__, formatter_class=ArgumentDefaultsHelpFormatter) parser.add_argument("-m", "--model", dest="model", help="where is th...
def get_parser()
Return the parser object for this script.
3.283863
3.111586
1.055366
assert len(points) > 0, "At least one point has to be given." min_x, max_x = points[0]['x'], points[0]['x'] min_y, max_y = points[0]['y'], points[0]['y'] for point in points: min_x, max_x = min(min_x, point['x']), max(max_x, point['x']) min_y, max_y = min(min_y, point['y']), max(max...
def get_bounding_box(points)
Get the bounding box of a list of points. Parameters ---------- points : list of points Returns ------- BoundingBox
1.540382
1.618011
0.952022
return a.p1.x <= b.p2.x \ and a.p2.x >= b.p1.x \ and a.p1.y <= b.p2.y \ and a.p2.y >= b.p1.y
def do_bb_intersect(a, b)
Check if BoundingBox a intersects with BoundingBox b.
1.816266
1.801931
1.007956
assert isinstance(segment1, LineSegment), \ "segment1 is not a LineSegment, but a %s" % type(segment1) assert isinstance(segment2, LineSegment), \ "segment2 is not a LineSegment, but a %s" % type(segment2) if len(get_segments_intersections(segment1, segment2)) >= 1: return 0 ...
def segments_distance(segment1, segment2)
Calculate the distance between two line segments in the plane. >>> a = LineSegment(Point(1,0), Point(2,0)) >>> b = LineSegment(Point(0,1), Point(0,2)) >>> "%0.2f" % segments_distance(a, b) '1.41' >>> c = LineSegment(Point(0,0), Point(5,5)) >>> d = LineSegment(Point(2,2), Point(4,4)) >>> e =...
2.091994
2.223016
0.941061
assert isinstance(point, Point), \ "point is not of type Point, but of %r" % type(point) dx = segment.p2.x - segment.p1.x dy = segment.p2.y - segment.p1.y if dx == dy == 0: # the segment's just a point return point.dist_to(segment.p1) if dx == 0: # It's a straight vertical li...
def point_segment_distance(point, segment)
>>> a = LineSegment(Point(1,0), Point(2,0)) >>> b = LineSegment(Point(2,0), Point(0,2)) >>> point_segment_distance(Point(0,0), a) 1.0 >>> "%0.2f" % point_segment_distance(Point(0,0), b) '1.41'
1.594266
1.631159
0.977382
px = p2['x']-p1['x'] py = p2['y']-p1['y'] squared_distance = px*px + py*py if squared_distance == 0: # The line is in fact only a single dot. # In this case the distance of two points has to be # calculated line_point = Point(p1['x'], p1['y']) point = Point(...
def perpendicular_distance(p3, p1, p2)
Calculate the distance from p3 to the stroke defined by p1 and p2. The distance is the length of the perpendicular from p3 on p1. Parameters ---------- p1 : dictionary with "x" and "y" start of stroke p2 : dictionary with "x" and "y" end of stroke p3 : dictionary with "x" and "y...
2.874981
2.967555
0.968805
return math.hypot(self.x - p2.x, self.y - p2.y)
def dist_to(self, p2)
Measure the distance to another point.
2.58699
2.240561
1.154617
# y1 = m*x1 + t # y2 = m*x2 + t => y1-y2 = m*(x1-x2) <=> m = (y1-y2)/(x1-x2) return ((self.p1.y-self.p2.y) / (self.p1.x-self.p2.x))
def get_slope(self)
Return the slope m of this line segment.
2.914595
2.588026
1.126185
return self.p1.y-self.get_slope()*self.p1.x
def get_offset(self)
Get the offset t of this line segment.
10.868193
5.420849
2.004888
# This can be solved more efficiently with sweep line counter = 0 for i, j in itertools.combinations(range(len(self.lineSegments)), 2): inters = get_segments_intersections(self.lineSegments[i], self.lineSegments[j]) ...
def count_selfintersections(self)
Get the number of self-intersections of this polygonal chain.
3.772438
3.697923
1.020151
line_segments_a = self.lineSegments # Calculate intersections intersection_points = [] for line1, line2 in itertools.product(line_segments_a, line_segments_b): intersection_points += get_segments_intersections(line1, lin...
def count_intersections(self, line_segments_b)
Count the intersections of two strokes with each other. Parameters ---------- line_segments_b : list A list of line segemnts Returns ------- int The number of intersections between A and B.
3.13971
3.729332
0.841896
return (self.p2.x-self.p1.x)*(self.p2.y-self.p1.y)
def get_area(self)
Calculate area of bounding box.
2.989645
2.248777
1.329454
return Point((self.p1.x+self.p2.x)/2.0, (self.p1.y+self.p2.y)/2.0)
def get_center(self)
Get the center point of this bounding box.
2.388881
2.075306
1.151098
import pymysql import pymysql.cursors # Import configuration file cfg = utils.get_database_configuration() if cfg is None: return None # Establish database connection connection = pymysql.connect(host=cfg[mysql_cfg]['host'], user=cfg[mysql_cfg]...
def _fetch_data_from_server(raw_data_id, mysql_cfg)
Get the data from raw_data_id from the server. :returns: The ``data`` if fetching worked, ``None`` if it failed.
3.037215
2.995429
1.01395
loaded = pickle.load(open(path_to_data, "rb")) raw_datasets = loaded['handwriting_datasets'] for raw_dataset in raw_datasets: if raw_dataset['handwriting'].raw_data_id == raw_data_id: return raw_dataset['handwriting'] return None
def _get_data_from_rawfile(path_to_data, raw_data_id)
Get a HandwrittenData object that has ``raw_data_id`` from a pickle file ``path_to_data``. :returns: The HandwrittenData object if ``raw_data_id`` is in path_to_data, otherwise ``None``.
3.400266
3.37358
1.00791
loaded = pickle.load(open(path_to_data, "rb")) raw_datasets = loaded['handwriting_datasets'] raw_ids = {} for raw_dataset in raw_datasets: raw_data_id = raw_dataset['handwriting'].raw_data_id if raw_dataset['formula_id'] not in raw_ids: raw_ids[raw_dataset['formula_id']]...
def _list_ids(path_to_data)
List raw data IDs grouped by symbol ID from a pickle file ``path_to_data``.
2.798081
2.523357
1.108873
current_desc_file = os.path.join(utils.get_project_root(), prev_description['data-source'], "info.yml") if not os.path.isfile(current_desc_file): logging.error("You are probably not in the folder of a model, because " ...
def _get_description(prev_description)
Get the parsed description file (a dictionary) from another parsed description file.
3.7472
3.733887
1.003565
# Get model description model_description_file = os.path.join(model_folder, "info.yml") if not os.path.isfile(model_description_file): logging.error("You are probably not in the folder of a model, because " "%s is not a file. (-m argument)", model_de...
def _get_system(model_folder)
Return the preprocessing description, the feature description and the model description.
3.321974
2.827605
1.174837
print("## Raw Data (ID: %i)" % raw_data_id) print("```") print(raw_data_string) print("```") preprocessing_desc, feature_desc, _ = _get_system(model_folder) # Print model print("## Model") print("%s\n" % model_folder) # Get the preprocessing queue tmp = preprocessing_desc...
def display_data(raw_data_string, raw_data_id, model_folder, show_raw)
Print ``raw_data_id`` with the content ``raw_data_string`` after applying the preprocessing of ``model_folder`` to it.
4.770017
4.71379
1.011928
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter parser = ArgumentParser(description=__doc__, formatter_class=ArgumentDefaultsHelpFormatter) parser.add_argument("-i", "--id", dest="id", default=292293, type=int, ...
def get_parser()
Return the parser object for this script.
3.277597
3.216375
1.019035
if list_ids: preprocessing_desc, _, _ = _get_system(model) raw_datapath = os.path.join(utils.get_project_root(), preprocessing_desc['data-source']) _list_ids(raw_datapath) else: if contact_server: data = _fetch_data_from_server...
def main(list_ids, model, contact_server, raw_data_id, show_raw, mysql_cfg='mysql_online')
Main function of view.py.
3.885891
3.915504
0.992437
with open(filename, 'w') as f: f.write('SCG_INK\n') f.write('%i\n' % len(hw.get_pointlist())) for stroke in hw.get_pointlist(): f.write('%i\n' % len(stroke)) for point in stroke: f.write('%i %i\n' % (point['x'], point['y']))
def write_hw_scgink(hw, filename='mathbrush-test.txt')
Parameters ---------- hw : HandwrittenData object filename : string Path, where the SCG INK file gets written
2.311404
2.292904
1.008068
# Read the model description file with open(os.path.join(folder, "info.yml"), 'r') as ymlfile: preprocessing_description = yaml.load(ymlfile) # Get the path of the raw data raw_datapath = os.path.join(utils.get_project_root(), preprocessing_description['dat...
def get_parameters(folder)
Get the parameters of the preprocessing done within `folder`. Parameters ---------- folder : string Returns ------- tuple : (path of raw data, path where preprocessed data gets stored, list of preprocessing algorithms)
4.16942
3.559397
1.171384
# Log everything logging.info("Data soure %s", path_to_data) logging.info("Output will be stored in %s", outputpath) tmp = "Preprocessing Queue:\n" for preprocessing_class in preprocessing_queue: tmp += str(preprocessing_class) + "\n" logging.info(tmp) # Load from pickled file ...
def create_preprocessed_dataset(path_to_data, outputpath, preprocessing_queue)
Create a preprocessed dataset file by applying `preprocessing_queue` to `path_to_data`. The result will be stored in `outputpath`.
3.930034
3.96053
0.9923
raw_datapath, outputpath, p_queue = get_parameters(folder) create_preprocessed_dataset(raw_datapath, outputpath, p_queue) utils.create_run_logfile(folder)
def main(folder)
Main part of preprocess_dataset that glues things togeter.
8.971308
8.39584
1.068542
index2formula_id = sorted(formula_id2index.items(), key=lambda n: n[1]) index2formula_file = os.path.join(feature_folder, "index2formula_id.csv") with open(index2formula_file, "w") as f: f.write("index,formula_id,latex\n") for formula_id, index in index2formula_id: f.write("...
def _create_index_formula_lookup(formula_id2index, feature_folder, index2latex)
Create a lookup file where the index is mapped to the formula id and the LaTeX command. Parameters ---------- formula_id2index : dict feature_folder : str Path to a folder in which a feature file as well as an index2formula_id.csv is. index2latex : dict Maps an integer i...
1.950272
2.096926
0.930062
translationfilename = "%s/translation-%s.csv" % (feature_folder, dataset_name) with open(translationfilename, "w") as f: f.write("index,raw_data_id,latex,formula_id\n") for el in translation: f.write("%i,%i,%s,%i\n" % (formula...
def _create_translation_file(feature_folder, dataset_name, translation, formula_id2index)
Write a loop-up file that contains the direct (record-wise) lookup information. Parameters ---------- feature_folder : Path to the feature files. dataset_name : 'traindata', 'validdata' or 'testdata'. translation : list of triples (raw data id, formula in latex, formula ...
2.671982
2.508217
1.065291
# Read the feature description file with open(os.path.join(feature_folder, "info.yml"), 'r') as ymlfile: feature_description = yaml.load(ymlfile) # Get preprocessed .pickle file from model description file path_to_data = os.path.join(utils.get_project_root(), ...
def main(feature_folder, create_learning_curve=False)
main function of create_ffiles.py
3.778582
3.781039
0.99935
logging.info("Multiply data...") for algorithm in mult_queue: new_trning_set = [] for recording in training_set: samples = algorithm(recording['handwriting']) for sample in samples: new_trning_set.append({'id': recording['id'], ...
def training_set_multiplication(training_set, mult_queue)
Multiply the training set by all methods listed in mult_queue. Parameters ---------- training_set : set of all recordings that will be used for training mult_queue : list of all algorithms that will take one recording and generate more than one. Returns ------- mutl...
4.641297
4.276567
1.085286
loaded = pickle.load(open(path_to_data, 'rb')) datasets = loaded['handwriting_datasets'] training_set, validation_set, test_set = [], [], [] dataset_by_formula_id = {} formula_id2index = {} index2latex = {} # Group data in dataset_by_formula_id so that 10% can be used for the # v...
def get_sets(path_to_data)
Get a training, validation and a testset as well as a dictionary that maps each formula_id to an index (0...nr_of_formulas - 1). Parameters ---------- path_to_data : A pickle file that contains a list of datasets. Returns ------- tuple 0: list The training_set c...
2.684487
2.37079
1.132317
mode += 'b' arguments = {} with open(serialization_file, mode, **arguments) as csvfile: spamwriter = csv.writer(csvfile, delimiter=str(';'), quotechar=str('"'), quoting=csv.QUOTE_MINIMAL) ...
def _calculate_feature_stats(feature_list, prepared, serialization_file): # pylint: disable=R0914 # Create feature only list feats = [x for x, _ in prepared] # Label is not necessary # Calculate all means / mins / maxs means = numpy.mean(feats, 0) mins = numpy.min(feats, 0) maxs = numpy....
Calculate min, max and mean for each feature. Store it in object.
2.7156
2.526793
1.074722
if is_traindata: _calculate_feature_stats(feature_list, prepared, "featurenormalization.csv") start = 0 for feature in feature_list: end = start + feature.get_dimension() # For every instance in the dataset: Norm...
def _normalize_features(feature_list, prepared, is_traindata)
Normalize features (mean subtraction, division by variance or range).
4.585152
4.527404
1.012755
prepared = [] start_time = time.time() translation = [] for i, data in enumerate(dataset): x = [] handwriting = data['handwriting'] x = handwriting.feature_extraction(feature_list) # Feature selection y = formula_id2index[data['formula_id']] # Get label tra...
def prepare_dataset(dataset, formula_id2index, feature_list, is_traindata, do_normalization=False)
Transform each instance of dataset to a (Features, Label) tuple.
4.052455
4.039137
1.003297
# create raw data file for hdf5_create if dataset_name == "traindata" and create_learning_curve: max_trainingexamples = 501 output_filename_save = output_filename steps = 10 for trainingexamples in range(100, max_trainingexamples, steps): # adjust output_filename...
def make_hdf5(dataset_name, feature_count, data, output_filename, create_learning_curve)
Create the hdf5 file. Parameters ---------- filename : name of the file that hdf5_create will use to create the hdf5 file. feature_count : integer number of features data : list of tuples data format ('feature_string', 'label')
4.266694
4.072322
1.04773
seg_data = "segmentation-X.npy" seg_labels = "segmentation-y.npy" # seg_ids = "segmentation-ids.npy" if os.path.isfile(seg_data) and os.path.isfile(seg_labels): X = numpy.load(seg_data) y = numpy.load(seg_labels) with open('datasets.pickle', 'rb') as f: datasets...
def get_dataset()
Create a dataset for machine learning of segmentations. Returns ------- tuple : (X, y) where X is a list of tuples. Each tuple is a feature. y is a list of labels (0 for 'not in one symbol' and 1 for 'in symbol')
2.796602
2.710714
1.031684
for symbol_index, symbol in enumerate(segmentation): if stroke_id_needle in symbol: return symbol_index return None
def _get_symbol_index(stroke_id_needle, segmentation)
Parameters ---------- stroke_id_needle : int Identifier for the stroke of which the symbol should get found. segmentation : list of lists of integers An ordered segmentation of strokes to symbols. Returns ------- The symbol index in which stroke_id_needle occurs Examples ...
2.4943
3.839132
0.649704
cfg = utils.get_database_configuration() mysql = cfg['mysql_online'] connection = pymysql.connect(host=mysql['host'], user=mysql['user'], passwd=mysql['passwd'], db=mysql['db'], ...
def get_segmented_raw_data(top_n=10000)
Fetch data from the server. Parameters ---------- top_n : int Number of data sets which get fetched from the server.
3.981648
4.038149
0.986008
new_recordings = [] for recording in recordings: recording['data'] = json.loads(recording['data']) tmp = json.loads(recording['segmentation']) recording['segmentation'] = normalize_segmentation(tmp) had_none = False for stroke in recording['data']: for po...
def filter_recordings(recordings)
Remove all recordings which have points without time. Parameters ---------- recordings : list of dicts Each dictionary has the keys 'data' and 'segmentation' Returns ------- list of dicts : Only recordings where all points have time values.
3.171129
3.22962
0.981889
assert type(X) is numpy.ndarray assert type(y) is numpy.ndarray assert len(X) == len(y) assert X.dtype == 'float32' assert y.dtype == 'int32' nn_pickled_filename = 'is_one_symbol_classifier.pickle' if os.path.isfile(nn_pickled_filename): with open(nn_pickled_filename, 'rb') as ...
def get_nn_classifier(X, y)
Train a neural network classifier. Parameters ---------- X : numpy array A list of feature vectors y : numpy array A list of labels Returns ------- Theano expression : The trained neural network
2.371397
2.517065
0.942128
stroke1 = recording[strokeid1] stroke2 = recording[strokeid2] assert isinstance(stroke1, list), "stroke1 is a %s" % type(stroke1) X_i = [] for s in [stroke1, stroke2]: hw = HandwrittenData(json.dumps([s])) feat1 = features.ConstantPointCoordinates(strokes=1, ...
def get_stroke_features(recording, strokeid1, strokeid2)
Get the features used to decide if two strokes belong to the same symbol or not. Parameters ---------- recording : list A list of strokes strokeid1 : int strokeid2 : int Returns ------- list : A list of features which could be useful to decide if stroke1 and ...
4.98532
5.265643
0.946764
def translate(segmentation, strokes): t = [] for symbol in segmentation: symbol_new = [] for stroke in symbol: symbol_new.append(strokes[stroke]) t.append(symbol_new) return t if strokes is None: strokes = [i for i in range...
def merge_segmentations(segs1, segs2, strokes=None)
Parameters ---------- segs1 : a list of tuples Each tuple is a segmentation with its score segs2 : a list of tuples Each tuple is a segmentation with its score strokes : list of stroke names for segs2 Returns ------- list of tuples : Segmentations with their score, c...
3.693754
3.338536
1.1064
points = get_points(recording) mst = get_mst(points) mst_wood = [{'mst': mst, 'strokes': list(range(len(mst)))}] # TODO: break mst into wood of msts wherever possible by recognizing single # symbols by stroke bbintersections = get_bb_intersections(recording) for i, stroke in enumerate(...
def get_mst_wood(recording, single_clf)
Parameters ---------- recording : A list of lists Each sublist represents a stroke single_clf : object A classifier for single symbols - it only says "True" when a stroke is a single symbol or "False" when a stroke is only part of a symbol. Returns ------- list A...
5.294992
5.288478
1.001232
for symbol_pred in pred_seg: for symbol_real in real_seg: if symbol_pred[0] in symbol_real: for stroke in symbol_pred: if stroke not in symbol_real: return True return False
def has_missing_break(real_seg, pred_seg)
Parameters ---------- real_seg : list of integers The segmentation as it should be. pred_seg : list of integers The predicted segmentation. Returns ------- bool : True, if strokes of two different symbols are put in the same symbol.
3.268273
3.439592
0.950192
for symbol_real in real_seg: for symbol_pred in pred_seg: if symbol_real[0] in symbol_pred: for stroke in symbol_real: if stroke not in symbol_pred: return True return False
def has_wrong_break(real_seg, pred_seg)
Parameters ---------- real_seg : list of integers The segmentation as it should be. pred_seg : list of integers The predicted segmentation. Returns ------- bool : True, if strokes of one symbol were segmented to be in different symbols.
3.193564
3.303719
0.966657
for mst_index, mst in enumerate(mst_wood): if i in mst['strokes']: return (mst_index, mst['strokes'].index(i)) raise ValueError('%i was not found as stroke index.' % i)
def find_split_node(mst_wood, i)
Parameters ---------- mst_wood : list of dictionarys i : int Number of the stroke where one mst gets split Returns ------- tuple : (mst index, node index)
4.903517
3.47278
1.411986
for j in range(len(mst['mst'])): mst['mst'][i][j] = 0 mst['mst'][j][i] = 0 _, components = scipy.sparse.csgraph.connected_components(mst['mst']) comp_indices = {} for el in set(components): comp_indices[el] = {'strokes': [], 'strokes_i': []} for i, comp_nr in enumerate(c...
def break_mst(mst, i)
Break mst into multiple MSTs by removing one node i. Parameters ---------- mst : symmetrical square matrix i : index of the mst where to break Returns ------- list of dictionarys ('mst' and 'strokes' are the keys)
2.530824
2.450582
1.032744
last_stroke = -1 for symbol in segmentation: for stroke in symbol: if last_stroke > stroke: return True last_stroke = stroke return False
def _is_out_of_order(segmentation)
Check if a given segmentation is out of order. Examples -------- >>> _is_out_of_order([[0, 1, 2, 3]]) False >>> _is_out_of_order([[0, 1], [2, 3]]) False >>> _is_out_of_order([[0, 1, 3], [2]]) True
4.413099
6.614048
0.667231
points = [] for stroke in recording: point = geometry.get_bounding_box(stroke).get_center() points.append(point) return points
def get_points(recording)
Get one point for each stroke in a recording. The point represents the strokes spacial position (e.g. the center of the bounding box). Parameters ---------- recording : list of strokes Returns ------- list : points
5.888773
4.933218
1.193698
intersections = numpy.zeros((len(recording), len(recording)), dtype=bool) for i in range(len(recording)-1): a = geometry.get_bounding_box(recording[i]).grow(0.2) for j in range(i+1, len(recording)): b = geometry.get_bounding_box(recording[j]).grow...
def get_bb_intersections(recording)
Get all intersections of the bounding boxes of strokes. Parameters ---------- recording : list of lists of integers Returns ------- A symmetrical matrix which indicates if two bounding boxes intersect.
2.189176
2.325851
0.941237
graph = Graph() for point in points: graph.add_node(point) graph.generate_euclidean_edges() matrix = scipy.sparse.csgraph.minimum_spanning_tree(graph.w) mst = matrix.toarray().astype(int) # returned matrix is not symmetrical! make it symmetrical for i in range(len(mst)): ...
def get_mst(points)
Parameters ---------- points : list of points (geometry.Point) The first element of the list is the center of the bounding box of the first stroke, the second one belongs to the seconds stroke, ... Returns ------- mst : square matrix 0 nodes the edges are not connected, > 0 ...
2.467777
2.515862
0.980887
evaluate = utils.evaluate_model_single_recording_preloaded results = evaluate(self.preprocessing_queue, self.feature_list, self.model, self.output_semantics, json.dumps(parsed_json['data'...
def predict(self, parsed_json)
Parameters ---------- parsed_json : dict with keys 'data' and 'id', where 'data' contains a recording and 'id' is the id on write-math.com for debugging purposes
10.488932
9.155006
1.145704
self.nodes.append(Node(len(self.nodes), payload)) return len(self.nodes) - 1
def add_node(self, payload)
Returns ------- int Identifier for the inserted node.
3.235871
3.239433
0.9989
global stroke_prob assert count >= 1 epsilon = 0.00000001 if stroke_prob is None: misc_path = pkg_resources.resource_filename('hwrt', 'misc/') stroke_prob_file = os.path.join(misc_path, 'prob_stroke_count_by_symbol.yml') with open(stro...
def p_strokes(symbol, count)
Get the probability of a written `symbol` having `count` strokes. Parameters ---------- symbol : str LaTeX command count : int, >= 1 Returns ------- float In [0.0, 1.0]
3.154775
3.138959
1.005039
prob = 0.0 for symbol, seg in zip(hypothesis['symbols'], hypothesis['segmentation']): # symbol_latex = symbol['symbol'].split(";")[1] # TODO: Does p_strokes really improve the system? prob += symbol['probability'] # * p_strokes(symbol_latex, len(seg)) # Use language model to u...
def _calc_hypothesis_probability(hypothesis)
Get the probability (or rather a score) of a hypothesis. Parameters ---------- hypothesis : dict with keys 'segmentation', 'symbols', ... Returns ------- float in [0.0, 1.0]
5.611263
5.306657
1.057401
latex = [] for symbol in hyp['symbols']: latex.append(symbol['symbol']) return ";;".join(latex)
def build_unicode(hyp)
Parameters ---------- hyp : dict {'segmentation': [[0, 3], [1, 2]], 'symbols': [{'symbol': ID, 'probability': 0.12}], 'geometry': {'symbol': index, 'bottom': None or dict, 'subscript': None or dict, 'right': None or dict...
6.055804
4.803274
1.260766
latex = [] for symbol in hyp['symbols']: latex.append(symbol['symbol'].split(";")[1]) return " ".join(latex)
def build_latex(hyp)
Parameters ---------- hyp : dict {'segmentation': [[0, 3], [1, 2]], 'symbols': [{'symbol': ID, 'probability': 0.12}], 'geometry': {'symbol': index, 'bottom': None or dict, 'subscript': None or dict, 'right': None or dict...
5.161469
4.119364
1.252977
guesses = single_clf.predict({'data': [new_stroke], 'id': None})[:self.m] for hyp in self.hypotheses: new_geometry = deepcopy(hyp['geometry']) most_right = new_geometry if len(hyp['symbols']) == 0: while '...
def _add_hypotheses_assuming_new_stroke(self, new_stroke, stroke_nr, new_beam)
Get new guesses by assuming new_stroke is a new symbol. Parameters ---------- new_stroke : list of dicts A list of dicts [{'x': 12, 'y': 34, 'time': 56}, ...] which represent a point. stroke_nr : int Number of the stroke for segmentation new_b...
3.615623
3.617811
0.999395
global single_clf if len(self.hypotheses) == 0: # Don't put this in the constructor! self.hypotheses = [{'segmentation': [], 'symbols': [], 'geometry': {}, 'probability': Decimal(1) ...
def add_stroke(self, new_stroke)
Update the beam so that it considers `new_stroke`. When a `new_stroke` comes, it can either belong to a symbol for which at least one other stroke was already made or belong to a symbol for which `new_stroke` is the first stroke. The number of hypotheses after q strokes without pruning...
3.977414
3.878302
1.025555
self.hypotheses = sorted(self.hypotheses, key=lambda e: e['probability'], reverse=True)[:self.k]
def _prune(self)
Shorten hypotheses to the best k ones.
4.826556
2.745283
1.758127
results = [] for hyp in self.hypotheses: symbols = [] for sym in hyp['symbols']: symbols.append({'id': sym['symbol'].split(';')[0], 'probability': sym['probability']}) results.append({'probability': float(hyp['p...
def get_writemath_results(self)
Get the result in the format [{'probability': 0.987, 'segmentation': [[0, 1], [2, 4], [3]]} // index of the stroke 'symbols': [{'id': 456, // on write-math.com 'probability': 0.123}, {'id': 456, 'probability': 0.999}, //...
3.739108
2.275662
1.643086
with open('hwrt/misc/is_one_symbol_classifier.pickle', 'rb') as f: a = pickle.load(f) arrays = [] for el1 in a.input_storage: for el2 in el1.__dict__['storage']: if isinstance(el2, cuda.CudaNdarray): arrays.append({'storage': numpy.asarray(el2), ...
def get_matrices()
Get the matrices from a pickled files. Returns ------- list List of all matrices.
7.202266
7.302507
0.986273
# Write layers filenames = [] for layer in range(len(matrices)): if matrices[layer]['name'] == 'W': weights = matrices[layer]['storage'] weights_file = h5py.File('W%i.hdf5' % (layer / 2), 'w') weights_file.create_dataset(weights_file.id.name, data=weights) ...
def create_model_tar(matrices, tarname="model-cuda-converted.tar")
Create a tar file which contains the model. Parameters ---------- matrices : list tarname : str Target file which will be created.
2.330292
2.356073
0.989057
hwr_objects = [] for filepath in natsort.natsorted(glob.glob("%s/*.inkml" % folder)): tmp = inkml.read(filepath) for hwr in tmp.to_single_symbol_list(): hwr_objects.append(hwr) logging.info("Done reading formulas") save_raw_pickle(hwr_objects) return hwr_objects
def read_folder(folder)
Parameters ---------- folder : str Returns ------- list of HandwrittenData objects
6.761775
7.024781
0.96256
converted_hwr = [] translate = {} translate_id = {} model_path = pkg_resources.resource_filename('hwrt', 'misc/') translation_csv = os.path.join(model_path, 'latex2writemathindex.csv') arguments = {'newline': '', 'encoding': 'utf8'} with open(translation_csv, 'rt', **arguments) as csvf...
def save_raw_pickle(hwr_objects)
Parameters ---------- hwr_objects : list of hwr objects
3.006896
3.057577
0.983425
# Required due to multiple with statements on one line req_version = (2, 7) cur_version = sys.version_info if cur_version >= req_version: print("Python version... %sOK%s (found %s, requires %s)" % (Bcolors.OKGREEN, Bcolors.ENDC, str(platform.python_version()), s...
def check_python_version()
Check if the currently running Python version is new enough.
3.081026
2.945454
1.046027
print("\033[1mCheck modules\033[0m") required_modules = ['argparse', 'matplotlib', 'natsort', 'pymysql', 'cPickle', 'theano', 'dropbox', 'yaml', 'webbrowser', 'hashlib', 'numpy', 'jinja2'] found = [] for required_module in requ...
def check_python_modules()
Check if all necessary / recommended modules are installed.
2.188133
2.166026
1.010206
print("\033[1mCheck executables\033[0m") required_executables = [utils.get_nntoolkit()] for executable in required_executables: path = which(executable) if path is None: print("%s ... %sNOT%s found" % (executable, Bcolors.WARNING, ...
def check_executables()
Check if all necessary / recommended executables are installed.
3.347914
3.304142
1.013248
check_python_version() check_python_modules() check_executables() home = os.path.expanduser("~") print("\033[1mCheck files\033[0m") rcfile = os.path.join(home, ".hwrtrc") if os.path.isfile(rcfile): print("~/.hwrtrc... %sFOUND%s" % (Bcolors.OKGREEN, Bcolors.ENDC)) ...
def main()
Execute all checks.
3.274641
3.182312
1.029013
d1 = read_raw(dataset1) d2 = read_raw(dataset2) merged = merge(d1, d2) with open(target, 'wb') as f: pickle.dump(merged, f, protocol=pickle.HIGHEST_PROTOCOL)
def main(dataset1, dataset2, target)
Parameters ---------- dataset1 : str dataset2 : str target : str
2.225493
2.45869
0.905154
with open(data_path, 'rb') as f: data = pickle.load(f) return data
def read_raw(data_path)
Parameters ---------- data_path : str
2.239678
2.90811
0.770149
if d1['formula_id2latex'] is None: formula_id2latex = {} else: formula_id2latex = d1['formula_id2latex'].copy() formula_id2latex.update(d2['formula_id2latex']) handwriting_datasets = d1['handwriting_datasets'] for dataset in d2['handwriting_datasets']: handwriting_datase...
def merge(d1, d2)
Merge two raw datasets into one. Parameters ---------- d1 : dict d2 : dict Returns ------- dict
2.495876
2.577705
0.968255
with open(path) as f: content = f.read() pretty_print = lambda data: '\n'.join([line for line in parseString(data) .toprettyxml(indent=' ' * 2) .split('\n') ...
def beautify_xml(path)
Beautify / pretty print XML in `path`. Parameters ---------- path : str Returns ------- str
3.130471
3.766354
0.831168
import xml.etree.ElementTree root = xml.etree.ElementTree.parse(filepath).getroot() # Get the raw data recording = [] strokes = sorted(root.findall('{http://www.w3.org/2003/InkML}trace'), key=lambda child: int(child.attrib['id'])) time = 0 for stroke in strokes: ...
def read(filepath)
Read a single InkML file Parameters ---------- filepath : string path to the (readable) InkML file Returns ------- HandwrittenData : The parsed InkML file as a HandwrittenData object
2.847991
2.784192
1.022915
import glob recordings = [] for filename in natsorted(glob.glob("%s/*.inkml" % folder)): hw = read(filename) if hw.formula_in_latex is not None: hw.formula_in_latex = hw.formula_in_latex.strip() if hw.formula_in_latex is None or \ not hw.formula_in_latex.s...
def read_folder(folder)
Parameters ---------- folder : string Path to a folde with *.inkml files. Returns ------- list : Objects of the type HandwrittenData
3.034233
2.824206
1.074367
s1bb = s1.get_bounding_box() s2bb = s2.get_bounding_box() total_area = ((s2bb['maxx'] - s2bb['minx']+1) * (s2bb['maxy'] - s2bb['miny']+1)) total_area = float(total_area) top_area = 0.0 superscript_area = 0.0 right_area = 0.0 subscript_area = 0.0 bottom_area = 0...
def estimate(s1, s2)
Estimate the spacial relationship by examining the position of the bounding boxes. Parameters ---------- s1 : HandwrittenData s2 : HandwrittenData Returns ------- dict of probabilities {'bottom': 0.1, 'subscript': 0.2, 'right': 0.3, 'superscript': 0.3...
1.432286
1.367265
1.047556
return os.path.isfile(local_path_file) and \ hashlib.md5(open(local_path_file, 'rb').read()).hexdigest() == md5_hash
def is_file_consistent(local_path_file, md5_hash)
Check if file is there and if the md5_hash is correct.
2.001699
1.799139
1.112587
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter parser = ArgumentParser(description=__doc__, formatter_class=ArgumentDefaultsHelpFormatter) return parser
def get_parser()
Return the parser object for this script.
2.415366
2.013899
1.199348