forked from Yara724/api
80 lines
9.8 KiB
Markdown
80 lines
9.8 KiB
Markdown
# 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 currently returns no price estimates and no 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=180000
|
||
```
|
||
|
||
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`, without the retired pipeline query flags. 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.
|