支持兼容dalle3绘图调用接口

This commit is contained in:
Vinlic 2024-03-27 10:36:36 +08:00
parent 96a80f5f32
commit ea49bd3023
5 changed files with 957 additions and 548 deletions

View File

@ -5,5 +5,6 @@ export default {
API_TOKEN_EXPIRES: [-2002, 'Token已失效'],
API_FILE_URL_INVALID: [-2003, '远程文件URL非法'],
API_FILE_EXECEEDS_SIZE: [-2004, '远程文件超出大小'],
API_CHAT_STREAM_PUSHING: [-2005, '已有对话流正在输出']
API_CHAT_STREAM_PUSHING: [-2005, '已有对话流正在输出'],
API_CONTENT_FILTERED: [-2006, '内容由于合规问题已被阻止生成']
}

File diff suppressed because it is too large Load Diff

39
src/api/routes/images.ts Normal file
View File

@ -0,0 +1,39 @@
import _ from "lodash";
import Request from "@/lib/request/Request.ts";
import chat from "@/api/controllers/chat.ts";
import util from "@/lib/util.ts";
export default {
prefix: "/v1/images",
post: {
"/generations": async (request: Request) => {
request
.validate("body.prompt", _.isString)
.validate("headers.authorization", _.isString);
// refresh_token切分
const tokens = chat.tokenSplit(request.headers.authorization);
// 随机挑选一个refresh_token
const token = _.sample(tokens);
const prompt = request.body.prompt;
const responseFormat = _.defaultTo(request.body.response_format, "url");
const model = request.body.model;
const imageUrls = await chat.generateImages(model, prompt, token);
let data = [];
if (responseFormat == "b64_json") {
data = (
await Promise.all(imageUrls.map((url) => util.fetchFileBASE64(url)))
).map((b64) => ({ b64_json: b64 }));
} else {
data = imageUrls.map((url) => ({
url,
}));
}
return {
created: util.unixTimestamp(),
data,
};
},
},
};

View File

@ -1,7 +1,9 @@
import chat from "./chat.ts";
import images from "./images.ts";
import ping from "./ping.ts";
export default [
chat,
images,
ping
];

View File

