最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

使用Python自動(dòng)化生成PPT并結(jié)合LLM生成內(nèi)容的代碼解析

 更新時(shí)間:2025年05月14日 09:53:01   作者:東方佑  
PowerPoint是常用的文檔工具,但手動(dòng)設(shè)計(jì)和排版耗時(shí)耗力,本文將展示如何通過 Python 自動(dòng)化提取 PPT 樣式并生成新 PPT,同時(shí)結(jié)合大語言模型(LLM)生成內(nèi)容(如自我介紹文本),實(shí)現(xiàn)高效、個(gè)性化的 PPT 制作,需要的朋友可以參考下

核心代碼解析

1. 提取 PPT 樣式到 JSON

extract_ppt_with_style 函數(shù)用于將 PPT 的樣式(字體、顏色、段落格式等)提取到 JSON 文件中,方便后續(xù)復(fù)用。

關(guān)鍵步驟:

  • 遍歷 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",  # 強(qiáng)制設(shè)置為 "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. 應(yīng)用 JSON 樣式到新 PPT

apply_styles_to_ppt 函數(shù)根據(jù) JSON 文件中的樣式信息,將內(nèi)容和格式應(yīng)用到模板 PPT 中。

關(guān)鍵步驟:

  • 讀取 JSON 數(shù)據(jù):解析字體、顏色等樣式信息。
  • 動(dòng)態(tài)設(shè)置樣式:支持 RGB 顏色、主題色,并兼容十六進(jìn)制顏色(如 #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)  # 默認(rèn)黑色
    prs.save(output_pptx)

結(jié)合 LLM 生成內(nèi)容

場景:生成自我介紹 PPT

假設(shè)需要根據(jù)用戶輸入的姓名、職位等信息,自動(dòng)生成帶樣式的自我介紹 PPT,可以按以下步驟操作:

1. 使用 LLM 生成文本內(nèi)容

通過調(diào)用 LLM(如 GPT-3.5、通義千問等),生成自我介紹的文本內(nèi)容:

import openai

def generate_self_introduction(name, role):
    prompt = f"生成一份關(guān)于 {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 字段中:

# 假設(shè)提取的 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)容應(yīng)用到模板中:

apply_styles_to_ppt("template.pptx", "modified.json", "output.pptx")

注意事項(xiàng)

  1. JSON 格式要求

    • 顏色值需為數(shù)組格式(如 rgb: [255, 0, 0])或十六進(jìn)制字符串(如 "hex": "#FF0000")。
    • 主題色需使用 MSO_THEME_COLOR 枚舉名稱(如 "ACCENT_1")。
  2. 形狀名稱標(biāo)準(zhǔn)化

    • 在提取樣式時(shí),強(qiáng)制將 shape_name 設(shè)置為 "Text",確保后續(xù)處理一致性。
  3. 兼容性

    • 確保模板 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)
    # 假設(shè)修改第一段文本
    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")

通過上述方法,你可以自動(dòng)化生成個(gè)性化 PPT,結(jié)合 LLM 的內(nèi)容生成能力,實(shí)現(xiàn)從設(shè)計(jì)到內(nèi)容的全流程自動(dòng)化!

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"]

                    # 假設(shè) 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":
                        # 解析十六進(jìn)制顏色
                        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:
                        # 默認(rèn)顏色(黑色)
                        run.font.color.rgb = RGBColor(0, 0, 0)

    prs.save(output_pptx)


if __name__ == '__main__':
    # 使用示例
    extract_ppt_with_style("template.pptx", "output_styles.json")
    # 這是一個(gè)ppt 模版解析出來的json 結(jié)構(gòu) name 為 shape 類型保持不變 請 改變 name 為 Text 類型的text ,text 的值進(jìn)行自我介紹 # 注意:只輸出json
    # 使用示例
    apply_styles_to_ppt("template.pptx", "output_styles.json", "new_ppt.pptx")

