<commit_before>"""
RESTful interface to interacting with OCR plugins.
"""
import os
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import render_to_response

from ocradmin.ocrtasks.models import OcrTask
from nodetree.manager import ModuleManager 
from ocradmin.core.decorators import saves_files

import logging
logger = logging.getLogger(__name__)

import simplejson

import tasks

import numpy

manager = ModuleManager()
manager.register_module("ocradmin.plugins.ocropus_nodes")
manager.register_module("ocradmin.plugins.tesseract_nodes")
manager.register_module("ocradmin.plugins.cuneiform_nodes")
manager.register_module("ocradmin.plugins.abbyy_nodes")
manager.register_module("ocradmin.plugins.numpy_nodes")
manager.register_module("ocradmin.plugins.pil_nodes")

def query(request):
    """
    Query plugin info.  This returns a list
    of available OCR engines and an URL that
    can be queries when one of them is selected.
    """
    stages=request.GET.getlist("stage")
    return HttpResponse(
            manager.get_json(*stages), mimetype="application/json")

@saves_files
def runscript(request):
    """
    Execute a script (sent as JSON).
    """
    evalnode = request.POST.get("node", "")
    jsondata = request.POST.get("script")
    nodes = simplejson.loads(jsondata)
    

    from nodetree import script, node

    try:
        pl = script.Script(nodes, manager=manager)
        term = pl.get_node(evalnode)
        if term is None:
            term = pl.get_terminals()[0]
        result = term.validate()
    except node.ValidationError, err:
        return HttpResponse(simplejson.dumps(dict(
            status="VALIDATION",
            node=err.node.label,
            error=err.msg,
        )), mimetype="application/json")

    async = OcrTask.run_celery_task("run.script", evalnode, nodes,
            request.output_path, untracked=True,
            asyncronous=True, queue="interactive")
    out = dict(
        node=evalnode,
        task_id=async.task_id,
        status=async.status,
        results=async.result
    )
    return HttpResponse(simplejson.dumps(out), mimetype="application/json")


def results(request, task_ids):
    """
    Fetch the results of several Celery task ids.
    """
    results = []
    for task_id in task_ids.split(","):<commit_msg>Handle case when the script has no nodes<commit_after>"""
RESTful interface to interacting with OCR plugins.
"""
import os
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import render_to_response

from ocradmin.ocrtasks.models import OcrTask
from nodetree.manager import ModuleManager 
from ocradmin.core.decorators import saves_files

import logging
logger = logging.getLogger(__name__)

import simplejson

import tasks

import numpy

manager = ModuleManager()
manager.register_module("ocradmin.plugins.ocropus_nodes")
manager.register_module("ocradmin.plugins.tesseract_nodes")
manager.register_module("ocradmin.plugins.cuneiform_nodes")
manager.register_module("ocradmin.plugins.abbyy_nodes")
manager.register_module("ocradmin.plugins.numpy_nodes")
manager.register_module("ocradmin.plugins.pil_nodes")

def query(request):
    """
    Query plugin info.  This returns a list
    of available OCR engines and an URL that
    can be queries when one of them is selected.
    """
    stages=request.GET.getlist("stage")
    return HttpResponse(
            manager.get_json(*stages), mimetype="application/json")

@saves_files
def runscript(request):
    """
    Execute a script (sent as JSON).
    """
    evalnode = request.POST.get("node", "")
    jsondata = request.POST.get("script")
    nodes = simplejson.loads(jsondata)
    

    from nodetree import script, node

    try:
        pl = script.Script(nodes, manager=manager)
        term = pl.get_node(evalnode)
        if term is None:
            terms = pl.get_terminals()
            if not terms:
                return HttpResponse(simplejson.dumps(dict(
                    status="NOSCRIPT",
                )), mimetype="application/json")
            term = terms[0]                
        result = term.validate()
    except node.ValidationError, err:
        return HttpResponse(simplejson.dumps(dict(
            status="VALIDATION",
            node=err.node.label,
            error=err.msg,
        )), mimetype="application/json")

    async = OcrTask.run_celery_task("run.script", evalnode, nodes,
            request.output_path, untracked=True,
            asyncronous=True, queue="interactive")
    out = dict(
        node=evalnode,
        task_id=async.task_id,
        status=async.status,
        results=async.result
    )
    return HttpResponse(simplejson.dumps(out), mimetype="application/json")


def results(request, task_ids):
    """
    Fetch the results of several Celery task ids.
    """
    results = []
    for task_id in task_ids.split(","):
{'fraction_non_alphanumeric': 0.10223123732251521, 'fraction_numerical': 0.0016227180527383367, 'mean_word_length': 3.261884183232498, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, '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': '782044', 'n_tokens_mistral': 1449, 'n_tokens_neox': 1421, 'n_words': 329}