1. Overview#
Dermatology Bridge is a clinician-facing longitudinal decision-support tool built on the YouCam Skin AI Server-to-Server (S2S) v2.0 API. During clinic visits, patients capture guided selfies; the platform records immutable 12-concern skin analyses across visits, computes treatment-response flags against the patient's baseline visit, validates AI-generated clinical narratives against raw numeric scores, and exports both a structured 3-page consultation PDF report and a standards-compliant HL7 FHIR R4 `Bundle` of Observation resources.
Clinical Boundary: Every screen, narrative hypothesis, PDF report, and FHIR resource enforces the mandatory clinical notice: "For clinician review — not a diagnosis."
2. The Problem#
Consumer skin analysis tools are designed for single-session product recommendations, creating four critical gaps when applied in a dermatology or aesthetic clinic setting:
- No longitudinal baseline or noise filtering: A 2-point shift in
acneorrednessbetween two selfies is often caused by ambient clinic lighting or slight angle differences rather than true physiological change. Without a Minimal Detectable Change (MDC) threshold and minimum follow-up interval, raw deltas mislead reviewers. - Inconsistent polarity across metrics: In YouCam's 12 skin concerns, rising scores indicate worsening for 8 metrics (such as
acne,wrinkle, andrednesswherelower_is_better), but indicate improvement for 4 metrics (moisture,radiance,firmness, andskin_tonewherehigher_is_better). - LLM numeric hallucination risk: Asking an LLM to summarize longitudinal patient progress risks fabricated percentages or misquoted baseline scores.
- Strict API unit budget and privacy constraints: Each YouCam S2S v2.0 analysis task consumes
len(dst_actions)= 12 API units against a hard 1,000-unit hackathon budget, and returned segmentationmask_urllinks are ephemeral presigned URLs that expire rapidly.
3. The Approach#
Dermatology Bridge is structured as a polyglot monorepo (apps/api in FastAPI + SQLAlchemy 2.0 + Pydantic v2, and apps/web in Next.js 14 App Router + TypeScript) governed by five non-negotiable architectural principles:
- Mock-first budget gate (`ALLOW_LIVE_CALLS=false`): By default, the backend serves deterministic, high-fidelity synthetic fixtures (
fixtures/) so automated tests and UI development consume zero YouCam API units. WhenALLOW_LIVE_CALLS=trueis enabled, every task creation logslen(dst_actions)units tologs/unit_budget.csv. - Frozen Concern Contract (`ANALYSIS_VERSION = 1`): The 12 YouCam
dst_actionsand their clinical polarity (lower_is_bettervs.higher_is_better) are frozen and versioned on everyVisitrow. - Deterministic MDC Verdict Engine: Before the narrative layer runs, pure Python domain functions compute exact
Decimaldeltas, percentage changes, and treatment-response verdicts (improving,stalled,worsening,insufficient_data). - Post-Generation Numeric Grounding Validator: The narrative agent only reads structured JSON (never patient images), and its prose output is parsed by a regex numeric validator that rejects any number not present within
±0.5of the patient's actualconcern_scores.
Concern Action (dst_actions) | Clinical Label | Polarity (CONCERN_DIRECTION) | MDC Threshold (pts) |
|---|---|---|---|
acne, redness, oiliness | Acne, Erythema, Sebum | lower_is_better | 5.0 |
wrinkle, pores, texture, dark_circle_v2, dark_spot | Wrinkles, Pores, Texture, Dark Circles, Spots | lower_is_better | 4.0 |
moisture | Skin Moisture | higher_is_better | 5.0 |
radiance, firmness, skin_tone | Radiance, Firmness, Tone Evenness | higher_is_better | 4.0 |
4. System Architecture#
The system cleanly isolates external computer-vision ingestion, relational persistence, deterministic clinical math, grounded narrative generation, and multi-format clinical export (PDF + FHIR R4).
Patient timeline, guided visit capture, longitudinal concern charts, and PDF/FHIR export triggers
2-step presigned upload, 12-action task creation, exponential backoff polling (2s → 30s), and mask caching
Enforces MIN_VISITS=2, MIN_DAYS_BETWEEN=21, polarity rules, and per-concern MDC thresholds
Regex numeric token extractor verifying every prose number within ±0.5 of source concern_scores
Patients, immutable Visits, ConcernScores, cached segmentation masks, and SQLite/PostgreSQL fallback
Renders longitudinal trajectory charts, MDC flags, and grounded hypotheses
Serializes validated Observation resources at GET /api/patients/{id}/fhir
5. Engineering Deep Dive#
5.1 Longitudinal MDC Verdict Computation (`domain/flags.py`)#
To prevent clinicians from acting on minor camera or lighting noise, compute_verdict() enforces three sequential gates before classifying a skin concern as improving or worsening:
- Sufficient longitudinal window: The patient must have at least
MIN_VISITS = 2completed visits separated by at leastMIN_DAYS_BETWEEN = 21days; otherwise the verdict is"insufficient_data". - Minimal Detectable Change (MDC) filter: If
abs(latest_score - baseline_score) < MDC_TABLE[concern], the movement is within measurement noise and classified as"stalled". - Polarity-aware direction check: The sign of
deltais interpreted againstCONCERN_DIRECTION[concern].
from decimal import Decimal, ROUND_HALF_UP
from typing import Final, Literal
from app.domain.concerns import CONCERN_DIRECTION
Verdict = Literal["improving", "stalled", "worsening", "insufficient_data"]
MIN_DAYS_BETWEEN: Final[int] = 21
MIN_VISITS: Final[int] = 2
MDC_TABLE: Final[dict[str, float]] = {
"acne": 5.0,
"wrinkle": 4.0,
"pores": 4.0,
"texture": 4.0,
"redness": 5.0,
"oiliness": 5.0,
"moisture": 5.0,
"radiance": 4.0,
"firmness": 4.0,
"dark_circle_v2": 4.0,
"dark_spot": 4.0,
"skin_tone": 4.0,
}
def compute_verdict(
concern: str,
baseline_score: float | Decimal | None = None,
latest_score: float | Decimal | None = None,
days_between: int = MIN_DAYS_BETWEEN,
visit_count: int = MIN_VISITS,
*,
delta: float | Decimal | None = None,
) -> Verdict:
if concern not in CONCERN_DIRECTION or concern not in MDC_TABLE:
raise ValueError(f"Unknown concern {concern!r}; must be in CONCERN_LIST.")
if visit_count < MIN_VISITS or days_between < MIN_DAYS_BETWEEN:
return "insufficient_data"
if delta is None:
if baseline_score is None or latest_score is None:
return "insufficient_data"
numeric_delta = float(latest_score) - float(baseline_score)
else:
numeric_delta = float(delta)
if abs(numeric_delta) < MDC_TABLE[concern]:
return "stalled"
direction = CONCERN_DIRECTION[concern]
if direction == "higher_is_better":
return "improving" if numeric_delta > 0 else "worsening"
return "improving" if numeric_delta < 0 else "worsening"5.2 Deterministic Numeric Grounding Validator (`services/agent/validate.py`)#
When the narrative service generates a clinical summary and concern-level attribution hypotheses from structured JSON, we cannot trust prompt instructions alone to prevent hallucinated numbers.
validate.py uses a negative-lookbehind regular expression ((?<![a-zA-Z_])-?\d+(?:\.\d+)?) that extracts every standalone integer, decimal, or percentage in the agent's prose while ignoring identifier suffixes like dark_circle_v2. Every extracted number is compared against collect_source_numbers(source_json) within DEFAULT_TOLERANCE = 0.5. If any number fails verification—or if the mandatory clinical disclaimer is missing—UngroundedClaim is raised so the orchestrator can retry once and otherwise fall back to a deterministic Markdown template (templates/narrative_fallback.md):
import re
from collections.abc import Sequence
# Matches standalone signed/unsigned integers and decimals (e.g. 68, -30.0, 44.1%)
# while ignoring digits attached to identifier prefixes like 'dark_circle_v2'.
_NUMERIC_TOKEN_RE = re.compile(r"(?<![a-zA-Z_])-?\d+(?:\.\d+)?")
DEFAULT_TOLERANCE = 0.5
class UngroundedClaim(ValueError):
"""Raised when agent output contains a numeric claim not grounded in source concern_scores."""
def __init__(self, message: str, *, ungrounded_value: float | None = None) -> None:
super().__init__(message)
self.ungrounded_value = ungrounded_value
def extract_numeric_tokens(text: str) -> list[float]:
if not text:
return []
return [float(match.group(0)) for match in _NUMERIC_TOKEN_RE.finditer(text)]
def verify_numbers_against_source(
text: str,
source_numbers: Sequence[float],
*,
tolerance: float = DEFAULT_TOLERANCE,
) -> list[float]:
tokens = extract_numeric_tokens(text)
if not tokens:
return []
if not source_numbers:
raise UngroundedClaim(
f"Agent emitted numeric token {tokens[0]} but source concern_scores has no numbers.",
ungrounded_value=tokens[0],
)
for token in tokens:
matched = any(
abs(token - ref) <= tolerance or abs(abs(token) - abs(ref)) <= tolerance
for ref in source_numbers
)
if not matched:
raise UngroundedClaim(
f"Ungrounded numeric claim {token} not found within ±{tolerance} of source.",
ungrounded_value=token,
)
return tokens5.3 HL7 FHIR R4 Observation Bundle Export (`services/report/fhir.py`)#
To make longitudinal skin scores interoperable with electronic health record (EHR) systems, GET /api/patients/{id}/fhir serializes every verified concern_scores row into a strict Pydantic v2 FHIRObservation (ConfigDict(extra="forbid")) using UCUM unit {score} (http://unitsofmeasure.org), explicit severity bucket interpretations, and the mandatory clinical disclaimer annotation:
class FHIRObservation(BaseModel):
"""FHIR R4 Observation resource representing a single concern_scores row."""
model_config = ConfigDict(extra="forbid")
resourceType: Literal["Observation"] = "Observation"
id: str
status: Literal["final", "preliminary", "amended"] = "final"
category: list[FHIRCodeableConcept]
code: FHIRCodeableConcept
subject: FHIRReference
encounter: FHIRReference
effectiveDateTime: str
valueQuantity: FHIRQuantity
interpretation: list[FHIRCodeableConcept]
note: list[FHIRAnnotation]6. Technical Demo#
Technical walkthrough recording coming soon
Walkthrough of the Dermatology Bridge monorepo: YouCam S2S v2.0 task polling, Minimal Detectable Change (MDC) verdict computation, the ±0.5 numeric grounding validator, and FHIR R4 Observation bundle export.
Walkthrough Sequence & Checkpoints
- 00:00Consumer Try-On vs. Clinical Longitudinal Tracking — Why single-point skin scores fail clinicians without baseline deltas and Minimal Detectable Change (MDC) thresholds.
- 01:20YouCam S2S v2.0 Contract & Budget Gate — Two-step presigned upload, 12 frozen dst_actions, exponential backoff polling, and the 1,000-unit API budget guard.
- 02:45Deterministic Numeric Grounding Validator — Walking through apps/api/app/services/agent/validate.py to see how ungrounded LLM numbers trigger UngroundedClaim.
- 04:003-Page Consultation PDF & FHIR R4 Export — Inspecting GET /api/patients/{id}/fhir and strict Pydantic extra='forbid' Observation resources.
View Written Walkthrough Summary / Transcript ▾
Dermatology Bridge bridges consumer skin analysis and clinical follow-up. While Perfect Corp's YouCam Skin AI API powers virtual try-on for hundreds of consumer brands, clinicians need longitudinal evidence across multiple visits—not a one-off beauty score.
In our FastAPI backend, every patient visit records an immutable snapshot across 12 frozen skin concern actions (acne, wrinkle, pores, texture, redness, oiliness, moisture, radiance, firmness, dark_circle_v2, dark_spot, and skin_tone). To prevent over-interpreting minor lighting or camera variation between visits, our domain layer applies per-concern Minimal Detectable Change (MDC) thresholds of 4.0 to 5.0 points and requires at least 2 visits separated by 21 days before emitting an improving or worsening verdict.
Most importantly, the narrative agent never sees patient selfies—it only receives structured JSON scores. Every numeric token emitted in the agent's summary or attribution hypothesis is extracted via regex and verified within ±0.5 of the source concern_scores before anything is shown to a clinician.
7. Challenges and Trade-offs#
- Normalizing YouCam S2S v2.0 Payload Deltas: In testing against the Perfect Corp API Playground and SDK wrappers, we discovered two envelope variations: some responses wrap payload fields inside
result(result.file_id,result.task_status,result.results[]) while others alias the envelope asdata, and individual concern items may expose eitherscoreorui_score. We documented these deltas indocs/api-contract.mdand built a normalizer that accepts both shapes while preserving the untouched upstream JSON invisits.raw_result. - Caching Ephemeral Segmentation Masks: The
mask_urllinks returned inresult.results[]are short-lived presigned URLs. If stored directly in the database, masks break when a clinician opens a patient's longitudinal chart days later. At visit creation (POST /api/visits), the backend immediately fetches and caches each mask into private storage (concern_scores.mask_storage_key) and serves them via short-lived internal signed URLs without ever writing image URLs to application logs. - SQLite Local Fallback vs. PostgreSQL Production Types: As recorded in
docs/TECHDEBT.md, to ensure zero-friction local setup when a PostgreSQL/Neon instance is not running, the session layer supports a local SQLite fallback (sqlite:///./dermobridge.db) while keeping full PostgreSQL column definitions (UUID,TIMESTAMPTZ,JSONB) in the SQLAlchemy models and Alembic migrations.
8. Testing and Validation#
- Unit & Domain Verification: Tested
compute_delta_and_pctandcompute_verdictacross boundary conditions (visit_count < 2,days_between = 20vs.21, exact MDC boundaries,base_dec == 0division-by-zero protection, and bothhigher_is_betterandlower_is_betterconcerns). - Grounding Validator Adversarial Checks: Verified that
verify_numbers_against_sourceignores embedded version tokens likedark_circle_v2, accepts rounded numbers within±0.5, and raisesUngroundedClaimwhenever an ungrounded number or missing clinical disclaimer is injected. - Zero-Unit Mock Execution: Confirmed that full patient seeding (
python -m app.scripts.seed), visit analysis, narrative generation, PDF building, and FHIR export run end-to-end withALLOW_LIVE_CALLS=false.
9. What I Learned#
- Regex post-validation is an effective guardrail for quantitative LLM prose: When an AI model is asked to write narrative explanations of structured numerical tables, pairing a constrained JSON input with a deterministic post-generation numeric token verifier eliminates hallucinated statistics cleanly.
- Maintain an explicit API contract log: Recording observed upstream API payload variations in
docs/api-contract.mdbefore changing client code kept the mock fixtures and live S2S parser 100% synchronized.
10. Future Improvements#
- Automated Image Quality Pre-Check: Add client-side luminance and face-framing checks in
apps/webbefore uploading a selfie so poor-lighting captures are caught prior to spending 12 YouCam S2S API units. - Side-by-Side Mask Overlay Slider: Enhance the visit comparison UI with an interactive opacity slider comparing baseline and latest segmentation masks for
acneanddark_spot.