Background Fetch API দিয়ে AI মডেলগুলি ডাউনলোড করুন

প্রকাশিত: ২০ ফেব্রুয়ারী, ২০২৫

নির্ভরযোগ্যভাবে বৃহৎ AI মডেল ডাউনলোড করা একটি চ্যালেঞ্জিং কাজ। ব্যবহারকারীরা যদি তাদের ইন্টারনেট সংযোগ হারিয়ে ফেলেন অথবা আপনার ওয়েবসাইট বা ওয়েব অ্যাপ্লিকেশন বন্ধ করে দেন, তাহলে তারা আংশিকভাবে ডাউনলোড করা মডেল ফাইলগুলি হারিয়ে ফেলেন এবং আপনার পৃষ্ঠায় ফিরে এসে নতুন করে শুরু করতে হয়। ব্যাকগ্রাউন্ড ফেচ API কে একটি প্রগতিশীল উন্নতি হিসেবে ব্যবহার করে, আপনি ব্যবহারকারীর অভিজ্ঞতা উল্লেখযোগ্যভাবে উন্নত করতে পারেন।

Browser Support

  • ক্রোম: ৭৪।
  • প্রান্ত: ৭৯।
  • ফায়ারফক্স: সমর্থিত নয়।
  • সাফারি: সমর্থিত নয়।

Source

একজন পরিষেবা কর্মী নিবন্ধন করুন

ব্যাকগ্রাউন্ড ফেচ এপিআই-এর জন্য আপনার অ্যাপকে একজন পরিষেবা কর্মী নিবন্ধন করতে হবে।

if ('serviceWorker' in navigator) {
  window.addEventListener('load', async () => {
    const registration = await navigator.serviceWorker.register('sw.js');
    console.log('Service worker registered for scope', registration.scope);
  });
}

ব্যাকগ্রাউন্ড ফেচ ট্রিগার করুন

ব্রাউজারটি যখন ডাউনলোড করে, তখন এটি ব্যবহারকারীকে অগ্রগতি প্রদর্শন করে এবং ডাউনলোড বাতিল করার একটি পদ্ধতি দেয়। ডাউনলোড সম্পূর্ণ হয়ে গেলে, ব্রাউজার পরিষেবা কর্মীকে শুরু করে এবং অ্যাপ্লিকেশনটি প্রতিক্রিয়া সহ পদক্ষেপ নিতে পারে।

ব্যাকগ্রাউন্ড ফেচ এপিআই অফলাইনে থাকাকালীনও ফেচ শুরু করার জন্য প্রস্তুত করতে পারে। ব্যবহারকারী পুনরায় সংযোগ স্থাপনের সাথে সাথেই ডাউনলোড শুরু হয়। ব্যবহারকারী অফলাইনে গেলে, ব্যবহারকারী আবার অনলাইন না হওয়া পর্যন্ত প্রক্রিয়াটি বিরতি দেয়।

নিম্নলিখিত উদাহরণে, ব্যবহারকারী Gemma 2B ডাউনলোড করার জন্য একটি বোতামে ক্লিক করেন। আনার আগে, আমরা পরীক্ষা করি যে মডেলটি আগে ডাউনলোড এবং ক্যাশে করা হয়েছে কিনা, যাতে আমরা অপ্রয়োজনীয় রিসোর্স ব্যবহার না করি। যদি এটি ক্যাশে না থাকে, তাহলে আমরা ব্যাকগ্রাউন্ড আনা শুরু করি।

const FETCH_ID = 'gemma-2b';
const MODEL_URL =
  'https://storage.googleapis.com/jmstore/kaggleweb/grader/g-2b-it-gpu-int4.bin';

