Search code examples
pythonpython-requestsdownloadprogress-barmp4

Progress bar not working properly in Python


I have created a program that downloads mp4 videos from a link. I've added the code below

chunk_size = 256
URL = 'https://gogodownload.net/download.php?url=aHR0cHM6LyAdrefsdsdfwerFrefdsfrersfdsrfer363435349URASDGHUSRFSJGYfdsffsderFStewthsfSFtrftesdfseWVpYnU0bmM3LmdvY2RuYW5pLmNvbS91c2VyMTM0Mi9lYzBiNzk3NmM1M2Q4YmY5MDU2YTYwNjdmMGY3ZTA3Ny9FUC4xLnYwLjM2MHAubXA0P3Rva2VuPW8wVnNiR3J6ZXNWaVA0UkljRXBvc2cmZXhwaXJlcz0xNjcxOTkzNzg4JmlkPTE5MzU1Nw=='
x = requests.head(URL)
y = requests.head(x.headers['Location'])

file_size = int(y.headers['content-length'])

response = requests.get(URL, stream=True)
with open('video.mp4', 'wb') as f:
    for chunk in response.iter_content(chunk_size=chunk_size):
        f.write(chunk)

This code works properly and downloads the video but I want to add a live progress bar. I Tried using alive-progress (code added below) but it didnt work properly.

def compute():
    response = requests.get(URL, stream=True)
    with open('video.mp4', 'wb') as f:
        for chunk in response.iter_content(chunk_size=chunk_size):
            f.write(chunk)
            yield 256

with alive_bar(file_size) as bar:
    for i in compute():
        bar()

This is the response I got, however the file downloaded properly Alive Progress

Any help?


Solution

  • This is the code you should try. I updated your chunk_size property to match the file size, which I also converted into KB (Kilo Bytes). It shows the values properly alongside the percentage as well

    As for the weird boxes showing up on your terminal, that is because your terminal does not support the encoding used by the library. Maybe try editing your terminal settings to support "UTF-8" or higher

    file_size = int(int(y.headers['content-length']) / 1024)
    chunk_size = 1024
    
    def compute():
        response = requests.get(URL, stream=True)
        with open('video.mp4', 'wb') as f:
            for chunk in response.iter_content(chunk_size=chunk_size):
                f.write(chunk)
                yield 1024
    
    with alive_bar(file_size) as bar:
        for i in compute():
            bar()