Err: documentTextDetection is not a function - google-cloud-vision

just follow https://cloud.google.com/vision/docs/detecting-fulltext
got err when runs to the 3rd line
const vision = require('#google-cloud/vision');
const ocr = new vision.ImageAnnotatorClient();
const [r] = ocr.documentTextDetection(file.path);
const fullText = r.fullTextAnnotation;
documentTextDetection is not a function
Ok to call .textDetection()
Environment details
OS: Win 10
Node.js version: 8.14.0
npm version: 6.4.1
#google-cloud/vision version: 1.2.0
Thanks!

Don't know why, it works once doing it in a Promise
ocr.documentTextDetection(file.path)
.then(
function (data) {
const [r] = data;
const dr = r.fullTextAnnotation;

Related

Firebase Cloud function cannot be deployed

I cannot figure out why my cloud functions are not deploying, has anybody experienced this issue?
const functions = require("firebase-functions");
const { Configuration, OpenAIApi } = require("openai");
//create an image function
exports.createNewImage = functions.https.onCall(async (data, context) => {
const textReceived = data.prompt; //basically the text sent
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
return openai
.createImage({
prompt: textReceived,
n: 2,
size: "1024x1024",
})
.then((apiResponse) => {
const imageUrl = apiResponse.data[0].url;
return imageUrl;
});
});
Logs say open ai is missing in json dependencies, but wasn't that installed when installed openai via npm?
the issue was that I deployed openai in the root folder instead of the dang functions folder :p

Cannot find module 'firebase-functions/lib/encoder' from 'node_modules/firebase-functions-test/lib/providers/firestore.js'

Hey I am trying to unit test this cloud function right here:
import { logger, region, https } from "firebase-functions/v1";
import Message from "../types/message";
const helloWorldHandler = region("europe-west1").https.onCall((_, context) => {
if (context.app == undefined) {
throw new https.HttpsError("failed-precondition", "The function must be called from an App Check verified app.");
}
logger.info("Hello logs!", { structuredData: true });
const message: Message = {
text: "Hello from Firebase!",
code: 200,
};
return message;
});
export default helloWorldHandler;
with the following test:
import * as functions from "firebase-functions-test";
import * as path from "path";
const projectConfig = {
projectId: "myproject-id",
};
const testEnv = functions(projectConfig, path.resolve("./flowus-app-dev-fb-admin-sdk-key"));
// has to be after initializing functions
import helloWorldHandler from "../src/functions/helloworld";
import Message from "../src/types/message";
describe('Testing "helloWorld"', () => {
const helloWorld = testEnv.wrap(helloWorldHandler);
it("helloWorld does work", async () => {
const data = {};
const success: Message = await helloWorld(data);
expect(success.code).toBe(200);
});
});
When I run it with yarn test I receive the following error
Cannot find module 'firebase-functions/lib/encoder' from 'node_modules/firebase-functions-test/lib/providers/firestore.js'
Even though my function does not even use firestore in the first place?
Any ideas ?
I was facing a similar issue while trying to set up a unit testing environment for firebase cloud functions.
Mainly, after following all the steps on Firebase's docs, and running npm test
I would get the following error
Error [ERR_PACKAGE_PATH_NOT_EXPORTED] Package subpath './lib/encoder'
is not defined by "exports"
After stumbling on Farid's suggestion for this problem, I realized that, for some reason, npm i firebase-functions-test does not install the latest version of the module.
Try npm i firebase-functions-test#latest.

Cannot call Firestore from Cloud Functions unit tests

Developing Google cloud functions locally.
Trying to test functions that invoke Firestore.
Here is a minimal example.
Emulators are running.
The function addMessage() works completely fine when invoked from the browser.
The function fails with error TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. when invoked from tests.
Question: Why is this error occurring and how can I invoke the Firestore function successfully from the tests?
functions/index.js:
require ('dotenv').config();
const functions = require ('firebase-functions');
const admin = require ('firebase-admin');
admin.initializeApp();
exports.addMessage = functions.https.onRequest (async (req, res) => {
const original = req.query.text;
const writeResult = await admin.firestore().collection ('messages').add ({text: original});
const docSnap = await writeResult.get();
const writtenText = docSnap.get ('text');
res.send (`Message with text: ${writtenText} added.`);
});
functions/test/index.test.js:
const admin = require ('firebase-admin');
const firebase_functions_test = require ('firebase-functions-test')({
projectId: 'my-project-id'
}, '/path/to/google-application-credentials.json');
const testFunctions = require ('../index.js');
describe ('addMessage()', () => {
it ('returns Message with text: Howdy added.', (done) => {
const req = {query: {text: 'Howdy'} };
const res = {
send: (body) => {
expect (body).toBe (`Message with text: Howdy added.`);
done();
}
};
testFunctions.addMessage (req, res);
});
});
Starting jest from functions folder:
(Among other test-related output):
FAIL test/index.test.js
● addMessage() › returns Message with text: Howdy added.
TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type object
7 | exports.addMessage = functions.https.onRequest (async (req, res) => {
8 | const original = req.query.text;
> 9 | const writeResult = await admin.firestore().collection ('messages').add ({text: original});
| ^
10 | const docSnap = await writeResult.get();
11 | const writtenText = docSnap.get ('text');
12 | res.send (`Message with text: ${writtenText} added.`);
at GrpcClient.loadProto (node_modules/google-gax/src/grpc.ts:166:23)
at new FirestoreClient (node_modules/#google-cloud/firestore/build/src/v1/firestore_client.js:118:38)
at ClientPool.Firestore._clientPool.pool_1.ClientPool [as clientFactory] (node_modules/#google-cloud/firestore/build/src/index.js:326:26)
at ClientPool.acquire (node_modules/#google-cloud/firestore/build/src/pool.js:87:35)
at ClientPool.run (node_modules/#google-cloud/firestore/build/src/pool.js:164:29)
at Firestore.request (node_modules/#google-cloud/firestore/build/src/index.js:983:33)
at WriteBatch.commit_ (node_modules/#google-cloud/firestore/build/src/write-batch.js:496:48)
Caused by: Error:
at WriteBatch.commit (node_modules/#google-cloud/firestore/build/src/write-batch.js:415:23)
at DocumentReference.create (node_modules/#google-cloud/firestore/build/src/reference.js:283:14)
at CollectionReference.add (node_modules/#google-cloud/firestore/build/src/reference.js:2011:28)
at Object.<anonymous>.exports.addMessage.functions.https.onRequest (index.js:9:71)
at Object.addMessage (node_modules/firebase-functions/lib/providers/https.js:50:16)
at Object.done (test/index.test.js:17:19)
Environment:
"node": "10"
"firebase-admin": "^8.12.1",
"firebase-functions": "^3.7.0"
"firebase-functions-test": "^0.2.1",
"jest": "^25.5.4"
Solved by adding jest.config.js to functions/:
module.exports = {
testEnvironment: 'node'
};
Solution based on this (but NB I needed to place jest.config.js in functions/, not the project root).
Also tried this but appeared to do nothing.
Tests now run perfectly except that they end with a Jest error:
Jest did not exit one second after the test run has completed.
This usually means that there are asynchronous operations that weren't stopped in your tests. Consider running Jest with `--detectOpenHandles` to troubleshoot this issue.
This seems to be harmless.
Thanks #gso_gabriel for the valuable links!

How do I check the status of my most recently completed Codebuild build projects?

How do I check the status of my most recent AWS Codebuild build projects using the CLI? I see that you can view the build details, but it requires a specific build-id, and the summarized build information does not give any details on which build phase is correlated to the status that appears in the console.
You can approach the problem in two steps:
Get the id of the most recent build with list-builds-for-project
Select the relevant field from the output of batch-get-builds
Assuming you have aws CLI and jq installed, and are receiving CLI results in JSON format:
id=$(aws codebuild list-builds-for-project --project-name myproject | jq -r '.ids[0]')
The default sort order puts the most recently completed build at the top of the list. Then use $id from the prior step:
aws codebuild batch-get-builds --ids "$id" | jq '.builds[].phases[] | select (.phaseType=="BUILD") | .phaseStatus'
See select objects based on value of variable in object using jq for a discussion of the jq syntax.
I may have reinvented or over-engineered the wheel, but wrote a little node program to do this that might be of use to you.
const { exec } = require("child_process");
const { promisify } = require("util");
const asyncExec = promisify(exec);
const getLatestBuildId = async () => {
const listBuildsCommand = "aws codebuild list-builds";
const { stdout } = await asyncExec(listBuildsCommand);
const { ids } = JSON.parse(stdout);
const [latestBuildId] = ids;
return latestBuildId;
};
const getBuildStatus = async (latestBuildId) => {
const batchGetBuildsCommand = `aws codebuild batch-get-builds --ids ${latestBuildId}`;
const { stdout } = await asyncExec(batchGetBuildsCommand);
const { builds } = JSON.parse(stdout);
const [latestBuild] = builds;
const { id, currentPhase, buildStatus, startTime, endTime } = latestBuild;
return {
id,
currentPhase,
buildStatus,
start: new Date(startTime * 1000).toLocaleTimeString(),
end: new Date(endTime * 1000).toLocaleTimeString(),
};
};
const reportBuildStatus = async () => {
const latestBuildId = await getLatestBuildId();
const latestBuild = await getBuildStatus(latestBuildId);
console.log(latestBuild);
};
reportBuildStatus();

Function execution took 60002 ms, finished with status: 'timeout' [duplicate]

This question already has an answer here:
Google Cloud Function Environmnet Timing out on every functions
(1 answer)
Closed 4 years ago.
I have a Firebase cloud function that is loosely based on this example
https://github.com/firebase/functions-samples/tree/master/image-sharp
Today, when deploying some small changes it gave me this warning
$ firebase deploy --only functions
⚠ functions: package.json indicates an outdated version of firebase-functions.
Please upgrade using npm install --save firebase-functions#latest in your functions directory.
so I did the upgrade, which upgraded firebase-functions from ^1.0.3 to ^2.0.0
since then have been getting this when running the function
Function execution took 60002 ms, finished with status: 'timeout'
instead of the usual
Function execution took 10 ms, finished with status: 'ok'
I started stripping down my function but even going down to bare bones it was still getting the error.
I then started a new project used the example function as is and it behaves exactly the same way. With firebase-functions ^2.0.0 it gives the timeout error but with ^1.0.0 it works fine.
Is this a known issue?
Thanks
Here is the example code
exports.generateThumbnail = functions.storage.object().onFinalize((object) => {
const fileBucket = object.bucket; // The Storage bucket that contains the file.
const filePath = object.name; // File path in the bucket.
const contentType = object.contentType; // File content type.
// Exit if this is triggered on a file that is not an image.
if (!contentType.startsWith('image/')) {
console.log('This is not an image.');
return null;
}
// Get the file name.
const fileName = path.basename(filePath);
// Exit if the image is already a thumbnail.
if (fileName.startsWith('thumb_')) {
console.log('Already a Thumbnail.');
return null;
}
// Download file from bucket.
const bucket = gcs.bucket(fileBucket);
const metadata = {
contentType: contentType,
};
// We add a 'thumb_' prefix to thumbnails file name. That's where we'll upload the thumbnail.
const thumbFileName = `thumb_${fileName}`;
const thumbFilePath = path.join(path.dirname(filePath), thumbFileName);
// Create write stream for uploading thumbnail
const thumbnailUploadStream = bucket.file(thumbFilePath).createWriteStream({metadata});
// Create Sharp pipeline for resizing the image and use pipe to read from bucket read stream
const pipeline = sharp();
pipeline
.resize(THUMB_MAX_WIDTH, THUMB_MAX_HEIGHT)
.max()
.pipe(thumbnailUploadStream);
bucket.file(filePath).createReadStream().pipe(pipeline);
const streamAsPromise = new Promise((resolve, reject) =>
thumbnailUploadStream.on('finish', resolve).on('error', reject));
return streamAsPromise.then(() => {
console.log('Thumbnail created successfully');
return null;
});
I was going to comment but it requires me 50+ reputations.....
Anyway, I am experiencing the same problem:
exports.sendNotificationForMessage = functions.firestore.document('chatrooms/{chatroomId}/messages/{messageId}').onCreate((snap, context) => {
const newMessage = snap.data();
const messageContent = newMessage.text;
const senderName = newMessage.senderDisplayName;
const senderId = newMessage.senderId;
const chatroomId = context.params.chatroomId;
console.log(newMessage)
return true;
});
It finished with status timeout.
If it's a problem with firebase-function 2.0, what is the command to downgrade it back to version 1.x? Googled about it but no luck.
Try calling resolve and reject with ():
exports.generateThumbnail = functions.storage.object().onFinalize((object) => {
const fileBucket = object.bucket; // The Storage bucket that contains the file.
const filePath = object.name; // File path in the bucket.
const contentType = object.contentType; // File content type.
// Exit if this is triggered on a file that is not an image.
if (!contentType.startsWith('image/')) {
console.log('This is not an image.');
return null;
}
// Get the file name.
const fileName = path.basename(filePath);
// Exit if the image is already a thumbnail.
if (fileName.startsWith('thumb_')) {
console.log('Already a Thumbnail.');
return null;
}
// Download file from bucket.
const bucket = gcs.bucket(fileBucket);
const metadata = {
contentType: contentType,
};
// We add a 'thumb_' prefix to thumbnails file name. That's where we'll upload the thumbnail.
const thumbFileName = `thumb_${fileName}`;
const thumbFilePath = path.join(path.dirname(filePath), thumbFileName);
// Create write stream for uploading thumbnail
const thumbnailUploadStream = bucket.file(thumbFilePath).createWriteStream({metadata});
// Create Sharp pipeline for resizing the image and use pipe to read from bucket read stream
const pipeline = sharp();
pipeline.resize(THUMB_MAX_WIDTH, THUMB_MAX_HEIGHT).max().pipe(thumbnailUploadStream);
bucket.file(filePath).createReadStream().pipe(pipeline);
const streamAsPromise = new Promise((resolve, reject) =>
thumbnailUploadStream.on('finish', resolve()).on('error', reject()));
return streamAsPromise.then(() => {
console.log('Thumbnail created successfully');
return null;
});
});

Resources