File size: 12,641 Bytes
b310def
 
 
60b9834
5c7869e
 
60b9834
 
5899d37
b310def
60b9834
b310def
 
 
c1ac6cf
b310def
 
 
 
 
 
f9e54c0
9587328
b310def
 
 
 
 
60b9834
b310def
 
 
 
 
 
 
 
660c142
b310def
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60b9834
660c142
 
 
 
 
 
 
b310def
 
60b9834
660c142
 
 
 
 
 
 
 
b310def
 
60b9834
b310def
660c142
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b310def
660c142
 
 
 
b310def
 
60b9834
660c142
 
 
 
 
 
b310def
 
60b9834
 
b310def
 
60b9834
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b310def
60b9834
b310def
60b9834
 
 
b310def
 
60b9834
 
 
 
b310def
60b9834
 
b310def
60b9834
 
b310def
60b9834
 
 
 
 
 
 
 
 
 
b310def
60b9834
 
 
 
 
 
 
 
 
 
 
b310def
 
5899d37
660c142
 
 
 
 
 
 
 
 
5899d37
660c142
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
373e485
b310def
660c142
 
 
 
 
 
 
 
 
 
 
 
b310def
 
5899d37
660c142
 
 
5899d37
 
b310def
 
 
660c142
 
 
 
b310def
 
60b9834
 
b310def
 
 
 
 
 
 
 
 
 
 
660c142
 
b310def
60b9834
660c142
b310def
 
660c142
 
 
 
b310def
 
660c142
b310def
f9e54c0
b310def
 
660c142
f9e54c0
 
 
 
660c142
f9e54c0
 
 
660c142
f9e54c0
 
 
 
660c142
f9e54c0
 
 
660c142
f9e54c0
 
 
 
660c142
f9e54c0
 
 
660c142
b310def
 
f9e54c0
 
 
 
 
 
 
b310def
 
f9e54c0
 
 
 
 
 
b310def
 
60b9834
 
9587328
 
60b9834
9587328
60b9834
 
 
 
3b8b027
9587328
660c142
5899d37
 
9587328
 
 
60b9834
9587328
60b9834
9587328
 
 
60b9834
 
 
 
 
9587328
 
 
60b9834
9587328
 
60b9834
 
 
9587328
2711de6
 
9587328
 
 
60b9834
9587328
 
60b9834
9587328
 
 
c1ac6cf
 
 
60b9834
9587328
c1ac6cf
 
60b9834
c1ac6cf
 
9587328
c1ac6cf
b310def
 
8b3957e
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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
# coding=utf-8

from io import BytesIO
from typing import Optional, Dict, Any, List, Set, Union, Tuple

# System Libraries
import os
import time
import asyncio

# Third-party imports
from fastapi import FastAPI, File, UploadFile, HTTPException, Depends
from fastapi.middleware.cors import CORSMiddleware
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from fastapi.responses import HTMLResponse
import numpy as np
import torch
import torchaudio
from funasr import AutoModel
from dotenv import load_dotenv
import os
import time
import gradio as gr

# ๅŠ ่ฝฝ็Žฏๅขƒๅ˜้‡
load_dotenv()

# ่Žทๅ–API Token
API_TOKEN: str = os.getenv("API_TOKEN")
if not API_TOKEN:
    raise RuntimeError("API_TOKEN environment variable is not set")

# ่ฎพ็ฝฎ่ฎค่ฏ
security = HTTPBearer()

app = FastAPI(
    title="SenseVoice API",
    description="Speech To Text API Service",
    version="1.0.0"
)

# ๅ…่ฎธ่ทจๅŸŸ่ฏทๆฑ‚
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# ๅˆๅง‹ๅŒ–ๆจกๅž‹
model = AutoModel(
    model="FunAudioLLM/SenseVoiceSmall",
    vad_model="iic/speech_fsmn_vad_zh-cn-16k-common-pytorch",
    vad_kwargs={"max_single_segment_time": 30000},
    hub="hf",
    device="cuda"
)

