Find JavaScript Code Integrate Clarifai Face Detection API - javascript

taking a course where we integrate Clarifai Face Detection API into our app and the course shows a section on Clarifai's documents where you can copy some JavaScript code under what looks like "Request" and it has
app.models.predict(Model ID, Web Address)
function(response) {
},
function(err) {
}
);
Which is then used under our onSubmitRequest input. Any tips on where to find this?
Thanks much

we generally don't recommend using this JS package as it is no longer supported [R]. Please use the NodeJS gRPC variant: https://www.npmjs.com/package/clarifai-nodejs-grpc or call our REST API directly: https://docs.clarifai.com/api-guide/predict/images (see "Javascript (REST)" code snippets)

I think that we just took the same online course and in order to accomplish that step, you will need to update your code basis according to the new Clarifai standards. I did that and it worked as follows:
Note:
You will need to modify the USER_ID, PAT and APP_ID with your own credentials.
Also, you will be using the result variable insted of the response variable.
In case you run into error or have any dubts check these links:
https://help.clarifai.com/hc/en-us/articles/4408131912727-How-do-I-find-my-user-id-app-id-and-PAT-
https://help.clarifai.com/hc/en-us/articles/1500007677141-Where-to-find-your-Model-IDs-and-Model-Version-IDs
onButtomSubmit = () => {
//help me => user_id can be found in multiple ways, one way is in https://portal.clarifai.com/settings/profile
const USER_ID = "Use-your-ID-here";
// Your PAT (Personal Access Token) can be found in the portal under Authentification
// help me => PAT can be found in https://portal.clarifai.com/settings/authentication (create one if necessary!)
const PAT = "Use-your-APi-Here";
// help me => App Id is just the name of your app on the portal.
const APP_ID = "Use-your-app-name-here";
// Change these to whatever model and image input you want to use
// help me => https://help.clarifai.com/hc/en-us/articles/1500007677141-Where-to-find-your-Model-IDs-and-Model-Version-IDs
const MODEL_ID = "face-detection";
const MODEL_VERSION_ID = "45fb9a671625463fa646c3523a3087d5";
const IMAGE_URL = this.state.input;
///////////////////////////////////////////////////////////////////////////////////
// YOU DO NOT NEED TO CHANGE ANYTHING BELOW THIS LINE TO RUN THIS EXAMPLE
///////////////////////////////////////////////////////////////////////////////////
const raw = JSON.stringify({
user_app_id: {
user_id: USER_ID,
app_id: APP_ID,
},
inputs: [
{
data: {
image: {
url: IMAGE_URL,
},
},
},
],
});
const requestOptions = {
method: "POST",
headers: {
Accept: "application/json",
Authorization: "Key " + PAT,
},
body: raw,
};
fetch(
"https://api.clarifai.com/v2/models/" +
MODEL_ID +
"/versions/" +
MODEL_VERSION_ID +
"/outputs",
requestOptions
)
.then((response) => response.json())
.then((result) =>
console.log(result)
)
.catch((error) => console.log("error", error));
};
have fun :)

Related

Twillio : before building the app, what is the base URL?

I wrote Twillio code to get phone verification in frontend.
And here PRACTICE_BASE_URL was my IP address like below since I just test it on expo.
Whenever IP address I changed it.
const PRACTICE_BASE_URL = "http://172.30.1.18:4000";
const sendCode = async () => {
setPhoneInserted(true);
setwaitMessage(true);
// send verfication code to phone number
await fetch(`${PRACTICE_BASE_URL}/verify/${phone}`, {
method: "GET",
headers: {
"Content-Type": "application/json",
},
})
.then((res) => res.json())
.then((res) => {
if (res.status === "pending") {
setcheckedNumber(phone);
setwaitMessage(false);
}
})
.catch((err) => {
setPhoneInserted(false);
setwaitMessage(false);
setphone("");
console.log(err);
setDisableConfirm(true);
goDownY.start();
setVeriBox(true);
setVerimessage("잘못된 휴대전화번호입니다.");
reset();
setretry(true);
});
};
I want to build the app in real or beta version from expo now.
So how do I change BASE_URL here?
I searched but not found in Twillio homepage. please help me.
The usual base URL for the Twilio API is:
https://api.twilio.com/2010-04-01/
The base URL for the Twilio Verify API is:
https://verify.twilio.com/v2/

Why the data doesn't want to be appear in my .json file using nodeJS?

