Android पर, अपनी पसंद के मुताबिक TensorFlow Lite मॉडल का इस्तेमाल करना

अगर आपका ऐप्लिकेशन, पसंद के मुताबिक TensorFlow Lite मॉडल का इस्तेमाल करता है, तो अपने मॉडल को डिप्लॉय करने के लिए, Firebase ML का इस्तेमाल किया जा सकता है. Firebase के साथ मॉडल डिप्लॉय करके, अपने ऐप्लिकेशन के शुरुआती डाउनलोड साइज़ को कम किया जा सकता है. साथ ही, ऐप्लिकेशन का नया वर्शन रिलीज़ किए बिना, ऐप्लिकेशन के एमएल मॉडल अपडेट किए जा सकते हैं. इसके अलावा, रिमोट कॉन्फ़िगरेशन और A/B टेस्टिंग की मदद से, उपयोगकर्ताओं के अलग-अलग सेट के लिए डाइनैमिक तौर पर अलग-अलग मॉडल दिखाए जा सकते हैं.

TensorFlow Lite के मॉडल

TensorFlow Lite मॉडल, ऐसे एमएल मॉडल हैं जिन्हें मोबाइल डिवाइसों पर चलाने के लिए ऑप्टिमाइज़ किया गया है. TensorFlow Lite का मॉडल पाने के लिए:

वेब कंटेनर इंस्टॉल करने से पहले

  1. अगर आपने पहले से Firebase को नहीं जोड़ा है, तो अपने Android प्रोजेक्ट में Firebase जोड़ें.
  2. अपने मॉड्यूल (ऐप्लिकेशन-लेवल) की Gradle फ़ाइल (आम तौर पर, <project>/<app-module>/build.gradle.kts या <project>/<app-module>/build.gradle) में, Android के लिए Firebase एमएल मॉडल डाउनलोडर लाइब्रेरी के लिए डिपेंडेंसी जोड़ें. लाइब्रेरी के वर्शन को कंट्रोल करने के लिए, हम Firebase Android BoM का इस्तेमाल करने का सुझाव देते हैं.

    इसके अलावा, Firebase ML मॉडल डाउनलोडर सेट अप करने के दौरान, आपको अपने ऐप्लिकेशन में TensorFlow Lite SDK टूल जोड़ना होगा.

    dependencies {
        // Import the BoM for the Firebase platform
        implementation(platform("com.google.firebase:firebase-bom:33.1.1"))
    
        // Add the dependency for the Firebase ML model downloader library
        // When using the BoM, you don't specify versions in Firebase library dependencies
        implementation("com.google.firebase:firebase-ml-modeldownloader")
    // Also add the dependency for the TensorFlow Lite library and specify its version implementation("org.tensorflow:tensorflow-lite:2.3.0")
    }

    Firebase Android BoM का इस्तेमाल करने पर, आपका ऐप्लिकेशन हमेशा Firebase की Android लाइब्रेरी के साथ काम करने वाले वर्शन का इस्तेमाल करेगा.

    (वैकल्पिक) BoM का इस्तेमाल किए बिना Firebase लाइब्रेरी डिपेंडेंसी जोड़ें

    अगर आप Firebase BoM का इस्तेमाल नहीं करना चाहते हैं, तो आपको उसकी डिपेंडेंसी लाइन में Firebase लाइब्रेरी के हर वर्शन की जानकारी देनी होगी.

    ध्यान दें कि अगर आप अपने ऐप्लिकेशन में कई Firebase लाइब्रेरी का इस्तेमाल करते हैं, तो हमारा सुझाव है कि लाइब्रेरी के वर्शन मैनेज करने के लिए, BoM का इस्तेमाल करें. इससे यह पक्का होता है कि ऐप्लिकेशन के सभी वर्शन काम करते हैं.

    dependencies {
        // Add the dependency for the Firebase ML model downloader library
        // When NOT using the BoM, you must specify versions in Firebase library dependencies
        implementation("com.google.firebase:firebase-ml-modeldownloader:25.0.0")
    // Also add the dependency for the TensorFlow Lite library and specify its version implementation("org.tensorflow:tensorflow-lite:2.3.0")
    }
    क्या आपको Kotlin से जुड़े लाइब्रेरी मॉड्यूल की तलाश है? अक्टूबर 2023 (Firebase BoM 32.5.0) से, Kotlin और Java डेवलपर, दोनों मुख्य लाइब्रेरी मॉड्यूल पर निर्भर कर सकते हैं. ज़्यादा जानकारी के लिए, इस इनिशिएटिव के बारे में अक्सर पूछे जाने वाले सवाल देखें.
  3. अपने ऐप्लिकेशन के मेनिफ़ेस्ट में, यह बताएं कि इंटरनेट की अनुमति ज़रूरी है:
    <uses-permission android:name="android.permission.INTERNET" />

