Catch up on highlights from Firebase at Google I/O 2023. Learn more

نشر وإدارة النماذج المخصصة

يمكنك نشر وإدارة النماذج المخصصة والنماذج المدربة على AutoML باستخدام إما وحدة تحكم Firebase أو Firebase Admin Python و Node.js SDK. إذا كنت ترغب فقط في نشر نموذج وتحديثه من حين لآخر ، فعادة ما يكون من الأسهل استخدام وحدة تحكم Firebase. يمكن أن يكون Admin SDK مفيدًا عند الدمج مع خطوط الأنابيب ، والعمل مع أجهزة الكمبيوتر المحمولة Colab أو Jupyter ، ومهام سير العمل الأخرى.

نشر النماذج وإدارتها في وحدة تحكم Firebase

نماذج TensorFlow Lite

لنشر نموذج TensorFlow Lite باستخدام وحدة تحكم Firebase:

  1. افتح صفحة نموذج Firebase ML Custom في وحدة تحكم Firebase.
  2. انقر فوق إضافة نموذج مخصص (أو إضافة نموذج آخر ).
  3. حدد اسمًا سيتم استخدامه لتعريف نموذجك في مشروع Firebase الخاص بك ، ثم قم بتحميل ملف نموذج TensorFlow Lite (عادةً ما ينتهي بـ .tflite أو .lite ).

بعد نشر النموذج الخاص بك ، يمكنك العثور عليه في الصفحة المخصصة. من هناك ، يمكنك إكمال المهام مثل تحديث النموذج بملف جديد وتنزيل النموذج وحذف النموذج من مشروعك.

انشر النماذج وأدرها باستخدام Firebase Admin SDK

يوضح هذا القسم كيف يمكنك إكمال مهام إدارة ونشر النموذج الشائعة باستخدام Admin SDK. راجع مرجع SDK لـ Python أو Node.js للحصول على مساعدة إضافية.

للحصول على أمثلة حول SDK قيد الاستخدام ، راجع نموذج Python quickstart وعينة Node.js quickstart .

قبل ان تبدأ

  1. إذا لم يكن لديك بالفعل مشروع Firebase ، فأنشئ مشروعًا جديدًا في وحدة تحكم Firebase . بعد ذلك ، افتح مشروعك وقم بما يلي:

    1. في صفحة الإعدادات ، قم بإنشاء حساب خدمة وتنزيل ملف مفتاح حساب الخدمة. احتفظ بهذا الملف آمنًا ، لأنه يمنح وصول المسؤول إلى مشروعك.

    2. في صفحة التخزين ، قم بتمكين التخزين السحابي. سجل اسم الدلو الخاص بك.

      أنت بحاجة إلى حاوية التخزين السحابي لتخزين ملفات النماذج مؤقتًا أثناء إضافتها إلى مشروع Firebase. إذا كنت تستخدم خطة Blaze ، فيمكنك إنشاء واستخدام دلو غير الافتراضي لهذا الغرض.

    3. في صفحة Firebase ML ، انقر فوق البدء إذا لم تقم بتمكين Firebase ML بعد.

  2. في وحدة تحكم Google APIs ، افتح مشروع Firebase الخاص بك وقم بتمكين Firebase ML API.

  3. قم بتثبيت وتهيئة Admin SDK .

    عند تهيئة SDK ، حدد بيانات اعتماد حساب الخدمة وحاوية التخزين السحابي التي تريد استخدامها لتخزين النماذج الخاصة بك:

    بايثون

    import firebase_admin
    from firebase_admin import ml
    from firebase_admin import credentials
    
    firebase_admin.initialize_app(
      credentials.Certificate('/path/to/your/service_account_key.json'),
      options={
          'storageBucket': 'your-storage-bucket',
      })
    

    Node.js

    const admin = require('firebase-admin');
    const serviceAccount = require('/path/to/your/service_account_key.json');
    admin.initializeApp({
      credential: admin.credential.cert(serviceAccount),
      storageBucket: 'your-storage-bucket',
    });
    const ml = admin.machineLearning();
    

نشر النماذج

ملفات TensorFlow Lite

لنشر نموذج TensorFlow Lite من ملف نموذج ، قم بتحميله إلى مشروعك ثم انشره:

بايثون

# First, import and initialize the SDK as shown above.

# Load a tflite file and upload it to Cloud Storage
source = ml.TFLiteGCSModelSource.from_tflite_model_file('example.tflite')

# Create the model object
tflite_format = ml.TFLiteFormat(model_source=source)
model = ml.Model(
    display_name="example_model",  # This is the name you use from your app to load the model.
    tags=["examples"],             # Optional tags for easier management.
    model_format=tflite_format)

# Add the model to your Firebase project and publish it
new_model = ml.create_model(model)
ml.publish_model(new_model.model_id)

Node.js

// First, import and initialize the SDK as shown above.

