星火大模型——多模态API调用(图像+文本)

2024-01-11 06:52

本文主要是介绍星火大模型——多模态API调用(图像+文本),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

参考文档

  • 图片理解 API 文档

环境配置

pip3 install websocket-client

核心代码

import _thread as thread
import base64
import datetime
import hashlib
import hmac
import json
from urllib.parse import urlparse
import ssl
from datetime import datetime
from time import mktime
from urllib.parse import urlencode
from wsgiref.handlers import format_date_time
import websocket  # 使用websocket_client
from PIL import Image
import ioappid = "xxx"    #填写控制台中获取的 APPID 信息
api_secret = "xxxx"   #填写控制台中获取的 APISecret 信息
api_key ="xxxx"    #填写控制台中获取的 APIKey 信息
#  = open("images\PointAClouth.png",'rb').read()# Function to resize the image
def resize_image(image_path, size):image = Image.open(image_path)resized_image = image.resize(size)print(resized_image.size)# import pdb; pdb.set_trace()return resized_image# Function to encode the image
def encode_image(image):image_byte_array = io.BytesIO()image.save(image_byte_array, format='PNG')image_byte_array = image_byte_array.getvalue()return image_byte_array, base64.b64encode(image_byte_array).decode('utf-8')# Path to your image
image_path = "images/PointAClouth.png"# Getting the base64 string of the resized image
new_size = (1000, 1000)
resized_image = resize_image(image_path, new_size)
imagedata, base64_image = encode_image(resized_image)imageunderstanding_url = "wss://spark-api.cn-huabei-1.xf-yun.com/v2.1/image"#云端环境的服务地址
text =[{"role": "user", "content": base64_image, "content_type":"image"}]class Ws_Param(object):# 初始化def __init__(self, APPID, APIKey, APISecret, imageunderstanding_url):self.APPID = APPIDself.APIKey = APIKeyself.APISecret = APISecretself.host = urlparse(imageunderstanding_url).netlocself.path = urlparse(imageunderstanding_url).pathself.ImageUnderstanding_url = imageunderstanding_url# 生成urldef create_url(self):# 生成RFC1123格式的时间戳now = datetime.now()date = format_date_time(mktime(now.timetuple()))# 拼接字符串signature_origin = "host: " + self.host + "\n"signature_origin += "date: " + date + "\n"signature_origin += "GET " + self.path + " HTTP/1.1"# 进行hmac-sha256进行加密signature_sha = hmac.new(self.APISecret.encode('utf-8'), signature_origin.encode('utf-8'),digestmod=hashlib.sha256).digest()signature_sha_base64 = base64.b64encode(signature_sha).decode(encoding='utf-8')authorization_origin = f'api_key="{self.APIKey}", algorithm="hmac-sha256", headers="host date request-line", signature="{signature_sha_base64}"'authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode(encoding='utf-8')# 将请求的鉴权参数组合为字典v = {"authorization": authorization,"date": date,"host": self.host}# 拼接鉴权参数,生成urlurl = self.ImageUnderstanding_url + '?' + urlencode(v)#print(url)# 此处打印出建立连接时候的url,参考本demo的时候可取消上方打印的注释,比对相同参数时生成的url与自己代码生成的url是否一致return url# 收到websocket错误的处理
def on_error(ws, error):print("### error:", error)# 收到websocket关闭的处理
def on_close(ws,one,two):print(" ")# 收到websocket连接建立的处理
def on_open(ws):thread.start_new_thread(run, (ws,))def run(ws, *args):data = json.dumps(gen_params(appid=ws.appid, question= ws.question ))ws.send(data)# 收到websocket消息的处理
def on_message(ws, message):#print(message)data = json.loads(message)code = data['header']['code']if code != 0:print(f'请求错误: {code}, {data}')ws.close()else:# print("text_token:", payload.usage.text.prompt_tokens)choices = data["payload"]["choices"]status = choices["status"]content = choices["text"][0]["content"]print(content,end ="")# print(usage)global answeranswer += content# print(1)if status == 2:# import pdb; pdb.set_trace()print("usage:", data["payload"]['usage'])ws.close()def gen_params(appid, question):"""通过appid和用户的提问来生成请参数"""data = {"header": {"app_id": appid},"parameter": {"chat": {"domain": "image","temperature": 0.5,"top_k": 4,"max_tokens": 2028,"auditing": "default"}},"payload": {"message": {"text": question}}
}return datadef main(appid, api_key, api_secret, imageunderstanding_url,imagedata,question):wsParam = Ws_Param(appid, api_key, api_secret, imageunderstanding_url)websocket.enableTrace(False)wsUrl = wsParam.create_url()ws = websocket.WebSocketApp(wsUrl, on_message=on_message, on_error=on_error, on_close=on_close, on_open=on_open)ws.appid = appidws.imagedata = imagedataws.question = questionws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})def getText(role, content):jsoncon = {}jsoncon["role"] = rolejsoncon["content"] = contenttext.append(jsoncon)return textdef getlength(text):length = 0for content in text:temp = content["content"]leng = len(temp)length += lengreturn lengthdef checklen(text):#print("text-content-tokens:", getlength(text[1:]))while (getlength(text[1:])> 8000):del text[1]return textif __name__ == '__main__':text.clear# while(1):# Input = input("\n" +"问:")getText("system","xxxx")Input = "xxxxx"question = checklen(getText("user",Input))answer = ""print("答:",end = "")main(appid, api_key, api_secret, imageunderstanding_url, imagedata,question)getText("assistant", answer)print(text[1:])# print(str(text))

