Spaces:
Runtime error
Runtime error
Create main.py
Browse files
main.py
ADDED
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi import FastAPI, UploadFile, File
|
2 |
+
import torch
|
3 |
+
from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor, pipeline
|
4 |
+
|
5 |
+
app = FastAPI()
|
6 |
+
|
7 |
+
|
8 |
+
device = "cuda:0" if torch.cuda.is_available() else "cpu"
|
9 |
+
torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
|
10 |
+
|
11 |
+
model_id = "openai/whisper-large-v3"
|
12 |
+
|
13 |
+
model = AutoModelForSpeechSeq2Seq.from_pretrained(
|
14 |
+
model_id, torch_dtype=torch_dtype, low_cpu_mem_usage=True, use_safetensors=True
|
15 |
+
)
|
16 |
+
model.to(device)
|
17 |
+
|
18 |
+
processor = AutoProcessor.from_pretrained(model_id)
|
19 |
+
|
20 |
+
pipe = pipeline(
|
21 |
+
"automatic-speech-recognition",
|
22 |
+
model=model,
|
23 |
+
tokenizer=processor.tokenizer,
|
24 |
+
feature_extractor=processor.feature_extractor,
|
25 |
+
max_new_tokens=128,
|
26 |
+
chunk_length_s=30,
|
27 |
+
batch_size=16,
|
28 |
+
return_timestamps=True,
|
29 |
+
torch_dtype=torch_dtype,
|
30 |
+
device=device,
|
31 |
+
)
|
32 |
+
|
33 |
+
sample = dataset[0]["audio"]
|
34 |
+
|
35 |
+
# result = pipe(sample)
|
36 |
+
# print(result["text"])
|
37 |
+
|
38 |
+
|
39 |
+
@app.post("/speech_to_text")
|
40 |
+
async def speech_to_text(file : UploadFile = File(...))
|
41 |
+
if file:
|
42 |
+
contents = await file.read()
|
43 |
+
with open(file.filename, "wb") as f:
|
44 |
+
f.write(contents)
|
45 |
+
|
46 |
+
converted_result = pipe(file.filename)
|
47 |
+
return {
|
48 |
+
"status": 200,
|
49 |
+
"text": converted_result["text"]
|
50 |
+
}
|
51 |
+
else:
|
52 |
+
return {
|
53 |
+
"status": -1
|
54 |
+
}
|