Я использую Google Cloud Video Intelligence для обнаружения текста. Теперь я хочу использовать его для транскрипции речи, поэтому я добавил функцию SPEECH_TRANSCRIPTION к TEXT_DETECTION, но ответ содержит результат только для одной функции, последней.
const gcsUri = 'gs://path-to-the-video-on-gcs'
const request = {
inputUri: gcsUri,
features: ['TEXT_DETECTION', 'SPEECH_TRANSCRIPTION'],
};
// Detects text in a video
const [operation] = await video.annotateVideo(request);
const [operationResult] = await operation.promise();
const annotationResult = operationResult.annotationResults[0]
const textAnnotations = annotationResult.textAnnotations
const speechTranscriptions = annotationResult.speechTranscriptions
console.info(textAnnotations) // --> []
console.info(speechTranscriptions) // --> [{...}]
Является ли это случаем, когда аннотация выполняется только для одного объекта за раз?
Аннотирование будет выполнено для обоих объектов. Ниже приведен пример кода.
const videoIntelligence = require('@google-cloud/video-intelligence');
const client = new videoIntelligence.VideoIntelligenceServiceClient();
const gcsUri = 'gs://cloud-samples-data/video/JaneGoodall.mp4';
async function analyzeVideoTranscript() {
const videoContext = {
speechTranscriptionConfig: {
languageCode: 'en-US',
enableAutomaticPunctuation: true,
},
};
const request = {
inputUri: gcsUri,
features: ['TEXT_DETECTION','SPEECH_TRANSCRIPTION'],
videoContext: videoContext,
};
const [operation] = await client.annotateVideo(request);
const results = await operation.promise();
console.info('Waiting for operation to complete...');
// Gets annotations for video
console.info('Result------------------->');
console.info(results[0].annotationResults);
var i=1;
results[0].annotationResults.forEach(annotationResult=> {
console.info("annotation result no: "+i+" =======================>")
console.info("Speech : "+annotationResult.speechTranscriptions);
console.info("Text: "+annotationResult.textAnnotations);
i++;
});
}
analyzeVideoTranscript();
NB: я обнаружил, что annotationResult может не возвращать результат в том же порядке, что и заявленные функции. Вы можете изменить код соответственно в соответствии с вашими потребностями.
Редактировать:
Вы можете проверить, сколько результатов вы получаете, распечатав results.annotationResults.length . У вас должно быть два результата аннотации для отдельных объектов. Все, что вам нужно сделать, это пройтись по ответу.
Вот вывод приведенного выше кода:
Вывод был преобразован в строку, так как я напечатал результат в той же строке.
Привет @ChukwumaNwaugha, я обновил свой ответ скриншотами вывода. Я не уверен, как вы не получаете результаты текстовых аннотаций.
Привет, Киран Мэтью, спасибо за продолжение. И да, ты прав. Я извлекал первый элемент массива, не учитывая, что могут быть и другие элементы массива с данными. И это было виновником const annotationResult = operationResult.annotationResults[0] в коде.
Я думаю, это связано с асинхронным вызовом и оператором распространения .... Я проверил это со всеми функциями, чтобы быть уверенным, и это сработало для меня.
const { VideoIntelligenceServiceClient } = require('@google-cloud/video-
intelligence');
const path = require('path');
const gcsUri = 'gs://path/somefile';
const outputUri = `gs://optional-path-to-save-check-bucket}.json`;
const videoClient = new VideoIntelligenceServiceClient({
keyFilename: '/path_to_local/key/used/to_test_this.json'
});
const transcriptConfig = {
languageCode: "en-US",
enableAutomaticPunctuation: true,
enableSpeakerDiarization: true,
enableWordConfidence: true,
speechContexts: []
};
const videoContext = {
speechTranscriptionConfig: transcriptConfig,
};
//Threw in all features to check myself
const request = {
inputUri: gcsUri,
outputUri: outputUri,
features: [ 'OBJECT_TRACKING',
'LABEL_DETECTION',
'SHOT_CHANGE_DETECTION',
'TEXT_DETECTION',
'FACE_DETECTION',
'PERSON_DETECTION',
'LOGO_RECOGNITION',
'EXPLICIT_CONTENT_DETECTION',
'SPEECH_TRANSCRIPTION'],
videoContext: videoContext
};
async function detectTextAndSpeech() {
// Detects text and speech in a video
const [operation] = await videoClient.annotateVideo(request);
const [operationResult] = await operation.promise();
const textAnnotations = [];
const speechTranscriptions = [];
operationResult.annotationResults.forEach(annotationResult => {
if (annotationResult.textAnnotations) {
textAnnotations.push(...annotationResult.textAnnotations);
}
if (annotationResult.speechTranscriptions) {
speechTranscriptions.push(...annotationResult.speechTranscriptions);
}
});
console.info(textAnnotations);
console.info(speechTranscriptions);
}
detectTextAndSpeech();
Спасибо за продолжение 🙏
Это не работает для меня. Я получил следующий результат { "тексты": [], "транскрипции": [{...}] }