downloadButton.addEventListener('click', async (event) => {
  // If the model is already downloaded, return it from the cache.
  const modelAlreadyDownloaded = await caches.match(MODEL_URL);
  if (modelAlreadyDownloaded) {
    const modelBlob = await modelAlreadyDownloaded.blob();
    // Do something with the model.
    console.log(modelBlob);
    return;
  }

  // The model still needs to be downloaded.
  // Feature detection and fallback to classic `fetch()`.
  if (!('BackgroundFetchManager' in self)) {
    try {
      const response = await fetch(MODEL_URL);
      if (!response.ok || response.status !== 200) {
        throw new Error(`Download failed ${MODEL_URL}`);
      }
      const modelBlob = await response.blob();
      // Do something with the model.
      console.log(modelBlob);
      return;
    } catch (err) {
      console.error(err);
    }
  }

  // The service worker registration.
  const registration = await navigator.serviceWorker.ready;

  // Check if there's already a background fetch running for the `FETCH_ID`.
  let bgFetch = await registration.backgroundFetch.get(FETCH_ID);

  // If not, start a background fetch.
  if (!bgFetch) {
    bgFetch = await registration.backgroundFetch.fetch(FETCH_ID, MODEL_URL, {
      title: 'Gemma 2B model',
      icons: [
        {
          src: 'icon.png',
          size: '128x128',
          type: 'image/png',
        },
      ],
      downloadTotal: await getResourceSize(MODEL_URL),
    });
  }
});

getResourceSize() ফাংশনটি ডাউনলোডের বাইট সাইজ প্রদান করে। আপনি একটি HEAD অনুরোধ করে এটি বাস্তবায়ন করতে পারেন।

const getResourceSize = async (url) => {
  try {
    const response = await fetch(url, { method: 'HEAD' });
    if (response.ok) {
      return response.headers.get('Content-Length');
    }
    console.error(`HTTP error: ${response.status}`);
    return 0;
  } catch (error) {
    console.error('Error fetching content size:', error);
    return 0;
  }
};

ডাউনলোডের অগ্রগতি রিপোর্ট করুন

ব্যাকগ্রাউন্ড ফেচ শুরু হলে, ব্রাউজারটি একটি BackgroundFetchRegistration ফেরত পাঠায়। আপনি এটি ব্যবহার করে ব্যবহারকারীকে ডাউনলোডের অগ্রগতি এবং progress ইভেন্ট সম্পর্কে অবহিত করতে পারেন।

bgFetch.addEventListener('progress', (e) => {
  // There's no download progress yet.
  if (!bgFetch.downloadTotal) {
    return;
  }
  // Something went wrong.
  if (bgFetch.failureReason) {
    console.error(bgFetch.failureReason);
  }
  if (bgFetch.result === 'success') {
    return;
  }
  // Update the user about progress.
  console.log(`${bgFetch.downloaded} / ${bgFetch.downloadTotal}`);
});

ব্যবহারকারী এবং ক্লায়েন্টকে ফেচ সম্পূর্ণ হওয়ার বিষয়ে অবহিত করুন

ব্যাকগ্রাউন্ড ফেচ সফল হলে, আপনার অ্যাপের সার্ভিস ওয়ার্কার একটি backgroundfetchsuccess ইভেন্ট পাবেন।

সার্ভিস ওয়ার্কারে নিম্নলিখিত কোডটি অন্তর্ভুক্ত করা হয়েছে। শেষের দিকে updateUI() কলটি আপনাকে ব্রাউজারের ইন্টারফেস আপডেট করতে দেয় যাতে ব্যবহারকারীকে সফল ব্যাকগ্রাউন্ড ফেচ সম্পর্কে অবহিত করা যায়। অবশেষে, ক্লায়েন্টকে ডাউনলোড সম্পন্ন হওয়ার বিষয়ে অবহিত করুন, উদাহরণস্বরূপ, postMessage() ব্যবহার করে।

