forked from Yara724/api
Added AI damage helper
This commit is contained in:
@@ -0,0 +1,75 @@
|
||||
# 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:30527
|
||||
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 `/pipeline/detect_parts_with_damages`, with `side`, `segments`, `bounding_box`, `severity`, `confidence` all `true`. Managed local files only; no URL fetching, redirects or arbitrary file paths. Maximum file size 20 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 verified provider OpenAPI declares top-level `distinct_damaged_parts_report` (`parts`, `report`), `damaged_part_table`, and `case_report`. Each part includes `part_name` and optional nullable `damage_severity`, `part_bbox`, `confidence`, `side`, `car_side`.
|
||||
|
||||
The adapter validates this envelope, bounds response/detection sizes and stores a compact result: `parts[{name,severity,bbox,confidence,side,carSide}]`, `report`, `caseReport`. The duplicated `damaged_part_table` is unnecessary for rendering and is not stored. Repeated part names remain separate detections. Missing/invalid boxes or confidence do not produce guessed values. Invalid envelopes are failures, not successful empty analyses.
|
||||
|
||||
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.
|
||||
|
||||
No segmentation polygon is fabricated from a bounding box. The provider's current response has no usable mask/polygon field, despite `segments=true`.
|
||||
|
||||
## Expert UI and access
|
||||
|
||||
Open **گزارش خسارت → تحلیل هوش مصنوعی**. Select a photo, inspect numbered boxes, toggle overlays or select a detected part to highlight its box. Severity, confidence and side are shown next to the detection; Persian image summary and full report are 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
|
||||
|
||||
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.
|
||||
@@ -422,28 +422,21 @@
|
||||
</div>
|
||||
|
||||
<!-- ═══════════════════════════════════════════════════════════ -->
|
||||
<h2 id="ai">7 — AI Service <span class="status-badge status-disabled">disabled (code present)</span></h2>
|
||||
<h2 id="ai">7 — AI Damage Companion <span class="status-badge status-partial">opt-in development rollout</span></h2>
|
||||
<p class="section-intro">
|
||||
An image-based car damage detection service is integrated in the
|
||||
codebase but its HTTP calls are <strong>fully commented out</strong>.
|
||||
The module initialises on startup, attempts a login (silently swallowed
|
||||
if it fails), and exposes an <code>aiRequestImage</code> method — but
|
||||
the underlying axios calls are disabled. The service does not affect
|
||||
any production flow.
|
||||
Damaged-part uploads schedule persisted background analysis in <code>ai-damage-jobs</code>.
|
||||
Expert review shows the original photo with client-drawn bounding boxes, per-detection severity,
|
||||
confidence, side and Persian reports. The AI does not set prices, change selected parts,
|
||||
advance workflow steps, or replace the expert decision.
|
||||
</p>
|
||||
|
||||
<div class="card card-yellow">
|
||||
<h3>Intended interface (when re-enabled)</h3>
|
||||
<h3>Development pipeline</h3>
|
||||
<table>
|
||||
<tr><th style="width:70px">Method</th><th>Path</th><th>What it does</th></tr>
|
||||
<tr><td><span class="method post">POST</span></td><td><code>{AI_URL_V2}/auth/login</code></td><td>Authenticate with username + password. Returns <code>accessToken</code>.</td></tr>
|
||||
<tr><td><span class="method get">GET</span></td><td><code>{AI_URL_V2}/auth/profile</code></td><td>Fetch <code>apiKey.key</code> needed as the <code>gateway-api-key</code> request header.</td></tr>
|
||||
<tr><td><span class="method post">POST</span></td><td><code>{AI_URL_V2}/services/car-damage/detector?version=ai-v7</code></td><td>Submit a car part image (multipart). Returns <code>downloadLink</code> with annotated result.</td></tr>
|
||||
<tr><td><span class="method post">POST</span></td><td><code>{AI_DAMAGE_URL}/pipeline/detect_parts_with_damages?side=true&segments=true&bounding_box=true&severity=true&confidence=true</code></td><td>One JPEG per multipart <code>images</code> request. Returns JSON detections and reports; no image URL or pricing.</td></tr>
|
||||
</table>
|
||||
<p class="warn" style="margin-top:8px;">
|
||||
Status: all three calls are wrapped in commented-out <code>axios.request(…)</code> blocks.
|
||||
<code>CW_URL</code> is not in <code>.env.example</code>. To re-enable, uncomment the login, getApiKey, and aiRequestImage axios calls, and configure <code>AI_URL_V2</code>, <code>AI_USERNAME</code>, <code>AI_PASSWORD</code>.
|
||||
</p>
|
||||
<p class="note">Disabled unless <code>AI_DAMAGE_ENABLED=true</code>. Atomic leases recover jobs after restart; transient errors receive bounded retries. Uploads and expert review continue when AI is unavailable. Replaced or removed photos are excluded from the live AI tab. Older current captures are scheduled when an authorized reviewer opens the tab.</p>
|
||||
<p><a href="ai-damage-companion.md">Configuration, result contract, access controls and rollout checks</a></p>
|
||||
</div>
|
||||
|
||||
<!-- ═══════════════════════════════════════════════════════════ -->
|
||||
@@ -563,9 +556,9 @@
|
||||
<h3>AI service</h3>
|
||||
<table class="env-table">
|
||||
<tr><th>Variable</th><th>Description</th></tr>
|
||||
<tr><td><code>AI_URL_V2</code></td><td>AI gateway base URL. Default: <code>https://ai-gw.ittalie.ir</code> (unused — service is disabled)</td></tr>
|
||||
<tr><td><code>AI_USERNAME</code></td><td>AI service login username (unused)</td></tr>
|
||||
<tr><td><code>AI_PASSWORD</code></td><td>AI service login password (unused)</td></tr>
|
||||
<tr><td><code>AI_DAMAGE_ENABLED</code></td><td>Explicit opt-in (<code>true</code>); defaults to disabled.</td></tr>
|
||||
<tr><td><code>AI_DAMAGE_URL</code></td><td>Development base URL: <code>http://79.132.207.77:30527</code>. Required when enabled.</td></tr>
|
||||
<tr><td><code>AI_DAMAGE_TIMEOUT_MS</code></td><td>Request timeout; default 180000 ms (1000–600000).</td></tr>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user