tuan243 commited on
Commit
79616b0
·
verified ·
1 Parent(s): c8e63c7

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -0
app.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, File, UploadFile
2
+ import librosa
3
+ import numpy as np
4
+ import shutil
5
+ from funasr import AutoModel
6
+
7
+ app = FastAPI()
8
+
9
+ # Load mô hình SenseVoiceSmall
10
+ model_dir = "FunAudioLLM/SenseVoiceSmall"
11
+ model = AutoModel(model=model_dir, vad_model="fsmn-vad", vad_kwargs={"max_single_segment_time": 30000}, device="cpu", hub="hf")
12
+
13
+ # Hàm tính RMS energy
14
+ def calculate_rms_energy(audio_path):
15
+ y, sr = librosa.load(audio_path)
16
+ rms = librosa.feature.rms(y=y)[0]
17
+ return np.mean(rms)
18
+
19
+ # Hàm phát hiện tiếng ồn
20
+ def detect_noise(audio_path):
21
+ rms_energy = calculate_rms_energy(audio_path)
22
+ res = model.generate(input=audio_path, language="auto", audio_event_detection=True)
23
+ audio_events = res[0].get("audio_event_detection", {})
24
+
25
+ if rms_energy > 0.02:
26
+ return "ồn ào"
27
+ elif rms_energy > 0.01:
28
+ for event_label, event_score in audio_events.items():
29
+ if event_score > 0.7 and event_label in ["laughter", "applause", "crying", "coughing"]:
30
+ return f"ồn ào ({event_label})"
31
+ return "yên tĩnh"
32
+
33
+ # API nhận file âm thanh từ Flutter
34
+ @app.post("/detect-noise/")
35
+ async def detect_noise_api(file: UploadFile = File(...)):
36
+ file_path = f"temp/{file.filename}"
37
+ with open(file_path, "wb") as buffer:
38
+ shutil.copyfileobj(file.file, buffer)
39
+
40
+ result = detect_noise(file_path)
41
+ return {"noise_level": result}