以上就是使用Python自動(dòng)化生成PPT并結(jié)合LLM生成內(nèi)容的代碼解析的詳細(xì)內(nèi)容,更多關(guān)于Python自動(dòng)化生成PPT的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Python format函數(shù)詳談

    Python format函數(shù)詳談

    這篇文章主要介紹了Python中用format函數(shù)格式化字符串的用法,格式化字符串是Python學(xué)習(xí)當(dāng)中的基礎(chǔ)知識,希望能夠給你帶來幫助
    2021-10-10
  • python 的生產(chǎn)者和消費(fèi)者模式

    python 的生產(chǎn)者和消費(fèi)者模式

    這篇文章主要介紹了python 的生產(chǎn)者和python 的消費(fèi)者模式的具體相關(guān)資料,需要的朋友可以參考下面文章內(nèi)容
    2021-09-09
  • 使用Python進(jìn)行時(shí)間序列分析的8種繪圖類型

    使用Python進(jìn)行時(shí)間序列分析的8種繪圖類型

    時(shí)間序列數(shù)據(jù)是按時(shí)間順序按固定時(shí)間間隔排列的觀測值的集合,每個(gè)觀察對應(yīng)于一個(gè)特定的時(shí)間點(diǎn),并且可以以各種頻率(例如,每天、每月、每年)記錄數(shù)據(jù),本文介紹了幾種類型的繪圖,可幫助您使用 Python 進(jìn)行時(shí)間序列分析,并提供使用可免費(fèi)訪問的數(shù)據(jù)集的詳細(xì)示例
    2023-09-09
  • python實(shí)現(xiàn)將JSON文件中的數(shù)據(jù)格式化處理

    python實(shí)現(xiàn)將JSON文件中的數(shù)據(jù)格式化處理

    JSON是一種輕量級的數(shù)據(jù)交換格式,常用于Web服務(wù)間的數(shù)據(jù)傳輸,Python內(nèi)置了??json??模塊,能夠方便地進(jìn)行JSON數(shù)據(jù)的解析與格式化,本文將通過具體的Python代碼實(shí)例,深入探討如何將JSON文件中的數(shù)據(jù)進(jìn)行格式化處理,需要的朋友可以參考下
    2024-03-03
  • Python實(shí)戰(zhàn)之SEO優(yōu)化自動(dòng)化工具開發(fā)指南

    Python實(shí)戰(zhàn)之SEO優(yōu)化自動(dòng)化工具開發(fā)指南

    在數(shù)字化營銷時(shí)代,搜索引擎優(yōu)化(SEO)已成為網(wǎng)站獲取流量的重要手段,本文將帶您使用Python開發(fā)一套完整的SEO自動(dòng)化工具,需要的可以了解下
    2025-08-08
  • jetson上安裝pycharm的詳細(xì)過程

    jetson上安裝pycharm的詳細(xì)過程

    Pycharm是一個(gè)非常優(yōu)秀的代碼編輯、調(diào)試,開發(fā)軟件,我平時(shí)在Windows系統(tǒng)學(xué)習(xí)編程時(shí)也比較喜歡使用Pycharm,這篇文章主要介紹了jetson上安裝pycharm的過程,需要的朋友可以參考下
    2022-07-07
  • 使用Python判斷IP地址合法性的方法實(shí)例

    使用Python判斷IP地址合法性的方法實(shí)例

    這篇文章主要介紹了使用Python判斷IP地址合法性的方法實(shí)例,需要的朋友可以參考下
    2014-03-03
  • Python 郵箱登錄驗(yàn)證碼功能實(shí)現(xiàn)代碼

    Python 郵箱登錄驗(yàn)證碼功能實(shí)現(xiàn)代碼

    本文介紹了結(jié)合前端校驗(yàn)和后端Redis緩存策略實(shí)現(xiàn)郵箱登錄的功能,旨在提高安全性和效率,前端校驗(yàn)郵箱格式,后端生成并發(fā)送驗(yàn)證碼,使用Redis緩存驗(yàn)證碼以提高效率和安全性,感興趣的朋友一起看看吧
    2024-12-12
  • python可迭代類型遍歷過程中數(shù)據(jù)改變會(huì)不會(huì)報(bào)錯(cuò)

    python可迭代類型遍歷過程中數(shù)據(jù)改變會(huì)不會(huì)報(bào)錯(cuò)

    這篇文章主要介紹了python可迭代類型遍歷過程中數(shù)據(jù)改變會(huì)不會(huì)報(bào)錯(cuò)問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-12-12
  • Python打印斐波拉契數(shù)列實(shí)例

    Python打印斐波拉契數(shù)列實(shí)例

    這篇文章主要介紹了Python打印斐波拉契數(shù)列的方法,實(shí)例分析了基于Python實(shí)現(xiàn)斐波那契數(shù)列的實(shí)現(xiàn)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下
    2015-07-07

最新評論

凤庆县| 贵溪市| 梧州市| 新田县| 留坝县| 南涧| 库车县| 白山市| 灵璧县| 武清区| 张北县| 安图县| 房产| 册亨县| 邵武市| 宝清县| 伊金霍洛旗| 洮南市| 达孜县| 瑞安市| 黑水县| 鲁山县| 陇西县| 新田县| 浙江省| 温泉县| 乌审旗| 满城县| 湖口县| 金溪县| 内江市| 阿巴嘎旗| 绍兴市| 泰宁县| 綦江县| 盘山县| 鹤峰县| 台前县| 富顺县| 宣武区| 洛扎县|