google vision apiから同期のリクエストを投げてレスポンスがundefinedで返ってしまいます
Q&A
Closed
解決したいこと
npmの"sync-fetch"モジュールとgoogle vision apiを使用し、Google Cloud Visionに対しリクエストを行った場合、同期(sync)レスポンスが"undefined"で返ってきてしまいます。(非同期(async)では画像解析結果のレスポンスが返ってきます)
期待結果としては、syncレスポンスでも、asyncレスポンスと同様に、画像の解析結果のレスポンスが返ってほしいです。
発生している問題・エラー
npmのsync-fetchを使っていて、google vision apiから同期のリクエストし投げていますがレスポンスがundefinedで返ってしまいます。(非同期のリクエストは問題ないです)
sync -------------------------------------------------
undefined
async ------------------------------------------------
{"labelAnnotations":[{"description":"Building","score":"96.2%"},{"description":"Infrastructure","score":"90.0%"},{"description":"Lighting","score":"87.0%"},{"description":"Tree","score":"86.6%"},{"description":"Urban design","score":"85.4%"},{"description":"Plant","score":"83.4%"},{"description":"Thoroughfare","score":"83.1%"},{"description":"Line","score":"81.6%"},{"description":"Neighbourhood","score":"81.4%"},{"description":"City","score":"80.4%"}]}
構成図
├── node_modules
├── package.json
├── images
│ └── shibuya-scranble.jpg
├── index.js
└── app
└── vision.js
shibuya-scranble.jpg:https://imgur.com/sMFvicA
該当するソースコード
index.js
(async function () {
const vision = require('./app/vision.js')
const content = './images/shibuya-scranble.jpg'
const result = await vision.client(content)
console.log("async ------------------------------------------------")
console.log(result)
})();
const vision = require('./app/vision.js')
const content = './images/shibuya-scranble.jpg'
console.log("sync -------------------------------------------------")
console.log(vision.syncfetch(content))
vision.js
//Node.jsのモジュール
const vision = require('@google-cloud/vision')
const fs = require('fs')
const syncfetch = require('sync-fetch')
const { Base64 } = require('js-base64')
const { execSync } = require('child_process')
const api = {
//非同期リクエスト
client: async (content) => {
try {
const client = new vision.ImageAnnotatorClient()
const [labelDetection] = await client.labelDetection(content)
const labels = labelDetection.labelAnnotations
let labelAnnotations = [];
labels.forEach(label => {
labelAnnotations.push({
"description": label.description,
"score": parseFloat(label.score * 100).toFixed(1)+"%"
})
})
const response_text = {
"labelAnnotations": labelAnnotations,
}
//非同期responseを受け取る
return JSON.stringify(response_text)
} catch (err) {
throw new Error(err)
}
},
//同期リクエスト
syncfetch: (content) => {
const image = Base64.encode(fs.readFileSync(content))
const req = {
"requests": [
{
"image": {
"content": image
},
"features": [
{
"type": "LABEL_DETECTION"
}
]
}
]
}
const stdout = execSync('gcloud auth application-default print-access-token')
const token = stdout.toString().trim()
const response = syncfetch('https://vision.googleapis.com/v1/images:annotate', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(req)
})
//同期responseを受け取る
const json = response.json()
return JSON.stringify(json.responses)
}
}
module.exports = api
0