(async () => {
  // Upload the tflite file to Cloud Storage
  const storageBucket = admin.storage().bucket('your-storage-bucket');
  const files = await storageBucket.upload('./example.tflite');

  // Create the model object and add the model to your Firebase project.
  const bucket = files[0].metadata.bucket;
  const name = files[0].metadata.name;
  const gcsUri = `gs:/⁠/${bucket}/${name}`;
  const model = await ml.createModel({
    displayName: 'example_model',  // This is the name you use from your app to load the model.
    tags: ['examples'],  // Optional tags for easier management.
    tfliteModel: { gcsTfliteUri: gcsUri },
  });

  // Publish the model.
  await ml.publishModel(model.modelId);

  process.exit();
})().catch(console.error);

نماذج TensorFlow و Keras

باستخدام Python SDK ، يمكنك تحويل نموذج من تنسيق نموذج محفوظ TensorFlow إلى TensorFlow Lite وتحميله إلى حاوية التخزين السحابي في خطوة واحدة. بعد ذلك ، انشره بنفس الطريقة التي تنشر بها ملف TensorFlow Lite.

بايثون

# First, import and initialize the SDK as shown above.

# Convert the model to TensorFlow Lite and upload it to Cloud Storage
source = ml.TFLiteGCSModelSource.from_saved_model('./model_directory')

# Create the model object
tflite_format = ml.TFLiteFormat(model_source=source)
model = ml.Model(
    display_name="example_model",  # This is the name you use from your app to load the model.
    tags=["examples"],             # Optional tags for easier management.
    model_format=tflite_format)

# Add the model to your Firebase project and publish it
new_model = ml.create_model(model)
ml.publish_model(new_model.model_id)

إذا كان لديك نموذج Keras ، فيمكنك أيضًا تحويله إلى TensorFlow Lite وتحميله في خطوة واحدة. يمكنك استخدام نموذج Keras المحفوظ في ملف HDF5:

بايثون

import tensorflow as tf

# Load a Keras model, convert it to TensorFlow Lite, and upload it to Cloud Storage
model = tf.keras.models.load_model('your_model.h5')
source = ml.TFLiteGCSModelSource.from_keras_model(model)

# Create the model object, add the model to your project, and publish it. (See
# above.)
# ...

أو يمكنك تحويل نموذج Keras وتحميله مباشرة من البرنامج النصي التدريبي الخاص بك:

بايثون

import tensorflow as tf

# Create a simple Keras model.
x = [-1, 0, 1, 2, 3, 4]
y = [-3, -1, 1, 3, 5, 7]

model = tf.keras.models.Sequential(
    [tf.keras.layers.Dense(units=1, input_shape=[1])])
model.compile(optimizer='sgd', loss='mean_squared_error')
model.fit(x, y, epochs=3)

# Convert the model to TensorFlow Lite and upload it to Cloud Storage
source = ml.TFLiteGCSModelSource.from_keras_model(model)

# Create the model object, add the model to your project, and publish it. (See
# above.)
# ...

نماذج AutoML TensorFlow Lite

إذا قمت بتدريب نموذج Edge باستخدام AutoML Cloud API أو باستخدام Google Cloud Console UI ، فيمكنك نشر النموذج على Firebase باستخدام Admin SDK.

ستحتاج إلى تحديد معرف مورد النموذج ، وهو عبارة عن سلسلة تشبه المثال التالي:

projects/PROJECT_NUMBER/locations/STORAGE_LOCATION/models/MODEL_ID
PROJECT_NUMBER رقم مشروع حاوية التخزين السحابي التي تحتوي على النموذج. قد يكون هذا هو مشروع Firebase الخاص بك أو مشروع Google Cloud آخر. يمكنك العثور على هذه القيمة في صفحة الإعدادات بوحدة تحكم Firebase أو لوحة تحكم Google Cloud Console.
STORAGE_LOCATION موقع الموارد لحاوية التخزين السحابي التي تحتوي على النموذج. هذه القيمة هي دائمًا us-central1 .
MODEL_ID معرّف النموذج الذي حصلت عليه من AutoML Cloud API.

بايثون

# First, import and initialize the SDK as shown above.

# Get a reference to the AutoML model
source = ml.TFLiteAutoMlSource('projects/{}/locations/{}/models/{}'.format(
    # See above for information on these values.
    project_number,
    storage_location,
    model_id
))

# Create the model object
tflite_format = ml.TFLiteFormat(model_source=source)
model = ml.Model(
    display_name="example_model",  # This is the name you will use from your app to load the model.
    tags=["examples"],             # Optional tags for easier management.
    model_format=tflite_format)

# Add the model to your Firebase project and publish it
new_model = ml.create_model(model)
new_model.wait_for_unlocked()
ml.publish_model(new_model.model_id)

Node.js

// First, import and initialize the SDK as shown above.

(async () => {
  // Get a reference to the AutoML model. See above for information on these
  // values.
  const automlModel = `projects/${projectNumber}/locations/${storageLocation}/models/${modelId}`;

  // Create the model object and add the model to your Firebase project.
  const model = await ml.createModel({
    displayName: 'example_model',  // This is the name you use from your app to load the model.
    tags: ['examples'],  // Optional tags for easier management.
    tfliteModel: { automlModel: automlModel },
  });

  // Wait for the model to be ready.
  await model.waitForUnlocked();

  // Publish the model.
  await ml.publishModel(model.modelId);

  process.exit();
})().catch(console.error);

