-
Notifications
You must be signed in to change notification settings - Fork 7.4k
feat(ai-logic): add hybrid on-device inference sample #2773
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+403
−4
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
f5d6b01
feat(ai-logic): add hybrid on-device inference sample
thatfiredev 737c180
add a hybrid category
thatfiredev 03dff58
lint ?
thatfiredev c0fbec1
address review feedback
thatfiredev 15f6463
remove expense uuid
thatfiredev 09a7700
camera intent and json parsing
thatfiredev aff8f5f
show inference mode on screen
thatfiredev 497a4c2
add camera permission check
thatfiredev File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
10 changes: 10 additions & 0 deletions
10
firebase-ai/app/src/main/java/com/google/firebase/quickstart/ai/feature/hybrid/Expense.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| package com.google.firebase.quickstart.ai.feature.hybrid | ||
|
|
||
| import kotlinx.serialization.Serializable | ||
|
|
||
| @Serializable | ||
| data class Expense( | ||
| val name: String, | ||
| val price: Double, | ||
| val inferenceMode: String = "" | ||
| ) |
153 changes: 153 additions & 0 deletions
153
...rc/main/java/com/google/firebase/quickstart/ai/feature/hybrid/HybridInferenceViewModel.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,153 @@ | ||
| package com.google.firebase.quickstart.ai.feature.hybrid | ||
|
|
||
| import android.graphics.Bitmap | ||
| import android.util.Log | ||
| import androidx.lifecycle.ViewModel | ||
| import androidx.lifecycle.viewModelScope | ||
| import com.google.firebase.Firebase | ||
| import com.google.firebase.ai.InferenceMode | ||
| import com.google.firebase.ai.InferenceSource | ||
| import com.google.firebase.ai.OnDeviceConfig | ||
| import com.google.firebase.ai.ai | ||
| import com.google.firebase.ai.ondevice.DownloadStatus | ||
| import com.google.firebase.ai.ondevice.FirebaseAIOnDevice | ||
| import com.google.firebase.ai.ondevice.OnDeviceModelStatus | ||
| import com.google.firebase.ai.type.GenerativeBackend | ||
| import com.google.firebase.ai.type.PublicPreviewAPI | ||
| import com.google.firebase.ai.type.content | ||
| import com.google.firebase.quickstart.ai.ui.HybridInferenceUiState | ||
| import kotlinx.coroutines.flow.MutableStateFlow | ||
| import kotlinx.coroutines.flow.StateFlow | ||
| import kotlinx.coroutines.flow.asStateFlow | ||
| import kotlinx.coroutines.flow.update | ||
| import kotlinx.coroutines.launch | ||
| import kotlinx.serialization.Serializable | ||
| import kotlinx.serialization.json.Json | ||
| import java.util.UUID | ||
|
|
||
| @Serializable | ||
| object HybridInferenceRoute | ||
|
|
||
| @OptIn(PublicPreviewAPI::class) | ||
| class HybridInferenceViewModel : ViewModel() { | ||
| private val _uiState = MutableStateFlow( | ||
| HybridInferenceUiState( | ||
| expenses = listOf( | ||
| Expense("Lunch", 15.50, "Example data"), | ||
| Expense("Coffee", 4.75, "Example data") | ||
| ) | ||
| ) | ||
| ) | ||
| val uiState: StateFlow<HybridInferenceUiState> = _uiState.asStateFlow() | ||
|
|
||
| private val model = Firebase.ai(backend = GenerativeBackend.googleAI()).generativeModel( | ||
| modelName = "gemini-3.1-flash-lite-preview", | ||
| onDeviceConfig = OnDeviceConfig(mode = InferenceMode.PREFER_ON_DEVICE) | ||
| ) | ||
|
|
||
| init { | ||
| checkAndDownloadModel() | ||
| } | ||
|
|
||
| private fun checkAndDownloadModel() { | ||
| viewModelScope.launch { | ||
| try { | ||
| val status = FirebaseAIOnDevice.checkStatus() | ||
| updateStatus(status) | ||
|
|
||
| if (status == OnDeviceModelStatus.DOWNLOADABLE) { | ||
| FirebaseAIOnDevice.download().collect { downloadStatus -> | ||
| when (downloadStatus) { | ||
| is DownloadStatus.DownloadStarted -> { | ||
| _uiState.update { it.copy(modelStatus = "Downloading model...") } | ||
| } | ||
|
|
||
| is DownloadStatus.DownloadInProgress -> { | ||
| val progress = downloadStatus.totalBytesDownloaded | ||
| _uiState.update { it.copy(modelStatus = "Downloading: $progress bytes downloaded") } | ||
| } | ||
|
|
||
| is DownloadStatus.DownloadCompleted -> { | ||
| _uiState.update { it.copy(modelStatus = "Model ready") } | ||
| } | ||
|
|
||
| is DownloadStatus.DownloadFailed -> { | ||
| _uiState.update { | ||
| it.copy( | ||
| modelStatus = "Download failed", errorMessage = "Model download failed" | ||
| ) | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } catch (e: Exception) { | ||
| _uiState.update { it.copy(modelStatus = "Error checking status", errorMessage = e.message) } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private fun updateStatus(status: OnDeviceModelStatus) { | ||
| val statusText = when (status) { | ||
| OnDeviceModelStatus.AVAILABLE -> "Model available" | ||
| OnDeviceModelStatus.DOWNLOADABLE -> "Model downloadable" | ||
| OnDeviceModelStatus.DOWNLOADING -> "Model downloading..." | ||
| OnDeviceModelStatus.UNAVAILABLE -> "On-device model unavailable" | ||
| else -> "Unknown" | ||
| } | ||
| _uiState.update { it.copy(modelStatus = statusText) } | ||
| } | ||
|
|
||
| fun scanReceipt(bitmap: Bitmap) { | ||
| viewModelScope.launch { | ||
| _uiState.update { it.copy(isScanning = true, errorMessage = null) } | ||
| try { | ||
| val prompt = content { | ||
| image(bitmap) | ||
| text( | ||
| """ | ||
| Extract the store name and the total price from this receipt. | ||
| Output only in JSON format containg 2 fields '{name,price}'. | ||
| Do not include any currency signs or backticks or any text around it. | ||
| Use dots for decimals. | ||
| Examples: | ||
| - {"name": "FakeStore", "price": "2.0"} | ||
| - {"name": "SomeMarket", "price": "3.5"} | ||
| """.trimIndent() | ||
| ) | ||
| } | ||
|
|
||
| val response = model.generateContent(prompt) | ||
| val text = response.text | ||
| val inferenceMode = if (response.inferenceSource == InferenceSource.ON_DEVICE) { | ||
| "On-device" | ||
| } else { | ||
| "Cloud" | ||
| } | ||
| Log.d("HybridVM", "$inferenceMode response: $text") | ||
| if (text != null) { | ||
| parseAndAddExpense(text, inferenceMode) | ||
| } else { | ||
| _uiState.update { it.copy(errorMessage = "Could not extract data") } | ||
| } | ||
| } catch (e: Exception) { | ||
| _uiState.update { it.copy(errorMessage = "Error: ${e.message}") } | ||
| } finally { | ||
| _uiState.update { it.copy(isScanning = false) } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private fun parseAndAddExpense(text: String, inferenceMode: String) { | ||
| val json = text | ||
| // The on-device model sometimes outputs backticks, so we remove those | ||
| .replace("```json", "") | ||
| .replace("```", "") | ||
| try { | ||
| val newExpense = Json.decodeFromString<Expense>(json).copy(inferenceMode = inferenceMode) | ||
| _uiState.update { it.copy(expenses = it.expenses + newExpense) } | ||
| } catch (e: Exception) { | ||
| _uiState.update { it.copy(errorMessage = e.localizedMessage) } | ||
| } | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.