1.) I have a function that successfully generates random words in accordance with the user input (if user input is 10 than 10 random words will be displayed on the website). A have a json server were I'm getting the words using GET request fetch api as you can see below:
function getRandomWords() {
let words = getServerData('http://localhost:3000/words').then(data => {
const wordsToMemorize = document.querySelector('#words-to-memorize');
document.querySelector("#wordsInput").addEventListener("click", function() {
let temp = wordsToMemorize.value;
generatedArrayELements.innerHTML = "";
for(let i = 0; i < temp; i++) {
let rander = Math.floor(Math.random() * 3000);
generatedArrayELements.innerHTML += data[rander] + "</br>";
}})
});
}
2.) I want to transfer the generated words to my .json file in to the randomwords array but it doesn't want to work. And using DOM down there also doesnt make sense that I just realised:
function putServerData() {
let data = getRandomWords();
let fetchOptions = {
method: "POST",
mode: "cors",
cache: "no-cache",
headers: {
'Content-Type': 'application/json'
},
credentials: "same-origin",
body: JSON.stringify(data)
};
return fetch("http://localhost:3000/randomwords", fetchOptions)
.then(resp => resp.json())
.then(json => console.log(json));
}
document.querySelector("#wordsInput").addEventListener("click", function() {
putServerData();
})
3.) I feel like being very close to my goal because the random word generator works and I can also POST data in to the .json file if I set manually the value to the let data variable, like let data = ["test"]. What I dont know is how to send the generated random words in to my .json file.
4.) My json file:
{
"randomwords": [],
"words": [
"a",
"abandon",
"ability",
"able",
"abortion",
"about",
"above",
"abroad",
"absence",
"absolute",
"absolutely",
"absorb",
"abuse",
"academic",
"accept",
"access"...(remaining words...)
}]
4.) I tried to follow the documentation. Maybe I need to use some timeout because the random words first need to be generated before I use POST request on them. I've been struggling with this for almost a week and cant find solution, I read almost every relating post in SO. Every help would be greatly appreciated.
return a promise in my getRandomWords() with some timeout can be a working solution?
You can't add date to json file by making a fetch post call, however what you can do is write the data to your json file, you can do that by using the node fs module.
first make a route handler
const fs = require('fs')
router.post("/savedata", (req, res) => {
const jsondata = req.body
fs.writeFileSync('./path/to/your/json/data', jsondata, err => {
if (err) {
res.send("error saving file")
} else {
res.send("data saved successfully")
}
})
})
and then use fetch to make a call to your passing the data in the body

“Unauthorized” response when cityiq API

I am trying to access the Current powered by GE CityIQ API to develop a parking app, I followed the API documentation however I cannot seem to successfully query because I do not have an access token. I have a user name and password as well as the urls and predix zone id for parking provided by the city I am using. When I try and run my javascript and log my access token the response is “Unauthorized”. Do i have to raise a request to the city for the access token?
The code is written in javascript and is using node.js and node-fetch.
Here is my code:
const fetch = require("node-fetch")
function request(url, headers, body) {
let options = { headers: headers, body:body}
return fetch(url, options).then(result => {
if (result.status>=400) return(result.statusText)
else return result.text().then(txt => {
try { return JSON.parse(txt) }
catch (err) { return txt }
})
})
}
// my credentials
const developer, uaa, metadataservice, eventservice, predixZone
developer = '{user}:{pass}'
uaa='{uaaURL}'
eventservice='{eventURL}'
metadataservice='{metadataURL}'
predixZone='{predixzoneParking}'
async function example(event){
let devToken = (await request(uaa+'?grant_type=client_credentials', {authorization: 'Basic '+developer}))
console.log(devToken)
let output = (await request(metadataservice+'/assets/search?q=eventTypes:PKIN',{authorization: 'Bearer '+devToken,'predix-zone-id':predixZone})).content
console.log(output)
}
example()
What am I doing wrong or probably missing?
It looks like you have not base64 encoded your username and password.
At the top of your code:
const btoa = str => new Buffer(str).toString('base64')
When you declare your user name and pass:
developer = btoa('{user}:{pass}')

How do I pass a react DOM state's information to backend(NodeJS) when a button is invoked?