这篇关于星火大模型——多模态API调用(图像+文本)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/593515

相关文章

使用Python实现图像LBP特征提取的操作方法

《使用Python实现图像LBP特征提取的操作方法》LBP特征叫做局部二值模式,常用于纹理特征提取,并在纹理分类中具有较强的区分能力,本文给大家介绍了如何使用Python实现图像LBP特征提取的操作方... 目录一、LBP特征介绍二、LBP特征描述三、一些改进版本的LBP1.圆形LBP算子2.旋转不变的LB

C#TextBox设置提示文本方式(SetHintText)

《C#TextBox设置提示文本方式(SetHintText)》:本文主要介绍C#TextBox设置提示文本方式(SetHintText),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑... 目录C#TextBox设置提示文本效果展示核心代码总结C#TextBox设置提示文本效果展示核心代

springboot项目中常用的工具类和api详解

《springboot项目中常用的工具类和api详解》在SpringBoot项目中,开发者通常会依赖一些工具类和API来简化开发、提高效率,以下是一些常用的工具类及其典型应用场景,涵盖Spring原生... 目录1. Spring Framework 自带工具类(1) StringUtils(2) Coll

OpenCV图像形态学的实现

《OpenCV图像形态学的实现》本文主要介绍了OpenCV图像形态学的实现,包括腐蚀、膨胀、开运算、闭运算、梯度运算、顶帽运算和黑帽运算,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起... 目录一、图像形态学简介二、腐蚀(Erosion)1. 原理2. OpenCV 实现三、膨胀China编程(

Spring Security基于数据库的ABAC属性权限模型实战开发教程

《SpringSecurity基于数据库的ABAC属性权限模型实战开发教程》:本文主要介绍SpringSecurity基于数据库的ABAC属性权限模型实战开发教程,本文给大家介绍的非常详细,对大... 目录1. 前言2. 权限决策依据RBACABAC综合对比3. 数据库表结构说明4. 实战开始5. MyBA

Java调用C++动态库超详细步骤讲解(附源码)

《Java调用C++动态库超详细步骤讲解(附源码)》C语言因其高效和接近硬件的特性,时常会被用在性能要求较高或者需要直接操作硬件的场合,:本文主要介绍Java调用C++动态库的相关资料,文中通过代... 目录一、直接调用C++库第一步:动态库生成(vs2017+qt5.12.10)第二步:Java调用C++

Java的IO模型、Netty原理解析

《Java的IO模型、Netty原理解析》Java的I/O是以流的方式进行数据输入输出的,Java的类库涉及很多领域的IO内容:标准的输入输出,文件的操作、网络上的数据传输流、字符串流、对象流等,这篇... 目录1.什么是IO2.同步与异步、阻塞与非阻塞3.三种IO模型BIO(blocking I/O)NI

在C#中调用Python代码的两种实现方式

《在C#中调用Python代码的两种实现方式》:本文主要介绍在C#中调用Python代码的两种实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录C#调用python代码的方式1. 使用 Python.NET2. 使用外部进程调用 Python 脚本总结C#调

基于Flask框架添加多个AI模型的API并进行交互

《基于Flask框架添加多个AI模型的API并进行交互》:本文主要介绍如何基于Flask框架开发AI模型API管理系统,允许用户添加、删除不同AI模型的API密钥,感兴趣的可以了解下... 目录1. 概述2. 后端代码说明2.1 依赖库导入2.2 应用初始化2.3 API 存储字典2.4 路由函数2.5 应

使用Python实现文本转语音(TTS)并播放音频

《使用Python实现文本转语音(TTS)并播放音频》在开发涉及语音交互或需要语音提示的应用时,文本转语音(TTS)技术是一个非常实用的工具,下面我们来看看如何使用gTTS和playsound库将文本... 目录什么是 gTTS 和 playsound安装依赖库实现步骤 1. 导入库2. 定义文本和语言 3