emotion_dict: Dict[str, str] = {
    "<|HAPPY|>":        "๐Ÿ˜Š",
    "<|SAD|>":          "๐Ÿ˜”",
    "<|ANGRY|>":        "๐Ÿ˜ก",
    "<|NEUTRAL|>":      "",
    "<|FEARFUL|>":      "๐Ÿ˜ฐ",
    "<|DISGUSTED|>":    "๐Ÿคข",
    "<|SURPRISED|>":    "๐Ÿ˜ฎ",
}

event_dict: Dict[str, str] = {
    "<|BGM|>":          "๐ŸŽผ",
    "<|Speech|>":       "",
    "<|Applause|>":     "๐Ÿ‘",
    "<|Laughter|>":     "๐Ÿ˜€",
    "<|Cry|>":          "๐Ÿ˜ญ",
    "<|Sneeze|>":       "๐Ÿคง",
    "<|Breath|>":       "",
    "<|Cough|>":        "๐Ÿคง",
}

emoji_dict: Dict[str, str] = {
    "<|nospeech|><|Event_UNK|>": "โ“",
    "<|zh|>":           "",
    "<|en|>":           "",
    "<|yue|>":          "",
    "<|ja|>":           "",
    "<|ko|>":           "",
    "<|nospeech|>":     "",
    "<|HAPPY|>":        "๐Ÿ˜Š",
    "<|SAD|>":          "๐Ÿ˜”",
    "<|ANGRY|>":        "๐Ÿ˜ก",
    "<|NEUTRAL|>":      "",
    "<|BGM|>":          "๐ŸŽผ",
    "<|Speech|>":       "",
    "<|Applause|>":     "๐Ÿ‘",
    "<|Laughter|>":     "๐Ÿ˜€",
    "<|FEARFUL|>":      "๐Ÿ˜ฐ",
    "<|DISGUSTED|>":    "๐Ÿคข",
    "<|SURPRISED|>":    "๐Ÿ˜ฎ",
    "<|Cry|>":          "๐Ÿ˜ญ",
    "<|EMO_UNKNOWN|>":  "",
    "<|Sneeze|>":       "๐Ÿคง",
    "<|Breath|>":       "",
    "<|Cough|>":        "๐Ÿ˜ท",
    "<|Sing|>":         "",
    "<|Speech_Noise|>": "",
    "<|withitn|>":      "",
    "<|woitn|>":        "",
    "<|GBG|>":          "",
    "<|Event_UNK|>":    "",
}

lang_dict: Dict[str, str] = {
    "<|zh|>":           "<|lang|>",
    "<|en|>":           "<|lang|>",
    "<|yue|>":          "<|lang|>",
    "<|ja|>":           "<|lang|>",
    "<|ko|>":           "<|lang|>",
    "<|nospeech|>":     "<|lang|>",
}

emo_set: Set[str] = {"๐Ÿ˜Š", "๐Ÿ˜”", "๐Ÿ˜ก", "๐Ÿ˜ฐ", "๐Ÿคข", "๐Ÿ˜ฎ"}
event_set: Set[str] = {"๐ŸŽผ", "๐Ÿ‘", "๐Ÿ˜€", "๐Ÿ˜ญ", "๐Ÿคง", "๐Ÿ˜ท"}


def format_text_with_emotion(text: str) -> str:
    """Format text with emotion and event markers"""
    token_count: Dict[str, int] = {}
    original_text = text
    for token in emoji_dict:
        token_count[token] = text.count(token)
    
    # Determine dominant emotion
    dominant_emotion = "<|NEUTRAL|>"
    for emotion in emotion_dict:
        if token_count[emotion] > token_count[dominant_emotion]:
            dominant_emotion = emotion
    
    # Add event markers
    text = original_text
    for event in event_dict:
        if token_count[event] > 0:
            text = event_dict[event] + text
    
    # Replace all tokens with their emoji equivalents
    for token in emoji_dict:
        text = text.replace(token, emoji_dict[token])
    
    # Add dominant emotion
    text = text + emotion_dict[dominant_emotion]

    # Clean up emoji spacing
    for emoji in emo_set.union(event_set):
        text = text.replace(" " + emoji, emoji)
        text = text.replace(emoji + " ", emoji)
    return text.strip()


