import os import requests from huggingface_hub import HfApi from dotenv import load_dotenv # Load environment variables from .env file (where HF_TOKEN is stored) load_dotenv() # Get the Hugging Face token from environment variable HF_TOKEN = os.getenv("HF_TOKEN") # Check if token is available if not HF_TOKEN: raise ValueError("HF_TOKEN not found in environment variables. Please set it in a .env file.") # Initialize Hugging Face API api = HfApi() # URL of the file to copy file_url = "https://physionet.org/static/published-projects/ptb-xl/ptb-xl-a-large-publicly-available-electrocardiography-dataset-1.0.3.zip" filename = "ptb-xl-a-large-publicly-available-electrocardiography-dataset-1.0.3.zip" # Repository details repo_id = "Nayefleb/ECG" repo_type = "space" def download_and_upload_file(): try: # Temporary path to store the file in the Space's environment temp_path = f"/tmp/{filename}" # Download the file from the URL to the temporary path print(f"Downloading {filename} from {file_url}...") response = requests.get(file_url, stream=True) response.raise_for_status() # Raise an error if the download fails with open(temp_path, "wb") as f: for chunk in response.iter_content(chunk_size=8192): f.write(chunk) print(f"Downloaded {filename} to temporary storage.") # Upload the file to Hugging Face Space print(f"Uploading {filename} to {repo_id}...") api.upload_file( path_or_fileobj=temp_path, # Local path in the Space's environment path_in_repo=filename, # Destination path in the repository repo_id=repo_id, repo_type=repo_type, token=HF_TOKEN ) print(f"Successfully uploaded {filename} to {repo_id}") # Clean up the temporary file os.remove(temp_path) print("Cleaned up temporary file.") except Exception as e: print(f"Error: {str(e)}") if __name__ == "__main__": download_and_upload_file()