File size: 2,239 Bytes
9073c71
03dd32d
1786917
 
03dd32d
 
9073c71
1786917
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
056e59a
03dd32d
1786917
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
from smolagents.tools import Tool
import pandas as pd
from tabulate import tabulate
from typing import Union, Optional
from huggingface_hub import hf_hub_download

class ExcelAnalysisTool(Tool):
    """Render an Excel worksheet as Markdown text."""

    name = "excel_to_text"
    description = (
        "Read an Excel file and return a Markdown table of the requested sheet. "
        "Accepts either the sheet name or the zero-based index."
    )

    inputs = {
        "excel_path": {
            "type": "string",
            "description": "Path to the Excel file (.xlsx / .xls).",
        },
        "sheet_name": {
            "type": "string",
            "description": (
                "Worksheet name or zero‑based index *as a string* (optional; default first sheet)."
            ),
            "nullable": True,
        },
    }

    output_type = "string"

    def forward(
            self,
            excel_path: str,
            sheet_name: Optional[str] = None,
    ) -> str:
        """Load *excel_path* and return the sheet as a Markdown table."""

        path = pathlib.Path(excel_path).expanduser().resolve()
        if not path.exists():
            return f"Error: Excel file not found at {path}"

        try:
            # Interpret sheet identifier -----------------------------------
            sheet: Union[str, int]
            if sheet_name is None or sheet_name == "":
                sheet = 0  # first sheet
            else:
                # If the user passed a numeric string (e.g. "1"), cast to int
                sheet = int(sheet_name) if sheet_name.isdigit() else sheet_name

            # Load worksheet ----------------------------------------------
            df = pd.read_excel(path, sheet_name=sheet)

            # Render to Markdown; fall back to tabulate if needed ---------
            if hasattr(pd.DataFrame, "to_markdown"):
                return df.to_markdown(index=False)
            from tabulate import tabulate  # pragma: no cover – fallback path

            return tabulate(df, headers="keys", tablefmt="github", showindex=False)

        except Exception as exc:  # broad catch keeps the agent chat‑friendly
            return f"Error reading Excel file: {exc}"