def format_text_advanced(text: str) -> str:
    """Advanced text formatting with multilingual and complex token handling"""
    def get_emotion(text: str) -> Optional[str]:
        return text[-1] if text[-1] in emo_set else None

    def get_event(text: str) -> Optional[str]:
        return text[0] if text[0] in event_set else None

    # Handle special cases
    text = text.replace("<|nospeech|><|Event_UNK|>", "โ“")
    for lang in lang_dict:
        text = text.replace(lang, "<|lang|>")
    
    # Process text segments
    text_segments: List[str] = [format_text_with_emotion(segment).strip() for segment in text.split("<|lang|>")]
    formatted_text = " " + text_segments[0]
    current_event = get_event(formatted_text)

    # Merge segments
    for i in range(1, len(text_segments)):
        if not text_segments[i]:
            continue

        if get_event(text_segments[i]) == current_event and get_event(text_segments[i]) is not None:
            text_segments[i] = text_segments[i][1:]
        current_event = get_event(text_segments[i])

        if get_emotion(text_segments[i]) is not None and get_emotion(text_segments[i]) == get_emotion(formatted_text):
            formatted_text = formatted_text[:-1]
        formatted_text += text_segments[i].strip()

    formatted_text = formatted_text.replace("The.", " ")
    return formatted_text.strip()


async def audio_stt(audio: torch.Tensor, sample_rate: int, language: str = "auto") -> str:
    """Process audio tensor and perform speech-to-text conversion.
    
    Args:
        audio: Input audio tensor
        sample_rate: Audio sample rate in Hz
        language: Target language code (auto/zh/en/yue/ja/ko/nospeech)
    
    Returns:
        str: Transcribed and formatted text result
    """
    try:
        # Normalize
        if audio.dtype != torch.float32:
            if audio.dtype == torch.int16:
                audio = audio.float() / torch.iinfo(torch.int16).max
            elif audio.dtype == torch.int32:
                audio = audio.float() / torch.iinfo(torch.int32).max
            else:
                audio = audio.float()
        
        # Make sure audio in correct range
        if audio.abs().max() > 1.0:
            audio = audio / audio.abs().max()
        
        # Convert to mono channel
        if len(audio.shape) > 1:
            audio = audio.mean(dim=0)
        audio = audio.squeeze()
        
        # Resample
        if sample_rate != 16000:
            resampler = torchaudio.transforms.Resample(
                orig_freq=sample_rate,
                new_freq=16000
            )
            audio = resampler(audio.unsqueeze(0)).squeeze(0)
        
        text = model.generate(
            input=audio,
            cache={},
            language=language,
            use_itn=True,
            batch_size_s=500,
            merge_vad=True
        )
        
        # ๆ ผๅผๅŒ–็ป“ๆžœ
        result = text[0]["text"]
        return format_text_advanced(result)
    
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"Audio processing failed in audio_stt: {str(e)}"
        )

async def process_audio(audio_data: bytes, language: str = "auto") -> str:
    """Process audio data and return transcription result.
    
    Args:
        audio_data: Raw audio data in bytes
        language: Target language code
        
    Returns:
        str: Transcribed and formatted text
        
    Raises:
        HTTPException: If audio processing fails
    """
    try:
        audio_buffer = BytesIO(audio_data)
        waveform, sample_rate = torchaudio.load(
            uri=audio_buffer,
            normalize=True,
            channels_first=True
        )
        result = await audio_stt(waveform, sample_rate, language)
        return result
    
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"Audio processing failed: {str(e)}"
        )


async def verify_token(credentials: HTTPAuthorizationCredentials = Depends(security)) -> HTTPAuthorizationCredentials:
    """Verify Bearer Token authentication"""
    if credentials.credentials != API_TOKEN:
        raise HTTPException(
            status_code=401,
            detail="Invalid authentication token",
            headers={"WWW-Authenticate": "Bearer"}
        )
    return credentials

