はい、PowerPointプレゼンテーションをLLMに適したMarkdown形式に変換する関数の続きを作成します。
考慮事項に基づいて、以下の点を実装します。
- スライドのタイトル: 各スライドのタイトルをMarkdownの見出し(
###)として抽出します。
- テキストコンテンツ:
- テキストボックスやプレースホルダー内のテキストを抽出します。
- 箇条書きや段落のインデントを考慮し、Markdownのリスト形式(
-)に変換します。
- テーブル: PowerPointのテーブルをMarkdownのテーブル形式に変換します。
- 画像とチャート:
- 画像が存在する場合は
[Image Placeholder]と出力します。
- チャートが存在する場合は
[Chart Placeholder]と出力します。
- (LLMに渡すため、実際の画像を埋め込んだり、外部ファイルに保存したりはしません)
- その他のシェイプ: テキスト、テーブル、画像、チャート以外のシェイプ(例:線、図形など)は通常LLMにとっての重要な情報ではないため、無視します。
必要なライブラリ: python-pptxとpathlib。
from pathlib import Path
from pptx import Presentation
from pptx.enum.shapes import MsoShapeType
from io import StringIO
def pptx_to_markdown(file_path: Path) -> str:
"""
PowerPoint (.pptx) ファイルをMarkdown形式の文字列に変換します。
LLMへの入力に適した形式で、テキスト、テーブル、画像/チャートの
プレースホルダー情報を含みます。
Args:
file_path (Path): 変換するPowerPointファイルのパス。
Returns:
str: 変換されたMarkdown形式の文字列。
"""
presentation = Presentation(file_path)
md_output = StringIO()
md_output.write(f"# Presentation: {file_path.stem}\n\n")
for slide_num, slide in enumerate(presentation.slides, start=1):
md_output.write(f"## Slide {slide_num}\n")
# スライドのタイトルを抽出(もしあれば)
# レイアウトによってタイトルがshapes.titleにあるとは限らないため、
# text_frameを持つシェイプの中からタイトルとして認識できるものを探す
# ここではshapes.titleがあればそれを優先
if slide.shapes.title:
md_output.write(f"### {slide.shapes.title.text}\n")
else:
# タイトルプレースホルダーがない場合、最初のテキストシェイプをタイトルとみなす場合もある
# ここではシンプルにshapes.titleのみをチェック
pass
md_output.write("\n") # スペーシング
# 各スライド内のシェイプを処理
for shape in slide.shapes:
# テキストフレームを持つシェイプ(テキストボックス、プレースホルダーなど)
if shape.has_text_frame:
# スライドタイトルは既に処理済みなのでスキップ
if shape == slide.shapes.title:
continue
for paragraph in shape.text_frame.paragraphs:
text = paragraph.text.strip()
if not text:
continue # 空の段落はスキップ
# インデントレベルに基づいて箇条書きまたは通常のテキストとして出力
# 箇条書きと見なせる場合は'- 'を付ける
indent = " " * paragraph.level
if paragraph.level > 0:
md_output.write(f"{indent}- {text}\n")
else:
md_output.write(f"{indent}{text}\n\n") # 通常の段落は改行を2つ
# テーブル
elif shape.has_table:
md_output.write("### Table:\n")
table = shape.table
# ヘッダー行
header_row = [table.cell(0, col).text.strip() for col in range(len(table.columns))]
md_output.write("| " + " | ".join(header_row) + " |\n")
# セパレーター行
md_output.write("|" + "---|".join(["-" * (len(h) + 2) for h in header_row]) + "|\n") # 各ヘッダーの長さに合わせたハイフン
# データ行
for row_idx in range(1, len(table.rows)):
data_row = [table.cell(row_idx, col).text.strip() for col in range(len(table.columns))]
md_output.write("| " + " | ".join(data_row) + " |\n")
md_output.write("\n") # テーブルの後に空行
# 画像
elif shape.shape_type == MsoShapeType.PICTURE:
md_output.write("[Image Placeholder]\n\n")
# チャート
elif shape.has_chart:
md_output.write("[Chart Placeholder]\n\n")
# その他のシェイプは無視(LLMにとっての情報価値が低いと判断)
# 例: MsoShapeType.AUTO_SHAPE (四角、丸など), MsoShapeType.LINE など
return md_output.getvalue()
# --- 使用例 ---
if __name__ == "__main__":
# テスト用のダミーPPTXファイルを作成する(実運用では既存ファイルを使用)
from pptx.util import Inches
from pptx.enum.shapes import MsoAutoShapeType # for creating simple shapes
# ダミーのPPTXファイルを作成する関数
def create_dummy_pptx(file_name="example_presentation.pptx"):
prs = Presentation()
# Slide 1: Title and Text
slide1_layout = prs.slide_layouts[0] # Title Slide layout
slide1 = prs.slides.add_slide(slide1_layout)
title1 = slide1.shapes.title
title1.text = "Introduction to My Project"
body1 = slide1.placeholders[1] # Body placeholder
tf1 = body1.text_frame
p1 = tf1.add_paragraph()
p1.text = "This presentation outlines the key aspects of my new project."
p1.level = 0
p2 = tf1.add_paragraph()
p2.text = "Key Objectives:"
p2.level = 0
p3 = tf1.add_paragraph()
p3.text = "Objective 1: Research Phase"
p3.level = 1
p4 = tf1.add_paragraph()
p4.text = "Objective 2: Development Phase"
p4.level = 1
p5 = tf1.add_paragraph()
p5.text = "Sub-objective A"
p5.level = 2
# Slide 2: Table
slide2_layout = prs.slide_layouts[5] # Blank layout
slide2 = prs.slides.add_slide(slide2_layout)
slide2.shapes.title.text = "Project Milestones" # Manually setting title for blank layout
# Add a table
rows, cols = 3, 3
left = top = Inches(1)
width = Inches(6)
height = Inches(2)
table_shape = slide2.shapes.add_table(rows, cols, left, top, width, height)
table = table_shape.table
# Set column widths (optional, but good practice)
table.columns[0].width = Inches(2.0)
table.columns[1].width = Inches(2.0)
table.columns[2].width = Inches(2.0)
# Populate table cells
table.cell(0, 0).text = "Phase"
table.cell(0, 1).text = "Start Date"
table.cell(0, 2).text = "End Date"
table.cell(1, 0).text = "Planning"
table.cell(1, 1).text = "2023-01-01"
table.cell(1, 2).text = "2023-01-31"
table.cell(2, 0).text = "Execution"
table.cell(2, 1).text = "2023-02-01"
table.cell(2, 2).text = "2023-03-31"
# Slide 3: Image and Chart placeholder
slide3_layout = prs.slide_layouts[5] # Blank layout
slide3 = prs.slides.add_slide(slide3_layout)
slide3.shapes.title.text = "Visuals and Data"
# Add a picture placeholder (no actual image needed for this test)
# We can't easily add a "placeholder" that behaves like a real image
# without an actual image file. So, just create a simple shape that *looks* like a placeholder.
# For the purpose of the converter, it will be detected as MsoShapeType.PICTURE if it's a real picture.
# To make a fake one detectable as a picture, you would typically need to insert a real one.
# Let's add a rectangle with text to simulate a placeholder if no real image is available.
# Or just a dummy shape that the converter will ignore, as it's not a picture/chart.
# For actual testing, you'd insert a real image.
# To simulate a PICTURE MsoShapeType, you'd need an actual image file.
# For simplicity, let's just make sure the converter handles it if it encounters one.
# In a real scenario, you'd call slide.shapes.add_picture('path/to/image.png', ...)
# For demonstration purposes, let's add a placeholder for a chart
# (python-pptx usually creates charts from data, so we'll just add a simple shape
# and assume it *could* be a chart if it had the right type)
# To make it detect as a chart, we'd use prs.add_chart. For this example,
# we'll rely on the `has_chart` property.
# Adding a simple rectangle for a "chart" simulation
# Note: This won't actually be detected as `has_chart` by python-pptx
# unless it was created as a chart object. This is for visual debugging of the dummy.
left, top, width, height = Inches(1), Inches(4), Inches(4), Inches(2)
shape_chart_placeholder = slide3.shapes.add_shape(MsoAutoShapeType.RECTANGLE, left, top, width, height)
shape_chart_placeholder.text_frame.text = "Placeholder for a Chart"
# If this were a real chart, it would be `prs.add_chart(...)` and then `shape.has_chart` would be True.
# Add some regular text
txBox = slide3.shapes.add_textbox(Inches(7), Inches(1), Inches(2), Inches(1))
tf = txBox.text_frame
p = tf.add_paragraph()
p.text = "This slide contains various visual elements."
p.level = 0
# Save the presentation
prs.save(file_name)
print(f"Dummy PPTX '{file_name}' created.")
return Path(file_name)
test_pptx_path = create_dummy_pptx()
# 変換を実行
markdown_output = pptx_to_markdown(test_pptx_path)
print("\n--- Converted Markdown Output ---\n")
print(markdown_output)
# 変換されたMarkdownをファイルに保存する例
output_md_path = test_pptx_path.with_suffix('.md')
with open(output_md_path, "w", encoding="utf-8") as f:
f.write(markdown_output)
print(f"\nMarkdown output saved to '{output_md_path}'")
# Clean up dummy pptx
# test_pptx_path.unlink()
# print(f"Dummy PPTX '{test_pptx_path}' removed.")
解説
StringIOの使用: 直接文字列に連結する代わりにio.StringIOを使うことで、大量のテキストを効率的に構築できます。
enumerateとstart=1: スライド番号を1から始めるためにenumerateを使用しています。
- スライドタイトル:
slide.shapes.titleは、標準的なレイアウトのタイトルプレースホルダーにアクセスする最も直接的な方法です。
- もしカスタムレイアウトなどで
slide.shapes.titleが存在しない場合は、slide.shapesをループして、shape.has_text_frameかつフォントサイズや位置がタイトルらしいものを探すなど、より複雑なロジックが必要になりますが、ここでは一般的なケースをカバーしています。
- テキスト処理:
shape.has_text_frameでテキストを含むシェイプを特定します。
shape.text_frame.paragraphsをループして各段落を処理します。
paragraph.levelは段落のインデントレベルを示します(0が最上位)。これを利用してMarkdownの箇条書き(- )とインデント( )を適用します。
strip()で余分な空白を除去し、if not text: continueで空の段落をスキップします。
- テーブル処理:
shape.has_tableでテーブルシェイプを特定します。
- テーブルの行と列をループし、
table.cell(row, col).textでセルのテキストを取得します。
- Markdownのテーブル形式(ヘッダー行、セパレーター行、データ行)に整形します。
- 画像とチャート:
shape.shape_type == MsoShapeType.PICTUREで画像シェイプを特定します。
shape.has_chartでチャートシェイプを特定します。
- これらの場合、具体的な内容ではなく
[Image Placeholder]や[Chart Placeholder]という情報のみを出力します。これはLLMに渡す際に「ここに画像/チャートがあった」というコンテキストを与えるのに十分です。
- エラーハンドリング: この関数は基本的な変換に焦点を当てています。複雑な埋め込みオブジェクト(動画、複雑なOLEオブジェクトなど)は現在サポートしていません。また、PowerPointファイルの破損や読み込みエラーに対する明示的なエラーハンドリングは含まれていませんが、
python-pptxライブラリが基本的なファイル読み込みエラーは処理します。
- LLMへの適応:
- 各スライドの始まりに
## Slide Xのような明確な見出しを付け、スライドタイトルがあればそれも副見出しとして加えることで、LLMがプレゼンテーションの構造を理解しやすくなります。
- テキストは段落や箇条書きとして整形され、読みやすい形式になっています。
- 画像やチャートの情報は、コンテンツの一部としてLLMに伝えられ、必要に応じてLLMがそれらの視覚的要素について言及する手助けとなります。
この関数は、PowerPointプレゼンテーションの主要なテキストコンテンツと構造を、LLMが解釈しやすいMarkdown形式で提供します。