NonSittinon commited on
Commit
f59a1cb
·
verified ·
1 Parent(s): 6f82f53

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +34 -13
app.py CHANGED
@@ -23,16 +23,25 @@ import gradio as gr
23
  from transformers import HubertForSequenceClassification, Wav2Vec2FeatureExtractor
24
 
25
  # ---------------------------------------------------------------------------
26
- # 1) โหลด checkpoint + สร้างโมเดล
 
 
 
 
 
 
 
 
 
 
 
 
27
  # ---------------------------------------------------------------------------
28
  CKPT_PATH = "hubert_plant_normal_noise_classifier.pt"
29
  EXAMPLES_DIR = "examples"
30
 
31
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
32
- print("Using device:", device)
33
-
34
  print("Loading checkpoint:", CKPT_PATH)
35
- checkpoint = torch.load(CKPT_PATH, map_location=device)
36
 
37
  MODEL_NAME = checkpoint["model_name"]
38
  LABEL2ID = checkpoint["label2id"]
@@ -47,8 +56,9 @@ model = HubertForSequenceClassification.from_pretrained(
47
  id2label=ID2LABEL,
48
  )
49
  model.load_state_dict(checkpoint["model_state_dict"])
50
- model.to(device)
51
  model.eval()
 
 
52
 
53
  feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(MODEL_NAME)
54
 
