当前位置: 首页 > news >正文

【Liblib】基于LiblibAI自定义模型,总结一下Python开发步骤

一、前言

Liblib AI(哩布哩布 AI)是一个集成了先进人工智能技术和用户友好设计的 AI 图像创作绘画平台和模型分享社区。

  • 强大的图像生成能力 :以 Stable Diffusion 技术为核心,提供文生图、图生图、图像后期处理等功能,支持多种模型和风格特征的模型(LoRA 模型),并允许用户进行面部修复和高清修复等操作。
  • 丰富的模型素材库 :拥有 10 万 + 的模型库,涵盖插画、摄影、3D 立体、商品摄影、设计、数字艺术、油画、水彩、二次元等 300 多种风格,用户可训练专属 LoRA 模型并参与社区互动。
  • 多端支持 :除了电脑端,还有手机端 APP,用户可以通过手机号验证登录使用,APP 版本具备 AI 绘画、AI 写作、AI 音频合成等功能。

Liblib是个图像ai平台,有根据文字生成图片,修复图片,图片重绘等多种功能。

LiblibAI官网:LiblibAI-哩布哩布AI - 中国领先的AI创作平台

LiblibAI开放平台文档:Docs

API试用计划:登录后可领取500试用积分,限时7天免费测试体验。

二、准备

1、首先要去官网注册一个账号并登录。

2、在官网首页左侧导航栏有API开发平台的菜单,点击进去,记得先登录账号。

 3、点击进去会看到两个使用api平台需要用到的key,把这两个key复制出来保存好。

三、主要步骤:

1、获取AccessKey与SecretKey

2、使用秘钥,获取网址必要的参数

3、请求网址,基于文生图参数,获取任务id

4、请求网址,基于任务id,获取图片网址

四、具体操作

1、接口网址

Liblib开放平台域名:https://openapi.liblibai.cloud(无法直接打开,需配合密钥访问)

2、生成API密钥

在登录Liblib领取API试用积分或购买API积分后,Liblib会生成开放平台访问密钥,用于后续API接口访问,密钥包括:​

  • AccessKey,API访问凭证,唯一识别访问用户,长度通常在20-30位左右,如:KIQMFXjHaobx7wqo9XvYKA​
  • SecretKey,API访问密钥,用于加密请求参数,避免请求参数被篡改,长度通常在30位以上,如:KppKsn7ezZxhi6lIDjbo7YyVYzanSu2d​

3、使用密钥​获取网址必要的参数

申请API密钥之后,需要在每次请求API接口的查询字符串中固定传递以下参数:​



如请求地址:https://test.xxx.com/api/genImg?AccessKey=KIQMFXjHaobx7wqo9XvYKA&Signature=test1232132&Timestamp=1725458584000&SignatureNonce=random1232

4、Python生成密码代码:

# 请求API接口的uri地址
text2img_uri = "/api/generate/webui/text2img"def make_sign(uri):"""生成签名"""# 当前毫秒时间戳timestamp = str(int(time.time() * 1000))# 随机字符串signature_nonce = str(uuid.uuid4()).replace('-', '')# 拼接请求数据content = '&'.join((uri, timestamp, signature_nonce))# 生成签名digest = hmac.new(SECRET_KEY.encode(), content.encode(), sha1).digest()# 移除为了补全base64位数而填充的尾部等号sign = base64.urlsafe_b64encode(digest).rstrip(b'=').decode()return sign, timestamp, signature_nonce

注意:uri要与调用的接口保持一致

5、Python调用接口代码:

