Skip to content

Instantly share code, notes, and snippets.

@apkelly
Last active February 24, 2019 13:24
Show Gist options
  • Save apkelly/cffbb51f2b537c0d0858d70841848618 to your computer and use it in GitHub Desktop.
Save apkelly/cffbb51f2b537c0d0858d70841848618 to your computer and use it in GitHub Desktop.
CloudAutoMLViewModel.kt
companion object {
private const val PROJECT = "devnibbles"
private const val LOCATION = "us-central1"
private const val MODEL = "ICN3704829353327390855"
private const val SERVICE_ACCOUNT_JSON = "<insert json here>"
}
private val mServiceCredentials = ServiceAccountCredentials
.fromStream(ByteArrayInputStream(SERVICE_ACCOUNT_JSON.toByteArray(Charset.defaultCharset())))
.createScoped(mutableListOf("https://www.googleapis.com/auth/cloud-platform"))
fun classifyUsingCloudSDK(faceId: Int, imageBytes: ByteArray) {
launch(errorHandler) {
// Show loading indicator while we wait for the request.
mResult.value = LoadingResource(null)
withContext(Dispatchers.IO) {
// Define the authentication credentials
val settings = PredictionServiceSettings.newBuilder()
.setCredentialsProvider(FixedCredentialsProvider.create(mServiceCredentials)).build()
val predictionServiceClient = PredictionServiceClient.create(settings)
predictionServiceClient.use { client ->
// Build the body of our request, essentially the image to be classified.
val name = ModelName.of(PROJECT, LOCATION, MODEL)
val image = Image.newBuilder().setImageBytes(ByteString.copyFrom(imageBytes)).build()
val payload = ExamplePayload.newBuilder().setImage(image).build()
val params = HashMap<String, String>()
// Make the API request.
val response = client.predict(name, payload, params)
if (response.payloadCount > 0) {
// We have a prediction!
var predictedName: String? = null
response.getPayload(0).allFields.entries.forEach { entry ->
// TODO: Check that score is within a valid threshold.
if (entry.key.jsonName == "displayName") {
predictedName = entry.value as String
}
}
if (predictedName != null) {
// We had an actual name returned
mResult.postValue(SuccessResource(Pair(faceId, predictedName!!)))
} else {
// No name was returned, this is an unknown face.
mResult.postValue(ErrorResource(null, Pair(-1, "Not recognised (001)")))
}
} else {
// There were no payloads returned, possible error or unknown face.
mResult.postValue(ErrorResource(null, Pair(-1, "Not recognised (002)")))
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment