当前位置:   article > 正文

【2022 CCF BDCI 文心大模型创意项目】AI一键搞定全套写文稿_您能具体分享一个应用文心模型的项目案例吗?在这个案例中,您是如何根据项目的

您能具体分享一个应用文心模型的项目案例吗?在这个案例中,您是如何根据项目的

★★★ 本文源自AI Studio社区精品项目,【点击此处】查看更多精品内容 >>>


【2022 CCF BDCI 文心大模型创意项目】AI一键搞定全套写文稿加配图(文心大模型图文创作)

版本更新

  • 由于hub调用文心模型的接口发生变化,需要给定ak和sk,请到文心官方申请:wenxin.baidu.com
  • 由于文心模型版本更新,“儿童画”不能作为style传入,需要重新调整提示词
  • 调整API调用代码,以符合新版API

一、项目简介

  • 所谓绘本,就是一段文字,配上一幅图片,这个活儿现在可以让AI来做,只要给它一个题目
  • 这个试验项目,用的是百度文心大模型,只需要一个标题,剩下的事情AI全包了
  • 可能是预训练模型的问题,生成的图文还不是很理想,但是也比你憋了一晚上还写不出来强
  • 这里面,标题、摘要、内容、配图都有了,只差封装到HTML
  • 使用了两种方式来调用模型,第一种是通过paddlehub,第二种是使用文心开放API

二、使用paddlehub调用文心大模型生成图文

2.1 第一步:安装paddlehub,获取所需的模型

#升级一下pip
!pip install --upgrade pip
  • 1
  • 2
Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple
Requirement already satisfied: pip in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (22.3.1)
  • 1
  • 2
# 提示需要这个版本的tqdm,但是好像不安装也行
!pip install tqdm==4.48.2 --user
  • 1
  • 2
Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple
Collecting tqdm==4.48.2
  Using cached https://pypi.tuna.tsinghua.edu.cn/packages/28/7e/281edb5bc3274dfb894d90f4dbacfceaca381c2435ec6187a2c6f329aed7/tqdm-4.48.2-py2.py3-none-any.whl (68 kB)
Installing collected packages: tqdm
  Attempting uninstall: tqdm
    Found existing installation: tqdm 4.27.0
    Uninstalling tqdm-4.27.0:
      Successfully uninstalled tqdm-4.27.0
[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.
paddlefsl 1.0.0 requires tqdm~=4.27.0, but you have tqdm 4.48.2 which is incompatible.[0m[31m
[0mSuccessfully installed tqdm-4.48.2
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
# 安装paddlehub
!pip install --upgrade paddlehub --user
  • 1
  • 2
Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple
Requirement already satisfied: paddlehub in ./.data/webide/pip/lib/python3.7/site-packages (2.3.1)
Requirement already satisfied: opencv-python in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from paddlehub) (4.6.0.66)
Requirement already satisfied: gunicorn>=19.10.0 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from paddlehub) (20.0.4)
Requirement already satisfied: filelock in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from paddlehub) (3.0.12)
Requirement already satisfied: numpy in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from paddlehub) (1.19.5)
Requirement already satisfied: colorama in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from paddlehub) (0.4.4)
Requirement already satisfied: gradio in ./.data/webide/pip/lib/python3.7/site-packages (from paddlehub) (3.14.0)
Requirement already satisfied: colorlog in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from paddlehub) (4.1.0)
Requirement already satisfied: pyzmq in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from paddlehub) (23.2.1)
Requirement already satisfied: packaging in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from paddlehub) (21.3)
Requirement already satisfied: tqdm in ./.data/webide/pip/lib/python3.7/site-packages (from paddlehub) (4.48.2)
Requirement already satisfied: pyyaml in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from paddlehub) (5.1.2)
Requirement already satisfied: paddlenlp>=2.0.0 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from paddlehub) (2.1.1)
Requirement already satisfied: rarfile in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from paddlehub) (3.1)
Requirement already satisfied: Pillow in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from paddlehub) (8.2.0)
Requirement already satisfied: paddle2onnx>=0.5.1 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from paddlehub) (1.0.0)
Requirement already satisfied: flask>=1.1.0 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from paddlehub) (1.1.1)
Requirement already satisfied: visualdl>=2.0.0 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from paddlehub) (2.4.0)
Requirement already satisfied: easydict in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from paddlehub) (1.9)
Requirement already satisfied: matplotlib in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from paddlehub) (2.2.3)
Requirement already satisfied: click>=5.1 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from flask>=1.1.0->paddlehub) (8.0.4)
Requirement already satisfied: Jinja2>=2.10.1 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from flask>=1.1.0->paddlehub) (3.0.0)
Requirement already satisfied: Werkzeug>=0.15 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from flask>=1.1.0->paddlehub) (0.16.0)
Requirement already satisfied: itsdangerous>=0.24 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from flask>=1.1.0->paddlehub) (1.1.0)
Requirement already satisfied: setuptools>=3.0 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from gunicorn>=19.10.0->paddlehub) (41.4.0)
Requirement already satisfied: multiprocess in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from paddlenlp>=2.0.0->paddlehub) (0.70.11.1)
Requirement already satisfied: h5py in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from paddlenlp>=2.0.0->paddlehub) (2.9.0)
Requirement already satisfied: jieba in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from paddlenlp>=2.0.0->paddlehub) (0.42.1)
Requirement already satisfied: paddlefsl==1.0.0 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from paddlenlp>=2.0.0->paddlehub) (1.0.0)
Requirement already satisfied: seqeval in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from paddlenlp>=2.0.0->paddlehub) (1.2.2)
Requirement already satisfied: requests~=2.24.0 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from paddlefsl==1.0.0->paddlenlp>=2.0.0->paddlehub) (2.24.0)
Collecting tqdm
  Using cached https://pypi.tuna.tsinghua.edu.cn/packages/16/33/6d8bd6a7c4238f383426b7593bf05bfd6d9e1f10c3084b56c0f14d973754/tqdm-4.27.0-py2.py3-none-any.whl (44 kB)