ضع قائمة بنماذج مشروعك

يمكنك سرد نماذج مشروعك ، اختياريا تصفية النتائج:

بايثون

# First, import and initialize the SDK as shown above.

face_detectors = ml.list_models(list_filter="tags: face_detector").iterate_all()
print("Face detection models:")
for model in face_detectors:
  print('{} (ID: {})'.format(model.display_name, model.model_id))

Node.js

// First, import and initialize the SDK as shown above.

(async () => {
  let listOptions = {filter: 'tags: face_detector'}
  let models;
  let pageToken = null;
  do {
    if (pageToken) listOptions.pageToken = pageToken;
    ({models, pageToken} = await ml.listModels(listOptions));
    for (const model of models) {
      console.log(`${model.displayName} (ID: ${model.modelId})`);
    }
  } while (pageToken != null);

  process.exit();
})().catch(console.error);

يمكنك التصفية حسب الحقول التالية:

مجال أمثلة
display_name display_name = example_model
display_name != example_model

جميع أسماء العرض بالبادئة_ experimental_ :

display_name : experimental_*

لاحظ أنه يتم دعم مطابقة البادئة فقط.

tags tags: face_detector
tags: face_detector AND tags: experimental
state.published state.published = true
state.published = false

ادمج عوامل التصفية مع عوامل التشغيل AND و OR و NOT والأقواس ( ( ، ) ).

نماذج التحديث

بعد إضافة نموذج إلى مشروعك ، يمكنك تحديث اسم العرض والعلامات وملف نموذج tflite :

بايثون

# First, import and initialize the SDK as shown above.

model = ...   # Model object from create_model(), get_model(), or list_models()

# Update the model with a new tflite model. (You could also update with a
# `TFLiteAutoMlSource`)
source = ml.TFLiteGCSModelSource.from_tflite_model_file('example_v2.tflite')
model.model_format = ml.TFLiteFormat(model_source=source)

# Update the model's display name.
model.display_name = "example_model"

# Update the model's tags.
model.tags = ["examples", "new_models"]

# Add a new tag.
model.tags += "experimental"

# After you change the fields you want to update, save the model changes to
# Firebase and publish it.
updated_model = ml.update_model(model)
ml.publish_model(updated_model.model_id)

Node.js

// First, import and initialize the SDK as shown above.

(async () => {
  const model = ... // Model object from createModel(), getModel(), or listModels()

  // Upload a new tflite file to Cloud Storage.
  const files = await storageBucket.upload('./example_v2.tflite');
  const bucket = files[0].metadata.bucket;
  const name = files[0].metadata.name;

  // Update the model. Any fields you omit will be unchanged.
  await ml.updateModel(model.modelId, {
    displayName: 'example_model',  // Update the model's display name.
    tags: model.tags.concat(['new']),  // Add a tag.
    tfliteModel: {gcsTfliteUri: `gs:/⁠/${bucket}/${name}`},
  });

  process.exit();
})().catch(console.error);

إلغاء نشر أو حذف النماذج

لإلغاء نشر نموذج أو حذفه ، مرر معرف النموذج إلى أساليب إلغاء النشر أو الحذف. عندما تقوم بإلغاء نشر نموذج ، فإنه يظل في مشروعك ، ولكنه غير متاح لتنزيل تطبيقاتك. عندما تحذف نموذجًا ، تتم إزالته تمامًا من مشروعك. (لا يُتوقع إلغاء نشر نموذج في سير عمل قياسي ، ولكن يمكنك استخدامه لإلغاء نشر نموذج جديد على الفور قمت بنشره عن طريق الخطأ ولم يتم استخدامه في أي مكان حتى الآن ، أو في الحالات التي يكون فيها من الأسوأ على المستخدمين تنزيل ملف "سيء" النموذج بدلاً من الحصول على أخطاء غير موجودة في النموذج.)

إذا لم يكن لديك مرجع إلى كائن النموذج ، فربما تحتاج إلى الحصول على معرف النموذج عن طريق سرد نماذج مشروعك مع مرشح. على سبيل المثال ، لحذف جميع النماذج التي تحمل علامة "face_detector":

بايثون

# First, import and initialize the SDK as shown above.

face_detectors = ml.list_models(list_filter="tags: 'face_detector'").iterate_all()
for model in face_detectors:
  ml.delete_model(model.model_id)

Node.js

// First, import and initialize the SDK as shown above.

(async () => {
  let listOptions = {filter: 'tags: face_detector'}
  let models;
  let pageToken = null;
  do {
    if (pageToken) listOptions.pageToken = pageToken;
    ({models, pageToken} = await ml.listModels(listOptions));
    for (const model of models) {
      await ml.deleteModel(model.modelId);
    }
  } while (pageToken != null);

  process.exit();
})().catch(console.error);