self.addEventListener('backgroundfetchsuccess', (event) => {
  // Get the background fetch registration.
  const bgFetch = event.registration;

  event.waitUntil(
    (async () => {
      // Open a cache named 'downloads'.
      const cache = await caches.open('downloads');
      // Go over all records in the background fetch registration.
      // (In the running example, there's just one record, but this way
      // the code is future-proof.)
      const records = await bgFetch.matchAll();
      // Wait for the response(s) to be ready, then cache it/them.
      const promises = records.map(async (record) => {
        const response = await record.responseReady;
        await cache.put(record.request, response);
      });
      await Promise.all(promises);

      // Update the browser UI.
      event.updateUI({ title: 'Model downloaded' });

      // Inform the clients that the model was downloaded.
      self.clients.matchAll().then((clientList) => {
        for (const client of clientList) {
          client.postMessage({
            message: 'download-complete',
            id: bgFetch.id,
          });
        }
      });
    })(),
  );
});

পরিষেবা কর্মীর কাছ থেকে বার্তা গ্রহণ করুন

ক্লায়েন্টে ডাউনলোড সম্পন্ন হওয়ার বিষয়ে প্রেরিত সফল বার্তাটি পেতে, message ইভেন্টগুলি শুনুন। পরিষেবা কর্মীর কাছ থেকে বার্তাটি পাওয়ার পরে, আপনি AI মডেলের সাথে কাজ করতে পারেন এবং এটি Cache API দিয়ে সংরক্ষণ করতে পারেন।

navigator.serviceWorker.addEventListener('message', async (event) => {
  const cache = await caches.open('downloads');
  const keys = await cache.keys();
  for (const key of keys) {
    const modelBlob = await cache
      .match(key)
      .then((response) => response.blob());
    // Do something with the model.
    console.log(modelBlob);
  }
});

ব্যাকগ্রাউন্ড ফেচ বাতিল করুন

ব্যবহারকারীকে চলমান ডাউনলোড বাতিল করতে দিতে, BackgroundFetchRegistration এর abort() পদ্ধতিটি ব্যবহার করুন।

const registration = await navigator.serviceWorker.ready;
const bgFetch = await registration.backgroundFetch.get(FETCH_ID);
if (!bgFetch) {
  return;
}
await bgFetch.abort();

মডেলটি ক্যাশে করুন

ডাউনলোড করা মডেলগুলি ক্যাশে রাখুন , তাই আপনার ব্যবহারকারীরা কেবল একবার মডেলটি ডাউনলোড করেন। যদিও ব্যাকগ্রাউন্ড ফেচ API ডাউনলোডের অভিজ্ঞতা উন্নত করে, আপনার সর্বদা ক্লায়েন্ট-সাইড এআই-তে যতটা সম্ভব ছোট মডেল ব্যবহার করার লক্ষ্য রাখা উচিত।

একসাথে, এই API গুলি আপনার ব্যবহারকারীদের জন্য আরও ভালো ক্লায়েন্ট-সাইড AI অভিজ্ঞতা তৈরি করতে সাহায্য করে।

ডেমো

আপনি ডেমো এবং এর সোর্স কোডে এই পদ্ধতির সম্পূর্ণ বাস্তবায়ন দেখতে পাবেন।

Chrome DevTools অ্যাপ্লিকেশন প্যানেলে ব্যাকগ্রাউন্ড ফেচ ডাউনলোডের জন্য খোলে।
Chrome DevTools ব্যবহার করে, আপনি চলমান ব্যাকগ্রাউন্ড ফেচ সম্পর্কিত ইভেন্টগুলির পূর্বরূপ দেখতে পারবেন। ডেমোটিতে একটি চলমান ডাউনলোড দেখানো হয়েছে যা ১৭.৫৪ মিলিয়ন মেগাবাইট সম্পন্ন হয়েছে, যার মধ্যে মোট ১.২৬ গিগাবাইট রয়েছে। ব্রাউজারের ডাউনলোড সূচকটি চলমান ডাউনলোডও দেখায়।

স্বীকৃতি

ফ্রাঙ্কোইস বিউফোর্ট , আন্দ্রে বান্দারা , সেবাস্টিয়ান বেঞ্জ , মাউড নাল্পাস , এবং আলেকজান্দ্রা ক্লেপার এই নির্দেশিকাটি পর্যালোচনা করেছেন।