使用Python自動化生成PPT并結(jié)合LLM生成內(nèi)容的代碼解析
核心代碼解析
1. 提取 PPT 樣式到 JSON
extract_ppt_with_style 函數(shù)用于將 PPT 的樣式(字體、顏色、段落格式等)提取到 JSON 文件中,方便后續(xù)復用。
關鍵步驟:
- 遍歷 PPT 的每一頁:逐頁提取文本框的樣式。
- 記錄樣式信息:包括字體名稱、大小、加粗、斜體、顏色(支持主題色和 RGB 顏色)。
- JSON 結(jié)構(gòu)示例:
{
"slide_number": 1,
"shapes": [
{
"shape_name": "Text",
"paragraphs": [
{
"alignment": "LEFT",
"runs": [
{
"text": "自我介紹",
"font": {
"name": "Arial",
"size": 24,
"bold": true,
"italic": false,
"color": {
"type": "rgb",
"rgb": [255, 0, 0]
}
}
}
]
}
]
}
]
}
代碼片段:
def extract_ppt_with_style(ppt_path, output_json):
prs = Presentation(ppt_path)
data = []
for slide_idx, slide in enumerate(prs.slides):
slide_data = {
"slide_number": slide_idx + 1,
"shapes": []
}
for shape in slide.shapes:
if not shape.has_text_frame:
continue
text_frame = shape.text_frame
text_info = {
"shape_name": "Text", # 強制設置為 "Text" 類型
"paragraphs": []
}
for paragraph in text_frame.paragraphs:
para_info = {
"alignment": str(paragraph.alignment),
"runs": []
}
for run in paragraph.runs:
run_info = {
"text": run.text,
"font": {
"name": run.font.name,
"size": str(run.font.size) if run.font.size else None,
"bold": run.font.bold,
"italic": run.font.italic,
"color": {
"type": "theme" if run.font.color.type == MSO_THEME_COLOR else "rgb",
"theme_color": run.font.color.theme_color,
"rgb": (run.font.color.rgb[0], run.font.color.rgb[1], run.font.color.rgb[2]) if run.font.color.rgb else None
}
}
}
para_info["runs"].append(run_info)
text_info["paragraphs"].append(para_info)
slide_data["shapes"].append(text_info)
data.append(slide_data)
with open(output_json, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2, ensure_ascii=False)
2. 應用 JSON 樣式到新 PPT
apply_styles_to_ppt 函數(shù)根據(jù) JSON 文件中的樣式信息,將內(nèi)容和格式應用到模板 PPT 中。
關鍵步驟:
- 讀取 JSON 數(shù)據(jù):解析字體、顏色等樣式信息。
- 動態(tài)設置樣式:支持 RGB 顏色、主題色,并兼容十六進制顏色(如
#FF0000)。 - 生成最終 PPT:將修改后的樣式保存為新文件。
代碼片段:
def apply_styles_to_ppt(template_path, json_path, output_pptx):
with open(json_path, 'r', encoding='utf-8') as f:
data = json.load(f)
prs = Presentation(template_path)
for slide_idx, slide in enumerate(prs.slides):
for shape_idx, shape in enumerate(slide.shapes):
if not shape.has_text_frame:
continue
text_frame = shape.text_frame
for paragraph_idx, paragraph in enumerate(text_frame.paragraphs):
for run_idx, run in enumerate(paragraph.runs):
run_info = data[slide_idx]["shapes"][shape_idx]["paragraphs"][paragraph_idx]["runs"][run_idx]
run.text = run_info["text"] # 替換文本內(nèi)容
run.font.name = run_info["font"]["name"]
run.font.size = run_info["font"]["size"]
run.font.bold = run_info["font"]["bold"]
run.font.italic = run_info["font"]["italic"]
color_data = run_info["font"]["color"]
if color_data["type"] == "rgb":
r, g, b = color_data["rgb"] # 直接解析 RGB 數(shù)組
run.font.color.rgb = RGBColor(r, g, b)
elif color_data["type"] == "hex":
hex_color = color_data["hex"].lstrip("#")
r = int(hex_color[0:2], 16)
g = int(hex_color[2:4], 16)
b = int(hex_color[4:6], 16)
run.font.color.rgb = RGBColor(r, g, b)
elif color_data["type"] == "theme":
theme_color = getattr(MSO_THEME_COLOR, color_data["theme_color"], MSO_THEME_COLOR.ACCENT_1)
run.font.color.theme_color = theme_color
else:
run.font.color.rgb = RGBColor(0, 0, 0) # 默認黑色
prs.save(output_pptx)
結(jié)合 LLM 生成內(nèi)容
場景:生成自我介紹 PPT
假設需要根據(jù)用戶輸入的姓名、職位等信息,自動生成帶樣式的自我介紹 PPT,可以按以下步驟操作:
1. 使用 LLM 生成文本內(nèi)容
通過調(diào)用 LLM(如 GPT-3.5、通義千問等),生成自我介紹的文本內(nèi)容:
import openai
def generate_self_introduction(name, role):
prompt = f"生成一份關于 {name}({role})的自我介紹,要求簡潔明了,適合 PPT 展示。"
response = openai.Completion.create(
engine="text-davinci-003",
prompt=prompt,
max_tokens=150
)
return response.choices[0].text.strip()
2. 將 LLM 內(nèi)容注入 JSON
將生成的文本內(nèi)容填充到 JSON 的 text 字段中:
# 假設提取的 JSON 結(jié)構(gòu)如下:
json_data = {
"slide_number": 1,
"shapes": [
{
"shape_name": "Text",
"paragraphs": [
{
"runs": [
{"text": "【待替換的占位符】", ...}
]
}
]
}
]
}
# 替換文本內(nèi)容
generated_text = generate_self_introduction("張三", "數(shù)據(jù)分析師")
json_data["shapes"][0]["paragraphs"][0]["runs"][0]["text"] = generated_text
3. 生成最終 PPT
調(diào)用 apply_styles_to_ppt 將樣式和內(nèi)容應用到模板中:
apply_styles_to_ppt("template.pptx", "modified.json", "output.pptx")
注意事項
JSON 格式要求:
- 顏色值需為數(shù)組格式(如
rgb: [255, 0, 0])或十六進制字符串(如"hex": "#FF0000")。 - 主題色需使用
MSO_THEME_COLOR枚舉名稱(如"ACCENT_1")。
- 顏色值需為數(shù)組格式(如
形狀名稱標準化:
- 在提取樣式時,強制將
shape_name設置為"Text",確保后續(xù)處理一致性。
- 在提取樣式時,強制將
兼容性:
- 確保模板 PPT 的形狀結(jié)構(gòu)與 JSON 數(shù)據(jù)匹配(如位置、層級)。
完整示例
if __name__ == '__main__':
# 1. 提取模板樣式到 JSON
extract_ppt_with_style("template.pptx", "output_styles.json")
# 2. 生成自我介紹文本并修改 JSON
with open("output_styles.json", "r") as f:
data = json.load(f)
# 假設修改第一段文本
data[0]["shapes"][0]["paragraphs"][0]["runs"][0]["text"] = "我是張三,一名數(shù)據(jù)分析師..."
# 3. 生成最終 PPT
apply_styles_to_ppt("template.pptx", "output_styles.json", "new_ppt.pptx")
通過上述方法,你可以自動化生成個性化 PPT,結(jié)合 LLM 的內(nèi)容生成能力,實現(xiàn)從設計到內(nèi)容的全流程自動化!
from pptx import Presentation
from pptx.enum.dml import MSO_THEME_COLOR
from pptx.dml.color import RGBColor
import json
def extract_ppt_with_style(ppt_path, output_json):
prs = Presentation(ppt_path)
data = []
for slide_idx, slide in enumerate(prs.slides):
slide_data = {
"slide_number": slide_idx + 1,
"shapes": []
}
for shape in slide.shapes:
if not shape.has_text_frame:
continue # 跳過非文本形狀
text_frame = shape.text_frame
text_info = {
"shape_name": shape.name,
"paragraphs": []
}
for paragraph in text_frame.paragraphs:
para_info = {
"alignment": str(paragraph.alignment),
"runs": []
}
for run in paragraph.runs:
run_info = {
"text": run.text,
"font": {
"name": run.font.name,
"size": str(run.font.size) if run.font.size else None,
"bold": run.font.bold,
"italic": run.font.italic,
"color": {
"type": "theme" if run.font.color.type == MSO_THEME_COLOR else "rgb",
"theme_color": run.font.color.theme_color,
"rgb": (run.font.color.rgb[0], run.font.color.rgb[1],
run.font.color.rgb[2]) if run.font.color.rgb else None
}
},
# "highlight_color": str(run.highlight_color) # 修改:從 run 而非 run.font 獲取
}
para_info["runs"].append(run_info)
text_info["paragraphs"].append(para_info)
slide_data["shapes"].append(text_info)
data.append(slide_data)
with open(output_json, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2, ensure_ascii=False)
def apply_styles_to_ppt(template_path, json_path, output_pptx):
with open(json_path, 'r', encoding='utf-8') as f:
data = json.load(f)
prs = Presentation(template_path)
for slide_idx, slide in enumerate(prs.slides):
for shape_idx, shape in enumerate(slide.shapes):
if not shape.has_text_frame:
continue # 跳過非文本形狀
text_frame = shape.text_frame
for paragraph_idx, paragraph in enumerate(text_frame.paragraphs):
for run_idx, run in enumerate(paragraph.runs):
run_info = data[slide_idx]["shapes"][shape_idx]["paragraphs"][paragraph_idx]["runs"][run_idx]
run.text = run_info["text"]
run.font.name = run_info["font"]["name"]
run.font.size = run_info["font"]["size"]
run.font.bold = run_info["font"]["bold"]
run.font.size = run_info["font"]["size"]
run.font.italic = run_info["font"]["italic"]
# 假設 run_data 是從 JSON 中讀取的字典
color_data = run_info["font"]["color"]
if color_data["type"] == "rgb":
# 解析 RGB 值
r_str, g_str, b_str = color_data["rgb"]
r = r_str
g = g_str
b = b_str
run.font.color.rgb = RGBColor(r, g, b)
elif color_data["type"] == "hex":
# 解析十六進制顏色
hex_color = color_data["hex"].lstrip("#")
r = int(hex_color[0:2], 16)
g = int(hex_color[2:4], 16)
b = int(hex_color[4:6], 16)
run.font.color.rgb = RGBColor(r, g, b)
elif color_data["type"] == "theme":
# 使用主題顏色(如 MSO_THEME_COLOR.ACCENT_1)
theme_color_name = color_data["theme_color"]
theme_color = getattr(MSO_THEME_COLOR, theme_color_name, MSO_THEME_COLOR.ACCENT_1)
run.font.color.theme_color = theme_color
else:
# 默認顏色(黑色)
run.font.color.rgb = RGBColor(0, 0, 0)
prs.save(output_pptx)
if __name__ == '__main__':
# 使用示例
extract_ppt_with_style("template.pptx", "output_styles.json")
# 這是一個ppt 模版解析出來的json 結(jié)構(gòu) name 為 shape 類型保持不變 請 改變 name 為 Text 類型的text ,text 的值進行自我介紹 # 注意:只輸出json
# 使用示例
apply_styles_to_ppt("template.pptx", "output_styles.json", "new_ppt.pptx")
以上就是使用Python自動化生成PPT并結(jié)合LLM生成內(nèi)容的代碼解析的詳細內(nèi)容,更多關于Python自動化生成PPT的資料請關注腳本之家其它相關文章!
相關文章
python實現(xiàn)數(shù)據(jù)清洗(缺失值與異常值處理)
今天小編就為大家分享一篇python實現(xiàn)數(shù)據(jù)清洗(缺失值與異常值處理),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12
python操作excel之openpyxl模塊讀寫xlsx格式使用方法詳解
這篇文章主要介紹了python操作excel之openpyxl模塊讀寫xlsx格式使用方法詳解,需要的朋友可以參考下2022-12-12
Python單元測試工具doctest和unittest使用解析
這篇文章主要介紹了Python單元測試工具doctest和unittest使用解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-09-09

