Skip to content

Commit

Permalink
Add foolproof messages for empty settings
Browse files Browse the repository at this point in the history
  • Loading branch information
j3soon committed Jan 27, 2024
1 parent 960fe1d commit e00f5c4
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
package com.example.whispertoinput

import android.content.Context
import android.util.Log
import androidx.datastore.preferences.core.Preferences
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.first
Expand All @@ -41,6 +42,7 @@ class WhisperTranscriber {
val apiKey: String
)

private val TAG = "WhisperTranscriber"
private var currentTranscriptionJob: Job? = null

fun startAsync(
Expand All @@ -55,16 +57,22 @@ class WhisperTranscriber {
// Retrieve configs
val (endpoint, languageCode, isRequestStyleOpenaiApi, apiKey) = context.dataStore.data.map { preferences: Preferences ->
Config(
preferences[ENDPOINT] ?: "",
preferences[ENDPOINT] ?: "",
preferences[LANGUAGE_CODE] ?: "en",
preferences[REQUEST_STYLE] ?: true,
preferences[API_KEY] ?: ""
)
}.first()

// Foolproof message
if (endpoint == "") {
throw Exception(context.getString(R.string.error_endpoint_unset))
}

// Make request
val client = OkHttpClient()
val request = buildWhisperRequest(
context,
filename,
"$endpoint?encode=true&task=transcribe&language=$languageCode&word_timestamps=false&output=txt",
mediaType,
Expand Down Expand Up @@ -108,6 +116,7 @@ class WhisperTranscriber {

// If exception message is not null
if (!exceptionMessage.isNullOrEmpty()) {
Log.e(TAG, exceptionMessage)
exceptionCallback(exceptionMessage)
}
}
Expand All @@ -125,6 +134,7 @@ class WhisperTranscriber {
}

private fun buildWhisperRequest(
context: Context,
filename: String,
url: String,
mediaType: String,
Expand All @@ -150,6 +160,10 @@ class WhisperTranscriber {

val requestHeaders: Headers = Headers.Builder().apply {
if (isRequestStyleOpenaiApi) {
// Foolproof message
if (apiKey == "") {
throw Exception(context.getString(R.string.error_apikey_unset))
}
add("Authorization", "Bearer $apiKey")
}
add("Content-Type", "multipart/form-data")
Expand Down
4 changes: 4 additions & 0 deletions android/app/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@
<string name="btn_previous_ime_hint">Switch To Previous Input Method</string>
<string name="generate_logcat">Generate Recent Logcat</string>

<!-- Warning and Error Messages -->
<string name="error_endpoint_unset">Error: Endpoint is not set in settings.</string>
<string name="error_apikey_unset">Error: OpenAI API Key is not set in settings.</string>

<!-- Settings -->
<string name="whisper_to_input_settings_title">Whisper To Input Settings</string>
<string name="settings_btn_apply">Apply</string>
Expand Down

0 comments on commit e00f5c4

Please sign in to comment.