Skip to content
TheChatArchiveThe Chat Archive
Geminigemini-2.5-flash-lite-preview-06-17-thinking· GoogleHugging Face LMArena Human Preference 140K

https://docs.google.com/document/d/1li3J7ZJx2spu-Ua0qXmhkTaMV5Pe6R5D6UOjvlwlWXs this is…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Claudeclaude-sonnet-4-20250514’s answer.
  1. User
  2. Gemini Assistant

    You've hit on a key limitation! The URL you provided:

    https://docs.google.com/document/d/1li3J7ZJx2spu-Ua0qXmhkTaMV5Pe6R5D6UOjvlwlWXs

    is not a direct link to a downloadable file (like .docx, .pdf, etc.). It's a link to the Google Docs web interface for viewing or editing the document.

    The previous code works by:

    1. Looking at the file extension in the URL (.pdf, .xlsx, etc.). This URL has no such extension.
    2. Making an HTTP request (HEAD or GET) and checking the Content-Type header. Google Docs will serve this URL as an HTML page (text/html), not as a Word document file.
    3. Checking magic bytes, which requires downloading the actual file data. Downloading the HTML page won't reveal Word magic bytes.

    How to Address This:

    You need to decide how you want to handle these kinds of URLs.

    Option 1: Reject Google Docs Links Explicitly

    Modify the code to specifically detect Google Docs (or similar web app) URLs and raise a specific error, acknowledging it's not a direct file link.

    import requests
    import os
    from urllib.parse import urlparse
    
    class UnsupportedFileTypeError(Exception):
        """Custom exception for unsupported file types"""
        pass
    
    class NotADirectFileLinkError(Exception):
        """Custom exception for URLs that are not direct file links"""
        pass
    
    def infer_file_type(url):
        """
        Infer file type from a URL. Supports direct links to PDF, Excel (xls, xlsx),
        and Word (doc, docx).
        Raises UnsupportedFileTypeError for unsupported file types.
        Raises NotADirectFileLinkError for URLs that are not direct file downloads
        (e.g., Google Docs view links).
        """
    
        # --- Check for Google Docs / Sheets / Slides VIEW URLs ---
        # This is a common pattern, but might need adjustment for other Google services
        # or future changes by Google.
        parsed_url = urlparse(url)
        if "docs.google.com" in parsed_url.netloc and "/document/d/" in parsed_url.path:
            raise NotADirectFileLinkError(f"URL appears to be a Google Docs view link, not a direct file download: {url}")
        if "sheets.google.com" in parsed_url.netloc and "/edit" in parsed_url.path:
             raise NotADirectFileLinkError(f"URL appears to be a Google Sheets view link, not a direct file download: {url}")
        # Add similar checks for other services like Slides if needed
    
        # --- Original Logic Starts Here ---
    
        # Define supported file extensions and their MIME types
        SUPPORTED_TYPES = {
            'pdf': {
                'extensions': ['.pdf'],
                'mime_types': ['application/pdf'],
                # Note: Magic bytes might be less reliable for PDFs served directly
                # without specific content-disposition headers.
                '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 (COM Structure Binary File)
                    b'PK\x03\x04'  # XLSX, XLSM, XLSB (ZIP format)
                ]
            },
            'word': {
                'extensions': ['.doc', '.docx', '.docm'],
                'mime_types': [
                    'application/msword', # .doc
                    'application/vnd.openxmlformats-officedocument.wordprocessingml.document', # .docx
                    'application/vnd.ms-word.document.macroEnabled.12' # .docm
                ],
                'magic_bytes': [
                    b'\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1',  # DOC (COM Structure Binary File)
                    b'PK\x03\x04'  # DOCX, DOCM (ZIP format)
                ]
            }
        }
    
        # Use the previously parsed URL object
        filename = os.path.basename(parsed_url.path)
        file_extension = os.path.splitext(filename)[1].lower()
    
        file_type_found = None
        checked_content = False # Flag to avoid redundant downloads
    
        # 1. Check Extension First (Quick check)
        for file_type, info in SUPPORTED_TYPES.items():
            if file_extension in info['extensions']:
                file_type_found = file_type
                break
    
        # 2. Check Content-Type Header if extension didn't match or is ambiguous (like PK)
        #    or if we didn't already find a strong candidate via extension.
        if file_type_found is None or file_extension in ['.docx', '.xlsx']: # Need Content-Type for zip-based
            try:
                headers = {
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
                }
                # Try HEAD first for efficiency
                response = requests.head(url, headers=headers, allow_redirects=True, timeout=10)
                response.raise_for_status() # Raise error for bad status codes (4xx or 5xx)
    
                content_type = response.headers.get('content-type', '').lower()
    
                for file_type, info in SUPPORTED_TYPES.items():
                    if any(mime in content_type for mime in info['mime_types']):
                        # If we already had a match by extension, ensure they agree
                        if file_type_found and file_type_found != file_type:
                             # Ambiguity: e.g., extension says PDF, Content-Type says something else
                             # Fallback to magic bytes or raise error depending on strictness needed
                             pass # Continue to magic bytes check below
                        else:
                            file_type_found = file_type
                            checked_content = True # We got a likely match from headers
                            break # Found a match via Content-Type
    
                # If extension check failed but Content-Type matched, we trust Content-Type for now
                if not file_extension and file_type_found:
                    checked_content = True
    
            except requests.exceptions.RequestException as e:
                # HEAD request failed, maybe the server doesn't handle it well, or URL is bad.
                # We will try GET later if needed, but log this issue.
                print(f"Warning: HEAD request failed for {url}: {e}")
                pass # Continue to check extension/magic bytes if possible
    
    
        # 3. Check Magic Bytes if necessary
        #    - If extension check failed completely.
        #    - If extension was ambiguous (e.g. '.docx'/'xlsx' which are ZIPs).
        #    - If Content-Type check failed or gave no result.
        #    - If extension and Content-Type disagreed.
        needs_magic_bytes_check = (
            file_type_found is None or # No luck yet
            (file_extension in ['.docx', '.xlsx'] and not checked_content) or # Ambiguous ext
            (file_type_found and file_type_found != file_type_from_mime if 'file_type_from_mime' in locals() else False) # Disagreement
            )
    
        if needs_magic_bytes_check and not checked_content: # Only download if really needed
            try:
                headers = { # Re-set headers for GET request
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
                }
                response = requests.get(url, headers=headers, stream=True, timeout=10)
                response.raise_for_status()
    
                # Read only a small portion for magic bytes check
                first_bytes = response.raw.read(8) # Read first 8 bytes
    
                # Check if it's a ZIP-based format (DOCX, XLSX)
                if first_bytes.startswith(b'PK\x03\x04'):
                    # Need to check *inside* the zip for specific office structure
                    # This requires reading more data or using zipfile module.
                    # For simplicity here, we rely on the content-type if available,
                    # or tentatively classify as the most likely based on extension/context.
                    # A more robust check would involve unzipping headers.
                    # Let's check if we had a prior extension match.
                    if file_extension in SUPPORTED_TYPES['excel']['extensions']:
                        file_type_found = 'excel'
                    elif file_extension in SUPPORTED_TYPES['word']['extensions']:
                        file_type_found = 'word'
                    # If extension was missing/unhelpful, Content-Type check (if done) is primary.
                    # If neither extension nor Content-Type helped, this is ambiguous.
    
                else: # Check other magic bytes
                    for file_type, info in SUPPORTED_TYPES.items():
                        for magic in info['magic_bytes']:
                            if magic == b'PK\x03\x04': continue # Already handled above
                            if first_bytes.startswith(magic):
                                file_type_found = file_type
                                break # Found match
                        if file_type_found:
                            break # Found match
    
            except requests.exceptions.RequestException as e:
                 raise Exception(f"Error accessing URL content for magic bytes check: {str(e)}")
            # Ensure response is closed if using stream=True and not iterating fully
            finally:
                if 'response' in locals() and response:
                     response.close()
    
    
        # Final Decision
        if not file_type_found:
            # If we reached here without a match, try one last check on Content-Type if not done yet
            content_type = content_type if 'content_type' in locals() else '' # Get content_type if available
            for file_type, info in SUPPORTED_TYPES.items():
                if any(mime in content_type for mime in info['mime_types']):
                     file_type_found = file_type
                     break
    
        if not file_type_found:
             raise UnsupportedFileTypeError(
                f"Unsupported or unrecognized file type. URL: {url}, "
                f"Extension: '{file_extension or 'None'}', "
                f"Content-Type: '{content_type or 'None'}'"
            )
    
        return file_type_found
    
    # Example usage
    if __name__ == "__main__":
        test_urls = [
            "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf", # Valid PDF
            "https://file-examples.com/storage/fe27251a9162542407c029a/2017/10/file-example_xls_150KB.xls", # Valid XLS
            "https://file-examples.com/storage/fe27251a9162542407c029a/2017/02/doc.doc", # Valid DOC
            "https://file-examples.com/storage/fe27251a9162542407c029a/2017/04/file_example_PPTX_500kB.pptx", # Unsupported PPTX
            "https://example.com/image.jpg", # Unsupported JPG (no real URL)
            "https://docs.google.com/document/d/1li3J7ZJx2spu-Ua0qXmhkTaMV5Pe6R5D6UOjvlwlWXs", # Google Docs link
            "https://sheets.google.com/some/sheet/path", # Google Sheets link
            "https://www.google.com" # Plain HTML
        ]
    
        for url in test_urls:
            try:
                file_type = infer_file_type(url)
                print(f"URL: {url} -> Detected Type: {file_type}")
            except NotADirectFileLinkError as e:
                print(f"URL: {url} -> Error: {e}")
            except UnsupportedFileTypeError as e:
                print(f"URL: {url} -> Error: {e}")
            except Exception as e:
                print(f"URL: {url} -> Unexpected Error: {e}")
            print("-" * 60)
    
    

    Option 2: Try to Get the Actual File URL (More Complex)

    If you need to process the content of Google Docs links, you'd have to first construct the export URL. For a Google Doc, this typically looks like:

    https://docs.google.com/document/d/DOCUMENT_ID/export?format=docx

    or for Excel:

    https://docs.google.com/spreadsheets/d/SPREADSHEET_ID/export?format=xlsx

    You would need to:

    1. Detect the Google Docs/Sheets URL pattern.
    2. Extract the document ID.
    3. Construct the appropriate export URL (e.g., requesting docx format).
    4. Call the infer_file_type function (or a similar one) on that export URL.

    This adds significant complexity and requires handling authentication if the document isn't publicly shared. The code above implements Option 1, which is generally safer and more aligned with the original request of inferring type from direct file links.

  3. User

    also handle hosted microsoft word doc too

  4. Gemini Assistant

    Okay, let's refine the code to better handle hosted files, ensuring it relies on Content-Type headers and magic bytes when the URL extension might be missing or unreliable for determining the type of hosted Word documents (or Excel/PDF files).

    The core idea is to strengthen the checks using HTTP headers and file signatures, especially when the URL itself doesn't provide a clear extension like .docx or .doc.

    import requests
    import os
    from urllib.parse import urlparse
    import mimetypes # Useful for standard MIME type lookups, though we define our own list
    
    # --- Custom Exceptions ---
    class UnsupportedFileTypeError(Exception):
        """Custom exception for file types not supported by the function."""
        pass
    
    class NotADirectFileLinkError(Exception):
        """Custom exception for URLs that are not direct file downloads (e.g., web views)."""
        pass
    
    # --- Supported File Type Definitions ---
    
    # Mapping of file extensions to a general type category
    SUPPORTED_EXTENSIONS = {
        '.pdf': 'pdf',
        '.xls': 'excel', '.xlsx': 'excel', '.xlsm': 'excel', '.xlsb': 'excel',
        '.doc': 'word', '.docx': 'word', '.docm': 'word', '.dot': 'word', '.dotx': 'word', '.dotm': 'word'
    }
    
    # Mapping of common MIME types to type categories
    SUPPORTED_MIME_TYPES = {
        'pdf': ['application/pdf'],
        'excel': [
            'application/vnd.ms-excel',                                  # .xls
            'application/msexcel',                                       # Older alias for .xls
            'application/x-msexcel',                                     # Older alias for .xls
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', # .xlsx
            'application/vnd.ms-excel.sheet.macroEnabled.12',            # .xlsm
            'application/vnd.ms-excel.sheet.binary.macroEnabled.12',     # .xlsb
        ],
        'word': [
            'application/msword',                                        # .doc
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document', # .docx
            'application/vnd.ms-word.document.macroEnabled.12',          # .docm
            'application/vnd.openxmlformats-officedocument.wordprocessingml.template', # .dotx
            'application/vnd.ms-word.template.macroEnabled.12',          # .dotm
        ]
    }
    
    # Mapping of magic bytes (file signatures) to type categories
    # Note: PK\x03\x04 indicates a ZIP archive, which requires further inspection
    #       to differentiate between DOCX, XLSX, PPTX etc. We'll rely on other methods for these.
    MAGIC_BYTES_MAP = {
        b'\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1': 'ole', # OLE compound file (DOC, XLS, older PPT)
        b'PK\x03\x04': 'zip_archive',       # ZIP-based format (DOCX, XLSX, PPTX, etc.)
        b'%PDF': 'pdf',                     # PDF format
    }
    # Refine OLE detection: OLE files can be DOC or XLS. We'll refine this later if needed.
    
    # --- Helper Functions ---
    
    def _get_file_type_from_mime(content_type):
        """Checks if the provided MIME type matches any supported categories."""
        if not content_type:
            return None
        for type_name, mime_list in SUPPORTED_MIME_TYPES.items():
            # Check if any of the supported MIME types for this category are part of the content_type string
            if any(supported_mime in content_type for supported_mime in mime_list):
                # Special handling for ZIP archives if content type suggests it vaguely
                # e.g., 'application/zip' might be too generic
                if 'zip' in content_type and type_name not in ['word', 'excel']: # Avoid generic zip match if specific ones failed
                     return None # Let specific checks handle ZIP formats like DOCX/XLSX
                return type_name
        return None
    
    def _get_file_type_from_magic(first_bytes):
        """Checks if the initial bytes match known magic bytes signatures."""
        for magic, file_type in MAGIC_BYTES_MAP.items():
            if first_bytes.startswith(magic):
                if file_type == 'ole':
                    # OLE files can be DOC or XLS. We need more context.
                    # Let's tentatively call it 'ole' and rely on other checks.
                    return 'ole'
                elif file_type == 'zip_archive':
                    # ZIP archives need internal inspection. We'll treat this as a hint.
                    return 'zip_archive'
                else:
                    return file_type # PDF, etc.
        return None
    
    def infer_file_type(url):
        """
        Infers the file type from a URL, supporting direct links to PDF, Excel, and Word files.
    
        Handles cases where the URL might not have a standard file extension by relying
        on HTTP Content-Type headers and file magic bytes.
    
        Args:
            url (str): The URL pointing to the file.
    
        Returns:
            str: The inferred file type ('pdf', 'excel', or 'word').
    
        Raises:
            NotADirectFileLinkError: If the URL appears to be a web view/editor link (e.g., Google Docs).
            UnsupportedFileTypeError: If the file type cannot be determined or is not one of the supported types.
            requests.exceptions.RequestException: If there's an error accessing the URL.
        """
    
        # --- 1. Preliminary Check: Is it a known web app link? ---
        parsed_url = urlparse(url)
        # Add patterns for common services that host documents but aren't direct links
        if ("docs.google.com" in parsed_url.netloc and "/document/d/" in parsed_url.path) or \
           ("sheets.google.com" in parsed_url.netloc and ("/edit" in parsed_url.path or "/view" in parsed_url.path)) or \
           ("onedrive.live.com" in parsed_url.netloc and "/edit.aspx" in parsed_url.path):
            raise NotADirectFileLinkError(f"URL appears to be a web view/editor link, not a direct file download: {url}")
    
        filename = os.path.basename(parsed_url.path)
        file_extension = os.path.splitext(filename)[1].lower()
    
        # --- State Variables ---
        file_type_candidate = None
        content_type_header = None
        downloaded_bytes = None # Store downloaded bytes for magic check if needed
    
        # --- 2. Check URL Extension (Initial Guess) ---
        if file_extension in SUPPORTED_EXTENSIONS:
            file_type_candidate = SUPPORTED_EXTENSIONS[file_extension]
            # Note: .docx, .xlsx are ZIP based, extension alone might not be definitive.
    
        # --- 3. Check Content-Type Header (More Reliable for Hosted Files) ---
        try:
            headers = {
                # Use a common browser User-Agent to potentially avoid blocking
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
            }
            # Use HEAD request first for efficiency - it fetches headers only
            response = requests.head(url, headers=headers, allow_redirects=True, timeout=10)
            response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
            content_type_header = response.headers.get('content-type', '').lower()
    
            mime_based_type = _get_file_type_from_mime(content_type_header)
    
            if mime_based_type:
                # If extension was missing/ambiguous OR if mime type matches a specific type
                if not file_type_candidate or file_type_candidate == 'ole' or file_type_candidate == 'zip_archive':
                    file_type_candidate = mime_based_type
                # Handle potential mismatches (e.g., extension says DOC, header says PDF)
                elif file_type_candidate != mime_based_type:
                    print(f"Warning: Mismatch detected. URL extension suggests '{file_type_candidate}', "
                          f"but Content-Type is '{content_type_header}'. Prioritizing Content-Type.")
                    file_type_candidate = mime_based_type
    
        except requests.exceptions.RequestException as e:
            print(f"Warning: HEAD request failed for {url}: {e}. Proceeding with other checks if possible.")
            # Allow continuation, maybe GET will work or extension was enough.
    
        # --- 4. Check Magic Bytes (Fallback, requires downloading content) ---
        # We need to download if:
        #  a) We have no candidate yet (extension failed, HEAD failed/returned nothing useful).
        #  b) The candidate is 'ole' or 'zip_archive' and needs refinement, AND Content-Type didn't resolve it.
        needs_magic_check = False
        if not file_type_candidate:
            needs_magic_check = True
        elif file_type_candidate in ['ole', 'zip_archive']:
            # If it looked like OLE or ZIP and Content-Type didn't clarify, try magic bytes.
            if not content_type_header or not _get_file_type_from_mime(content_type_header):
                 needs_magic_check = True
            # If Content-Type DID clarify it (e.g., PDF), we don't need magic bytes.
    
        if needs_magic_check:
            try:
                headers = { # Re-set headers for GET request
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
                }
                # Use stream=True to download only necessary parts
                response = requests.get(url, headers=headers, stream=True, timeout=10)
                response.raise_for_status()
    
                # Read a small chunk sufficient for most magic bytes checks
                read_bytes = response.raw.read(8) # Read first 8 bytes
                downloaded_bytes = read_bytes # Store for potential further checks if needed
    
                magic_based_type = _get_file_type_from_magic(read_bytes)
    
                if magic_based_type:
                    if magic_based_type == 'ole':
                        # OLE can be DOC or XLS. Need to differentiate.
                        # A simple heuristic: check if Content-Type suggested excel or word earlier.
                        # Or, if Content-Type was generic or missing, maybe lean towards DOC as default OLE.
                        # This part is inherently ambiguous without deeper inspection.
                        # Let's refine based on previous checks if possible.
                        if file_type_candidate == 'excel': # If prior hint was excel
                             file_type_candidate = 'excel'
                        elif file_type_candidate == 'word': # If prior hint was word
                             file_type_candidate = 'word'
                        else:
                            # No prior hint, OLE detected. Could be DOC or XLS.
                            # Let's tentatively default to 'word' or raise ambiguity?
                            # For now, let's consider it potentially 'word' if no other info.
                            # A safer approach might be to require Content-Type for OLE.
                            # Let's refine: if content_type_header was received, use it.
                            # Otherwise, mark as ambiguous or default cautiously.
                            if content_type_header and _get_file_type_from_mime(content_type_header):
                                file_type_candidate = _get_file_type_from_mime(content_type_header)
                            else:
                                # Very ambiguous. Let's prefer 'word' as a common OLE type if forced.
                                # Or better, raise error if truly unclear.
                                print(f"Warning: Detected OLE file ({url}) but couldn't determine DOC/XLS from context.")
                                # file_type_candidate = 'word' # Tentative default
                                # Instead of defaulting, let it fall through and potentially fail validation.
    
                    elif magic_based_type == 'zip_archive':
                        # DOCX, XLSX etc. are ZIPs. Need to check inside or rely on headers/extension.
                        # If we already have a candidate (e.g., from extension '.docx'), keep it.
                        if not file_type_candidate:
                            print(f"Warning: Detected ZIP archive ({url}) but couldn't determine specific Office format.")
                            # Rely on Content-Type if available, otherwise it will fail.
                            if content_type_header and _get_file_type_from_mime(content_type_header):
                                 file_type_candidate = _get_file_type_from_mime(content_type_header)
    
                    else: # Directly identifiable type like PDF
                        file_type_candidate = magic_based_type
    
            except requests.exceptions.RequestException as e:
                raise Exception(f"Error during download for magic bytes check: {str(e)}")
            finally:
                if 'response' in locals() and response:
                    response.close() # Ensure the connection is closed
    
        # --- 5. Final Validation ---
        if not file_type_candidate:
            # If after all checks, we still haven't identified a type
            details = f"URL: {url}, Extension: '{file_extension or 'None'}'"
            if content_type_header:
                details += f", Content-Type: '{content_type_header}'"
            raise UnsupportedFileTypeError(f"Could not determine a supported file type. {details}")
    
        # Check if the final candidate is one of the specifically supported types
        if file_type_candidate not in ['pdf', 'excel', 'word']:
             details = f"URL: {url}, Detected Type: '{file_type_candidate}', Extension: '{file_extension or 'None'}'"
             if content_type_header:
                 details += f", Content-Type: '{content_type_header}'"
             raise UnsupportedFileTypeError(f"File type '{file_type_candidate}' is not supported. {details}")
    
        return file_type_candidate
    
    
    # --- Example Usage ---
    if __name__ == "__main__":
        # Example URLs for testing
        test_urls = [
            # Supported types with extensions
            ("https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf", "pdf"),
            ("https://file-examples.com/storage/fe27251a9162542407c029a/2017/10/file-example_xls_150KB.xls", "excel"),
            ("https://file-examples.com/storage/fe27251a9162542407c029a/2017/02/doc.doc", "word"),
            ("https://file-examples.com/storage/fe27251a9162542407c029a/2017/04/file_example_docx_2MB.docx", "word"),
            ("https://file-examples.com/storage/fe27251a9162542407c029a/2017/11/file_example_XLSX_10.xlsx", "excel"),
    
            # Unsupported types
            ("https://file-examples.com/storage/fe27251a9162542407c029a/2017/04/file_example_PPTX_500kB.pptx", "Unsupported"), # PPTX
            ("https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png", "Unsupported"), # Image
    
            # Non-direct file links (should raise NotADirectFileLinkError)
            ("https://docs.google.com/document/d/1li3J7ZJx2spu-Ua0qXmhkTaMV5Pe6R5D6UOjvlwlWXs", "NotADirectFileLink"),
            ("https://www.google.com", "NotADirectFileLink"), # Plain HTML
    
            # Hosted file, no extension, relies on Content-Type (hypothetical example)
            # To test this properly, you'd need a server or mock. Let's assume one exists:
            # ("http://example.com/download/mydoc_direct", "word"), # If Content-Type is wordprocessingml
            # ("http://example.com/download/mysheet_direct", "excel"), # If Content-Type is spreadsheetml
        ]
    
        print("--- Testing File Type Inference ---")
        for url, expected_outcome in test_urls:
            print(f"Processing URL: {url}")
            try:
                detected_type = infer_file_type(url)
                print(f"  -> SUCCESS: Detected type is '{detected_type}'")
                if expected_outcome != detected_type and expected_outcome not in ["Unsupported", "NotADirectFileLink"]:
                     print(f"  -> !!! TEST FAILED: Expected '{expected_outcome}', but got '{detected_type}'")
                elif expected_outcome in ["Unsupported", "NotADirectFileLink"]:
                     print(f"  -> !!! TEST FAILED: Expected error '{expected_outcome}', but got success ('{detected_type}')")
    
            except NotADirectFileLinkError as e:
                print(f"  -> Caught Expected Error: {e}")
                if expected_outcome != "NotADirectFileLink":
                    print(f"  -> !!! TEST FAILED: Caught unexpected error type. Expected '{expected_outcome}'.")
            except UnsupportedFileTypeError as e:
                print(f"  -> Caught Expected Error: {e}")
                if expected_outcome != "Unsupported":
                    print(f"  -> !!! TEST FAILED: Caught unexpected error type. Expected '{expected_outcome}'.")
            except requests.exceptions.RequestException as e:
                print(f"  -> Caught Request Error: {e}")
                # This might be expected for non-existent URLs in tests, or indicate a real network issue.
            except Exception as e:
                print(f"  -> Caught UNEXPECTED General Error: {e}")
            print("-" * 60)
    

    Key Improvements:

    1. Refined Logic Flow:
      • Starts by checking for known non-direct web app links (like Google Docs).
      • Uses URL extension as an initial guess.
      • Prioritizes Content-Type header: Makes a HEAD request. If a matching MIME type is found, it's heavily weighted, especially if the extension was missing or ambiguous (like .docx/.xlsx which are ZIP-based). It also warns about mismatches between extension and header.
      • Magic Bytes as Fallback: Downloads the beginning of the file only if necessary (e.g., no initial candidate, or ambiguous types like OLE/ZIP that need refinement). It handles OLE files (DOC/XLS) cautiously, preferring Content-Type if available.
    2. Better MIME Type Handling: Includes more variations of MIME types commonly used for Word and Excel files.
    3. Magic Byte Categories: Introduced 'ole' and 'zip_archive' categories for magic bytes to explicitly handle cases needing further context.
    4. User-Agent: Includes a standard browser User-Agent header in requests, which can help with servers that might otherwise block simple script requests.
    5. Error Handling & Warnings: Provides more specific warnings for mismatches and clearer error messages.
    6. Testing: The example usage block is enhanced to validate against expected outcomes (specific type or specific error).

    This version should be significantly more robust in identifying hosted Word documents (and other supported types) even when the URL doesn't explicitly contain the file extension.

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