def call_liblibai_api():generateUuid = ""# 生成签名sign, timestamp, signature_nonce = make_sign(text2img_uri)# 准备请求参数uri = 'https://openapi.liblibai.cloud/api/generate/webui/text2img'  # 根据API地址更新uriuri = f"{uri}?AccessKey={ACCESS_KEY}&Signature={sign}&Timestamp={timestamp}&SignatureNonce={signature_nonce}"print(uri)headers = {'Content-Type': 'application/json'}data = {"templateUuid": "e10adc3949ba59abbe56e057f20f883e","generateParams": {"checkPointId": "ba34a22f1c044472a42b6051aac2afb3","prompt": "This is a 12-story hospital building. The ground floor houses the emergency room and pharmacy. The entrance is spacious and has a sheltered structure. Each floor from the second to the twelfth floor has a ward area, including a nurse station, ward Windows, and space for placing medical equipment. The building's exterior is simple, with Windows arranged regularly. From the outside, a clear 12-story structure can be seen.","negativePrompt": "ng_deepnegative_v1_75t,(badhandv4:1.2),EasyNegative,(worst quality:2),","sampler": 15,"steps": 20,"cfgScale": 7,"width": 768,"height": 1024,"imgCount": 1,"randnSource": 0,"seed": 2228967414,"restoreFaces": 0,"hiResFixInfo": {"hiresSteps": 20,"hiresDenoisingStrength": 0.75,"upscaler": 10,"resizedWidth": 1024,"resizedHeight": 1536}}}try:# 发送POST请求response = requests.post(uri, headers=headers, data=json.dumps(data))# 处理响应if response.status_code == 200:result = response.json()generateUuid = result['data']['generateUuid']print('API调用成功,返回结果:', result)else:print('API调用失败,状态码:', response.status_code, ',响应内容:', response.text)except requests.exceptions.RequestException as e:print('请求异常:', e)return generateUuid

注意:具体参数说明,请参考开发文档

6、接口返回示例,获取任务id:

{"code": 0,"msg": "","data": {"generateUuid": "8dcbfa2997444899b71357ccb7db378b"}
}

7、Python查看任务,并得到图片地址:

def get_cd_laowang_img(generateUuid):result = {}# 生成签名sign, timestamp, signature_nonce = make_sign(generate_webui_status_uri)# 准备请求参数uri = 'https://openapi.liblibai.cloud/api/generate/webui/status'  # 根据API地址更新uriuri = f"{uri}?AccessKey={ACCESS_KEY}&Signature={sign}&Timestamp={timestamp}&SignatureNonce={signature_nonce}"print(uri)headers = {'Content-Type': 'application/json'}data = {"generateUuid": generateUuid,}try:# 发送POST请求response = requests.post(uri, headers=headers, data=json.dumps(data))# 处理响应if response.status_code == 200:result = response.json()print('API调用成功,返回结果:', result)else:print('API调用失败,状态码:', response.status_code, ',响应内容:', response.text)except requests.exceptions.RequestException as e:print('请求异常:', e)return result

注意:因为api接口改变,所以需要再次生成签名

五、全部代码如下:

