nopaque/app/services/views.py
2019-09-24 16:55:24 +02:00

64 lines
2.4 KiB
Python

from flask import abort, current_app, flash, redirect, render_template, url_for
from . import services
from flask_login import current_user, login_required
from .forms import NewOCRJobForm, NewNLPJobForm
from ..models import Job
from .. import db
import json
import os
SERVICE_REQUIREMENTS = {'nlp': {'mem_mb': 4096, 'n_cores': 2},
'ocr': {'mem_mb': 8192, 'n_cores': 4}}
@services.route('/<service_handle>', methods=['GET', 'POST'])
@login_required
def service(service_handle):
if service_handle not in ['nlp', 'ocr']:
abort(404)
elif service_handle == 'nlp':
page_title = 'Natural Language Processing'
new_job_form = NewNLPJobForm()
elif service_handle == 'ocr':
page_title = 'Optical Character Recognition'
new_job_form = NewOCRJobForm()
if new_job_form.validate_on_submit():
_service_args = ['-l {}'.format(new_job_form.language.data)]
if service_handle == 'ocr':
if not new_job_form.binarization.data:
_service_args.append('--skip-binarisation')
job = Job(
creator=current_user,
description=new_job_form.description.data,
mem_mb=SERVICE_REQUIREMENTS[service_handle]['mem_mb'],
n_cores=SERVICE_REQUIREMENTS[service_handle]['n_cores'],
service=service_handle,
service_args=json.dumps(_service_args),
service_version=new_job_form.version.data,
status='preparing',
title=new_job_form.title.data
)
db.session.add(job)
db.session.commit()
dir = os.path.join(current_app.config['OPAQUE_STORAGE_DIRECTORY'],
str(job.user_id),
'jobs',
str(job.id))
try:
os.makedirs(dir)
except OSError:
flash('OSError!')
db.session.remove(job)
db.session.commit()
else:
for file in new_job_form.files.data:
file.save(os.path.join(dir, file.filename))
job.status = 'submitted'
db.session.commit()
flash('Job created!')
return redirect(url_for('services.{}'.format(service_handle)))
return render_template('services/{}.html.j2'.format(service_handle),
title=page_title,
new_job_form=new_job_form)