Spaces:
Sleeping
Sleeping
| import os | |
| import requests | |
| import requests | |
| import base64 | |
| def download_file(task_id: str): | |
| # Construct the URL | |
| url = f"https://agents-course-unit4-scoring.hf.space/files/{task_id}" | |
| # Send the request to download the file | |
| response = requests.get(url) | |
| if response.status_code == 200: | |
| # Get the content type from the response headers to determine the file extension | |
| content_type = response.headers.get('Content-Type', '') | |
| file_extension = '' | |
| # Map content types to file extensions | |
| if 'pdf' in content_type: | |
| file_extension = '.pdf' | |
| elif 'jpg' in content_type or 'jpeg' in content_type: | |
| file_extension = '.jpg' | |
| elif 'png' in content_type: | |
| file_extension = '.png' | |
| elif 'txt' in content_type: | |
| file_extension = '.txt' | |
| elif 'zip' in content_type: | |
| file_extension = '.zip' | |
| elif 'mp3' in content_type: | |
| file_extension = '.mp3' | |
| # Add more file types as necessary | |
| # If the extension can't be determined, default to .bin | |
| if not file_extension: | |
| file_extension = '.bin' | |
| # Set the path to the Downloads folder (adjust 'YourUsername' to your actual username) | |
| save_path = os.path.join(os.path.expanduser('~'), 'Downloads', f"{task_id}_file{file_extension}") | |
| # Save the file with the appropriate extension | |
| with open(save_path, 'wb') as f: | |
| f.write(response.content) | |
| print(f"File successfully downloaded and saved as {save_path}") | |
| else: | |
| print(f"Failed to download the file. Status code: {response.status_code}") | |
| def download_file_as_base64(task_id: str) -> str: | |
| # Construct the URL | |
| url = f"https://agents-course-unit4-scoring.hf.space/files/{task_id}" | |
| # Send the request to download the file | |
| response = requests.get(url) | |
| if response.status_code == 200: | |
| # Encode the content to Base64 | |
| encoded_bytes = base64.b64encode(response.content) | |
| encoded_str = encoded_bytes.decode('utf-8') # Convert bytes to string | |
| return encoded_str | |
| else: | |
| raise Exception(f"Failed to download the file. Status code: {response.status_code}") | |