ChatGPT + Stable Diffusion + 百度AI + MoviePy 实现文字生成视频,小说转视频,自媒体神器!(一)

ChatGPT + Stable Diffusion + 百度AI + MoviePy 实现文字生成视频,小说转视频,自媒体神器!(一)

前言

最近大模型频出,但是对于我们普通人来说,如何使用这些AI工具来辅助我们的工作呢,或者参与进入我们的生活,就着现在比较热门的几个AI,写个一个提高生产力工具,现在在逻辑上已经走通了,后面会针对web页面、后台进行优化。

github链接 https://github.com/Anning01/TextCreateVideo
B站教程视频 https://www.bilibili.com/video/BV18M4y1H7XN/

那么从一个用户输入文本到生成视频,我分成了五个步骤来做。

其中2、3 和 4 没有关系,后期做成异步并行。

第一步、将用户输入的文本进行段落切割。

我这里默认用户输入的为txt文件,也是建议一章一章来,太大并不是不可以执行,只是时间上耗费太多,当然4080用户除外!

python 复制代码
from config import file_path


class Main:

    def txt_handle(self, filepath):
        """
        txt文件处理
        :return:
        """
        file = open(file_path + filepath, 'r')
        content = file.read().replace('\n', '')
        return content.split('。')

这里比较简单,现在也没有做前端页面,现在将文件放在指定的目录下,会将txt文件按照中文"。"来切片。后期考虑有传整本的需求,会加上数据库进行持久化,按照章节区分,按章节来生成视频。


第二步、使用chatGPT生成提示词

我ChatGPT的免费调用API次数没了,最优选肯定是原生调用ChatGPT的api,但是没有这个条件,我选择了一些提供ChatGPT的API中间商

fastapi 和 API2D

python 复制代码
from SDK.ChatGPT.FastGPT.app import Main as FM
from SDK.ChatGPT.API2D.app import Main as AM
from config import apikey, appId, ForwardKey


class Main:

    # 默认反向提升词
    negative = "NSFW,sketches, (worst quality:2), (low quality:2), (normal quality:2), lowres, normal quality, ((monochrome)), ((grayscale)), skin spots, acnes, skin blemishes, bad anatomy,(long hair:1.4),DeepNegative,(fat:1.2),facing away, looking away,tilted head, {Multiple people}, lowres,bad anatomy,bad hands, text, error, missing fingers,extra digit, fewer digits, cropped, worstquality, low quality, normal quality,jpegartifacts,signature, watermark, username,blurry,bad feet,cropped,poorly drawn hands,poorly drawn face,mutation,deformed,worst quality,low quality,normal quality,jpeg artifacts,signature,watermark,extra fingers,fewer digits,extra limbs,extra arms,extra legs,malformed limbs,fused fingers,too many fingers,long neck,cross-eyed,mutated hands,polar lowres,bad body,bad proportions,gross proportions,text,error,missing fingers,missing arms,missing legs,extra digit, extra arms, extra leg, extra foot,"
    # 默认提示词
    prompt = "best quality,masterpiece,illustration, an extremely delicate and beautiful,extremely detailed,CG,unity,8k wallpaper, "

    def create_prompt_words(self, text_list: list):
        """
        生成英文提示词
        :return: [{prompt, negative, text, index},...]
        """
        # 包含着 坐标、英文提示词、英文反向提示词、中文文本 列表
        data = []
        instance_class_list = []
        if all([apikey, appId]):
            instance_class_list.append(FM())
        if ForwardKey:
            instance_class_list.append(AM())
        for index, value in enumerate(text_list):
            prompt = instance_class_list[0].prompt_generation_chatgpt(value)
            if not prompt:
                if len(instance_class_list) >= 1:
                    instance_class_list.pop(0)
                    prompt = instance_class_list[0].prompt_generation_chatgpt(value)
                    if not prompt:
                        print("------fastgpt和API2D都无法使用---------")
                        raise Exception("请检查代码")
                else:
                    print("------fastgpt和API2D都无法使用---------")
                    raise Exception("请检查代码")
            print(f"-----------生成第{index}段提示词-----------")
            data.append({
                "index": index,
                "text": value,
                "prompt": self.prompt + prompt,
                "negative": self.negative,
            })
        return data

