public async Task<JsonDocument> AnalyzeDocumentAsync(Stream documentStream)
{
HttpRequestMessage analyzeRequest = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri(
$"{_endpoint}/formrecognizer/documentModels/prebuilt-receipt:analyze?api-version={_apiversion}"
),
Content = new StreamContent(documentStream)
};
analyzeRequest.Headers.Add("Ocp-Apim-Subscription-Key", _apiKey);
analyzeRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
HttpResponseMessage analyzeResponse = await _httpClient.SendAsync(analyzeRequest);
// Check if the response is successful
analyzeResponse.EnsureSuccessStatusCode();
if (!analyzeResponse.Headers.Contains("apim-request-id"))
{
throw new InvalidOperationException(
"Response does not contain the header 'apim-request-id'."
);
}
string requestId = analyzeResponse.Headers.GetValues("apim-request-id").FirstOrDefault() ?? string.Empty;
//===============================================================
string status = "running";
JsonDocument result = null;
while (status == "running" || status == "notStarted")
{
HttpRequestMessage resultRequest = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri($"{_endpoint}/formrecognizer/documentModels/prebuilt-receipt/analyzeResults/{requestId}?api-version={_apiversion}")
};
resultRequest.Headers.Add("Ocp-Apim-Subscription-Key", _apiKey);
HttpResponseMessage resultResponse = await _httpClient.SendAsync(resultRequest);
resultResponse.EnsureSuccessStatusCode();
String resultJson = await resultResponse.Content.ReadAsStringAsync();
result = JsonDocument.Parse(resultJson);
status = result.RootElement.GetProperty("status").GetString();
if (status == "running")
{
// Wait for a specific interval before polling again
await Task.Delay(TimeSpan.FromSeconds(1));
}
if (status == "failed")
{
throw new Exception("Document analysis failed.");
}
}
if ((result != null) && (status == "succeeded"))
{
return result;
}
else
{
throw new Exception("Document analysis failed.");
}
}
ที่นี้เราจะเห็นว่าผมมีดัก Status running / failed / succeeded อันนี้ผมไปดูจาก API Doc ของมัน ส่วน AnalyzeOperation
program.cs อันนี้ register service / controller ครับ
ลองยิง REST API ตอนนี้ผลลัพธ์ที่ได้จะมาเยอะๆ เหมือนกันที่ลองใน Blog ก่อนหน้า อันนี้ง่ายขึ้นด้วย ไม่ต้องมาแปลง base64 แล้ว กำหนด REST + เลือก Body เป็น From File ได้เลย
public async Task<ExtractReceiptDTO> ExtractReceipt(Stream documentStream)
{
JsonDocument result = await AnalyzeDocumentAsync(documentStream);
// Extract the documents property and count the number of documents
JsonElement documents = result.RootElement.GetProperty("analyzeResult").GetProperty("documents");
if (documents.GetArrayLength() == 0)
{
throw new Exception("Document analysis failed.");
}
//result.Documents can contain multiple documents, but we only get first one in this example
JsonElement fields = result.RootElement
.GetProperty("analyzeResult")
.GetProperty("documents")[0].GetProperty("fields");
// Extract the values
string merchantName = fields.GetProperty("MerchantName").GetProperty("valueString").GetString();
double total = fields.GetProperty("Total").GetProperty("valueNumber").GetDouble();
double totalTax = fields.GetProperty("TotalTax").GetProperty("valueNumber").GetDouble();
DateTime transactionDate = fields.GetProperty("TransactionDate").GetProperty("valueDate").GetDateTime();
return new ExtractReceiptDTO
{
MerchantName = merchantName,
Total = total,
TotalTax = totalTax,
TransactionDate = transactionDate
};
}
พอได้ตรงนี้แล้วหลายคนน่าจะมี Idea ทำต่อครับ อย่างผมเอาข้อมูลตรงนี้เก็บลง DB / Spreadsheet ทำข้อมูลสรุปได้แล้วครับ ผมทำใช้เองมาพักนึงเหมือนกันครับ เดี๋ยวค่อยมาเขียน Blog ขยายเรื่อยๆ ^__^
To provide the best experiences, we use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional
Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes.The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.