Requirement already satisfied: pandas in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from visualdl>=2.0.0->paddlehub) (1.1.5)
Requirement already satisfied: six>=1.14.0 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from visualdl>=2.0.0->paddlehub) (1.16.0)
Requirement already satisfied: bce-python-sdk in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from visualdl>=2.0.0->paddlehub) (0.8.53)
Requirement already satisfied: Flask-Babel>=1.0.0 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from visualdl>=2.0.0->paddlehub) (1.0.0)
Requirement already satisfied: protobuf>=3.11.0 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from visualdl>=2.0.0->paddlehub) (3.20.0)
Requirement already satisfied: pydantic in ./.data/webide/pip/lib/python3.7/site-packages (from gradio->paddlehub) (1.10.2)
Requirement already satisfied: pydub in ./.data/webide/pip/lib/python3.7/site-packages (from gradio->paddlehub) (0.25.1)
Requirement already satisfied: ffmpy in ./.data/webide/pip/lib/python3.7/site-packages (from gradio->paddlehub) (0.3.0)
Requirement already satisfied: websockets>=10.0 in ./.data/webide/pip/lib/python3.7/site-packages (from gradio->paddlehub) (10.4)
Requirement already satisfied: uvicorn in ./.data/webide/pip/lib/python3.7/site-packages (from gradio->paddlehub) (0.20.0)
Requirement already satisfied: markupsafe in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from gradio->paddlehub) (2.0.1)
Requirement already satisfied: httpx in ./.data/webide/pip/lib/python3.7/site-packages (from gradio->paddlehub) (0.23.1)
Requirement already satisfied: fastapi in ./.data/webide/pip/lib/python3.7/site-packages (from gradio->paddlehub) (0.88.0)
Requirement already satisfied: fsspec in ./.data/webide/pip/lib/python3.7/site-packages (from gradio->paddlehub) (2022.11.0)
Requirement already satisfied: aiohttp in ./.data/webide/pip/lib/python3.7/site-packages (from gradio->paddlehub) (3.8.3)
Requirement already satisfied: altair in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from gradio->paddlehub) (4.2.0)
Requirement already satisfied: pycryptodome in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from gradio->paddlehub) (3.9.9)
Requirement already satisfied: python-multipart in ./.data/webide/pip/lib/python3.7/site-packages (from gradio->paddlehub) (0.0.5)
Requirement already satisfied: orjson in ./.data/webide/pip/lib/python3.7/site-packages (from gradio->paddlehub) (3.8.3)
Requirement already satisfied: markdown-it-py[linkify,plugins] in ./.data/webide/pip/lib/python3.7/site-packages (from gradio->paddlehub) (2.1.0)
Requirement already satisfied: pytz in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from matplotlib->paddlehub) (2019.3)
Requirement already satisfied: python-dateutil>=2.1 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from matplotlib->paddlehub) (2.8.2)
Requirement already satisfied: cycler>=0.10 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from matplotlib->paddlehub) (0.10.0)
Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from matplotlib->paddlehub) (3.0.9)
Requirement already satisfied: kiwisolver>=1.0.1 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from matplotlib->paddlehub) (1.1.0)
Requirement already satisfied: importlib-metadata in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from click>=5.1->flask>=1.1.0->paddlehub) (4.2.0)
Requirement already satisfied: Babel>=2.3 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from Flask-Babel>=1.0.0->visualdl>=2.0.0->paddlehub) (2.8.0)
Requirement already satisfied: idna<3,>=2.5 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from requests~=2.24.0->paddlefsl==1.0.0->paddlenlp>=2.0.0->paddlehub) (2.8)
Requirement already satisfied: chardet<4,>=3.0.2 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from requests~=2.24.0->paddlefsl==1.0.0->paddlenlp>=2.0.0->paddlehub) (3.0.4)
Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from requests~=2.24.0->paddlefsl==1.0.0->paddlenlp>=2.0.0->paddlehub) (1.25.6)
Requirement already satisfied: certifi>=2017.4.17 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from requests~=2.24.0->paddlefsl==1.0.0->paddlenlp>=2.0.0->paddlehub) (2019.9.11)
Requirement already satisfied: aiosignal>=1.1.2 in ./.data/webide/pip/lib/python3.7/site-packages (from aiohttp->gradio->paddlehub) (1.3.1)
Requirement already satisfied: multidict<7.0,>=4.5 in ./.data/webide/pip/lib/python3.7/site-packages (from aiohttp->gradio->paddlehub) (6.0.3)
Requirement already satisfied: async-timeout<5.0,>=4.0.0a3 in ./.data/webide/pip/lib/python3.7/site-packages (from aiohttp->gradio->paddlehub) (4.0.2)
Requirement already satisfied: charset-normalizer<3.0,>=2.0 in ./.data/webide/pip/lib/python3.7/site-packages (from aiohttp->gradio->paddlehub) (2.1.1)
Requirement already satisfied: frozenlist>=1.1.1 in ./.data/webide/pip/lib/python3.7/site-packages (from aiohttp->gradio->paddlehub) (1.3.3)
Requirement already satisfied: asynctest==0.13.0 in ./.data/webide/pip/lib/python3.7/site-packages (from aiohttp->gradio->paddlehub) (0.13.0)
Requirement already satisfied: typing-extensions>=3.7.4 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from aiohttp->gradio->paddlehub) (4.3.0)
Requirement already satisfied: attrs>=17.3.0 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from aiohttp->gradio->paddlehub) (22.1.0)
Requirement already satisfied: yarl<2.0,>=1.0 in ./.data/webide/pip/lib/python3.7/site-packages (from aiohttp->gradio->paddlehub) (1.8.2)
Requirement already satisfied: entrypoints in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from altair->gradio->paddlehub) (0.4)
Requirement already satisfied: jsonschema>=3.0 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from altair->gradio->paddlehub) (4.16.0)
Requirement already satisfied: toolz in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from altair->gradio->paddlehub) (0.12.0)
Requirement already satisfied: future>=0.6.0 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from bce-python-sdk->visualdl>=2.0.0->paddlehub) (0.18.0)
Requirement already satisfied: starlette==0.22.0 in ./.data/webide/pip/lib/python3.7/site-packages (from fastapi->gradio->paddlehub) (0.22.0)
Requirement already satisfied: anyio<5,>=3.4.0 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from starlette==0.22.0->fastapi->gradio->paddlehub) (3.6.1)
Requirement already satisfied: rfc3986[idna2008]<2,>=1.3 in ./.data/webide/pip/lib/python3.7/site-packages (from httpx->gradio->paddlehub) (1.5.0)
Requirement already satisfied: httpcore<0.17.0,>=0.15.0 in ./.data/webide/pip/lib/python3.7/site-packages (from httpx->gradio->paddlehub) (0.16.2)
Requirement already satisfied: sniffio in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from httpx->gradio->paddlehub) (1.3.0)
Requirement already satisfied: mdurl~=0.1 in ./.data/webide/pip/lib/python3.7/site-packages (from markdown-it-py[linkify,plugins]->gradio->paddlehub) (0.1.2)
Requirement already satisfied: mdit-py-plugins in ./.data/webide/pip/lib/python3.7/site-packages (from markdown-it-py[linkify,plugins]->gradio->paddlehub) (0.3.3)
Requirement already satisfied: linkify-it-py~=1.0 in ./.data/webide/pip/lib/python3.7/site-packages (from markdown-it-py[linkify,plugins]->gradio->paddlehub) (1.0.3)
Requirement already satisfied: dill>=0.3.3 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from multiprocess->paddlenlp>=2.0.0->paddlehub) (0.3.3)
Requirement already satisfied: scikit-learn>=0.21.3 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from seqeval->paddlenlp>=2.0.0->paddlehub) (0.22.1)
Requirement already satisfied: h11>=0.8 in ./.data/webide/pip/lib/python3.7/site-packages (from uvicorn->gradio->paddlehub) (0.14.0)
Requirement already satisfied: pkgutil-resolve-name>=1.3.10 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from jsonschema>=3.0->altair->gradio->paddlehub) (1.3.10)
Requirement already satisfied: importlib-resources>=1.4.0 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from jsonschema>=3.0->altair->gradio->paddlehub) (5.9.0)
Requirement already satisfied: pyrsistent!=0.17.0,!=0.17.1,!=0.17.2,>=0.14.0 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from jsonschema>=3.0->altair->gradio->paddlehub) (0.18.1)
Requirement already satisfied: uc-micro-py in ./.data/webide/pip/lib/python3.7/site-packages (from linkify-it-py~=1.0->markdown-it-py[linkify,plugins]->gradio->paddlehub) (1.0.1)
Requirement already satisfied: joblib>=0.11 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from scikit-learn>=0.21.3->seqeval->paddlenlp>=2.0.0->paddlehub) (0.14.1)
Requirement already satisfied: scipy>=0.17.0 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from scikit-learn>=0.21.3->seqeval->paddlenlp>=2.0.0->paddlehub) (1.3.0)
Requirement already satisfied: zipp>=0.5 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from importlib-metadata->click>=5.1->flask>=1.1.0->paddlehub) (3.8.1)
Installing collected packages: tqdm
  Attempting uninstall: tqdm
    Found existing installation: tqdm 4.48.2
    Uninstalling tqdm-4.48.2:
      Successfully uninstalled tqdm-4.48.2