1. अपना मॉडल डिप्लॉय करना

Firebase कंसोल या Firebase एडमिन Python और Node.js SDK टूल का इस्तेमाल करके, पसंद के मुताबिक बनाए गए TensorFlow मॉडल को डिप्लॉय करें. कस्टम मॉडल डिप्लॉय करना और मैनेज करना लेख पढ़ें.

अपने Firebase प्रोजेक्ट में कोई कस्टम मॉडल जोड़ने के बाद, अपने ऐप्लिकेशन में उस मॉडल का रेफ़रंस देने के लिए, अपना बताया गया नाम इस्तेमाल करें. आपके पास किसी भी समय TensorFlow Lite का नया मॉडल डिप्लॉय करने और उपयोगकर्ताओं के डिवाइसों पर इस नए मॉडल को डाउनलोड करने का विकल्प होता है. इसके लिए, आपको getModel() पर कॉल करना होगा (यहां देखें).

2. मॉडल को डिवाइस पर डाउनलोड करें और TensorFlow Lite का अनुवादक मोड शुरू करें

अपने ऐप्लिकेशन में TensorFlow Lite के मॉडल का इस्तेमाल करने के लिए, सबसे पहले Firebase ML SDK टूल का इस्तेमाल करके डिवाइस पर मॉडल का सबसे नया वर्शन डाउनलोड करें. इसके बाद, मॉडल की मदद से TensorFlow Lite इंटरप्रेटर को इंस्टैंशिएट करें.

मॉडल डाउनलोड करने के लिए, मॉडल डाउनलोड करने वाले के getModel() तरीके को कॉल करें. साथ ही, मॉडल को अपलोड करते समय असाइन किया गया नाम बताएं. साथ ही, यह बताएं कि आपको हमेशा नया मॉडल डाउनलोड करना है या नहीं और किन स्थितियों में डाउनलोड करने की अनुमति देनी है.

डाउनलोड करने के इन तीन तरीकों में से कोई एक चुनें:

डाउनलोड का टाइप जानकारी
LOCAL_MODEL डिवाइस से लोकल मॉडल डाउनलोड करें. अगर कोई लोकल मॉडल उपलब्ध नहीं है, तो यह LATEST_MODEL की तरह काम करता है. अगर आपको मॉडल के अपडेट देखने में दिलचस्पी नहीं है, तो इस डाउनलोड टाइप का इस्तेमाल करें. उदाहरण के लिए, मॉडल नेम को फिर से पाने के लिए रिमोट कॉन्फ़िगरेशन का इस्तेमाल किया जा रहा है और मॉडल को हमेशा नए नामों के तहत अपलोड किया जाता है (सुझाया गया).
LOCAL_MODEL_UPDATE_IN_BACKGROUND डिवाइस से लोकल मॉडल डाउनलोड करें और बैकग्राउंड में मॉडल अपडेट करना शुरू करें. अगर कोई लोकल मॉडल उपलब्ध नहीं है, तो यह LATEST_MODEL की तरह काम करता है.
LATEST_MODEL सबसे नया मॉडल पाएं. अगर लोकल मॉडल नया वर्शन है, तो लोकल मॉडल दिखाता है. अगर ऐसा नहीं है, तो नया मॉडल डाउनलोड करें. ऐसा तब तक नहीं होगा, जब तक नया वर्शन डाउनलोड नहीं हो जाता (हम ऐसा करने का सुझाव नहीं देते). इस व्यवहार का इस्तेमाल सिर्फ़ उन मामलों में करें जहां आपको साफ़ तौर पर नए वर्शन की ज़रूरत है.

आपको मॉडल से जुड़ी सुविधाओं को बंद रखना चाहिए. उदाहरण के लिए, अपने यूज़र इंटरफ़ेस (यूआई) के किसी हिस्से को धूसर करना या छिपाना. ऐसा तब तक करना चाहिए, जब तक आप यह पुष्टि न कर लें कि मॉडल डाउनलोड हो गया है.

Kotlin+KTX

val conditions = CustomModelDownloadConditions.Builder()
        .requireWifi()  // Also possible: .requireCharging() and .requireDeviceIdle()
        .build()
FirebaseModelDownloader.getInstance()
        .getModel("your_model", DownloadType.LOCAL_MODEL_UPDATE_IN_BACKGROUND,
            conditions)
        .addOnSuccessListener { model: CustomModel? ->
            // Download complete. Depending on your app, you could enable the ML
            // feature, or switch from the local model to the remote model, etc.

            // The CustomModel object contains the local path of the model file,
            // which you can use to instantiate a TensorFlow Lite interpreter.
            val modelFile = model?.file
            if (modelFile != null) {
                interpreter = Interpreter(modelFile)
            }
        }

Java

