科大讯飞AI图片生成 API 接口

本文借助科大讯飞AI图片生成开放平台,使用PHP调用Python构建一个API。

还没有使用讯飞星火的朋友可以参考此文

讯飞星火大模型API矩阵

一、构建API

index.php获取文字及图片参数供Python调用

<?php
header('Access-Control-Allow-Origin:*');
header('Content-type: application/json');

$text=isset($_GET['text'])? $_GET['text'] :null; 
if(empty($text)){die("请传入文本参数");}

$width = isset($_GET['width'])? $_GET['width'] :null; 
$height = isset($_GET['height'])? $_GET['height'] :null; 
if(empty($width)||empty($height)){die("请传入图片完整尺寸参数");}

$str = exec("python3 w2p.py $text $width $height");
$data = json_decode($str, true); 

$response_msg = $data["code"];
if($response_msg == "200") {$code = "200";}
else{$code = "202";}
$image = $data["image"];

$json_return = array(
    "code" => $code,
    "src" => $text,
    "image" => "你的api网络位置".$image
);
echo json_encode($json_return, JSON_UNESCAPED_UNICODE);

Python请求讯飞识别接口:w2p.py文件写入内容

# encoding: UTF-8
import time

import requests
from datetime import datetime
from wsgiref.handlers import format_date_time
from time import mktime
import hashlib
import base64
import hmac
from urllib.parse import urlencode
import json
from PIL import Image
from io import BytesIO
import json
import sys

class AssembleHeaderException(Exception):
    def __init__(self, msg):
        self.message = msg


class Url:
    def __init__(this, host, path, schema):
        this.host = host
        this.path = path
        this.schema = schema
        pass


# calculate sha256 and encode to base64
def sha256base64(data):
    sha256 = hashlib.sha256()
    sha256.update(data)
    digest = base64.b64encode(sha256.digest()).decode(encoding='utf-8')
    return digest


def parse_url(requset_url):
    stidx = requset_url.index("://")
    host = requset_url[stidx + 3:]
    schema = requset_url[:stidx + 3]
    edidx = host.index("/")
    if edidx <= 0:
        raise AssembleHeaderException("invalid request url:" + requset_url)
    path = host[edidx:]
    host = host[:edidx]
    u = Url(host, path, schema)
    return u


# 生成鉴权url
def assemble_ws_auth_url(requset_url, method="GET", api_key="", api_secret=""):
    u = parse_url(requset_url)
    host = u.host
    path = u.path
    now = datetime.now()
    date = format_date_time(mktime(now.timetuple()))
    # print(date)
    # date = "Thu, 12 Dec 2019 01:57:27 GMT"
    signature_origin = "host: {}\ndate: {}\n{} {} HTTP/1.1".format(host, date, method, path)
    # print(signature_origin)
    signature_sha = hmac.new(api_secret.encode('utf-8'), signature_origin.encode('utf-8'),
                             digestmod=hashlib.sha256).digest()
    signature_sha = base64.b64encode(signature_sha).decode(encoding='utf-8')
    authorization_origin = "api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"" % (
        api_key, "hmac-sha256", "host date request-line", signature_sha)
    authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode(encoding='utf-8')
    # print(authorization_origin)
    values = {
        "host": host,
        "date": date,
        "authorization": authorization
    }

    return requset_url + "?" + urlencode(values)

# 生成请求body体
def getBody(appid,text,width,height):
    body= {
        "header": {
            "app_id": appid,
            "uid":"123456789"
        },
        "parameter": {
            "chat": {
                "domain": "general",
                "width": width,
                "height": height,
                "temperature":0.5,
                "max_tokens":4096
            }
        },
        "payload": {
            "message":{
                "text":[
                    {
                        "role":"user",
                        "content":text
                    }
                ]
            }
        }
    }
    return body

# 发起请求并返回结果
def main(text,appid,apikey,apisecret,width,height):
    host = 'http://spark-api.cn-huabei-1.xf-yun.com/v2.1/tti'
    url = assemble_ws_auth_url(host,method='POST',api_key=apikey,api_secret=apisecret)
    content = getBody(appid,text,width,height)
    # print(time.time())
    response = requests.post(url,json=content,headers={'content-type': "application/json"}).text
    # print(time.time())
    return response

#将base64 的图片数据存在本地
def base64_to_image(base64_data, save_path):
    # 解码base64数据
    img_data = base64.b64decode(base64_data)

    # 将解码后的数据转换为图片
    img = Image.open(BytesIO(img_data))

    # 保存图片到本地
    img.save(save_path)


# 解析并保存到指定位置
def parser_Message(message):
    data = json.loads(message)
    # print("data" + str(message))
    code = data['header']['code']
    if code != 0:
        print(f'请求错误: {code}, {data}')
    else:
        text = data["payload"]["choices"]["text"]
        imageContent = text[0]
        # if('image' == imageContent["content_type"]):
        imageBase = imageContent["content"]
        imageName = data['header']['sid']
        savePath = f"data/{imageName}.jpg"
        base64_to_image(imageBase,savePath)
        # print("图片保存路径:" + savePath)
        jsondata = {
            "code": "200",
            "image": "/data/" + imageName + ".jpg"
        }
        json_data = json.dumps(jsondata)
        print(json_data)


if __name__ == '__main__':
    #运行前请配置以下鉴权三要素,获取途径:https://console.xfyun.cn/services/tti
    APPID ='xxxxxx'
    APISecret = 'xxxxxx'
    APIKEY = 'xxxxxx'
    desc = sys.argv[1]
    WIDTH = int(sys.argv[2])
    HEIGHT = int(sys.argv[3])
    res = main(desc,appid=APPID,apikey=APIKEY,apisecret=APISecret,width=WIDTH,height=HEIGHT)
    # print(res)
    #保存到指定位置
    parser_Message(res)

注意新建data数据文件夹,填写讯飞鉴权三要素

二、调用示例

https://你的api网络位置/?text=白日依山尽,黄河入海流&width=512&height=512

三、返回数据

{
    "code": "200",
    "src": "生成一张图:白日依山尽,黄河入海流",
    "image": "你的api网络位置/data/cht000bc10b@dx19067ff76f0b8f3550.jpg"
}


Demo:https://api.szfx.top/api/xftti.html

构建的在线AI图片生成网站:https://tool.szfx.top/tti

本文采用 CC BY-NC-SA 3.0 Unported 许可,转载请以超链接注明出处。
原文地址:科大讯飞AI图片生成 API 接口 作者:松鼠小
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
Source: Telegram @AmashiroNatsukiEars_NoWord Sticker
Source: Github @zhheo/Sticker-Heo
Source: github.com/k4yt3x/flowerhd
颜文字
AmashiroNatsukiEars
Heo
小恐龙
花!
上一篇
下一篇