Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -361,100 +361,6 @@ def detect_paper_bounds(image: np.ndarray, paper_size: str, output_unit: str = "
|
|
| 361 |
logger.error(f"Error in paper detection: {e}")
|
| 362 |
raise ReferenceBoxNotDetectedError(f"Failed to detect paper: {str(e)}")
|
| 363 |
|
| 364 |
-
# def detect_paper_bounds(image: np.ndarray, paper_size: str) -> Tuple[np.ndarray, float]:
|
| 365 |
-
# """
|
| 366 |
-
# Detect paper bounds in the image and calculate scaling factor
|
| 367 |
-
# """
|
| 368 |
-
# try:
|
| 369 |
-
# paper_detector = get_paper_detector()
|
| 370 |
-
|
| 371 |
-
# if paper_detector is not None:
|
| 372 |
-
# # Use trained model if available
|
| 373 |
-
# # FIXED: Add verbose=False to suppress prints, and use proper confidence threshold
|
| 374 |
-
# results = paper_detector.predict(image, conf=0.8, verbose=False) # Lower confidence threshold
|
| 375 |
-
|
| 376 |
-
# if not results or len(results) == 0:
|
| 377 |
-
# logger.warning("No results from paper detector")
|
| 378 |
-
# return detect_paper_contour(image)
|
| 379 |
-
|
| 380 |
-
# # Check if boxes exist and are not empty
|
| 381 |
-
# if not hasattr(results[0], 'boxes') or results[0].boxes is None or len(results[0].boxes) == 0:
|
| 382 |
-
# logger.warning("No boxes detected by model, using fallback contour detection")
|
| 383 |
-
# return detect_paper_contour(image)
|
| 384 |
-
|
| 385 |
-
# # Get the largest detected paper
|
| 386 |
-
# boxes = results[0].boxes.xyxy.cpu().numpy() # Convert to numpy
|
| 387 |
-
# if len(boxes) == 0:
|
| 388 |
-
# logger.warning("Empty boxes detected, using fallback")
|
| 389 |
-
# return detect_paper_contour(image)
|
| 390 |
-
|
| 391 |
-
# largest_box = None
|
| 392 |
-
# max_area = 0
|
| 393 |
-
|
| 394 |
-
# for box in boxes:
|
| 395 |
-
# x_min, y_min, x_max, y_max = box
|
| 396 |
-
# area = (x_max - x_min) * (y_max - y_min)
|
| 397 |
-
# if area > max_area:
|
| 398 |
-
# max_area = area
|
| 399 |
-
# largest_box = box
|
| 400 |
-
|
| 401 |
-
# if largest_box is None:
|
| 402 |
-
# logger.warning("No valid paper box found, using fallback")
|
| 403 |
-
# return detect_paper_contour(image)
|
| 404 |
-
|
| 405 |
-
# # Convert box to contour-like format
|
| 406 |
-
# x_min, y_min, x_max, y_max = map(int, largest_box)
|
| 407 |
-
# paper_contour = np.array([
|
| 408 |
-
# [[x_min, y_min]],
|
| 409 |
-
# [[x_max, y_min]],
|
| 410 |
-
# [[x_max, y_max]],
|
| 411 |
-
# [[x_min, y_max]]
|
| 412 |
-
# ])
|
| 413 |
-
|
| 414 |
-
# logger.info(f"Paper detected by model: {x_min},{y_min} to {x_max},{y_max}")
|
| 415 |
-
|
| 416 |
-
# else:
|
| 417 |
-
# # Use fallback contour detection
|
| 418 |
-
# logger.info("Using fallback contour detection for paper")
|
| 419 |
-
# paper_contour, _ = detect_paper_contour(image)
|
| 420 |
-
|
| 421 |
-
# # Calculate scaling factor based on paper size
|
| 422 |
-
# scaling_factor = calculate_paper_scaling_factor(paper_contour, paper_size)
|
| 423 |
-
|
| 424 |
-
# return paper_contour, scaling_factor
|
| 425 |
-
|
| 426 |
-
# except Exception as e:
|
| 427 |
-
# logger.error(f"Error in paper detection: {e}")
|
| 428 |
-
# # Instead of raising PaperNotDetectedError, raise ReferenceBoxNotDetectedError
|
| 429 |
-
# raise ReferenceBoxNotDetectedError(f"Failed to detect paper: {str(e)}")
|
| 430 |
-
|
| 431 |
-
# def calculate_paper_scaling_factor(paper_contour: np.ndarray, paper_size: str) -> float:
|
| 432 |
-
# """
|
| 433 |
-
# Calculate scaling factor based on detected paper dimensions
|
| 434 |
-
# """
|
| 435 |
-
# # Get paper dimensions
|
| 436 |
-
# paper_dims = PAPER_SIZES[paper_size]
|
| 437 |
-
# expected_width_mm = paper_dims["width"]
|
| 438 |
-
# expected_height_mm = paper_dims["height"]
|
| 439 |
-
|
| 440 |
-
# # Calculate bounding rectangle of paper contour
|
| 441 |
-
# rect = cv2.boundingRect(paper_contour)
|
| 442 |
-
# detected_width_px = rect[2]
|
| 443 |
-
# detected_height_px = rect[3]
|
| 444 |
-
|
| 445 |
-
# # Calculate scaling factors for both dimensions
|
| 446 |
-
# scale_x = expected_width_mm / detected_width_px
|
| 447 |
-
# scale_y = expected_height_mm / detected_height_px
|
| 448 |
-
|
| 449 |
-
# # Use average of both scales
|
| 450 |
-
# # scaling_factor = (scale_x + scale_y) / 2
|
| 451 |
-
# scaling_factor = min(scale_x, scale_y)
|
| 452 |
-
|
| 453 |
-
# logger.info(f"Paper detection: {detected_width_px}x{detected_height_px} px -> {expected_width_mm}x{expected_height_mm} mm")
|
| 454 |
-
# logger.info(f"Calculated scaling factor: {scaling_factor:.4f} mm/px")
|
| 455 |
-
|
| 456 |
-
# return scaling_factor
|
| 457 |
-
|
| 458 |
def calculate_paper_scaling_factor(paper_contour: np.ndarray, paper_size: str, output_unit: str = "mm") -> float:
|
| 459 |
"""
|
| 460 |
Calculate scaling factor based on detected paper dimensions with proper unit handling.
|
|
@@ -671,55 +577,6 @@ def resample_contour(contour, edge_radius_px: int = 0):
|
|
| 671 |
logger.error(f"Error in resample_contour: {e}")
|
| 672 |
raise
|
| 673 |
|
| 674 |
-
# def save_dxf_spline(inflated_contours, scaling_factor, height, finger_clearance=False):
|
| 675 |
-
# """Save contours as DXF splines with optional finger cuts"""
|
| 676 |
-
# doc = ezdxf.new(units=ezdxf.units.MM)
|
| 677 |
-
# doc.header["$INSUNITS"] = ezdxf.units.MM
|
| 678 |
-
# msp = doc.modelspace()
|
| 679 |
-
# final_polygons_inch = []
|
| 680 |
-
# finger_centers = []
|
| 681 |
-
# original_polygons = []
|
| 682 |
-
|
| 683 |
-
# # Scale correction factor
|
| 684 |
-
# scale_correction = 1.0
|
| 685 |
-
|
| 686 |
-
# for contour in inflated_contours:
|
| 687 |
-
# try:
|
| 688 |
-
# resampled_contour = resample_contour(contour)
|
| 689 |
-
|
| 690 |
-
# points_inch = [(x * scaling_factor, (height - y) * scaling_factor)
|
| 691 |
-
# for x, y in resampled_contour]
|
| 692 |
-
|
| 693 |
-
# if len(points_inch) < 3:
|
| 694 |
-
# continue
|
| 695 |
-
|
| 696 |
-
# tool_polygon = build_tool_polygon(points_inch)
|
| 697 |
-
# original_polygons.append(tool_polygon)
|
| 698 |
-
|
| 699 |
-
# if finger_clearance:
|
| 700 |
-
# try:
|
| 701 |
-
# tool_polygon, center = place_finger_cut_adjusted(
|
| 702 |
-
# tool_polygon, points_inch, finger_centers, final_polygons_inch
|
| 703 |
-
# )
|
| 704 |
-
# except FingerCutOverlapError:
|
| 705 |
-
# tool_polygon = original_polygons[-1]
|
| 706 |
-
|
| 707 |
-
# exterior_coords = polygon_to_exterior_coords(tool_polygon)
|
| 708 |
-
# if len(exterior_coords) < 3:
|
| 709 |
-
# continue
|
| 710 |
-
|
| 711 |
-
# # Apply scale correction
|
| 712 |
-
# corrected_coords = [(x * scale_correction, y * scale_correction) for x, y in exterior_coords]
|
| 713 |
-
|
| 714 |
-
# msp.add_spline(corrected_coords, degree=3, dxfattribs={"layer": "TOOLS"})
|
| 715 |
-
# final_polygons_inch.append(tool_polygon)
|
| 716 |
-
|
| 717 |
-
# except ValueError as e:
|
| 718 |
-
# logger.warning(f"Skipping contour: {e}")
|
| 719 |
-
|
| 720 |
-
# dxf_filepath = os.path.join("./outputs", "out.dxf")
|
| 721 |
-
# doc.saveas(dxf_filepath)
|
| 722 |
-
# return dxf_filepath, final_polygons_inch, original_polygons
|
| 723 |
|
| 724 |
def save_dxf_spline(inflated_contours, scaling_factor, height, finger_clearance=False):
|
| 725 |
"""Save contours as DXF splines with optional finger cuts - scaling_factor should be in mm/px"""
|
|
@@ -1105,7 +962,7 @@ def predict_with_paper(image, paper_size, offset, offset_unit, finger_clearance=
|
|
| 1105 |
orig_size = image.shape[:2]
|
| 1106 |
# objects_mask = remove_bg(image)
|
| 1107 |
# objects_mask = remove_bg(image)
|
| 1108 |
-
objects_mask =
|
| 1109 |
processed_size = objects_mask.shape[:2]
|
| 1110 |
|
| 1111 |
# Resize mask to match original image
|
|
|
|
| 361 |
logger.error(f"Error in paper detection: {e}")
|
| 362 |
raise ReferenceBoxNotDetectedError(f"Failed to detect paper: {str(e)}")
|
| 363 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 364 |
def calculate_paper_scaling_factor(paper_contour: np.ndarray, paper_size: str, output_unit: str = "mm") -> float:
|
| 365 |
"""
|
| 366 |
Calculate scaling factor based on detected paper dimensions with proper unit handling.
|
|
|
|
| 577 |
logger.error(f"Error in resample_contour: {e}")
|
| 578 |
raise
|
| 579 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 580 |
|
| 581 |
def save_dxf_spline(inflated_contours, scaling_factor, height, finger_clearance=False):
|
| 582 |
"""Save contours as DXF splines with optional finger cuts - scaling_factor should be in mm/px"""
|
|
|
|
| 962 |
orig_size = image.shape[:2]
|
| 963 |
# objects_mask = remove_bg(image)
|
| 964 |
# objects_mask = remove_bg(image)
|
| 965 |
+
objects_mask = remove_bg(image)
|
| 966 |
processed_size = objects_mask.shape[:2]
|
| 967 |
|
| 968 |
# Resize mask to match original image
|