tuan243 commited on
Commit
eee6482
·
verified ·
1 Parent(s): ead532d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +99 -71
app.py CHANGED
@@ -1,13 +1,98 @@
1
- from fastapi import FastAPI, File, UploadFile
2
- import librosa
3
- import numpy as np
4
- import shutil
5
- import uvicorn
6
- import os
7
- from funasr import AutoModel
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  from starlette.middleware import Middleware
9
  from starlette.middleware.cors import CORSMiddleware
10
-
11
  import logging
12
 
13
  logging.basicConfig(level=logging.INFO)
@@ -17,73 +102,16 @@ app = FastAPI(
17
  middleware=[
18
  Middleware(
19
  CORSMiddleware,
20
- allow_origins=["*"], # Cho phép tất cả các origin
21
  allow_credentials=True,
22
- allow_methods=["*"], # Cho phép tất cả các phương thức
23
- allow_headers=["*"], # Cho phép tất cả các header
24
  )
25
  ]
26
  )
27
- # Tạo thư mục temp nếu chưa có
28
- if not os.path.exists("temp"):
29
- os.makedirs("temp")
30
-
31
- # Load mô hình SenseVoiceSmall từ Hugging Face
32
- model_dir = "FunAudioLLM/SenseVoiceSmall"
33
- model = AutoModel(
34
- model=model_dir,
35
- vad_model="fsmn-vad",
36
- vad_kwargs={"max_single_segment_time": 30000},
37
- device="cuda:0",
38
- hub="hf",
39
- )
40
 
41
- # Hàm tính RMS energy
42
- def calculate_rms_energy(audio_path):
43
- y, sr = librosa.load(audio_path)
44
- rms = librosa.feature.rms(y=y)[0]
45
- return np.mean(rms)
46
-
47
- # Hàm phát hiện tiếng ồn
48
- def detect_noise(audio_path):
49
- rms_energy = calculate_rms_energy(audio_path)
50
- res = model.generate(input=audio_path, language="auto", audio_event_detection=True)
51
- audio_events = res[0].get("audio_event_detection", {})
52
-
53
- if rms_energy > 0.02:
54
- return "ồn ào"
55
- elif rms_energy > 0.01:
56
- for event_label, event_score in audio_events.items():
57
- if event_score > 0.7 and event_label in ["laughter", "applause", "crying", "coughing"]:
58
- return f"ồn ào ({event_label})"
59
- return "yên tĩnh"
60
-
61
- @app.get("/")
62
- def read_root():
63
- return {"message": "Hello, World!"}
64
-
65
- print(app.routes)
66
-
67
- # API nhận file âm thanh từ Flutter
68
  @app.post("/detect-noise/")
69
  async def detect_noise_api(file: UploadFile = File(...)):
70
- try:
71
- logger.info("Tên file: %s", file.filename)
72
- logger.info("Loại file: %s", file.content_type)
73
- file_size = len(await file.read())
74
- logger.info("Kích thước file: %s bytes", file_size)
75
- await file.seek(0) # Reset lại vị trí đọc file
76
-
77
- file_path = f"temp/{file.filename}"
78
- with open(file_path, "wb") as buffer:
79
- shutil.copyfileobj(file.file, buffer)
80
-
81
- result = detect_noise(file_path)
82
- return {"noise_level": result}
83
- except Exception as e:
84
- logger.exception("Lỗi trong API: %s", e)
85
- return {"error": str(e)}
86
-
87
- # Chạy FastAPI trên Hugging Face Spaces
88
- if __name__ == "__main__":
89
- uvicorn.run(app, host="0.0.0.0", port=7860)
 
