#!/usr/bin/env python from flask import Flask, redirect, request, render_template, send_from_directory import json import os from os.path import join import uuid from . import db, config, scanner, calibration app = Flask(__name__) @app.route("/") def hello_world(): conn = db.get() objects = db.Object.all(conn) return render_template('index.html', objects=objects) @app.route("/create-object/", methods=["POST"]) def create_object(): conn = db.get() with conn: object = db.Object.create(request.form.get('name'), conn) os.makedirs(join(config.DATA_DIR, str(object.id), 'previews')) return redirect('/') @app.route('/object/') def object(id: int): conn = db.get() object = db.Object.get_from_id(id, conn) calibration = object.calibration(conn) return render_template('object.html', object=object, calibration=calibration) @app.route("/calibrate/") def calibrate(id: int): conn = db.get() object = db.Object.get_from_id(id, conn) if object.calibration_id is None: with conn: calibration = db.Calibration.create(conn) object.calibration_id = calibration.id object.save(conn) else: calibration = object.calibration(conn) return render_template('calibrate.html', object=object, calibration=calibration, leds=config.LEDS_UUIDS) @app.route("/api/preview/") def preview(id: int): conn = db.get() db.Object.get_from_id(id, conn) capture_uuid = uuid.uuid4() if scanner.capture(join(config.DATA_DIR, str(id), 'previews', str(capture_uuid) + '.jpg')): return str(capture_uuid) else: return "Impossible de capturer l'image.", 500 @app.route("/api/scan-for-calibration/") def scan_calibration(id: int): conn = db.get() calibration = db.Calibration.get_from_id(id, conn) def generate(): length = len(config.LEDS_UUIDS) for index, led_uuid in enumerate(scanner.scan(join(config.CALIBRATION_DIR, id))): yield f"{led_uuid},{(index+1)/length}\n" with conn: calibration.state = db.CalibrationState.HasData calibration.save(conn) return app.response_class(generate(), mimetype='text/plain') @app.route("/api/calibrate/") def run_calibration(id: int): conn = db.get() db.Calibration.get_from_id(id, conn) calibration_json = calibration.calibrate(join(config.CALIBRATION_DIR, str(id))) with open(join(config.CALIBRATION_DIR, str(id), 'calibration.json'), 'w') as f: json.dump(calibration_json, f, indent=4) return 'ok' @app.route("/calibration/") def calibration_page(id: int): conn = db.get() calibration = db.Calibration.get_from_id(id, conn) return render_template('calibration.html', calibration=calibration) @app.route('/static/') def send_static(path): return send_from_directory('static', path) @app.route('/data/') def send_data(path): return send_from_directory('data', path)