@ -1,41 +1,43 @@
import os from 'os';
import path from 'path';
import crypto from 'crypto';
import { Readable, Writable } from 'stream';
import os from "os";
import path from "path";
import crypto from "crypto";
import { Readable, Writable } from "stream";
import 'colors';
import mime from 'mime';
import fs from 'fs-extra';
import { v1 as uuid } from 'uuid';
import { format as dateFormat } from 'date-fns';
import CRC32 from 'crc-32';
import randomstring from 'randomstring';
import _ from 'lodash';
import { CronJob } from 'cron';
import "colors";
import mime from "mime";
import axios from "axios";
import fs from "fs-extra";
import { v1 as uuid } from "uuid";
import { format as dateFormat } from "date-fns";
import CRC32 from "crc-32";
import randomstring from "randomstring";
import _ from "lodash";
import { CronJob } from "cron";
import HTTP_STATUS_CODE from './http-status-codes.ts';
import HTTP_STATUS_CODE from "./http-status-codes.ts";
const autoIdMap = new Map();
const util = {
is2DArrays(value: any) {
return _.isArray(value) && (!value[0] || (_.isArray(value[0]) && _.isArray(value[value.length - 1])));
return (
_.isArray(value) &&
(!value[0] || (_.isArray(value[0]) && _.isArray(value[value.length - 1])))
);
},
uuid: (separator = true) => separator ? uuid() : uuid().replace(/\-/g, ""),
uuid: (separator = true) => (separator ? uuid() : uuid().replace(/\-/g, "")),
autoId: (prefix = '') => {
autoId: (prefix = "") => {
let index = autoIdMap.get(prefix);
if(index > 999999) index = 0; //超过最大数字则重置为0
if (index > 999999) index = 0; //超过最大数字则重置为0
autoIdMap.set(prefix, (index || 0) + 1);
return `${prefix}${index || 1}`;
},
ignoreJSONParse(value: string) {
const result = _.attempt(() => JSON.parse(value));
if(_.isError(result))
return null;
if (_.isError(result)) return null;
return result;
},
@ -44,13 +46,14 @@ const util = {
},
getResponseContentType(value: any): string | null {
return value.headers ? (value.headers["content-type"] || value.headers["Content-Type"]) : null;
return value.headers
? value.headers["content-type"] || value.headers["Content-Type"]
: null;
},
mimeToExtension(value: string) {
let extension = mime.getExtension(value);
if(extension == "mpga")
return "mp3";
if (extension == "mpga") return "mp3";
return extension;
},
@ -60,8 +63,15 @@ const util = {
},
createCronJob(cronPatterns: any, callback?: Function) {
if(!_.isFunction(callback)) throw new Error("callback must be an Function");
return new CronJob(cronPatterns, () => callback(), null, false, "Asia/Shanghai");
if (!_.isFunction(callback))
throw new Error("callback must be an Function");
return new CronJob(
cronPatterns,
() => callback(),
null,
false,
"Asia/Shanghai"
);
},
getDateString(format = "yyyy-MM-dd", date = new Date()) {
@ -73,9 +83,13 @@ const util = {
const addresses = [];
for (let name in interfaces) {
const networks = interfaces[name];
const results = networks.filter(network => network.family === "IPv4" && network.address !== "127.0.0.1" && !network.internal);
if (results[0] && results[0].address)
addresses.push(results[0].address);
const results = networks.filter(
(network) =>
network.family === "IPv4" &&
network.address !== "127.0.0.1" &&
!network.internal
);
if (results[0] && results[0].address) addresses.push(results[0].address);
}
return addresses;
},
@ -85,19 +99,27 @@ const util = {
const addresses = [];
for (let name in interfaces) {
const networks = interfaces[name];
const results = networks.filter(network => network.family === "IPv4" && network.address !== "127.0.0.1" && !network.internal);
if (results[0] && results[0].mac)
addresses.push(results[0].mac);
const results = networks.filter(
(network) =>
network.family === "IPv4" &&
network.address !== "127.0.0.1" &&
!network.internal
);
if (results[0] && results[0].mac) addresses.push(results[0].mac);
}
return addresses;
},
generateSSEData(event?: string, data?: string, retry?: number) {
return `event: ${event || "message"}\ndata: ${(data || "").replace(/\n/g, "\\n").replace(/\s/g, "\\s")}\nretry: ${retry || 3000}\n\n`;
return `event: ${event || "message"}\ndata: ${(data || "")
.replace(/\n/g, "\\n")
.replace(/\s/g, "\\s")}\nretry: ${retry || 3000}\n\n`;
},
buildDataBASE64(type, ext, buffer) {
return `data:${type}/${ext.replace("jpg", "jpeg")};base64,${buffer.toString("base64")}`;
return `data:${type}/${ext.replace("jpg", "jpeg")};base64,${buffer.toString(
"base64"
)}`;
},
isLinux() {
@ -105,7 +127,15 @@ const util = {
},
isIPAddress(value) {
return _.isString(value) && (/^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$/.test(value) || /\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))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f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*/.test(
value
))
);
},
isPort(value) {
@ -113,11 +143,17 @@ const util = {
},
isReadStream(value): boolean {
return value && (value instanceof Readable || "readable" in value || value.readable);
return (
value &&
(value instanceof Readable || "readable" in value || value.readable)
);
},
isWriteStream(value): boolean {
return value && (value instanceof Writable || "writable" in value || value.writable);
return (
value &&
(value instanceof Writable || "writable" in value || value.writable)
);
},
isHttpStatusCode(value) {
@ -142,7 +178,7 @@ const util = {
extractBASE64DataFormat(value): string | null {
const match = value.trim().match(/^data:(.+);base64,/);
if(!match) return null;
if (!match) return null;
return match[1];
},
@ -167,7 +203,9 @@ const util = {
},
isEmail(value) {
return /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/.test(value);
return /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/.test(
value
);
},
isAsyncFunction(value) {
@ -181,7 +219,7 @@ const util = {
readStream.once("end", resolve);
readStream.once("error", reject);
});
readStream.once("data", data => head = data);
readStream.once("data", (data) => (head = data));
await readPromise;
return head.compare(Buffer.from([0x61, 0x63, 0x54, 0x4c])) === 0;
},
@ -197,7 +235,9 @@ const util = {
urlJoin(...values) {
let url = "";
for (let i = 0; i < values.length; i++)
url += `${i > 0 ? "/" : ""}${values[i].replace(/^\/*/, "").replace(/\/*$/, "")}`;
url += `${i > 0 ? "/" : ""}${values[i]
.replace(/^\/*/, "")
.replace(/\/*$/, "")}`;
return url;
},
@ -208,16 +248,19 @@ const util = {
const hours = Math.floor(sec / 3600);
const minutes = Math.floor((sec - hours * 3600) / 60);
const seconds = sec - hours * 3600 - minutes * 60;
const ms = milliseconds % 60000 - seconds * 1000;
return `${hours > 9 ? hours : "0" + hours}:${minutes > 9 ? minutes : "0" + minutes}:${seconds > 9 ? seconds : "0" + seconds}.${ms}`;
const ms = (milliseconds % 60000) - seconds * 1000;
return `${hours > 9 ? hours : "0" + hours}:${
minutes > 9 ? minutes : "0" + minutes
}:${seconds > 9 ? seconds : "0" + seconds}.${ms}`;
},
millisecondsToTimeString(milliseconds) {
if(milliseconds < 1000)
return `${milliseconds}ms`;
if(milliseconds < 60000)
if (milliseconds < 1000) return `${milliseconds}ms`;
if (milliseconds < 60000)
return `${parseFloat((milliseconds / 1000).toFixed(2))}s`;
return `${Math.floor(milliseconds / 1000 / 60)}m${Math.floor(milliseconds / 1000 % 60)}s`;
return `${Math.floor(milliseconds / 1000 / 60)}m${Math.floor(
(milliseconds / 1000) % 60
)}s`;
},
rgbToHex(r, g, b): string {
@ -242,7 +285,7 @@ const util = {
},
booleanParse(value) {
return value === "true" || value === true ? true : false
return value === "true" || value === true ? true : false;
},
encodeBASE64(value) {
@ -253,6 +296,12 @@ const util = {
return Buffer.from(value, "base64").toString();
},
async fetchFileBASE64(url: string) {
const result = await axios.get(url, {
responseType: "arraybuffer",
});
return result.data.toString("base64");
},
};
export default util;