python+qwen3-coder+vue实现多项目ai对话生成ppt演示文档代码

代码语言:python

所属分类:人工智能

代码描述:python+qwen3-coder+vue实现多项目ai对话生成ppt演示文档代码

代码标签: python qwen coder vue 多项目 ai 对话 生成 ppt 演示 文档 代码

下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开

#!/usr/local/python3/bin/python3
# -*- coding: utf-8 -*
import os
import json
import uvicorn
from fastapi import FastAPI, HTTPException
from fastapi.responses import HTMLResponse, JSONResponse
from pydantic import BaseModel
from openai import OpenAI
from typing import List, Dict
import openai

# ##################################################################
# 配置部分
# ##################################################################

# --- OpenAI API 密钥 ---
# 强烈建议使用环境变量来管理密钥。
# 在这里替换为您自己的通义千问 API 密钥
OPENAI_API_KEY = "sk-" 

# --- 演示文稿项目数据存储目录 ---
PROJECTS_DIR = "presentations"
if not os.path.exists(PROJECTS_DIR):
    os.makedirs(PROJECTS_DIR)

# --- 初始化 FastAPI 应用 ---
app = FastAPI()

# --- 初始化 OpenAI 客户端 ---
try:
    client = openai.OpenAI(api_key=OPENAI_API_KEY, base_url="https://dashscope.aliyuncs.com/compatible-mode/v1")
except Exception as e:
    print(f"初始化 OpenAI 客户端时出错: {e}")
    client = None
# ##################################################################
# Pydantic 模型定义
# ##################################################################

class ChatRequest(BaseModel):
    """定义聊天请求的请求体结构"""
    message: str

# --- 新增 ---
# 用于接收前端确认后的最终大纲
class OutlineRequest(BaseModel):
    """定义提交最终大纲的请求体结构。"""
    outline: str


# ##################################################################
# 后端逻辑部分
# ##################################################################

@app.get("/api/projects", response_model=List[str])
async def get_projects():
    """获取所有已创建演示文稿项目的列表。"""
    projects = [f.replace(".json", "") for f in os.listdir(PROJECTS_DIR) if f.endswith(".json")]
    return sorted(projects)

@app.post("/api/projects/{project_name}")
async def create_project(project_name: str):
    """创建一个新项目,并为其生成一个空的聊天记录 JSON 文件。"""
    if not project_name or not project_name.strip():
        raise HTTPException(status_code=400, detail="项目名称不能为空。")
    
    file_path = os.path.join(PROJECTS_DIR, f"{project_name}.json")
    if os.path.exists(file_path):
        raise HTTPException(status_code=400, detail="项目名称已存在,请换一个。")
    
    with open(file_path, 'w', encoding='utf-8') as f:
        json.dump([], f)
        
    return {"message": f"项目 '{project_name}' 创建成功。"}

@app.get("/api/chat/{project_name}", response_model=List[Dict])
async def get_chat_history(project_name: str):
    """获取指定项目的聊天历史记录。"""
    file_path = os.path.join(PROJECTS_DIR, f"{project_name}.json")
    if not os.path.exists(file_path):
        raise HTTPException(status_code=404, detail="项目未找到。")
    with open(file_path, 'r', encoding='utf-8') as f:
        return json.load(f)

# --- 新增 ---
# 第一步:根据用户主题生成大纲
@app.post("/api/chat/{project_name}/generate-outline")
async def generate_outline(project_name: str, request: ChatRequest):
    """接收用户主题,生成演示文稿大纲,并返回给用户编辑。"""
    file_path = os.path.join(PROJECTS_DIR, f"{project_name}.json")
    if not os.path.exists(file_path):
        raise HTTPException(status_code=404, detail="项目未找到。")

    with open(file_path, 'r', encoding='utf-8') as f:
        chat_history = json.load(f)
    
    chat_history.append({"role": "user", "content": request.message})

    outline_content = generate_ppt_outline_with_openai(request.message)

    # 在AI返回的消息中增加一个 `is_outline` 标志,用于前端识别
    ai_response = {
        "role": "assistant", 
        "content": outline_content,
        "is_outline": True  # 这是给前端的信号
    }
    
    chat_history.append(ai_response)
    save_chat_history(project_name, chat_history)

    return JSONResponse(content={"chat_response": ai_response})

# --- 修改 ---
# 第二步:根据用户确认后的大纲生成最终的HTML幻灯片
@app.post("/api/chat/{project_name}/generate-slides-from-outline")
async def generate_slides_from_outline(project_name: str, request: OutlineRequest):
    """接收用户确认(并可能已编辑)的大纲,生成最终的HTML幻灯片。"""
    file_path = os.path.join(PROJECTS_DIR, f"{project_name}.json")
    if not os.path.exists(file_path):
        raise HTTPException(status_code=404, detail="项目未找到。")

    with open(file_path, 'r', encoding='utf-8') as f:
        chat_history = json.load(f)
    
    # 记录用户确认大纲的动作
    # 注意:我们将最后一条AI消息(即大纲)的内容更新为用户最终确认的版本
    for message in reversed(chat_history):
        if message.get("is_outline"):
            message["content"] = request.outline
            message["is_outline"] = False # 将其锁定,不再是可编辑状态
            break
            
    # 使用最终的大纲来生成HTML
    generation_history = [{"role": "user", "content": f"请根据以下大纲生成演示文稿:\n\n{request.outline}"}]
    generated_html = gen.........完整代码请登录后点击上方下载按钮下载查看

网友评论0