Image Classification in Nativescript via API - machine-learning

I will be building an app to detect cat diseases (in their eyes) using Nativescript-Vue.
I'm searching other image classifications project and plugins in Native Script but there where little to no results. I explored google vision, Microsoft custom vision, clarify, but there were no plugins ready for Native Script.
I'm not so good yet to convert react native implementation and its possible counterpart to Native Script. Has anyone tried it?

You may use the MLKit from Firebase plugin which is recommended by Google for mobile apps. Google Vision also has REST apis if you like to stick with that.

If you want to try it but given your credit card, you may use Google Vision, Amazon Rekognition, Microsofts and other ML related in the market. But if you dont want or have a credit card number, in my case, I use https://clarifai.com/ .
For the API package,npm install --save clarifai and for the implementation, I got it with,
const Clarifai = require('clarifai')
const app = new Clarifai.App({
apiKey: 'dac044d841bb40f6bc6a79e5d1a65fcf'
})
sendToClarifai(encoded_image) {
let vm = this
app.models.predict(Clarifai.GENERAL_MODEL, { base64: encoded_image }).then(
function (response) {
// do something with response
var concepts = response['outputs'][0]['data']['concepts']
console.log('CONCEPTS', concepts)
vm.isLoading = false
let isDetectedEyeRelated = false
//loop through items
concepts.forEach(obj => {
if (['disease', 'animal', 'pet', 'cat', 'cataract', 'cataracts', 'eye', 'conjunctivitis'].includes(obj.name)) {
isDetectedEyeRelated = true
}
//more to improve here but very inaccurate
})
//show message
let message = ""
let firstQuestionArray = []
if (isDetectedEyeRelated) {
message = "Your cat might have some eye problems."
firstQuestionArray = ["Do you see redness or discharge?", "Does your cat squinting or the emergence of the third eyelid?"]
} else {
message = "Our classification model cannot identify the subject.\nCheck camera settings and proper position."
firstQuestionArray = ["Does your cat has bright, clear evenly focused eyes?", "Do you see redness or discharge?", "Does your cat squinting or the emergence of the third eyelid?"]
}
//follow up questions
action({
message: message + '\n\nBelow are follow up questions:',
cancelButtonText: "Cancel",
actions: firstQuestionArray,
cancelable: false
})
.then(result => {
if (result.includes("redness") || result.includes("emergence")) { //A
action({
message: "Please select any of these symptoms to know what seems could be the problem",
cancelButtonText: "Cancel",
actions: ["Do you see any familiar pink or reddish color, sticky eye discharge and swelling?", "Did you notice any cloudiness in their eyes, change of iris color and unusual meowing?"],
cancelable: false
})
.then(result => {
if (result.includes("reddish")) { //A
alert({
title: "Identify",
message: "This could be a sign that your cat has conjunctivitis.",
okButtonText: "See Early Treatment"
}).then(() => {
vm.setTreatmentType('eye_conjunctivitis')
vm.setTreatmentTitle('Eye Conjunctivitis Identification and Treatment')
vm.$router.replace({
path: '/pdf-treatment'
})
})
} else if (result.includes("cloudiness")) { //b
alert({
title: "Identify",
message: "This could be a sign that your cat has cataract.",
okButtonText: "See Early Treatment"
}).then(() => {
vm.setTreatmentType('eye_cataract')
vm.setTreatmentTitle('Eye Cataract Identification and Treatment')
vm.$router.replace({
path: '/pdf-treatment'
})
})
}
})
} else if (result.includes("bright")) { //b
const user_data = LS.getItem(vm.loggedUsername)
const obj = JSON.parse(user_data)
obj.progress.eye = 'good condition'
//update the user data
LS.removeItem(vm.loggedUsername)
LS.setItem(vm.loggedUsername, JSON.stringify(obj))
alert({
title: "Congratulations",
message: "Your cat's eye is in good condition.",
okButtonText: "Done"
}).then(() => {
console.log("Alert dialog closed");
})
vm.$router.push({
path: '/categories'
})
}
})
},
function (err) {
// there was an error
console.log('CLARIFAI ERROR', err)
}
)
Or something similar with my implementation.

Related

How do i style a youtube live stream message?

Hi so i am manually inserting in my live stream using a node js googleapis/youtube package. The message shows as a plain text message, what i would like to know is how can i change the design of this text message so that it is more noticeable like maybe highlighting it? I am currently using the following code
const youtubeService = {};
youtubeService.insertMessage = messageText => {
console.log(myliveChatId);
const response = youtube.liveChatMessages.insert(
{
auth: auth,
part: 'snippet',
resource: {
snippet: {
type: 'textMessageEvent',
liveChatId: myliveChatId,
textMessageDetails: {
messageText: 'hello man'
}
}
}
},
(error) => {
console.log(error);
}
);
console.log(response);
};
EDIT:
This is how a chat message usually appears
what i want is something like this
Note: The message that is inserted onto my livestream via the code wont be through my account but rather someone else's.

Access an API through Google Actions/Dialogflow

I wanted to trigger a Jenkins job through the Jenkins API
we can do that by hitting the URL similar to "JENKINS_URL/job/JOBNAME/build"
I want to hit the API via Google action/Dialogflow.
Is there any tutorial available to do a similar process that I want to achieve?
You should take a look at the Dialogflow quotes sample, which shows how to make external API calls:
// Retrieve data from the external API.
app.intent('Default Welcome Intent', (conv) => {
// Note: Moving this fetch call outside of the app intent callback will
// cause it to become a global var (i.e. it's value will be cached across
// function executions).
return fetch(URL)
.then((response) => {
if (response.status < 200 || response.status >= 300) {
throw new Error(response.statusText);
} else {
return response.json();
}
})
.then((json) => {
// Grab random quote data from JSON.
const data = json.data[Math.floor(Math.random() * json.data.length)];
const randomQuote =
data.quotes[Math.floor(Math.random() * data.quotes.length)];
conv.close(new SimpleResponse({
text: json.info,
speech: `${data.author}, from Google ` +
`Developer Relations once said... ${randomQuote}`,
}));
if (conv.screen) {
conv.close(new BasicCard({
text: randomQuote,
title: `${data.author} once said...`,
image: new Image({
url: BACKGROUND_IMAGE,
alt: 'DevRel Quote',
}),
}));
}
});
});

Apple Pay - onvalidatemerchant Payment Not Completed error

I am implementing apple pay onto our website. I do not have a macOS device and am using windows visual studios / mvcnet. I have done all the merchantID and certification stuff and configured it on the windows machine. I am using Apple Pay JS and on the step where the payment sheet is opened with session.begin(). I use an ajax call to retrieve a merchantSession, which I believe it does successfully because the object consumed by session.completeMerchantValidation(merchantSession) contains an epochnumber, expiration time and the site name. However, immediately after completeMerchantValidation, the oncancel event is fired, and I get a red alert saying "Payment not completed".
I need help with how to proceed from here, I read somewhere online that the domain on where I am testing needs to be a registered merchant domain. For example, when I test the functionality of the button, I need to be on www.mySite.com, where I have mySite.com registered as a domain. Can someone confirm if this is true.. because I am accessing the site from my iOS devices through local IP address. If that is not true, any help proceeding from where I am would be helpful.
function StartPaySession() {
var lineItems = [
{
label: 'Shipping',
amount: '0.00',
}
];
var shippingMethods = [
{
label: 'Free Shipping',
amount: '0.00',
identifier: 'free',
detail: 'Delivers in five business days',
},
{
label: 'Express Shipping',
amount: '5.00',
identifier: 'express',
detail: 'Delivers in two business days',
}
];
var total = {
label: 'Apple Pay Example',
amount: '8.99',
};
var paymentData = {
countryCode: 'US',
currencyCode: 'USD',
shippingMethods: shippingMethods,
lineItems: lineItems,
total: total,
supportedNetworks: ['amex', 'discover', 'masterCard', 'visa'],
merchantCapabilities: ['supports3DS'],
requiredShippingContactFields: ['postalAddress', 'email'],
};
var paySession = new ApplePaySession(2, paymentData);
paySession.onvalidatemerchant = function (event) {
var validationData = { ValidationUrl: event.validationURL };
$.ajax({
url: '/orders/cart/startapplepaysession',
method: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(validationData)
}).then(function (merchantSession) {
paySession.completeMerchantValidation(merchantSession);
alert("end = " + window.location.host);
}, function (error) {
alert("merchant validation unsuccessful: " + JSON.stringify(error));
paySession.abort();
});
};
paySession.onpaymentmethodselected = function (event) {
alert("1");
paySession.completePaymentMethodSelection(total, lineItems);
};
paySession.onshippingcontactselected = function (event) {
alert("2");
paySession.completeShippingContactSelection(ApplePaySession.STATUS_SUCCESS, shippingMethods, total, lineItems);
};
paySession.onshippingmethodselected = function (event) {
alert("3");
paySession.completeShippingMethodSelection(ApplePaySession.STATUS_SUCCESS, total, lineItems);
}
paySession.onpaymentauthorized = function (event) {
var token = event.payment.token;
alert("payment authorization | token = " + token);
paySession.completePayment(ApplePaySession.STATUS_SUCCESS);
}
paySession.oncancel = function (event) {
alert("payment cancel error " + event);
}
paySession.begin();
};
You are creating the Apple pay session at the wrong place.You need to create it from server side not on the client side.
These links might help requesting apple pay payment session, complete merchant validation
Steps are discussed here:on validate merchant
This is an old question, but thought I'd post my experience in case it's relevant. I was seeing the same behavior as described by original poster when testing on my local server, but was able to get payment sheet interactions to work.
What worked for me
Log in to AppleID as a Sandbox Test User
Specify "localhost" as the domain when performing merchant validation, e.g.:
{
"merchantIdentifier": "<your merchant ID>",
"displayName": "<your merchant display name>",
"initiative": "web",
"initiativeContext": "localhost"
}

Zapier Cli: Not able to set authentication.connectionLabel dynamically

Following the developer docs, I have attempted numerous variations trying to achieve this.
I would like to extract the label from the token payload, if not I can build it from the /me response body.
This is my latest attempt:
var jwtDecode = require('jwt-decode');
const getTokenFields = (z, bundle) => {
var sub = jwtDecode(bundle.authData.token)['sub']
console.log(sub)
return sub;
};
const getLabelField = (z, bundle) => {
var sub = jwtDecode(bundle.authData.token)['sub']['label']
console.log(sub)
return sub;
};
const authentication = {
type: 'session',
test: {
url: '{{process.env.AP_HOST}}/me'
},
fields: [
{
key: 'token',
type: 'string',
required: true,
helpText: 'See settings to get your token'
}
],
sessionConfig: {
perform: getTokenFields
},
connectionLabel: {
perform: getLabelField
}
};
module.exports = authentication;
the only thing that I can get to work is:
connectionLabel: "{{bundle.authData.token}}", but it looks terrible!
connectionLabel: "{{bundle.authData.responsefield}}" feels like it should be something that should work but it doesn't either
David here, from the Zapier Platform team.
Instead of connectionLabel: {perform: getLabelField}, it should just be connectionLabel: getLabelField. You can also use a string that pulls from the bundle (like you're seeing) or any data that comes back from the designated test endpoint (see here).
There should be validation that prevents what you have (that'll error when you run zapier validate) but if that comes back clean then definitely let us know.

React-Native Firebase Phone Auth freezes iPhone

I want to sign the user in by phoneNumber in react-native. On Android this code snippet works neat. But on iOS always when I start this function the emulator freezes. I am trying to use this code Auth-Example I am using the react-native-firebase library.
openPhoneVerification() {
firebase
.auth()
.signInWithPhoneNumber(this.state.phoneNumber)
.then(confirmResult =>
this.props.navigation.navigate("PhoneVerification", {
confirmResult
})
)
// Wrong number - https://firebase.google.com/docs/reference/js/firebase.auth.Auth#signInWithPhoneNumber
.catch(error =>
Alert.alert(
"Number not valid",
"Please check your number and type in again",
[
{
text: "OK",
style: "cancel"
}
],
{ cancelable: true }
)
);
}
Solution for anyone encountering the same issue:
Make sure that the name given to your APN matches the app name

Resources