"""Floor direction response formatting: API payloads and metadata dicts.""" import base64 import cv2 import numpy as np from errors import server_error def encode_png_data_url(image_bgr: np.ndarray) -> str: ok, encoded = cv2.imencode(".png", image_bgr) if not ok: server_error("Could not encode overlay image.") payload = base64.b64encode(encoded.tobytes()).decode("ascii") return f"data:image/png;base64,{payload}" def floor_direction_response(result, segmentation) -> dict: overlay_image_base64 = None if result.overlay_bgr is not None: overlay_image_base64 = encode_png_data_url(result.overlay_bgr) return { "angle_degrees": result.angle_degrees, "render_angle_degrees": result.render_angle_degrees, "secondary_angle_degrees": result.secondary_angle_degrees, "direction_label": result.direction_label, "confidence": result.confidence, "segmentation": { "label": segmentation.label, "confidence": segmentation.confidence, "polygon_count": len(segmentation.polygons), "floor_area_ratio": result.floor_area_ratio, "source_path": segmentation.source_path, "raw_keys": segmentation.raw_keys or [], }, "line_count": result.line_count, "dominant_line_count": result.dominant_line_count, "grid_pattern_detected": result.grid_pattern_detected, "dominant_lines": [ { "x1": line.x1, "y1": line.y1, "x2": line.x2, "y2": line.y2, "angle_degrees": line.angle_degrees, "length": line.length, } for line in result.dominant_lines ], "warnings": result.warnings, "overlay_image_base64": overlay_image_base64, } def floor_direction_metadata(result, segmentation) -> dict: return { "source": "backend-floor-direction", "angleDegrees": result.angle_degrees, "renderAngleDegrees": result.render_angle_degrees, "secondaryAngleDegrees": result.secondary_angle_degrees, "directionLabel": result.direction_label, "confidence": result.confidence, "floorAreaRatio": result.floor_area_ratio, "lineCount": result.line_count, "dominantLineCount": result.dominant_line_count, "gridPatternDetected": result.grid_pattern_detected, "warnings": result.warnings, "dominantLines": [ { "x1": line.x1, "y1": line.y1, "x2": line.x2, "y2": line.y2, "angleDegrees": line.angle_degrees, "length": line.length, } for line in result.dominant_lines ], "segmentation": { "label": segmentation.label, "confidence": segmentation.confidence, "polygonCount": len(segmentation.polygons), "sourcePath": segmentation.source_path, }, }