Skip to content

Commit 3d6e8d9

Browse files
committed
del google-service-on-tflite
1 parent 281c3dd commit 3d6e8d9

6 files changed

Lines changed: 87 additions & 111 deletions

File tree

gradle/libs.versions.toml

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,9 @@ preferenceKtx = "1.2.1"
8787
tensorflowLite = "2.14.0"
8888
tensorflowLiteSupport = "0.4.4"
8989

90+
litert = "2.1.0"
91+
litertSupportAndMetadata = "1.0.0"
92+
9093
[libraries]
9194
androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
9295
androidx-lifecycle-process = { module = "androidx.lifecycle:lifecycle-process", version.ref = "lifecycleRuntimeKtx" }
@@ -180,6 +183,11 @@ androidx-preference-ktx = { module = "androidx.preference:preference-ktx", versi
180183
tensorflow-lite = { module = "org.tensorflow:tensorflow-lite", version.ref = "tensorflowLite" }
181184
tensorflow-lite-support = { module = "org.tensorflow:tensorflow-lite-support", version.ref = "tensorflowLiteSupport" }
182185

186+
187+
litert = { group = "com.google.ai.edge.litert", name = "litert", version.ref = "litert" }
188+
litert-support = { group = "com.google.ai.edge.litert", name = "litert-support", version.ref = "litertSupportAndMetadata" }
189+
litert-metadata = { group = "com.google.ai.edge.litert", name = "litert-metadata", version.ref = "litertSupportAndMetadata" }
190+
183191
[plugins]
184192
androidApplication = { id = "com.android.application", version.ref = "agp" }
185193
androidLibrary = { id = "com.android.library", version.ref = "agp" }

subs/ai/build.gradle.kts

Lines changed: 25 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,16 @@ android {
99

1010
defaultConfig {
1111
minSdk = libs.versions.minSdk.get().toInt()
12-
12+
1313
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
1414
}
1515

1616
buildTypes {
1717
getByName("release") {
1818
isMinifyEnabled = false
19-
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), file("proguard-rules.pro"))
19+
proguardFiles(
20+
getDefaultProguardFile("proguard-android-optimize.txt"), file("proguard-rules.pro")
21+
)
2022
}
2123
}
2224

@@ -30,14 +32,12 @@ android {
3032
}
3133