@@ -56,7 +66,21 @@ print(f"โหลดโมเดลเรียบร้อย | คลาส: {
56
 
57
 
58
  # ---------------------------------------------------------------------------
59
- # 2) ฟังก์ชันวิเคราะห์เสียง: ทำนาย + โชว์ waveform/spectrogram
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  # ---------------------------------------------------------------------------
61
  def analyze_audio(audio_filepath):
62
  if audio_filepath is None:
@@ -79,10 +103,7 @@ def analyze_audio(audio_filepath):
79
 
80
  # ---- ทำนาย ----
81
  inputs = feature_extractor(wav_np, sampling_rate=sr, return_tensors="pt")
82
- input_values = inputs["input_values"].to(device)
83
- with torch.no_grad():
84
- logits = model(input_values=input_values).logits
85
- probs = torch.softmax(logits, dim=-1).squeeze(0).cpu().numpy()
86
 
87
  pred_id = int(np.argmax(probs))
88
  pred_label = ID2LABEL[pred_id]
@@ -109,14 +130,14 @@ def analyze_audio(audio_filepath):
109
 
110
 
111
  # ---------------------------------------------------------------------------
112
- # 3) ไฟล์ตัวอย่างจากโฟลเดอร์ examples/ (รองรับโฟลเดอร์ย่อยตามคลาสด้วย)
113
  # ---------------------------------------------------------------------------
114
  example_files = sorted(glob.glob(os.path.join(EXAMPLES_DIR, "**", "*.wav"), recursive=True)) if os.path.isdir(EXAMPLES_DIR) else []
115
  print(f"พบไฟล์ตัวอย่าง {len(example_files)} ��ฟล์ ในโฟลเดอร์ {EXAMPLES_DIR}/")
116
 
117
 
118
  # ---------------------------------------------------------------------------
119
- # 4) Gradio Interface
120
  # ---------------------------------------------------------------------------
121
  demo = gr.Interface(
122
  fn=analyze_audio,
 
23
  from transformers import HubertForSequenceClassification, Wav2Vec2FeatureExtractor
24
 
25
  # ---------------------------------------------------------------------------
26
+ # 0) รองรับ Hugging Face ZeroGPU (ถ้า Space ตั้ง Hardware เป็น ZeroGPU)
27
+ # ZeroGPU กำหนดว่าต้องมีอย่างน้อย 1 ฟังก์ชันติด @spaces.GPU ไม่งั้นจะ error ตอน startup
28
+ # ถ้ารันบน Space ปกติ (CPU basic / GPU ธรรมดา) หรือรันในเครื่องตัวเอง decorator นี้จะไม่มีผลอะไร ปลอดภัย
29
+ # ---------------------------------------------------------------------------
30
+ try:
31
+ import spaces
32
+ GPU_DECORATOR = spaces.GPU
33
+ except ImportError:
34
+ def GPU_DECORATOR(fn): # เผื่อรันนอก Hugging Face Spaces (เช่นในเครื่องตัวเอง) ที่ไม่มี package "spaces"
35
+ return fn
36
+
37
+ # ---------------------------------------------------------------------------
38
+ # 1) โหลด checkpoint + สร้างโมเดล (โหลดไว้บน CPU ก่อนเสมอ)
39
  # ---------------------------------------------------------------------------
40
  CKPT_PATH = "hubert_plant_normal_noise_classifier.pt"
41
  EXAMPLES_DIR = "examples"
42
 
 
 
 
43
  print("Loading checkpoint:", CKPT_PATH)
44
+ checkpoint = torch.load(CKPT_PATH, map_location="cpu")
45
 
46
  MODEL_NAME = checkpoint["model_name"]
47
  LABEL2ID = checkpoint["label2id"]
 
56
  id2label=ID2LABEL,
57
  )
58
  model.load_state_dict(checkpoint["model_state_dict"])
 
59
  model.eval()
60
+ # หมายเหตุ: ไม่ .to("cuda") ตรงนี้ตั้งแต่ตอน startup เพราะ Space แบบ ZeroGPU จะยังไม่จ่าย GPU ให้
61
+ # จนกว่าจะเข้าไปในฟังก์ชันที่ติด @spaces.GPU (ดูฟังก์ชัน _run_inference ด้านล่าง)
62
 
63
  feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(MODEL_NAME)
64
 
 
66
 
67
 
68
  # ---------------------------------------------------------------------------
69
+ # 2) ฟังก์ชันรัน inference บน GPU (ติด @spaces.GPU เพื่อให้ ZeroGPU จ่าย GPU มาให้ตอนเรียกฟังก์ชันนี้)
70
+ # ---------------------------------------------------------------------------
71
+ @GPU_DECORATOR
72
+ def _run_inference(input_values):
73
+ infer_device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
74
+ model.to(infer_device)
75
+ input_values = input_values.to(infer_device)
76
+ with torch.no_grad():
77
+ logits = model(input_values=input_values).logits
78
+ probs = torch.softmax(logits, dim=-1).squeeze(0).cpu().numpy()
79
+ return probs
80
+
81
+
82
+ # ---------------------------------------------------------------------------
83
+ # 3) ฟังก์ชันวิเคราะห์เสียง: ทำนาย + โชว์ waveform/spectrogram
84
  # ---------------------------------------------------------------------------
85
  def analyze_audio(audio_filepath):
86
  if audio_filepath is None:
 
103
 
104
  # ---- ทำนาย ----
105
  inputs = feature_extractor(wav_np, sampling_rate=sr, return_tensors="pt")
106
+ probs = _run_inference(inputs["input_values"])
 
 
 
107
 
108
  pred_id = int(np.argmax(probs))
109
  pred_label = ID2LABEL[pred_id]
 
130
 
131
 
132
  # ---------------------------------------------------------------------------
133
+ # 4) ไฟล์ตัวอย่างจากโฟลเดอร์ examples/ (รองรับโฟลเดอร์ย่อยตามคลาสด้วย)
134
  # ---------------------------------------------------------------------------
135
  example_files = sorted(glob.glob(os.path.join(EXAMPLES_DIR, "**", "*.wav"), recursive=True)) if os.path.isdir(EXAMPLES_DIR) else []
136
  print(f"พบไฟล์ตัวอย่าง {len(example_files)} ��ฟล์ ในโฟลเดอร์ {EXAMPLES_DIR}/")
137
 
138
 
139
  # ---------------------------------------------------------------------------
140
+ # 5) Gradio Interface
141
  # ---------------------------------------------------------------------------
142
  demo = gr.Interface(
143
  fn=analyze_audio,