-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathocr.service.ts
More file actions
199 lines (177 loc) · 6.24 KB
/
Copy pathocr.service.ts
File metadata and controls
199 lines (177 loc) · 6.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
import { HttpService } from "@nestjs/axios";
import { Injectable, Logger, NotFoundException } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { readFile } from "fs/promises";
import { join } from "path";
import { lastValueFrom } from "rxjs";
import { DatabaseService } from "@/database/database.service";
import { DocumentStatus } from "@/generated/enums";
import { AnalysisResponse, AnalysisResult } from "@/ocr/azureTypes";
export interface OcrRequestResponse {
status: DocumentStatus;
apimRequestId?: string;
error?: Error;
}
@Injectable()
export class OcrService {
private readonly logger = new Logger(OcrService.name);
private readonly azureModelId: string;
private readonly azureEndpoint: string;
private readonly azureApiKey: string;
constructor(
private configService: ConfigService,
private databaseService: DatabaseService,
private httpService: HttpService,
) {
this.azureEndpoint = this.configService.get<string>(
"AZURE_DOCUMENT_INTELLIGENCE_ENDPOINT",
);
this.azureApiKey = this.configService.get<string>(
"AZURE_DOCUMENT_INTELLIGENCE_API_KEY",
);
this.azureModelId = "prebuilt-layout";
if (!this.azureEndpoint || !this.azureApiKey) {
const azureConfigMessage =
"Azure Document Intelligence credentials not configured.";
this.logger.warn(azureConfigMessage);
throw Error(azureConfigMessage);
}
}
/**
* Sends a document to Azure for OCR processing.
* @param documentId ID from documents table
* @returns New status of document and request ID from Azure.
*/
async requestOcr(documentId: string): Promise<OcrRequestResponse> {
this.logger.debug(`Document ID: ${documentId || "N/A"}`);
// Find filepath of document
const document = await this.databaseService.findDocument(documentId);
if (document == null) {
throw new NotFoundException(
`Entry for document with ID ${documentId} not found.`,
);
}
try {
// Resolve stored relative path to absolute (we only store relative paths)
const filePath = join(process.cwd(), document.file_path);
const fileBuffer = await readFile(filePath);
if (fileBuffer == null) throw Error("File not found.");
this.logger.debug(`File size: ${fileBuffer.length} bytes`);
// Send file to Azure for OCR
const azureResponse = await lastValueFrom(
this.httpService.post(
`${this.azureEndpoint}/documentModels/${this.azureModelId}:analyze?api-version=2024-11-30&features=keyValuePairs`,
{
base64Source: fileBuffer.toString("base64"),
},
{
headers: {
"api-key": this.azureApiKey,
},
},
),
);
if (azureResponse.status != 202) {
throw Error("Error sending document to Azure");
}
const updateResult = await this.databaseService.updateDocument(
documentId,
{
apim_request_id: azureResponse.headers["apim-request-id"], // docPoller.headers["apim-request-id"],
status: DocumentStatus.ongoing_ocr,
},
);
// Return the apim request ID
return {
apimRequestId: updateResult.apim_request_id,
status: updateResult.status,
};
} catch (error) {
this.logger.error(`Error processing document: ${error.message}`);
this.logger.error(`Stack: ${error.stack}`);
if (document != null) {
await this.databaseService.updateDocument(documentId, {
status: DocumentStatus.failed,
});
}
return {
status: DocumentStatus.failed,
error: error.message,
};
}
}
/**
* Retrieves the results of an Azure OCR request.
* @param documentId ID from documents table
* @returns The AnalysisResult of OCR processing.
*/
async retrieveOcrResults(documentId: string): Promise<AnalysisResult> {
// Get apim ID of document
const document = await this.databaseService.findDocument(documentId);
if (document == null) {
throw new NotFoundException(
`Entry for document with ID ${documentId} not found.`,
);
}
const apim = document.apim_request_id;
// Potentially was never sent or failed to send
if (
document.status == DocumentStatus.pre_ocr ||
document.status == DocumentStatus.failed ||
apim == null
) {
throw Error(`Document ID ${documentId} has not yet been sent for OCR.`);
}
// Get OCR results from Azure
const azureResponse = await lastValueFrom(
this.httpService.get(
`${this.azureEndpoint}/documentModels/${this.azureModelId}/analyzeResults/${apim}?api-version=2024-11-30`,
{
headers: {
"api-key": this.azureApiKey,
},
},
),
);
if (azureResponse.status != 200) {
throw Error(
`Failed to retrieve OCR results for document ID ${documentId}`,
);
}
const analysisResponse: AnalysisResponse = azureResponse.data;
this.logger.debug(`Azure response status: ${analysisResponse.status}`);
this.logger.debug(
`Azure response created: ${analysisResponse.createdDateTime}`,
);
this.logger.debug(
`Azure response updated: ${analysisResponse.lastUpdatedDateTime}`,
);
// Log the full response for debugging
// this.logger.debug(`Full Azure response: ${JSON.stringify(analysisResponse, null, 2)}`);
// If status is "running", processing is not complete yet
if (analysisResponse.status === "running") {
this.logger.debug(
`OCR processing still running for document ${documentId}, will retry later`,
);
return null; // Indicate processing not complete
}
const analysisResult = analysisResponse.analyzeResult;
if (!analysisResult) {
throw new Error(
`No analyzeResult in Azure response for document ${documentId} (status: ${analysisResponse.status})`,
);
}
this.logger.debug(
`Analysis result content length: ${analysisResult.content?.length || 0}`,
);
this.logger.debug(
`Analysis result pages: ${analysisResult.pages?.length || 0}`,
);
// Update OCR results table
this.databaseService.upsertOcrResult({
documentId,
analysisResponse,
});
return analysisResult;
}
}