""" Utility module for generating file viewer HTML content. """ import base64 import mimetypes import os def generate_file_viewer_html(file_path: str) -> str: """ Generate HTML content for viewing different file types. Args: file_path: The absolute path to the file Returns: str: HTML content for viewing the file Raises: ValueError: If the file extension is not supported """ file_extension = os.path.splitext(file_path)[1].lower() file_name = os.path.basename(file_path) # Define supported file extensions supported_extensions = [ '.pdf', '.png', '.jpg', '.jpeg', '.gif', ] # Check if the file extension is supported if file_extension not in supported_extensions: raise ValueError( f'Unsupported file extension: {file_extension}. ' f'Supported extensions are: {", ".join(supported_extensions)}' ) # Check if the file exists if not os.path.exists(file_path): raise ValueError( f'File not found locally: {file_path}. Please download the file to the local machine and try again.' ) # Read file content directly file_content = None mime_type = mimetypes.guess_type(file_path)[0] or 'application/octet-stream' # For binary files (images, PDFs), encode as base64 if file_extension in ['.pdf', '.png', '.jpg', '.jpeg', '.gif', '.bmp']: with open(file_path, 'rb') as file: file_content = base64.b64encode(file.read()).decode('utf-8') # For text files, read as text else: with open(file_path, 'r', encoding='utf-8') as file: file_content = file.read() return f"""