Skip to content

Commit

Permalink
优化文件流转
Browse files Browse the repository at this point in the history
  • Loading branch information
Vinlic committed May 16, 2024
1 parent 4136cb3 commit 70642df
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 13 deletions.
5 changes: 1 addition & 4 deletions src/api/controllers/audio.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,10 +118,7 @@ async function createTranscriptions(
const transcodedFilePath = `tmp/${name}_transcodeed.mp3`;
await util.transAudioCode(filePath, transcodedFilePath);
const buffer = await fs.readFile(transcodedFilePath);
Promise.all([
fs.remove(filePath),
fs.remove(transcodedFilePath)
])
fs.remove(transcodedFilePath)
.catch(err => logger.error('移除临时文件失败:', err));
let session: ClientHttp2Session;
return (async () => {
Expand Down
19 changes: 10 additions & 9 deletions src/api/routes/audio.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import _ from "lodash";
import fs from "fs-extra";
import mime from "mime";

import Request from "@/lib/request/Request.ts";
import Response from "@/lib/response/Response.ts";
Expand Down Expand Up @@ -62,14 +60,17 @@ export default {
const tokens = core.tokenSplit(request.headers.authorization);
// 随机挑选一个token
const token = _.sample(tokens);
if(!request.files['file'])
if(!request.files['file'] && !request.body["file"])
throw new Error('File field is not set');
let tmpFilePath;
if(request.files['file']) {
const file = request.files['file'];
if(!['audio/mp3', 'audio/mpeg', 'audio/x-wav', 'audio/wave', 'audio/mp4a-latm', 'audio/flac', 'audio/ogg', 'audio/webm'].includes(file.mimetype))
throw new Error(`File MIME type ${file.mimetype} is unsupported`);
tmpFilePath = file.filepath;
}
else
throw new Error('File field is not set');
const file = request.files['file'];
if(!['audio/mp3', 'audio/mpeg', 'audio/x-wav', 'audio/wave', 'audio/mp4a-latm', 'audio/flac', 'audio/ogg', 'audio/webm'].includes(file.mimetype))
throw new Error(`File MIME type ${file.mimetype} is unsupported`);
const ext = mime.getExtension(file.mimetype);
const tmpFilePath = `tmp/${file.newFilename}.${ext == 'mpga' ? 'mp3' : ext}`;
await fs.copy(file.filepath, tmpFilePath);
const { model, response_format: responseFormat = 'json' } = request.body;
const text = await audio.createTranscriptions(model, tmpFilePath, token);
return new Response(responseFormat == 'json' ? { text } : text);
Expand Down

0 comments on commit 70642df

Please sign in to comment.