File size: 9,486 Bytes
90d7802
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
#!/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']}")