diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3787a9b..f9cbcd7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -17,3 +17,19 @@ jobs: java-version: 17 - uses: gradle/actions/setup-gradle@v4 - run: ./gradlew :sip:test :gateway:test + + phone-apk: + # The phone app needs no native code, so CI can compile both flavors. + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: 17 + - uses: gradle/actions/setup-gradle@v4 + - run: ./gradlew :phone:assembleFullDebug :phone:assembleFossDebug + - uses: actions/upload-artifact@v4 + with: + name: simbridge-phone-debug + path: phone/build/outputs/apk/**/*.apk diff --git a/CHANGELOG.md b/CHANGELOG.md index 492e74b..9eb3b94 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,17 @@ # Changelog +## SimBridge 2.2.0 + +### Main phone +- **Live call translation** for relayed calls (Settings > Call translation): + - **Captions:** the caller's words appear translated in a floating window over the call screen + (or tap Translate in the call notification for full screen). + - **Captions + voice:** your words are also spoken to the caller in their language. + - 19 languages (Turkish, English, Arabic, Persian, Russian, Ukrainian, French, German, Spanish and more). + - Free engines: Groq GPT-OSS 120B / 20B, Cerebras GPT-OSS 120B, Google Gemini 2.5 Flash-Lite, + or on-device (ML Kit, full build only). Speech recognition: Groq Whisper or on-device. + - Options: pause length, read the caller's translation to you, large text, on-device only. + ## SimBridge 2.1.0 ### Main phone diff --git a/phone/build.gradle.kts b/phone/build.gradle.kts index f12b86d..74d8c3f 100644 --- a/phone/build.gradle.kts +++ b/phone/build.gradle.kts @@ -14,8 +14,8 @@ android { applicationId = "io.github.simbridge" minSdk = 34 targetSdk = 36 - versionCode = 220 - versionName = "2.1.0" + versionCode = 230 + versionName = "2.2.0" } // Same signing source as the gateway app: a git-ignored signing.properties in the project root. val localSigning = Properties().apply { @@ -56,6 +56,8 @@ android { create("full") { dimension = "store" buildConfigField("boolean", "UPDATE_CHECK_DEFAULT", "true") + // ML Kit translation ships a ~16 MB native lib per ABI; Android 14+ phones are arm64. + ndk { abiFilters += "arm64-v8a" } } create("foss") { dimension = "store" @@ -79,5 +81,7 @@ dependencies { implementation(libs.kotlinx.coroutines.android) // QR scanning for pairing via Google Play services (no camera permission needed). "fullImplementation"("com.google.android.gms:play-services-code-scanner:16.1.0") + // On-device Turkish/English translation for call captions (offline fallback). + "fullImplementation"("com.google.mlkit:translate:17.0.3") } diff --git a/phone/fastlane/metadata/android/en-US/changelogs/230.txt b/phone/fastlane/metadata/android/en-US/changelogs/230.txt new file mode 100644 index 0000000..9d827e0 --- /dev/null +++ b/phone/fastlane/metadata/android/en-US/changelogs/230.txt @@ -0,0 +1 @@ +Live call translation: captions of the caller's words in your language in a floating window, and optional translated voice to the caller. 19 languages; free cloud engines (Groq, Cerebras, Gemini) or on-device. diff --git a/phone/src/foss/kotlin/io/github/simbridge/OfflineTranslate.kt b/phone/src/foss/kotlin/io/github/simbridge/OfflineTranslate.kt new file mode 100644 index 0000000..9a0f3b3 --- /dev/null +++ b/phone/src/foss/kotlin/io/github/simbridge/OfflineTranslate.kt @@ -0,0 +1,15 @@ +package io.github.simbridge + +import android.content.Context + +/** F-Droid build: no Google ML Kit, so translation needs the cloud (Groq key). */ +object OfflineTranslate { + fun translate(@Suppress("UNUSED_PARAMETER") ctx: Context, @Suppress("UNUSED_PARAMETER") text: String, + @Suppress("UNUSED_PARAMETER") from: String, @Suppress("UNUSED_PARAMETER") to: String): String? { + Captions.say("Offline translation isn't in the F-Droid build: add a Groq key in Settings") + return null + } + + @Suppress("UNUSED_PARAMETER") fun prepare(ctx: Context, a: String, b: String) = Unit + +} diff --git a/phone/src/full/kotlin/io/github/simbridge/OfflineTranslate.kt b/phone/src/full/kotlin/io/github/simbridge/OfflineTranslate.kt new file mode 100644 index 0000000..27f7aae --- /dev/null +++ b/phone/src/full/kotlin/io/github/simbridge/OfflineTranslate.kt @@ -0,0 +1,32 @@ +package io.github.simbridge + +import android.content.Context +import com.google.android.gms.tasks.Tasks +import com.google.mlkit.nl.translate.Translation +import com.google.mlkit.nl.translate.Translator +import com.google.mlkit.nl.translate.TranslatorOptions +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.TimeUnit + +/** On-device translation with Google ML Kit (free, offline once the ~30 MB models are downloaded). */ +object OfflineTranslate { + private val clients = ConcurrentHashMap() + + private fun client(from: String, to: String) = clients.getOrPut("$from>$to") { + Translation.getClient(TranslatorOptions.Builder().setSourceLanguage(from).setTargetLanguage(to).build()) + } + + /** Worker thread only: blocks until translated (downloads the model the first time). */ + fun translate(@Suppress("UNUSED_PARAMETER") ctx: Context, text: String, from: String, to: String): String? = runCatching { + val t = client(from, to) + Tasks.await(t.downloadModelIfNeeded(), 90, TimeUnit.SECONDS) + Tasks.await(t.translate(text), 10, TimeUnit.SECONDS) + }.onFailure { Log.w("translate: on-device translation failed", it); Captions.say("On-device translation failed: ${it.message}") }.getOrNull() + + /** Downloads both directions of a language pair in the background. */ + fun prepare(@Suppress("UNUSED_PARAMETER") ctx: Context, a: String, b: String) { + client(a, b).downloadModelIfNeeded() + client(b, a).downloadModelIfNeeded() + } + +} diff --git a/phone/src/main/AndroidManifest.xml b/phone/src/main/AndroidManifest.xml index 59a8162..30e9a05 100644 --- a/phone/src/main/AndroidManifest.xml +++ b/phone/src/main/AndroidManifest.xml @@ -28,6 +28,8 @@ + + + + + () + var info by mutableStateOf("") + var mode by mutableStateOf(TranslateMode.OFF) + private val main = Handler(Looper.getMainLooper()) + fun add(c: Caption) { main.post { lines += c; if (lines.size > 300) lines.removeAt(0) } } + fun update(id: Long, translated: String) { + main.post { val i = lines.indexOfFirst { it.id == id }; if (i >= 0) lines[i] = lines[i].copy(translated = translated) } + } + fun say(s: String) { main.post { info = s } } + fun showMode(m: TranslateMode) { main.post { mode = m } } + fun clear() { main.post { lines.clear(); info = "" } } +} + +/** + * Translates one call. The audio thread only measures loudness and queues finished utterances; + * recognition, translation and speech run on one worker per direction, so the call never stutters. + */ +class CallTranslator(private val ctx: Context, private val prefs: Prefs, private val rate: Int, private val frame: Int) { + private val callerLang = prefs.callerLang + private val myLang = prefs.myLang + private val speech = Speech(ctx, prefs) + private val callerJobs = Executors.newSingleThreadExecutor() + private val myJobs = Executors.newSingleThreadExecutor() + private val theirs = Segmenter(rate, prefs.pauseMs) { pcm -> runCatching { callerJobs.execute { handle(pcm, fromCaller = true) } } } + private val mine = Segmenter(rate, prefs.pauseMs) { pcm -> runCatching { myJobs.execute { handle(pcm, fromCaller = false) } } } + /** Translated speech for the caller, and for me, in call-sized frames (up to 60 s each). */ + private val toCaller = LinkedBlockingQueue(3000) + private val toMe = LinkedBlockingQueue(3000) + private val silence = ShortArray(frame) + private val recent = ArrayDeque() + private val seq = AtomicLong() + private var voice: Voice? = null + + @Volatile var mode: TranslateMode = prefs.translateMode + set(v) { + field = v + Captions.showMode(v) + if (v == TranslateMode.VOICE || prefs.speakToMe) runCatching { myJobs.execute { voice() } } // warm up TTS + } + + init { + Captions.showMode(mode) + if (mode == TranslateMode.VOICE || prefs.speakToMe) myJobs.execute { voice() } + Thread({ speech.warmUp() }, "translate-warmup").start() + } + + /** Audio thread: one frame of the caller's voice, as received. */ + fun heard(down: ShortArray) { + if (mode != TranslateMode.OFF) theirs.push(down) + } + + /** Audio thread: what I hear; translations read to me are mixed over the (quieter) caller. */ + fun downlink(down: ShortArray): ShortArray { + if (mode == TranslateMode.OFF) { toMe.clear(); return down } + val t = toMe.poll() ?: return down + return ShortArray(down.size) { i -> (down[i] * 0.3 + t[i]).toInt().coerceIn(-32768, 32767).toShort() } + } + + /** Audio thread: one frame from my mic; returns what the caller hears instead. */ + fun uplink(mic: ShortArray): ShortArray { + if (mode != TranslateMode.VOICE) { toCaller.clear(); return mic } + mine.push(mic) + return toCaller.poll() ?: silence + } + + fun close() { + callerJobs.shutdownNow(); myJobs.shutdownNow() + synchronized(this) { voice?.shutdown(); voice = null } + } + + @Synchronized private fun voice(): Voice = voice ?: Voice(ctx).also { voice = it } + + private fun handle(pcm: ShortArray, fromCaller: Boolean) { + if (mode == TranslateMode.OFF) return + val from = if (fromCaller) callerLang else myLang + val to = if (fromCaller) myLang else callerLang + val t0 = System.currentTimeMillis() + val heard = speech.transcribe(pcm, rate, from)?.trim().orEmpty() + val t1 = System.currentTimeMillis() + if (heard.isEmpty() || Speech.isJunk(heard)) return + val id = seq.incrementAndGet() + Captions.add(Caption(id, fromCaller, heard, null)) // show what was heard right away + val context = synchronized(recent) { recent.toList() } + val said = speech.translate(heard, from, to, context)?.trim() + val t2 = System.currentTimeMillis() + Captions.update(id, said ?: "(not translated)") + synchronized(recent) { recent.addLast(heard); while (recent.size > 3) recent.removeFirst() } + var tts = 0L + if (!said.isNullOrEmpty()) { + val target = when { + !fromCaller && mode == TranslateMode.VOICE -> toCaller + fromCaller && prefs.speakToMe -> toMe + else -> null + } + if (target != null) { + val out = voice().synth(said, to, rate) + tts = System.currentTimeMillis() - t2 + if (out != null) enqueue(out, target) + } + } + Log.i("translate: ${if (fromCaller) "caller" else "me"} audio=${pcm.size * 1000L / rate}ms stt=${t1 - t0}ms mt=${t2 - t1}ms tts=${tts}ms") + } + + private fun enqueue(out: ShortArray, q: LinkedBlockingQueue) { + var i = 0 + while (i < out.size) { + val f = ShortArray(frame) + System.arraycopy(out, i, f, 0, minOf(frame, out.size - i)) + if (!q.offer(f)) break + i += frame + } + } +} + +/** + * Cuts 20 ms frames into utterances by loudness: starts on speech (with 300 ms lead-in), + * ends after [pauseMs] of quiet or 15 s. The noise floor adapts so line hiss doesn't count as speech. + */ +class Segmenter(private val rate: Int, private val pauseMs: Int, private val onUtterance: (ShortArray) -> Unit) { + private val lead = ArrayDeque() + private val out = ArrayList() + private var speaking = false + private var loudMs = 0 + private var quietMs = 0 + private var floor = 200.0 + + fun push(frame: ShortArray) { + val f = frame.copyOf() + val ms = f.size * 1000 / rate + val level = rms(f) + val loud = level > max(MIN_LEVEL, floor * 3) + if (!speaking) { + if (!loud) floor = floor * 0.95 + level * 0.05 + lead.addLast(f) + while (lead.size * ms > 300) lead.removeFirst() + if (loud) { speaking = true; loudMs = ms; quietMs = 0; out.addAll(lead); lead.clear() } + return + } + out += f + if (loud) { loudMs += ms; quietMs = 0 } else quietMs += ms + if (quietMs >= pauseMs || out.size * ms >= 15_000) { + if (loudMs >= 300) onUtterance(Pcm.concat(out)) + speaking = false + out.clear() + } + } + + private fun rms(f: ShortArray): Double { + var s = 0.0 + for (v in f) s += v.toDouble() * v + return sqrt(s / max(1, f.size)) + } + + private companion object { const val MIN_LEVEL = 300.0 } +} + +/** Small PCM16 helpers: join, resample, WAV in and out. */ +object Pcm { + fun concat(parts: List): ShortArray { + val all = ShortArray(parts.sumOf { it.size }) + var o = 0 + for (p in parts) { System.arraycopy(p, 0, all, o, p.size); o += p.size } + return all + } + + /** Linear resampling; when going down, averages each window first so 24 kHz TTS doesn't alias at 8 kHz. */ + fun resample(x: ShortArray, from: Int, to: Int): ShortArray { + if (from == to || x.isEmpty()) return x + val ratio = from.toDouble() / to + val n = (x.size / ratio).toInt() + return ShortArray(n) { i -> + val p = i * ratio + if (ratio > 1) { + val a = p.toInt(); val b = minOf(x.size, (p + ratio).toInt().coerceAtLeast(a + 1)) + var s = 0L + for (j in a until b) s += x[j] + (s / (b - a)).toInt().toShort() + } else { + val j = p.toInt(); val t = p - j + val a = x[minOf(j, x.size - 1)]; val b = x[minOf(j + 1, x.size - 1)] + (a + (b - a) * t).toInt().toShort() + } + } + } + + fun bytes(x: ShortArray): ByteArray { + val b = ByteArray(x.size * 2) + for (i in x.indices) { b[2 * i] = x[i].toInt().toByte(); b[2 * i + 1] = (x[i].toInt() shr 8).toByte() } + return b + } + + fun wav(x: ShortArray, rate: Int): ByteArray { + val data = bytes(x) + val h = java.nio.ByteBuffer.allocate(44).order(java.nio.ByteOrder.LITTLE_ENDIAN) + h.put("RIFF".toByteArray()).putInt(36 + data.size).put("WAVE".toByteArray()) + h.put("fmt ".toByteArray()).putInt(16).putShort(1).putShort(1).putInt(rate).putInt(rate * 2).putShort(2).putShort(16) + h.put("data".toByteArray()).putInt(data.size) + return h.array() + data + } + + /** Reads a 16-bit PCM WAV (first channel) and resamples it to [rate]. */ + fun readWav(file: java.io.File, rate: Int): ShortArray? { + val b = java.nio.ByteBuffer.wrap(file.readBytes()).order(java.nio.ByteOrder.LITTLE_ENDIAN) + if (b.remaining() < 12) return null + b.position(12) + var src = 0; var ch = 1 + while (b.remaining() >= 8) { + val id = ByteArray(4).also { b.get(it) }.decodeToString() + var len = b.int + if (id == "fmt ") { + val start = b.position() + b.short; ch = b.short.toInt(); src = b.int + b.position(start + len) + } else if (id == "data") { + if (len <= 0 || len > b.remaining()) len = b.remaining() + if (src == 0) return null + val n = len / 2 / ch + val x = ShortArray(n) { i -> b.getShort(b.position() + i * 2 * ch) } + return resample(x, src, rate) + } else { + b.position(minOf(b.limit(), b.position() + len + (len and 1))) + } + } + return null + } +} diff --git a/phone/src/main/kotlin/io/github/simbridge/CaptionActivity.kt b/phone/src/main/kotlin/io/github/simbridge/CaptionActivity.kt new file mode 100644 index 0000000..1261227 --- /dev/null +++ b/phone/src/main/kotlin/io/github/simbridge/CaptionActivity.kt @@ -0,0 +1,101 @@ +package io.github.simbridge + +import android.os.Bundle +import android.view.WindowManager +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.FilterChip +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import io.github.simbridge.ui.LinkTheme + +/** Live captions of the call, over the lock screen. Opened from the bubble or the in-call notification. */ +class CaptionActivity : ComponentActivity() { + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setShowWhenLocked(true) + window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) + val prefs = LinkApp.core(this).prefs + setContent { + LinkTheme { + Scaffold { pad -> + Column(Modifier.fillMaxSize().padding(pad).padding(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { + ModeChips() + if (ActiveCall.current == null) Text(stringResource(R.string.tr_no_call), style = MaterialTheme.typography.bodyMedium) + CaptionList(Modifier.weight(1f), large = prefs.captionLarge) + } + } + } + } + } +} + +/** Off / Captions / Captions + voice for the call in progress. */ +@Composable +internal fun ModeChips() { + val call = ActiveCall.current + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + listOf(TranslateMode.OFF to R.string.tr_off, TranslateMode.CAPTIONS to R.string.tr_captions, + TranslateMode.VOICE to R.string.tr_voice).forEach { (m, label) -> + FilterChip(Captions.mode == m, { call?.translator?.mode = m }, { Text(stringResource(label)) }, enabled = call != null) + } + } +} + +/** + * Status line plus the scrolling caption chat; newest at the bottom. Laid out bottom-up so a line + * growing (its translation arriving) stays in view; follows new lines unless I scrolled back to read. + */ +@Composable +internal fun CaptionList(modifier: Modifier, large: Boolean, compact: Boolean = false) { + val list = rememberLazyListState() + val newest = Captions.lines.asReversed() + LaunchedEffect(Captions.lines.size) { if (list.firstVisibleItemIndex <= 1) list.animateScrollToItem(0) } + Column(modifier) { + if (Captions.info.isNotEmpty()) Text(Captions.info, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error) + LazyColumn(Modifier.fillMaxWidth(), state = list, reverseLayout = true, + verticalArrangement = Arrangement.spacedBy(if (compact) 4.dp else 8.dp, Alignment.Bottom)) { + items(newest, key = { it.id }) { CaptionLine(it, large, compact) } + } + } +} + +@Composable +private fun CaptionLine(c: Caption, large: Boolean, compact: Boolean) { + val bg = if (c.fromCaller) MaterialTheme.colorScheme.surfaceVariant else MaterialTheme.colorScheme.primaryContainer + val fg = if (c.fromCaller) MaterialTheme.colorScheme.onSurface else MaterialTheme.colorScheme.onPrimaryContainer + // Big line: what I need to read (caller's words in my language; my words as I said them). + val main = if (c.fromCaller) c.translated ?: c.heard else c.heard + val sub = if (c.fromCaller) (if (c.translated == null) "…" else c.heard) else c.translated ?: "…" + val big = when { compact -> 16.sp; large -> 26.sp; else -> 21.sp } + val small = when { compact -> 13.sp; large -> 19.sp; else -> 16.sp } + Box(Modifier.fillMaxWidth(), contentAlignment = if (c.fromCaller) Alignment.CenterStart else Alignment.CenterEnd) { + Card(Modifier.fillMaxWidth(0.9f), colors = CardDefaults.cardColors(containerColor = bg, contentColor = fg)) { + Column(Modifier.padding(if (compact) 8.dp else 12.dp)) { + Text(main, fontSize = big, lineHeight = big * 1.25f, fontWeight = FontWeight.Medium, color = fg) + Text(sub, fontSize = small, lineHeight = small * 1.25f, color = fg.copy(alpha = 0.85f)) + } + } + } +} diff --git a/phone/src/main/kotlin/io/github/simbridge/CaptionBubble.kt b/phone/src/main/kotlin/io/github/simbridge/CaptionBubble.kt new file mode 100644 index 0000000..a82c963 --- /dev/null +++ b/phone/src/main/kotlin/io/github/simbridge/CaptionBubble.kt @@ -0,0 +1,132 @@ +package io.github.simbridge + +import android.content.Context +import android.content.Intent +import android.graphics.PixelFormat +import android.provider.Settings +import android.view.Gravity +import android.view.WindowManager +import androidx.compose.foundation.clickable +import androidx.compose.foundation.gestures.detectDragGestures +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.OpenInFull +import androidx.compose.material.icons.filled.Translate +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.platform.ComposeView +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.LifecycleOwner +import androidx.lifecycle.LifecycleRegistry +import androidx.lifecycle.setViewTreeLifecycleOwner +import androidx.savedstate.SavedStateRegistry +import androidx.savedstate.SavedStateRegistryController +import androidx.savedstate.SavedStateRegistryOwner +import androidx.savedstate.setViewTreeSavedStateRegistryOwner +import io.github.simbridge.ui.LinkTheme + +/** + * Floating translate button over the call screen (needs "Display over other apps"). + * Tap: a small chat window with the mode buttons; drag to move. Main thread only. + */ +class CaptionBubble(private val ctx: Context) { + private val wm = ctx.getSystemService(WindowManager::class.java) + private var view: ComposeView? = null + private var owner: OverlayOwner? = null + private val lp = WindowManager.LayoutParams( + WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT, + WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY, + WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT, + ).apply { gravity = Gravity.TOP or Gravity.END; x = 24; y = 360 } + + fun show() { + if (view != null || !Settings.canDrawOverlays(ctx)) return + val o = OverlayOwner().also { owner = it } + val v = ComposeView(ctx).apply { + setViewTreeLifecycleOwner(o) + setViewTreeSavedStateRegistryOwner(o) + } + v.setContent { LinkTheme { Bubble(::move, ::openFull) } } + if (runCatching { wm.addView(v, lp) }.isSuccess) view = v else o.destroy() + } + + fun hide() { + view?.let { runCatching { wm.removeView(it) } } + view = null + owner?.destroy(); owner = null + } + + private fun move(dx: Float, dy: Float) { + val v = view ?: return + lp.x = (lp.x - dx.toInt()).coerceAtLeast(0) // gravity END: x counts from the right edge + lp.y = (lp.y + dy.toInt()).coerceAtLeast(0) + runCatching { wm.updateViewLayout(v, lp) } + } + + private fun openFull() { + runCatching { ctx.startActivity(Intent(ctx, CaptionActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) } + } +} + +@androidx.compose.runtime.Composable +private fun Bubble(move: (Float, Float) -> Unit, openFull: () -> Unit) { + var open by remember { mutableStateOf(false) } + val drag = Modifier.pointerInput(Unit) { detectDragGestures { change, d -> change.consume(); move(d.x, d.y) } } + if (!open) { + Surface(drag.size(56.dp).clickable { open = true }, shape = CircleShape, + color = MaterialTheme.colorScheme.primary, shadowElevation = 6.dp) { + Box(contentAlignment = Alignment.Center) { + Icon(Icons.Filled.Translate, stringResource(R.string.translate), tint = MaterialTheme.colorScheme.onPrimary) + } + } + } else { + Surface(Modifier.width(310.dp).heightIn(max = 420.dp), shape = RoundedCornerShape(20.dp), shadowElevation = 8.dp) { + Column(Modifier.padding(10.dp)) { + Row(drag.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + Text(stringResource(R.string.translate), Modifier.weight(1f).padding(start = 6.dp), style = MaterialTheme.typography.titleMedium) + IconButton(openFull) { Icon(Icons.Filled.OpenInFull, null) } + IconButton({ open = false }) { Icon(Icons.Filled.Close, null) } + } + ModeChips() + CaptionList(Modifier.weight(1f, fill = false).padding(top = 6.dp), large = false, compact = true) + } + } + } +} + +/** Lifecycle for a Compose view that lives in a window instead of an activity. */ +private class OverlayOwner : LifecycleOwner, SavedStateRegistryOwner { + private val registry = LifecycleRegistry(this) + private val saved = SavedStateRegistryController.create(this) + override val lifecycle: Lifecycle get() = registry + override val savedStateRegistry: SavedStateRegistry get() = saved.savedStateRegistry + + init { + saved.performRestore(null) + registry.currentState = Lifecycle.State.RESUMED + } + + fun destroy() { registry.currentState = Lifecycle.State.DESTROYED } +} diff --git a/phone/src/main/kotlin/io/github/simbridge/GatewayConnectionService.kt b/phone/src/main/kotlin/io/github/simbridge/GatewayConnectionService.kt index 9050278..84b9539 100644 --- a/phone/src/main/kotlin/io/github/simbridge/GatewayConnectionService.kt +++ b/phone/src/main/kotlin/io/github/simbridge/GatewayConnectionService.kt @@ -79,6 +79,17 @@ class GatewayConnection(private val core: LinkCore, private val leg: CallLeg, pr @Volatile private var recorder: CallRecorder? = null private val label: String get() = leg.remote.number?.takeIf { it.isNotBlank() } ?: leg.target ?: "" val isRecording get() = recorder != null + /** Live translation of this call, for CaptionActivity's mode buttons. */ + val translator get() = audio.translator + + private fun startTranslator() { + if (audio.translator != null) return + val f = leg.media?.format ?: return + Captions.clear() + audio.translator = CallTranslator(core.context, core.prefs, f.sampleRate, f.frameSamples) + if (core.prefs.captionBubble) bubble = CaptionBubble(core.context).also { it.show() } + } + private var bubble: CaptionBubble? = null /** Starts recording both sides to Recordings/SimBridge (Record button or auto-record). */ @Synchronized fun startRecording() { @@ -116,6 +127,7 @@ class GatewayConnection(private val core: LinkCore, private val leg: CallLeg, pr android.os.Handler(android.os.Looper.getMainLooper()).post { LinkService.onCallActive() leg.media?.let(audio::start) + startTranslator() ActiveCall.current = this@GatewayConnection core.notifier.inCall(label, recording = false) if (core.prefs.autoRecord) startRecording() @@ -169,7 +181,9 @@ class GatewayConnection(private val core: LinkCore, private val leg: CallLeg, pr stopRecording() if (ActiveCall.current === this) { ActiveCall.current = null; core.notifier.cancelInCall() } stopRingback() - Thread { audio.stop() }.start() + bubble?.let { b -> android.os.Handler(android.os.Looper.getMainLooper()).post { b.hide() } } + bubble = null + Thread { audio.stop(); audio.translator?.close(); audio.translator = null }.start() core.legs.remove(leg.id) setDisconnected(dc) destroy() diff --git a/phone/src/main/kotlin/io/github/simbridge/Notifier.kt b/phone/src/main/kotlin/io/github/simbridge/Notifier.kt index 38bb392..5935a76 100644 --- a/phone/src/main/kotlin/io/github/simbridge/Notifier.kt +++ b/phone/src/main/kotlin/io/github/simbridge/Notifier.kt @@ -148,13 +148,17 @@ class Notifier(private val context: Context, private val core: LinkCore) { val action = if (recording) RecordReceiver.STOP else RecordReceiver.START val pi = PendingIntent.getBroadcast(context, 11, Intent(context, RecordReceiver::class.java).setAction(action), PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) + val captions = PendingIntent.getActivity(context, 12, Intent(context, CaptionActivity::class.java) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), PendingIntent.FLAG_IMMUTABLE) val n = Notification.Builder(context, CH_CALL) .setSmallIcon(R.drawable.ic_link) .setContentTitle(if (recording) context.getString(R.string.n_recording, name) else context.getString(R.string.n_call_with, name)) .setContentText(if (recording) context.getString(R.string.n_rec_saved_end) else context.getString(R.string.n_tap_record)) .setOngoing(true).setUsesChronometer(true).setShowWhen(true) .setCategory(Notification.CATEGORY_CALL) + .setContentIntent(captions) .addAction(Notification.Action.Builder(null, if (recording) context.getString(R.string.stop_recording) else context.getString(R.string.record), pi).build()) + .addAction(Notification.Action.Builder(null, context.getString(R.string.translate), captions).build()) .build() runCatching { nm.notify(ID_CALL, n) } } diff --git a/phone/src/main/kotlin/io/github/simbridge/Prefs.kt b/phone/src/main/kotlin/io/github/simbridge/Prefs.kt index 8710d58..88e4932 100644 --- a/phone/src/main/kotlin/io/github/simbridge/Prefs.kt +++ b/phone/src/main/kotlin/io/github/simbridge/Prefs.kt @@ -105,6 +105,80 @@ class Prefs(context: Context) { get() = p.getBoolean("block_hidden", false) set(v) = p.edit().putBoolean("block_hidden", v).apply() + /** Calls: translation mode each call starts in (can be changed during the call). */ + var translateMode: TranslateMode + get() = runCatching { TranslateMode.valueOf(p.getString("translate_mode", null) ?: "OFF") }.getOrDefault(TranslateMode.OFF) + set(v) = p.edit().putString("translate_mode", v.name).apply() + + /** Translation: never send call audio to the cloud (less accurate). */ + var translateOnDevice: Boolean + get() = p.getBoolean("translate_on_device", false) + set(v) = p.edit().putBoolean("translate_on_device", v).apply() + + /** Translation: Groq key (speech recognition and the Groq engines), encrypted like the pairing secrets. */ + var groqKey: String + get() = sealed("groq_sealed") + set(v) = sealed("groq_sealed", v) + + var cerebrasKey: String + get() = sealed("cerebras_sealed") + set(v) = sealed("cerebras_sealed", v) + + var geminiKey: String + get() = sealed("gemini_sealed") + set(v) = sealed("gemini_sealed", v) + + fun keyFor(e: Engine): String = when (e) { + Engine.GROQ_120B, Engine.GROQ_20B -> groqKey + Engine.CEREBRAS -> cerebrasKey + Engine.GEMINI -> geminiKey + Engine.ON_DEVICE -> "" + } + + /** Translation: engine for text translation. */ + var translateEngine: Engine + get() = runCatching { Engine.valueOf(p.getString("translate_engine", null) ?: "GROQ_120B") }.getOrDefault(Engine.GROQ_120B) + set(v) = p.edit().putString("translate_engine", v.name).apply() + + /** Translation: model override for the engine (blank = the engine's default). */ + var translateModel: String + get() = p.getString("translate_model", null)?.takeIf { it.isNotBlank() && it != "openai/gpt-oss-120b" } ?: "" + set(v) = p.edit().putString("translate_model", v.trim()).apply() + + /** Translation: the caller's language and mine (ISO codes from [Langs]). */ + var callerLang: String + get() = p.getString("caller_lang", null) ?: "tr" + set(v) = p.edit().putString("caller_lang", v).apply() + + var myLang: String + get() = p.getString("my_lang", null) ?: "en" + set(v) = p.edit().putString("my_lang", v).apply() + + /** Translation: quiet time that ends a sentence. Shorter is faster but may split sentences. */ + var pauseMs: Int + get() = p.getInt("pause_ms", 600) + set(v) = p.edit().putInt("pause_ms", v).apply() + + /** Translation: also read the caller's translated words to me in the earpiece. */ + var speakToMe: Boolean + get() = p.getBoolean("speak_to_me", false) + set(v) = p.edit().putBoolean("speak_to_me", v).apply() + + /** Translation: floating translate button over the call screen. */ + var captionBubble: Boolean + get() = p.getBoolean("caption_bubble", true) + set(v) = p.edit().putBoolean("caption_bubble", v).apply() + + /** Translation: larger caption text. */ + var captionLarge: Boolean + get() = p.getBoolean("caption_large", false) + set(v) = p.edit().putBoolean("caption_large", v).apply() + + private fun sealed(k: String): String = p.getString(k, null)?.let(::unseal) ?: "" + private fun sealed(k: String, v: String) { + if (v.isBlank()) p.edit().remove(k).apply() else p.edit().putString(k, seal(v.trim())).apply() + } + fun isBlocked(number: String?): Boolean { return blocked.any { io.github.sparkcyf.voicesipagent.voice.PhoneNumbers.same(number, it) } } diff --git a/phone/src/main/kotlin/io/github/simbridge/Speech.kt b/phone/src/main/kotlin/io/github/simbridge/Speech.kt new file mode 100644 index 0000000..6b5538d --- /dev/null +++ b/phone/src/main/kotlin/io/github/simbridge/Speech.kt @@ -0,0 +1,255 @@ +package io.github.simbridge + +import android.content.Context +import android.content.Intent +import android.media.AudioFormat +import android.os.Bundle +import android.os.Handler +import android.os.Looper +import android.os.ParcelFileDescriptor +import android.speech.RecognitionListener +import android.speech.RecognizerIntent +import android.speech.SpeechRecognizer +import android.speech.tts.TextToSpeech +import android.speech.tts.UtteranceProgressListener +import androidx.annotation.StringRes +import org.json.JSONArray +import org.json.JSONObject +import java.io.File +import java.io.IOException +import java.net.HttpURLConnection +import java.net.URL +import java.util.Locale +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit + +/** Text translation engines. Cloud ones are free tiers with an OpenAI-compatible API. */ +enum class Engine(val base: String, val model: String, @StringRes val title: Int, @StringRes val note: Int, val keyUrl: String) { + GROQ_120B("https://api.groq.com/openai/v1/", "openai/gpt-oss-120b", R.string.eng_groq120, R.string.eng_groq120_n, "https://console.groq.com/keys"), + GROQ_20B("https://api.groq.com/openai/v1/", "openai/gpt-oss-20b", R.string.eng_groq20, R.string.eng_groq20_n, "https://console.groq.com/keys"), + CEREBRAS("https://api.cerebras.ai/v1/", "gpt-oss-120b", R.string.eng_cerebras, R.string.eng_cerebras_n, "https://cloud.cerebras.ai"), + GEMINI("https://generativelanguage.googleapis.com/v1beta/openai/", "gemini-2.5-flash-lite", R.string.eng_gemini, R.string.eng_gemini_n, "https://aistudio.google.com/apikey"), + ON_DEVICE("", "", R.string.eng_device, R.string.eng_device_n, ""), +} + +/** Languages every engine handles (Whisper, the LLMs, ML Kit, Android TTS and recognizer). */ +object Langs { + val all = listOf("tr", "en", "ar", "fa", "ru", "uk", "fr", "de", "es", "it", "pt", "nl", "pl", "zh", "ja", "ko", "hi", "ur", "id") + private val region = mapOf("tr" to "tr-TR", "en" to "en-US", "ar" to "ar-SA", "fa" to "fa-IR", "ru" to "ru-RU", "uk" to "uk-UA", + "fr" to "fr-FR", "de" to "de-DE", "es" to "es-ES", "it" to "it-IT", "pt" to "pt-BR", "nl" to "nl-NL", "pl" to "pl-PL", + "zh" to "zh-CN", "ja" to "ja-JP", "ko" to "ko-KR", "hi" to "hi-IN", "ur" to "ur-PK", "id" to "id-ID") + + fun tag(code: String) = region[code] ?: code + fun locale(code: String): Locale = Locale.forLanguageTag(tag(code)) + /** English name, for prompts. */ + fun name(code: String): String = Locale.forLanguageTag(code).getDisplayLanguage(Locale.ENGLISH) + /** Name in that language ("Türkçe"), for pickers. */ + fun label(code: String): String = Locale.forLanguageTag(code).let { it.getDisplayLanguage(it).replaceFirstChar { c -> c.titlecase(it) } } +} + +/** + * Speech to text (Groq Whisper, or the on-device recognizer) and translation (the chosen engine). + * Any cloud failure (offline, rate limit) falls back to on-device for that line. + */ +class Speech(private val ctx: Context, private val prefs: Prefs) { + private val cloudSpeech get() = !prefs.translateOnDevice && prefs.groqKey.isNotBlank() + + fun transcribe(pcm: ShortArray, rate: Int, lang: String): String? { + if (cloudSpeech) runCatching { return groqTranscribe(pcm, rate, lang) } + .onFailure { Log.w("translate: cloud speech failed, using on-device", it); Captions.say("Cloud speech failed (${it.message}); using on-device") } + return OnDeviceStt.transcribe(ctx, pcm, rate, lang) + } + + /** [context]: the last few lines of the call, so short fragments translate correctly. */ + fun translate(text: String, from: String, to: String, context: List): String? { + val e = prefs.translateEngine + val key = prefs.keyFor(e) + if (!prefs.translateOnDevice && e != Engine.ON_DEVICE && key.isNotBlank()) runCatching { return chat(e, key, text, from, to, context) } + .onFailure { Log.w("translate: cloud translation failed, using on-device", it); Captions.say("Cloud translation failed (${it.message}); using on-device") } + return OfflineTranslate.translate(ctx, text, from, to) + } + + /** Opens the TLS connections at call start, so the first line doesn't pay the handshake. */ + fun warmUp() { + val e = prefs.translateEngine + val hosts = buildList { + if (cloudSpeech) add(Engine.GROQ_120B.base to prefs.groqKey) + if (!prefs.translateOnDevice && e != Engine.ON_DEVICE && prefs.keyFor(e).isNotBlank()) add(e.base to prefs.keyFor(e)) + }.distinctBy { it.first } + for ((base, key) in hosts) runCatching { + val c = (URL(base + "models").openConnection() as HttpURLConnection).apply { + connectTimeout = 4000; readTimeout = 6000; setRequestProperty("Authorization", "Bearer $key") + } + read(c) + } + } + + private fun groqTranscribe(pcm: ShortArray, rate: Int, lang: String): String { + val boundary = "simbridge" + System.nanoTime() + val c = post(Engine.GROQ_120B.base + "audio/transcriptions", prefs.groqKey, "multipart/form-data; boundary=$boundary") + c.outputStream.use { o -> + fun field(name: String, value: String) = + o.write("--$boundary\r\nContent-Disposition: form-data; name=\"$name\"\r\n\r\n$value\r\n".toByteArray()) + field("model", "whisper-large-v3-turbo") + field("language", lang) + field("temperature", "0") + field("response_format", "json") + o.write("--$boundary\r\nContent-Disposition: form-data; name=\"file\"; filename=\"speech.wav\"\r\nContent-Type: audio/wav\r\n\r\n".toByteArray()) + o.write(Pcm.wav(pcm, rate)) + o.write("\r\n--$boundary--\r\n".toByteArray()) + } + return JSONObject(read(c)).getString("text") + } + + private fun chat(e: Engine, key: String, text: String, from: String, to: String, context: List): String { + val model = prefs.translateModel.ifBlank { e.model } + val earlier = if (context.isEmpty()) "" else + "\nEarlier in this call (context only, do not translate):\n" + context.joinToString("\n") + val body = JSONObject() + .put("model", model) + .put("temperature", 0) + .put("max_tokens", 600) + .put("messages", JSONArray() + .put(JSONObject().put("role", "system").put("content", + "Translate the user's message from ${Langs.name(from)} to ${Langs.name(to)}. It is speech recognized from a phone call: " + + "keep meaning and tone, fix obvious recognition mistakes, keep names and numbers. Reply with the translation only.$earlier")) + .put(JSONObject().put("role", "user").put("content", text))) + if (model.contains("gpt-oss")) body.put("reasoning_effort", "low") + val c = post(e.base + "chat/completions", key, "application/json") + c.outputStream.use { it.write(body.toString().toByteArray()) } + return JSONObject(read(c)).getJSONArray("choices").getJSONObject(0).getJSONObject("message").getString("content") + } + + private fun post(url: String, key: String, type: String): HttpURLConnection = + (URL(url).openConnection() as HttpURLConnection).apply { + requestMethod = "POST" + doOutput = true + connectTimeout = 4000 + readTimeout = 12000 + setRequestProperty("Authorization", "Bearer $key") + setRequestProperty("Content-Type", type) + } + + /** Reads the whole body and closes the stream without disconnect(), so the connection is reused. */ + private fun read(c: HttpURLConnection): String { + val code = c.responseCode + if (code !in 200..299) { + val err = c.errorStream?.use { it.bufferedReader().readText() }.orEmpty() + throw IOException("HTTP $code ${err.take(160)}") + } + return c.inputStream.use { it.bufferedReader().readText() } + } + + companion object { + /** Lines Whisper invents from silence or noise (video-subtitle habits). */ + private val junk = listOf("altyazı", "izlediğiniz için", "abone ol", "thank you for watching", "thanks for watching", + "subtitles by", "amara.org") + + fun isJunk(text: String): Boolean { + val t = text.lowercase(Locale.ROOT).trim(' ', '.', '!', '?') + return t.length < 2 || (t.length < 60 && junk.any { t.contains(it) }) + } + } +} + +/** Android's on-device recognizer, fed our PCM through a pipe (no second microphone user). */ +object OnDeviceStt { + private val main = Handler(Looper.getMainLooper()) + + private fun intent(lang: String) = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH) + .putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM) + .putExtra(RecognizerIntent.EXTRA_LANGUAGE, Langs.tag(lang)) + + fun transcribe(ctx: Context, pcm: ShortArray, rate: Int, lang: String): String? { + if (!SpeechRecognizer.isOnDeviceRecognitionAvailable(ctx)) { + Captions.say("This phone has no on-device speech recognizer: add a Groq key in Settings"); return null + } + val audio = Pcm.resample(pcm, rate, 16000) + val pipe = ParcelFileDescriptor.createPipe() + val req = intent(lang) + .putExtra(RecognizerIntent.EXTRA_AUDIO_SOURCE, pipe[0]) + .putExtra(RecognizerIntent.EXTRA_AUDIO_SOURCE_ENCODING, AudioFormat.ENCODING_PCM_16BIT) + .putExtra(RecognizerIntent.EXTRA_AUDIO_SOURCE_CHANNEL_COUNT, 1) + .putExtra(RecognizerIntent.EXTRA_AUDIO_SOURCE_SAMPLING_RATE, 16000) + val done = CountDownLatch(1) + var text: String? = null + var rec: SpeechRecognizer? = null + main.post { + rec = runCatching { SpeechRecognizer.createOnDeviceSpeechRecognizer(ctx) }.getOrNull()?.apply { + setRecognitionListener(object : RecognitionListener { + override fun onResults(b: Bundle) { + text = b.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)?.firstOrNull(); done.countDown() + } + override fun onError(error: Int) { + if (error == SpeechRecognizer.ERROR_LANGUAGE_NOT_SUPPORTED || error == SpeechRecognizer.ERROR_LANGUAGE_UNAVAILABLE) { + runCatching { triggerModelDownload(intent(lang)) } + Captions.say("Downloading the offline ${Langs.name(lang)} speech model…") + } else if (error != SpeechRecognizer.ERROR_NO_MATCH && error != SpeechRecognizer.ERROR_SPEECH_TIMEOUT) { + Log.w("translate: on-device recognizer error $error") + } + done.countDown() + } + override fun onReadyForSpeech(p: Bundle?) = Unit + override fun onBeginningOfSpeech() = Unit + override fun onRmsChanged(v: Float) = Unit + override fun onBufferReceived(b: ByteArray?) = Unit + override fun onEndOfSpeech() = Unit + override fun onPartialResults(b: Bundle?) = Unit + override fun onEvent(t: Int, b: Bundle?) = Unit + }) + startListening(req) + } + if (rec == null) done.countDown() + } + Thread { + runCatching { ParcelFileDescriptor.AutoCloseOutputStream(pipe[1]).use { it.write(Pcm.bytes(audio)) } } + }.start() + done.await(15, TimeUnit.SECONDS) + main.post { rec?.destroy() } + runCatching { pipe[0].close() } + return text + } + + /** Asks the system to fetch offline models for these languages (call from the main thread). */ + fun prepare(ctx: Context, langs: List) { + if (!SpeechRecognizer.isOnDeviceRecognitionAvailable(ctx)) return + val r = SpeechRecognizer.createOnDeviceSpeechRecognizer(ctx) + langs.forEach { runCatching { r.triggerModelDownload(intent(it)) } } + main.postDelayed({ r.destroy() }, 2000) + } +} + +/** Android text-to-speech, rendered to a file so it can go into the call instead of the speaker. */ +class Voice(ctx: Context) { + private val dir = ctx.cacheDir + private val ready = CountDownLatch(1) + @Volatile private var ok = false + @Volatile private var spoken = CountDownLatch(1) + private val tts = TextToSpeech(ctx.applicationContext) { ok = it == TextToSpeech.SUCCESS; ready.countDown() } + + init { + tts.setOnUtteranceProgressListener(object : UtteranceProgressListener() { + override fun onStart(id: String?) = Unit + override fun onDone(id: String?) { spoken.countDown() } + @Deprecated("Deprecated in Java") override fun onError(id: String?) { spoken.countDown() } + }) + } + + /** Speech for [text] as mono PCM at [rate], or null if the voice isn't installed. One at a time. */ + @Synchronized fun synth(text: String, lang: String, rate: Int): ShortArray? { + if (!ready.await(5, TimeUnit.SECONDS) || !ok) { Captions.say("Text-to-speech isn't available"); return null } + val r = tts.setLanguage(Langs.locale(lang)) + if (r == TextToSpeech.LANG_MISSING_DATA || r == TextToSpeech.LANG_NOT_SUPPORTED) { + Captions.say("Install the ${Langs.name(lang)} voice: Settings > System > Languages > Text-to-speech"); return null + } + val f = File.createTempFile("tts", ".wav", dir) + try { + spoken = CountDownLatch(1) + if (tts.synthesizeToFile(text, Bundle(), f, "u" + System.nanoTime()) != TextToSpeech.SUCCESS) return null + if (!spoken.await(15, TimeUnit.SECONDS)) return null + return Pcm.readWav(f, rate) + } finally { f.delete() } + } + + fun shutdown() = tts.shutdown() +} diff --git a/phone/src/main/kotlin/io/github/simbridge/ui/SettingsScreen.kt b/phone/src/main/kotlin/io/github/simbridge/ui/SettingsScreen.kt index 3dc4333..a8231fe 100644 --- a/phone/src/main/kotlin/io/github/simbridge/ui/SettingsScreen.kt +++ b/phone/src/main/kotlin/io/github/simbridge/ui/SettingsScreen.kt @@ -6,6 +6,8 @@ import android.os.PowerManager import android.provider.Settings import android.telecom.TelecomManager import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer @@ -29,6 +31,7 @@ import androidx.compose.material.icons.filled.Visibility import androidx.compose.material.icons.filled.VisibilityOff import androidx.compose.material.icons.filled.Warning import androidx.compose.material.icons.filled.Wifi +import androidx.compose.material.icons.filled.Translate import androidx.compose.material3.Button import androidx.compose.material3.ElevatedCard import androidx.compose.material3.ExperimentalMaterial3Api @@ -187,6 +190,7 @@ fun SettingsScreen(core: LinkCore, onSimPhone: () -> Unit = {}, onBlocked: () -> } TextButton(onRecordings) { Text(stringResource(R.string.recordings)) } } + TranslationCard(core) val exportLauncher = androidx.activity.compose.rememberLauncherForActivityResult( androidx.activity.result.contract.ActivityResultContracts.CreateDocument("application/json")) { uri -> uri ?: return@rememberLauncherForActivityResult @@ -321,3 +325,120 @@ private fun localIp(): String? = runCatching { java.net.NetworkInterface.getNetworkInterfaces().toList().filter { it.isUp && !it.isLoopback } .flatMap { it.inetAddresses.toList() }.firstOrNull { it is java.net.Inet4Address && it.isSiteLocalAddress }?.hostAddress }.getOrNull() + +@Composable +private fun TranslationCard(core: LinkCore) { + val ctx = LocalContext.current + val prefs = core.prefs + var mode by remember { mutableStateOf(prefs.translateMode) } + var engine by remember { mutableStateOf(prefs.translateEngine) } + var caller by remember { mutableStateOf(prefs.callerLang) } + var mine by remember { mutableStateOf(prefs.myLang) } + var pause by remember { mutableIntStateOf(prefs.pauseMs) } + var onDevice by remember { mutableStateOf(prefs.translateOnDevice) } + var speakToMe by remember { mutableStateOf(prefs.speakToMe) } + var bubble by remember { mutableStateOf(prefs.captionBubble) } + var large by remember { mutableStateOf(prefs.captionLarge) } + var groq by remember { mutableStateOf(prefs.groqKey) } + var cerebras by remember { mutableStateOf(prefs.cerebrasKey) } + var gemini by remember { mutableStateOf(prefs.geminiKey) } + var model by remember { mutableStateOf(prefs.translateModel) } + var tick by remember { mutableIntStateOf(0) } + LaunchedEffect(Unit) { while (true) { delay(1500); tick++ } } + val overlayOk = remember(tick) { Settings.canDrawOverlays(ctx) } + fun open(url: String) = runCatching { ctx.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url))) } + + Card(Icons.Filled.Translate, stringResource(R.string.set_translate), stringResource(R.string.set_translate_text), ok = true) { + Text(stringResource(R.string.set_tr_start), style = MaterialTheme.typography.labelLarge) + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + listOf(io.github.simbridge.TranslateMode.OFF to R.string.tr_off, io.github.simbridge.TranslateMode.CAPTIONS to R.string.tr_captions, + io.github.simbridge.TranslateMode.VOICE to R.string.tr_voice).forEach { (m, label) -> + androidx.compose.material3.FilterChip(mode == m, { mode = m; prefs.translateMode = m }, { Text(stringResource(label)) }) + } + } + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + LangPicker(stringResource(R.string.set_tr_caller), caller, Modifier.weight(1f)) { caller = it; prefs.callerLang = it } + LangPicker(stringResource(R.string.set_tr_me), mine, Modifier.weight(1f)) { mine = it; prefs.myLang = it } + } + + Spacer(Modifier.size(8.dp)) + Text(stringResource(R.string.set_tr_engine), style = MaterialTheme.typography.labelLarge) + io.github.simbridge.Engine.entries.forEach { e -> + Row(Modifier.fillMaxWidth().clickable { engine = e; prefs.translateEngine = e }, verticalAlignment = Alignment.CenterVertically) { + androidx.compose.material3.RadioButton(engine == e, { engine = e; prefs.translateEngine = e }) + Column(Modifier.weight(1f)) { + Text(stringResource(e.title), style = MaterialTheme.typography.bodyLarge) + Text(stringResource(e.note), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + } + } + if (!onDevice) { + KeyField(stringResource(R.string.set_groq_key), groq, "https://console.groq.com/keys", ::open) { groq = it; prefs.groqKey = it } + if (engine == io.github.simbridge.Engine.CEREBRAS) + KeyField(stringResource(R.string.set_cerebras_key), cerebras, engine.keyUrl, ::open) { cerebras = it; prefs.cerebrasKey = it } + if (engine == io.github.simbridge.Engine.GEMINI) + KeyField(stringResource(R.string.set_gemini_key), gemini, engine.keyUrl, ::open) { gemini = it; prefs.geminiKey = it } + if (engine != io.github.simbridge.Engine.ON_DEVICE) + OutlinedTextField(model, { model = it; prefs.translateModel = it }, Modifier.fillMaxWidth(), singleLine = true, + label = { Text(stringResource(R.string.set_translate_model)) }, placeholder = { Text(engine.model) }) + } + + Spacer(Modifier.size(8.dp)) + Text(stringResource(R.string.set_tr_pause), style = MaterialTheme.typography.labelLarge) + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + listOf(450 to R.string.set_tr_fast, 600 to R.string.set_tr_normal, 900 to R.string.set_tr_patient).forEach { (ms, label) -> + androidx.compose.material3.FilterChip(pause == ms, { pause = ms; prefs.pauseMs = ms }, { Text(stringResource(label)) }) + } + } + SwitchRow(stringResource(R.string.set_tr_bubble), bubble) { + bubble = it; prefs.captionBubble = it + if (it && !overlayOk) + runCatching { ctx.startActivity(Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + ctx.packageName))) } + } + if (bubble && !overlayOk) TextButton({ + runCatching { ctx.startActivity(Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + ctx.packageName))) } + }) { Text(stringResource(R.string.set_tr_bubble_allow)) } + SwitchRow(stringResource(R.string.set_tr_speak_me), speakToMe) { speakToMe = it; prefs.speakToMe = it } + SwitchRow(stringResource(R.string.set_tr_large), large) { large = it; prefs.captionLarge = it } + SwitchRow(stringResource(R.string.set_translate_offline), onDevice) { + onDevice = it; prefs.translateOnDevice = it + if (it) { io.github.simbridge.OfflineTranslate.prepare(ctx, caller, mine); io.github.simbridge.OnDeviceStt.prepare(ctx, listOf(caller, mine)) } + } + } +} + +@Composable +private fun SwitchRow(text: String, on: Boolean, set: (Boolean) -> Unit) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text(text, Modifier.weight(1f), style = MaterialTheme.typography.bodyLarge) + Switch(on, set) + } +} + +@Composable +private fun KeyField(label: String, value: String, url: String, open: (String) -> Unit, set: (String) -> Unit) { + var show by remember { mutableStateOf(false) } + OutlinedTextField(value, set, Modifier.fillMaxWidth(), singleLine = true, label = { Text(label) }, + visualTransformation = if (show) VisualTransformation.None else PasswordVisualTransformation(), + trailingIcon = { IconButton({ show = !show }) { Icon(if (show) Icons.Filled.VisibilityOff else Icons.Filled.Visibility, null) } }) + TextButton({ open(url) }) { Text(stringResource(R.string.set_get_key, Uri.parse(url).host ?: url)) } +} + +@Composable +private fun LangPicker(label: String, code: String, modifier: Modifier, pick: (String) -> Unit) { + var open by remember { mutableStateOf(false) } + Box(modifier) { + androidx.compose.material3.OutlinedButton({ open = true }, Modifier.fillMaxWidth()) { + Column { + Text(label, style = MaterialTheme.typography.labelSmall) + Text(io.github.simbridge.Langs.label(code)) + } + } + androidx.compose.material3.DropdownMenu(open, { open = false }) { + io.github.simbridge.Langs.all.forEach { c -> + androidx.compose.material3.DropdownMenuItem({ Text(io.github.simbridge.Langs.label(c) + " · " + io.github.simbridge.Langs.name(c)) }, + { pick(c); open = false }) + } + } + } +} diff --git a/phone/src/main/res/values-tr/strings.xml b/phone/src/main/res/values-tr/strings.xml index 1768a49..b540b72 100644 --- a/phone/src/main/res/values-tr/strings.xml +++ b/phone/src/main/res/values-tr/strings.xml @@ -206,4 +206,39 @@ Bir SIM telefonunun kodunu tekrar tarayana kadar aramalar ve mesajlar durur. Siz Siz: + Çevir + Kapalı + Altyazı + Altyazı + ses + Devam eden arama yok: son arama gösteriliyor. + Arama çevirisi + Altyazı: arayanın sözleri kayan bir pencerede çevrilmiş görünür (veya arama bildirimindeki Çevir\'e dokunun). Altyazı + ses: ayrıca sözleriniz karşı tarafa kendi dilinde okunur. Konuşurken okumak için hoparlör veya kulaklık kullanın. Gerektiğinde arayana sesinin işlendiğini söyleyin. + Yalnızca cihazda (gizli, daha az doğru) + Groq API anahtarı (ücretsiz) + Çeviri modeli + Her arama şununla başlar + Arayanın dili + Benim dilim + Çeviri motoru + Şu kadar duraklamadan sonra çevir + 0,45 sn (hızlı) + 0,6 sn + 0,9 sn (tam cümleler) + Aramalarda kayan çeviri düğmesi + \"Diğer uygulamaların üzerinde göster\" iznini ver + Arayanın çevirisini bana da sesli oku + Büyük altyazı yazısı + Cerebras API anahtarı (ücretsiz) + Google AI Studio API anahtarı (ücretsiz) + %1$s adresinden ücretsiz anahtar alın + Groq · GPT-OSS 120B (önerilen) + Doğru ve hızlı (yaklaşık 0,3–0,6 sn). Groq anahtarını kullanır. + Groq · GPT-OSS 20B + En hızlı (yaklaşık 0,2–0,4 sn), biraz daha az doğru. Groq anahtarını kullanır. + Cerebras · GPT-OSS 120B + Groq 120B kadar doğru, çoğu zaman daha hızlı. Ücretsiz Cerebras anahtarı gerekir. + Google Gemini 2.5 Flash-Lite + Az yaygın dillerde en doğal, daha yavaş (yaklaşık 0,6–1,2 sn). Ücretsiz Google anahtarı; Google ücretsiz katman verilerini kullanabilir. + Cihazda (Google ML Kit) + Çevrimdışı ve gizli, en az doğru. F-Droid sürümünde yok. diff --git a/phone/src/main/res/values/strings.xml b/phone/src/main/res/values/strings.xml index d3c3790..53053cb 100644 --- a/phone/src/main/res/values/strings.xml +++ b/phone/src/main/res/values/strings.xml @@ -207,4 +207,39 @@ Calls and texts stop until you scan a SIM phone\'s code again. You You: + Translate + Off + Captions + Captions + voice + No call in progress: showing the last call. + Call translation + Captions: the caller\'s words show translated in a floating window (or tap Translate in the call notification). Captions + voice: also, your words are spoken to them in their language. Use the speaker or earbuds to read while talking. Tell the caller their voice is processed when required. + On-device only (private, less accurate) + Groq API key (free, also used for speech recognition) + Translation model + Each call starts with + Caller speaks + I speak + Translation engine + Translate after a pause of + 0.45 s (fast) + 0.6 s + 0.9 s (whole sentences) + Floating translate button during calls + Allow \"Display over other apps\" + Also read the caller\'s translation to me + Large caption text + Cerebras API key (free) + Google AI Studio API key (free) + Get a free key at %1$s + Groq · GPT-OSS 120B (recommended) + Accurate and fast (about 0.3–0.6 s). Uses the Groq key. + Groq · GPT-OSS 20B + Fastest (about 0.2–0.4 s), a little less accurate. Uses the Groq key. + Cerebras · GPT-OSS 120B + As accurate as Groq 120B, often faster. Needs a free Cerebras key. + Google Gemini 2.5 Flash-Lite + Most natural for less common languages, slower (about 0.6–1.2 s). Free Google key; Google may use free-tier data. + On-device (Google ML Kit) + Offline and private, least accurate. Not in the F-Droid build.