[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.
sahi 0.10.1 requires tqdm>=4.48.2, but you have tqdm 4.27.0 which is incompatible.[0m[31m
[0mSuccessfully installed tqdm-4.27.0
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
# 获取模型,用于生成文本
!hub install ernie_zeus
  • 1
  • 2
/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/setuptools/depends.py:2: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses
  import imp
[32m[2022-12-20 15:39:05,406] [    INFO][0m - Module ernie_zeus already installed in /home/aistudio/.paddlehub/modules/ernie_zeus[0m
[0m
  • 1
  • 2
  • 3
  • 4
# 获取模型,用于生成图片
!hub install ernie_vilg
  • 1
  • 2
/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/setuptools/depends.py:2: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses
  import imp
[32m[2022-12-20 15:39:12,197] [    INFO][0m - Module ernie_vilg already installed in /home/aistudio/.paddlehub/modules/ernie_vilg[0m
[0m
  • 1
  • 2
  • 3
  • 4

2.2 第二步:导入一些包

  • 这些包在后面调用文心开放API的例子中也会用到
# 导入需要的包
#import json
import PIL.Image as Image
import random
#import numpy as np
from io import BytesIO
#import base64
import requests
import matplotlib.pyplot as plt
#import cv2
import os
import shutil

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

2.3 第三步:想一个标题,让AI来创作文章

# 由于api'发生变更,调用文心模型需要ak和sk,需要到文心官网申请ak和sk,网址:wenxin.baidu.com
# 我这里把ak和sk放到了一个文件里,请使用自己申请到的ak和sk
# 文件内只有两行,形如    ak = XXXXX
wx_ak = ""
wx_sk = ""
wenxin_apicfg = "wenxin.baidu.com"
with open(wenxin_apicfg) as f:
    i = 0    # 行计数,只读取2行
    for line in f:
        i += 1
        if i>2: break
        lbl,val = line.strip().split("=")
        lbl = lbl.strip()
        val = val.strip()
        if lbl == "ak":
            wx_ak = val
        elif lbl == "sk":
            wx_sk = val
        # print(line)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
# paddlehub,创作文章
import paddlehub as hub

# 加载模型
model = hub.Module(name='ernie_zeus',ak = wx_ak,sk = wx_sk)
txt_title = "小猴和桃子"
txt_tail = "小猴爬到树上吃到了桃子"
input_dict = {
    "text": f"题目:《{txt_title}》\n\n结局:{txt_tail}\n\n正文:",
    "seq_len": 512,
    "topp": 0.5,
    "penalty_score": 2.0,
    "min_dec_len": 128,
    "is_unidirectional": True,
    "task_prompt": "novel",
    "mask_type":"paragraph",
    "min_dec_penalty_text":txt_tail,
    "stop_token":txt_tail
}
# 作文创作
result = model.custom_generation(**input_dict)
txt_content = result
print(txt_content)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
一天,森林里的动物们都在为过新年而忙碌着。有些动物准备打扫卫生、做游戏;还有许多动物要买食品和礼物送给自己亲爱的家人或朋友。大象伯伯也不例外。他刚从集市回来就开始清理房间啦!它先把报纸铺平,然后再拿出抹布擦地板,接下去又用拖把仔细地拖干净每个角落……最后才请小猴子帮助自己搬东西呢!可是这只淘气包总喜欢玩耍,于是便想了一个办法—让桃树爷爷变成孙悟空站到上面当“千斤顶”,好爬得更高点儿吃掉那些桃子。果真如此,没几分钟工夫,小猴子已经坐在枝头享受起美味的水蜜桃了。
  • 1

2.4 第四步:让AI来生成摘要

  • 摘要不能太长,后面要用摘要生成图片,参数长度有限制
# paddlehub,生成摘要
import paddlehub as hub

# 加载模型
model = hub.Module(name='ernie_zeus',ak = wx_ak,sk = wx_sk)
input_dict = {
    "text": f"文章:{txt_content}”\n\n摘要:",
    "seq_len": 64-len(txt_title)-6,    # 限制摘要长度,后面生成图片的输入参数不能太长
    "topp": 0.0,
    "penalty_score": 1.0,
    "min_dec_len": 4,
    "is_unidirectional": 0,
    "task_prompt": "Summarization"
}
# 文本摘要
result = model.custom_generation(**input_dict)
txt_smr = result
print(txt_smr)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
一天,森林里的动物们都在为过新年而忙碌着。有些动物准备打扫卫生、做游戏;还有许多动物要买食品和礼物送给自
  • 1

2.5 第五步:让AI来给文章配图

# 定义一个用于显示图片的函数
def show_pic(pic):
    plt.figure(dpi = 144)
    plt.axis('off')
    plt.imshow(pic)
  • 1
  • 2
  • 3
  • 4
  • 5
# paddlehub,生成图片
import paddlehub as hub    # 导入paddlehub
ernie_vilg_module = hub.Module(name='ernie_vilg',ak=wx_ak,sk=wx_sk)    # 导入模型
if os.path.exists("./imgs/"):shutil.rmtree("./imgs/")    # 删除文件夹 
input_txt = f"儿童画,简笔画,插画,《{txt_title},{txt_smr}》"
results = ernie_vilg_module.generate_image(
    text_prompts=input_txt,    # 提示词
    style="油画",    # 图片类型
    topk = 10,    # 图片数量,最大10
    visualization = 1,
    output_dir="./imgs/")    # 图片保存目录
# 返回的results 就是图片列表,PIL的Image格式

# 将结果显示出来
for pic in results:
    show_pic(pic)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
HBox(children=(IntProgress(value=0), HTML(value='')))


Saving Images...
Done
  • 1
  • 2
  • 3
  • 4
  • 5

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

2.6 第六步:简单生成个HTML文档

  • doc.html 作为模板
  • 将生成的doc1.html和文件夹imgs下载到本地,使用浏览器打开doc1.html即可看到页面
# 重命名图片
def rename_pics(path):
    file_list=os.listdir(path)
    i=0
    for fname in file_list:
        ex_name = fname[fname.index('.'):]    # 扩展名
        old_name = os.path.join(path,fname)
        new_name = str(i)+ex_name
        new_name = os.path.join(path,new_name)
        os.rename(old_name,new_name)
        i+=1

rename_pics("./imgs/")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
# 生成HTML文档
doc_template = open("./doc.html")
doc_file = "doc1.html"
img_uri = "./imgs/0.png"
if(os.path.exists(doc_file)):os.remove(doc_file)    # 删除已有的文件
with open(doc_file,"w",encoding='utf-8') as f:
    for line in doc_template:
        f.write(
            line.replace(
                "{{page_title}}",txt_title).replace(
                    "{{txt_title}}", txt_title).replace(
                        "{{txt_smr}}", "【文章摘要】"+txt_smr).replace(
                            "{{txt_content}}","【正文】"+txt_content).replace(
                                "{{txt_img}}",img_uri)
                )
doc_template.close()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

三、使用文心开放API来生成图文

  • 需要先去文心官网申请ak和sk,官网地址:https://wenxin.baidu.com

3.1 第一步:安装文心开放API

# 安装文心开放api接口
!pip install --upgrade wenxin_api
  • 1
  • 2
Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple
Requirement already satisfied: wenxin_api in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (0.1.3)
Requirement already satisfied: tqdm in ./.data/webide/pip/lib/python3.7/site-packages (from wenxin_api) (4.27.0)
Requirement already satisfied: requests>=2.20 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from wenxin_api) (2.24.0)
Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from requests>=2.20->wenxin_api) (1.25.6)
Requirement already satisfied: chardet<4,>=3.0.2 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from requests>=2.20->wenxin_api) (3.0.4)
Requirement already satisfied: idna<3,>=2.5 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from requests>=2.20->wenxin_api) (2.8)
Requirement already satisfied: certifi>=2017.4.17 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from requests>=2.20->wenxin_api) (2019.9.11)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

3.2 第二步:配置开放api接口

# 开放api接口配置
import wenxin_api # 可以通过"pip install wenxin-api"命令安装

# 我这里把ak和sk放到了一个文件里,请使用自己申请到的ak和sk
# 文件内只有两行,形如    ak = XXXXX
wenxin_apicfg = "wenxin.baidu.com"    # api 配置文件
with open(wenxin_apicfg) as f:
    i = 0    # 行计数,只读取2行
    for line in f:
        i += 1
        if i>2: break
        lbl,val = line.strip().split("=")
        lbl = lbl.strip()
        val = val.strip()
        if lbl == "ak":
            wenxin_api.ak = val
        elif lbl == "sk":
            wenxin_api.sk = val
        # print(line)
#print(f"wenxin_ak:{wenxin_api.ak}\nwenxin_sk:{wenxin_api.sk}")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

3.3 第三步:想一个标题,让AI来创作文章

# 开放API,生成文章
# -*- coding: utf-8 -*
import wenxin_api # 可以通过"pip install wenxin-api"命令安装
from wenxin_api.tasks.composition import Composition
#wenxin_api.ak = ""
#wenxin_api.sk = ""
txt_title = "小猴和桃子"
txt_tail = "小猴爬到树上吃到了桃子"
input_dict = {
    "text": f"题目:{txt_title}\n正文:",
    "seq_len": 512,
    "topp": 0.9,
    "penalty_score": 1.2,
    "min_dec_len": 128,
    "is_unidirectional": 0,
    "task_prompt": "novel",
    "mask_type":"paragraph"
}
rst = Composition.create(**input_dict)
txt_content = rst["result"]
print(txt_content)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
2022-12-20 15:44:35,210 - model 1: starts writing
有一个小猴子,喜欢吃桃。你不给它吃,就在地上打滚耍赖,撅着屁股玩儿起了尿盆:“我要喝水!”
又来到了果园里面,很多人都拿出各种奇形怪状的东西向他砸过去。也没见什么稀罕物件,便笑着跑开了;再后退两步看仔细些才发现自己还站在那些成年人跟前呢,赶紧走吧趁这机会能逃掉算好运气啦。可是谁让身体内流淌着猩红鲜血和荷尔蒙汗液捏?
  • 1
  • 2
  • 3

3.4 第四步:让AI来生成摘要

# 开放API,获取摘要
# -*- coding: utf-8 -*
import wenxin_api # 可以通过"pip install wenxin-api"命令安装
from wenxin_api.tasks.summarization import Summarization
#wenxin_api.ak = ""
#wenxin_api.sk = ""

input_dict = {
    "text": f"文章:{txt_content}”\n\n摘要:",
    "seq_len": 55,
    "topp": 0.0,
    "penalty_score": 1.0,
    "min_dec_len": 4,
    "is_unidirectional": 0,
    "task_prompt": "Summarization"
}
rst = Summarization.create(**input_dict)
txt_smr = rst["result"]
print(txt_smr)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
2022-12-20 15:45:27,908 - model 1: starts writing
“我们的身体里流淌着猩红鲜血和荷尔蒙汗液。”
  • 1
  • 2

3.5 让AI来给文章配图

# 图片显示函数
def show_img(img_path):
    response = requests.get(img_path) #图片地址
    response = response.content
    BytesIOObj = BytesIO()
    BytesIOObj.write(response)
    img = Image.open(BytesIOObj)
    #img = cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)
    #img = img.resize((120,120))
    #plt.figure(dpi = 300)
    plt.figure(dpi = 144)
    plt.axis('off')
    plt.imshow(img) 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
# 开放API,生成图片
# -*- coding: utf-8 -*
import wenxin_api # 可以通过"pip install wenxin-api"命令安装
from wenxin_api.tasks.text_to_image import TextToImage
#wenxin_api.ak = ""
#wenxin_api.sk = ""

input_txt = f"儿童画,简笔画,插画,《{txt_title},{txt_smr}》"
input_dict = {
    "text": input_txt,
    "style": "油画",
    "num": "4"
}
rst = TextToImage.create(**input_dict)    # 转换成关键字参数传递给接口
# rst dict类型
#print(rst)

# 显示图片
imgUrls = rst["imgUrls"]    # 提取图片地址,list格式

for imurl in imgUrls:
    #print(imurl)
    show_img(imurl)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
2022-12-20 15:47:12,890 - model is painting now!, taskId: 11671300, waiting: 3m
2022-12-20 15:47:33,234 - model is painting now!, taskId: 11671300, waiting: 30s
  • 1
  • 2

0 - model is painting now!, taskId: 11671300, waiting: 3m
2022-12-20 15:47:33,234 - model is painting now!, taskId: 11671300, waiting: 30s

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

3.6 简单生成个HTML文档

  • 使用文心开放API返回来的直接就是图片的链接,可以直接用
  • 把生成的doc1.html下载到本地,用浏览器打开即可看到页面
# 生成HTML文档
doc_template = open("./doc.html")
doc_file = "doc1.html"
img_uri = imgUrls[0]
if(os.path.exists(doc_file)):os.remove(doc_file)    # 删除已有的文件
with open(doc_file,"w",encoding='utf-8') as f:
    for line in doc_template:
        f.write(
            line.replace(
                "{{page_title}}",txt_title).replace(
                    "{{txt_title}}", txt_title).replace(
                        "{{txt_smr}}", "【文章摘要】"+txt_smr).replace(
                            "{{txt_content}}","【正文】"+txt_content).replace(
                                "{{txt_img}}",img_uri)
                )
doc_template.close()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

四、总结

  • 只需要要给题目,剩下的事情完全交给AI
  • 现在生成的图文还不是很理想
  • 但是随着模型的迭代,也许真会有那么一天,你给孩子买的绘本其实是AI创作的
  • 这个实验项目的最大问题是需要反复调用模型
  • 生成HTML仍然需要自己处理,如果AI能够把这个活儿也给干了,就完美了
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/614796
推荐阅读
相关标签
  

闽ICP备14008679号