Skip to content
TheChatArchiveThe Chat Archive
gpt-4o-2024-05-13· OpenAIAi2 WildChat-4.8M (AI2)

saya menggunakan pydrive2 di google colab untuk mendownload file google drive, tapi…

  1. User

    saya menggunakan pydrive2 di google colab untuk mendownload file google drive, tapi sepertinya tidak full speed seperti yang diharapkan, coba modifikasi skrip berikut agar berfungsi layaknya download manager yang bisa multithreaded

    #@markdown  PyDrive2 Downloader from google.colab import auth from googleapiclient.discovery import build from googleapiclient.http import MediaIoBaseDownload from tqdm.notebook import tqdm import io import time

    Authenticate and create the service client for Drive API

    auth.authenticate_user() drive_service = build('drive', 'v3')

    ID of the file you want to download

    file_id = '1ll_9Id1ftPj0-MmWcAW7GgTRTqofJ-5T' #@param {type:"string"}

    Destination path where you want to save the file

    dst_pth = '/content/TEST.mp4' #@param {type:"string"}

    Request the file metadata to get the file size

    file_metadata = drive_service.files().get(fileId=file_id, fields='size').execute() file_size = int(file_metadata.get('size', 0))

    Request the file

    request = drive_service.files().get_media(fileId=file_id)

    Create a file handle to write the file to

    fh = io.FileIO(dst_pth, mode='wb')

    Create a downloader object

    downloader = MediaIoBaseDownload(fh, request)

    Custom format for the progress bar

    custom_tqdm_format = '{desc} |{bar}| {n_fmt}/{total_fmt} [{rate_noinv_fmt}{postfix}]'

    def adjust_units(size_in_bytes): units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'] unit_index = 0 while size_in_bytes >= 1024 and unit_index < len(units) - 1: size_in_bytes /= 1024.0 unit_index += 1 return size_in_bytes, units[unit_index]

    Create a progress bar object

    pbar = tqdm(total=file_size, desc='Downloading', unit='MB', unit_scale=True, bar_format=custom_tqdm_format)

    Start the download process and update the progress bar

    done = False start_time = time.time() while not done: status, done = downloader.next_chunk() elapsed_time = time.time() - start_time download_speed = status.progress() * file_size / elapsed_time if elapsed_time > 0 else 0 pbar.set_postfix_str(f'Speed: {download_speed:,.2f} MB/s, Elapsed: {elapsed_time:,.2f} s') pbar.update(status.resumable_progress - pbar.n) # Update progress

    Close the file handle after downloading is complete

    fh.close() pbar.close()

    print(f'File downloaded to {dst_pth}')

  2. Assistant

    Untuk meningkatkan kecepatan unduh dengan menggunakan multi-threading, prinsip dasar yang kita gunakan adalah membagi file menjadi beberapa bagian kecil dan mengunduhnya secara paralel. Pada contoh skrip yang dimodifikasi di bawah ini, kita akan menggunakan concurrent.futures untuk mengelola threading:

    1. Mendapatkan ukuran file dan membagi file menjadi beberapa bagian (chunk).
    2. Mengunduh setiap bagian menggunakan thread.

    Pada kode di bawah ini, saya telah memodifikasi skrip untuk menambahkan fungsi multi-threaded download menggunakan pustaka concurrent.futures.

    from google.colab import auth
    from googleapiclient.discovery import build
    from googleapiclient.http import MediaIoBaseDownload
    from tqdm.notebook import tqdm
    import concurrent.futures
    import io
    import time
    
    # Authenticate and create the service client for Drive API
    auth.authenticate_user()
    drive_service = build('drive', 'v3')
    
    # ID of the file you want to download
    file_id = '1ll_9Id1ftPj0-MmWcAW7GgTRTqofJ-5T'  # @param {type:"string"}
    # Destination path where you want to save the file
    dst_pth = '/content/TEST.mp4'  # @param {type:"string"}
    
    # Request the file metadata to get the file size
    file_metadata = drive_service.files().get(fileId=file_id, fields='size').execute()
    file_size = int(file_metadata.get('size', 0))
    
    # Number of threads
    num_threads = 4  # Number of threads you want. Increase or decrease based on your requirements
    
    # Calculate chunk size
    chunk_size = file_size // num_threads
    
    # Helper function to download a chunk of the file
    def download_chunk(start_byte, end_byte, thread_number):
        request = drive_service.files().get_media(fileId=file_id)
        request.headers['Range'] = f'bytes={start_byte}-{end_byte}'
    
        fh = io.BytesIO()
        downloader = MediaIoBaseDownload(fh, request)
        done = False
    
        while not done:
            status, done = downloader.next_chunk()
        
        return thread_number, fh.getvalue()
    
    # Create a progress bar object
    custom_tqdm_format = '{desc} |{bar}| {n_fmt}/{total_fmt} [{rate_noinv_fmt}{postfix}]'
    pbar = tqdm(total=file_size, desc='Downloading', unit='B', unit_scale=True, bar_format=custom_tqdm_format)
    
    file_segments = [None] * num_threads
    
    with concurrent.futures.ThreadPoolExecutor(max_workers=num_threads) as executor:
        future_to_chunk = {
            executor.submit(download_chunk, i * chunk_size, (i + 1) * chunk_size - 1, i): i
            for i in range(num_threads)
        }
    
        for future in concurrent.futures.as_completed(future_to_chunk):
            thread_number = future_to_chunk[future]
            chunk_data = future.result()
            file_segments[thread_number] = chunk_data[1]
            pbar.update(chunk_size)
    
    # Write the segments into the destination file
    with open(dst_pth, 'wb') as f:
        for segment in file_segments:
            f.write(segment)
    
    pbar.close()
    
    print(f'File downloaded to {dst_pth}')
    

    Perhatikan perubahan kunci:

    • Multi-threading: Menggunakan concurrent.futures.ThreadPoolExecutor untuk mengunduh bagian file secara paralel.
    • Chunking: Membagi file menjadi beberapa bagian dan mengunduh setiap bagian menggunakan thread terpisah.
    • Menggabungkan: Setelah mengunduh semua bagian, mereka digabungkan menjadi satu file.

    Pastikan jumlah thread (num_threads) disesuaikan dengan kemampuan koneksi internet dan spesifikasi perangkat keras, karena jumlah yang terlalu tinggi dapat menyebabkan masalah kinerja atau membebani jaringan.

  3. User

    di bagian ini

    Number of threads

    num_threads = 4 # Number of threads you want. Increase or decrease based on your requirements

    berapa maksimal num_threads atau masih wajar jika menggunakannya di google colab

  4. Assistant

    Penentuan jumlah threads (num_threads) yang optimal sangat bergantung pada beberapa faktor, termasuk kecepatan internet, spesifikasi perangkat keras (CPU dan RAM), serta batasan dan kebijakan yang diberlakukan oleh platform seperti Google Colab.

    Secara khusus untuk Google Colab:

    1. Batasan Perangkat Keras: Google Colab biasanya memberikan akses ke CPU dengan 2 core dan RAM sekitar 12-16GB dalam versi gratis. Untuk versi Pro, Anda mungkin mendapatkan lebih banyak resource.
    2. Batasan Jaringan: Google Colab menjalankan notebook di lingkungan berbagi (shared environment), yang berarti bandwidth jaringan tidak hanya digunakan oleh Anda, tetapi juga oleh pengguna lain yang menggunakan layanan yang sama.
    3. Kutub Waktu Reservasi (Runtime): Colab menerapkan batas waktu eksekusi pada setiap sesi runtime, biasanya beberapa jam. Jika runtime ini habis, semua proses akan dihentikan, termasuk proses unduh.

    Untuk menjaga keseimbangan antara kinerja unduhan dan beban sistem, berikut adalah beberapa rekomendasi untuk num_threads:

    • Mulai dengan jumlah kecil: Mulailah dengan jumlah thread yang lebih rendah seperti 4, kemudian coba tingkatkan sedikit demi sedikit sambil memantau kinerja.
    • Pengujian Kecepatan Maksimal: Pada beberapa skenario, peningkatan jumlah thread tidak selalu meningkatkan kecepatan unduhan secara proporsional, karena ada overhead pengelolaan thread.
    • Pertimbangan terhadap volatility: Google Colab bisa saja memberikan resources yang lebih rendah pada waktu-waktu tertentu, sehingga kinerja bisa bervariasi sepanjang hari.

    Sebagai referensi umum, pada Google Colab, jumlah threads yang “masih wajar” bisa berkisar antara 4 hingga 8. Namun, Anda bisa menguji hingga 16 thread tergantung pada kapasitas dan hasil pengujian.

    Berikut adalah contoh bagaimana mengatur dan menguji jumlah threads:

    # Number of threads
    initial_num_threads = 4  # Start with a base number
    max_num_threads = 16  # Test up to this number, but monitor system performance
    
    for test_num_threads in range(initial_num_threads, max_num_threads + 1, 4):
        print(f'Testing with {test_num_threads} threads...')
        # Kecepatan download dapat dipantau di sini
        # Ulangi proses unduhan yang sama dengan jumlah threads yang berbeda
        # Contoh penggunaan `test_num_threads` sebagai `num_threads`:
        
        with concurrent.futures.ThreadPoolExecutor(max_workers=test_num_threads) as executor:
            future_to_chunk = {
                executor.submit(download_chunk, i * chunk_size, (i + 1) * chunk_size - 1, i): i
                for i in range(test_num_threads)
            }
        
            for future in concurrent.futures.as_completed(future_to_chunk):
                thread_number = future_to_chunk[future]
                chunk_data = future.result()
                file_segments[thread_number] = chunk_data[1]
                pbar.update(chunk_size)
    
        # Monitoring and logging the speed or system usage can be implemented here
        # Adjust threads based on performance observations
    

    Dengan pengujian seperti ini, Anda bisa menentukan jumlah thread optimal untuk unduhan pada Google Colab dalam kasus pengecualian tertentu. Jangan lupa untuk menutup resource dan handle error jika lebih dari satu unduhan dilakukan di loop uji ini.

  5. User

    ada error seperti ini menggunakan skrip diatas


    SSLError Traceback (most recent call last) in <cell line: 49>() 55 for future in concurrent.futures.as_completed(future_to_chunk): 56 thread_number = future_to_chunk[future] ---> 57 chunk_data = future.result() 58 file_segments[thread_number] = chunk_data[1] 59 pbar.update(chunk_size)

    17 frames /usr/lib/python3.10/ssl.py in read(self, len, buffer) 1157 try: 1158 if buffer is not None: -> 1159 return self._sslobj.read(len, buffer) 1160 else: 1161 return self._sslobj.read(len)

    SSLError: [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:2578)

  6. Assistant

    Kesalahan SSLError: [SSL: WRONG_VERSION_NUMBER] biasanya terjadi karena masalah dengan koneksi SSL, yang bisa disebabkan oleh berbagai alasan seperti koneksi jaringan yang tidak stabil, konfigurasi SSL yang salah, atau batasan dari server.

    Untuk menangani dan mengatasi masalah ini, saya akan menyarankan beberapa langkah:

    1. Gunakan Backoff dan Retry: Tambahkan mekanisme backoff dan retry untuk menangani kesalahan jaringan sementara dan mencoba kembali unduhan jika terjadi kesalahan.

    2. Pastikan Semua Koneksi SSL Sudah Diperbarui: Pastikan bahwa semua pustaka yang digunakan telah diperbarui ke versi terbaru.

    Untuk mempermudah, berikut adalah skrip yang telah dimodifikasi dengan mekanisme retry menggunakan pustaka tenacity untuk menangani kesalahan SSL yang mungkin sementara.

    Pertama, instal tenacity jika belum terinstal:

    !pip install tenacity
    

    Kemudian, gunakan kode berikut di Google Colab:

    from google.colab import auth
    from googleapiclient.discovery import build
    from googleapiclient.http import MediaIoBaseDownload
    from tenacity import retry, wait_fixed, stop_after_attempt
    from tqdm.notebook import tqdm
    import concurrent.futures
    import io
    import time
    
    # Authenticate and create the service client for Drive API
    auth.authenticate_user()
    drive_service = build('drive', 'v3')
    
    # ID of the file you want to download
    file_id = '1ll_9Id1ftPj0-MmWcAW7GgTRTqofJ-5T'  # @param {type:"string"}
    # Destination path where you want to save the file
    dst_pth = '/content/TEST.mp4'  # @param {type:"string"}
    
    # Request the file metadata to get the file size
    file_metadata = drive_service.files().get(fileId=file_id, fields='size').execute()
    file_size = int(file_metadata.get('size', 0))
    
    # Number of threads
    num_threads = 4  # Number of threads you want. Increase or decrease based on your requirements
    
    # Calculate chunk size
    chunk_size = file_size // num_threads
    
    # Helper function to download a chunk of the file with retry mechanism
    @retry(wait=wait_fixed(2), stop=stop_after_attempt(5))
    def download_chunk(start_byte, end_byte, thread_number):
        request = drive_service.files().get_media(fileId=file_id)
        request.headers['Range'] = f'bytes={start_byte}-{end_byte}'
    
        fh = io.BytesIO()
        downloader = MediaIoBaseDownload(fh, request)
        done = False
    
        while not done:
            status, done = downloader.next_chunk()
        
        return thread_number, fh.getvalue()
    
    # Create a progress bar object
    custom_tqdm_format = '{desc} |{bar}| {n_fmt}/{total_fmt} [{rate_noinv_fmt}{postfix}]'
    pbar = tqdm(total=file_size, desc='Downloading', unit='B', unit_scale=True, bar_format=custom_tqdm_format)
    
    file_segments = [None] * num_threads
    
    with concurrent.futures.ThreadPoolExecutor(max_workers=num_threads) as executor:
        future_to_chunk = {
            executor.submit(download_chunk, i * chunk_size, (i + 1) * chunk_size - 1, i): i
            for i in range(num_threads)
        }
    
        for future in concurrent.futures.as_completed(future_to_chunk):
            thread_number = future_to_chunk[future]
            try:
                chunk_data = future.result()
                file_segments[thread_number] = chunk_data[1]
                pbar.update(chunk_size)
            except Exception as e:
                print(f"Error in thread {thread_number}: {e}")
                raise
    
    # Write the segments into the destination file
    with open(dst_pth, 'wb') as f:
        for segment in file_segments:
            f.write(segment)
    
    pbar.close()
    
    print(f'File downloaded to {dst_pth}')
    

    Penjelasan tambahan:

    1. Tenacity for Retry: Pustaka tenacity digunakan untuk menangani retry otomatis ketika terjadi kesalahan. Dalam fungsi download_chunk, jika terjadi kesalahan, ia akan mencoba kembali hingga 5 kali dengan interval 2 detik di antara percobaan.
    2. Handling Errors per Thread: Dalam pengelolaan future dari concurrent.futures, jika ada kesalahan pada download, informasi kesalahan akan dicetak dan menghentikan eksekusi lebih lanjut.

    Dengan pendekatan ini, seharusnya dapat membantu menangani masalah SSL: WRONG_VERSION_NUMBER. Jika masalah ini masih terjadi, kemungkinan ada masalah yang lebih mendasar dengan koneksi jaringan atau platform Google Colab saat itu.