File size: 8,363 Bytes
6bc074c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
package handler

import (
	"fmt"
	"io"
	"strings"

	"aurora/httpclient/bogdanfinn"
	"aurora/internal/accounts"
	"aurora/internal/chatgpt"
	"aurora/internal/config"
	officialtypes "aurora/typings/official"
	chatgptrequestconverter "aurora/conversion/requests/chatgpt"

	"github.com/gin-gonic/gin"
)

type AudioHandler struct {
	accountPool *accounts.Pool
	cfg         *config.Config
}

func NewAudioHandler(pool *accounts.Pool, cfg *config.Config) *AudioHandler {
	return &AudioHandler{accountPool: pool, cfg: cfg}
}

// ── TTS ──

var ttsFmtMap = map[string]string{
	"mp3":  "mp3",
	"opus": "opus",
	"aac":  "aac",
	"flac": "aac",
	"wav":  "aac",
	"pcm":  "aac",
}

var ttsTypeMap = map[string]string{
	"mp3":  "audio/mpeg",
	"opus": "audio/ogg",
	"aac":  "audio/aac",
}

var ttsVoiceMap = map[string]string{
	"alloy":   "cove",
	"ash":     "fathom",
	"coral":   "vale",
	"echo":    "ember",
	"fable":   "breeze",
	"onyx":    "orbit",
	"nova":    "maple",
	"sage":    "glimmer",
	"shimmer": "juniper",
}

func (h *AudioHandler) TTS(c *gin.Context) {
	var original_request officialtypes.TTSAPIRequest
	err := c.BindJSON(&original_request)
	if err != nil {
		c.JSON(400, gin.H{"error": gin.H{
			"message": "Request must be proper JSON",
			"type":    "invalid_request_error",
			"param":   nil,
			"code":    err.Error(),
		}})
		return
	}
	if original_request.Input == "" {
		c.JSON(400, gin.H{"error": gin.H{
			"message": "Missing required parameter: input",
			"type":    "invalid_request_error",
			"param":   "input",
			"code":    "missing_required_parameter",
		}})
		return
	}

	account, _, err := resolveAccount(c, h.accountPool, h.cfg, true)
	if err != nil {
		c.JSON(400, gin.H{"error": gin.H{
			"message": err.Error(),
			"type":    "authorization_error",
			"param":   "Authorization",
			"code":    400,
		}})
		return
	}
	if account == nil || account.Token == "" {
		c.JSON(400, gin.H{"error": "TTS requires a logged-in ChatGPT access token."})
		return
	}
	if !account.Type.Satisfies(accounts.CapTTS) {
		c.JSON(403, gin.H{"error": "TTS requires a logged-in ChatGPT account."})
		return
	}

	proxyUrl := account.Proxy
	client := setupClientWithProxy(proxyUrl)

	// Convert the chat request to a ChatGPT request
	translated_request := chatgptrequestconverter.ConvertTTSAPIRequest(original_request.Input)
	clientState := chatgpt.NewChatClientState()
	clientState.ConversationID = translated_request.ConversationID
	clientState.ParentMessageID = translated_request.ParentMessageID

	response, wsConn, _, status, err := conversationClientOrder(&client, account, translated_request, proxyUrl, false, clientState, h.accountPool)
	if err != nil {
		c.JSON(status, gin.H{"error": gin.H{
			"message": err.Error(),
			"type":    "request_conversion_error",
			"param":   "model",
			"code":    "request_conversion_error",
		}})
		return
	}
	defer response.Body.Close()
	if chatgpt.Handle_request_error(c, response) {
		if wsConn != nil {
			wsConn.Close()
		}
		return
	}

	msgId, convId := chatgpt.HandlerTTS(response, original_request.Input)
	if msgId == "" || convId == "" {
		c.JSON(500, gin.H{"error": "failed to get TTS message id"})
		return
	}
	defer chatgpt.RemoveConversation(client, account, convId, proxyUrl)

	format := ttsFmtMap[original_request.Format]
	if format == "" {
		format = "aac"
	}
	voice := ttsVoiceMap[original_request.Voice]
	if voice == "" {
		voice = "cove"
	}
	data, status, err := chatgpt.GetTTS(client, account, msgId, convId, voice, format, proxyUrl)
	if err != nil {
		c.JSON(status, gin.H{"error": gin.H{
			"message": err.Error(),
			"type":    "synthesize_request_error",
			"param":   nil,
			"code":    status,
		}})
		return
	}
	c.Data(200, ttsTypeMap[format], data)
}

// ── Audio Transcriptions ──

var transcriptionsSupportedFormats = map[string]string{
	"json":         "application/json",
	"text":         "text/plain",
	"verbose_json": "application/json",
}

func (h *AudioHandler) Transcriptions(c *gin.Context) {
	h.handleTranscription(c, false)
}

func (h *AudioHandler) Translations(c *gin.Context) {
	h.handleTranscription(c, true)
}