CustomModelDownloadConditions conditions = new CustomModelDownloadConditions.Builder()
    .requireWifi()  // Also possible: .requireCharging() and .requireDeviceIdle()
    .build();
FirebaseModelDownloader.getInstance()
    .getModel("your_model", DownloadType.LOCAL_MODEL_UPDATE_IN_BACKGROUND, conditions)
    .addOnSuccessListener(new OnSuccessListener<CustomModel>() {
      @Override
      public void onSuccess(CustomModel model) {
        // Download complete. Depending on your app, you could enable the ML
        // feature, or switch from the local model to the remote model, etc.

        // The CustomModel object contains the local path of the model file,
        // which you can use to instantiate a TensorFlow Lite interpreter.
        File modelFile = model.getFile();
        if (modelFile != null) {
            interpreter = new Interpreter(modelFile);
        }
      }
    });

कई ऐप्लिकेशन अपने इनिशलाइज़ेशन कोड में डाउनलोड टास्क शुरू करते हैं, लेकिन मॉडल का इस्तेमाल करने से पहले, किसी भी समय ऐसा किया जा सकता है.

3. इनपुट डेटा के आधार पर अनुमान लगाएं

अपने मॉडल के इनपुट और आउटपुट आकार पाना

TensorFlow Lite मॉडल इंटरप्रेटर, इनपुट के तौर पर इनपुट लेता है और एक या उससे ज़्यादा कई डाइमेंशन वाले अरे को आउटपुट के तौर पर बनाता है. इन कलेक्शन में byte, int, long या float वैल्यू होती हैं. किसी मॉडल को डेटा भेजने या उसके नतीजे का इस्तेमाल करने से पहले, आपको उन कैटगरी की संख्या और डाइमेंशन ("आकार") पता होना चाहिए जिनका इस्तेमाल आपका मॉडल करता है.

अगर आपने मॉडल खुद बनाया है या मॉडल के इनपुट और आउटपुट फ़ॉर्मैट का इस्तेमाल किया है, तो हो सकता है कि आपके पास यह जानकारी पहले से हो. अगर आपको मॉडल के इनपुट और आउटपुट का आकार और डेटा टाइप नहीं पता है, तो अपने मॉडल की जांच करने के लिए TensorFlow Lite इंटरप्रेटर का इस्तेमाल करें. उदाहरण के लिए:

Python

import tensorflow as tf

interpreter = tf.lite.Interpreter(model_path="your_model.tflite")
interpreter.allocate_tensors()

# Print input shape and type
inputs = interpreter.get_input_details()
print('{} input(s):'.format(len(inputs)))
for i in range(0, len(inputs)):
    print('{} {}'.format(inputs[i]['shape'], inputs[i]['dtype']))

# Print output shape and type
outputs = interpreter.get_output_details()
print('\n{} output(s):'.format(len(outputs)))
for i in range(0, len(outputs)):
    print('{} {}'.format(outputs[i]['shape'], outputs[i]['dtype']))

आउटपुट का उदाहरण:

1 input(s):
[  1 224 224   3] <class 'numpy.float32'>

1 output(s):
[1 1000] <class 'numpy.float32'>

अनुवादक चलाएं

अपने मॉडल के इनपुट और आउटपुट का फ़ॉर्मैट तय करने के बाद, अपना इनपुट डेटा लें. साथ ही, अपने मॉडल के लिए सही साइज़ का इनपुट पाने के लिए ज़रूरी डेटा में बदलाव करें.

उदाहरण के लिए, अगर आपके पास [1 224 224 3] फ़्लोटिंग-पॉइंट वैल्यू के इनपुट साइज़ वाला इमेज क्लासिफ़िकेशन मॉडल है, तो आपके पास किसी Bitmap ऑब्जेक्ट से इनपुट ByteBuffer जनरेट करने का विकल्प है, जैसा कि इस उदाहरण में दिखाया गया है:

Kotlin+KTX

val bitmap = Bitmap.createScaledBitmap(yourInputImage, 224, 224, true)
val input = ByteBuffer.allocateDirect(224*224*3*4).order(ByteOrder.nativeOrder())
for (y in 0 until 224) {
    for (x in 0 until 224) {
        val px = bitmap.getPixel(x, y)

        // Get channel values from the pixel value.
        val r = Color.red(px)
        val g = Color.green(px)
        val b = Color.blue(px)

        // Normalize channel values to [-1.0, 1.0]. This requirement depends on the model.
        // For example, some models might require values to be normalized to the range
        // [0.0, 1.0] instead.
        val rf = (r - 127) / 255f
        val gf = (g - 127) / 255f
        val bf = (b - 127) / 255f

        input.putFloat(rf)
        input.putFloat(gf)
        input.putFloat(bf)
    }
}

Java

