ChatGPT + Stable Diffusion + 百度AI + MoviePy 實(shí)現(xiàn)文字生成視頻,小說轉(zhuǎn)視頻,自媒體神器!(二) 前言
最近大模型頻出,但是對于我們普通人來說,如何使用這些AI工具來輔助我們的工作呢,或者參與進(jìn)入我們的生活,就著現(xiàn)在比較熱門的幾個(gè)AI,寫個(gè)一個(gè)提高生產(chǎn)力工具,現(xiàn)在在邏輯上已經(jīng)走通了,后面會(huì)針對web頁面、后臺(tái)進(jìn)行優(yōu)化。
github鏈接
B站教程視頻 https://www.bilibili.com/video/BV18M4y1H7XN/
第三步、調(diào)用百度語音合成包進(jìn)行語音合成
這里不是智能用百度的API合成,想谷歌的,阿里云的都可以,只是我比較熟悉百度的API ps~: 關(guān)鍵是免費(fèi)??
class Main:
client_id = client_id
client_secret = client_secret
def create_access_token(self):
url = f"https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={self.client_id}&client_secret={self.client_secret}"
payload = ""
headers = {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
response = requests.request("POST", url, headers=headers, data=payload)
print("-----------向百度獲取 access_token API 發(fā)起請求了-----------")
access_token = response.json()
access_token.update({"time": datetime.now().strftime("%Y-%m-%d")})
with open('access_token.json', 'w') as f:
json.dump(access_token, f)
return access_token
def get_access_token(self):
if os.path.exists('access_token.json'):
with open('access_token.json', 'r') as f:
data = json.load(f)
time = data.get("time")
if time and (datetime.now() - datetime.strptime(time, '%Y-%m-%d')).days >= 29:
return self.create_access_token()
return data
return self.create_access_token()
def text_to_audio(self, text: str, index: int):
url = "https://tsn.baidu.com/text2audio"
text = text.encode('utf8')
FORMATS = {3: "mp3", 4: "pcm", 5: "pcm", 6: "wav"}
FORMAT = FORMATS[6]
data = {
# 合成的文本,文本長度必須小于1024GBK字節(jié)。建議每次請求文本不超過120字節(jié),約為60個(gè)漢字或者字母數(shù)字。
"tex": text,
# access_token
"tok": self.get_access_token().get("access_token"),
# 用戶唯一標(biāo)識(shí),用來計(jì)算UV值。建議填寫能區(qū)分用戶的機(jī)器 MAC 地址或 IMEI 碼,長度為60字符以內(nèi)
"cuid": hex(uuid.getnode()),
# 客戶端類型選擇,web端填寫固定值1
"ctp": "1",
# 固定值zh。語言選擇,目前只有中英文混合模式,填寫固定值zh
"lan": "zh",
# 語速,取值0-15,默認(rèn)為5中語速
"spd": 5,
# 音調(diào),取值0-15,默認(rèn)為5中語調(diào)
"pit": 5,
# 音量,基礎(chǔ)音庫取值0-9,精品音庫取值0-15,默認(rèn)為5中音量(取值為0時(shí)為音量最小值,并非為無聲)
"vol": 5,
# (基礎(chǔ)音庫) 度小宇=1,度小美=0,度逍遙(基礎(chǔ))=3,度丫丫=4
# (精品音庫) 度逍遙(精品)=5003,度小鹿=5118,度博文=106,度小童=110,度小萌=111,度米朵=103,度小嬌=5
"per": 5003,
# 3為mp3格式(默認(rèn)); 4為pcm-16k;5為pcm-8k;6為wav(內(nèi)容同pcm-16k); 注意aue=4或者6是語音識(shí)別要求的格式,但是音頻內(nèi)容不是語音識(shí)別要求的自然人發(fā)音,所以識(shí)別效果會(huì)受影響。
"aue": FORMAT
}
data = urllib.parse.urlencode(data)
response = requests.post(url, data)
if response.status_code == 200:
result_str = response.content
save_file = str(index) + '.' + FORMAT
audio = file_path + "audio"
if not os.path.isdir(audio):
os.mkdir(audio)
audio_path = f'{audio}/' + save_file
with open(audio_path, 'wb') as of:
of.write(result_str)
return audio_path
else:
return False
當(dāng)然了,這個(gè)設(shè)計(jì)也是熱拔插的,以后這些數(shù)據(jù)都會(huì)做成動(dòng)態(tài)的,在頁面用戶可以調(diào)整,也可以選擇其他的API服務(wù)商
第四步、調(diào)用百度語音合成包進(jìn)行語音合成
這里就比較麻煩了,首先要搭建起 Stable Diffusion 的環(huán)境,Window 用戶我記得有一個(gè) 繪世
的軟件,一鍵就可以安裝,mac用戶要去官網(wǎng)下載。
class Main:
sd_url = sd_url
def draw_picture(self, obj_list):
"""
:param obj_list:
:return: 圖片地址列表
"""
picture_path_list = []
for index, obj in enumerate(obj_list):
novel_dict = {
"enable_hr": "false",
"denoising_strength": 0,
"firstphase_width": 0,
"firstphase_height": 0,
"hr_scale": 2,
"hr_upscaler": "string",
"hr_second_pass_steps": 0,
"hr_resize_x": 0,
"hr_resize_y": 0,
"prompt": "{}".format(obj["prompt"]),
"styles": [
"string"
],
"seed": -1,
"subseed": -1,
"subseed_strength": 0,
"seed_resize_from_h": -1,
"seed_resize_from_w": -1,
"sampler_name": "DPM++ SDE Karras",
"batch_size": 1,
"n_iter": 1,
"steps": 50,
"cfg_scale": 7,
"width": 1024,
"height": 768,
"restore_faces": "false",
"tiling": "false",
"do_not_save_samples": "false",
"do_not_save_grid": "false",
"negative_prompt": obj["negative"],
"eta": 0,
"s_churn": 0,
"s_tmax": 0,
"s_tmin": 0,
"s_noise": 1,
"override_settings": {},
"override_settings_restore_afterwards": "true",
"script_args": [],
"sampler_index": "DPM++ SDE Karras",
"script_name": "",
"send_images": "true",
"save_images": "true",
"alwayson_scripts": {}
}
html = requests.post(self.sd_url, data=json.dumps(novel_dict))
img_response = json.loads(html.text)
image_bytes = base64.b64decode(img_response['images'][0])
image = Image.open(io.BytesIO(image_bytes))
# 圖片存放
new_path = file_path + 'picture'
if not os.path.exists(new_path):
os.makedirs(new_path)
picture_name = str(obj['index']) + ".png"
image_path = os.path.join(new_path, picture_name)
image.save(image_path)
picture_path_list.append(image_path)
print(f"-----------生成第{index}張圖片-----------")
return picture_path_list
后期我看看能不能引入 Midjuorney 的服務(wù)商,或者他們官方的API ps ~ 做人沒有夢想和咸魚有什么區(qū)別??
第五步、使用moviepy將圖片和語音結(jié)合起來生成視頻
moviepy中文文檔文章來源:http://www.zghlxwxcb.cn/news/detail-628263.html
import os
from moviepy.editor import ImageSequenceClip, AudioFileClip, concatenate_videoclips
import numpy as np
from config import file_path
class Main:
def merge_video(self, picture_path_list: list, audio_path_list: list, name: str):
"""
:param picture_path_list: 圖片路徑列表
:param audio_path_list: 音頻路徑列表
:return:
"""
clips = []
for index, value in enumerate(picture_path_list):
audio_clip = AudioFileClip(audio_path_list[index])
img_clip = ImageSequenceClip([picture_path_list[index]], audio_clip.duration)
img_clip = img_clip.set_position(('center', 'center')).fl(self.fl_up, apply_to=['mask']).set_duration(
audio_clip.duration)
clip = img_clip.set_audio(audio_clip)
clips.append(clip)
print(f"-----------生成第{index}段視頻-----------")
print(f"-----------開始合成視頻-----------")
final_clip = concatenate_videoclips(clips)
new_parent = file_path + "video/"
if not os.path.exists(new_parent):
os.makedirs(new_parent)
final_clip.write_videofile(new_parent + name + ".mp4", fps=24, audio_codec="aac")
def fl_up(self, gf, t):
# 獲取原始圖像幀
frame = gf(t)
# 進(jìn)行滾動(dòng)效果,將圖像向下滾動(dòng)50像素
height, width = frame.shape[:2]
scroll_y = int(t * 10) # 根據(jù)時(shí)間t計(jì)算滾動(dòng)的像素?cái)?shù)
new_frame = np.zeros_like(frame)
# 控制滾動(dòng)的范圍,避免滾動(dòng)超出圖像的邊界
if scroll_y < height:
new_frame[:height - scroll_y, :] = frame[scroll_y:, :]
return new_frame
暫時(shí)就先寫到這里了,后期努力添磚加瓦。 代碼已經(jīng)開源了。鏈接 有什么問題可以在github上或者博客介紹里來問我,byebye~??文章來源地址http://www.zghlxwxcb.cn/news/detail-628263.html
到了這里,關(guān)于ChatGPT + Stable Diffusion + 百度AI + MoviePy 實(shí)現(xiàn)文字生成視頻,小說轉(zhuǎn)視頻,自媒體神器!(二)的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!