fixed a bug:translate maybe timeout

This commit is contained in:
2026-10-03 19:49:21 +08:00
parent 6bd64ee4a9
commit 9daea7b807
10 changed files with 554 additions and 99 deletions

View File

@@ -375,8 +375,12 @@ class MainActivity : Activity() {
screenState.chineseTranslationError = ""
applyChineseSubtitle(controller.currentSentence())
translationRequest?.cancel()
val expectedIndexes = sentences.mapNotNull { sentence ->
sentence.index.takeIf { !sentence.text.isNullOrBlank() }
}
translationRequest = translationApi.translate(
item.id,
expectedIndexes,
object : SubtitleTranslationCallback {
override fun onSuccess(result: SubtitleTranslationResult) {
if (!screenState.isCurrentTranslationRequest(generation, item.id)) return

View File

@@ -41,11 +41,12 @@ internal class SubtitleTranslationApi(
fun translate(
videoHash: String,
expectedIndexes: Collection<Int> = emptyList(),
callback: SubtitleTranslationCallback,
): CancellableTranslationRequest {
val future = executor.submit {
try {
val result = requestBlocking(videoHash)
val result = loadBlocking(videoHash, expectedIndexes)
if (!Thread.currentThread().isInterrupted) {
mainHandler.post { callback.onSuccess(result) }
}
@@ -62,13 +63,31 @@ internal class SubtitleTranslationApi(
executor.shutdownNow()
}
private fun requestBlocking(videoHash: String): SubtitleTranslationResult {
private fun loadBlocking(
videoHash: String,
expectedIndexes: Collection<Int>,
): SubtitleTranslationResult {
val stored = runCatching {
requestBlocking(videoHash, method = "GET", readTimeoutMs = 15_000)
}.getOrNull()
val expected = expectedIndexes.toSet()
if (stored != null && (expected.isEmpty() || expected.all { stored.translations.containsKey(it) })) {
return stored
}
return requestBlocking(videoHash, method = "POST", readTimeoutMs = 180_000)
}
private fun requestBlocking(
videoHash: String,
method: String,
readTimeoutMs: Int,
): SubtitleTranslationResult {
val endpoint = baseUrl.trimEnd('/') + "/api/v1/videos/$videoHash/subtitle-translation"
val connection = URL(endpoint).openConnection() as HttpURLConnection
try {
connection.requestMethod = "POST"
connection.requestMethod = method
connection.connectTimeout = 15_000
connection.readTimeout = 120_000
connection.readTimeout = readTimeoutMs
connection.doOutput = false
connection.useCaches = false
connection.setRequestProperty("Accept", "application/json")