missvector commited on
Commit
fcd4871
·
1 Parent(s): 45725c3

fix: use window.location.origin for transcribe endpoint

Browse files
Files changed (2) hide show
  1. app.py +27 -24
  2. static/script.js +29 -8
app.py CHANGED
@@ -2,8 +2,9 @@ import os
2
  import tempfile
3
  import time
4
  import pathlib
 
5
  from fastapi import FastAPI, File, UploadFile
6
- from fastapi.responses import HTMLResponse, JSONResponse
7
  from fastapi.staticfiles import StaticFiles
8
  from fastapi.middleware.cors import CORSMiddleware
9
  from faster_whisper import WhisperModel
@@ -41,28 +42,30 @@ async def root():
41
  return f.read()
42
 
43
  @app.post("/transcribe")
44
- async def transcribe_audio(file: UploadFile = File(...)):
45
- try:
46
- suffix = Path(file.filename).suffix
47
- with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
48
- shutil.copyfileobj(file.file, tmp)
49
- tmp_path = tmp.name
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
 
51
- loop = asyncio.get_event_loop()
52
- result = await loop.run_in_executor(
53
- executor,
54
- partial(model.transcribe, tmp_path, language="ru")
55
- )
56
-
57
- text = result["text"].strip()
58
- Path(tmp_path).unlink()
59
-
60
- return JSONResponse({"text": text, "status": "ok"})
61
 
62
- except Exception as e:
63
- return JSONResponse(
64
- {"text": f"Error {str(e)}", "status": "error"},
65
- status_code=500
66
- )
67
- finally:
68
- file.file.close()
 
2
  import tempfile
3
  import time
4
  import pathlib
5
+ import json
6
  from fastapi import FastAPI, File, UploadFile
7
+ from fastapi.responses import HTMLResponse, JSONResponse, StreamingResponse
8
  from fastapi.staticfiles import StaticFiles
9
  from fastapi.middleware.cors import CORSMiddleware
10
  from faster_whisper import WhisperModel
 
42
  return f.read()
43
 
44
  @app.post("/transcribe")
45
+ async def transcribe_audio_stream(file: UploadFile = File(...)):
46
+ async def generate():
47
+ try:
48
+ suffix = Path(file.filename).suffix
49
+ with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
50
+ shutil.copyfileobj(file.file, tmp)
51
+ tmp_path = tmp.name
52
+
53
+ yield json.dumps({"status": "processing", "message": "Загрузка модели..."}) + "\n"
54
+
55
+ loop = asyncio.get_event_loop()
56
+ result = await loop.run_in_executor(
57
+ executor,
58
+ partial(model.transcribe, tmp_path, language="ru")
59
+ )
60
+
61
+ text = result["text"].strip()
62
+ Path(tmp_path).unlink()
63
+
64
+ yield json.dumps({"status": "ok", "text": text}) + "\n"
65
 
66
+ except Exception as e:
67
+ yield json.dumps({"status": "error", "text": f"Ошибка: {str(e)}"}) + "\n"
68
+ finally:
69
+ file.file.close()
 
 
 
 
 
 
70
 
71
+ return StreamingResponse(generate(), media_type="application/x-ndjson")
 
 
 
 
 
 
static/script.js CHANGED
@@ -72,21 +72,42 @@ async function handleFile(file) {
72
  formData.append('file', file);
73
 
74
  try {
75
- const baseUrl = window.location.origin;
76
- const response = await fetch('transcribe', {
77
  method: 'POST',
78
  body: formData
79
  });
80
 
81
- const data = await response.json();
 
 
82
 
83
- if (data.status === 'ok') {
84
- transcriptText.value = data.text;
85
- } else {
86
- transcriptText.value = data.text;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
  }
88
  } catch (error) {
89
- transcriptText.value = 'Connection Error';
90
  console.error(error);
91
  }
92
  }
 
72
  formData.append('file', file);
73
 
74
  try {
75
+ const response = await fetch('/transcribe', {
 
76
  method: 'POST',
77
  body: formData
78
  });
79
 
80
+ const reader = response.body.getReader();
81
+ const decoder = new TextDecoder();
82
+ let buffer = '';
83
 
84
+ while (true) {
85
+ const { value, done } = await reader.read();
86
+ if (done) break;
87
+
88
+ buffer += decoder.decode(value, { stream: true });
89
+ const lines = buffer.split('\n');
90
+ buffer = lines.pop();
91
+
92
+ for (const line of lines) {
93
+ if (line.trim()) {
94
+ try {
95
+ const data = JSON.parse(line);
96
+ if (data.status === 'ok') {
97
+ transcriptText.value = data.text;
98
+ } else if (data.status === 'error') {
99
+ transcriptText.value = data.text;
100
+ } else if (data.status === 'processing') {
101
+ transcriptText.value = data.message;
102
+ }
103
+ } catch (e) {
104
+ console.error('Error parsing JSON:', e);
105
+ }
106
+ }
107
+ }
108
  }
109
  } catch (error) {
110
+ transcriptText.value = 'Ошибка соединения';
111
  console.error(error);
112
  }
113
  }