Merge pull request 'Changed AI to new version' (#372) from s.yahyaee/yara724-api:main into main

Reviewed-on: Yara724/api#372
This commit is contained in:
2026-11-03 15:58:46 +03:30
11 changed files with 4349 additions and 61 deletions
+1 -1
View File
@@ -57,7 +57,7 @@ SANHUB_PASSWORD =
# 🤖 AI Services # 🤖 AI Services
# --------------------------------------------- # ---------------------------------------------
AI_DAMAGE_ENABLED=false AI_DAMAGE_ENABLED=false
AI_DAMAGE_URL=http://79.132.207.77:30527 AI_DAMAGE_URL=http://79.132.207.77:30531
AI_DAMAGE_TIMEOUT_MS=180000 AI_DAMAGE_TIMEOUT_MS=180000
# Independent on-demand price research (disabled by default; no automatic capture calls). # Independent on-demand price research (disabled by default; no automatic capture calls).
+1
View File
@@ -186,6 +186,7 @@ dist
*.sh *.sh
!scripts/fanavaran-flow-test.sh !scripts/fanavaran-flow-test.sh
!scripts/fanavaran-auth.sh !scripts/fanavaran-auth.sh
!scripts/get-fanavaran-car-parts.sh
# --- local WIP (do not track) --- # --- local WIP (do not track) ---
.agents/ .agents/
+7 -12
View File
@@ -1,27 +1,22 @@
# Use the official Node.js image as the base image # Use the official Node.js image as the base image
FROM node:20-alpine FROM docker.arvancloud.ir/node:20-alpine
# Set the working directory inside the container
WORKDIR /app WORKDIR /app
# Copy package.json and package-lock.json to the working directory
COPY package*.json ./ COPY package*.json ./
# Iran access Repo RUN npm config set registry "https://repo.hmirror.ir/npm"
RUN npm config set registry https://mirror-npm.runflare.com
# Install the project dependencies # Install the project dependencies
RUN npm i --force RUN npm i --force --verbose --no-scripts
# Copy the rest of the application code to the working directory # Copy the rest of the application code to the working directory
COPY . .
# Compile once at image build time — do not compile with `nest start` at container boot COPY . .
RUN npm run build
# Expose the port on which your NestJS application will run # Expose the port on which your NestJS application will run
EXPOSE 3002 EXPOSE 3002
# Run the prebuilt app (avoids TypeScript compile OOM on restart) # Start the NestJS application
ENV NODE_OPTIONS=--max-old-space-size=1024 CMD ["npm", "start"]
CMD ["npm", "run", "start:prod"]
+10 -6
View File
@@ -8,7 +8,7 @@ Set these **API environment variables** and restart the API:
```dotenv ```dotenv
AI_DAMAGE_ENABLED=true AI_DAMAGE_ENABLED=true
AI_DAMAGE_URL=http://79.132.207.77:30527 AI_DAMAGE_URL=http://79.132.207.77:30531
AI_DAMAGE_TIMEOUT_MS=180000 AI_DAMAGE_TIMEOUT_MS=180000
``` ```
@@ -30,23 +30,25 @@ No existing claim documents are migrated or rewritten. The old login/profile/dow
- 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. - 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. - 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. - 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 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. - 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. - 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 ## 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 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 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 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. 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`. 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 ## 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. 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. 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.
@@ -70,6 +72,8 @@ Expert endpoints reuse the exact existing claim-detail gate (role, organization,
## Implementation verification ## 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. 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. 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.
+3680
View File
File diff suppressed because it is too large Load Diff
+211
View File
@@ -0,0 +1,211 @@
#!/usr/bin/env bash
set -euo pipefail
CONFIG_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/yara724"
CONFIG_FILE="$CONFIG_DIR/fanavaran-car-parts.env"
usage() {
cat <<'USAGE'
Usage: scripts/get-fanavaran-car-parts.sh [--reset]
Fetches Fanavaran's complete car-components lookup:
GET /BimeApi/v2.0/car/base-info/car-components
On first run, prompts for the Fanavaran credentials and request header values,
then saves them with owner-only permissions under ~/.config/yara724/.
Use --reset to enter new values.
USAGE
}
die() {
printf 'Error: %s\n' "$*" >&2
exit 1
}
encode() {
printf '%s' "$1" | base64 | tr -d '\n'
}
decode() {
printf '%s' "$1" | base64 --decode
}
prompt_value() {
local label="$1" variable="$2" secret="${3:-false}" value
if [[ "$secret" == true ]]; then
read -r -s -p "$label: " value
printf '\n' >&2
else
read -r -p "$label: " value
fi
[[ -n "$value" ]] || die "$label is required"
printf -v "$variable" '%s' "$value"
}
save_config() {
mkdir -p "$CONFIG_DIR"
chmod 700 "$CONFIG_DIR"
local temporary_file
temporary_file="$(mktemp "$CONFIG_DIR/.fanavaran-car-parts.XXXXXX")"
chmod 600 "$temporary_file"
{
printf 'BASE_URL=%s\n' "$(encode "$base_url")"
printf 'APP_NAME=%s\n' "$(encode "$app_name")"
printf 'APP_SECRET=%s\n' "$(encode "$app_secret")"
printf 'USERNAME=%s\n' "$(encode "$fanavaran_username")"
printf 'PASSWORD=%s\n' "$(encode "$fanavaran_password")"
printf 'CORP_ID=%s\n' "$(encode "$corp_id")"
printf 'CONTRACT_ID=%s\n' "$(encode "$contract_id")"
printf 'LOCATION=%s\n' "$(encode "$location")"
} > "$temporary_file"
mv -f "$temporary_file" "$CONFIG_FILE"
}
load_config() {
[[ -f "$CONFIG_FILE" ]] || return 1
# Config values are base64 encoded, so this file is safe to parse as data.
while IFS='=' read -r key value; do
case "$key" in
BASE_URL) base_url="$(decode "$value")" ;;
APP_NAME) app_name="$(decode "$value")" ;;
APP_SECRET) app_secret="$(decode "$value")" ;;
USERNAME) fanavaran_username="$(decode "$value")" ;;
PASSWORD) fanavaran_password="$(decode "$value")" ;;
CORP_ID) corp_id="$(decode "$value")" ;;
CONTRACT_ID) contract_id="$(decode "$value")" ;;
LOCATION) location="$(decode "$value")" ;;
esac
done < "$CONFIG_FILE"
[[ -n "${base_url:-}" && -n "${app_name:-}" && -n "${app_secret:-}" && \
-n "${fanavaran_username:-}" && -n "${fanavaran_password:-}" && \
-n "${corp_id:-}" && -n "${contract_id:-}" && -n "${location:-}" ]] ||
die "Saved config is incomplete. Run with --reset to re-enter it."
}
prompt_config() {
local client
printf 'Choose Fanavaran tenant (parsian, tejaratno, moallem).\n'
prompt_value 'Tenant' client
case "${client,,}" in
parsian|tejaratno) base_url_default='https://apimanager.iraneit.com/BimeApiManager/api' ;;
moallem) base_url_default='https://api.inssw.ir/BimeApiManager/api' ;;
*) die 'Tenant must be parsian, tejaratno, or moallem' ;;
esac
read -r -p "API manager base URL [$base_url_default]: " base_url
base_url="${base_url:-$base_url_default}"
base_url="${base_url%/}"
[[ "$base_url" == https://* ]] || die 'Base URL must use HTTPS'
prompt_value 'App name' app_name
prompt_value 'App secret' app_secret true
prompt_value 'Fanavaran username' fanavaran_username
prompt_value 'Fanavaran password' fanavaran_password true
prompt_value 'CorpId' corp_id
prompt_value 'ContractId' contract_id
prompt_value 'Location' location
save_config
printf 'Credentials saved privately to %s\n' "$CONFIG_FILE" >&2
}
read_response_header() {
local wanted="$1" file="$2"
awk -F: -v wanted="$wanted" '
tolower($1) == tolower(wanted) {
sub(/^[^:]*:[[:space:]]*/, "")
sub(/\r$/, "")
print
exit
}
' "$file"
}
check_http_status() {
local status="$1" body_file="$2" label="$3"
if [[ ! "$status" =~ ^2[0-9][0-9]$ ]]; then
printf '%s failed (HTTP %s). Response:\n' "$label" "$status" >&2
cat "$body_file" >&2
printf '\n' >&2
exit 1
fi
}
reset_config=false
if [[ "${1:-}" == "--help" || "${1:-}" == "-h" ]]; then
usage
exit 0
elif [[ "${1:-}" == "--reset" ]]; then
reset_config=true
elif [[ $# -gt 0 ]]; then
usage >&2
exit 2
fi
if [[ "$reset_config" == true ]] || ! load_config; then
prompt_config
fi
command -v curl >/dev/null || die 'curl is required'
command -v base64 >/dev/null || die 'base64 is required'
command -v node >/dev/null || die 'node is required to parse the login response'
temporary_dir="$(mktemp -d)"
chmod 700 "$temporary_dir"
trap 'rm -rf "$temporary_dir"' EXIT
printf 'Requesting Fanavaran app token...\n' >&2
cat > "$temporary_dir/app-token.headers" <<HEADERS
appname: $app_name
secret: $app_secret
Content-Length: 0
HEADERS
chmod 600 "$temporary_dir/app-token.headers"
app_status="$(curl --silent --show-error --output "$temporary_dir/app-token.body" \
--dump-header "$temporary_dir/app-token.response-headers" --write-out '%{http_code}' \
--request POST --header "@$temporary_dir/app-token.headers" \
"$base_url/EITAuthentication/GetAppToken")"
check_http_status "$app_status" "$temporary_dir/app-token.body" 'GetAppToken'
app_token="$(read_response_header apptoken "$temporary_dir/app-token.response-headers")"
[[ -n "$app_token" ]] || die 'GetAppToken succeeded but no apptoken response header was found'
printf 'Logging in to Fanavaran...\n' >&2
cat > "$temporary_dir/login.headers" <<HEADERS
appToken: $app_token
userName: $fanavaran_username
password: $fanavaran_password
Content-Length: 0
HEADERS
chmod 600 "$temporary_dir/login.headers"
login_status="$(curl --silent --show-error --output "$temporary_dir/login.body" \
--dump-header "$temporary_dir/login.response-headers" --write-out '%{http_code}' \
--request POST --header "@$temporary_dir/login.headers" \
"$base_url/EITAuthentication/Login")"
check_http_status "$login_status" "$temporary_dir/login.body" 'Login'
authentication_token="$(read_response_header authenticationtoken "$temporary_dir/login.response-headers")"
if [[ -z "$authentication_token" ]]; then
authentication_token="$(node -e '
const fs = require("node:fs");
try {
const body = JSON.parse(fs.readFileSync(process.argv[1], "utf8"));
process.stdout.write(body.authenticationToken || body.authenticationtoken || body.authentication_token || "");
} catch {}
' "$temporary_dir/login.body")"
fi
[[ -n "$authentication_token" ]] || die 'Login succeeded but no authentication token was found'
cat > "$temporary_dir/lookup.headers" <<HEADERS
authenticationToken: $authentication_token
CorpId: $corp_id
ContractId: $contract_id
Location: $location
Accept: application/json
HEADERS
chmod 600 "$temporary_dir/lookup.headers"
printf 'Fetching complete car-parts lookup...\n' >&2
lookup_status="$(curl --silent --show-error --output "$temporary_dir/lookup.body" \
--write-out '%{http_code}' --request GET --header "@$temporary_dir/lookup.headers" \
"$base_url/BimeApi/v2.0/car/base-info/car-components")"
check_http_status "$lookup_status" "$temporary_dir/lookup.body" 'Car-parts lookup'
cat "$temporary_dir/lookup.body"
printf '\n'
+2
View File
@@ -19,6 +19,8 @@ export class AiJob {
@Prop() leaseToken?: string; @Prop() leaseToken?: string;
@Prop() completedAt?: Date; @Prop() completedAt?: Date;
@Prop() error?: string; @Prop() error?: string;
@Prop() errorCode?: string;
@Prop() errorRequestId?: string;
@Prop({ type: MongoSchema.Types.Mixed }) result?: AiResult; @Prop({ type: MongoSchema.Types.Mixed }) result?: AiResult;
} }
export const AiJobSchema = SchemaFactory.createForClass(AiJob); export const AiJobSchema = SchemaFactory.createForClass(AiJob);
+149 -1
View File
@@ -1,4 +1,4 @@
import { normalizeAiResult } from "./ai-result"; import { AiAssessmentError, normalizeAiResult } from "./ai-result";
import { currentAiCaptures } from "./ai-captures"; import { currentAiCaptures } from "./ai-captures";
const response = () => ({ const response = () => ({
@@ -26,6 +26,154 @@ const response = () => ({
}); });
describe("AI response contract", () => { describe("AI response contract", () => {
const assessment = () => ({
request_id: "assessment-123",
pipeline: { version: "v1", vlm_model: "model", prompt_version: "p1" },
vehicle: { color: "خاکستری", body_type: "sedan" },
damaged_parts: [
{
part: "Mirror",
side: "left",
severity: "minor",
localized: true,
damage_types: ["scratch"],
descriptions: ["خراش روی آینه"],
evidence: [
{
image_index: 0,
filename: "mirror.jpg",
view: "front",
severity: "minor",
link_status: "linked",
part: {
instance_id: 1,
confidence: 0.9,
box: { x1: 10, y1: 20, x2: 40, y2: 80 },
polygon: [
[10, 20],
[40, 20],
[40, 80],
],
},
},
],
},
],
internal_damages: [
{
category: "radiator",
label_fa: "رادیاتور",
likelihood: "medium",
reason: "نیاز به بررسی",
},
],
case_report: "گزارش ارزیابی",
});
it("normalizes assessments, retaining evidence, damage descriptions and provenance", () => {
const result = normalizeAiResult(assessment());
expect(result).toMatchObject({
requestId: "assessment-123",
pipeline: { version: "v1" },
vehicle: { color: "خاکستری", bodyType: "sedan" },
internalDamages: [
{ labelFa: "رادیاتور", likelihood: "medium", reason: "نیاز به بررسی" },
],
caseReport: "گزارش ارزیابی",
parts: [
{
name: "Mirror",
side: "left",
severity: "minor",
localized: true,
damageTypes: ["scratch"],
descriptions: ["خراش روی آینه"],
confidence: 0.9,
bbox: { x1: 10, y1: 20, x2: 40, y2: 80 },
evidence: [
{
imageIndex: 0,
instanceId: 1,
polygon: [
[10, 20],
[40, 20],
[40, 80],
],
},
],
},
],
});
});
it("keeps multiple evidence boxes for a part without drawing evidence from another photo", () => {
const value = assessment();
const evidence = value.damaged_parts[0].evidence;
evidence.push({
...evidence[0],
part: { ...evidence[0].part, instance_id: 2 },
});
evidence.push({ ...evidence[0], image_index: 1 });
const result = normalizeAiResult(value);
expect(result.parts).toHaveLength(1);
expect(result.parts[0].evidence).toHaveLength(2);
expect(
result.parts[0].evidence.every((item) => item.imageIndex === 0),
).toBe(true);
});
it("does not invent boxes for unlocalized, unlinked or invalid evidence", () => {
const value = assessment();
value.damaged_parts[0].localized = false;
expect(normalizeAiResult(value).parts[0].bbox).toBeNull();
value.damaged_parts[0].localized = true;
value.damaged_parts[0].evidence[0].link_status = "unlinked";
expect(normalizeAiResult(value).parts[0].bbox).toBeNull();
value.damaged_parts[0].evidence[0].link_status = "linked";
value.damaged_parts[0].evidence[0].part.box.x2 = NaN;
value.damaged_parts[0].evidence[0].part.polygon = [[null, null]];
expect(normalizeAiResult(value).parts[0].evidence[0]).toMatchObject({
bbox: null,
polygon: null,
});
});
it("accepts zero detections and parts without evidence", () => {
const value = assessment();
value.damaged_parts[0].evidence = [];
expect(normalizeAiResult(value).parts[0]).toMatchObject({
bbox: null,
evidence: [],
});
value.damaged_parts = [];
expect(normalizeAiResult(value).parts).toEqual([]);
});
it("rejects error envelopes even with an HTTP-success response, preserving code and request id", () => {
try {
normalizeAiResult({
error: {
code: "INVALID_IMAGE",
message: "Invalid image",
request_id: "r-1",
},
});
throw new Error("Expected assessment failure");
} catch (error) {
expect(error).toBeInstanceOf(AiAssessmentError);
expect(error).toMatchObject({
code: "INVALID_IMAGE",
requestId: "r-1",
message: "Invalid image",
});
}
expect(() =>
normalizeAiResult({ damaged_parts: [], case_report: null }),
).toThrow();
expect(() =>
normalizeAiResult({ ...assessment(), internal_damages: {} }),
).toThrow();
});
it("preserves distinct repeated detections, nullable fields and Persian reports without requiring a returned image", () => { it("preserves distinct repeated detections, nullable fields and Persian reports without requiring a returned image", () => {
const result = normalizeAiResult(response()); const result = normalizeAiResult(response());
expect(result.parts).toHaveLength(2); expect(result.parts).toHaveLength(2);
+163
View File
@@ -5,18 +5,181 @@ export interface AiPart {
side: string | null; side: string | null;
carSide: string | null; carSide: string | null;
bbox: { x1: number; y1: number; x2: number; y2: number } | null; bbox: { x1: number; y1: number; x2: number; y2: number } | null;
damageTypes?: string[];
descriptions?: string[];
localized?: boolean;
evidence?: AiEvidence[];
}
export interface AiEvidence {
imageIndex: number;
filename: string | null;
view: string | null;
severity: string | null;
linkStatus: string | null;
instanceId: number | null;
confidence: number | null;
bbox: AiPart["bbox"];
polygon: [number, number][] | null;
} }
export interface AiResult { export interface AiResult {
parts: AiPart[]; parts: AiPart[];
report: string; report: string;
caseReport: string; caseReport: string;
requestId?: string | null;
pipeline?: Record<string, string | null>;
vehicle?: { color: string | null; bodyType: string | null };
internalDamages?: Array<{
category: string | null;
labelFa: string | null;
likelihood: string | null;
reason: string | null;
}>;
} }
const text = (v: unknown): string | null => const text = (v: unknown): string | null =>
typeof v === "string" ? v.trim().slice(0, 20000) : null; typeof v === "string" ? v.trim().slice(0, 20000) : null;
export class AiAssessmentError extends Error {
constructor(
public readonly code: string | null,
public readonly requestId: string | null,
public readonly httpStatus?: number,
message = "AI assessment provider returned an error",
) {
super(message);
}
}
function boundingBox(value: any): AiPart["bbox"] {
return value &&
[value.x1, value.y1, value.x2, value.y2].every(
(n) => typeof n === "number" && Number.isFinite(n),
) &&
value.x2 > value.x1 &&
value.y2 > value.y1
? { x1: value.x1, y1: value.y1, x2: value.x2, y2: value.y2 }
: null;
}
const confidence = (value: unknown): number | null =>
typeof value === "number" &&
Number.isFinite(value) &&
value >= 0 &&
value <= 1
? value
: null;
function strings(value: unknown): string[] {
return Array.isArray(value)
? value
.slice(0, 100)
.map(text)
.filter((item): item is string => !!item)
: [];
}
/** Each durable job uploads exactly one image, whose evidence index is zero. */
function normalizeAssessment(raw: any): AiResult {
if (!Array.isArray(raw.damaged_parts) || typeof raw.case_report !== "string")
throw new Error("Invalid AI assessment response");
if (
raw.damaged_parts.length > 500 ||
(raw.internal_damages != null && !Array.isArray(raw.internal_damages)) ||
(raw.internal_damages?.length ?? 0) > 500
)
throw new Error("Invalid AI assessment collections");
let evidenceCount = 0;
const parts = raw.damaged_parts.map((part: any): AiPart => {
const name = text(part?.part);
if (!name || (part.evidence != null && !Array.isArray(part.evidence)))
throw new Error("Invalid AI damaged part");
evidenceCount += part.evidence?.length ?? 0;
if (evidenceCount > 2000) throw new Error("Too many AI evidence records");
const evidence: AiEvidence[] = (part.evidence ?? [])
.filter((item: any) => item?.image_index === 0)
.map((item: any): AiEvidence => {
const linked = part.localized === true && item.link_status === "linked";
const rawPolygon = item.part?.polygon;
const polygon =
linked &&
Array.isArray(rawPolygon) &&
rawPolygon.length >= 3 &&
rawPolygon.length <= 10000 &&
rawPolygon.every(
(point: unknown) =>
Array.isArray(point) &&
point.length === 2 &&
point.every((n) => typeof n === "number" && Number.isFinite(n)),
)
? rawPolygon.map(
(point: number[]) => [point[0], point[1]] as [number, number],
)
: null;
return {
imageIndex: 0,
filename: text(item.filename),
view: text(item.view),
severity: text(item.severity),
linkStatus: text(item.link_status),
instanceId: Number.isInteger(item.part?.instance_id)
? item.part.instance_id
: null,
confidence: confidence(item.part?.confidence),
bbox: linked ? boundingBox(item.part?.box) : null,
polygon,
};
});
const firstBox = evidence.find((item) => item.bbox);
return {
name,
severity: text(part.severity),
confidence: firstBox?.confidence ?? null,
side: text(part.side),
carSide: firstBox?.view ?? null,
bbox: firstBox?.bbox ?? null,
damageTypes: strings(part.damage_types),
descriptions: strings(part.descriptions),
localized: part.localized === true,
evidence,
};
});
return {
parts,
report: "",
caseReport: text(raw.case_report) ?? "",
requestId: text(raw.request_id),
pipeline: Object.fromEntries(
[
"version",
"vlm_model",
"prompt_version",
"part_model_sha256",
"car_model_sha256",
].map((key) => [key, text(raw.pipeline?.[key])]),
),
vehicle: {
color: text(raw.vehicle?.color),
bodyType: text(raw.vehicle?.body_type),
},
internalDamages: (raw.internal_damages ?? []).map((item: any) => ({
category: text(item?.category),
labelFa: text(item?.label_fa),
likelihood: text(item?.likelihood),
reason: text(item?.reason),
})),
};
}
/** Preserve detections independently: repeated names may describe different boxes. */ /** Preserve detections independently: repeated names may describe different boxes. */
export function normalizeAiResult(value: unknown): AiResult { export function normalizeAiResult(value: unknown): AiResult {
const raw = value as any; const raw = value as any;
if (raw?.error)
throw new AiAssessmentError(
text(raw.error.code),
text(raw.error.request_id),
undefined,
text(raw.error.message) ?? undefined,
);
if (raw && "damaged_parts" in raw) return normalizeAssessment(raw);
const report = raw?.distinct_damaged_parts_report; const report = raw?.distinct_damaged_parts_report;
if ( if (
!report || !report ||
+63 -14
View File
@@ -1,6 +1,7 @@
import { ConfigService } from "@nestjs/config"; import { ConfigService } from "@nestjs/config";
import { AiService, aiImageKey } from "./ai.service"; import { AiService, aiImageKey } from "./ai.service";
import { AiJobSchema } from "./ai-job.schema"; import { AiJobSchema } from "./ai-job.schema";
import { AiAssessmentError } from "./ai-result";
const image = { path: "files/part.jpg", label: "گلگیر" }; const image = { path: "files/part.jpg", label: "گلگیر" };
const result = { parts: [], report: "گزارش", caseReport: "گزارش کامل" }; const result = { parts: [], report: "گزارش", caseReport: "گزارش کامل" };
@@ -129,7 +130,7 @@ describe("durable AI jobs", () => {
); );
} }
}); });
it("does not retry invalid/non-car images automatically", async () => { it("does not retry rejected requests automatically or assume every 400 means no car", async () => {
const { service, jobs } = setup(); const { service, jobs } = setup();
claimJob(jobs); claimJob(jobs);
jest jest
@@ -141,7 +142,32 @@ describe("durable AI jobs", () => {
expect.objectContaining({ expect.objectContaining({
$set: expect.objectContaining({ $set: expect.objectContaining({
status: "failed", status: "failed",
error: "خودرو در تصویر تشخیص داده نشد.", error: "سرویس هوش مصنوعی درخواست تحلیل این تصویر را نپذیرفت.",
}),
}),
);
});
it("persists provider error tracking metadata and uses the HTTP status for retry decisions", async () => {
const { service, jobs } = setup();
claimJob(jobs);
jest
.spyOn(service, "aiRequestImage")
.mockRejectedValue(
new AiAssessmentError(
"INVALID_INPUT",
"req-123",
422,
"Unusable photo",
),
);
await service.work();
expect(jobs.updateOne).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
$set: expect.objectContaining({
status: "failed",
errorCode: "INVALID_INPUT",
errorRequestId: "req-123",
}), }),
}), }),
); );
@@ -195,7 +221,7 @@ describe("durable AI jobs", () => {
}); });
describe("AI multipart transport", () => { describe("AI multipart transport", () => {
it("posts real image bytes under images with every pipeline flag and no returned-image dependency", async () => { it("posts real image bytes to assessments with no retired pipeline flags", async () => {
const fs = await import("node:fs/promises"); const fs = await import("node:fs/promises");
const { resolve, join } = await import("node:path"); const { resolve, join } = await import("node:path");
const axios = (await import("axios")).default; const axios = (await import("axios")).default;
@@ -214,15 +240,8 @@ describe("AI multipart transport", () => {
.spyOn(axios, "post") .spyOn(axios, "post")
.mockImplementation(async (url, form: any, config) => { .mockImplementation(async (url, form: any, config) => {
const parsed = new URL(String(url)); const parsed = new URL(String(url));
expect(parsed.pathname).toBe("/pipeline/detect_parts_with_damages"); expect(parsed.pathname).toBe("/api/v1/assessments");
for (const option of [ expect(parsed.search).toBe("");
"side",
"segments",
"bounding_box",
"severity",
"confidence",
])
expect(parsed.searchParams.get(option)).toBe("true");
expect(config?.headers?.["content-type"]).toMatch( expect(config?.headers?.["content-type"]).toMatch(
/^multipart\/form-data; boundary=/, /^multipart\/form-data; boundary=/,
); );
@@ -243,7 +262,9 @@ describe("AI multipart transport", () => {
expect(body.includes(bytes)).toBe(true); expect(body.includes(bytes)).toBe(true);
return { return {
data: { data: {
distinct_damaged_parts_report: { parts: [], report: "گزارش" }, request_id: "req-123",
damaged_parts: [],
internal_damages: [],
case_report: "گزارش کامل", case_report: "گزارش کامل",
}, },
} as any; } as any;
@@ -252,11 +273,39 @@ describe("AI multipart transport", () => {
const { service } = setup(); const { service } = setup();
await expect( await expect(
service.aiRequestImage({ path: file, fileName: "test.jpg" }), service.aiRequestImage({ path: file, fileName: "test.jpg" }),
).resolves.toMatchObject({ parts: [], report: "گزارش" }); ).resolves.toMatchObject({ parts: [], requestId: "req-123" });
await expect( await expect(
service.aiRequestImage({ path: "/etc/hosts" }), service.aiRequestImage({ path: "/etc/hosts" }),
).rejects.toThrow("outside upload storage"); ).rejects.toThrow("outside upload storage");
expect(post).toHaveBeenCalledTimes(1); expect(post).toHaveBeenCalledTimes(1);
await fs.truncate(file, 15 * 1024 * 1024 + 1);
await expect(service.aiRequestImage({ path: file })).rejects.toThrow(
"Invalid image size",
);
expect(post).toHaveBeenCalledTimes(1);
await fs.writeFile(file, bytes);
const { AxiosError } = await import("axios");
post.mockRejectedValueOnce(
new AxiosError("Rejected", undefined, undefined, undefined, {
status: 422,
data: {
error: {
code: "INVALID_INPUT",
message: "Invalid image",
request_id: "req-error",
},
},
} as any),
);
await expect(
service.aiRequestImage({ path: file }),
).rejects.toMatchObject({
code: "INVALID_INPUT",
requestId: "req-error",
httpStatus: 422,
message: "Invalid image",
});
} finally { } finally {
pathSpy.mockRestore(); pathSpy.mockRestore();
post.mockRestore(); post.mockRestore();
+61 -26
View File
@@ -14,7 +14,7 @@ import { Model } from "mongoose";
import axios from "axios"; import axios from "axios";
import FormData = require("form-data"); import FormData = require("form-data");
import { AiJob } from "./ai-job.schema"; import { AiJob } from "./ai-job.schema";
import { normalizeAiResult } from "./ai-result"; import { AiAssessmentError, normalizeAiResult } from "./ai-result";
import { buildFileLink } from "src/helpers/urlCreator"; import { buildFileLink } from "src/helpers/urlCreator";
export interface AiCapture { export interface AiCapture {
@@ -110,6 +110,8 @@ export class AiService implements OnModuleInit, OnModuleDestroy {
attempts: job?.attempts ?? 0, attempts: job?.attempts ?? 0,
completedAt: job?.completedAt, completedAt: job?.completedAt,
error: job?.error, error: job?.error,
errorCode: job?.errorCode,
errorRequestId: job?.errorRequestId,
result: job?.status === "completed" ? job.result : undefined, result: job?.status === "completed" ? job.result : undefined,
}; };
}), }),
@@ -126,7 +128,13 @@ export class AiService implements OnModuleInit, OnModuleDestroy {
}, },
{ {
$set: { status: "queued", attempts: 0, nextAttemptAt: new Date() }, $set: { status: "queued", attempts: 0, nextAttemptAt: new Date() },
$unset: { error: 1, leaseToken: 1, leaseUntil: 1 }, $unset: {
error: 1,
errorCode: 1,
errorRequestId: 1,
leaseToken: 1,
leaseUntil: 1,
},
}, },
); );
return this.list(claimId, images); return this.list(claimId, images);
@@ -139,22 +147,13 @@ export class AiService implements OnModuleInit, OnModuleDestroy {
if (!path.startsWith(root + sep)) if (!path.startsWith(root + sep))
throw new Error("Image outside upload storage"); throw new Error("Image outside upload storage");
const info = await stat(path); const info = await stat(path);
if (!info.isFile() || info.size > 20 * 1024 * 1024) if (!info.isFile() || info.size <= 0)
throw new Error("Invalid image size"); throw new AiAssessmentError(null, null, 422, "Invalid image size");
if (info.size > 15 * 1024 * 1024)
throw new AiAssessmentError(null, null, 413, "Invalid image size");
const base = this.config.get<string>("AI_DAMAGE_URL"); const base = this.config.get<string>("AI_DAMAGE_URL");
if (!base) throw new Error("AI_DAMAGE_URL is required"); if (!base) throw new Error("AI_DAMAGE_URL is required");
const url = new URL( const url = new URL("/api/v1/assessments", base);
"pipeline/detect_parts_with_damages",
base.replace(/\/?$/, "/"),
);
for (const option of [
"side",
"segments",
"bounding_box",
"severity",
"confidence",
])
url.searchParams.set(option, "true");
const form = new FormData(); const form = new FormData();
const stream = createReadStream(path); const stream = createReadStream(path);
form.append("images", stream, { form.append("images", stream, {
@@ -166,11 +165,24 @@ export class AiService implements OnModuleInit, OnModuleDestroy {
headers: form.getHeaders(), headers: form.getHeaders(),
timeout: this.timeout, timeout: this.timeout,
signal, signal,
maxBodyLength: 21 * 1024 * 1024, maxBodyLength: 16 * 1024 * 1024,
maxContentLength: 2 * 1024 * 1024, maxContentLength: 2 * 1024 * 1024,
maxRedirects: 0, maxRedirects: 0,
}); });
return normalizeAiResult(data); return normalizeAiResult(data);
} catch (error) {
if (axios.isAxiosError(error) && error.response?.data?.error) {
const detail = error.response.data.error;
const safeText = (value: unknown) =>
typeof value === "string" ? value.slice(0, 500) : null;
throw new AiAssessmentError(
safeText(detail.code),
safeText(detail.request_id),
error.response.status,
safeText(detail.message) ?? undefined,
);
}
throw error;
} finally { } finally {
stream.destroy(); stream.destroy();
} }
@@ -210,11 +222,20 @@ export class AiService implements OnModuleInit, OnModuleDestroy {
const result = await this.aiRequestImage(job, this.abort.signal); const result = await this.aiRequestImage(job, this.abort.signal);
await this.jobs.updateOne(owned, { await this.jobs.updateOne(owned, {
$set: { status: "completed", result, completedAt: new Date() }, $set: { status: "completed", result, completedAt: new Date() },
$unset: { error: 1, leaseUntil: 1, leaseToken: 1 }, $unset: {
error: 1,
errorCode: 1,
errorRequestId: 1,
leaseUntil: 1,
leaseToken: 1,
},
}); });
} catch (error) { } catch (error) {
if (this.stopping) return; // Leave lease for another process after shutdown. if (this.stopping) return; // Leave lease for another process after shutdown.
const status = (error as any)?.response?.status; const providerError =
error instanceof AiAssessmentError ? error : undefined;
const status =
providerError?.httpStatus ?? (error as any)?.response?.status;
const terminal = const terminal =
job.attempts >= 3 || job.attempts >= 3 ||
[400, 401, 403, 404, 413, 415, 422].includes(status); [400, 401, 403, 404, 413, 415, 422].includes(status);
@@ -222,19 +243,33 @@ export class AiService implements OnModuleInit, OnModuleDestroy {
$set: { $set: {
status: terminal ? "failed" : "queued", status: terminal ? "failed" : "queued",
error: error:
status === 400 status === 413
? "خودرو در تصویر تشخیص داده نشد." ? "حجم تصویر برای تحلیل باید حداکثر ۱۵ مگابایت باشد."
: status === 422 || status === 415 : status === 400
? "سرویس هوش مصنوعی این تصویر را نپذیرفت؛ یک تصویر JPEG واضح بارگذاری کنید." ? "سرویس هوش مصنوعی درخواست تحلیل این تصویر را نپذیرفت."
: "تحلیل تصویر انجام نشد. دوباره تلاش کنید.", : status === 422 || status === 415
? "سرویس هوش مصنوعی این تصویر را نپذیرفت؛ یک تصویر JPEG واضح بارگذاری کنید."
: "تحلیل تصویر انجام نشد. دوباره تلاش کنید.",
...(providerError?.code ? { errorCode: providerError.code } : {}),
...(providerError?.requestId
? { errorRequestId: providerError.requestId }
: {}),
nextAttemptAt: new Date( nextAttemptAt: new Date(
Date.now() + 30000 * 2 ** Math.min(job.attempts - 1, 3), Date.now() + 30000 * 2 ** Math.min(job.attempts - 1, 3),
), ),
}, },
$unset: { leaseUntil: 1, leaseToken: 1 }, $unset: {
leaseUntil: 1,
leaseToken: 1,
...(!providerError?.code ? { errorCode: 1 } : {}),
...(!providerError?.requestId ? { errorRequestId: 1 } : {}),
},
}); });
this.logger.warn( this.logger.warn(
`AI analysis failed (${status ?? "network/response"}); ${terminal ? "manual retry available" : "retry queued"}.`, `AI analysis failed (${status ?? "network/response"}); ${terminal ? "manual retry available" : "retry queued"}.` +
(providerError
? ` ${JSON.stringify({ code: providerError.code, requestId: providerError.requestId })}`
: ""),
); );
} }
} catch { } catch {