You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android应用非Google Translate API实现英文至印地语动态数据实时翻译咨询

Great question! Since you've already got static translations sorted with string resources, handling dynamic English content from your server to Hindi without relying on Google Translate API is totally achievable. Here are three practical approaches tailored to your needs:

1. Offline Open-Source Translation Models (Local Processing)

This approach lets you translate text directly on the device, no network calls required—perfect for real-time performance and user privacy. You'll bundle a pre-trained neural machine translation (NMT) model into your app, typically in TensorFlow Lite (TFLite) format.

  • MarianMT: Pre-trained models for English-to-Hindi (e.g., Helsinki-NLP/opus-mt-en-hi) are available and can be converted to TFLite for mobile use.
  • mBART: Multilingual model that supports en-hi translation, with quantized variants for smaller size.

Example Implementation (Kotlin):

First, bundle the TFLite model and corresponding tokenizer (e.g., SentencePiece) in your app's assets folder. Then load and use it:

import org.tensorflow.lite.Interpreter
import java.io.File
import java.io.FileOutputStream

class OfflineTranslator(private val context: Context) {
    private lateinit var tflite: Interpreter
    private lateinit var tokenizer: SentencePieceTokenizer // Implement using SentencePiece library

    init {
        initModel()
        initTokenizer()
    }

    private fun initModel() {
        // Copy model from assets to app files directory (for better performance)
        val modelFile = File(context.filesDir, "en_hi_marianmt.tflite")
        if (!modelFile.exists()) {
            context.assets.open("en_hi_marianmt.tflite").use { inputStream ->
                FileOutputStream(modelFile).use { outputStream ->
                    inputStream.copyTo(outputStream)
                }
            }
        }

        // Configure interpreter for multi-core processing
        val options = Interpreter.Options().apply {
            setNumThreads(4)
            setUseNNAPI(true) // Leverage device's neural hardware if available
        }
        tflite = Interpreter(modelFile, options)
    }

    private fun initTokenizer() {
        // Load SentencePiece model from assets
        val spModel = context.assets.open("sentencepiece.model").readBytes()
        tokenizer = SentencePieceTokenizer(spModel)
    }

    fun translate(text: String): String {
        // Step 1: Tokenize input text
        val inputTokens = tokenizer.encode(text)
        // Step 2: Convert tokens to tensor input (pad to max sequence length)
        val inputTensor = prepareInputTensor(inputTokens)
        // Step 3: Allocate output tensor
        val outputTensor = Array(1) { FloatArray(MAX_SEQUENCE_LENGTH) }
        // Step 4: Run inference
        tflite.run(inputTensor, outputTensor)
        // Step 5: Detokenize output to get Hindi text
        return tokenizer.decode(extractOutputTokens(outputTensor))
    }

    // Helper functions for tensor preparation and post-processing
    private fun prepareInputTensor(tokens: List<Int>): Array<FloatArray> {
        // Implement padding/conversion to model's expected input format
        return arrayOf(tokens.padEnd(MAX_SEQUENCE_LENGTH, 0).map { it.toFloat() }.toFloatArray())
    }

    private fun extractOutputTokens(output: Array<FloatArray>): List<Int> {
        // Convert output tensor back to token IDs, filter special tokens
        return output[0].map { it.toInt() }.takeWhile { it != tokenizer.eosId }
    }

    companion object {
        private const val MAX_SEQUENCE_LENGTH = 128
    }
}

Pros & Cons:

  • ✅ No network dependency, real-time translation
  • ✅ Full control over translation logic, no third-party costs
  • ❌ Increases app size (quantized models are ~100MB; unquantized ~300-500MB)
  • ❌ Slight performance hit on low-end devices (mitigate with caching frequent translations)
2. Self-Hosted Translation Service

If you have backend infrastructure, deploy an open-source NMT model on your own server and expose a simple API for your Android app to call. This keeps heavy processing off the device while avoiding third-party APIs.

  • Model: Use Helsinki-NLP/opus-mt-en-hi (Hugging Face Transformers) for ready-to-use en-hi translation
  • API Framework: FastAPI (lightweight, easy to set up)
  • Hosting: Deploy on your existing server, or use a low-cost service like AWS EC2 or DigitalOcean

Example Server Endpoint (Python/FastAPI):

from fastapi import FastAPI, HTTPException
from transformers import MarianMTModel, MarianTokenizer

app = FastAPI(title="Custom Translation API")

# Load pre-trained model and tokenizer once at startup
MODEL_NAME = "Helsinki-NLP/opus-mt-en-hi"
tokenizer = MarianTokenizer.from_pretrained(MODEL_NAME)
model = MarianMTModel.from_pretrained(MODEL_NAME)

@app.post("/translate/en-to-hi")
async def translate_en_to_hi(text: str):
    try:
        # Tokenize input
        inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True)
        # Generate translation
        outputs = model.generate(**inputs)
        # Decode output (skip special tokens like <s>, </s>)
        translated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
        return {"translated_text": translated_text}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

Android Client Code (Retrofit):

import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.Field
import retrofit2.http.FormUrlEncoded
import retrofit2.http.POST

interface TranslationApi {
    @FormUrlEncoded
    @POST("/translate/en-to-hi")
    suspend fun translateEnToHi(@Field("text") text: String): TranslationResponse
}

data class TranslationResponse(val translated_text: String)

// Initialize Retrofit client
val retrofit = Retrofit.Builder()
    .baseUrl("https://your-server-domain.com/") // Replace with your server URL
    .addConverterFactory(GsonConverterFactory.create())
    .build()

val translationApi = retrofit.create(TranslationApi::class.java)

// Usage in a coroutine
suspend fun getTranslatedText(englishText: String): String? {
    return try {
        val response = translationApi.translateEnToHi(englishText)
        response.translated_text
    } catch (e: Exception) {
        // Handle network errors, server issues
        null
    }
}

Pros & Cons:

  • ✅ No app size bloat, offloads processing to server
  • ✅ Easy to update models without pushing app updates
  • ❌ Requires backend maintenance and hosting costs
  • ❌ Depends on network connectivity (but you're already fetching dynamic data from the server, so this is likely acceptable)
3. Non-Google Third-Party APIs (Free/Low-Cost)

If self-hosting or offline models aren't feasible, consider alternative APIs that don't rely on Google Translate:

  • DeepL API: Offers a free tier with up to 500,000 characters/month, supports English-to-Hindi with high accuracy.
  • LibreTranslate: Open-source, community-driven API—you can self-host it or use public instances (note: public instances may have rate limits).

This is the quickest to implement but gives you less control compared to the first two options.

Key Final Tips:

  • Test Translation Quality: Not all pre-trained models are equal—test en-hi translations with your specific content (e.g., app-specific terminology) to ensure accuracy.
  • Cache Translations: Store frequently translated texts locally (e.g., in SharedPreferences or Room) to avoid redundant processing/API calls.
  • App Bundle Optimization: For offline models, use Android App Bundles to deliver the Hindi translation model only to users who need it, reducing APK size for others.

内容的提问来源于stack exchange,提问作者Dilip Dubey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:01:35