import gradio as gr
import subprocess
import os
from datetime import datetime
import random
import string
import shlex
def generate_random_suffix(length=8):
# 生成指定長度的隨機字母或數字組合
characters = string.ascii_letters + string.digits
return ''.join(random.choice(characters) for _ in range(length))
def convert_markdown_to_ppt(markdown_file, markdown_text, input_type, template_file=None):
# 根據輸入類型處理 Markdown 檔案或字串
if input_type == "Upload Markdown File":
input_path = markdown_file.name
else: # "Enter Markdown Text"
# 將字串內容寫入暫存檔案
timestamp = datetime.now().strftime("%Y_%m_%d_%H_%M_%S")
random_suffix = generate_random_suffix()
input_path = f"/tmp/file-{timestamp}-{random_suffix}.md"
with open(input_path, "w") as file:
file.write(markdown_text)
# 定義輸出 PPTX 路徑
# output_pptx_path = "/tmp/" + os.path.split(input_path)[1].replace(".md", ".pptx")
output_pptx_path = os.path.splitext(input_path)[0] + ".pptx"
# 將 Markdown 轉換為 PPTX
command_pptx = f"pandoc {shlex.quote(input_path)} -o {shlex.quote(output_pptx_path)}"
if template_file is not None:
template_path = template_file.name
command_pptx += f" --reference-doc='{template_path}'"
else:
# 使用預設樣式轉換
command_pptx += " --reference-doc=template.pptx"
try:
# result = subprocess.run(command_pptx, shell=True, check=True)
result = subprocess.run(command_pptx, shell=True, check=True, capture_output=True, text=True)
# print(result.stdout + result.stderr)
return output_pptx_path, result.stdout if result.stdout else "" + result.stderr if result.stderr else ""
except subprocess.CalledProcessError as e:
return None, f"Error: Conversion to PPTX failed. Details: {e}"
except Exception as e:
return None, f"Unexpected error occurred during PPTX conversion: {e}"
def update_visibility(input_type):
# 根據選擇顯示/隱藏相應的輸入框
if input_type == "Upload Markdown File":
return gr.update(visible=True), gr.update(visible=False)
else:
return gr.update(visible=False), gr.update(visible=True)
# 設定範例檔案的路徑
examples = [
["example.md", None], # 僅上傳 Markdown 檔案
["example.md", "template.pptx"] # 同時上傳 Markdown 檔案和模板
]
# 設定 Gradio 介面
with gr.Blocks() as iface:
gr.Markdown("""
# Markdown to PPT Converter
上傳一個 Markdown 檔案,並選擇性地上傳 PPT 模板,將其轉換為 PPT 格式並下載。
Upload a Markdown file, and optionally upload a PPT template to convert it into PPT format and download.
## 使用步驟
1. **選擇輸入方式**:可以選擇「上傳 Markdown 檔案」或「輸入 Markdown 字串」。
2. **上傳或輸入 Markdown 檔案**:根據選擇進行上傳或輸入。
3. **選擇性上傳 PPT 模板**:如需指定模板,可點擊「PPT Template (Optional)」欄位上傳 PPT 模板檔案。否則將使用預設樣式轉換。
a. **模板格式要求**:PPT 模板檔案需為 PPTX 格式的檔案。
b. **模板名稱要求**:模板中的樣式名稱需符合 Pandoc 的樣式名稱,如「Title Slide」、「Section Header」、「Title and Content」、「Two Content」、「Comparison」、「Content with Caption」、「Blank」。
c. **模板範例參考**: [PPT 模板範例](https://huggingface.co/spaces/u5ername/markdown2ppt-docker/blob/main/template.pptx) (可以在範例的 PPT 中查看模板的命名方式)
4. **點擊提交**:點擊「Submit」按鈕進行轉換。
5. **下載轉換結果**:轉換完成後,下載生成的 PPT 文件。
## Steps
1. **Choose Input Type**: You can select either "Upload Markdown File" or "Enter Markdown Text".
2. **Upload or Enter Markdown File**: Proceed with upload or text input based on your choice.
3. **Optionally upload a PPT template**: If you want to use a specific template, click on the "PPT Template (Optional)" field to upload a PPT template file. Otherwise, the default style will be used.
a. **Template Format Requirements**: The PPT template file must be in PPTX format.
b. **Template Naming Requirements**: The style names in the template must conform to Pandoc's style naming conventions, such as "Title Slide", "Section Header", "Title and Content", "Two Content", "Comparison", "Content with Caption", "Blank".
c. **Template Example Reference**: [PPT Template Example](https://huggingface.co/spaces/u5ername/markdown2ppt-docker/blob/main/template.pptx) (You can check the naming conventions in the example PPT)
4. **Click Submit**: Press the "Submit" button to start the conversion.
5. **Download the result**: Once the conversion is complete, download the generated PPT file.
""")
input_type = gr.Radio(["Upload Markdown File", "Enter Markdown Text"], label="Input Type", value="Upload Markdown File")
markdown_file = gr.File(label="Markdown File", visible=True)
markdown_text = gr.Textbox(lines=10, placeholder="Enter Markdown content here...", visible=False)
template_file = gr.File(label="PPT Template (Optional)")
input_type.change(
update_visibility,
inputs=input_type,
outputs=[markdown_file, markdown_text]
)
submit_button = gr.Button("Submit")
output_pptx = gr.File(label="Download PPTX")
error_message = gr.Textbox(lines=2, label="Error Message")
submit_button.click(
convert_markdown_to_ppt,
inputs=[markdown_file, markdown_text, input_type, template_file],
outputs=[output_pptx, error_message]
)
gr.Examples(
examples=examples,
inputs=[markdown_file, template_file]
)
gr.Markdown("""
## 更多資訊 | More Information
,
""")
iface.launch(allowed_paths=["/tmp"])