<commit_before>#!/usr/bin/python

"""forna_server.py: A server for converting RNA secondary structures to force-directed graphs
   and doing something more."""

                                                                                                         
__author__      = "<NAME>"
__copyright__   = "Copyright 2014"
__version__     = "0.1"
__maintainer__  = "<NAME>"
__email__       = "<EMAIL>"  

from flask import Flask, request, abort

import forna
import json
import re
import sys
import os
import RNA
from optparse import OptionParser

import forgi.utilities.debug as fud

def create_app(static):
    '''
    Create the forna application given the options that were passed.

    '''
    app = Flask(__name__, static_folder='htdocs')

    @app.errorhandler(400)
    # pylint: disable=W0612
    def custom405(error):
        return error.description, 400

    @app.route('/struct_graph', methods=['POST'])
    # pylint: disable=W0612
    def struct_graph():
        print >>sys.stderr, "request.json:", request.json
        #print >>sys.stderr, "dir(request)", dir(request)
        if not request.json:
           abort(400, "Missing a json in the request")

        fud.pv('request.json')
        
        if 'seq' not in request.json and 'struct' not in request.json:
            abort(400, "Missing seq and struct in the json file")

        if re.match("^[ACGTUWSMKRYBDHV]+$", request.json['seq']) is None:
            abort(400, "Invalid sequence: {}".format(request.json['seq']))

        if re.match("^[\(\)\.\[\]\{\}]+[\*]?$", request.json['struct']) is None:
            abort(400, "Invalid structure: {}".format(request.json['struct']))

        print >>sys.stderr, "struct[-1]:", request.json['struct'][-1]
        if request.json['struct'][-1] == '*':
            circular = True
            structure = request.json['struct'].strip('*')
        else:
            circular = False
            structure = request.json['struct']

        fasta_text = ">{}\n{}\n{}".format(request.json['header'], request.json['seq'],
                                               structure)

        print >>sys.stderr, "hcirc:", circular
        try:
            result = forna.fasta_to_json(fasta_text, circular)
        except Exception as ex:
            abort(400, "Secondary structure parsing error: {}".format(str(ex)))

        return json.dumps(result), 201
    
    @app.route('/mfe_struct', methods=['POST'])
    # pylint: disable=W0612
    def mfe_struct():
        if not request.json:
            abort(400, "Request has no json.")
            
        if 'seq' not in request.json:
            abort(400, "Request has no sequence in the json.")

        if re.match("^[ACGTUWSMKRYBDHV]+$", request.json['seq']) is None:
            abort(400, "Invalid sequence: {}".format(request.json['seq']))


        result = RNA.fold(str(request.json['seq']))[0]
        return json.dumps(result), 201

    @app.route('/colors_to_json', methods=['POST'])
    def colors_to_json():
        if not request.json:
            abort(400, "Request has no json.")

        if 'text' not in request.json:
            abort(400, "Request has no text field.")

        color_json = forna.parse_colors_text(request.json['text'])
        return json.dumps(color_json)
    
    
    if static:<commit_msg>No more cryptic error messages<commit_after>#!/usr/bin/python

"""forna_server.py: A server for converting RNA secondary structures to force-directed graphs
   and doing something more."""

                                                                                                         
__author__      = "<NAME>"
__copyright__   = "Copyright 2014"
__version__     = "0.1"
__maintainer__  = "<NAME>"
__email__       = "<EMAIL>"  

from flask import Flask, request, abort

import forna
import json
import re
import sys
import os
import RNA
from optparse import OptionParser

import forgi.utilities.debug as fud

def create_app(static):
    '''
    Create the forna application given the options that were passed.

    '''
    app = Flask(__name__, static_folder='htdocs')

    @app.errorhandler(400)
    # pylint: disable=W0612
    def custom405(error):
        return error.description, 400

    @app.route('/struct_graph', methods=['POST'])
    # pylint: disable=W0612
    def struct_graph():
        print >>sys.stderr, "request.json:", request.json
        #print >>sys.stderr, "dir(request)", dir(request)
        if not request.json:
           abort(400, "Missing a json in the request")

        fud.pv('request.json')
        
        if 'seq' not in request.json and 'struct' not in request.json:
            abort(400, "Missing seq and struct in the json file")

        if re.match("^[ACGTUWSMKRYBDHV]+$", request.json['seq']) is None:
            abort(400, "Invalid sequence: {}".format(request.json['seq']))

        if re.match("^[\(\)\.\[\]\{\}]+[\*]?$", request.json['struct']) is None:
            abort(400, "Invalid structure: {}".format(request.json['struct']))

        print >>sys.stderr, "struct[-1]:", request.json['struct'][-1]
        if request.json['struct'][-1] == '*':
            circular = True
            structure = request.json['struct'].strip('*')
        else:
            circular = False
            structure = request.json['struct']

        fasta_text = ">{}\n{}\n{}".format(request.json['header'], request.json['seq'],
                                               structure)

        print >>sys.stderr, "hcirc:", circular
        try:
            result = forna.fasta_to_json(fasta_text, circular)
        except Exception as ex:
            abort(400, "Secondary structure parsing error: {}".format(str(ex)))

        return json.dumps(result), 201
    
    @app.route('/mfe_struct', methods=['POST'])
    # pylint: disable=W0612
    def mfe_struct():
        if not request.json:
            abort(400, "Request has no json.")
            
        if 'seq' not in request.json:
            abort(400, "Request has no sequence in the json.")

        if re.match("^[ACGTUWSMKRYBDHV]+$", request.json['seq']) is None:
            abort(400, "Invalid sequence: {}".format(request.json['seq']))


        result = RNA.fold(str(request.json['seq']))[0]
        return json.dumps(result), 201

    @app.route('/colors_to_json', methods=['POST'])
    def colors_to_json():
        if not request.json:
            abort(400, "Request has no json.")

        if 'text' not in request.json:
            abort(400, "Request has no text field.")

        try:
            color_json = forna.parse_colors_text(request.json['text'])
        except Exception as ex:
            abort(400, "Custom color error: {}".format(str(ex)))

        return json.dumps(color_json)
    
    
    if static:
{'fraction_non_alphanumeric': 0.14186184405573674, 'fraction_numerical': 0.02030833086273347, 'mean_word_length': 2.21132793907663, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 27, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 12, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5851620', 'n_tokens_mistral': 2071, 'n_tokens_neox': 1920, 'n_words': 509}