ImageAnnotatorClient google vision API - google-cloud-platform

Trying to use node to run a label detection with the vision api:
'use strict';
// Imports the Google Cloud client library
const vision = require('#google-cloud/vision');
// Creates a client
const client = new ImageAnnotatorClient({
projectId: 'my-project-xxx',
keyFilename: 'Users/xxx/Downloads/xxx.json',
});
// Performs label detection on the image file
client
.labelDetection('.//Users/xxx/Downloads/menu.jpg')
.then(results => {
const labels = results[0].labelAnnotations;
console.log('Labels:');
labels.forEach(label => console.log(label.description));
})
.catch(err => {
console.error('ERROR:', err);
});
Continuously receiving error: "ImageAnnotatorClient is not defined"
Any reason for this?

Can you try modifying the line:
const client = new ImageAnnotatorClient({
for:
const client = new vision.ImageAnnotatorClient({
The ImageAnnotatorClient method is extracted from the Cloud Vision API, which you imported as the vision variable.

Related

GCC Cloud Function internal server error 500

I have a firestore database that I want to backup regulalry using google cloud's scheduler alongside google cloud function. I am following this tutorial: https://firebase.google.com/docs/firestore/solutions/schedule-export#gcp-console.
I am using Node.js 16 with 2 GB of RAM with the code below:
const firestore = require('#google-cloud/firestore');
const client = new firestore.v1.FirestoreAdminClient();
const bucket = 'gs://BUCKET_NAME'
exports.scheduledFirestoreExport = (event, context) => {
const databaseName = client.databasePath(
process.env.GCLOUD_PROJECT,
'(default)'
);
return client
.exportDocuments({
name: databaseName,
outputUriPrefix: bucket,
collectionIds: [],
})
.then(responses => {
const response = responses[0];
return response;
})
.catch(err => {
});
};
When I test the function it just returns an Internal Server Error 500. Any ideas?
Also, here is a picture of the errors im getting from the logs:

How to add lambda layers in Cloud 9

I tried to edit the lambda function using AWS Cloud 9 but unfortunately, the layers were not imported. How do I attach lambda layers to it?
var config = require('./config.js');
var AWS = require("aws-sdk");
//How to import Axios in cloud 9 as I have added Axios layer in Lambda
const axios = require("axios");
exports.handler = async(event, context, callback) => {
//Get DataList
var get_data = await config.connectToDatabase()
.then(db => config.get_items(db))
.then(result => {
console.log(result);
return result;
});
callback(null, get_data);
}
The code is working fine when I run this function in lambda but there is an error when I tried the same function in cloud 9, It says Module not found Axios because Cloud 9 does not support layers.

Cannot find module aws-amplify, lambda function

I'm try to make an API post request in my lambda function but in the aws website, using nodejs I cannot import API ? Here is what I am trying
console.log('Loading function');
const AWS = require('aws-sdk');
const translate = new AWS.Translate({ apiVersion: '2017-07-01' });
var API = require('aws-amplify');
exports.handler = async (event, context) => {
try {
const params = {
SourceLanguageCode: 'en', /* required */
TargetLanguageCode: 'es', /* required */
Text: 'Hello World', /* required */
};
const data = await translate.translateText(params).promise();
createSite(data.TranslatedText);
} catch (err) {
console.log(err, err.stack);
}
function createSite(site) {
return API.post("sites", "/sites", {
body: site
});
}
};
I have also tried import...
I think you may be looking at front-end browser based JavaScript examples, which aren't always going to work in a back-end AWS Lambda NodeJS runtime environment. It appears you are trying to use this library, which states it is "a JavaScript library for frontend and mobile developers", which probably isn't what you want to use on AWS Lambda. It appears you also did not include that library in your AWS Lambda function's deployment.
I suggest using the AWS Amplify client in the AWS SDK for NodeJS which is automatically included in your Lambda function's runtime environment. You would create an Amplify client like so:
var amplify = new AWS.Amplify();

Expo, React Native, Share/upload picture to Facebook (story on my own page)

I am really lost here, I have an Expo React-Native application. the user can login with Facebook credentials.
loginWithFacebook = async () => {
const { type, token } = await Expo.Facebook.logInWithReadPermissionsAsync(FACBOOK_APP_ID, {
permissions: ['public_profile', 'email'],
});
if (type === 'success') {
this.callGraph(token);
} else {...});
}
};
and
callGraph = async (token) => {
const response = await fetch(`https://graph.facebook.com/me?access_token=${token}&fields=id,name,email,picture`);
const responceJSON = JSON.stringify(await response.json());
try {
await AsyncStorage.multiSet([['FBResponse', responceJSON], ['FBToken', token]]);
} catch (error) {...}
};
now I have the Token and info of the loged in user. now I get a picture from cameraRoll
pickImage = async () => {
const result = await Expo.ImagePicker.launchImageLibraryAsync({...});
};
which gives the URI of the image at the device, also I am using RNFetchBlob to again have the image as base64.
but I am really confused that how should I share/upload this picture to Facebook. Should I eject from Expo install FBSDK and do it from Android folder? or I can do it with the Graph API? or I can Link it to Expo?
I could not find a single example, just simple react-native-share samples are what I see everywhere.
Facebook integration for Expo only accepts read permissions and one cannot login with publish_actions it seems the community is still working on it. and for using fbsdk you should either eject from Expo or ask for permissions via the Expo WebBrowser integration.

Save image picked from ReactNative/Expo ImagePicker to Baqend

I'm having a hard time saving an image that is being picked from Expo (React Native).
https://docs.expo.io/versions/latest/sdk/imagepicker.html
It seems that React Native does not have support for uploading the selected image as blob, but does have a base64 option.
The code:
_pickImage = async () => {
let pickerResult = await ImagePicker.launchImageLibraryAsync({
allowsEditing: true,
base64: true,
aspect: [4, 4],
});
this._handleImagePicked(pickerResult);
};
_handleImagePicked(pickerResult) {
const uri = pickerResult.base64;
const img = new db.File({ name: 'test.jpg', data: uri, type: 'base64', mimeType: 'image/jpg' });
db.UserData.load(this.state.UserDataID).then(UserData => {
img.upload({ force: true }).then((file) => {
UserData.photo = "https://remarkable-apple-95.app.baqend.com/v1" + file.id;
alert(file.id)
return UserData.update();
},
(error) => { alert(error); }
);
});
}
When I console.log(pickerResult.base64) I get a super long string that looks like base64, but when this is run, the img.upload is throwing the error and it says "PersistentError: An unexpected persistent error occurred."
You're right. React Native has no support for binary data. Unfortunately Baqend does not support base64 file uploads yet.
As a workaround you have 2 options:
Use the React Native Fetch Blob library, which bypasses the limitations of React Native not supporting binary files by uploading and downloading the files directly via native code and gives back a reference to those. Your code could look similar to this:
ImagePicker.showImagePicker(options, async (response) => {
const upload = new db.message.UploadFile('files', 'uploadFetchBlob.jpg')
const body = 'RNFetchBlob-' + response.uri;
RNFetchBlob.fetch('PUT', 'https://{YOUR-APP-NAME}.app.baqend.com/v1' + upload.request.path, upload.request.headers, body).then((res) => {
db.File({ parent: 'files', name: 'uploadFetchBlob.jpg'}).url
})
});
Unfortunately this wont work with the expo client right now, but you'd have to eject your project and use 'native code'.
The second option would be not to use the baqend file endpoint directly, but upload your base64 string to a baqend module instead. There you can parse your base64 string and upload it to your files from within your backend module. You can find an example for this in our Guide. https://www.baqend.com/guide/topics/baqend-code/#handling-binary-data
Hope this helps