Implement a worker for write-math.com.

def work():
    """Implement a worker for write-math.com."""
    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 something to classify
        url = "http://www.martin-thoma.de/write-math/api/get_unclassified.php"
        response = urlopen(url)
        page_source = response.read()
        parsed_json = json.loads(page_source)
        if parsed_json is False:
            return "Nothing left to classify"
        raw_data_json = parsed_json['recording']

        # Classify
        # Check recording
        try:
            json.loads(raw_data_json)
        except ValueError:
            return ("Raw Data ID %s; Invalid JSON string: %s" %
                    (parsed_json['id'], raw_data_json))

        # Classify
        if use_segmenter_flag:
            strokelist = json.loads(raw_data_json)
            beam = se.Beam()
            for stroke in strokelist:
                beam.add_stroke(stroke)
            results = beam.get_writemath_results()
        else:
            results_sym = classify.classify_segmented_recording(raw_data_json)
            results = []
            strokelist = json.loads(raw_data_json)
            segmentation = [list(range(len(strokelist)))]
            translate = _get_translate()
            for symbol in results_sym:
                s = {'id': get_writemath_id(symbol, translate),
                     'probability': symbol['probability']}
                results.append({'probability': symbol['probability'],
                                'segmentation': segmentation,
                                'symbols': [s]})

        print("\thttp://write-math.com/view/?raw_data_id=%s" %
              str(parsed_json['id']))

        # Submit classification to write-math.com server
        results_json = get_json_result(results, n=n)
        headers = {'User-Agent': 'Mozilla/5.0',
                   'Content-Type': 'application/x-www-form-urlencoded'}
        payload = {'recording_id': parsed_json['id'],
                   'results': results_json,
                   'api_key': cmd['worker_api_key']}

        s = requests.Session()
        req = requests.Request('POST', url, headers=headers, data=payload)
        prepared = req.prepare()
        response = s.send(prepared)
        try:
            response = json.loads(response.text)
        except ValueError:
            return "Invalid JSON response: %s" % response.text

        if 'error' in response:
            logging.info(response)
            return str(response)
    return "Done - Classified %i recordings" % chunk_size