基于讯飞星火大模型实现智能PPT制作

步骤一:领取讯飞智能PPT生成资源

步骤二:创建sourceai/model/ppt/xunfei/AIPPT.py,代码如下

# -*- coding:utf-8 -*-
import hashlib
import hmac
import base64
import json
import time

import requests


class AIPPT():
    def __init__(self, APPId, APISecret, Text):
        self.APPid = APPId
        self.APISecret = APISecret
        self.text = Text
        self.header = {}

    # 获取签名
    def get_signature(self, ts):
        try:
            # 对app_id和时间戳进行MD5加密
            auth = self.md5(self.APPid + str(ts))
            # 使用HMAC-SHA1算法对加密后的字符串进行加密
            return self.hmac_sha1_encrypt(auth, self.APISecret)
        except Exception as e:
            print(e)
            return None

    def hmac_sha1_encrypt(self, encrypt_text, encrypt_key):
        # 使用HMAC-SHA1算法对文本进行加密,并将结果转换为Base64编码
        return base64.b64encode(
            hmac.new(encrypt_key.encode('utf-8'), encrypt_text.encode('utf-8'), hashlib.sha1).digest()).decode('utf-8')

    def md5(self, text):
        # 对文本进行MD5加密,并返回加密后的十六进制字符串
        return hashlib.md5(text.encode('utf-8')).hexdigest()

    # 创建PPT生成任务
    def create_task(self):
        url = 'https://zwapi.xfyun.cn/api/aippt/create'
        timestamp = int(time.time())
        signature = self.get_signature(timestamp)
        body = self.getbody(self.text)

        headers = {
            "appId": self.APPid,
            "timestamp": str(timestamp),
            "signature": signature,
            "Content-Type": "application/json; charset=utf-8"
        }
        self.header = headers
        response = requests.request("POST", url=url, data=json.dumps(body), headers=headers).text
        resp = json.loads(response)
        print(resp)
        if 0 == resp['code']:
            print('创建PPT任务成功')
            return resp['data']['sid'], resp['data']['coverImgSrc']
        else:
            print('创建PPT任务失败')
            return None,None

    # 构建请求body体
    def getbody(self, text):
        body = {
            "query": text
        }
        return body

    # 轮询任务进度,返回完整响应信息
    def get_process(self, sid):
        print("sid:" + sid)
        print(self.header)
        if (None != sid):
            response = requests.request("GET", url=f"https://zwapi.xfyun.cn/api/aippt/progress?sid={sid}",
                                        headers=self.header).text
            print(response)
            return response
        else:
            return None

    # 获取PPT,以下载连接形式返回
    def get_result(self):

        # 创建PPT生成任务
        task_id,coverImgSrc = self.create_task()
        # PPTurl = ''
        # 轮询任务进度
        while (True):
            time.sleep(1)
            response = self.get_process(task_id)
            resp = json.loads(response)
            process = resp['data']['process']
            if (process == 100):
                PPTurl = resp['data']['pptUrl']
                break
        return PPTurl,coverImgSrc

def start(content):
    # 控制台获取
    APPId = "7e02e2701"
    APISecret = "NGNmZjBlNzM3YzA1N2Q5MzI0NWE0ZGY1"

    # PPT生成(直接根据用户输入要求,获得最终PPT)

    res = AIPPT(APPId, APISecret, content)

    # return res.get_result()

    ppt_path,coverImgSrc = res.get_result()
    print("生成的PPT请从此地址获取:\n" + ppt_path)
    return ppt_path,coverImgSrc



if __name__ == '__main__':

    Text = "大数据技术分享"
    result ,coverImgSrc =start(Text)
    print("生成的PPT请从此地址获取:\n" + result+coverImgSrc)

步骤三:创建sourceai/controller/ppt_view.py文件,代码如下

from django.shortcuts import render
from django.http import HttpResponse
from sourceai.model.ppt.xunfei import AIPPT
import json


# Create your views here.

def ppt_index(request):
    return render(request, 'ppt/xunfeippt.html')


def ppt_to_create(request):
    context = request.POST.get('context')
    ppt_url, cover_img = AIPPT.start(context)

    return HttpResponse(json.dumps({"res": ppt_url, "cover": cover_img}))

步骤四:在soft863ai/urls.py中新增如下内容

from sourceai.controller import ppt_view
    path('sparkppt', ppt_view.ppt_index),
    path('sparkpptto', ppt_view.ppt_to_create),

