Added AI damage helper

This commit is contained in:
SepehrYahyaee
2026-10-03 16:38:48 +03:30
parent 18ccfa81e4
commit 2f92766689
22 changed files with 1085 additions and 442 deletions
+220 -175
View File
@@ -1,204 +1,249 @@
import { createReadStream, existsSync } from "node:fs";
import { join } from "node:path";
import { createHash, randomUUID } from "node:crypto";
import { createReadStream } from "node:fs";
import { realpath, stat } from "node:fs/promises";
import { basename, resolve, sep } from "node:path";
import {
HttpException,
HttpStatus,
Injectable,
Logger,
OnModuleDestroy,
OnModuleInit,
} from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { AxiosRequestConfig } from "axios"; // TODO: Change all axios usages to HttpModule
import { InjectModel } from "@nestjs/mongoose";
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 { buildFileLink } from "src/helpers/urlCreator";
export interface AiCapture {
path: string;
fileName?: string;
label?: string;
}
export const aiImageKey = (path: string) =>
createHash("sha256").update(resolve(path)).digest("hex");
@Injectable()
export class AiService implements OnModuleInit {
private apiKey: string;
private accessToken: string = null;
export class AiService implements OnModuleInit, OnModuleDestroy {
private readonly logger = new Logger(AiService.name);
private timer?: NodeJS.Timeout;
private busy = false;
private stopping = false;
private abort?: AbortController;
constructor(
private readonly config: ConfigService,
@InjectModel(AiJob.name) private readonly jobs: Model<AiJob>,
) {}
// These configurations are for authentication and getting the API key.
private readonly loginOptions: AxiosRequestConfig = {
method: "POST",
headers: { "Content-Type": "application/json" },
url: `${this.configService.get<string>("AI_URL_V2")}/auth/login`,
data: {
username: this.configService.get<string>("AI_USERNAME"),
password: this.configService.get<string>("AI_PASSWORD"),
},
timeout: 1000, // TODO: Make this ENV
};
constructor(private readonly configService: ConfigService) {}
private get profileOptions(): AxiosRequestConfig {
return {
method: "GET",
url: `${this.configService.get<string>("AI_URL_V2")}/auth/profile`,
headers: {
Authorization: `Bearer ${this.accessToken}`,
},
};
get enabled() {
return this.config.get<string>("AI_DAMAGE_ENABLED") === "true";
}
private get timeout() {
return Math.min(
600000,
Math.max(1000, Number(this.config.get("AI_DAMAGE_TIMEOUT_MS")) || 180000),
);
}
// This getter dynamically creates the base options for the image processing request.
private get imageProcessOptions(): AxiosRequestConfig {
return {
method: "POST",
url: `${process.env.AI_URL_V2}/services/car-damage/detector?version=ai-v7`,
headers: {
Authorization: `Bearer ${this.accessToken}`,
"gateway-api-key": `${this.apiKey}`,
},
};
onModuleInit() {
if (!this.enabled) return;
this.timer = setInterval(() => {
void this.work();
}, 5000);
this.timer.unref();
void this.work();
}
onModuleDestroy() {
this.stopping = true;
clearInterval(this.timer);
this.abort?.abort();
}
async onModuleInit() {
/** Only persist the job here; never wait for the AI in an upload request. */
async enqueue(claimId: string, image: AiCapture): Promise<void> {
if (!this.enabled || !image.path) return;
try {
const res = await this.login();
// if (res?.accessToken) {
// this.accessToken = res.accessToken;
// await this.getApiKey();
// }
await this.jobs.updateOne(
{ claimId, imageKey: aiImageKey(image.path) },
{
$setOnInsert: {
claimId,
imageKey: aiImageKey(image.path),
path: image.path,
fileName: image.fileName,
status: "queued",
attempts: 0,
nextAttemptAt: new Date(),
},
},
{ upsert: true },
);
} catch (error) {
// Don't prevent app startup if AI service is temporarily unavailable
// The service will attempt to re-authenticate when aiRequestImage is called
// Reset tokens so re-authentication will be attempted
this.accessToken = null;
this.apiKey = null;
// Concurrent duplicate uploads are already queued. A storage outage must not fail capture.
if ((error as any)?.code !== 11000)
this.logger.error(
"Could not persist AI job; expert review will retry scheduling.",
);
}
}
private async login() {
// const loginResponse = await axios.request(this.loginOptions);
// return loginResponse.data;
async list(claimId: string, images: AiCapture[]) {
// Older captures and jobs missed during a database outage are scheduled on review.
for (const image of images) await this.enqueue(claimId, image);
const keys = images.map((image) => aiImageKey(image.path));
const rows = await this.jobs
.find({ claimId, imageKey: { $in: keys } })
.lean();
const byKey = new Map(rows.map((row) => [row.imageKey, row]));
return {
enabled: this.enabled,
images: images.map((image) => {
const key = aiImageKey(image.path);
const job = byKey.get(key);
return {
imageKey: key,
label: image.label ?? "تصویر خسارت",
imageUrl: buildFileLink(image.path),
status: job?.status ?? (this.enabled ? "queued" : "disabled"),
attempts: job?.attempts ?? 0,
completedAt: job?.completedAt,
error: job?.error,
result: job?.status === "completed" ? job.result : undefined,
};
}),
};
}
private async getApiKey() {
// const profileResponse = await axios.request(this.profileOptions);
// this.apiKey = profileResponse.data.apiKey.key;
// return this.apiKey;
async retry(claimId: string, images: AiCapture[]) {
if (this.enabled)
await this.jobs.updateMany(
{
claimId,
imageKey: { $in: images.map((image) => aiImageKey(image.path)) },
status: "failed",
},
{
$set: { status: "queued", attempts: 0, nextAttemptAt: new Date() },
$unset: { error: 1, leaseToken: 1, leaseUntil: 1 },
},
);
return this.list(claimId, images);
}
public async aiRequestImage(file: {
path: string;
fileName?: string;
}): Promise<any> {
// Ensure authentication is set up
if (!this.accessToken || !this.apiKey) {
async aiRequestImage(file: AiCapture, signal?: AbortSignal) {
// Only local managed uploads; never fetch a supplied URL or arbitrary server file.
const root = await realpath(resolve("files"));
const path = await realpath(resolve(file.path));
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");
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 form = new FormData();
const stream = createReadStream(path);
form.append("images", stream, {
filename: file.fileName || basename(path),
knownLength: info.size,
});
try {
const { data } = await axios.post(url.toString(), form, {
headers: form.getHeaders(),
timeout: this.timeout,
signal,
maxBodyLength: 21 * 1024 * 1024,
maxContentLength: 2 * 1024 * 1024,
maxRedirects: 0,
});
return normalizeAiResult(data);
} finally {
stream.destroy();
}
}
/** Atomic leases make this safe across replicas and recover jobs after a restart. */
async work() {
if (!this.enabled || this.busy || this.stopping) return;
this.busy = true;
try {
const now = new Date();
const token = randomUUID();
const job = await this.jobs
.findOneAndUpdate(
{
$or: [
{ status: "queued", nextAttemptAt: { $lte: now } },
{ status: "processing", leaseUntil: { $lte: now } },
],
},
{
$set: {
status: "processing",
leaseToken: token,
leaseUntil: new Date(now.getTime() + this.timeout + 60000),
},
$inc: { attempts: 1 },
},
{ new: true, sort: { nextAttemptAt: 1 } },
)
.lean();
if (!job) return;
const owned = { _id: job._id, status: "processing", leaseToken: token };
try {
const res = await this.login();
// if (res?.accessToken) {
// this.accessToken = res.accessToken;
// await this.getApiKey();
// } else {
// throw new HttpException(
// "AI Service authentication failed",
// HttpStatus.UNAUTHORIZED,
// );
// }
if (job.attempts > 3) throw new Error("Retry limit reached");
this.abort = new AbortController();
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 },
});
} catch (error) {
throw new HttpException(
"AI Service authentication failed",
HttpStatus.UNAUTHORIZED,
if (this.stopping) return; // Leave lease for another process after shutdown.
const status = (error as any)?.response?.status;
const terminal =
job.attempts >= 3 ||
[400, 401, 403, 404, 413, 415, 422].includes(status);
await this.jobs.updateOne(owned, {
$set: {
status: terminal ? "failed" : "queued",
error:
status === 400
? "خودرو در تصویر تشخیص داده نشد."
: status === 422 || status === 415
? "سرویس هوش مصنوعی این تصویر را نپذیرفت؛ یک تصویر JPEG واضح بارگذاری کنید."
: "تحلیل تصویر انجام نشد. دوباره تلاش کنید.",
nextAttemptAt: new Date(
Date.now() + 30000 * 2 ** Math.min(job.attempts - 1, 3),
),
},
$unset: { leaseUntil: 1, leaseToken: 1 },
});
this.logger.warn(
`AI analysis failed (${status ?? "network/response"}); ${terminal ? "manual retry available" : "retry queued"}.`,
);
}
}
// Resolve relative paths to absolute paths
const filePath = file.path.startsWith("/")
? file.path
: join(process.cwd(), file.path.replace(/^\.\//, ""));
// Check if file exists
if (!existsSync(filePath)) {
throw new HttpException(
`File not found: ${file.path}`,
HttpStatus.NOT_FOUND,
);
}
// const form = new FormData();
const fileStream = createReadStream(filePath);
// Append file with filename if available
if (file.fileName) {
// form.append("images", fileStream, file.fileName);
} else {
// Extract filename from path if not provided
const pathParts = filePath.split("/");
const extractedFileName = pathParts[pathParts.length - 1];
// form.append("images", fileStream, extractedFileName);
}
try {
const requestHeaders = {
...this.imageProcessOptions.headers,
// ...form.getHeaders(),
};
const fs = require("fs");
const stats = fs.statSync(filePath);
// const response = await axios.request({
// ...this.imageProcessOptions,
// headers: requestHeaders,
// // data: form,
// maxContentLength: Infinity,
// maxBodyLength: Infinity,
// });
// Validate response structure
// if (!response.data) {
// throw new HttpException(
// "AI Service returned empty response",
// HttpStatus.BAD_GATEWAY,
// );
// }
// // Check for error in response first (AI service returns 201 with error in body)
// if (response.data.error) {
// throw new HttpException(
// `AI Service error: ${response.data.error}`,
// HttpStatus.BAD_GATEWAY,
// );
// }
// // Check for processed image (downloadLink)
// if (!response.data.downloadLink) {
// throw new HttpException(
// "AI Service did not return processed image (downloadLink missing)",
// HttpStatus.BAD_GATEWAY,
// );
// }
// return response.data;
} catch (er) {
// Determine error source
let errorSource = "UNKNOWN";
let errorMessage = er.message;
let errorDetails = "No error details available";
if (er.response) {
errorSource = "AI_SERVICE_RESPONSE";
errorMessage =
er.response?.data?.message ||
er.message ||
`HTTP ${er.response.status}`;
errorDetails = er.response?.data
? JSON.stringify(er.response.data, null, 2)
: `Status: ${er.response.status}, StatusText: ${er.response.statusText}`;
} else if (er.request) {
errorSource = "NETWORK_ERROR";
errorMessage = "Network error - AI service did not respond";
errorDetails = "Request was made but no response received";
} else {
errorSource = "REQUEST_SETUP_ERROR";
errorMessage = er.message || "Error setting up request";
}
// Re-throw with detailed error information
throw new HttpException(
`[${errorSource}] ${errorMessage}`,
er.response?.status || HttpStatus.INTERNAL_SERVER_ERROR,
} catch {
this.logger.error(
"AI worker storage unavailable; will retry on the next tick.",
);
} finally {
this.abort = undefined;
this.busy = false;
}
}
}