Skip to content

Instantly share code, notes, and snippets.

@akimabs
Created February 21, 2023 04:16
Show Gist options
  • Save akimabs/92e50712e96cb6f0e4a6ca42ba81e580 to your computer and use it in GitHub Desktop.
Save akimabs/92e50712e96cb6f0e4a6ca42ba81e580 to your computer and use it in GitHub Desktop.
ocr tesseract
import { HttpStatus, Injectable } from '@nestjs/common';
import { StatusMessage } from 'src/filters/message.constant';
import { Response } from 'src/models/response.model';
import { createWorker } from 'tesseract.js';
import { ResultFindTotalPrice } from './images';
import * as fs from 'fs';
require('dotenv').config();
@Injectable()
export class ImagesService {
async upload(files: Array<Express.Multer.File>) {
const { URL } = process.env;
const worker = createWorker({});
await worker.load();
await worker.loadLanguage('ind');
await worker.initialize('ind');
const {
data: { text },
} = await worker.recognize(`${URL}${files[0]?.filename}`);
await worker.terminate();
const findTotalPrice = (text: string): ResultFindTotalPrice => {
const result: ResultFindTotalPrice = {
isFoundTotalPrice: false,
totalPrice: 0,
};
const tempArray = text.split('\n');
let matchPrice = '';
tempArray.map((res) => {
if (res.toLowerCase().includes('total' || 'total harga')) {
matchPrice = res;
}
});
if (matchPrice) {
const totalValue = matchPrice
.toLowerCase()
.replace(/([,.])\s/g, '')
.split('total')[1];
result.isFoundTotalPrice = true;
result.totalPrice = Number(totalValue);
} else {
result.isFoundTotalPrice = false;
result.totalPrice = 0;
}
return result;
};
if (findTotalPrice(text).isFoundTotalPrice) {
return new Response(
StatusMessage.SUCCESS_FIND_TOTAL_PRICE,
HttpStatus.OK,
findTotalPrice(text),
);
} else {
const path = `./public/img/${files[0]?.filename}`;
fs.unlink(path, (err) => {
console.log(err);
});
return new Response(
StatusMessage.NO_DATA_TOTAL_PRICE,
HttpStatus.NO_CONTENT,
{},
);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment