<commit_before>'''
PathwayGenie (c) University of Manchester 2015

PathwayGenie is licensed under the MIT License.

To view a copy of this license, visit <http://opensource.org/licenses/MIT/>.

@author:  neilswainston
'''
# pylint: disable=no-self-use
# pylint: disable=too-few-public-methods
import json
import time
import uuid
from flask import Flask, Response, render_template, request

import parts


# Configuration:
DEBUG = True
SECRET_KEY = str(uuid.uuid4())

# Create application:
_APP = Flask(__name__)
_APP.config.from_object(__name__)

_STATUS = {}
_THREADS = {}

_ORGANISMS = [{'taxonomy_id': 83333, 'name': 'Saccharomyces'},
              {'taxonomy_id': 100226, 'name': 'Streptomyces'}]


@_APP.route('/')
def home():
    '''Renders homepage.'''
    return render_template('index.html')


@_APP.route('/submit', methods=['POST'])
def submit():
    '''Responds to submission.'''
    query = json.loads(request.data)
    query['protein_ids'] = [x.strip() for x in query['protein_ids'].split(',')]
    query['len_target'] = int(query['len_target'])
    query['tir_target'] = float(query['tir_target'])

    # Map organism to taxonomy id:
    organism = query.pop('organism')
    query['taxonomy_id'] = 83333

    # Do job in new thread, return result when completed:
    job_id = str(uuid.uuid4())
    _STATUS[job_id] = {'job_id': job_id, 'progress': 0}
    listener = Listener()
    thread = parts.PartsThread(job_id, query)
    thread.add_listener(listener)
    _THREADS[job_id] = thread
    thread.start()

    return job_id


@_APP.route('/progress/<job_id>')
def progress(job_id):
    '''Returns progress of job.'''
    def _check_progress(job_id):
        '''Checks job progress.'''
        while _STATUS[job_id]['progress'] < 100:
            time.sleep(1)
            yield 'data:' + _get_response(job_id) + '\n\n'

        yield 'data:' + _get_response(job_id) + '\n\n'

    if job_id in _STATUS:
        return Response(_check_progress(job_id), mimetype='text/event-stream')
    else:
        return 'Job ' + job_id + ' unknown or finished.'


@_APP.route('/organisms/<term>')
def get_organisms(term):
    '''Gets organisms from search term.'''
    term = term.lower()
    return json.dumps([value for value in _ORGANISMS
                       if term in value['name'].lower()])


@_APP.route('/cancel/<job_id>')
def cancel(job_id):
    '''Cancels job.'''
    _THREADS[job_id].cancel()
    return 'Cancelled: ' + job_id


def _get_response(job_id):
    '''Returns current progress for job id.'''
    return json.dumps(_STATUS[job_id])


class Listener(object):
    '''Simple event listener.'''

    def event_fired(self, event):
        '''Responds to event being fired.'''
        _STATUS[event['job_id']] = event


if __name__ == '__main__':
    _APP.run(threaded=True)<commit_msg>Minor restructure of organisms data structure.<commit_after>'''
PathwayGenie (c) University of Manchester 2015

PathwayGenie is licensed under the MIT License.

To view a copy of this license, visit <http://opensource.org/licenses/MIT/>.

@author:  neilswainston
'''
# pylint: disable=no-self-use
# pylint: disable=too-few-public-methods
import json
import time
import uuid
from flask import Flask, Response, render_template, request

import parts


# Configuration:
DEBUG = True
SECRET_KEY = str(uuid.uuid4())

# Create application:
_APP = Flask(__name__)
_APP.config.from_object(__name__)

_STATUS = {}
_THREADS = {}

_ORGANISMS = {'Saccharomyces': '83333',
              'Streptomyces': '100226'}


@_APP.route('/')
def home():
    '''Renders homepage.'''
    return render_template('index.html')


@_APP.route('/submit', methods=['POST'])
def submit():
    '''Responds to submission.'''
    query = json.loads(request.data)
    query['protein_ids'] = [x.strip() for x in query['protein_ids'].split(',')]
    query['len_target'] = int(query['len_target'])
    query['tir_target'] = float(query['tir_target'])

    # Map organism to taxonomy id:
    organism = query.pop('organism')
    query['taxonomy_id'] = _ORGANISMS[organism]

    # Do job in new thread, return result when completed:
    job_id = str(uuid.uuid4())
    _STATUS[job_id] = {'job_id': job_id, 'progress': 0}
    listener = Listener()
    thread = parts.PartsThread(job_id, query)
    thread.add_listener(listener)
    _THREADS[job_id] = thread
    thread.start()

    return job_id


@_APP.route('/progress/<job_id>')
def progress(job_id):
    '''Returns progress of job.'''
    def _check_progress(job_id):
        '''Checks job progress.'''
        while _STATUS[job_id]['progress'] < 100:
            time.sleep(1)
            yield 'data:' + _get_response(job_id) + '\n\n'

        yield 'data:' + _get_response(job_id) + '\n\n'

    if job_id in _STATUS:
        return Response(_check_progress(job_id), mimetype='text/event-stream')
    else:
        return 'Job ' + job_id + ' unknown or finished.'


@_APP.route('/organisms/<term>')
def get_organisms(term):
    '''Gets organisms from search term.'''
    term = term.lower()
    return json.dumps([{'name': k, 'taxonomy_id': v}
                       for k, v in _ORGANISMS.iteritems()
                       if term in k.lower()])


@_APP.route('/cancel/<job_id>')
def cancel(job_id):
    '''Cancels job.'''
    _THREADS[job_id].cancel()
    return 'Cancelled: ' + job_id


def _get_response(job_id):
    '''Returns current progress for job id.'''
    return json.dumps(_STATUS[job_id])


class Listener(object):
    '''Simple event listener.'''

    def event_fired(self, event):
        '''Responds to event being fired.'''
        _STATUS[event['job_id']] = event


if __name__ == '__main__':
    _APP.run(threaded=True)
{'fraction_non_alphanumeric': 0.15235065394132202, 'fraction_numerical': 0.008660303994344292, 'mean_word_length': 3.530824659727782, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5955187', 'n_tokens_mistral': 1974, 'n_tokens_neox': 1861, 'n_words': 450}