Skip to content
The Chat Archive
claude-opus-4-20250514-thinking-16k· Anthropic LMArena Human Preference 140K

I am getting a link which can be either pdf, excel or doc write a python code to infer…

  1. User

    I am getting a link which can be either pdf, excel or doc write a python code to infer type of the file any other file detected raise exception

  2. Assistant

    Here's a Python code that can infer the file type from a URL and raise an exception for unsupported file types:

    import requests
    import os
    from urllib.parse import urlparse
    
    class UnsupportedFileTypeError(Exception):
        """Custom exception for unsupported file types"""
        pass
    
    def infer_file_type(url):
        """
        Infer file type from a URL. Supports PDF, Excel (xls, xlsx), and Word (doc, docx).
        Raises UnsupportedFileTypeError for other file types.
        """
        
        # Define supported file extensions and their MIME types
        SUPPORTED_TYPES = {
            'pdf': {
                'extensions': ['.pdf'],
                'mime_types': ['application/pdf'],
                'magic_bytes': [b'%PDF']
            },
            'excel': {
                'extensions': ['.xls', '.xlsx', '.xlsm', '.xlsb'],
                'mime_types': [
                    'application/vnd.ms-excel',
                    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                    'application/vnd.ms-excel.sheet.macroEnabled.12',
                    'application/vnd.ms-excel.sheet.binary.macroEnabled.12'
                ],
                'magic_bytes': [
                    b'\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1',  # XLS
                    b'PK\x03\x04'  # XLSX (ZIP format)
                ]
            },
            'word': {
                'extensions': ['.doc', '.docx', '.docm'],
                'mime_types': [
                    'application/msword',
                    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                    'application/vnd.ms-word.document.macroEnabled.12'
                ],
                'magic_bytes': [
                    b'\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1',  # DOC
                    b'PK\x03\x04'  # DOCX (ZIP format)
                ]
            }
        }
        
        try:
            # Step 1: Check URL extension
            parsed_url = urlparse(url)
            filename = os.path.basename(parsed_url.path)
            file_extension = os.path.splitext(filename)[1].lower()
            
            file_type_from_ext = None
            for file_type, info in SUPPORTED_TYPES.items():
                if file_extension in info['extensions']:
                    file_type_from_ext = file_type
                    break
            
            # Step 2: Make a HEAD request to check content-type
            headers = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
            }
            
            response = requests.head(url, headers=headers, allow_redirects=True, timeout=10)
            
            # If HEAD fails, try GET with stream
            if response.status_code != 200:
                response = requests.get(url, headers=headers, stream=True, timeout=10)
                response.raise_for_status()
            
            content_type = response.headers.get('content-type', '').lower()
            
            file_type_from_mime = None
            for file_type, info in SUPPORTED_TYPES.items():
                if any(mime in content_type for mime in info['mime_types']):
                    file_type_from_mime = file_type
                    break
            
            # Step 3: If needed, check magic bytes
            file_type_from_magic = None
            if file_type_from_ext != file_type_from_mime or (not file_type_from_ext and not file_type_from_mime):
                # Download first few bytes to check magic bytes
                response = requests.get(url, headers=headers, stream=True, timeout=10)
                response.raise_for_status()
                
                # Read first 8 bytes (enough for most magic bytes)
                first_bytes = response.raw.read(8)
                
                for file_type, info in SUPPORTED_TYPES.items():
                    for magic in info['magic_bytes']:
                        if first_bytes.startswith(magic):
                            # For ZIP-based formats (XLSX, DOCX), need additional checking
                            if magic == b'PK\x03\x04':
                                # Download more to check for specific Office format
                                more_bytes = response.raw.read(1024)
                                full_bytes = first_bytes + more_bytes
                                
                                if b'word/' in full_bytes or b'document.xml' in full_bytes:
                                    file_type_from_magic = 'word'
                                elif b'xl/' in full_bytes or b'workbook.xml' in full_bytes:
                                    file_type_from_magic = 'excel'
                            else:
                                file_type_from_magic = file_type
                            break
                    if file_type_from_magic:
                        break
            
            # Determine final file type
            detected_type = file_type_from_ext or file_type_from_mime or file_type_from_magic
            
            if not detected_type:
                raise UnsupportedFileTypeError(
                    f"Unsupported file type. URL: {url}, "
                    f"Extension: {file_extension or 'None'}, "
                    f"Content-Type: {content_type or 'None'}"
                )
            
            return detected_type
            
        except requests.RequestException as e:
            raise Exception(f"Error accessing URL: {str(e)}")
        except Exception as e:
            if isinstance(e, UnsupportedFileTypeError):
                raise
            else:
                raise Exception(f"Error processing file: {str(e)}")
    
    
    # Example usage
    if __name__ == "__main__":
        # Test URLs
        test_urls = [
            "https://example.com/document.pdf",
            "https://example.com/spreadsheet.xlsx",
            "https://example.com/report.doc",
            "https://example.com/image.jpg",  # This should raise exception
        ]
        
        for url in test_urls:
            try:
                file_type = infer_file_type(url)
                print(f"URL: {url}")
                print(f"Detected file type: {file_type}")
                print("-" * 50)
            except UnsupportedFileTypeError as e:
                print(f"Error: {e}")
                print("-" * 50)
            except Exception as e:
                print(f"Unexpected error: {e}")
                print("-" * 50)
    

    Here's also a simplified version that only checks the URL extension if you don't need the robustness of checking actual file content:

    import os
    from urllib.parse import urlparse
    
    class UnsupportedFileTypeError(Exception):
        """Custom exception for unsupported file types"""
        pass
    
    def infer_file_type_simple(url):
        """
        Simple file type inference based on URL extension only.
        """
        # Define supported extensions
        SUPPORTED_EXTENSIONS = {
            '.pdf': 'pdf',
            '.xls': 'excel',
            '.xlsx': 'excel',
            '.xlsm': 'excel',
            '.xlsb': 'excel',
            '.doc': 'word',
            '.docx': 'word',
            '.docm': 'word'
        }
        
        # Parse URL and get file extension
        parsed_url = urlparse(url)
        filename = os.path.basename(parsed_url.path)
        file_extension = os.path.splitext(filename)[1].lower()
        
        if file_extension in SUPPORTED_EXTENSIONS:
            return SUPPORTED_EXTENSIONS[file_extension]
        else:
            raise UnsupportedFileTypeError(
                f"Unsupported file type: {file_extension or 'No extension found'} in URL: {url}"
            )
    
    # Example usage
    try:
        url = "https://example.com/document.pdf"
        file_type = infer_file_type_simple(url)
        print(f"File type: {file_type}")
    except UnsupportedFileTypeError as e:
        print(f"Error: {e}")
    

    The first solution is more robust as it:

    1. Checks the file extension from the URL
    2. Verifies with HTTP content-type headers
    3. Checks magic bytes (file signatures) for additional verification
    4. Handles edge cases like redirects and missing extensions

    The second solution is simpler and faster but only relies on the URL extension, which might not always be accurate.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.