118 lines
2.8 KiB
Python
118 lines
2.8 KiB
Python
from flask import Flask, request, jsonify
|
|
from flask_cors import CORS
|
|
import traceback
|
|
|
|
from cad_vector_area import calculate_pdf_vector_area
|
|
|
|
app = Flask(__name__)
|
|
CORS(app)
|
|
|
|
|
|
@app.route("/health", methods=["GET"])
|
|
def health():
|
|
return jsonify({
|
|
"success": True,
|
|
"message": "Python CAD Area service is running"
|
|
})
|
|
|
|
|
|
def get_float_or_none(name):
|
|
value = request.form.get(name, "").strip()
|
|
|
|
if value == "":
|
|
return None
|
|
|
|
try:
|
|
return float(value)
|
|
except ValueError:
|
|
return None
|
|
|
|
|
|
def get_int_or_default(name, default=1):
|
|
value = request.form.get(name, "").strip()
|
|
|
|
if value == "":
|
|
return default
|
|
|
|
try:
|
|
return int(value)
|
|
except ValueError:
|
|
return default
|
|
|
|
|
|
@app.route("/calculate", methods=["POST"])
|
|
def calculate():
|
|
try:
|
|
if "file" not in request.files:
|
|
return jsonify({
|
|
"success": False,
|
|
"message": "No PDF file received"
|
|
}), 400
|
|
|
|
uploaded_file = request.files["file"]
|
|
|
|
if uploaded_file.filename == "":
|
|
return jsonify({
|
|
"success": False,
|
|
"message": "Empty filename"
|
|
}), 400
|
|
|
|
if not uploaded_file.filename.lower().endswith(".pdf"):
|
|
return jsonify({
|
|
"success": False,
|
|
"message": "Only PDF files are allowed"
|
|
}), 400
|
|
|
|
pdf_bytes = uploaded_file.read()
|
|
|
|
scale_ratio = get_float_or_none("scale_ratio")
|
|
|
|
if scale_ratio is not None and scale_ratio <= 0:
|
|
scale_ratio = None
|
|
|
|
roi = {
|
|
"x": get_float_or_none("roi_x"),
|
|
"y": get_float_or_none("roi_y"),
|
|
"width": get_float_or_none("roi_width"),
|
|
"height": get_float_or_none("roi_height"),
|
|
"page": get_int_or_default("roi_page", 1)
|
|
}
|
|
|
|
has_roi = (
|
|
roi["x"] is not None and
|
|
roi["y"] is not None and
|
|
roi["width"] is not None and
|
|
roi["height"] is not None and
|
|
roi["width"] > 0 and
|
|
roi["height"] > 0
|
|
)
|
|
|
|
mode = request.form.get("mode", "auto_roi")
|
|
|
|
result = calculate_pdf_vector_area(
|
|
pdf_bytes=pdf_bytes,
|
|
filename=uploaded_file.filename,
|
|
scale_ratio=scale_ratio,
|
|
profile_color=None,
|
|
roi=roi if has_roi else None,
|
|
mode=mode
|
|
)
|
|
|
|
status_code = 200 if result.get("success") else 422
|
|
|
|
return jsonify(result), status_code
|
|
|
|
except Exception as e:
|
|
return jsonify({
|
|
"success": False,
|
|
"message": str(e),
|
|
"trace": traceback.format_exc()
|
|
}), 500
|
|
|
|
|
|
if __name__ == "__main__":
|
|
app.run(
|
|
host="127.0.0.1",
|
|
port=5055,
|
|
debug=True
|
|
) |