#!/usr/bin/env python3 """ Attachment handler for downloading and processing file attachments from the API. """ import os import tempfile import requests import logging from pathlib import Path import mimetypes # Configure logging logger = logging.getLogger(__name__) # API base URL API_BASE_URL = "https://agents-course-unit4-scoring.hf.space" def download_file_by_task_id(task_id): """ Download a file attachment for a specific task ID. Args: task_id (str): The task ID for which to download the file Returns: dict: Information about the downloaded file including path and type, or error information if the download failed """ try: # Request the file from the API url = f"{API_BASE_URL}/files/{task_id}" logger.info(f"Attempting to download file for task ID {task_id} from {url}") response = requests.get(url, stream=True) # Check if the request was successful if response.status_code != 200: logger.error(f"Failed to download file for task ID {task_id}. Status code: {response.status_code}") return { "success": False, "error": f"Failed to download file for task ID {task_id}. Status code: {response.status_code}", "task_id": task_id } # Get content type and filename from headers if available content_type = response.headers.get('Content-Type', '') content_disposition = response.headers.get('Content-Disposition', '') logger.debug(f"Content-Type: {content_type}") logger.debug(f"Content-Disposition: {content_disposition}") # Try to extract filename from content disposition filename = None if 'filename=' in content_disposition: # Parse filename from content disposition header for part in content_disposition.split(';'): part = part.strip() if part.startswith('filename='): filename = part[9:].strip('"\'') break # If no filename in content disposition, generate one based on content-type if not filename: # Generate a filename based on task_id and content type extension = "" # More comprehensive content-type detection if 'audio/' in content_type: subtype = content_type.split('audio/')[1].split(';')[0] extension = f".{subtype}" if subtype else ".mp3" elif 'video/' in content_type: subtype = content_type.split('video/')[1].split(';')[0] extension = f".{subtype}" if subtype else ".mp4" elif 'image/' in content_type: subtype = content_type.split('image/')[1].split(';')[0] extension = f".{subtype}" if subtype else ".png" elif 'application/vnd.ms-excel' in content_type: extension = ".xls" elif 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' in content_type: extension = ".xlsx" elif 'application/excel' in content_type: extension = ".xlsx" elif 'text/csv' in content_type: extension = ".csv" elif 'application/pdf' in content_type: extension = ".pdf" elif 'text/plain' in content_type: extension = ".txt" elif 'application/json' in content_type: extension = ".json" elif 'text/x-python' in content_type or 'application/x-python-code' in content_type: extension = ".py" else: # Try to guess extension from content-type guessed_extension = mimetypes.guess_extension(content_type) extension = guessed_extension if guessed_extension else ".bin" filename = f"task_{task_id}{extension}" logger.info(f"Filename determined to be: {filename}") # Create a temporary file with the appropriate extension with tempfile.NamedTemporaryFile(delete=False, suffix=Path(filename).suffix) as temp_file: # Write the file content bytes_downloaded = 0 for chunk in response.iter_content(chunk_size=8192): if chunk: temp_file.write(chunk) bytes_downloaded += len(chunk) temp_file_path = temp_file.name logger.info(f"Successfully downloaded {bytes_downloaded} bytes to {temp_file_path}") # Return information about the downloaded file return { "success": True, "file_path": temp_file_path, "file_name": filename, "content_type": content_type, "task_id": task_id, "file_size": bytes_downloaded } except Exception as e: logger.error(f"Error downloading file for task ID {task_id}: {str(e)}") import traceback logger.error(traceback.format_exc()) return { "success": False, "error": f"Error downloading file for task ID {task_id}: {str(e)}", "task_id": task_id } def cleanup_temp_file(file_path): """ Clean up a temporary file. Args: file_path (str): The path to the file to clean up """ try: if file_path and os.path.exists(file_path): logger.debug(f"Cleaning up temporary file: {file_path}") os.unlink(file_path) logger.debug(f"Successfully cleaned up file: {file_path}") return True except Exception as e: logger.error(f"Error cleaning up temporary file {file_path}: {str(e)}") return False def download_file_from_url(url): """ Download a file from a URL. Args: url (str): The URL of the file to download Returns: dict: Information about the downloaded file """ try: logger.info(f"Downloading file from URL: {url}") # Make the request response = requests.get(url, stream=True) response.raise_for_status() # Get content type and determine filename content_type = response.headers.get('Content-Type', '') content_disposition = response.headers.get('Content-Disposition', '') # Try to extract filename from content disposition filename = None if 'filename=' in content_disposition: for part in content_disposition.split(';'): part = part.strip() if part.startswith('filename='): filename = part[9:].strip('"\'') break # If no filename provided, extract from URL if not filename: filename = os.path.basename(url) # If URL doesn't end with a filename, create one based on content-type if not filename or '.' not in filename: extension = mimetypes.guess_extension(content_type) or '.bin' filename = f"download{extension}" # Create a temporary file with the appropriate extension with tempfile.NamedTemporaryFile(delete=False, suffix=Path(filename).suffix) as temp_file: # Write the file content bytes_downloaded = 0 for chunk in response.iter_content(chunk_size=8192): if chunk: temp_file.write(chunk) bytes_downloaded += len(chunk) temp_file_path = temp_file.name logger.info(f"Successfully downloaded {bytes_downloaded} bytes to {temp_file_path}") # Return information about the downloaded file return { "success": True, "file_path": temp_file_path, "file_name": filename, "content_type": content_type, "file_size": bytes_downloaded } except Exception as e: logger.error(f"Error downloading file from URL {url}: {str(e)}") return { "success": False, "error": f"Error downloading file from URL {url}: {str(e)}" } # Test code if __name__ == "__main__": # Configure logging for testing logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) # Test with a sample task ID test_task_id = "sample-task-id" print(f"Testing download with task ID: {test_task_id}") result = download_file_by_task_id(test_task_id) if result["success"]: print(f"Successfully downloaded file: {result['file_name']} to {result['file_path']}") cleanup_temp_file(result["file_path"]) else: print(f"Failed to download file: {result['error']}") # Test URL download test_url = "https://example.com/robots.txt" print(f"\nTesting download from URL: {test_url}") url_result = download_file_from_url(test_url) if url_result["success"]: print(f"Successfully downloaded file from URL: {url_result['file_name']} to {url_result['file_path']}") cleanup_temp_file(url_result["file_path"]) else: print(f"Failed to download file from URL: {url_result['error']}")