步骤五:创建templates/ppt/xunfeippt.html,代码如下

<!doctype html>
<html>
<head>
    <meta charset=utf-8>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="icon" href="/static/img/imgshibie.png"> <!-- 网页图标 -->
    <link rel="stylesheet" type="text/css" href="/static/css/index.css"/>
    <link rel="stylesheet" href="/static/css/index.css">
    <link rel="stylesheet" href="/static/css/animate.css">
    <script src="/static/js/jquery-1.11.3.min.js"></script>
    <script src="/static/js/typeit.min.js"></script>
    <script src="/static/js/rem.js" type="text/javascript" charset="utf-8"></script>
</head>
<body style="cursor: url(img/body2.png);">
<div class="canvas" style="opacity: .2">
    <iframe frameborder="0" src="/static/js/index.html" style="width: 100%; height: 100%"></iframe>
</div>
<div id="app">
    <div class="header_title">智能PPT生成</div>
    <div class="header_time"></div>
    <!-- //左侧显示信息 -->
    <div class="side_left ">
            <textarea id="context1"
                      style="width: 4.2rem;min-height: 5rem;background: rgba(255, 255, 255, 0);color:#3cf7f1;border:0;outline: none;margin-top: 1rem;margin-left:0.23rem;display: inline-block;">
            </textarea>
    </div>
    <div class="face-capture" id="face-capture">
        <div class="faceCon">
            <div class="videoFaceCon">
                <div class="title">点击开始创作</div>
                <div class="imgCoverCon">
                    <div class="retiveCon">
                        <img src="/static/img/1233.png" class="retiveConImg allRoteAnmi">
                        <img src="/static/img/imgshibie.png" class="videoFace">
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="side_right">
        <div class="rightCon">
            <div>
                <img class="textConImg" src='' width="400px">
                <iframe class="ppturl"  src="" hidden="" ></iframe>
            </div>
        </div>

    </div>
    <script type="text/javascript">
        window.onload = function () {
            $('.side_left').show();
            $('.side_right').show();
            // 时间
            var timer = '';
            var taker = '';
            timer && clearInterval(_this.timer);
            timer = setInterval(function () {
                var show_day = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日'];
                var nowtime = new Date();
                var year = nowtime.getFullYear();
                var month = nowtime.getMonth() + 1;
                var date = nowtime.getDate();
                var day = nowtime.getDay();
                var hour = nowtime.getHours();
                var minutes = nowtime.getMinutes();
                var second = nowtime.getSeconds();
                month < 10 ? month = '0' + month : month;
                hour < 10 ? hour = '0' + hour : hour;
                minutes < 10 ? minutes = '0' + minutes : minutes;
                second < 10 ? second = '0' + second : second;
                var show_day_s = day === 0 ? show_day[6] : show_day[day - 1];
                // _this.mytime = year + "年" + month + "月" + date + "日  " + show_day_s+ nowtime.toLocaleTimeString('chinese', { hour12: false });
                var mytimer = year + "年" + month + "月" + date + "日" + show_day_s + ' ' +
                    hour + ':' + minutes;
                $('.header_time').html(mytimer)
            }, 1000);

            //时间
            function goanimation() {
                taker = '';
                taker = new TypeIt('.rightCon', {
                    lifeLike: true,
                    cursorSpeed: 1000,
                    waitUntilVisible: false,
                    speed: 100
                }).go();
            }

            $('.videoFaceCon').click(() => {
                log = $("#context1").val()
                $('.title').html('正在创作..');

                //创建一个存储表单数据的对象
                var fd = new FormData();
                fd.append("context", log);
                fd.append("csrfmiddlewaretoken", '{{ csrf_token }}')
                $.ajax({
                    url: '/sparkpptto',
                    type: 'post',
                    data: fd,
                    dataType: 'json',
                    cache: false,
                    processData: false,
                    contentType: false,
                    success: function (obj) {
                        console.log(obj)
                        console.log(obj.res)
                        $('.textConImg').attr("src", obj.cover)
                        $('.ppturl').attr("src", obj.res)
                         $('.title').html('恭喜您,创作成功!')
                        $('.rightCon').show()
                        $('.rightCon').addClass('fadeInRightBig');

                        goanimation();
                        taker.reset();
                    }
                })
            })
        }
    </script>
</body>

</html>

步骤六:运行并测试

浏览器输入:

http://127.0.0.1:8000/sparkppt

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

数智侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值