|
| 1 | +import sys |
| 2 | +import csv |
| 3 | +import io |
| 4 | +from typing import BinaryIO, Any |
| 5 | +from charset_normalizer import from_bytes |
| 6 | +from ._html_converter import HtmlConverter |
| 7 | +from .._base_converter import DocumentConverter, DocumentConverterResult |
| 8 | +from .._stream_info import StreamInfo |
| 9 | + |
| 10 | +ACCEPTED_MIME_TYPE_PREFIXES = [ |
| 11 | + "text/csv", |
| 12 | + "application/csv", |
| 13 | +] |
| 14 | +ACCEPTED_FILE_EXTENSIONS = [".csv"] |
| 15 | + |
| 16 | + |
| 17 | +class CsvConverter(DocumentConverter): |
| 18 | + """ |
| 19 | + Converts CSV files to Markdown tables. |
| 20 | + """ |
| 21 | + |
| 22 | + def __init__(self): |
| 23 | + super().__init__() |
| 24 | + |
| 25 | + def accepts( |
| 26 | + self, |
| 27 | + file_stream: BinaryIO, |
| 28 | + stream_info: StreamInfo, |
| 29 | + **kwargs: Any, # Options to pass to the converter |
| 30 | + ) -> bool: |
| 31 | + mimetype = (stream_info.mimetype or "").lower() |
| 32 | + extension = (stream_info.extension or "").lower() |
| 33 | + if extension in ACCEPTED_FILE_EXTENSIONS: |
| 34 | + return True |
| 35 | + for prefix in ACCEPTED_MIME_TYPE_PREFIXES: |
| 36 | + if mimetype.startswith(prefix): |
| 37 | + return True |
| 38 | + return False |
| 39 | + |
| 40 | + def convert( |
| 41 | + self, |
| 42 | + file_stream: BinaryIO, |
| 43 | + stream_info: StreamInfo, |
| 44 | + **kwargs: Any, # Options to pass to the converter |
| 45 | + ) -> DocumentConverterResult: |
| 46 | + # Read the file content |
| 47 | + if stream_info.charset: |
| 48 | + content = file_stream.read().decode(stream_info.charset) |
| 49 | + else: |
| 50 | + content = str(from_bytes(file_stream.read()).best()) |
| 51 | + |
| 52 | + # Parse CSV content |
| 53 | + reader = csv.reader(io.StringIO(content)) |
| 54 | + rows = list(reader) |
| 55 | + |
| 56 | + if not rows: |
| 57 | + return DocumentConverterResult(markdown="") |
| 58 | + |
| 59 | + # Create markdown table |
| 60 | + markdown_table = [] |
| 61 | + |
| 62 | + # Add header row |
| 63 | + markdown_table.append("| " + " | ".join(rows[0]) + " |") |
| 64 | + |
| 65 | + # Add separator row |
| 66 | + markdown_table.append("| " + " | ".join(["---"] * len(rows[0])) + " |") |
| 67 | + |
| 68 | + # Add data rows |
| 69 | + for row in rows[1:]: |
| 70 | + # Make sure row has the same number of columns as header |
| 71 | + while len(row) < len(rows[0]): |
| 72 | + row.append("") |
| 73 | + # Truncate if row has more columns than header |
| 74 | + row = row[: len(rows[0])] |
| 75 | + markdown_table.append("| " + " | ".join(row) + " |") |
| 76 | + |
| 77 | + result = "\n".join(markdown_table) |
| 78 | + |
| 79 | + return DocumentConverterResult(markdown=result) |
0 commit comments