1
+ # from fastapi import FastAPI, File, UploadFile
2
+ # import librosa
3
+ # import numpy as np
4
+ # import shutil
5
+ # import uvicorn
6
+ # import os
7
+ # from funasr import AutoModel
8
+ # from starlette.middleware import Middleware
9
+ # from starlette.middleware.cors import CORSMiddleware
10
+
11
+ # import logging
12
+
13
+ # logging.basicConfig(level=logging.INFO)
14
+ # logger = logging.getLogger(__name__)
15
+
16
+ # app = FastAPI(
17
+ # middleware=[
18
+ # Middleware(
19
+ # CORSMiddleware,
20
+ # allow_origins=["*"], # Cho phép tất cả các origin
21
+ # allow_credentials=True,
22
+ # allow_methods=["*"], # Cho phép tất cả các phương thức
23
+ # allow_headers=["*"], # Cho phép tất cả các header
24
+ # )
25
+ # ]
26
+ # )
27
+ # # Tạo thư mục temp nếu chưa có
28
+ # if not os.path.exists("temp"):
29
+ # os.makedirs("temp")
30
+
31
+ # # Load mô hình SenseVoiceSmall từ Hugging Face
32
+ # model_dir = "FunAudioLLM/SenseVoiceSmall"
33
+ # model = AutoModel(
34
+ # model=model_dir,
35
+ # vad_model="fsmn-vad",
36
+ # vad_kwargs={"max_single_segment_time": 30000},
37
+ # device="cuda:0",
38
+ # hub="hf",
39
+ # )
40
+
41
+ # # Hàm tính RMS energy
42
+ # def calculate_rms_energy(audio_path):
43
+ # y, sr = librosa.load(audio_path)
44
+ # rms = librosa.feature.rms(y=y)[0]
45
+ # return np.mean(rms)
46
+
47
+ # # Hàm phát hiện tiếng ồn
48
+ # def detect_noise(audio_path):
49
+ # rms_energy = calculate_rms_energy(audio_path)
50
+ # res = model.generate(input=audio_path, language="auto", audio_event_detection=True)
51
+ # audio_events = res[0].get("audio_event_detection", {})
52
+
53
+ # if rms_energy > 0.02:
54
+ # return "ồn ào"
55
+ # elif rms_energy > 0.01:
56
+ # for event_label, event_score in audio_events.items():
57
+ # if event_score > 0.7 and event_label in ["laughter", "applause", "crying", "coughing"]:
58
+ # return f"ồn ào ({event_label})"
59
+ # return "yên tĩnh"
60
+
61
+ # @app.get("/")
62
+ # def read_root():
63
+ # return {"message": "Hello, World!"}
64
+
65
+ # print(app.routes)
66
+
67
+ # # API nhận file âm thanh từ Flutter
68
+ # @app.post("/detect-noise/")
69
+ # async def detect_noise_api(file: UploadFile = File(...)):
70
+ # try:
71
+ # logger.info("Tên file: %s", file.filename)
72
+ # logger.info("Loại file: %s", file.content_type)
73
+ # file_size = len(await file.read())
74
+ # logger.info("Kích thước file: %s bytes", file_size)
75
+ # await file.seek(0) # Reset lại vị trí đọc file
76
+
77
+ # file_path = f"temp/{file.filename}"
78
+ # with open(file_path, "wb") as buffer:
79
+ # shutil.copyfileobj(file.file, buffer)
80
+
81
+ # result = detect_noise(file_path)
82
+ # return {"noise_level": result}
83
+ # except Exception as e:
84
+ # logger.exception("Lỗi trong API: %s", e)
85
+ # return {"error": str(e)}
86
+
87
+ # # Chạy FastAPI trên Hugging Face Spaces
88
+ # if __name__ == "__main__":
89
+ # uvicorn.run(app, host="0.0.0.0", port=7860)
90
+
91
+
92
+ from fastapi import FastAPI
93
+ from fastapi import File, UploadFile
94
  from starlette.middleware import Middleware
95
  from starlette.middleware.cors import CORSMiddleware
 
96
  import logging
97
 
98
  logging.basicConfig(level=logging.INFO)
 
102
  middleware=[
103
  Middleware(
104
  CORSMiddleware,
105
+ allow_origins=["*"],
106
  allow_credentials=True,
107
+ allow_methods=["*"],
108
+ allow_headers=["*"],
109
  )
110
  ]
111
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
112
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
  @app.post("/detect-noise/")
114
  async def detect_noise_api(file: UploadFile = File(...)):
115
+ logger.info("Đã nhận được yêu cầu!")
116
+ return {"message": "OK"}
117
+