from app import db, hashids from app.models import Job, JobInput, JobStatus from flask import ( abort, current_app, flash, make_response, render_template, request, url_for ) from flask_login import current_user, login_required from werkzeug.utils import secure_filename from . import bp from . import SERVICES from .forms import AddJobForms import json @bp.route('/corpus-analysis') @login_required def corpus_analysis(): return render_template( 'services/corpus_analysis.html.j2', title='Corpus analysis' ) @bp.route('/', methods=['GET', 'POST']) @login_required def service(service): # Check if the requested service exist if service not in SERVICES or service not in AddJobForms: abort(404) version = request.args.get('version', SERVICES[service]['latest_version']) if version not in SERVICES[service]['versions']: abort(404) form = AddJobForms[service](prefix='add-job-form', version=version) title = SERVICES[service]['name'] if form.is_submitted(): if not form.validate(): return make_response(form.errors, 400) service_args = {} if service == 'spacy-nlp': service_args['model'] = form.model.data if form.encoding_detection.data: service_args['encoding_detection'] = True if service == 'tesseract-ocr': service_args['model'] = hashids.decode(form.model.data) if form.binarization.data: service_args['binarization'] = True job = Job( user=current_user, description=form.description.data, service=service, service_args=json.dumps(service_args), service_version=form.version.data, title=form.title.data ) db.session.add(job) db.session.flush(objects=[job]) db.session.refresh(job) try: job.makedirs() except OSError as e: current_app.logger.error(e) db.session.rollback() flash('Internal Server Error', 'error') return make_response({'redirect_url': url_for('.service', service=service)}, 500) # noqa for file in form.files.data: filename = secure_filename(file.filename) job_input = JobInput( filename=filename, job=job, mimetype=file.mimetype ) db.session.add(job_input) db.session.flush(objects=[job_input]) db.session.refresh(job_input) try: file.save(job_input.path) except OSError as e: current_app.logger.error(e) db.session.rollback() flash('Internal Server Error', 'error') return make_response({'redirect_url': url_for('.service', service=service)}, 500) # noqa job.status = JobStatus.SUBMITTED db.session.commit() flash(f'Job "{job.title}" added', 'job') return make_response({'redirect_url': url_for('jobs.job', job_id=job.id)}, 201) # noqa return render_template( f'services/{service.replace("-", "_")}.html.j2', form=form, title=title )