Spaces:
Running
Running
Upload folder using huggingface_hub
Browse filesFiles changed (12)
- AGENTS.md+21
- CLAUDE.md+21
- README.md+6-1
- web_demo/app.py+135-14
- web_demo/static/app.js+97
- web_demo/static/mobile/mobile.css+69
- web_demo/static/mobile/steps/result.js+88
- web_demo/static/shared/feedback.jsAdded+28
- web_demo/static/styles.css+73
- web_demo/supabase_client.py+36-1
- web_demo/templates/admin.html+103-44
- web_demo/templates/index.html+22
194 unmodified lines195196197198199200201202203204205206207208209210211212213214215216217218219220221194 unmodified lines
`/api/measure` is the single contract both surfaces speak. Any algorithm change in `measure_finger.py` improves both surfaces with zero front-end work. See `doc/v5/` for the in-browser capture coach (distance + level gates) and `doc/v6/` for the mobile flow.
### Post-result feedback (rating + comment)
After a successful run both surfaces show a "How did it go?" panel (5-star rating + optional comment). `POST /api/feedback` attaches them to the existing `measurements` row via `run_id` β there is no separate `feedback` table. Two columns on `measurements`:
| Column | Type | Notes ||---|---|---|| `feedback_rating` | `int` (1β5, NULL allowed) | API validates the range; no DB constraint. || `feedback_message` | `text` (NULL allowed) | Server caps length at `FEEDBACK_MAX_MESSAGE_LEN = 4000`. |
The endpoint only patches columns the user actually provided (partial submissions don't NULL the other column), retries 6 Γ 500 ms to absorb the race with the async measurement insert, and returns a real `404` if the row truly isn't there after the retries.
The admin dashboard surfaces this as an **Avg rating** stat card, a **User Ratings** 1β
β5β
distribution chart, and per-row **Rating** + **Comment** columns in the records table. `_compute_stats` filters feedback aggregation by `not fail_reason` so any pre-existing ratings on failed runs don't skew `avg_rating`.
The columns were added to the live DB via the Supabase Management API (the repo has no migrations dir); equivalent SQL:
```sqlalter table public.measurements add column if not exists feedback_rating int, add column if not exists feedback_message text;```
---
## Important Technical Details194 unmodified lines195196197198199200201202203204205206207208209210211212213214215216217218219220221194 unmodified lines
`/api/measure` is the single contract both surfaces speak. Any algorithm change in `measure_finger.py` improves both surfaces with zero front-end work. See `doc/v5/` for the in-browser capture coach (distance + level gates) and `doc/v6/` for the mobile flow.
### Post-result feedback (rating + comment)
After a successful run both surfaces show a "How did it go?" panel (5-star rating + optional comment). `POST /api/feedback` attaches them to the existing `measurements` row via `run_id` β there is no separate `feedback` table. Two columns on `measurements`:
| Column | Type | Notes ||---|---|---|| `feedback_rating` | `int` (1β5, NULL allowed) | API validates the range; no DB constraint. || `feedback_message` | `text` (NULL allowed) | Server caps length at `FEEDBACK_MAX_MESSAGE_LEN = 4000`. |
The endpoint only patches columns the user actually provided (partial submissions don't NULL the other column), retries 6 Γ 500 ms to absorb the race with the async measurement insert, and returns a real `404` if the row truly isn't there after the retries.
The admin dashboard surfaces this as an **Avg rating** stat card, a **User Ratings** 1β
β5β
distribution chart, and per-row **Rating** + **Comment** columns in the records table. `_compute_stats` filters feedback aggregation by `not fail_reason` so any pre-existing ratings on failed runs don't skew `avg_rating`.
The columns were added to the live DB via the Supabase Management API (the repo has no migrations dir); equivalent SQL:
```sqlalter table public.measurements add column if not exists feedback_rating int, add column if not exists feedback_message text;```
---
## Important Technical Details25 unmodified lines262728293031323334118 unmodified lines15315415515315615715815916016125 unmodified lines- **Ring size recommendation** maps calibrated diameter to sizes 6β13 (best match + 2-size range). Supports multiple ring models: **Gen1/Gen2** and **Air**, each with its own size chart.- **Multi-finger mode** measures index, middle, and ring fingers in one pass; consensus aggregation maximizes the chance at least one finger fits.- **Optional AI explanation** (OpenAI) generates a human-readable rationale for the recommendation (size selection is always deterministic).- **In-browser capture coach** (v5) opens the camera in-page and gates the shutter on live distance / level / brightness checks, eliminating bad-photo round trips.- **Mobile-native flow** (v6) at `/m` paginates the demo into six steps (intro β form β guide β capture β confirm β result); `/` auto-routes mobile UAs there.- **Post-result feedback** β successful runs get a 5-star rating + optional comment panel; data is attached to the measurement row and surfaced on the `/admin` dashboard (avg rating, rating distribution, per-row Rating and Comment columns).- Writes JSON output and always writes a result PNG next to it.
## Accuracy118 unmodified lines| [`doc/v1/`](doc/v1/) | v1 PRD, Plan, Progress (Sobel edge refinement; `auto`/`compare` modes later removed) || [`doc/v2/`](doc/v2/) | v2 Plan, Progress (calibration & regression) || [`doc/v3/`](doc/v3/) | v3 Progress (multi-finger, quality checks, AI explanation) || [`doc/v4/`](doc/v4/) | v4 PRD, Plan, Progress (SAM 2.1 card + hand segmentation β **current architecture**) || [`doc/v4/`](doc/v4/) | v4 PRD, Plan, Progress (SAM 2.1 card + hand segmentation) || [`doc/v5/`](doc/v5/) | v5 PRD, Plan, Progress (in-browser capture coach: live distance/level/brightness gates) || [`doc/v6/`](doc/v6/) | v6 PRD, Plan, Progress (mobile-native paginated flow at `/m` β **current surface**) || [`doc/report/`](doc/report/) | Validation, calibration & ring size mapping reports || [`doc/algorithms/`](doc/algorithms/) | Algorithm documentation || [`script/`](script/) | Batch measurement & analysis scripts |15 unmodified lines1617181920212213 unmodified lines36373839404142434445315 unmodified lines36136236336436536636795 unmodified lines46346446546646746846920 unmodified lines49049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256382 unmodified lines6466476486496506516525 unmodified lines65865966066166266366466566666758766866967014 unmodified lines68568668768868969069169269369461261369569669769869934 unmodified lines73473573665465573773873974074174274374474574674774874975075175225 unmodified lines77877978068778178278378423 unmodified lines8088098107178118128138143 unmodified lines81881982072772882182282382482582682782882983083183283383421 unmodified lines8568578588598608618628638648658668678688698708718728738748758768778788798808818 unmodified lines8908918928938948958968978988997819009019029032 unmodified lines90690790879079179290991091191291391479691591691791891992015 unmodified linesimport uuidfrom collections import Counter, defaultdictfrom concurrent.futures import ThreadPoolExecutorimport timefrom datetime import date, datetime, timedelta, timezonefrom pathlib import Pathfrom typing import Any, Dict, List, Optional, Tuple13 unmodified linesfrom web_demo.supabase_client import ( upload_file, save_measurement, update_measurement_feedback, FEEDBACK_OK, FEEDBACK_NO_ROW, FEEDBACK_DISABLED, list_measurements, list_measurements_for_stats, update_ground_truth,315 unmodified lines "result_image_url": f"/results/{result_png_name}", "input_image_url": input_image_url, "result_json_url": f"/results/{result_json_name}", "run_id": run_id, }
# Persist to Supabase in the background β do not block the response on95 unmodified lines "result_image_url": f"/results/{result_png_name}", "input_image_url": input_image_url, "result_json_url": f"/results/{result_json_name}", "run_id": run_id, }
# Persist to Supabase in the background.20 unmodified lines return jsonify(payload)
FEEDBACK_MAX_MESSAGE_LEN = 4000# The measurement row is persisted asynchronously (storage uploads + insert# take ~1β5 s on a healthy connection), so a fast-finger user can submit# feedback before the row exists. Retry briefly to absorb that race before# returning an error.FEEDBACK_RETRY_ATTEMPTS = 6FEEDBACK_RETRY_DELAY_S = 0.5
@app.route("/api/feedback", methods=["POST"])def api_feedback(): data = request.get_json(silent=True) or request.form run_id = (data.get("run_id") or "").strip() if not run_id: return jsonify({"success": False, "error": "run_id is required"}), 400
rating_raw = data.get("rating") rating: Optional[int] = None if rating_raw not in (None, ""): # Reject booleans (True/False are int subclasses in Python) and # floats (a malicious or buggy client sending 4.9 would otherwise # round-trip as 4 after int()). Accept int and str shapes only. if isinstance(rating_raw, bool) or isinstance(rating_raw, float): return jsonify({"success": False, "error": "rating must be an integer 1β5"}), 400 try: rating = int(rating_raw) except (TypeError, ValueError): return jsonify({"success": False, "error": "rating must be an integer 1β5"}), 400 if rating < 1 or rating > 5: return jsonify({"success": False, "error": "rating must be between 1 and 5"}), 400
message = (data.get("message") or "").strip()[:FEEDBACK_MAX_MESSAGE_LEN] or None
if rating is None and not message: return jsonify({"success": False, "error": "Provide a rating or a message"}), 400
# Only patch the columns the user actually provided β sending # {feedback_rating: rating, feedback_message: message} unconditionally # would NULL out the other column on a follow-up partial submission. updates: Dict[str, Any] = {} if rating is not None: updates["feedback_rating"] = rating if message is not None: updates["feedback_message"] = message
status = update_measurement_feedback(run_id, updates) if status == FEEDBACK_NO_ROW: # Race with the async measurement insert: row may not exist yet. # Bounded retry; if still missing afterwards, surface a real error. for _ in range(FEEDBACK_RETRY_ATTEMPTS - 1): time.sleep(FEEDBACK_RETRY_DELAY_S) status = update_measurement_feedback(run_id, updates) if status != FEEDBACK_NO_ROW: break
if status == FEEDBACK_OK or status == FEEDBACK_DISABLED: # DISABLED means RING_DISABLE_SUPABASE is set (local dev) β treat # as success since the user-facing action did what it could. return jsonify({"success": True})
if status == FEEDBACK_NO_ROW: logger.warning("Feedback not attached: no row for run %s", run_id) return jsonify({"success": False, "error": "Measurement not found"}), 404
# FEEDBACK_ERROR β Supabase raised; supabase_client already logged it. return jsonify({"success": False, "error": "Could not save feedback, please retry"}), 500
# ---------------------------------------------------------------------------# Admin routes# ---------------------------------------------------------------------------82 unmodified lines per_day_fails: Counter = Counter()
kol_counts: Counter = Counter() kol_counts_window: Counter = Counter() kol_last_seen: Dict[str, str] = {} kol_display: Dict[str, str] = {} fail_counter: Counter = Counter()5 unmodified lines confidence_sum = 0.0 confidence_n = 0
rating_buckets: Counter = Counter() rating_sum = 0.0 rating_n = 0 comment_count = 0
success_count = 0 fail_count = 0 gt_filled_count = 0
last_7_count = 0 prev_7_count = 014 unmodified lines d = _parse_iso_to_utc_date(created_at)
kkey = _kol_key(row.get("kol_name")) in_window = d is not None and window_start <= d <= today if kkey: kol_counts[kkey] += 1 if kkey not in kol_display: kol_display[kkey] = (row.get("kol_name") or "").strip() if in_window: kol_counts_window[kkey] += 1 if created_at and (kkey not in kol_last_seen or created_at > kol_last_seen[kkey]): kol_last_seen[kkey] = created_at if created_at and (kkey not in kol_last_seen or created_at > kol_last_seen[kkey]): kol_last_seen[kkey] = created_at
fail_reason = row.get("fail_reason") if fail_reason:34 unmodified lines else: confidence_buckets["LOW"] += 1
if any(row.get(k) not in (None, "") for k in ("gt_index_size", "gt_middle_size", "gt_ring_size")): gt_filled_count += 1 # Only count feedback on successful runs β feedback attached to a # failed measurement reflects "the tool didn't work for me," not a # rating of the measurement itself, so including it would poison # avg_rating. Going forward the UI also hides the panel on failure, # but this filter cleans up any pre-existing rows from when it didn't. if not fail_reason: rating = row.get("feedback_rating") if isinstance(rating, int) and 1 <= rating <= 5: rating_sum += rating rating_n += 1 rating_buckets[rating] += 1 if (row.get("feedback_message") or "").strip(): comment_count += 1
if d is not None: if window_start <= d <= today:25 unmodified lines "count": c, "last_at": kol_last_seen.get(k), } for k, c in kol_counts.most_common(10) for k, c in kol_counts_window.most_common(10) ]
fail_reasons = [23 unmodified lines total = len(rows) success_rate = (success_count / total) if total else 0.0 avg_confidence = (confidence_sum / confidence_n) if confidence_n else 0.0 gt_rate = (gt_filled_count / total) if total else 0.0 avg_rating = (rating_sum / rating_n) if rating_n else 0.0
return { "totals": {3 unmodified lines "fail_count": fail_count, "success_rate": round(success_rate, 4), "avg_confidence": round(avg_confidence, 4), "gt_filled_count": gt_filled_count, "gt_filled_rate": round(gt_rate, 4), "avg_rating": round(avg_rating, 2), "rating_count": rating_n, "comment_count": comment_count, "last_7_days": last_7_count, "prev_7_days": prev_7_count, "first_measurement_at": first_at, "last_measurement_at": last_at, }, "rating_distribution": [ {"stars": str(n), "count": rating_buckets.get(n, 0)} for n in (1, 2, 3, 4, 5) ], "window_days": days, "per_day": per_day_series, "top_kols": top_kols,21 unmodified lines return jsonify(_compute_stats(rows, days=days))
_CSV_INJECTION_LEAD = ("=", "+", "-", "@", "\t", "\r")
def _csv_safe(value: Any) -> str: """Defang CSV-injection vectors in user-supplied cell values.
Excel / Google Sheets treat a leading `=`, `+`, `-`, or `@` as a formula trigger. Prefixing a single quote turns the cell into plain text without changing how it displays once the user removes the quote, so the data round-trips back to whatever shape the user expected. """ if value is None: return "" s = str(value) if s and s[0] in _CSV_INJECTION_LEAD: return "'" + s return s
@app.route("/api/admin/export-csv")def api_admin_export_csv(): if not _check_admin_token():8 unmodified lines "ring_size", "ring_diameter", "ring_confidence", "confidence", "fail_reason", "ai_explanation", "ring_fit", "gt_best_finger", "gt_index_size", "gt_middle_size", "gt_ring_size", "gt_notes", "feedback_rating", "feedback_message", "photo_url", "result_url", "id", ] writer = csv.DictWriter(output, fieldnames=fieldnames, extrasaction="ignore") writer.writeheader() for row in rows: flat = { "kol_name": row.get("kol_name", ""), "kol_name": _csv_safe(row.get("kol_name", "")), "created_at": row.get("created_at", ""), "mode": row.get("mode", ""), "ring_model": row.get("ring_model", ""),2 unmodified lines "overall_range_max": row.get("overall_range_max", ""), "confidence": row.get("confidence", ""), "fail_reason": row.get("fail_reason", ""), "ai_explanation": (row.get("result_json") or {}).get("ai_explanation", ""), "ring_fit": row.get("ring_fit", ""), "gt_best_finger": row.get("gt_best_finger", ""), "ai_explanation": _csv_safe((row.get("result_json") or {}).get("ai_explanation", "")), "ring_fit": _csv_safe(row.get("ring_fit", "")), "gt_best_finger": _csv_safe(row.get("gt_best_finger", "")), "gt_index_size": row.get("gt_index_size", ""), "gt_middle_size": row.get("gt_middle_size", ""), "gt_ring_size": row.get("gt_ring_size", ""), "gt_notes": row.get("gt_notes", ""), "gt_notes": _csv_safe(row.get("gt_notes", "")), "feedback_rating": row.get("feedback_rating", ""), "feedback_message": _csv_safe(row.get("feedback_message", "")), "photo_url": row.get("photo_url", ""), "result_url": row.get("result_url", ""), "id": row.get("id", ""),11 unmodified lines121314151617181920212223242526206 unmodified lines2332342352362372382392402412422432442459 unmodified lines25525625725825926026126226326426526626726826975 unmodified lines34534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942011 unmodified linesconst multiResultPanel = document.getElementById("multiResultPanel");const overallSize = document.getElementById("overallSize");const fingerBreakdown = document.getElementById("fingerBreakdown");const feedbackSection = document.getElementById("feedbackSection");const feedbackForm = document.getElementById("feedbackForm");const feedbackMessage = document.getElementById("feedbackMessage");const feedbackStatus = document.getElementById("feedbackStatus");const feedbackSubmit = feedbackForm ? feedbackForm.querySelector(".feedback-submit") : null;const feedbackStarButtons = feedbackForm ? Array.from(feedbackForm.querySelectorAll(".star-btn")) : [];const defaultSampleUrl = window.DEFAULT_SAMPLE_URL || "";let lastRunId = "";let feedbackRating = 0;const failReasonMessageMap = { card_not_detected: "Card not detected. A card of standard credit card dimensions (85.6 Γ 54 mm) is required as a scale reference to measure your finger diameter. Place the card beside your hand on a plain white background (e.g. a sheet of paper), and turn on your phone's flash.",206 unmodified lines renderElapsed(); jsonOutput.textContent = '{\n "status": "processing"\n}'; fingerBreakdown.innerHTML = ""; // Clear feedback state at the top so every code path β HTTP error, // network error, fail_reason result β starts from a hidden panel and // an empty run_id. Otherwise a successful run that's followed by an // HTTP / network error would leave the panel visible with the prior // run_id, and any feedback would attach to the wrong row. lastRunId = ""; if (feedbackSection) feedbackSection.hidden = true; const timerId = setInterval(renderElapsed, 1000);
try {9 unmodified lines }
const data = await response.json(); lastRunId = data.run_id || ""; if (feedbackSection) { if (data.success && lastRunId) { feedbackSection.hidden = false; resetFeedbackForm(); } else { feedbackSection.hidden = true; } } jsonOutput.textContent = JSON.stringify(data.result, null, 2); jsonLink.href = data.result_json_url || "#";
75 unmodified lines showImage(inputPreview, inputFrame, defaultSampleUrl); setStatus("Sample image loaded. Click Start Measurement or upload your own photo.");}
function paintStars() { feedbackStarButtons.forEach((btn) => { const v = Number(btn.dataset.value); const filled = v <= feedbackRating; btn.classList.toggle("star-filled", filled); btn.setAttribute("aria-checked", v === feedbackRating ? "true" : "false"); });}
function resetFeedbackForm() { feedbackRating = 0; feedbackMessage.value = ""; feedbackStatus.textContent = ""; feedbackStatus.className = "feedback-status"; paintStars();}
if (feedbackForm) { feedbackStarButtons.forEach((btn) => { btn.addEventListener("click", () => { // Set-only (no toggle-to-clear) β the previous "click same star // to clear" behavior was undiscoverable and made it easy to wipe // a rating with a stray double-tap. Users can change the rating // by clicking a different star. feedbackRating = Number(btn.dataset.value); paintStars(); }); });
feedbackForm.addEventListener("submit", async (event) => { event.preventDefault(); const message = (feedbackMessage.value || "").trim(); if (!feedbackRating && !message) { feedbackStatus.textContent = "Pick a rating or write a comment."; feedbackStatus.className = "feedback-status feedback-status-error"; return; } if (!lastRunId) { feedbackStatus.textContent = "No measurement to attach this to yet."; feedbackStatus.className = "feedback-status feedback-status-error"; return; } feedbackSubmit.disabled = true; feedbackStatus.textContent = "Sendingβ¦"; feedbackStatus.className = "feedback-status"; try { const resp = await fetch("/api/feedback", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ run_id: lastRunId, rating: feedbackRating || undefined, message, }), }); if (!resp.ok) { const err = await resp.json().catch(() => ({})); throw new Error(err.error || `HTTP ${resp.status}`); } feedbackStatus.textContent = "Thanks β sent."; feedbackStatus.className = "feedback-status feedback-status-ok"; feedbackMessage.value = ""; feedbackRating = 0; paintStars(); } catch (err) { feedbackStatus.textContent = `Couldn't send: ${err.message}`; feedbackStatus.className = "feedback-status feedback-status-error"; } finally { feedbackSubmit.disabled = false; } });}823 unmodified lines824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895823 unmodified lines.size-ref-table tbody tr:nth-child(even) { background: rgba(245, 241, 231, 0.5);}
/* --- Feedback panel (mirrors desktop .feedback-*) ---------------- */
.feedback-panel .feedback-hint { margin: 0 0 12px; color: var(--ink-soft); font-size: 0.95rem;}
.feedback-form { display: flex; flex-direction: column; gap: 10px;}
.feedback-rating { display: flex; gap: 6px;}
.star-btn { background: none; border: none; padding: 4px 6px; font-size: 2rem; line-height: 1; color: rgba(45, 33, 33, 0.25); cursor: pointer; transition: color 0.15s ease, transform 0.1s ease;}
.star-btn.star-filled { color: #e3a73b; }
.feedback-form textarea { width: 100%; border: 1px solid var(--border); border-radius: 12px; padding: 10px 12px; /* 1rem keeps iOS Safari from auto-zooming the page on focus (same reason the .controls inputs use 1rem). */ font-size: 1rem; font-family: inherit; background: white; color: var(--ink); resize: vertical; min-height: 80px;}
.feedback-row { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; flex-direction: row-reverse; justify-content: flex-start;}
.feedback-submit { width: auto; padding: 10px 22px;}
.feedback-status { font-size: 0.9rem; color: var(--ink-soft);}
.feedback-status-ok { color: #2f7a3d; }.feedback-status-error { color: var(--accent); font-weight: 600; }7 unmodified lines891011121314129 unmodified lines1441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731747 unmodified lines1821831841851861871881891 unmodified line1911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552567 unmodified lines
import { session, resetForRetake } from "../session.js";import { formatFailReason } from "../../shared/fail-reasons.js";import { submitFeedback } from "../../shared/feedback.js";
const FINGER_LABEL = { index: "Index Finger",129 unmodified lines ? `<img src="${escape(overlayUrl)}" alt="Measurement overlay" onerror="this.remove()" />` : ""; // Only invite feedback after a successful run β asking "how did it // go?" on top of an error reads as tone-deaf, and ratings attached // to failed rows would skew dashboard stats. const feedbackPanel = succeeded && data.run_id ? ` <div class="panel feedback-panel"> <h2 class="panel-title">How did it go?</h2> <p class="feedback-hint">Rate this measurement and tell us anything you'd like to share or ask.</p> <form class="feedback-form" id="mobileFeedbackForm"> <div class="feedback-rating" role="radiogroup" aria-label="Rating"> ${[1, 2, 3, 4, 5].map((v) => ` <button type="button" class="star-btn" data-value="${v}" role="radio" aria-checked="false" aria-label="${v} star${v > 1 ? "s" : ""}">β
</button> `).join("")} </div> <textarea class="feedback-message" name="message" rows="4" maxlength="4000" placeholder="Your comment or question (optional)"></textarea> <div class="feedback-row"> <button type="submit" class="primary feedback-submit">Send</button> <span class="feedback-status" aria-live="polite"></span> </div> </form> </div> ` : "";
container.innerHTML = ` <section class="step step-result"> <div class="step-body">7 unmodified lines <h2 class="panel-title">Ring Size Recommendation</h2> ${renderRecommendation(payload, ringModel)} </div>
${feedbackPanel} </div> <footer class="step-foot"> <button type="button" class="primary step-retake">Measure Again</button>1 unmodified line </section> `;
const feedbackForm = container.querySelector("#mobileFeedbackForm"); if (feedbackForm) { const messageEl = feedbackForm.querySelector(".feedback-message"); const statusEl = feedbackForm.querySelector(".feedback-status"); const submitEl = feedbackForm.querySelector(".feedback-submit"); const starButtons = Array.from(feedbackForm.querySelectorAll(".star-btn")); let rating = 0; const paintStars = () => { starButtons.forEach((btn) => { const v = Number(btn.dataset.value); const filled = v <= rating; btn.classList.toggle("star-filled", filled); btn.setAttribute("aria-checked", v === rating ? "true" : "false"); }); }; starButtons.forEach((btn) => { btn.addEventListener("click", () => { // Set-only (no toggle-to-clear) β see desktop app.js for // the rationale; the previous behavior made it easy to wipe // a rating with an accidental double-tap. rating = Number(btn.dataset.value); paintStars(); }); });
feedbackForm.addEventListener("submit", async (event) => { event.preventDefault(); const message = (messageEl.value || "").trim(); if (!rating && !message) { statusEl.textContent = "Pick a rating or write a comment."; statusEl.className = "feedback-status feedback-status-error"; return; } if (!data.run_id) { statusEl.textContent = "No measurement to attach this to."; statusEl.className = "feedback-status feedback-status-error"; return; } submitEl.disabled = true; statusEl.textContent = "Sendingβ¦"; statusEl.className = "feedback-status"; const res = await submitFeedback({ runId: data.run_id, rating: rating || undefined, message, }); if (res.success) { statusEl.textContent = "Thanks β sent."; statusEl.className = "feedback-status feedback-status-ok"; messageEl.value = ""; rating = 0; paintStars(); } else { statusEl.textContent = `Couldn't send: ${res.error || "try again"}`; statusEl.className = "feedback-status feedback-status-error"; } submitEl.disabled = false; }); }
// "Measure again" returns to the photo-guide step so the user can // pick between Open Camera and Upload from photos β the upload // entry was added after this button originally jumped straight to12345678910111213141516171819202122232425262728// POST feedback (rating + comment) attached to a specific measurement// run. The endpoint requires a run_id and either a rating or a message// (or both). Returns { success, error? } β the server returns 200 even// when persistence is offline so callers only need to handle network// errors and 4xx validation failures.export async function submitFeedback({ runId, rating, message }) { if (!runId) { return { success: false, error: "Missing run_id" }; } const body = { run_id: runId }; if (rating) body.rating = rating; if (message) body.message = message; const resp = await fetch("/api/feedback", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), }); let data = null; try { data = await resp.json(); } catch { /* ignore parse errors β fall back to status code */ } if (!resp.ok) { return { success: false, error: (data && data.error) || `HTTP ${resp.status}` }; } return { success: true };}324 unmodified lines325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403324 unmodified lines }}
/* Feedback panel β sits inside .content, so it inherits the 8vw horizontal padding from there. No extra padding here, otherwise the panel ends up narrower than its sibling result panels above it. */.feedback-section { position: relative; z-index: 1;}
.feedback-hint { margin: 0 0 12px; color: var(--ink-soft); font-size: 0.95rem;}
.feedback-form { display: flex; flex-direction: column; gap: 10px;}
.feedback-rating { display: flex; gap: 4px;}
.star-btn { background: none; border: none; padding: 2px 4px; font-size: 1.7rem; line-height: 1; color: rgba(45, 33, 33, 0.25); cursor: pointer; transition: color 0.15s ease, transform 0.1s ease;}
.star-btn:hover { transform: translateY(-1px); }.star-btn.star-filled { color: #e3a73b; }
.feedback-form textarea { width: 100%; border: 1px solid var(--border); border-radius: 12px; padding: 10px 12px; font-size: 1rem; font-family: inherit; background: white; color: var(--ink); resize: vertical; min-height: 80px;}
.feedback-row { display: flex; align-items: center; gap: 12px; flex-direction: row-reverse; justify-content: flex-start;}
.feedback-submit { width: auto; padding: 10px 22px;}
.feedback-status { font-size: 0.9rem; color: var(--ink-soft);}
.feedback-status-ok { color: #2f7a3d; }.feedback-status-error { color: var(--accent); font-weight: 600; }
/* Multi-finger result styles */.multi-result { padding: 8px 0;122 unmodified lines12312412512612612712812921 unmodified lines151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191122 unmodified linesSTATS_COLUMNS = ( "id,created_at,kol_name,mode,ring_model,confidence,fail_reason," "overall_best_size,ring_fit,gt_index_size,gt_middle_size,gt_ring_size," "finger_index,photo_url,per_finger" "finger_index,photo_url,per_finger,feedback_rating,feedback_message")
21 unmodified lines return []
FEEDBACK_ALLOWED_FIELDS = {"feedback_rating", "feedback_message"}
# Return values for update_measurement_feedback. Stringly-typed because the# caller (the /api/feedback endpoint) needs to distinguish "persistence is# turned off in this env" (still report success to the user) from "the row# really doesn't exist" (surface a real error).FEEDBACK_OK = "ok"FEEDBACK_NO_ROW = "no_row"FEEDBACK_DISABLED = "disabled"FEEDBACK_ERROR = "error"
def update_measurement_feedback(run_id: str, updates: Dict[str, Any]) -> str: """Attach feedback (rating + message) to an existing measurement row.
Looks up the row by `run_id` (stamped at measure-time by app.py) and patches only the whitelisted feedback columns. Pass only the columns you actually want to change β keys not present are left untouched. Returns one of FEEDBACK_OK / FEEDBACK_NO_ROW / FEEDBACK_DISABLED / FEEDBACK_ERROR so the caller can decide whether to surface a failure. """ client = _get_client() if client is None: return FEEDBACK_DISABLED safe = {k: v for k, v in updates.items() if k in FEEDBACK_ALLOWED_FIELDS} if not safe or not run_id: return FEEDBACK_NO_ROW try: resp = client.table("measurements").update(safe).eq("run_id", run_id).execute() return FEEDBACK_OK if resp.data else FEEDBACK_NO_ROW except Exception as e: logger.error("Failed to update feedback for run %s: %s", run_id, e) return FEEDBACK_ERROR
def delete_measurement(measurement_id: str) -> bool: """Delete a measurement record by ID.""" client = _get_client()75 unmodified lines767778798081828384858687888983 unmodified lines17317417516816917617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621717321821922022141 unmodified lines26326426522122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325426626726826927027127263 unmodified lines3363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773785 unmodified lines38438538635038738838939018 unmodified lines40941041137541241341441570 unmodified lines48648748845248949049149249349449549628 unmodified lines52552652748748848952852953053153253353453553649653753853954067 unmodified lines60860961061161261361461561661761861962062162262362462562662762862963063175 unmodified lines .finger-cell { font-size: 12px; } .finger-cell .size { font-weight: 600; } .finger-cell .detail { color: var(--ink-soft); } .rating-stars { color: #e3a73b; letter-spacing: 1px; font-size: 13px; } .rating-stars .rating-empty { color: rgba(45, 33, 33, 0.18); } .comment-cell { display: inline-block; max-width: 220px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; vertical-align: middle; color: var(--ink-soft); font-size: 12px; cursor: help; } .empty { text-align: center; padding: 48px; color: var(--ink-soft); } .scroll-wrap { overflow-x: auto; } /* --- Tabs --- */83 unmodified lines <div class="admin-content" id="adminContent"> <h1>Ring Sizer β Admin</h1> <div class="tabs"> <button class="tab active" data-pane="dashboardPane">Dashboard</button> <button class="tab" data-pane="recordsPane">Records</button> <button class="tab active" data-pane="recordsPane">Records</button> <button class="tab" data-pane="dashboardPane">Dashboard</button> </div>
<!-- Records pane --> <div class="pane active" id="recordsPane"> <div class="toolbar"> <a href="/">Back to Demo</a> <a id="exportCsvLink" href="#" download>Export CSV</a> <button id="refreshBtn">Refresh</button> <button id="prevPageBtn" disabled>‹ Prev</button> <button id="nextPageBtn" disabled>Next ›</button> <span class="count" id="countLabel">Loading...</span> </div>
<div class="scroll-wrap"> <table> <thead> <tr> <th>KOL</th> <th>Date</th> <th>Model</th> <th>Photo</th> <th>Result</th> <th>Index</th> <th>Middle</th> <th>Ring</th> <th>Conf</th> <th>Fail</th> <th>Rating</th> <th>Comment</th> <th></th> </tr> </thead> <tbody id="tableBody"> <tr><td colspan="13" class="empty">Loading...</td></tr> </tbody> </table> </div> </div>
<!-- Dashboard pane --> <div class="pane active" id="dashboardPane"> <div class="pane" id="dashboardPane"> <div class="toolbar"> <a href="/">Back to Demo</a> <button id="dashRefreshBtn">Refresh</button>41 unmodified lines <h2>Mode (single vs multi)</h2> <div class="chart-wrap"><canvas id="chartModes"></canvas></div> </div> </div> </div>
<!-- Records pane --> <div class="pane" id="recordsPane"> <div class="toolbar"> <a href="/">Back to Demo</a> <a id="exportCsvLink" href="#" download>Export CSV</a> <button id="refreshBtn">Refresh</button> <button id="prevPageBtn" disabled>‹ Prev</button> <button id="nextPageBtn" disabled>Next ›</button> <span class="count" id="countLabel">Loading...</span> </div>
<div class="scroll-wrap"> <table> <thead> <tr> <th>KOL</th> <th>Date</th> <th>Model</th> <th>Photo</th> <th>Index</th> <th>Middle</th> <th>Ring</th> <th>Conf</th> <th>Fail</th> <th></th> </tr> </thead> <tbody id="tableBody"> <tr><td colspan="10" class="empty">Loading...</td></tr> </tbody> </table> <div class="chart-card"> <h2>User Ratings</h2> <div class="chart-wrap"><canvas id="chartRatings"></canvas></div> </div> </div> </div> </div>63 unmodified lines return `<span class="size">${size}</span> <span class="detail">${diam} ${conf}</span>`; };
const esc = (s) => String(s == null ? "" : s) .replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">") .replace(/"/g, """);
const fmtRating = (r) => { if (r == null || r < 1 || r > 5) return '<span class="detail">β</span>'; return `<span class="rating-stars" title="${r}/5">${"β
".repeat(r)}<span class="rating-empty">${"β
".repeat(5 - r)}</span></span>`; };
const fmtComment = (msg) => { if (!msg) return '<span class="detail">β</span>'; const trimmed = String(msg).slice(0, 80); const more = msg.length > 80 ? "β¦" : ""; return `<span class="comment-cell" title="${esc(msg)}">${esc(trimmed)}${more}</span>`; };
const rowHtml = (r) => { const pf = r.per_finger || {}; const photoThumb = r.photo_url ? `<img class="thumb" loading="lazy" src="${r.photo_url}" onclick="window.open('${r.photo_url}')" />` : "-"; const resultThumb = r.result_url ? `<img class="thumb" loading="lazy" src="${r.result_url}" onclick="window.open('${r.result_url}')" />` : "-"; return `<tr data-id="${r.id}"> <td><strong>${r.kol_name || "-"}</strong></td> <td>${fmtDate(r.created_at)}</td> <td>${r.ring_model || "-"}</td> <td>${photoThumb}</td> <td>${resultThumb}</td> <td class="finger-cell">${fmtFinger(pf, "index")}</td> <td class="finger-cell">${fmtFinger(pf, "middle")}</td> <td class="finger-cell">${fmtFinger(pf, "ring")}</td> <td>${r.confidence != null ? (r.confidence * 100).toFixed(0) + "%" : "-"}</td> <td>${r.fail_reason ? '<span class="fail">' + r.fail_reason + "</span>" : ""}</td> <td>${fmtRating(r.feedback_rating)}</td> <td>${fmtComment(r.feedback_message)}</td> <td><button class="del-btn" onclick="deleteRow(this)">Delete</button></td> </tr>`; };5 unmodified lines if (currentPage < 1) currentPage = 1; if (total === 0) { countLabel.textContent = "0 records"; tbody.innerHTML = '<tr><td colspan="10" class="empty">No measurements yet</td></tr>'; tbody.innerHTML = '<tr><td colspan="13" class="empty">No measurements yet</td></tr>'; } else { const start = (currentPage - 1) * PAGE_SIZE; const slice = allRows.slice(start, start + PAGE_SIZE);18 unmodified lines currentPage = 1; renderPage(); } catch (e) { tbody.innerHTML = `<tr><td colspan="10" class="empty">Error loading data: ${e.message}</td></tr>`; tbody.innerHTML = `<tr><td colspan="13" class="empty">Error loading data: ${e.message}</td></tr>`; } };
70 unmodified lines { label: "Last 7 days", value: fmtInt(t.last_7_days), sub: last7Delta.txt, subCls: last7Delta.cls }, { label: "Success rate", value: fmtPct(t.success_rate), sub: `${fmtInt(t.success_count)} ok Β· ${fmtInt(t.fail_count)} failed` }, { label: "Avg confidence", value: fmtPct(t.avg_confidence), sub: "successful runs only" }, { label: "Ground-truth coverage", value: fmtPct(t.gt_filled_rate), sub: `${fmtInt(t.gt_filled_count)} records labeled` }, { label: "Avg rating", value: t.rating_count ? `${t.avg_rating.toFixed(2)} β
` : "β", sub: `${fmtInt(t.rating_count)} rated Β· ${fmtInt(t.comment_count)} comments`, }, ]; statGrid.innerHTML = cards.map((c) => ` <div class="stat-card">28 unmodified lines data: { labels, datasets: [ { label: "Photos", data: s.per_day.map((d) => d.photos), borderColor: ACCENT, backgroundColor: ACCENT + "33", tension: 0.25, fill: true }, { label: "Unique KOLs", data: s.per_day.map((d) => d.unique_kols), borderColor: "#3d6b8b", backgroundColor: "transparent", tension: 0.25 }, { label: "Failures", data: s.per_day.map((d) => d.fails), borderColor: "#a05a3c", backgroundColor: "transparent", borderDash: [4, 4], tension: 0.25 }, { label: "Photos", data: s.per_day.map((d) => d.photos), borderColor: ACCENT, backgroundColor: ACCENT + "33", tension: 0.25, fill: true, pointStyle: "line" }, { label: "Unique KOLs", data: s.per_day.map((d) => d.unique_kols), borderColor: "#3d6b8b", backgroundColor: "transparent", tension: 0.25, pointStyle: "line" }, { label: "Failures", data: s.per_day.map((d) => d.fails), borderColor: "#a05a3c", backgroundColor: "transparent", borderDash: [4, 4], tension: 0.25, pointStyle: "line" }, ], }, options: { responsive: true, maintainAspectRatio: false, interaction: { mode: "index", intersect: false }, scales: { y: { beginAtZero: true, ticks: { precision: 0 } } }, plugins: { legend: { position: "bottom" } }, plugins: { legend: { position: "bottom", labels: { usePointStyle: true } } }, }, });
67 unmodified lines plugins: { legend: { position: "right" } }, }, });
// User ratings β vertical bar, 1β
β 5β
const ratings = s.rating_distribution || []; upsertChart("ratings", document.getElementById("chartRatings"), { type: "bar", data: { labels: ratings.map((d) => `${d.stars}β
`), datasets: [{ data: ratings.map((d) => d.count), backgroundColor: ["#bf3a2b", "#d96b2b", "#d9a83b", "#7a8b3d", "#2f7a3d"], }], }, options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { display: false } }, scales: { y: { beginAtZero: true, ticks: { precision: 0 } } }, }, }); };
const loadStats = async () => {128 unmodified lines129130131132133134135136137138139140141142143144145146147148149150151152153154155156128 unmodified lines <a id="jsonLink" hidden href="#"></a> {% endif %} </section>
<section class="feedback-section" id="feedbackSection" hidden> <div class="panel feedback-panel" id="feedbackPanel"> <h2>How did it go?</h2> <p class="feedback-hint">Rate this measurement and tell us anything you'd like to share or ask.</p> <form id="feedbackForm" class="feedback-form"> <div class="feedback-rating" role="radiogroup" aria-label="Rating"> <button type="button" class="star-btn" data-value="1" role="radio" aria-checked="false" aria-label="1 star">β
</button> <button type="button" class="star-btn" data-value="2" role="radio" aria-checked="false" aria-label="2 stars">β
</button> <button type="button" class="star-btn" data-value="3" role="radio" aria-checked="false" aria-label="3 stars">β
</button> <button type="button" class="star-btn" data-value="4" role="radio" aria-checked="false" aria-label="4 stars">β
</button> <button type="button" class="star-btn" data-value="5" role="radio" aria-checked="false" aria-label="5 stars">β
</button> </div> <textarea id="feedbackMessage" name="message" rows="4" maxlength="4000" placeholder="Your comment or question (optional)"></textarea> <div class="feedback-row"> <button type="submit" class="primary feedback-submit">Send</button> <span class="feedback-status" id="feedbackStatus" aria-live="polite"></span> </div> </form> </div> </section> </main>
<footer style="text-align:center;padding:24px 0 12px;opacity:0.4;font-size:13px;">AGENTS.md+21
CLAUDE.md+21
README.md+6-1
web_demo/app.py+135-14
web_demo/static/app.js+97
web_demo/static/mobile/mobile.css+69
web_demo/static/mobile/steps/result.js+88
web_demo/static/shared/feedback.jsAdded+28
web_demo/static/styles.css+73
web_demo/supabase_client.py+36-1
web_demo/templates/admin.html+103-44
web_demo/templates/index.html+22