Reputation: 2398
I've recently received permission to use Imagen from Google Cloud and decided to implement it on an Android project. This is the current code:
class CallImagen3UseCase @Inject constructor(
@ApplicationContext val context: Context
) : ICallImagen3UseCase {
override suspend fun call(): String? = suspendCoroutine { continuation ->
val okHttpClient = OkHttpClient.Builder()
.readTimeout(60, TimeUnit.SECONDS)
.connectTimeout(60, TimeUnit.SECONDS)
.build()
val retrofit: Retrofit = Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build()
val service = retrofit.create(GoogleImagenService::class.java)
val json = """
{
"instances": [
{
"prompt": "Create a fire elemental"
}
],
"parameters": {
"sampleCount": 1
}
}
""".trimIndent()
val requestBody: RequestBody = json.toRequestBody("application/json".toMediaTypeOrNull())
val call: Call<ResponseBody> = service.generateImagen3(requestBody)
call.enqueue(object : Callback<ResponseBody> {
override fun onResponse(p0: Call<ResponseBody>, response: Response<ResponseBody>) {
if (response.isSuccessful) {
try {
val responseBody = response.body()!!.string()
... // More code
} catch (e: IOException) {
Log.e("Imagen Error1", e.message.toString())
continuation.resumeWith(Result.success(null))
}
} else {
Log.e("Imagen Error2", response.message())
continuation.resumeWith(Result.success(null))
}
}
override fun onFailure(p0: Call<ResponseBody>, p1: Throwable) {
Log.e("Imagen Error3", p1.message.toString())
continuation.resumeWith(Result.success(null))
}
})
}
companion object {
const val location = "us-west1"
private const val url = "https://$location-aiplatform.googleapis.com/"
}
}
interface GoogleImagenService {
@Headers(
contentType,
authorization
)
@POST(imagen3Url)
fun generateImagen3(@Body body: RequestBody): Call<ResponseBody>
}
private const val model2 = "imagegeneration@006"
private const val token = "myToken"
private const val contentType = "Content-Type: application/json"
private const val authorization = "Authorization: Bearer $token"
private const val projectId = "projectID"
private const val imagen3Url = "v1/projects/$projectId/locations/$location/publishers/google/models/$model2:predict"
All requests are returning either 401 or 403. Is there anything missing? I've been using this code for two differents APIs and they return correctly.
Also, from what I've seen, it may not be a good practice to use this API on a front-end project since the bearer "Bearer $(gcloud auth print-access-token)" might need to be validated or updated constantly.
The original curl is from the documentation here
Upvotes: 0
Views: 41