11import logging
2- from typing import Generator
2+ import os
3+ from pathlib import Path
4+ from tempfile import NamedTemporaryFile
5+ from typing import Generator , Optional
36
47from dify_plugin import Tool
58from dify_plugin .entities .tool import ToolInvokeMessage
9+ from dify_plugin .file .file import File
610
711from tools .utils .file_utils import get_meta_data
812from tools .utils .mimetype_utils import MimeType
@@ -19,8 +23,30 @@ def _invoke(self, tool_parameters: dict) -> Generator[ToolInvokeMessage, None, N
1923 """
2024 # get parameters
2125 md_text = get_md_text (tool_parameters , is_strip_wrapper = True )
26+ docx_template_file : Optional [File ] = tool_parameters .get ("docx_template_file" )
27+ temp_pptx_template_file_path : Optional [str ] = None
28+ if docx_template_file and not isinstance (docx_template_file , File ):
29+ raise ValueError ("Not a valid file for pptx template file" )
30+
2231 try :
23- result_file_bytes = pandoc_convert_file (md_text , "docx" )
32+ if docx_template_file :
33+ temp_pptx_template_file = NamedTemporaryFile (delete = False )
34+ temp_pptx_template_file .write (docx_template_file .blob )
35+ temp_pptx_template_file .close ()
36+ temp_pptx_template_file_path = temp_pptx_template_file .name
37+
38+ current_script_folder = os .path .split (os .path .realpath (__file__ ))[0 ]
39+ if temp_pptx_template_file_path :
40+ template_docx_file = temp_pptx_template_file_path
41+ else :
42+ template_docx_file = f"{ current_script_folder } /template/docx_template.docx"
43+
44+ # Options for pandoc
45+ # https://pandoc.org/MANUAL.html#options
46+ extra_args = [
47+ "--reference-doc" , template_docx_file ,
48+ ]
49+ result_file_bytes = pandoc_convert_file (md_text , dst_format = "docx" , extra_args = extra_args )
2450 yield self .create_blob_message (
2551 blob = result_file_bytes ,
2652 meta = get_meta_data (
@@ -32,3 +58,6 @@ def _invoke(self, tool_parameters: dict) -> Generator[ToolInvokeMessage, None, N
3258 self .logger .exception ("Failed to convert markdown text to DOCX file" )
3359 yield self .create_text_message (f"Failed to convert markdown text to DOCX file, error: { str (e )} " )
3460 raise e
61+ finally :
62+ if temp_pptx_template_file_path :
63+ Path (temp_pptx_template_file_path ).unlink ()
0 commit comments