我将两个api接口做成插件式的,并且保证一个坏了可以去使用另一个

fastGPT

python 复制代码
class Main:
    apikey = apikey
    appId = appId
    url = "https://fastgpt.run/api/openapi/v1/chat/completions"

    def prompt_generation_chatgpt(self, param):
        # 发送HTTP POST请求
        headers = {
            'Content-Type': 'application/json',
            'User-Agent': 'Apifox/1.0.0 (https://www.apifox.cn)',
            'Authorization': f'Bearer {self.apikey}-{self.appId}'
        }
        data = {
            "stream": False,
            # "chatId": "3232",
            "messages": [
                {
                    "content": '根据下面的内容描述,生成一副画面并用英文单词表示:' + param,
                    "role": "user"
                }
            ]
        }
        json_data = json.dumps(data)
        # 发送HTTP POST请求
        response = requests.post(self.url, data=json_data, headers=headers)
        result_json = json.loads(response.text)
        if response.status_code != 200:
            print("-----------FastAPI出错了-----------")
            return False
        # 输出结果
        return result_json['responseData'][0]['answer']

API2D

python 复制代码
import requests
from config import ForwardKey


class Main:
    ForwardKey = ForwardKey
    url = "https://openai.api2d.net/v1/chat/completions"

    def prompt_generation_chatgpt(self, param):
        # 发送HTTP POST请求
        headers = {
            'Content-Type': 'application/json',
            'Authorization': f'Bearer {ForwardKey}'
            # <-- 把 fkxxxxx 替换成你自己的 Forward Key,注意前面的 Bearer 要保留,并且和 Key 中间有一个空格。
        }
        data = {
            "model": "gpt-3.5-turbo",
            "messages": [{"role": "user", "content": '根据下面的内容描述,生成一副画面并用英文单词表示:' + param, }]
        }
        response = requests.post(self.url, headers=headers, json=data)
        print("-----------进入API2D-----------")
        if response.status_code != 200:
            return False
        # 发送HTTP POST请求
        result_json = response.json()
        # 输出结果
        return result_json["choices"][0]["message"]["content"]
相关推荐
love530love4 小时前
【笔记】 Podman Desktop 中部署 Stable Diffusion WebUI (GPU 支持)
人工智能·windows·笔记·python·容器·stable diffusion·podman
迈火2 天前
PuLID_ComfyUI:ComfyUI中的图像生成强化插件
开发语言·人工智能·python·深度学习·计算机视觉·stable diffusion·语音识别
你好~每一天2 天前
2025 中小企业 AI 转型:核心岗技能 “怎么证、怎么用”?
人工智能·百度·数据挖掘·数据分析·职业·转行
realhuizhu2 天前
国庆收心指南:用AI提示词工程解决节后综合征
人工智能·ai·chatgpt·prompt·提示词·deepseek·假期综合征·节后综合征
yueyuebaobaoxinx2 天前
人机共生:生成式 AI 重构内容创作的机遇与博弈
人工智能·chatgpt·重构
张较瘦_2 天前
[论文阅读] AI+教学 | 编程入门课的AI助手革命?ChatGPT的4大核心影响全解析
论文阅读·人工智能·chatgpt
ding_zhikai2 天前
SD:在一个 Ubuntu 系统安装 stable diffusion Web UI
前端·ubuntu·stable diffusion
不当菜鸡的程序媛2 天前
Stable Diffusion里面Cross-Attention设计:为啥Q来自图像/噪声,K和V来自文本
人工智能·计算机视觉·stable diffusion
文火冰糖的硅基工坊5 天前
[创业之路-666]:第四次工业革命(智能革命)未来将创造大量的财富,普通人通过哪些方式参与这些财富的创造与分享?
人工智能·chatgpt·系统架构·产品运营·产业链
低调小一5 天前
iPhone美区账号登录指南:轻松下载ChatGPT应用
ios·chatgpt·iphone