@app.post("/v1/audio/transcriptions")
async def transcribe_audio(
    file: UploadFile = File(...),
    model: str = "FunAudioLLM/SenseVoiceSmall",
    language: str = "auto",
    token: HTTPAuthorizationCredentials = Depends(verify_token)
) -> Dict[str, Union[str, int, float]]:
    """Audio transcription endpoint.
    
    Args:
        file: Audio file (supports mp3, wav, flac, ogg, m4a)
        model: Model name
        language: Language code
        token: Authentication token
    
    Returns:
        Dict containing transcription result and metadata
    """
    start_time = time.time()
    
    try:
        # Check the file format
        if not file.filename.lower().endswith((".mp3", ".wav", ".flac", ".ogg", ".m4a")):
            return {
                "text": "",
                "error_code": 400,
                "error_msg": "ไธๆ”ฏๆŒ็š„้Ÿณ้ข‘ๆ ผๅผ",
                "process_time": time.time() - start_time
            }
        
        # Check the model
        if model != "FunAudioLLM/SenseVoiceSmall":
            return {
                "text": "",
                "error_code": 400,
                "error_msg": "ไธๆ”ฏๆŒ็š„ๆจกๅž‹",
                "process_time": time.time() - start_time
            }
        
        # Check the language
        if language not in ["auto", "zh", "en", "yue", "ja", "ko", "nospeech"]:
            return {
                "text": "",
                "error_code": 400,
                "error_msg": "ไธๆ”ฏๆŒ็š„่ฏญ่จ€",
                "process_time": time.time() - start_time
            }
        
        # STT
        content = await file.read()
        text = await process_audio(content, language)
        
        return {
            "text": text,
            "error_code": 0,
            "error_msg": "",
            "process_time": time.time() - start_time
        }
    
    except Exception as e:
        return {
            "text": "",
            "error_code": 500,
            "error_msg": str(e),
            "process_time": time.time() - start_time
        }


def transcribe_audio_gradio(audio: Optional[Tuple[int, np.ndarray]], language: str = "auto") -> str:
    """Gradio interface for audio transcription"""
    try:
        if audio is None:
            return "Please upload an audio file"
        
        # Extract audio data
        sample_rate, input_wav = audio
        
        # Normalize audio
        input_wav = input_wav.astype(np.float32) / np.iinfo(np.int16).max
        
        # Model Inference
        input_wav = torch.from_numpy(input_wav)
        result = asyncio.run(audio_stt(input_wav, sample_rate, language))
        
        return result
    except Exception as e:
        return f"Processing failed: {str(e)}"

# Create Gradio interface with localized labels
demo = gr.Interface(
    fn=transcribe_audio_gradio,
    inputs=[
        gr.Audio(
            sources=["upload", "microphone"],
            type="numpy",
            label="Upload audio or record from microphone"
        ),
        gr.Dropdown(
            choices=["auto", "zh", "en", "yue", "ja", "ko", "nospeech"],
            value="auto",
            label="Select Language"
        )
    ],
    outputs=gr.Textbox(label="Recognition Result"),
    title="SenseVoice Speech Recognition",
    description="Multi-language speech transcription service supporting Chinese, English, Cantonese, Japanese, and Korean",
    examples=[
        ["examples/zh.mp3", "zh"],
        ["examples/en.mp3", "en"],
    ]
)

# Mount Gradio app to FastAPI
app = gr.mount_gradio_app(app, demo, path="/")

# Custom Swagger UI redirect
@app.get("/docs", include_in_schema=False)
async def custom_swagger_ui_html():
    return HTMLResponse("""
    <!DOCTYPE html>
    <html>
        <head>
            <title>SenseVoice API Documentation</title>
            <meta http-equiv="refresh" content="0;url=/docs/" />
        </head>
        <body>
            <p>Redirecting to API documentation...</p>
        </body>
    </html>
    """)

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=7860)