(十三)AI作畫(huà)、AI繪畫(huà)、AIGC本地大模型
AI作畫(huà)近期很火,涌現(xiàn)出了很多AIGC(AI內(nèi)容生成)的網(wǎng)站、平臺(tái),但這些平臺(tái)都是使用的云上的算力,基本都有使用的各種限制等。
一、本代碼自動(dòng)將大模型下載本地,可以無(wú)-限-使-用。但是對(duì)硬件的要求較高需要8G顯存以上的顯卡才能快速出圖,用CPU會(huì)很慢的。
【同時(shí),針對(duì)沒(méi)有好顯卡的網(wǎng)友,也編寫(xiě)了一個(gè)調(diào)用云上API的版本:
https://pan.baidu.com/s/1s7B1SAWWoNSdbxXYGTlgDQ 提取碼:8888
遠(yuǎn)程API版本軟件界面:
二、本地模型的版本
下面Python的代碼是本地版本,模型大概6G大小,首次運(yùn)行需要在網(wǎng)絡(luò)較快的電腦運(yùn)行,下載時(shí)間需要半小時(shí)。
主代碼如下:
#AI繪畫(huà)工具_
import os, sys, time
import threading
import webbrowser
import configparser as configparser
from PIL import Image, ImageQt
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QWidget,QMessageBox, QFileDialog,QApplication
from PyQt5.QtCore import Qt, QTimer, QSize
from PyQt5.QtGui import QImage, QPixmap, QIcon
from PyQt5.QtCore import QByteArray
# import hashlib
from AI_Drawing_UI_Local import Ui_Ai_Drawing
import torch
from diffusers import StableDiffusionPipeline
my_title = "AI繪畫(huà)工具"
out_dir = os.path.join(os.path.expanduser("~"), 'Pictures')
out_dir_pic = out_dir
run_flag = 0; Box1_flag = True; Box2_flag = True; Box3_flag = False
filesnums = 1
t0 = time.time()
t1 = time.time()
t2 = time.time()
iii = 0
stop_flag = False
break_flag = False
icanx_path = os.path.join(os.path.expanduser("~"), '.icanx')
if not os.path.exists(icanx_path): os.mkdir(icanx_path)
ini_file = os.path.join(icanx_path,'icanx.ini')
cfg = configparser.ConfigParser()
if not os.path.exists(ini_file):
file = open(ini_file, 'w')
file.write("[APPID]\napiKey=\nsecretKey=\nout_path=\n")
file.close()
cfg.read(ini_file)
out_dir = os.path.join(os.path.expanduser("~"), 'Pictures')
cfg.set('APPID', 'out_path', out_dir) # 注意鍵值是用set()方法
cfg.write(open(ini_file, 'w')) # 一定要寫(xiě)入才生效
sample = [
'日照香爐生紫煙,遙看瀑布掛前川,水墨畫(huà)',
'亭臺(tái)樓榭 中國(guó)畫(huà)',
'楊柳依依 莫奈',
'牧童遙指杏花村 水墨畫(huà)',
'姹紫嫣紅 中國(guó)畫(huà)',
'青山綠水 梵高',
'雄鷹展翅 中國(guó)畫(huà)',
'倒影 寫(xiě)意 油畫(huà) 莫奈',
'孤舟蓑笠翁 水墨畫(huà)',
'萬(wàn)山紅遍 中國(guó)畫(huà)',
'山花爛漫 水彩畫(huà)',
'晚來(lái)天欲雪,能飲一杯無(wú)',
"星空,未來(lái),科技",
'山水,松,石,水墨畫(huà)',
'日出,海面,4k壁紙,復(fù)雜'
]
# def get_md5(src): #調(diào)用云上模型的API使用
# m = hashlib.md5()
# m.update(src.encode('UTF-8'))
# return m.hexdigest()
# def get_stamp():
# timestamp = int(round(time.time() * 1000))
# return str(timestamp)
class MainWin(QWidget, Ui_Ai_Drawing):
def __init__(self):
super(MainWin, self).__init__()
self.setupUi(self)
global run_flag, out_dir
self.createLayout()
data = QByteArray().fromBase64(ico_data.encode())
image = QImage()
#image.loadFromData(data, "my.ico")
pix = QPixmap.fromImage(image)
cfg.read(ini_file)
out_dir = cfg.get('APPID', 'out_path')
self.txt2.setText(out_dir)
self.flash_item_str = ""
self.setWindowIcon(QIcon(pix))
self.setWindowFlags(Qt.WindowMinimizeButtonHint)
self.show(); run_flag = 1
self.total_nums_over = 5
# def show_error(self,str):
# r_button = QMessageBox.question(self, my_title,'\n\n'+str+'\n\n', QMessageBox.Ok)
def show_error(self, str):
infoBox = QMessageBox()
infoBox.setIcon(QMessageBox.Information)
infoBox.setText(str)
infoBox.setStandardButtons(QMessageBox.Ok)
infoBox.button(QMessageBox.Ok).animateClick(10000) # 10秒自動(dòng)關(guān)閉
infoBox.exec_()
def set_False_Btn(self):
self.outButton.setEnabled(False)
self.startButton.setEnabled(False); self.stopButton.setEnabled(True)
self.quitButton.setEnabled(False)
def set_True_Btn(self):
self.outButton.setEnabled(True)
self.startButton.setEnabled(True); self.stopButton.setEnabled(False)
self.quitButton.setEnabled(True)
def startrun(self):
global iii, stop_flag, break_flag, t0, t2
iii = 0
stop_flag = False
break_flag = False
t0 = time.time()
if not os.path.exists(out_dir): self.show_error('輸出目錄不存在,請(qǐng)重新選擇!'); return
self.set_False_Btn()
out_sums = self.spinBox.value()
prompt = self.lineEdit.text()
self.set_text_info('【運(yùn)行信息】 正在初始化AI模型......')
def run_thread():
global iii, stop_flag, break_flag, t0 ,t1, t2
for i in range(out_sums):
iii += 1
t1 = time.time()
if break_flag:
self.txt12.setText('【運(yùn)行信息】 用戶終止了正在運(yùn)行的繪畫(huà)...')
# self.set_True_Btn()
break
torch.backends.cudnn.benchmark = True
pipe = StableDiffusionPipeline.from_pretrained("IDEA-CCNL/Taiyi-Stable-Diffusion-1B-Chinese-v0.1",
torch_dtype=torch.float16,
cache_dir='./model').to('cuda')
image = pipe(prompt, guidance_scale=7.5).images[0]
time_str = str(time.strftime('%Y%m%d@%H-%M-%S', time.localtime(time.time())))
file_name = out_dir + '/' + time_str + '.jpg'
image.save(file_name)
# image = Image.open("11.jpg")
# time.sleep(2)
t2 = time.time()
runinfo = '【運(yùn)行信息】 當(dāng)前繪畫(huà)耗時(shí):%.3f秒 | 總繪畫(huà)耗時(shí):%.1f秒 | 繪畫(huà)個(gè)數(shù):%d' % ((t2 - t1), (t2 - t0), i+1)
self.set_text_info(runinfo)
image = ImageQt.toqimage(image)
piximg = QPixmap.fromImage(image.scaled(QSize(256, 256), Qt.IgnoreAspectRatio))
if i % 3 == 0: self.my_label1.setPixmap(piximg)
if i % 3 == 1: self.my_label2.setPixmap(piximg)
if i % 3 == 2: self.my_label3.setPixmap(piximg)
stop_flag = True
t = threading.Thread(target=run_thread)
t.start()
self.my_timer = QTimer(self)
self.my_timer.start(500)
self.my_timer.timeout.connect(self.set_run_over)
def set_text_info(self, str):
self.txt12.setText(str)
self.flash_item_str = str
def set_run_over(self):
global t0, t1, t2, iii
if stop_flag:
t2 = time.time()
self.txt12.setText('【運(yùn)行信息】 繪畫(huà)完畢!總消耗時(shí)間:%d秒' % (t2 - t0))
self.set_True_Btn()
self.my_timer.stop()
else:
if self.txt12.text() == '【運(yùn)行信息】':
self.txt12.setText(self.flash_item_str)
else:
self.txt12.setText('【運(yùn)行信息】')
# self.txt12.repaint()
def stoprun(self):
global break_flag
r_button = QMessageBox.question(self, my_title,
"\n\n 確定要停止繪畫(huà)過(guò)程嗎?\n\n", QMessageBox.Yes | QMessageBox.No)
if r_button == QMessageBox.Yes: break_flag = True
def getapikeyBT(self):
webbrowser.open("https://fengshenbang-lm.com/document")
def helpWin(self):
str="\n\n\n【軟件設(shè)置】首次使用需要點(diǎn)擊右上角按鈕,此步驟只需操作一次即可;\n" \
"【繪畫(huà)提示】輸入您想得到的繪畫(huà)內(nèi)容、風(fēng)格等信息,可參考體驗(yàn)示例;\n" + \
"【測(cè)試示例】可以直接下拉選擇繪畫(huà)提示語(yǔ),用于初學(xué)者參考;\n"+\
"【輸出目錄】選擇繪畫(huà)文件保存的目錄,默認(rèn)是本機(jī)圖片目錄;\n【查看輸出】點(diǎn)擊打開(kāi)輸出目錄,便于查看繪畫(huà)結(jié)果;\n\n\n"
QMessageBox.question(self, my_title+" 【幫助信息】", str, QMessageBox.Ok)
def quitWin(self):
r_button = QMessageBox.question(self, my_title,
"\n\n退出將終止繪畫(huà)進(jìn)程...... \n\n確認(rèn)退出嗎?\n\n", QMessageBox.Yes | QMessageBox.No)
if r_button == QMessageBox.Yes:
cfg.read(ini_file)
cfg.set('APPID', 'out_path', out_dir) # 注意鍵值是用set()方法
cfg.write(open(ini_file, 'w')) # 一定要寫(xiě)入才生效
sys.exit()
def checkresult(self):
try: os.startfile(out_dir)
except: pass
def outButton_fuc(self):
global out_dir
out_dir = QFileDialog.getExistingDirectory(self,'選擇繪畫(huà)的輸出文件夾', out_dir)
if out_dir == '':
self.txt2.setText(out_dir_pic)
out_dir = out_dir_pic
else: self.txt2.setText(out_dir)
def click_comboBox(self, text):
self.lineEdit.setText(text)
def createLayout(self):
self.my_label1.setAlignment(Qt.AlignCenter)
self.my_label2.setAlignment(Qt.AlignCenter)
self.my_label3.setAlignment(Qt.AlignCenter)
# self.sample_lbl.setPixmap(QPixmap("sample.jpg"))
# self.my_label1.setFixedSize(427, 240); self.my_label2.setFixedSize(427, 240)
self.my_label1.setToolTip("本區(qū)域,顯示的是繪畫(huà)圖片縮略圖...")
self.my_label2.setToolTip("本區(qū)域,顯示的是繪畫(huà)圖片縮略圖...")
self.my_label3.setToolTip("本區(qū)域,顯示的是繪畫(huà)圖片縮略圖...")
self.txt12.setText('【運(yùn)行信息】 可以點(diǎn)擊幫助按鈕,查看使用說(shuō)明..')
self.lineEdit.setText(sample[0])
self.comboBox.addItems(sample)
self.comboBox.activated[str].connect(self.click_comboBox)
self.outButton.setToolTip("選擇輸出文件目錄,繪畫(huà)后的文件將存在此目錄...")
self.outButton.clicked.connect(self.outButton_fuc)
self.stopButton.setEnabled(False)
self.startButton.clicked.connect(self.startrun)
self.stopButton.clicked.connect(self.stoprun)
self.helpButton.clicked.connect(self.helpWin)
self.quitButton.clicked.connect(self.quitWin)
self.check_result.clicked.connect(self.checkresult)
if __name__ == '__main__':
QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
app = QtWidgets.QApplication(sys.argv)
MainWin = MainWin()
sys.exit(app.exec_())
軟件的界面代碼如下:文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-514103.html
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'AI_Drawing_UI_Local.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Ai_Drawing(object):
def setupUi(self, Ai_Drawing):
Ai_Drawing.setObjectName("Ai_Drawing")
Ai_Drawing.setEnabled(True)
Ai_Drawing.resize(864, 651)
font = QtGui.QFont()
font.setFamily("宋體")
font.setPointSize(12)
Ai_Drawing.setFont(font)
Ai_Drawing.setMouseTracking(False)
self.layoutWidget = QtWidgets.QWidget(Ai_Drawing)
self.layoutWidget.setGeometry(QtCore.QRect(320, 595, 531, 41))
self.layoutWidget.setObjectName("layoutWidget")
self.horizontalLayout_5 = QtWidgets.QHBoxLayout(self.layoutWidget)
self.horizontalLayout_5.setContentsMargins(0, 0, 0, 0)
self.horizontalLayout_5.setObjectName("horizontalLayout_5")
self.startButton = QtWidgets.QPushButton(self.layoutWidget)
font = QtGui.QFont()
font.setFamily("宋體")
font.setPointSize(12)
self.startButton.setFont(font)
self.startButton.setObjectName("startButton")
self.horizontalLayout_5.addWidget(self.startButton)
self.stopButton = QtWidgets.QPushButton(self.layoutWidget)
font = QtGui.QFont()
font.setFamily("宋體")
font.setPointSize(12)
self.stopButton.setFont(font)
self.stopButton.setObjectName("stopButton")
self.horizontalLayout_5.addWidget(self.stopButton)
spacerItem = QtWidgets.QSpacerItem(60, 20, QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_5.addItem(spacerItem)
self.helpButton = QtWidgets.QPushButton(self.layoutWidget)
font = QtGui.QFont()
font.setFamily("宋體")
font.setPointSize(12)
self.helpButton.setFont(font)
self.helpButton.setObjectName("helpButton")
self.horizontalLayout_5.addWidget(self.helpButton)
self.quitButton = QtWidgets.QPushButton(self.layoutWidget)
font = QtGui.QFont()
font.setFamily("宋體")
font.setPointSize(12)
self.quitButton.setFont(font)
self.quitButton.setObjectName("quitButton")
self.horizontalLayout_5.addWidget(self.quitButton)
self.groupBox_2 = QtWidgets.QGroupBox(Ai_Drawing)
self.groupBox_2.setGeometry(QtCore.QRect(10, 20, 841, 281))
self.groupBox_2.setContextMenuPolicy(QtCore.Qt.DefaultContextMenu)
self.groupBox_2.setAlignment(QtCore.Qt.AlignCenter)
self.groupBox_2.setObjectName("groupBox_2")
self.my_label1 = QtWidgets.QLabel(self.groupBox_2)
self.my_label1.setGeometry(QtCore.QRect(10, 20, 256, 256))
self.my_label1.setObjectName("my_label1")
self.my_label3 = QtWidgets.QLabel(self.groupBox_2)
self.my_label3.setGeometry(QtCore.QRect(570, 20, 256, 256))
self.my_label3.setObjectName("my_label3")
self.my_label2 = QtWidgets.QLabel(self.groupBox_2)
self.my_label2.setGeometry(QtCore.QRect(290, 20, 256, 256))
self.my_label2.setObjectName("my_label2")
self.groupBox_4 = QtWidgets.QGroupBox(Ai_Drawing)
self.groupBox_4.setGeometry(QtCore.QRect(10, 330, 841, 141))
self.groupBox_4.setAlignment(QtCore.Qt.AlignCenter)
self.groupBox_4.setObjectName("groupBox_4")
self.outButton = QtWidgets.QPushButton(self.groupBox_4)
self.outButton.setGeometry(QtCore.QRect(20, 100, 78, 24))
font = QtGui.QFont()
font.setFamily("宋體")
font.setPointSize(12)
self.outButton.setFont(font)
self.outButton.setObjectName("outButton")
self.txt2 = QtWidgets.QLabel(self.groupBox_4)
self.txt2.setGeometry(QtCore.QRect(110, 102, 771, 20))
self.txt2.setObjectName("txt2")
self.check_result = QtWidgets.QPushButton(self.groupBox_4)
self.check_result.setGeometry(QtCore.QRect(690, 100, 131, 24))
font = QtGui.QFont()
font.setFamily("宋體")
font.setPointSize(12)
self.check_result.setFont(font)
self.check_result.setObjectName("check_result")
self.txt2_2 = QtWidgets.QLabel(self.groupBox_4)
self.txt2_2.setGeometry(QtCore.QRect(20, 60, 81, 20))
self.txt2_2.setObjectName("txt2_2")
self.txt2_3 = QtWidgets.QLabel(self.groupBox_4)
self.txt2_3.setGeometry(QtCore.QRect(20, 30, 81, 20))
self.txt2_3.setObjectName("txt2_3")
self.lineEdit = QtWidgets.QLineEdit(self.groupBox_4)
self.lineEdit.setGeometry(QtCore.QRect(100, 30, 551, 20))
self.lineEdit.setObjectName("lineEdit")
self.comboBox = QtWidgets.QComboBox(self.groupBox_4)
self.comboBox.setGeometry(QtCore.QRect(100, 60, 551, 22))
self.comboBox.setObjectName("comboBox")
self.spinBox = QtWidgets.QSpinBox(self.groupBox_4)
self.spinBox.setGeometry(QtCore.QRect(770, 30, 51, 22))
self.spinBox.setMinimum(1)
self.spinBox.setStepType(QtWidgets.QAbstractSpinBox.DefaultStepType)
self.spinBox.setProperty("value", 3)
self.spinBox.setDisplayIntegerBase(10)
self.spinBox.setObjectName("spinBox")
self.txt2_4 = QtWidgets.QLabel(self.groupBox_4)
self.txt2_4.setGeometry(QtCore.QRect(690, 30, 81, 20))
self.txt2_4.setObjectName("txt2_4")
self.groupBox_5 = QtWidgets.QGroupBox(Ai_Drawing)
self.groupBox_5.setGeometry(QtCore.QRect(10, 500, 841, 61))
self.groupBox_5.setAlignment(QtCore.Qt.AlignCenter)
self.groupBox_5.setObjectName("groupBox_5")
self.txt12 = QtWidgets.QLabel(self.groupBox_5)
self.txt12.setGeometry(QtCore.QRect(20, 25, 861, 21))
self.txt12.setObjectName("txt12")
self.retranslateUi(Ai_Drawing)
QtCore.QMetaObject.connectSlotsByName(Ai_Drawing)
def retranslateUi(self, Ai_Drawing):
_translate = QtCore.QCoreApplication.translate
Ai_Drawing.setWindowTitle(_translate("Ai_Drawing", "iCANX AI繪畫(huà)工具"))
self.startButton.setText(_translate("Ai_Drawing", "開(kāi)始處理"))
self.stopButton.setText(_translate("Ai_Drawing", "停止處理"))
self.helpButton.setText(_translate("Ai_Drawing", "幫助"))
self.quitButton.setText(_translate("Ai_Drawing", "退出"))
self.groupBox_2.setTitle(_translate("Ai_Drawing", "預(yù)覽窗口"))
self.my_label1.setText(_translate("Ai_Drawing", " 【AI繪畫(huà)縮略圖顯示區(qū)域】"))
self.my_label3.setText(_translate("Ai_Drawing", " 【AI繪畫(huà)縮略圖顯示區(qū)域】"))
self.my_label2.setText(_translate("Ai_Drawing", " 【AI繪畫(huà)縮略圖顯示區(qū)域】"))
self.groupBox_4.setTitle(_translate("Ai_Drawing", "文件設(shè)置"))
self.outButton.setText(_translate("Ai_Drawing", "輸出目錄"))
self.txt2.setText(_translate("Ai_Drawing", "輸出目錄"))
self.check_result.setText(_translate("Ai_Drawing", "查看繪畫(huà)圖片"))
self.txt2_2.setText(_translate("Ai_Drawing", "體驗(yàn)示例:"))
self.txt2_3.setText(_translate("Ai_Drawing", "繪畫(huà)提示:"))
self.txt2_4.setText(_translate("Ai_Drawing", "輸出數(shù)量:"))
self.groupBox_5.setTitle(_translate("Ai_Drawing", "信息統(tǒng)計(jì)"))
self.txt12.setText(_translate("Ai_Drawing", "【運(yùn)行信息】"))
三、最后
上訴代碼沒(méi)有任何刪節(jié),可以直接運(yùn)行?;镜囊蕾?lài)庫(kù)還是要自己安裝的,看import就知道要安裝哪些庫(kù)了。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-514103.html
到了這里,關(guān)于(十三)AI作畫(huà)、AI繪畫(huà)、AIGC本地大模型的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!