Files
yara724-api/docs/ai-damage-companion.md
T

151 lines
14 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# AI damage companion
This opt-in integration supplements the expert's claim review. It never changes workflow status, damage selection/history, prices, severity entered by experts, or compensation decisions. The pipeline returns structured detections and optional advisory market prices, but no rendered image. The expert UI draws boxes on the captured photo.
## Enable in development
Set these **API environment variables** and restart the API:
```dotenv
AI_DAMAGE_ENABLED=true
AI_DAMAGE_URL=http://79.132.207.77:30531
AI_DAMAGE_TIMEOUT_MS=600000
AI_DAMAGE_PRICE_MIN_SEVERITY=severe
```
The integration is off when `AI_DAMAGE_ENABLED` is missing or false. Enabling it requires a valid URL. Keep it off in production during this development rollout. No frontend environment variable or credential is needed. The supplied pipeline has no authentication header.
Each API instance must have access to the same persistent `files` storage as the capture API. Jobs are stored in the existing MongoDB database's new `ai-damage-jobs` collection. Development creates the schema indexes automatically. If enabling in an environment with `autoIndex=false`, create both indexes first:
```javascript
db.getCollection('ai-damage-jobs').createIndex({ claimId: 1, imageKey: 1 }, { unique: true });
db.getCollection('ai-damage-jobs').createIndex({ status: 1, nextAttemptAt: 1, leaseUntil: 1 });
```
No existing claim documents are migrated or rewritten. The old login/profile/downloadLink adapter and in-memory queue have been removed. Historical legacy `aiImage`/`aiReport` values remain intact but are not used by the new companion.
## Capture and processing
- All current user, field expert, registrar, FileMaker and FileReviewer capture routes delegate to `capturePartV2`. Once a damaged-part photo is saved, it queues the exact local file. Car-angle captures, invoices, identity documents and signatures are excluded.
- Legacy part uploads also enqueue analysis separately from their existing image records.
- Enqueueing waits only for a Mongo upsert, never for inference; a persistence error is logged without failing upload. Viewing the tab re-schedules a missed current photo.
- One worker per instance polls every five seconds and claims one job atomically. A lease token guards completion writes across replicas. Expired leases recover after restart; leases last the configured HTTP timeout plus 60 seconds. Storage must be shared across replicas.
- Each claim/photo has one job. Repeated reads/uploads do not reset successful or failed analysis. Transient network/server/invalid-response failures retry up to three claims, with 30/60-second delays. Terminal 4xx image errors require explicit retry. A retry exhausted by process crashes is also marked failed.
- The worker sends one multipart `images` file to `POST /api/v1/assessments`, with `include_polygons=false` and `include_prices=false` for automatic capture analysis. Explicit expert pricing requests use `include_prices=true`, the configured `price_min_severity`, and a multipart `car` field. The provider also accepts batches of up to 12 images; this adapter intentionally keeps one photo per durable job, using the supported single-image request so results and retries stay tied to their source capture. Managed local files only; no URL fetching, redirects or arbitrary file paths. Maximum file size 15 MiB (enforced before upload), multipart body 16 MiB and response size 2 MiB.
- The provider's OpenAPI describes JPEG inputs. Current camera/compression flows emit JPEG; a rejected older format stays visible with a recoverable analysis error.
- Current media determines the displayed photos. Replaced and removed photos' job results are retained separately, but never attached to a newer photo or inserted into the live carousel. Existing parts revision history is untouched.
## JSON and coordinates
The assessment response contains `request_id`, pipeline provenance, vehicle color/body type, `damaged_parts`, `internal_damages`, and `case_report`. Each damaged part has `part`, `side`, `severity`, `damage_types`, `descriptions`, `localized`, and image-specific `evidence`. Bounding boxes now come from `evidence[].part.box`; confidence and instance IDs also come from the evidence part.
The adapter retains one normalized part per damaged-part entry with all evidence for the uploaded photo (`image_index: 0`). Only localized parts with `link_status: linked` can produce overlays. Each part can have multiple evidence boxes; all share its numbered label in the UI. Missing/unlinked/invalid coordinates never produce guessed boxes. Evidence belonging to a different image index is excluded. Part descriptions, damage types, possible internal damages, vehicle details, request ID and pipeline versions/hashes are retained. Existing saved results from the retired pipeline remain readable, and the response normalizer retains legacy envelope compatibility.
Both HTTP error responses and HTTP-success responses containing `{error: {code, message, request_id}}` are failures. HTTP status controls automatic retries; unknown failures use the existing bounded retry policy. Code and request ID are saved for troubleshooting, while experts see Persian error feedback and the request ID. A generic HTTP 400 is no longer assumed to mean no car was found.
The drawing contract is **pixel coordinates in the uploaded image's displayed intrinsic orientation/dimensions**: `x1,y1,x2,y2`, origin top-left. The UI uses the original image's natural dimensions as the SVG viewBox, scales image and boxes together without letterboxing, and clips boxes to the image. If the provider instead emits resized-image coordinates or uses a different EXIF orientation, its contract must provide those dimensions/orientation before conversion; the UI does not infer them from the largest detection. Validate alignment using a known annotated photo supplied by the AI team before rollout.
Valid evidence polygons are retained, with invalid placeholder points such as `[null, null]` discarded. The current UI draws bounding boxes; it does not fabricate polygons or masks.
## Expert UI and access
Open **گزارش خسارت → تحلیل هوش مصنوعی**. Select a photo, inspect numbered boxes, toggle overlays or select a detected part to highlight its box. Severity, confidence, side, damage types and descriptions are shown next to the detection. Vehicle color/body type and possible internal damage with likelihood/reasons are shown when available; the full report remains available below. Unknown provider labels remain readable rather than being mapped to a guessed catalog ID.
Pending images poll every five seconds while the tab is mounted and inference is enabled. Failed images offer **تحلیل دوباره تصاویر ناموفق**. Empty, disabled, image-load failure, fetch failure and retry failure states have separate feedback. Existing successful results remain visible when inference is disabled.
Endpoints:
- `GET /v2/expert-claim/request/:claimRequestId/ai-analysis`
- `POST /v2/expert-claim/request/:claimRequestId/ai-analysis/retry`
- `GET /expert-insurer/files/:publicId/ai-analysis`
- `POST /expert-insurer/files/:publicId/ai-analysis/retry`
- Admin equivalents: `GET /super-admin/insurer/files/:publicId/ai-analysis?clientId=...` and `POST /super-admin/insurer/files/:publicId/ai-analysis/retry?clientId=...`
Expert endpoints reuse the exact existing claim-detail gate (role, organization, branch, ownership/reviewer assignment and workflow visibility). Insurer endpoints first resolve the existing tenant-scoped public file detail; callers cannot supply a different underlying claim ID. Admin equivalents retain `SuperAdminGuard` and resolve the file inside the explicitly selected client. No public or user endpoint exposes AI results. Responses expose image URLs, status, localized errors and completed compact results; no local paths, raw upstream response or credentials.
## Development acceptance checks
1. Enable the environment above; capture two damaged-part JPEGs through any current creation flow. Confirm immediate capture responses and queued/processing jobs.
2. Open claim review and its AI tab. Confirm each response belongs to its source photo, repeated detections remain distinct, and boxes line up on desktop/mobile. Confirm JSON severity/confidence and Persian reports match the provider.
3. Replace one photo via an allowed resend. Confirm the old result is not shown on the replacement. Remove a part through existing expert editing; confirm its image/result disappears from current analysis while selection history stays intact.
4. Stop/restart an API worker during analysis: after lease expiry, a worker must reclaim it. Repeat with two replicas sharing storage; completion must be guarded by the lease token.
5. Make the provider unavailable: capture and pricing must still work; retries should stop and the tab should offer retry. Try another tenant/unauthorized claim ID: analysis read/retry must be denied by existing file access controls.
## Implementation verification
The historical live probe below used the retired pipeline. The assessment API migration is covered by mocked response, multipart transport, error-envelope and image-size checks; it has not been verified against the live new provider.
On 2026-10-03 the real multipart adapter successfully called the development pipeline with [Front bumper broken.jpg](https://commons.wikimedia.org/wiki/File:Front_bumper_broken.jpg), a public photograph by Tiia Monto (CC BY-SA 3.0). It returned HTTP 200 and six detections, with Persian reports, severity, confidence and bounding boxes. Rendering was checked against the source JPEG's actual 2121×1188 dimensions. No customer photo was used for this probe. A separate synthetic blank JPEG returned HTTP 500; that failure is handled by the existing bounded retry/error path.
Backend checks cover upload-to-queue integration, immutable per-photo association, atomic job leases/recovery, retry limits, real multipart bytes/options, response validation, and expert/insurer/admin file-access gates. Frontend checks cover clipping/scaling, readable 24px number badges, report toggles, pending polling, retry, disabled cached results, empty images, fetch recovery and desktop/mobile overflow.
## Unified advisory pricing
The OpenAI prompt/module, its routes under `/v2/price-estimation`, and the separate
expert price tab have been removed. No OpenAI key is needed in this API. Remove
`OPENAI_PRICE_ESTIMATION_*` from deployment settings. Existing price-estimate
collections are left intact; there is no database deletion or migration.
The existing AI tab now shows detection and market evidence together. Automatic
uploads continue to request detection only. An authorized reviewing expert confirms
or enters the damaged vehicle's Persian make/model, selects a current photo, then
requests **تحلیل و برآورد قیمت همین تصویر**. The input is prefilled from the panel's
resolved damaged-car identity when that name is Persian; missing or English-only
names require manual entry. The expert can correct an inquiry name before sending.
`POST /v2/expert-claim/request/:claimRequestId/ai-analysis/estimate` accepts:
```json
{"imageKey":"<64-character imageKey from the GET response>","carName":"پژو ۲۰۶ تیپ ۲"}
```
It uses the existing claim-detail authorization gate and accepts only a photo from
the current case's damage media. It queues work immediately rather than waiting on
the upstream model. Failed pricing can use the existing retry endpoint. A running
analysis or an already-queued pricing request returns 409 instead of queuing another
chargeable request. An explicit request after completion starts a fresh estimate.
The submitted car name and severity are stored with that image's job; polling
exposes these values while work is pending. Company/super-admin viewers may read
saved results and retry detection-only jobs but cannot submit or retry priced analyses.
The existing backend remains the authorized image transport, durable queue and
response adapter. Detection and pricing both come from the same assessment service;
there is no separate price-model prompt or market-research orchestration here.
### Deployment threshold
`AI_DAMAGE_PRICE_MIN_SEVERITY` accepts `minor`, `moderate`, `severe` (default) or
literal `null`. `minor` prices all damaged parts; `moderate` includes moderate and
severe parts; `severe` includes only severe parts. The provider's live OpenAPI
accepts only the three non-null enum strings, so the `null` setting is adapted to
`minor`, meaning all severities. Restart the API after changing configuration.
The threshold is recorded per requested job, including on retries.
### Units, completeness and interpretation
Provider monetary fields in tomans are converted to rials **once** by the response
normalizer: overall/genuine/aftermarket totals, component min/median/max, repair
estimates and individual listing prices. Missing/invalid/unsafe numbers remain null,
not zero. Unsupported currencies do not acquire a guessed conversion. Provider
processing cost and duration remain server-side diagnostics. They are excluded from
expert-facing API results, together with request IDs, pipeline versions, model names
and hashes, including when reading previously stored jobs. The UI explicitly
labels monetary values as rials and identifies an LLM repair guess separately.
Each job uses one photo, so the provider's `pricing` summary is **that photo's**
summary, never a whole-claim total. The UI warns against summing photos: the same
physical part may appear in multiple photos. Incomplete results keep their partial
warning, priced/unpriced counts and available evidence. No algorithm maps the AI's
names to Fanavaran parts or writes prices/repair choices/price drop into the claim.
The expert selects the matching catalogue part and enters the final valuation.
Sources show used/unused status; only absolute HTTP(S) links without credentials
are clickable. Price ranges, sample count, spread warning, original/aftermarket
alternatives, notes and the result date remain available. Model identity, billing,
processing timings and cache diagnostics are not displayed.
Legacy detection-only results still render normally. Opening the AI tab does not
start paid pricing. No real claim images were sent during implementation tests;
transport and UI tests use local fixtures. Validate actual market quality with the
AI team before relying on the estimates.