import requests
import json
import hmac
from hashlib import sha1
import base64
import time
import uuid# 配置信息
ACCESS_KEY = 'MXYG3cwFHVRa3wsLU5iJwQ'  # 替换为你的AccessKey
SECRET_KEY = '*************************'  # 替换为你的SecretKey# 请求API接口的uri地址
text2img_uri = "/api/generate/webui/text2img"
generate_webui_status_uri = "/api/generate/webui/status"def make_sign(uri):"""生成签名"""# 当前毫秒时间戳timestamp = str(int(time.time() * 1000))# 随机字符串signature_nonce = str(uuid.uuid4()).replace('-', '')# 拼接请求数据content = '&'.join((uri, timestamp, signature_nonce))# 生成签名digest = hmac.new(SECRET_KEY.encode(), content.encode(), sha1).digest()# 移除为了补全base64位数而填充的尾部等号sign = base64.urlsafe_b64encode(digest).rstrip(b'=').decode()return sign, timestamp, signature_noncedef call_liblibai_api():generateUuid = ""# 生成签名sign, timestamp, signature_nonce = make_sign(text2img_uri)# 准备请求参数uri = 'https://openapi.liblibai.cloud/api/generate/webui/text2img'  # 根据API地址更新uriuri = f"{uri}?AccessKey={ACCESS_KEY}&Signature={sign}&Timestamp={timestamp}&SignatureNonce={signature_nonce}"print(uri)headers = {'Content-Type': 'application/json'}data = {"templateUuid": "e10adc3949ba59abbe56e057f20f883e","generateParams": {"checkPointId": "ba34a22f1c044472a42b6051aac2afb3","prompt": "This is a 12-story hospital building. The ground floor houses the emergency room and pharmacy. The entrance is spacious and has a sheltered structure. Each floor from the second to the twelfth floor has a ward area, including a nurse station, ward Windows, and space for placing medical equipment. The building's exterior is simple, with Windows arranged regularly. From the outside, a clear 12-story structure can be seen.","negativePrompt": "ng_deepnegative_v1_75t,(badhandv4:1.2),EasyNegative,(worst quality:2),","sampler": 15,"steps": 20,"cfgScale": 7,"width": 768,"height": 1024,"imgCount": 1,"randnSource": 0,"seed": 2228967414,"restoreFaces": 0,"hiResFixInfo": {"hiresSteps": 20,"hiresDenoisingStrength": 0.75,"upscaler": 10,"resizedWidth": 1024,"resizedHeight": 1536}}}try:# 发送POST请求response = requests.post(uri, headers=headers, data=json.dumps(data))# 处理响应if response.status_code == 200:result = response.json()generateUuid = result['data']['generateUuid']print('API调用成功,返回结果:', result)else:print('API调用失败,状态码:', response.status_code, ',响应内容:', response.text)except requests.exceptions.RequestException as e:print('请求异常:', e)return generateUuiddef get_cd_laowang_img(generateUuid):result = {}# 生成签名sign, timestamp, signature_nonce = make_sign(generate_webui_status_uri)# 准备请求参数uri = 'https://openapi.liblibai.cloud/api/generate/webui/status'  # 根据API地址更新uriuri = f"{uri}?AccessKey={ACCESS_KEY}&Signature={sign}&Timestamp={timestamp}&SignatureNonce={signature_nonce}"print(uri)headers = {'Content-Type': 'application/json'}data = {"generateUuid": generateUuid,}try:# 发送POST请求response = requests.post(uri, headers=headers, data=json.dumps(data))# 处理响应if response.status_code == 200:result = response.json()print('API调用成功,返回结果:', result)else:print('API调用失败,状态码:', response.status_code, ',响应内容:', response.text)except requests.exceptions.RequestException as e:print('请求异常:', e)return resultif __name__ == '__main__':generateUuid = call_liblibai_api()time.sleep(20)if generateUuid != "":print("generateUuid:", generateUuid)result = get_cd_laowang_img(generateUuid)image_url = result['data']['images'][0]["imageUrl"]print(f"generateUuid:{generateUuid}")print(f"图片地址:{image_url}")

http://www.xdnf.cn/news/447643.html

相关文章:

  • 小说所有设定(v3.0 preview)
  • Qml自定义组件之车辆风扇展示
  • 【Linux】掌握 setsid:让进程脱离终端独立运行
  • 三种映射方式总结
  • 第二十九节:直方图处理-直方图均衡化
  • ET ProcessInnerSender类(实体) 分析
  • ultralytics中tasks.py---parse_model函数解析
  • 求助求助,重金酬谢
  • Java知识框架
  • AIGC与数字媒体实验室解决方案分享
  • Jmeter对服务端进行压测快速上手
  • 【电路笔记 通信】8B/10B编码 高速数据传输的串行数据编码技术 论文第三部分 The 8B/10B coding map
  • HarmonyOS NEXT 适配高德地图FlutterSDK实现地图展示,添加覆盖物和移动Camera
  • OpenCV CUDA 模块中用于在 GPU 上计算两个数组对应元素差值的绝对值函数absdiff(
  • Flutter 开发入门:从一个简单的计数器应用开始
  • 操作系统-物理结构
  • 【拥抱AI】Deer-Flow字节跳动开源的多智能体深度研究框架
  • MCP:开启AI的“万物互联”时代
  • 网站安全防御
  • 北斗导航 | 接收机自主完好性监测算法综述,1980至2025年(原理,公式,代码)
  • Java版OA管理系统源码 手机版OA系统源码
  • 深入理解卷积神经网络:从基础原理到实战应用
  • 硕士论文用YOLO可以毕业吗?
  • 记录算法笔记(20025.5.14)对称二叉树
  • 码题集——魔数、A的B次方、网球比赛、三角形、点与线段的关系
  • libmemcached库api接口讲解五
  • Java Queue 接口实现
  • 【经验分享】Dify+GraphRAG实现知识图谱智能问答
  • QMK键盘编码器(Encoder)(理论部分)
  • Unity Image组件无法阻挡手势的解决办法