# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 import csv import os from datetime import datetime from typing import Any, Optional, cast from robolab.core.utils.file_utils import convert_file_path, get_relative_path def csv_to_markdown_table( csv_input: str | list[list[str]] | list[dict[str, Any]], headers: Optional[list[str]] = None, align: str = "left" ) -> str: """ Convert CSV data to a markdown table format. Args: csv_input: Can be one of: - Path to a CSV file (str) - list of lists representing CSV rows - list of dictionaries (keys become headers) headers: Optional list of column headers. If None and csv_input is a file, headers are taken from the first row. align: Table alignment ('left', 'center', 'right'). Default is 'left'. Returns: str: Markdown formatted table Examples: # From file path markdown = csv_to_markdown_table("data.csv") # From list of lists data = [["Name", "Age"], ["Alice", "25"], ["Bob", "30"]] markdown = csv_to_markdown_table(data) # From list of dictionaries data = [{"Name": "Alice", "Age": "25"}, {"Name": "Bob", "Age": "30"}] markdown = csv_to_markdown_table(data) """ # Handle different input types if isinstance(csv_input, str): # Input is a file path if not os.path.exists(csv_input): raise FileNotFoundError(f"CSV file not found: {csv_input}") with open(csv_input, 'r', newline='', encoding='utf-8') as f: reader = csv.reader(f) rows = list(reader) if not rows: return "" if headers is None: headers = rows[0] data_rows = rows[1:] else: data_rows = rows elif isinstance(csv_input, list) and csv_input and isinstance(csv_input[0], dict): # Input is list of dictionaries dict_data = csv_input # type: ignore if headers is None: headers = list(dict_data[0].keys()) # type: ignore data_rows = [[str(row.get(header, "")) for header in headers] for row in dict_data] # type: ignore elif isinstance(csv_input, list): # Input is list of lists if not csv_input: return "" list_data = csv_input # type: ignore if headers is None: headers = list_data[0] # type: ignore data_rows = list_data[1:] # type: ignore else: data_rows = list_data # type: ignore else: raise ValueError("csv_input must be a file path, list of lists, or list of dictionaries") if not headers: return "" # Create alignment string align_chars = { "left": ":--", "center": ":-:", "right": "--:" } alignment = align_chars.get(align, ":--") # Build markdown table markdown_lines = [] # Header row header_row = "| " + " | ".join(str(header) for header in headers) + " |" markdown_lines.append(header_row) # Separator row separator_row = "| " + " | ".join(alignment for _ in headers) + " |" markdown_lines.append(separator_row) # Data rows for row in data_rows: # Ensure row has same length as headers padded_row = [str(cell) if i < len(row) else "" for i, cell in enumerate(row)] + [""] * (len(headers) - len(row)) padded_row = padded_row[:len(headers)] # Trim if too long data_row = "| " + " | ".join(padded_row) + " |" markdown_lines.append(data_row) return "\n".join(markdown_lines) def get_markdown_image_text( filename_to_img: str, relative_dir: str, image_dir: str, image_ext: str='.png', size: Optional[tuple[int, int]] = None, subtitle: Optional[str] = None ) -> str: """Helper function to find filename_to_img in image_dir and return a markdown image text, relative to relative_dir. Assumes that the image filename is the same as the filename_to_img, but with the extension replaced with image_ext. Args: filename_to_img: The filename to find in image_dir relative_dir: The directory to use as the base for the relative path image_dir: The directory to search for the image image_ext: The extension of the image file size: Optional tuple of (width, height) in pixels for custom image sizing subtitle: Optional subtitle text to display below the image (forces HTML img tag) Returns: str: Markdown image text or HTML img tag if size or subtitle is specified """ # Get extension of current filename ext = os.path.splitext(filename_to_img)[1] image_filename = filename_to_img.replace(ext, image_ext) image_path = os.path.join(image_dir, image_filename) if not os.path.exists(image_path): return "No image" # Calculate relative path from output directory to image relative_image_path = get_relative_path(image_path, relative_dir) # Normalize path separators for markdown (use forward slashes) relative_image_path = relative_image_path.replace(os.sep, '/') # Use HTML if subtitle or size is provided, otherwise use markdown use_html = subtitle is not None or size is not None if use_html: # Build HTML img tag if size is not None: width, height = size image_ref = f'{image_filename}' else: image_ref = f'{image_filename}' # Add subtitle if provided if subtitle is not None: return f"{image_ref}
{subtitle}" return image_ref else: # Use markdown syntax return f"![{image_filename}]({relative_image_path})" def add_images_to_csv( csv_file_path: str, image_dir: str, column_name_to_img: str = "scene", image_column_name: str = "Preview", relative_dir: str = None, size: Optional[tuple[int, int]] = None, replace_column: bool = False ) -> list[list[str]]: """ Load a CSV file and append image references for corresponding PNG files. Args: csv_file_path: Path to the CSV file to load image_dir: Directory where PNG images are stored column_name_to_img: Name of the column containing USD filenames image_column_name: Name to give the new image column (ignored if replace_column=True) relative_dir: Directory to use as base for relative paths size: Optional tuple of (width, height) in pixels for custom image sizing replace_column: If True, replace the content of column_name_to_img with the image and original text as subtitle. If False, add a new column. Returns: list of rows with image column added or replaced (including header row) """ if relative_dir is None: relative_dir = os.path.dirname(os.path.abspath(csv_file_path)) # Load CSV file if not os.path.exists(csv_file_path): raise FileNotFoundError(f"CSV file not found: {csv_file_path}") with open(csv_file_path, 'r', newline='', encoding='utf-8') as f: reader = csv.reader(f) rows = list(reader) if not rows: return [] headers = rows[0] data_rows = rows[1:] try: scene_col_idx = headers.index(column_name_to_img) except ValueError: # Scene column not found, return original data return rows if replace_column: # Replace the existing column with image + subtitle new_headers = headers new_data_rows = [] for row in data_rows: # Pad row to match header length padded_row = [str(cell) if i < len(row) else "" for i, cell in enumerate(row)] + [""] * (len(headers) - len(row)) padded_row = padded_row[:len(headers)] scene_filename = padded_row[scene_col_idx] # Use get_markdown_image_text with subtitle parameter image_ref = get_markdown_image_text( scene_filename, relative_dir, image_dir, image_ext='.png', size=size, subtitle=scene_filename ) # Replace column content with image and subtitle new_row = padded_row.copy() new_row[scene_col_idx] = image_ref new_data_rows.append(new_row) else: # Add image column to headers new_headers = headers + [image_column_name] new_data_rows = [] for row in data_rows: # Pad row to match header length padded_row = [str(cell) if i < len(row) else "" for i, cell in enumerate(row)] + [""] * (len(headers) - len(row)) padded_row = padded_row[:len(headers)] scene_filename = padded_row[scene_col_idx] image_ref = get_markdown_image_text(scene_filename, relative_dir, image_dir, image_ext='.png', size=size) new_row = padded_row + [image_ref] new_data_rows.append(new_row) return [new_headers] + new_data_rows def save_markdown_table( csv_input: str | list[list[str]] | list[dict[str, Any]], output_path: str, title: str = "", description: str = "", headers: Optional[list[str]] = None, align: str = "left", path_type: str = "absolute" # One of "absolute", "relative", or "filename_only" ) -> None: """ Convert CSV data to markdown table and save to file. Args: csv_input: CSV data (same as csv_to_markdown_table) output_path: Path where to save the markdown file title: Optional title for the markdown document description: Optional description for the markdown document headers: Optional list of column headers align: Table alignment ('left', 'center', 'right') path_type: How to handle file paths - "absolute" (default), "relative", or "filename_only" """ def check_cell_is_html(cell: str) -> bool: return ' str: """ Convert CSV string content to markdown table. Args: csv_string: CSV content as string align: Table alignment ('left', 'center', 'right') Returns: str: Markdown formatted table """ # Parse CSV string lines = csv_string.strip().split('\n') reader = csv.reader(lines) rows = list(reader) return csv_to_markdown_table(rows, align=align)