|
| 1 | +from typing import Any, Generator |
| 2 | +import openpyxl |
| 3 | +import requests |
| 4 | +from io import BytesIO |
| 5 | +from urllib.parse import urlparse |
| 6 | + |
| 7 | +from dify_plugin import Tool |
| 8 | +from dify_plugin.entities.tool import ToolInvokeMessage |
| 9 | + |
| 10 | +def get_url_from_file_data(file_data: Any) -> str: |
| 11 | + """DifyのファイルデータからURLを抽出する""" |
| 12 | + if hasattr(file_data, 'url'): |
| 13 | + return file_data.url |
| 14 | + elif isinstance(file_data, dict) and 'url' in file_data: |
| 15 | + return file_data['url'] |
| 16 | + return '' |
| 17 | + |
| 18 | +class ExcelCellWriterTool(Tool): |
| 19 | + def _invoke(self, tool_parameters: dict[str, Any]) -> Generator[ToolInvokeMessage, None, None]: |
| 20 | + try: |
| 21 | + # Excelファイルの取得 |
| 22 | + excel_file = tool_parameters.get("excel_file") |
| 23 | + if not excel_file: |
| 24 | + yield ToolInvokeMessage( |
| 25 | + type="text", |
| 26 | + message={"text": "Excelファイルが提供されていません。"} |
| 27 | + ) |
| 28 | + return |
| 29 | + |
| 30 | + # 編集データの取得 |
| 31 | + updates = tool_parameters.get("updates", {}) |
| 32 | + if not updates: |
| 33 | + yield ToolInvokeMessage( |
| 34 | + type="text", |
| 35 | + message={"text": "更新データが提供されていません。"} |
| 36 | + ) |
| 37 | + return |
| 38 | + |
| 39 | + # ファイルのURLを取得 |
| 40 | + file_url = get_url_from_file_data(excel_file) |
| 41 | + |
| 42 | + if not file_url: |
| 43 | + yield ToolInvokeMessage( |
| 44 | + type="text", |
| 45 | + message={"text": "ファイルのURLが見つかりません。"} |
| 46 | + ) |
| 47 | + return |
| 48 | + |
| 49 | + # ファイルをダウンロード |
| 50 | + try: |
| 51 | + response = requests.get(file_url) |
| 52 | + response.raise_for_status() |
| 53 | + file_bytes = response.content |
| 54 | + |
| 55 | + except Exception as e: |
| 56 | + yield ToolInvokeMessage( |
| 57 | + type="text", |
| 58 | + message={"text": f"ファイルのダウンロードに失敗しました: {str(e)}"} |
| 59 | + ) |
| 60 | + return |
| 61 | + |
| 62 | + # Excelファイルの読み込み |
| 63 | + try: |
| 64 | + wb = openpyxl.load_workbook(BytesIO(file_bytes)) |
| 65 | + ws = wb.active |
| 66 | + except Exception as e: |
| 67 | + yield ToolInvokeMessage( |
| 68 | + type="text", |
| 69 | + message={"text": f"Excelファイル読み込みエラー: {str(e)}"} |
| 70 | + ) |
| 71 | + return |
| 72 | + |
| 73 | + # セル内容の更新 |
| 74 | + try: |
| 75 | + # updatesが文字列の場合、JSONとしてパース |
| 76 | + if isinstance(updates, str): |
| 77 | + import json |
| 78 | + try: |
| 79 | + # シングルクォートをダブルクォートに置換 |
| 80 | + updates = updates.replace("'", '"') |
| 81 | + # datetimeオブジェクトを文字列に変換 |
| 82 | + updates = updates.replace( |
| 83 | + "datetime.datetime(", '"datetime(' |
| 84 | + ).replace(")", ')"') |
| 85 | + updates = json.loads(updates) |
| 86 | + except json.JSONDecodeError as e: |
| 87 | + yield ToolInvokeMessage( |
| 88 | + type="text", |
| 89 | + message={"text": f"JSONパースエラー: {str(e)}\n入力データ: {updates}"} |
| 90 | + ) |
| 91 | + return |
| 92 | + |
| 93 | + # updatesが辞書型か確認 |
| 94 | + if not isinstance(updates, dict): |
| 95 | + yield ToolInvokeMessage( |
| 96 | + type="text", |
| 97 | + message={"text": f"無効なupdates形式です。辞書型またはJSON文字列を指定してください\n入力データ: {updates}"} |
| 98 | + ) |
| 99 | + return |
| 100 | + |
| 101 | + # セル更新処理 |
| 102 | + for cell_ref, new_value in updates.items(): |
| 103 | + ws[cell_ref] = new_value |
| 104 | + |
| 105 | + except json.JSONDecodeError: |
| 106 | + yield ToolInvokeMessage( |
| 107 | + type="text", |
| 108 | + message={"text": "JSONパースエラー: updatesが有効なJSON形式ではありません"} |
| 109 | + ) |
| 110 | + return |
| 111 | + except Exception as e: |
| 112 | + yield ToolInvokeMessage( |
| 113 | + type="text", |
| 114 | + message={"text": f"セル更新エラー: {str(e)}"} |
| 115 | + ) |
| 116 | + return |
| 117 | + |
| 118 | + # 編集結果を保存 |
| 119 | + try: |
| 120 | + output = BytesIO() |
| 121 | + wb.save(output) |
| 122 | + output.seek(0) |
| 123 | + |
| 124 | + yield self.create_blob_message( |
| 125 | + blob=output.getvalue(), |
| 126 | + meta={ |
| 127 | + "mime_type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", |
| 128 | + "filename": "edited_file.xlsx" |
| 129 | + } |
| 130 | + ) |
| 131 | + except Exception as e: |
| 132 | + yield ToolInvokeMessage( |
| 133 | + type="text", |
| 134 | + message={"text": f"ファイル保存エラー: {str(e)}"} |
| 135 | + ) |
| 136 | + return |
| 137 | + |
| 138 | + except Exception as e: |
| 139 | + yield ToolInvokeMessage( |
| 140 | + type="text", |
| 141 | + message={"text": f"エラーが発生しました: {str(e)}"} |
| 142 | + ) |
0 commit comments