Bitmap bitmap = Bitmap.createScaledBitmap(yourInputImage, 224, 224, true);
ByteBuffer input = ByteBuffer.allocateDirect(224 * 224 * 3 * 4).order(ByteOrder.nativeOrder());
for (int y = 0; y < 224; y++) {
    for (int x = 0; x < 224; x++) {
        int px = bitmap.getPixel(x, y);

        // Get channel values from the pixel value.
        int r = Color.red(px);
        int g = Color.green(px);
        int b = Color.blue(px);

        // Normalize channel values to [-1.0, 1.0]. This requirement depends
        // on the model. For example, some models might require values to be
        // normalized to the range [0.0, 1.0] instead.
        float rf = (r - 127) / 255.0f;
        float gf = (g - 127) / 255.0f;
        float bf = (b - 127) / 255.0f;

        input.putFloat(rf);
        input.putFloat(gf);
        input.putFloat(bf);
    }
}

इसके बाद, मॉडल के आउटपुट को शामिल करने के लिए ByteBuffer का साइज़ तय करें. इसके बाद, इनपुट बफ़र और आउटपुट बफ़र को TensorFlow Lite इंटरप्रेटर के run() तरीके में पास करें. उदाहरण के लिए, [1 1000] फ़्लोटिंग-पॉइंट वैल्यू के आउटपुट आकार के लिए:

Kotlin+KTX

val bufferSize = 1000 * java.lang.Float.SIZE / java.lang.Byte.SIZE
val modelOutput = ByteBuffer.allocateDirect(bufferSize).order(ByteOrder.nativeOrder())
interpreter?.run(input, modelOutput)

Java

int bufferSize = 1000 * java.lang.Float.SIZE / java.lang.Byte.SIZE;
ByteBuffer modelOutput = ByteBuffer.allocateDirect(bufferSize).order(ByteOrder.nativeOrder());
interpreter.run(input, modelOutput);

आउटपुट का इस्तेमाल करने का तरीका, इस्तेमाल किए जा रहे मॉडल पर निर्भर करता है.

उदाहरण के लिए, अगर डेटा को अलग-अलग कैटगरी में बांटा जा रहा है, तो अगले चरण के तौर पर, उसके हिसाब से नतीजों के इंडेक्स को उन लेबल के साथ मैप करें:

Kotlin+KTX

modelOutput.rewind()
val probabilities = modelOutput.asFloatBuffer()
try {
    val reader = BufferedReader(
            InputStreamReader(assets.open("custom_labels.txt")))
    for (i in probabilities.capacity()) {
        val label: String = reader.readLine()
        val probability = probabilities.get(i)
        println("$label: $probability")
    }
} catch (e: IOException) {
    // File not found?
}

Java

modelOutput.rewind();
FloatBuffer probabilities = modelOutput.asFloatBuffer();
try {
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(getAssets().open("custom_labels.txt")));
    for (int i = 0; i < probabilities.capacity(); i++) {
        String label = reader.readLine();
        float probability = probabilities.get(i);
        Log.i(TAG, String.format("%s: %1.4f", label, probability));
    }
} catch (IOException e) {
    // File not found?
}

अपेंडिक्स: मॉडल की सुरक्षा

आप Firebase ML को अपने TensorFlow Lite मॉडल को चाहे किसी भी तरह से उपलब्ध कराएं, Firebase ML उन्हें लोकल स्टोरेज में स्टैंडर्ड सीरियल वाले प्रोटोबफ़ फ़ॉर्मैट में सेव करता है.

सिद्धांत के तौर पर, इसका मतलब है कि कोई भी व्यक्ति आपके मॉडल की कॉपी बना सकता है. हालांकि, ज़्यादातर मॉडल, ऐप्लिकेशन के हिसाब से काम के होते हैं और ऑप्टिमाइज़ेशन की वजह से उलझाने वाले होते हैं. इस वजह से, आपके कोड को खोलने और उसका फिर से इस्तेमाल करने वाले प्रतिस्पर्धियों के मुकाबले जोखिम भरा होता है. फिर भी, अपने ऐप्लिकेशन में कस्टम मॉडल का इस्तेमाल करने से पहले आपको इस जोखिम के बारे में पता होना चाहिए.

Android के एपीआई लेवल 21 (Lollipop) और इसके बाद के वर्शन पर, मॉडल को ऐसी डायरेक्ट्री में डाउनलोड किया जाता है जिसके लिए अपने-आप बैकअप लेने की सुविधा उपलब्ध नहीं है.

Android के एपीआई लेवल 20 और इससे पहले के वर्शन पर, इस मॉडल को ऐप्लिकेशन के निजी स्टोरेज में com.google.firebase.ml.custom.models नाम की डायरेक्ट्री में डाउनलोड किया जाता है. अगर आपने BackupAgent का इस्तेमाल करके फ़ाइल का बैकअप लेने की सुविधा चालू की है, तो इस डायरेक्ट्री को बाहर रखें.