Spaces:
Running
Running
Upload folder using huggingface_hub
Browse filesFiles changed (4)
25 unmodified lines26272829303132775 unmodified lines808809810811812813348 unmodified lines11621163116411651166116725 unmodified lines)from src.finger_segmentation import segment_hand, isolate_finger, clean_mask, get_finger_contourfrom src.geometry import estimate_finger_axis, localize_ring_zone, localize_ring_zone_from_landmarks, compute_cross_section_widthfrom src.edge_refinement import refine_edges_sobel, should_use_sobel_measurement, compare_edge_methodsfrom src.confidence import (compute_card_confidence,compute_finger_confidence,775 unmodified linesf"std={sobel_measurement['std_width_px']:.2f}px, "f"quality={sobel_measurement['edge_quality']['overall_score']:.3f})")except Exception as e:print(f"Edge refinement failed: {e}")sobel_failed = True348 unmodified linesmask_mode=mask_mode,finger_name=finger_name,)except Exception:sobel_failed = Trueif edge_method in ("sobel", "mask"):25 unmodified lines262728293031323334353637775 unmodified lines813814815816817818819820821822823824825826827828829830831832833834348 unmodified lines1183118411851186118711881189119011911192119311941195119611971198119925 unmodified lines)from src.finger_segmentation import segment_hand, isolate_finger, clean_mask, get_finger_contourfrom src.geometry import estimate_finger_axis, localize_ring_zone, localize_ring_zone_from_landmarks, compute_cross_section_widthfrom src.edge_refinement import (refine_edges_sobel,should_use_sobel_measurement,compare_edge_methods,MIN_MASK_SAMPLES,)from src.confidence import (compute_card_confidence,compute_finger_confidence,775 unmodified linesf"std={sobel_measurement['std_width_px']:.2f}px, "f"quality={sobel_measurement['edge_quality']['overall_score']:.3f})")# Hard-fail mask mode when there aren't enough valid rows to# trust the median. Without this gate a single surviving row# still produces a "valid" measurement.if edge_method == "mask":num_samples = int(sobel_measurement.get("num_samples", 0))if num_samples < MIN_MASK_SAMPLES:print(f"Insufficient valid edge samples: {num_samples} < {MIN_MASK_SAMPLES}")return create_output(card_detected=card_detected,finger_detected=True,scale_px_per_cm=px_per_cm,view_angle_ok=view_angle_ok,fail_reason=f"insufficient_edge_samples_{num_samples}",edge_method_used="mask",)except Exception as e:print(f"Edge refinement failed: {e}")sobel_failed = True348 unmodified linesmask_mode=mask_mode,finger_name=finger_name,)# Hard-fail mask mode when too few valid rows survived all the# invalidation gates.if edge_method == "mask":num_samples = int(sobel_measurement.get("num_samples", 0))if num_samples < MIN_MASK_SAMPLES:return create_output(card_detected=card_detected, finger_detected=True,scale_px_per_cm=px_per_cm, view_angle_ok=view_angle_ok,fail_reason=f"insufficient_edge_samples_{num_samples}",edge_method_used="mask",)except Exception:sobel_failed = Trueif edge_method in ("sobel", "mask"):
51 unmodified lines525354555657995 unmodified lines105310541055105610571058105951 unmodified lines# Configure logginglogger = logging.getLogger(__name__)# =============================================================================# Helper Functions (extracted from nested scope)995 unmodified lines# otherwise reasonable width usually indicates the per-finger mask# bled into an adjacent finger and width validation killed most# rows — contour is safer in that situation.MIN_MASK_SAMPLES = 20 # parity with the contour path's 20 samplesnum_samples = int(sobel_result.get("num_samples", 0))if num_samples < MIN_MASK_SAMPLES:return False, f"mask_samples_low_{num_samples}"51 unmodified lines52535455565758596061626364995 unmodified lines10601061106210631064106551 unmodified lines# Configure logginglogger = logging.getLogger(__name__)# Minimum valid cross-sections required for a trustworthy mask-based width# measurement. Below this the median is too sensitive to individual row# errors (webbing leakage, axis drift, finger tilt), so callers should fail# the measurement rather than report a potentially-wrong number. 20 keeps# parity with the contour path's 20-sample target.MIN_MASK_SAMPLES = 20# =============================================================================# Helper Functions (extracted from nested scope)995 unmodified lines# otherwise reasonable width usually indicates the per-finger mask# bled into an adjacent finger and width validation killed most# rows — contour is safer in that situation.num_samples = int(sobel_result.get("num_samples", 0))if num_samples < MIN_MASK_SAMPLES:return False, f"mask_samples_low_{num_samples}"
8 unmodified lines910111213141516171819202120 unmodified lines424344454647211 unmodified lines25926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829954 unmodified lines3543553563573583593603613623633643653663671 unmodified line3693703713723733743753763773783793803813823833843853863873883893901 unmodified line3923933943953963973983994008 unmodified linesimport csvimport ioimport jsonimport osimport reimport sysimport uuidfrom datetime import datetimefrom pathlib import Pathfrom typing import Dict, Any, Tupleimport cv2import numpy as np20 unmodified linesapp = Flask(__name__)def _allowed_file(filename: str) -> bool:return Path(filename).suffix.lower() in ALLOWED_EXTENSIONS211 unmodified linesresult_json_path = RESULTS_DIR / result_json_name_save_json(result_json_path, result)# --- Persist to Supabase ---photo_public_url = Noneresult_public_url = Noneif upload_path and upload_path.exists():photo_public_url = upload_file(str(upload_path), f"photos/{upload_name}")if result_png_path.exists():result_public_url = upload_file(str(result_png_path), f"results/{result_png_name}")ring_size = result.get("ring_size", {})measurement_id = save_measurement({"run_id": run_id,"kol_name": kol_name,"mode": "single","ring_model": ring_model,"finger_index": finger_index,"diameter_cm": result.get("finger_outer_diameter_cm"),"confidence": result.get("confidence"),"overall_best_size": ring_size.get("best_match"),"overall_range_min": ring_size.get("range_min"),"overall_range_max": ring_size.get("range_max"),"photo_url": photo_public_url,"result_url": result_public_url,"result_json": result,"fail_reason": result.get("fail_reason"),})payload = {"success": result.get("fail_reason") is None,"result": result,"result_image_url": f"/results/{result_png_name}","input_image_url": input_image_url,"result_json_url": f"/results/{result_json_name}","measurement_id": measurement_id,}return jsonify(payload)54 unmodified linesresult_json_path = RESULTS_DIR / result_json_name_save_json(result_json_path, result)# --- Persist to Supabase ---photo_public_url = Noneresult_public_url = Noneif upload_path and upload_path.exists():photo_public_url = upload_file(str(upload_path), f"photos/{upload_name}")if result_png_path.exists():result_public_url = upload_file(str(result_png_path), f"results/{result_png_name}")# Compute overall confidence from per-finger dataconfidences = [pf.get("confidence") for pf in per_finger.values()1 unmodified line]overall_confidence = min(confidences) if confidences else Nonemeasurement_id = save_measurement({"run_id": run_id,"kol_name": kol_name,"mode": "multi","ring_model": ring_model,"overall_best_size": result.get("overall_best_size"),"overall_range_min": result.get("overall_range_min"),"overall_range_max": result.get("overall_range_max"),"per_finger": per_finger,"confidence": overall_confidence,"photo_url": photo_public_url,"result_url": result_public_url,"result_json": result,"fail_reason": result.get("fail_reason"),})payload = {"success": result.get("fail_reason") is None,"mode": "multi",1 unmodified line"result_image_url": f"/results/{result_png_name}","input_image_url": input_image_url,"result_json_url": f"/results/{result_json_name}","measurement_id": measurement_id,}return jsonify(payload)8 unmodified lines9101112131415161718192021222320 unmodified lines44454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889211 unmodified lines30130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733854 unmodified lines3933943953963973981 unmodified line4004014024034044051 unmodified line4074084094104114124134144154164174184194204214224234244254264274284294304314324334344358 unmodified linesimport csvimport ioimport jsonimport loggingimport osimport reimport sysimport uuidfrom concurrent.futures import ThreadPoolExecutorfrom datetime import datetimefrom pathlib import Pathfrom typing import Any, Dict, Optional, Tupleimport cv2import numpy as np20 unmodified linesapp = Flask(__name__)logger = logging.getLogger(__name__)# Persist to Supabase off the request thread: two storage uploads + a row# insert add multi-second latency that the user would otherwise stare at# after the measurement is already done. max_workers=2 is plenty — each# request queues one task, and we don't need ordering._persist_executor = ThreadPoolExecutor(max_workers=2, thread_name_prefix="supa-persist")def _persist_measurement_async(*,upload_path: Optional[Path],upload_name: str,result_png_path: Path,result_png_name: str,record: Dict[str, Any],) -> None:"""Upload the photo + result PNG to Supabase Storage and insert themeasurement row. Designed to run in a worker thread — takes no requeststate and logs (rather than raises) on failure so a broken Supabaseconnection never poisons the measurement the user just saw."""def _task() -> None:try:photo_url = Noneresult_url = Noneif upload_path and upload_path.exists():photo_url = upload_file(str(upload_path), f"photos/{upload_name}")if result_png_path.exists():result_url = upload_file(str(result_png_path), f"results/{result_png_name}")record_with_urls = dict(record)record_with_urls["photo_url"] = photo_urlrecord_with_urls["result_url"] = result_urlsave_measurement(record_with_urls)except Exception as exc: # noqa: BLE001logger.exception("Supabase persist failed for run %s: %s",record.get("run_id"), exc)_persist_executor.submit(_task)def _allowed_file(filename: str) -> bool:return Path(filename).suffix.lower() in ALLOWED_EXTENSIONS211 unmodified linesresult_json_path = RESULTS_DIR / result_json_name_save_json(result_json_path, result)payload = {"success": result.get("fail_reason") is None,"result": result,"result_image_url": f"/results/{result_png_name}","input_image_url": input_image_url,"result_json_url": f"/results/{result_json_name}",}# Persist to Supabase in the background — do not block the response on# storage uploads or DB inserts.ring_size = result.get("ring_size", {})_persist_measurement_async(upload_path=upload_path,upload_name=upload_name,result_png_path=result_png_path,result_png_name=result_png_name,record={"run_id": run_id,"kol_name": kol_name,"mode": "single","ring_model": ring_model,"finger_index": finger_index,"diameter_cm": result.get("finger_outer_diameter_cm"),"confidence": result.get("confidence"),"overall_best_size": ring_size.get("best_match"),"overall_range_min": ring_size.get("range_min"),"overall_range_max": ring_size.get("range_max"),"result_json": result,"fail_reason": result.get("fail_reason"),},)return jsonify(payload)54 unmodified linesresult_json_path = RESULTS_DIR / result_json_name_save_json(result_json_path, result)# Compute overall confidence from per-finger dataconfidences = [pf.get("confidence") for pf in per_finger.values()1 unmodified line]overall_confidence = min(confidences) if confidences else Nonepayload = {"success": result.get("fail_reason") is None,"mode": "multi",1 unmodified line"result_image_url": f"/results/{result_png_name}","input_image_url": input_image_url,"result_json_url": f"/results/{result_json_name}",}# Persist to Supabase in the background._persist_measurement_async(upload_path=upload_path,upload_name=upload_name,result_png_path=result_png_path,result_png_name=result_png_name,record={"run_id": run_id,"kol_name": kol_name,"mode": "multi","ring_model": ring_model,"overall_best_size": result.get("overall_best_size"),"overall_range_min": result.get("overall_range_min"),"overall_range_max": result.get("overall_range_max"),"per_finger": per_finger,"confidence": overall_confidence,"result_json": result,"fail_reason": result.get("fail_reason"),},)return jsonify(payload)
25 unmodified lines2627282930313225 unmodified lines<span class="file-hint">JPG / PNG supported · 1080p or higher recommended</span></label><ul class="capture-tips"><li><strong>Turn on your phone's flash</strong>, it helps sharpen the finger edges.</li><li><strong>Use plain white background</strong>, a sheet of paper works great.</li><li><strong>Spread your fingers naturally</strong>, place the card beside your hand.</li>25 unmodified lines2627282930313225 unmodified lines<span class="file-hint">JPG / PNG supported · 1080p or higher recommended</span></label><ul class="capture-tips" hidden><li><strong>Turn on your phone's flash</strong>, it helps sharpen the finger edges.</li><li><strong>Use plain white background</strong>, a sheet of paper works great.</li><li><strong>Spread your fingers naturally</strong>, place the card beside your hand.</li>
measure_finger.py+33-1
src/edge_refinement.py+7-1
web_demo/app.py+88-53
web_demo/templates/index.html+1-1