Skip to main content
05 // ENGINEERING SPECIFICATIONHackathon Prototype

Dermatology Bridge: Longitudinal Clinical Skin Decision-Support & Grounded AI Reporting

A clinician-facing longitudinal skin analysis platform built on the YouCam Skin AI S2S v2.0 API that tracks 12 frozen skin concerns across patient visits, computes Minimal Detectable Change (MDC) treatment-response verdicts, enforces a deterministic numeric grounding validator on AI narratives, and exports FHIR R4 Observation bundles.

Published 2026-10-24Updated 2026-10-269 min readGitHub Repository
FastAPIPythonSQLAlchemy 2.0Pydantic v2Next.js 14TypeScriptYouCam S2S APIFHIR R4

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:

  1. No longitudinal baseline or noise filtering: A 2-point shift in acne or redness between 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.
  2. Inconsistent polarity across metrics: In YouCam's 12 skin concerns, rising scores indicate worsening for 8 metrics (such as acne, wrinkle, and redness where lower_is_better), but indicate improvement for 4 metrics (moisture, radiance, firmness, and skin_tone where higher_is_better).
  3. LLM numeric hallucination risk: Asking an LLM to summarize longitudinal patient progress risks fabricated percentages or misquoted baseline scores.
  4. 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 segmentation mask_url links 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. When ALLOW_LIVE_CALLS=true is enabled, every task creation logs len(dst_actions) units to logs/unit_budget.csv.
  • Frozen Concern Contract (`ANALYSIS_VERSION = 1`): The 12 YouCam dst_actions and their clinical polarity (lower_is_better vs. higher_is_better) are frozen and versioned on every Visit row.
  • Deterministic MDC Verdict Engine: Before the narrative layer runs, pure Python domain functions compute exact Decimal deltas, 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.5 of the patient's actual concern_scores.
Specification table (Concern Action (`dst_actions`), Clinical Label, Polarity (`CONCERN_DIRECTION`), MDC Threshold (pts))
Concern Action (dst_actions)Clinical LabelPolarity (CONCERN_DIRECTION)MDC Threshold (pts)
acne, redness, oilinessAcne, Erythema, Sebumlower_is_better5.0
wrinkle, pores, texture, dark_circle_v2, dark_spotWrinkles, Pores, Texture, Dark Circles, Spotslower_is_better4.0
moistureSkin Moisturehigher_is_better5.0
radiance, firmness, skin_toneRadiance, Firmness, Tone Evennesshigher_is_better4.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).

SYSTEM SCHEMATIC // DERMATOLOGY BRIDGE MONOREPO & GROUNDED CLINICAL PIPELINE
01. Clinician Frontend (apps/web)
Next.js 14 Clinician Workspace

Patient timeline, guided visit capture, longitudinal concern charts, and PDF/FHIR export triggers

Next.js 14 · TypeScript · Tailwind CSS
JWT-Authenticated REST JSON & Signed Storage URLs
02. FastAPI Backend & Domain Layer (apps/api)
YouCam S2S v2.0 Client

2-step presigned upload, 12-action task creation, exponential backoff polling (2s → 30s), and mask caching

services/youcam/client.py
MDC Verdict Domain Engine

Enforces MIN_VISITS=2, MIN_DAYS_BETWEEN=21, polarity rules, and per-concern MDC thresholds

domain/flags.py · Decimal
Agent Grounding Validator

Regex numeric token extractor verifying every prose number within ±0.5 of source concern_scores

services/agent/validate.py
SQLAlchemy 2.0 ORM & S2S v2.0 HTTP Client
03. Persistence & Clinical Interoperability Outputs
Relational Database & Private Storage

Patients, immutable Visits, ConcernScores, cached segmentation masks, and SQLite/PostgreSQL fallback

PostgreSQL / SQLite · Alembic
3-Page Consultation PDF Builder

Renders longitudinal trajectory charts, MDC flags, and grounded hypotheses

services/report/build.py
HL7 FHIR R4 Bundle Exporter

Serializes validated Observation resources at GET /api/patients/{id}/fhir

services/report/fhir.py · Pydantic v2
Figure: Dermatology Bridge Monorepo & Grounded Clinical Pipeline

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:

  1. Sufficient longitudinal window: The patient must have at least MIN_VISITS = 2 completed visits separated by at least MIN_DAYS_BETWEEN = 21 days; otherwise the verdict is "insufficient_data".
  2. Minimal Detectable Change (MDC) filter: If abs(latest_score - baseline_score) < MDC_TABLE[concern], the movement is within measurement noise and classified as "stalled".
  3. Polarity-aware direction check: The sign of delta is interpreted against CONCERN_DIRECTION[concern].
apps/api/app/domain/flags.pypython
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):

apps/api/app/services/agent/validate.pypython
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 tokens

5.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:

apps/api/app/services/report/fhir.pypython
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 & Verification
Recorded video walkthrough coming soon

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

  1. 00:00
    Consumer Try-On vs. Clinical Longitudinal Tracking — Why single-point skin scores fail clinicians without baseline deltas and Minimal Detectable Change (MDC) thresholds.
  2. 01:20
    YouCam 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.
  3. 02:45
    Deterministic Numeric Grounding Validator — Walking through apps/api/app/services/agent/validate.py to see how ungrounded LLM numbers trigger UngroundedClaim.
  4. 04:00
    3-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 as data, and individual concern items may expose either score or ui_score. We documented these deltas in docs/api-contract.md and built a normalizer that accepts both shapes while preserving the untouched upstream JSON in visits.raw_result.
  • Caching Ephemeral Segmentation Masks: The mask_url links returned in result.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_pct and compute_verdict across boundary conditions (visit_count < 2, days_between = 20 vs. 21, exact MDC boundaries, base_dec == 0 division-by-zero protection, and both higher_is_better and lower_is_better concerns).
  • Grounding Validator Adversarial Checks: Verified that verify_numbers_against_source ignores embedded version tokens like dark_circle_v2, accepts rounded numbers within ±0.5, and raises UngroundedClaim whenever 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 with ALLOW_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.md before 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/web before 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 acne and dark_spot.