func (h *AudioHandler) handleTranscription(c *gin.Context, isTranslation bool) {
	contentType := strings.Split(c.GetHeader("Content-Type"), ";")[0]
	contentType = strings.ToLower(strings.TrimSpace(contentType))
	if !strings.HasPrefix(contentType, "multipart/form-data") {
		c.JSON(400, gin.H{"error": gin.H{
			"message": "Request must be multipart/form-data",
			"type":    "invalid_request_error",
			"param":   "Content-Type",
			"code":    "invalid_content_type",
		}})
		return
	}

	if err := c.Request.ParseMultipartForm(50 << 20); err != nil {
		c.JSON(400, gin.H{"error": gin.H{
			"message": "Failed to parse multipart form: " + err.Error(),
			"type":    "invalid_request_error",
			"param":   nil,
			"code":    "parse_error",
		}})
		return
	}

	model := strings.TrimSpace(c.Request.FormValue("model"))
	language := strings.TrimSpace(c.Request.FormValue("language"))
	prompt := c.Request.FormValue("prompt")
	responseFormat := strings.TrimSpace(c.Request.FormValue("response_format"))

	if model == "" {
		model = "whisper-1"
	}
	if responseFormat == "" {
		responseFormat = "json"
	}

	respContentType, formatOK := transcriptionsSupportedFormats[responseFormat]
	if !formatOK {
		c.JSON(400, gin.H{"error": gin.H{
			"message": fmt.Sprintf("Unsupported response_format: %s. Supported values: json, text, verbose_json", responseFormat),
			"type":    "invalid_request_error",
			"param":   "response_format",
			"code":    "invalid_response_format",
		}})
		return
	}

	if len(prompt) > 1000 {
		prompt = prompt[:1000]
	}

	formFile, fileHeader, err := c.Request.FormFile("file")
	if err != nil {
		c.JSON(400, gin.H{"error": gin.H{
			"message": "Missing required multipart field: file",
			"type":    "invalid_request_error",
			"param":   "file",
			"code":    "missing_required_parameter",
		}})
		return
	}
	defer formFile.Close()

	audioData, err := io.ReadAll(formFile)
	if err != nil {
		c.JSON(400, gin.H{"error": gin.H{
			"message": err.Error(),
			"type":    "invalid_request_error",
			"param":   "file",
			"code":    "file_read_error",
		}})
		return
	}
	if len(audioData) == 0 {
		c.JSON(400, gin.H{"error": gin.H{
			"message": "Uploaded audio file is empty",
			"type":    "invalid_request_error",
			"param":   "file",
			"code":    "empty_file",
		}})
		return
	}

	account, _, err := resolveAccount(c, h.accountPool, h.cfg, true)
	if err != nil {
		c.JSON(400, gin.H{"error": gin.H{
			"message": err.Error(),
			"type":    "authorization_error",
			"param":   "Authorization",
			"code":    400,
		}})
		return
	}
	if account == nil || account.Token == "" {
		c.JSON(400, gin.H{"error": gin.H{
			"message": "Audio transcription requires a logged-in ChatGPT access token.",
			"type":    "invalid_request_error",
			"param":   "file",
			"code":    "missing_access_token",
		}})
		return
	}
	if !account.Type.Satisfies(accounts.CapTranscribe) {
		c.JSON(403, gin.H{"error": "Audio transcription requires a logged-in ChatGPT account."})
		return
	}

	proxyUrl := account.Proxy
	mimeType := fileHeader.Header.Get("Content-Type")
	if mimeType == "" {
		mimeType = "audio/mpeg"
	}

	// 使用账号绑定的 Client(有指纹 + 代理);不存在则新建
	client, ok := account.Client.(*bogdanfinn.TlsClient)
	if !ok || client == nil {
		client = bogdanfinn.NewStdClient()
		client.SetCookies("https://chatgpt.com", chatgpt.BasicCookies)
		if proxyUrl != "" {
			client.SetProxy(proxyUrl)
		}
	}

	text, status, err := chatgpt.TranscribeAudio(client, account, proxyUrl, audioData, fileHeader.Filename, mimeType, language)
	if err != nil {
		c.JSON(status, gin.H{"error": gin.H{
			"message": err.Error(),
			"type":    "transcription_error",
			"param":   nil,
			"code":    "transcription_error",
		}})
		return
	}

	switch responseFormat {
	case "json":
		c.JSON(200, officialtypes.TranscriptionResponse{Text: text})
	case "text":
		c.Data(200, "text/plain; charset=utf-8", []byte(text))
	case "verbose_json":
		c.JSON(200, officialtypes.VerboseTranscriptionResponse{
			Task:     "transcribe",
			Language: language,
			Duration: 0,
			Text:     text,
			Segments: []officialtypes.TranscriptionSegment{},
			Words:    []officialtypes.TranscriptionWord{},
		})
	default:
		c.Data(200, respContentType, []byte(text))
	}
}