pyqt 分類標注工具:
import glob
import sys
import json
import os
from PyQt5.QtWidgets import (QApplication, QMainWindow, QTableWidget, QTableWidgetItem,QSplitter, QVBoxLayout, QWidget, QPushButton, QRadioButton,QButtonGroup, QLabel, QHBoxLayout, QMessageBox
)
from PyQt5.QtCore import Qt, QUrl
from PyQt5.QtGui import QColor
from PyQt5.QtMultimedia import QMediaPlayer, QMediaContentclass AudioAnnotator(QMainWindow):def __init__(self,base_dir):super().__init__()self.setWindowTitle("MP3標注工具 (單選標注)")self.setGeometry(100, 100, 1000, 600) # 增大窗口尺寸# 初始化媒體播放器self.player = QMediaPlayer()# 主布局main_widget = QWidget()self.setCentralWidget(main_widget)layout = QVBoxLayout()main_widget.setLayout(layout)# 分割左右區域splitter = QSplitter(Qt.Horizontal)# 左側:音頻文件列表(表格)self.table = QTableWidget()self.table.setColumnCount(2)self.table.setHorizontalHeaderLabels(["音頻文件", "標注狀態"])self.table.setEditTriggers(QTableWidget.NoEditTriggers)self.table.cellClicked.connect(self.play_audio)self.table.setColumnWidth(0, 400) # 文件名列寬self.table.setColumnWidth(1, 150) # 狀態列寬# 右側:單選標注區域right_panel = QWidget()right_layout = QVBoxLayout()# 單選按鈕組self.radio_group = QButtonGroup()self.radio_1 = QRadioButton("small (1)")self.radio_2 = QRadioButton("normal (2)")self.radio_3 = QRadioButton("3 (3)")self.radio_group.addButton(self.radio_1, 1)self.radio_group.addButton(self.radio_2, 2)self.radio_group.addButton(self.radio_3, 3)self.radio_group.buttonClicked[int].connect(self.on_radio_selected)right_layout.addWidget(QLabel("標注選項:"))right_layout.addWidget(self.radio_1)right_layout.addWidget(self.radio_2)right_layout.addWidget(self.radio_3)right_layout.addStretch()right_panel.setLayout(right_layout)# 底部按鈕self.btn_save = QPushButton("保存標注")self.btn_save.clicked.connect(self.save_annotation)# 添加到布局splitter.addWidget(self.table)splitter.addWidget(right_panel)layout.addWidget(splitter)layout.addWidget(self.btn_save)self.json_path=os.path.basename(base_dir)+'.json'files = glob.glob(base_dir + "/*.mp3")self.audio_files = files# 加載歷史標注self.annotations = {}self.load_annotations()self.load_audio_files()def on_radio_selected(self, checked_id):print(f"選中了按鈕 ID: {checked_id}")current_row = self.table.currentRow()if current_row >= 0:audio_file = self.audio_files[current_row]checked_id = self.radio_group.checkedId()if checked_id == -1:QMessageBox.warning(self, "警告", "請選擇標注選項!")return# 更新標注字典self.annotations[audio_file] = checked_id# 保存到JSON文件with open(self.json_path, "w", encoding="utf-8") as f:json.dump(self.annotations, f, ensure_ascii=False, indent=4)# 更新表格顯示self.load_audio_files()def load_audio_files(self):"""加載音頻文件到表格并顯示標注狀態"""self.table.setRowCount(len(self.audio_files))# 標注選項映射label_map = {1: "small", 2: "normal", 3: "3"}for i, file in enumerate(self.audio_files):# 文件名列file_item = QTableWidgetItem(file)self.table.setItem(i, 0, file_item)# 狀態列status_item = QTableWidgetItem()if file in self.annotations:label_id = self.annotations[file]status_item.setText(f"已標注: {label_map.get(label_id, '未知')}")file_item.setBackground(QColor(200, 255, 200)) # 淺綠色背景status_item.setBackground(QColor(200, 255, 200))else:status_item.setText("未標注")file_item.setBackground(QColor(255, 200, 200)) # 淺紅色背景status_item.setBackground(QColor(255, 200, 200))self.table.setItem(i, 1, status_item)def play_audio(self, row, column):if column > 0: # 只在點擊第一列時觸發returnfile_path = self.audio_files[row]print('start play',file_path)media_content = QMediaContent(QUrl.fromLocalFile(file_path))self.player.setMedia(media_content)self.player.play()# 加載該音頻的歷史標注if file_path in self.annotations:checked_id = self.annotations[file_path]self.radio_group.button(checked_id).setChecked(True)else:self.radio_group.setExclusive(False)for btn in self.radio_group.buttons():btn.setChecked(False)self.radio_group.setExclusive(True)def save_annotation(self):"""保存標注到JSON文件"""current_row = self.table.currentRow()if current_row >= 0:audio_file = self.audio_files[current_row]checked_id = self.radio_group.checkedId()if checked_id == -1:QMessageBox.warning(self, "警告", "請選擇標注選項!")return# 更新標注字典self.annotations[audio_file] = checked_id# 保存到JSON文件with open(self.json_path, "w", encoding="utf-8") as f:json.dump(self.annotations, f, ensure_ascii=False, indent=4)# 更新表格顯示self.load_audio_files()QMessageBox.information(self, "成功", f"標注已保存:{os.path.basename(audio_file)} -> {checked_id}")else:QMessageBox.warning(self, "警告", "請先選中音頻文件!")def load_annotations(self):"""加載歷史標注文件"""if os.path.exists(self.json_path):try:with open(self.json_path, "r", encoding="utf-8") as f:self.annotations = json.load(f)# 轉換鍵為絕對路徑(如果保存的是相對路徑)base_dir = os.path.dirname(os.path.abspath(self.json_path))fixed_annotations = {}for k, v in self.annotations.items():if not os.path.isabs(k):fixed_path = os.path.join(base_dir, k)if os.path.exists(fixed_path):fixed_annotations[fixed_path] = velse:fixed_annotations[k] = velse:fixed_annotations[k] = vself.annotations = fixed_annotationsexcept Exception as e:QMessageBox.warning(self, "警告", f"加載標注文件出錯: {str(e)}")self.annotations = {}if __name__ == "__main__":base_dir = r"/Users/lbg/Documents/data/audio_0817_low"app = QApplication(sys.argv)window = AudioAnnotator(base_dir)window.show()sys.exit(app.exec_())