import os
import requests
from tqdm import tqdm  # Import tqdm for the progress bar

# Input the .m4s URL
url = input("Please enter the .m4s URL: ").strip()

# Input the filename for saving the video segment (with .mp4 extension)
filename = input("Please enter the filename : ").strip() + ".mp4"  # Ensure .mp4 extension

# Function to download the .m4s file with progress bar
def download_m4s(url, output_filename):
    print(f"Downloading {url}...")
    
    # Send a GET request to download the video segment
    response = requests.get(url, stream=True)
    
    if response.status_code == 200:
        # Get the content length from the response headers
        total_size = int(response.headers.get('Content-Length', 0))
        
        # Open the file to write the content
        with open(output_filename, 'wb') as file:
            # Use tqdm to create a progress bar for the download
            with tqdm(total=total_size, unit='B', unit_scale=True, desc=output_filename) as bar:
                for chunk in response.iter_content(chunk_size=8192):
                    if chunk:  # Filter out keep-alive chunks
                        file.write(chunk)
                        bar.update(len(chunk))  # Update the progress bar
        print(f"Downloaded successfully: {output_filename}")
    else:
        print(f"Failed to download. HTTP status code: {response.status_code}")

# Call the function to download the .m4s file
download_m4s(url, filename)
