목적 : 이미지에서 텍스트를 추출 하고, 그것을 영문으로 번역한 산출물을 얻는다.
아래의 작업개요는 google cloud OCR 튜토리얼 공식 문서를 기반으로 함.
https://cloud.google.com/functions/docs/tutorials/ocr
google cloud 계정 생성, 새 프로젝트 생성 (처음에 90일간은 무료로 사용가능함.)
API 추가
서비스 계정 키 발급 → 키 만들기 누르고 생성하고 json 선택 → json 파일 다운로드 됨.
⇒ json 파일 path로 환경변수 설정 함.
사용자 인증정보 세팅
환경변수 설정
코드를 사용 (필자는 이 방법으로 진행)
project library 설치
npm install @google-cloud/pubsub @google-cloud/storage @google-cloud/translate @google-cloud/vision
// 코드로 계정인증 하는 방법 사용
const projectId = '프로젝트 아이디'
const keyFilename ='key 포함한 json 파일 path' // app 경로를 기본으로 함. ex> './' 접근시, 바로 app root로 접근
const {Storage} = require('@google-cloud/storage');
const storage = new Storage({ projectId, keyFilename });
const createBucket = async function(){
const bucketName = '버킷 이름';
await storage.createBucket(bucketName);
console.log(`Bucket ${bucketName} created.`);
}
const getBucket = async function(){
const [buckets] = await storage.getBuckets();
console.log('버킷 가져오기 성공', buckets);
}
const getFiles = async function(){
const bucketName = '버킷 이름';
const [files] = storage.bucket(bucketName).getFiles();
console.log('버킷 파일 가져오기 성공', files);
}
const Vision = require('@google-cloud/vision');
// 코드로 계정인증 하는 방법 사용
const projectId = '프로젝트 아이디'
const keyFilename ='key 포함한 json 파일 path' // app 경로를 기본으로 함. ex> './' 접근시, 바로 app root로 접근
const vision = new Vision.ImageAnnotatorClient({ projectId, keyFilename });
const detectText = async (bucketName, filename) => {
console.log(`Looking for text in image ${filename}`);
if(bucketName){
//1-1. bucket에서 파일가져와서 적용
[textDetections] = await vision.textDetection(
`gs://${bucketName}/${filename}`
);
}else{
//1-2. local에서 파일가져와서 적용
[textDetections] = await vision.textDetection(filename);
}
const [annotation] = textDetections.textAnnotations;
const text = annotation ? annotation.description : '';
console.log('Extracted text from image:', text);
let [translateDetection] = await translate.detect(text);
if (Array.isArray(translateDetection)) {
[translateDetection] = translateDetection;
}
console.log(
`Detected language "${translateDetection.language}" for ${filename}`
);
const messageData = {
text: text,
filename: filename,
lang: 'en',
return messageData
};
const processImage = async event => {
const {bucket, name} = event;
if (!bucket) {
throw new Error(
'Bucket not provided. Make sure you have a "bucket" property in your request'
);
}
if (!name) {
throw new Error(
'Filename not provided. Make sure you have a "name" property in your request'
);
}
return await detectText(bucket, name);
console.log(`File ${name} processed.`);
};
///// 호출 함수 //////
callFunc = ()=>{
const bucketName ='버킷이름',
fileName ='파일경로 or 버킷내에 파일 경로 ';
const data = {
bucket: bucketName, // bucket 이 없는 경우 local에서 이미지가져와 적용
name: fileName
};
const process = await processImage(data);
console.log("process",process); // process.text 로 추출 된 text 확인 가능
}
// 코드로 계정인증 하는 방법 사용
const projectId = '프로젝트 아이디'
const keyFilename ='key 포함한 json 파일 path' // app 경로를 기본으로 함. ex> './' 접근시, 바로 app root로 접근
const {Translate} = require('@google-cloud/translate').v2;
const translate = new Translate({ projectId, keyFilename }));
exports.translateText = async event => {
const pubsubData = event.data;
const jsonStr = Buffer.from(pubsubData, 'base64').toString();
const {text, filename, lang} = JSON.parse(jsonStr);
if (!text) {
// throw new Error(
// 'Text not provided. Make sure you have a "text" property in your request'
// );
return {
text: text,
filename: filename,
lang: lang,
};
}
if (!filename) {
throw new Error(
'Filename not provided. Make sure you have a "filename" property in your request'
);
}
if (!lang) {
throw new Error(
'Language not provided. Make sure you have a "lang" property in your request'
);
}
console.log(`Translating text into ${lang}`);
const [translation] = await translate.translate(text, lang);
console.log('Translated text:', translation);
const messageData = {
text: translation,
filename: filename,
lang: lang,
};
console.log(messageData);
return messageData
// await publishResult(process.env.RESULT_TOPIC, messageData);
// await publishResult('ocr-result', messageData);
console.log(`Text translated to ${lang}`);
};
///// 호출 함수 //////
callFunc = ()=>{
const data = {
data: Buffer.from(
JSON.stringify({
text:'번역하려고 하는 문자',
filename:'파일경로 or 버킷내에 파일 경로',
lang:'언어(~로 번역)', //ex) 영문 = 'en'
})
).toString('base64'),
};
const translate= await translateText(data);
console.log("translated",translate); // translate.text 로 번역 된 text 확인 가능
}
// 코드로 계정인증 하는 방법 사용
const projectId = '프로젝트 아이디'
const keyFilename ='key 포함한 json 파일 path' // app 경로를 기본으로 함. ex> './' 접근시, 바로 app root로 접근
const {Storage} = require('@google-cloud/storage');
const storage = new Storage({ projectId, keyFilename });
const renameImageForSave = (filename, lang) => {
return `${filename}_to_${lang}.txt`;
};
exports.saveResult = async event => {
const pubsubData = event.data;
const jsonStr = Buffer.from(pubsubData, 'base64').toString();
const {text, filename, lang} = JSON.parse(jsonStr);
if (!text) {
throw new Error(
'Text not provided. Make sure you have a "text" property in your request'
);
}
if (!filename) {
throw new Error(
'Filename not provided. Make sure you have a "filename" property in your request'
);
}
if (!lang) {
throw new Error(
'Language not provided. Make sure you have a "lang" property in your request'
);
}
console.log(`Received request to save file ${filename}`);
const bucketName = event.result_bucket;
// const bucketName = process.env.RESULT_BUCKET;
const newFilename = renameImageForSave(filename, lang);
const file = storage.bucket(bucketName).file(newFilename);
console.log(`Saving result to ${newFilename} in bucket ${bucketName}`);
await file.save(text);
console.log('File saved.');
};
///// 호출 함수 //////
callFunc = ()=>{
const data = {
data: Buffer.from(
JSON.stringify({
text:'번역하려고 하는 문자',
filename:'파일경로 or 버킷내에 파일 경로',
lang:'언어(~로 번역)', //ex) 영문 = 'en'
})
,result_bucket: '결과 저장할 버킷 이름' // 버킷은 미리 생성되어 있어야함.
).toString('base64'),
};
const translate= await translateText(data);
console.log("translated",translate); // translate.text 로 번역 된 text 확인 가능
}
https://cloud.google.com/functions/docs/tutorials/ocr
https://cloud.google.com/docs/authentication/production?hl=ko
https://davelogs.tistory.com/36
https://cloud.google.com/storage/docs/listing-buckets?hl=ko#code-samples-list-buckets
https://cloud.google.com/vision/docs/samples/vision-text-detection
https://cloud.google.com/storage/docs/downloading-objects?hl=ko#storage-download-object-nodejs