Changed AI to new version

This commit is contained in:
SepehrYahyaee
2026-11-03 15:58:23 +03:30
parent c5aa0f925e
commit e75a144e50
11 changed files with 4349 additions and 61 deletions
+2
View File
@@ -19,6 +19,8 @@ export class AiJob {
@Prop() leaseToken?: string;
@Prop() completedAt?: Date;
@Prop() error?: string;
@Prop() errorCode?: string;
@Prop() errorRequestId?: string;
@Prop({ type: MongoSchema.Types.Mixed }) result?: AiResult;
}
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";
const response = () => ({
@@ -26,6 +26,154 @@ const response = () => ({
});
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", () => {
const result = normalizeAiResult(response());
expect(result.parts).toHaveLength(2);
+163
View File
@@ -5,18 +5,181 @@ export interface AiPart {
side: string | null;
carSide: string | 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 {
parts: AiPart[];
report: 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 =>
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. */
export function normalizeAiResult(value: unknown): AiResult {
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;
if (
!report ||
+63 -14
View File
@@ -1,6 +1,7 @@
import { ConfigService } from "@nestjs/config";
import { AiService, aiImageKey } from "./ai.service";
import { AiJobSchema } from "./ai-job.schema";
import { AiAssessmentError } from "./ai-result";
const image = { path: "files/part.jpg", label: "گلگیر" };
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();
claimJob(jobs);
jest
@@ -141,7 +142,32 @@ describe("durable AI jobs", () => {
expect.objectContaining({
$set: expect.objectContaining({
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", () => {
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 { resolve, join } = await import("node:path");
const axios = (await import("axios")).default;
@@ -214,15 +240,8 @@ describe("AI multipart transport", () => {
.spyOn(axios, "post")
.mockImplementation(async (url, form: any, config) => {
const parsed = new URL(String(url));
expect(parsed.pathname).toBe("/pipeline/detect_parts_with_damages");
for (const option of [
"side",
"segments",
"bounding_box",
"severity",
"confidence",
])
expect(parsed.searchParams.get(option)).toBe("true");
expect(parsed.pathname).toBe("/api/v1/assessments");
expect(parsed.search).toBe("");
expect(config?.headers?.["content-type"]).toMatch(
/^multipart\/form-data; boundary=/,
);
@@ -243,7 +262,9 @@ describe("AI multipart transport", () => {
expect(body.includes(bytes)).toBe(true);
return {
data: {
distinct_damaged_parts_report: { parts: [], report: "گزارش" },
request_id: "req-123",
damaged_parts: [],
internal_damages: [],
case_report: "گزارش کامل",
},
} as any;
@@ -252,11 +273,39 @@ describe("AI multipart transport", () => {
const { service } = setup();
await expect(
service.aiRequestImage({ path: file, fileName: "test.jpg" }),
).resolves.toMatchObject({ parts: [], report: "گزارش" });
).resolves.toMatchObject({ parts: [], requestId: "req-123" });
await expect(
service.aiRequestImage({ path: "/etc/hosts" }),
).rejects.toThrow("outside upload storage");
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 {
pathSpy.mockRestore();
post.mockRestore();
+61 -26
View File
@@ -14,7 +14,7 @@ import { Model } from "mongoose";
import axios from "axios";
import FormData = require("form-data");
import { AiJob } from "./ai-job.schema";
import { normalizeAiResult } from "./ai-result";
import { AiAssessmentError, normalizeAiResult } from "./ai-result";
import { buildFileLink } from "src/helpers/urlCreator";
export interface AiCapture {
@@ -110,6 +110,8 @@ export class AiService implements OnModuleInit, OnModuleDestroy {
attempts: job?.attempts ?? 0,
completedAt: job?.completedAt,
error: job?.error,
errorCode: job?.errorCode,
errorRequestId: job?.errorRequestId,
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() },
$unset: { error: 1, leaseToken: 1, leaseUntil: 1 },
$unset: {
error: 1,
errorCode: 1,
errorRequestId: 1,
leaseToken: 1,
leaseUntil: 1,
},
},
);
return this.list(claimId, images);
@@ -139,22 +147,13 @@ export class AiService implements OnModuleInit, OnModuleDestroy {
if (!path.startsWith(root + sep))
throw new Error("Image outside upload storage");
const info = await stat(path);
if (!info.isFile() || info.size > 20 * 1024 * 1024)
throw new Error("Invalid image size");
if (!info.isFile() || info.size <= 0)
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");
if (!base) throw new Error("AI_DAMAGE_URL is required");
const url = new URL(
"pipeline/detect_parts_with_damages",
base.replace(/\/?$/, "/"),
);
for (const option of [
"side",
"segments",
"bounding_box",
"severity",
"confidence",
])
url.searchParams.set(option, "true");
const url = new URL("/api/v1/assessments", base);
const form = new FormData();
const stream = createReadStream(path);
form.append("images", stream, {
@@ -166,11 +165,24 @@ export class AiService implements OnModuleInit, OnModuleDestroy {
headers: form.getHeaders(),
timeout: this.timeout,
signal,
maxBodyLength: 21 * 1024 * 1024,
maxBodyLength: 16 * 1024 * 1024,
maxContentLength: 2 * 1024 * 1024,
maxRedirects: 0,
});
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 {
stream.destroy();
}
@@ -210,11 +222,20 @@ export class AiService implements OnModuleInit, OnModuleDestroy {
const result = await this.aiRequestImage(job, this.abort.signal);
await this.jobs.updateOne(owned, {
$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) {
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 =
job.attempts >= 3 ||
[400, 401, 403, 404, 413, 415, 422].includes(status);
@@ -222,19 +243,33 @@ export class AiService implements OnModuleInit, OnModuleDestroy {
$set: {
status: terminal ? "failed" : "queued",
error:
status === 400
? "خودرو در تصویر تشخیص داده نشد."
: status === 422 || status === 415
? "سرویس هوش مصنوعی این تصویر را نپذیرفت؛ یک تصویر JPEG واضح بارگذاری کنید."
: "تحلیل تصویر انجام نشد. دوباره تلاش کنید.",
status === 413
? "حجم تصویر برای تحلیل باید حداکثر ۱۵ مگابایت باشد."
: status === 400
? "سرویس هوش مصنوعی درخواست تحلیل این تصویر را نپذیرفت."
: status === 422 || status === 415
? "سرویس هوش مصنوعی این تصویر را نپذیرفت؛ یک تصویر JPEG واضح بارگذاری کنید."
: "تحلیل تصویر انجام نشد. دوباره تلاش کنید.",
...(providerError?.code ? { errorCode: providerError.code } : {}),
...(providerError?.requestId
? { errorRequestId: providerError.requestId }
: {}),
nextAttemptAt: new Date(
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(
`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 {