I'm using his logic on the frontend, but I'm having some trouble actually receiving that data on the backend. I'm using the Sails.js framework. Any suggestions?
handleSubmit = () => {
// Gathering together the data you want to send to API
const payload = {
subject: this.state.subject,
message: this.state.message,
};
this.handleAjaxRequest(payload);
};
// Method to send data to the backend
// Making the req -I'm using Axios here.
handleAjaxRequest = (payload) => {
let request = axios({
method: 'post',
url: '/api/',
data: payload,
headers: 'Content-Type: application/json'
});
// Do stuff with the response from your backend.
request.then(response => {
console.debug(response.data);
})
.catch(error => {
console.error(error);
})
};
I used to do this using Express and didn't have these problems.
Any help, method, a suggestion is more than welcome :)
Please forgive my ignorance, I'm just here to learn.
Okay, so the first thing I had to do is generate a new restful API using the command sails generate api data. In the package.json file I set up a proxy that includes the backends endpoint, like this "proxy": "http://localhost:1337" - I mean, you don't need to do this, but if you don't then you have to include this URL part on every request. Because it doesn't change, it's pretty convenient to do so.
On the frontend, I made a function sendData() that takes the necessary data from my previous component (depending on what the user selected) and send that data using axios to the backend -->
sendData = () => {
const { relYear } = this.props.history.location.state.dev;
const { relMonth } = this.props.history.location.state.dev;
const selectedMonth = moment().month(relMonth).format("MM");
const finalSelect = parseInt(relYear + selectedMonth, 10);
axios.post('/data', { 'selectedDate' : finalSelect })
.then(res => console.log('Data send'))
.catch(err => console.error(err));
}
On the backend I fetched the data, did the calculations and send back the result to the frontend of my app. -->
getApiData = () => {
let apiData = [];
axios.get('/data')
.then(res => {
let first = Object.values(res.data.pop()).shift(); // Getting the relevant 'selectedDate'
apiData.push(first);
}).catch(err => console.error(err));
return apiData;
}

In firebase - How to generate an idToken on the server for testing purposes?

I want to test a a cloud function that creates users.
In normal cases, inside the browser i generate an idToken and i send it to server via headers: Authorization : Bearer etcIdToken
But I want to test this function without the browser. In my mocha tests i have:
before(done => {
firebase = require firebase.. -- this is suppose to be like the browser lib.
admin = require admin..
idToken = null;
uid = "AY8HrgYIeuQswolbLl53pjdJw8b2";
admin.auth()
.createCustomToken(uid) -- admin creates a customToken
.then(customToken => {
return firebase.auth() -- this is like browser code. customToken get's passed to the browser.
.signInWithCustomToken(customToken) -- browser signs in.
.then(signedInUser => firebase.auth() -- now i want to get an idToken. But this gives me an error.
.currentUser.getIdToken())
})
.then(idToken_ => {
idToken = idToken_
done();
})
.catch(err => done(err));
})
The error i'm getting is:
firebase.auth(...).currentUser.getIdToken is not a function - getting the idToken like this works on client - and is documented here.
I tried directly with signedInUser.getIdToken(). Same problem:
signedInUser.getIdToken is not a function - not documented. just a test.
I think this is because firebase object is not intended for node.js use like i'm doing here. When signing in - stuff get's saved in browser local storage - and maybe this is why.
But the question still remains. How can i get an idToken inside node.js in order to be able to test:
return chai.request(myFunctions.manageUsers)
.post("/create")
.set("Authorization", "Bearer " + idToken) --- i need the idToken here - like would be if i'm getting it from the browser.
.send({
displayName: "jony",
email: "jony#gmail.com",
password: "123456"
})
am I approaching this wrong? I know that if i can get the idToken it will work. Do i rely need the browser for this? Thanks :)
From Exchange custom token for an ID and refresh token, you can transform a custom token to an id token with the api. Hence, you just have to generate a custom token first from the uid, then transform it in a custom token. Here is my sample:
const admin = require('firebase-admin');
const config = require('config');
const rp = require('request-promise');
module.exports.getIdToken = async uid => {
const customToken = await admin.auth().createCustomToken(uid)
const res = await rp({
url: `https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyCustomToken?key=${config.get('firebase.apiKey')}`,
method: 'POST',
body: {
token: customToken,
returnSecureToken: true
},
json: true,
});
return res.idToken;
};
L. Meyer's Answer Worked for me.
But, the rp npm package is deprecated and is no longer used.
Here is the modified working code using axios.
const axios = require('axios').default;
const admin = require('firebase-admin');
const FIREBASE_API_KEY = 'YOUR_API_KEY_FROM_FIREBASE_CONSOLE';
const createIdTokenfromCustomToken = async uid => {
try {
const customToken = await admin.auth().createCustomToken(uid);
const res = await axios({
url: `https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyCustomToken?key=${FIREBASE_API_KEY}`,
method: 'post',
data: {
token: customToken,
returnSecureToken: true
},
json: true,
});
return res.data.idToken;
} catch (e) {
console.log(e);
}
}
curl 'https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword?key=<FIREBASE_KEY>' -H 'Content-Type: application/json'--data-binary '{"email": "test#test.com","password":"test","returnSecureToken":true}'
If this curl doesn't run, try running the same thing on Postman. It works!

Categories