3234
compileOptions {
33-
sourceCompatibility = JavaVersion.VERSION_17
34-
targetCompatibility = JavaVersion.VERSION_17
35-
}
36-
kotlinOptions {
37-
jvmTarget = "17"
35+
sourceCompatibility = JavaVersion.VERSION_21
36+
targetCompatibility = JavaVersion.VERSION_21
3837
}
38+
3939
androidResources {
40-
noCompress("tflite")
40+
noCompress.add("tflite")
4141
}
4242
buildFeatures {
4343
viewBinding = true
@@ -54,12 +54,22 @@ dependencies {
5454
androidTestImplementation(libs.androidx.espresso.core)
5555

5656
implementation(libs.android.draw)
57-
implementation(libs.play.services.tasks)
58-
59-
implementation(libs.play.services.tflite.java)
60-
implementation(libs.play.services.tflite.support)
61-
62-
implementation(libs.tensorflow.lite)
63-
implementation(libs.tensorflow.lite.support)
57+
// implementation(libs.play.services.tasks)
6458

59+
implementation(libs.litert)
60+
implementation(libs.litert.support) {
61+
exclude(group = "com.google.ai.edge.litert", module = "litert-api")
62+
}
63+
implementation(libs.litert.metadata) {
64+
exclude(group = "com.google.ai.edge.litert", module = "litert-api")
65+
}
66+
// implementation(libs.play.services.tflite.java) {
67+
// exclude(group = "com.google.ai.edge.litert", module = "litert-api")
68+
// }
69+
// implementation(libs.play.services.tflite.support) {
70+
// exclude(group = "com.google.ai.edge.litert", module = "litert-api")
71+
// }
72+
//
73+
// implementation(libs.tensorflow.lite)
74+
// implementation(libs.tensorflow.lite.support)
6575
}

subs/ai/src/main/java/com/engineer/ai/GanActivity.kt

Lines changed: 25 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -66,37 +66,34 @@ class GanActivity : AppCompatActivity() {
6666
}
6767

6868
private fun genBitmap() {
69-
TensorFlowLiteHelper.init(this) { playServicesOk ->
70-
val interpreterApi = TensorFlowLiteHelper.createInterpreterApi(
71-
context = this,
72-
modelName = "dcgan.tflite",
73-
preferPlayServices = playServicesOk
74-
)
75-
interpreterApi.let {
76-
Log.d(TAG, interpreterApi.getInputTensor(0).shape().contentToString())
77-
Log.d(TAG, interpreterApi.getOutputTensor(0).shape().contentToString())
78-
79-
80-
val noise = generateNoise(100)
81-
82-
// 2. 创建输入张量
83-
val inputBuffer =
84-
TensorBuffer.createFixedSize(intArrayOf(1, 100), DataType.FLOAT32).apply {
85-
loadArray(noise)
86-
}
69+
val interpreterApi = TensorFlowLiteHelper.createInterpreterApi(
70+
context = this, modelName = "dcgan.tflite"
71+
)
72+
interpreterApi.let {
73+
Log.d(TAG, interpreterApi.getInputTensor(0).shape().contentToString())
74+
Log.d(TAG, interpreterApi.getOutputTensor(0).shape().contentToString())
8775

88-
// 3. 准备输出张量 [1, 3, 64, 64]
89-
val outputBuffer =
90-
TensorBuffer.createFixedSize(intArrayOf(1, 3, 64, 64), DataType.FLOAT32)
91-
it.run(inputBuffer, outputBuffer)
92-
Log.d(TAG, outputBuffer.floatArray.contentToString())
9376

94-
val bitmap = convertOutputToBitmap(outputBuffer.floatArray, 64, 64)
95-
bitmapList.clear()
96-
bitmapList.add(bitmap)
97-
adapter.notifyDataSetChanged()
98-
}
77+
val noise = generateNoise(100)
78+
79+
// 2. 创建输入张量
80+
val inputBuffer =
81+
TensorBuffer.createFixedSize(intArrayOf(1, 100), DataType.FLOAT32).apply {
82+
loadArray(noise)
83+
}
84+
85+
// 3. 准备输出张量 [1, 3, 64, 64]
86+
val outputBuffer =
87+
TensorBuffer.createFixedSize(intArrayOf(1, 3, 64, 64), DataType.FLOAT32)
88+
it.run(inputBuffer, outputBuffer)
89+
Log.d(TAG, outputBuffer.floatArray.contentToString())
90+
91+
val bitmap = convertOutputToBitmap(outputBuffer.floatArray, 64, 64)
92+
bitmapList.clear()
93+
bitmapList.add(bitmap)
94+
adapter.notifyDataSetChanged()
9995
}
96+
10097
}
10198

10299
private fun generateNoise(size: Int): FloatArray {

subs/ai/src/main/java/com/engineer/ai/util/DigitClassifier.kt

Lines changed: 26 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,6 @@ import java.util.concurrent.Executors
2525

2626
class DigitClassifier(private val context: Context) {
2727

28-
// private var interpreter: Interpreter? = null
29-
3028
var isInitialized = false
3129
private set
3230

@@ -40,37 +38,34 @@ class DigitClassifier(private val context: Context) {
4038
private var interpreter: InterpreterApi? = null
4139

4240
fun initialize(cb: (Boolean) -> Unit) {
43-
TensorFlowLiteHelper.init(context) { playServicesOk ->
44-
try {
45-
interpreter = TensorFlowLiteHelper.createInterpreterApi(
46-
context = context,
47-
modelName = "mnist.tflite",
48-
preferPlayServices = playServicesOk
49-
)
50-
51-
val inter = interpreter
52-
if (inter == null) {
53-
isInitialized = false
54-
cb(false)
55-
return@init
56-
}
57-
58-
val inputShape = inter.getInputTensor(0).shape()
59-
Log.d(TAG, "input shape = ${inputShape.contentToString()}")
60-
Log.d(TAG, "elem shape = ${inter.getInputTensor(0).numElements()}")
61-
Log.d(TAG, "output shape = ${inter.getOutputTensor(0).shape().contentToString()}")
62-
63-
inputImageWidth = inputShape[1]
64-
inputImageHeight = inputShape[2]
65-
modelInputSize = FLOAT_TYPE_SIZE * inputImageWidth * inputImageHeight * PIXEL_SIZE
66-
isInitialized = true
67-
cb(true)
68-
} catch (t: Throwable) {
69-
Log.e(TAG, "Failed to initialize DigitClassifier.", t)
41+
try {
42+
interpreter = TensorFlowLiteHelper.createInterpreterApi(
43+
context = context, modelName = "mnist.tflite"
44+
)
45+
46+
val inter = interpreter
47+
if (inter == null) {
7048
isInitialized = false
7149
cb(false)
50+
return
7251
}
52+
53+
val inputShape = inter.getInputTensor(0).shape()
54+
Log.d(TAG, "input shape = ${inputShape.contentToString()}")
55+
Log.d(TAG, "elem shape = ${inter.getInputTensor(0).numElements()}")
56+
Log.d(TAG, "output shape = ${inter.getOutputTensor(0).shape().contentToString()}")
57+
58+
inputImageWidth = inputShape[1]
59+
inputImageHeight = inputShape[2]
60+
modelInputSize = FLOAT_TYPE_SIZE * inputImageWidth * inputImageHeight * PIXEL_SIZE
61+
isInitialized = true
62+
cb(true)
63+
} catch (t: Throwable) {
64+
Log.e(TAG, "Failed to initialize DigitClassifier.", t)
65+
isInitialized = false
66+
cb(false)
7367
}
68+
7469
}
7570

7671

@@ -91,7 +86,8 @@ class DigitClassifier(private val context: Context) {
9186
val result = output[0]
9287
Log.d(TAG, "result = ${result.contentToString()}")
9388
val maxIndex = result.indices.maxBy { result[it] }
94-
val resultString = "Prediction Result: %d\nConfidence: %2f".format(maxIndex, result[maxIndex])
89+
val resultString =
90+
"Prediction Result: %d\nConfidence: %2f".format(maxIndex, result[maxIndex])
9591

9692
return resultString
9793

subs/ai/src/main/java/com/engineer/ai/util/TensorFlowLiteHelper.kt

Lines changed: 2 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,7 @@ package com.engineer.ai.util
33
import android.content.Context
44
import android.content.res.AssetManager
55
import android.graphics.Bitmap
6-
import android.util.Log
7-
import com.google.android.gms.tasks.Task
8-
import com.google.android.gms.tflite.java.TfLite
96
import org.tensorflow.lite.InterpreterApi
10-
import org.tensorflow.lite.TensorFlowLite
117
import java.io.FileInputStream
128
import java.io.IOException
139
import java.nio.ByteBuffer
@@ -17,42 +13,10 @@ import java.nio.channels.FileChannel
1713
object TensorFlowLiteHelper {
1814
private const val TAG = "TensorFlowLiteHelper"
1915

20-
/**
21-
* Try to init Google Play Services TFLite (dynamite module).
22-
*
23-
* This will fail on devices without Google Play Services (e.g. many CN ROMs).
24-
* We treat failure as non-fatal and fall back to bundled TFLite runtime.
25-
*/
26-
fun init(context: Context, cb: (Boolean) -> Unit) {
27-
TfLite.initialize(context)
28-
.addOnSuccessListener {
29-
Log.d(TAG, "Initialized Play Services TFLite.")
30-
try {
31-
Log.d(
32-
TAG,
33-
"schema=${TensorFlowLite.schemaVersion(InterpreterApi.Options.TfLiteRuntime.FROM_SYSTEM_ONLY)} runtime=${TensorFlowLite.runtimeVersion(InterpreterApi.Options.TfLiteRuntime.FROM_SYSTEM_ONLY)}"
34-
)
35-
} catch (t: Throwable) {
36-
Log.w(TAG, "Unable to query system-only TFLite version.", t)
37-
}
38-
cb(true)
39-
}
40-
.addOnFailureListener { e ->
41-
Log.w(TAG, "Play Services TFLite init failed; will fall back to bundled runtime.", e)
42-
cb(false)
43-
}
44-
}
4516

46-
fun createInterpreterApi(context: Context, modelName: String, preferPlayServices: Boolean): InterpreterApi {
17+
fun createInterpreterApi(context: Context, modelName: String): InterpreterApi {
4718
val model = loadModelFile(context.assets, modelName)
48-
49-
val runtime = if (preferPlayServices) {
50-
InterpreterApi.Options.TfLiteRuntime.FROM_SYSTEM_ONLY
51-
} else {
52-
// Bundled runtime provided by org.tensorflow:tensorflow-lite
53-
InterpreterApi.Options.TfLiteRuntime.FROM_APPLICATION_ONLY
54-
}
55-
19+
val runtime = InterpreterApi.Options.TfLiteRuntime.FROM_APPLICATION_ONLY
5620
val options = InterpreterApi.Options().setRuntime(runtime)
5721
return InterpreterApi.create(model, options)
5822
}

subs/ai/src/main/res/layout/activity_digital_classification.xml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
android:text="@string/prediction_text_placeholder"
2424
android:textSize="20sp"
2525
android:textStyle="bold"
26+
android:lines="2"
2627
app:layout_constraintBottom_toTopOf="@id/clear_button"
2728
app:layout_constraintLeft_toLeftOf="parent"
2829
app:layout_constraintRight_toRightOf="parent"

0 commit comments

Comments
 (0)