NonSittinon commited on
Commit
ce20fd8
·
verified ·
1 Parent(s): bf78252

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +18 -24
app.py CHANGED
@@ -1,11 +1,11 @@
1
  """
2
- HuBERT Audio Classifier (INT8) - Gradio App สำหรับ deploy บน Hugging Face Spaces
3
 
4
  จำแนกเสียงเป็น 3 คลาส: Plant_Sounds / Normal / Noise
5
- ใช้โมเดล HuBERT ที่ fine-tune แล้วบีบอัดเป็น INT8 (dynamic quantization) รันบน CPU
6
 
7
- ต้องมีไฟล์ checkpoint "hubert_plant_normal_noise_classifier_int8.pt" อยู่โฟลเดอร์เดียวกับไฟล์นี้
8
- (export มาจากโน้ตบุ๊ก HuBERT_Plant_vs_Noise_Classifier.ipynb ส่วน "บีบอัดโมเดลเป็น INT8")
9
  """
10
 
11
  import os
@@ -23,13 +23,16 @@ import gradio as gr
23
  from transformers import HubertForSequenceClassification, Wav2Vec2FeatureExtractor
24
 
25
  # ---------------------------------------------------------------------------
26
- # 1) โหลด checkpoint + สร้างโครงสร้างโมเดล INT8 ให้ตรงกับตอน save
27
  # ---------------------------------------------------------------------------
28
  CKPT_PATH = "hubert_plant_normal_noise_classifier.pt"
29
  EXAMPLES_DIR = "examples"
30
 
 
 
 
31
  print("Loading checkpoint:", CKPT_PATH)
32
- checkpoint = torch.load(CKPT_PATH, map_location="cpu")
33
 
34
  MODEL_NAME = checkpoint["model_name"]
35
  LABEL2ID = checkpoint["label2id"]
@@ -37,23 +40,14 @@ ID2LABEL = checkpoint["id2label"]
37
  SAMPLE_RATE = checkpoint["sample_rate"]
38
  MAX_DURATION = checkpoint.get("max_duration", 1.0)
39
 
40
- # ต้องสร้างโครงสร้างโมเดล fp32 ก่อน แล้ว quantize ให้เป็นโครงสร้างเดียวกับตอน save
41
- # จากนั้นค่อย load_state_dict เข้าไป (state_dict จะตรงเป๊ะกับตอน quantize_dynamic ครั้งแรก)
42
- base_model = HubertForSequenceClassification.from_pretrained(
43
  MODEL_NAME,
44
  num_labels=len(LABEL2ID),
45
  label2id=LABEL2ID,
46
  id2label=ID2LABEL,
47
  )
48
- base_model.eval()
49
-
50
- model = torch.quantization.quantize_dynamic(
51
- base_model,
52
- {torch.nn.Linear},
53
- dtype=torch.qint8,
54
- )
55
  model.load_state_dict(checkpoint["model_state_dict"])
56
- model.to("cpu")
57
  model.eval()
58
 
59
  feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(MODEL_NAME)
@@ -85,9 +79,10 @@ def analyze_audio(audio_filepath):
85
 
86
  # ---- ทำนาย ----
87
  inputs = feature_extractor(wav_np, sampling_rate=sr, return_tensors="pt")
 
88
  with torch.no_grad():
89
- logits = model(input_values=inputs["input_values"]).logits
90
- probs = torch.softmax(logits, dim=-1).squeeze(0).numpy()
91
 
92
  pred_id = int(np.argmax(probs))
93
  pred_label = ID2LABEL[pred_id]
@@ -114,9 +109,9 @@ def analyze_audio(audio_filepath):
114
 
115
 
116
  # ---------------------------------------------------------------------------
117
- # 3) ไฟล์ตัวอย่างจากโฟลเดอร์ examples/ (ถ้ามี)
118
  # ---------------------------------------------------------------------------
119
- example_files = sorted(glob.glob(os.path.join(EXAMPLES_DIR, "*.wav"))) if os.path.isdir(EXAMPLES_DIR) else []
120
  print(f"พบไฟล์ตัวอย่าง {len(example_files)} ไฟล์ ในโฟลเดอร์ {EXAMPLES_DIR}/")
121
 
122
 
@@ -133,11 +128,10 @@ demo = gr.Interface(
133
  ],
134
  examples=example_files if example_files else None,
135
  cache_examples=False,
136
- title="🌱 HuBERT Audio Classifier (INT8): Plant_Sounds vs Normal vs Noise",
137
  description=(
138
  f"อัพโหลดไฟล์เสียง .wav ความยาว ~{MAX_DURATION:g} วินาที "
139
- f"ระบบจะจำแนกออกเป็น {len(ID2LABEL)} คลาส: {list(ID2LABEL.values())}\n\n"
140
- "โมเดลนี้เป็นเวอร์ชัน INT8 (บีบอัดแล้ว) รันบน CPU"
141
  ),
142
  )
143
 
 
1
  """
2
+ HuBERT Audio Classifier - Gradio App สำหรับ deploy บน Hugging Face Spaces
3
 
4
  จำแนกเสียงเป็น 3 คลาส: Plant_Sounds / Normal / Noise
5
+ ใช้โมเดล HuBERT ที่ fine-tune แล้ว (เวอร์ชันปกติ fp32 ไม่บีบอัด)
6
 
7
+ ต้องมีไฟล์ checkpoint "hubert_plant_normal_noise_classifier.pt" อยู่โฟลเดอร์เดียวกับไฟล์นี้
8
+ (export มาจากโน้ตบุ๊ก HuBERT_Plant_vs_Noise_Classifier.ipynb ส่วน "บันทึกโมเดลเป็นไฟล์ .pt")
9
  """
10
 
11
  import os
 
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"]
 
40
  SAMPLE_RATE = checkpoint["sample_rate"]
41
  MAX_DURATION = checkpoint.get("max_duration", 1.0)
42
 
43
+ model = HubertForSequenceClassification.from_pretrained(
 
 
44
  MODEL_NAME,
45
  num_labels=len(LABEL2ID),
46
  label2id=LABEL2ID,
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)
 
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
 
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
 
 
128
  ],
129
  examples=example_files if example_files else None,
130
  cache_examples=False,
131
+ title="🌱 HuBERT Audio Classifier: Plant_Sounds vs Normal vs Noise",
132
  description=(
133
  f"อัพโหลดไฟล์เสียง .wav ความยาว ~{MAX_DURATION:g} วินาที "
134
+ f"ระบบจะจำแนกออกเป็น {len(ID2LABEL)} คลาส: {list(ID2LABEL.values())}"
 
135
  ),
136
  )
137