bettersight-statement-extra.../app/main.py

118 lines
4.7 KiB
Python

import os, uuid
from flask import Flask, request, jsonify, send_file, render_template
from werkzeug.utils import secure_filename
import pipeline
import excel_export
def create_app():
app = Flask(__name__, template_folder="../templates")
app.config["UPLOAD_FOLDER"] = os.environ.get("UPLOAD_FOLDER", "/app/uploads")
app.config["OUTPUT_FOLDER"] = os.environ.get("OUTPUT_FOLDER", "/app/outputs")
app.config["DOCLING_URL"] = os.environ.get("DOCLING_URL", "http://localhost:5001")
app.config["MAX_CONTENT_LENGTH"] = 50 * 1024 * 1024
@app.route("/")
def index():
return render_template("index.html")
@app.route("/api/process", methods=["POST"])
def api_process():
f = request.files.get("statement_file")
if not f or not f.filename:
return jsonify({"error": "Upload a statement PDF"}), 400
def _opt_float(name):
v = request.form.get(name, "").strip()
return float(v) if v else None
opening_balance = _opt_float("opening_balance")
closing_balance = _opt_float("closing_balance")
path = os.path.join(app.config["UPLOAD_FOLDER"], f"{uuid.uuid4()}_{secure_filename(f.filename)}")
f.save(path)
try:
result = pipeline.run(path, app.config["DOCLING_URL"], opening_balance, closing_balance)
except ValueError as e:
return jsonify({"error": str(e)}), 400
except Exception as e:
return jsonify({"error": f"Could not parse {f.filename}: {e}"}), 400
finally:
os.remove(path)
fname = f"Statement_Extraction_{uuid.uuid4().hex[:8]}.xlsx"
fpath = os.path.join(app.config["OUTPUT_FOLDER"], fname)
excel_export.write_output_workbook(result, fpath, title=f.filename)
return jsonify({**result, "filename": fname, "title": f.filename}), 200
@app.route("/api/download/<filename>")
def api_download(filename):
safe = secure_filename(filename)
fpath = os.path.join(app.config["OUTPUT_FOLDER"], safe)
if not os.path.exists(fpath):
return jsonify({"error": "File not found"}), 404
return send_file(fpath, as_attachment=True)
def _opt_float_json(data, name):
v = data.get(name)
if v in (None, ""):
return None
return float(v)
@app.route("/api/recheck", methods=["POST"])
def api_recheck():
"""
Re-runs the six checks against a (possibly user-edited) transaction
list without re-extracting anything - used for live status/flag
updates in the UI right after an edit. See pipeline.recheck().
"""
data = request.get_json(silent=True) or {}
check_results = pipeline.recheck(
data.get("transactions", []), data.get("page_reports", []), data.get("period"),
_opt_float_json(data, "opening_balance"), _opt_float_json(data, "closing_balance"),
narrative_direction=data.get("narrative_direction"),
)
return jsonify(check_results), 200
@app.route("/api/export", methods=["POST"])
def api_export():
"""
Re-runs the six checks against the (possibly edited) transaction
list, same as /api/recheck, then writes and returns the Excel
workbook in one round trip - so a downloaded file always reflects
whatever is currently on screen, edits included, rather than the
original extraction from before any correction.
"""
data = request.get_json(silent=True) or {}
transactions = data.get("transactions", [])
page_reports = data.get("page_reports", [])
check_results = pipeline.recheck(
transactions, page_reports, data.get("period"),
_opt_float_json(data, "opening_balance"), _opt_float_json(data, "closing_balance"),
narrative_direction=data.get("narrative_direction"),
)
result = {
"transactions": transactions,
"page_reports": page_reports,
"period": data.get("period"),
"brought_forward_balance": data.get("brought_forward_balance"),
**check_results,
}
fname = f"Statement_Extraction_{uuid.uuid4().hex[:8]}.xlsx"
fpath = os.path.join(app.config["OUTPUT_FOLDER"], fname)
excel_export.write_output_workbook(result, fpath, title=data.get("title") or "Statement Extraction")
return send_file(fpath, as_attachment=True, download_name=fname)
return app
app = create_app()
if __name__ == "__main__":
os.makedirs(app.config["UPLOAD_FOLDER"], exist_ok=True)
os.makedirs(app.config["OUTPUT_FOLDER"], exist_ok=True)
port = int(os.environ.get("PORT", 8080))
app.run(host="0.0.0.0", port=port, debug=False, threaded=True)