pretrain_service.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. import csv
  2. import threading
  3. from pathlib import Path
  4. _PRETRAIN_CSV_NAME = "预训练之文件头.csv"
  5. _CSV_COLUMNS = ["id", "point_name", "measurement_type", "rpm", "sample_time", "file_name"]
  6. class PretrainService:
  7. """Append selected wave_file rows to the pre-training CSV (deduplicated by id)."""
  8. def __init__(self) -> None:
  9. self._csv_path = Path(__file__).resolve().parents[2] / _PRETRAIN_CSV_NAME
  10. self._lock = threading.Lock()
  11. @property
  12. def csv_path(self) -> Path:
  13. return self._csv_path
  14. def _read_records(self) -> list[dict[str, str]]:
  15. if not self._csv_path.exists():
  16. return []
  17. with self._csv_path.open("r", encoding="utf-8-sig", newline="") as handle:
  18. reader = csv.DictReader(handle)
  19. return [dict(row) for row in reader]
  20. def _write_records(self, records: list[dict[str, str]]) -> None:
  21. with self._csv_path.open("w", encoding="utf-8-sig", newline="") as handle:
  22. writer = csv.DictWriter(handle, fieldnames=_CSV_COLUMNS)
  23. writer.writeheader()
  24. writer.writerows(records)
  25. def recorded_ids(self, ids: list[int]) -> list[int]:
  26. wanted = {int(value) for value in ids if value}
  27. if not wanted:
  28. return []
  29. with self._lock:
  30. records = self._read_records()
  31. existing: set[int] = set()
  32. for row in records:
  33. raw = str(row.get("id") or "").strip()
  34. if raw.isdigit():
  35. existing.add(int(raw))
  36. return sorted(existing & wanted)
  37. def recorded_counts(self) -> dict[str, int]:
  38. """每个 point_name 在预训练 CSV 中的记录数量。"""
  39. with self._lock:
  40. records = self._read_records()
  41. counts: dict[str, int] = {}
  42. for row in records:
  43. name = str(row.get("point_name") or "").strip()
  44. if name:
  45. counts[name] = counts.get(name, 0) + 1
  46. return counts
  47. def device_point_counts(self) -> dict[str, int]:
  48. """每个 device_point 在预训练 CSV 中的记录数量(按 point_name 后缀剥离)。"""
  49. with self._lock:
  50. records = self._read_records()
  51. suffixes = ["压力盖侧", "压力轴侧", "活塞杆沉降", "十字头振动", "自由端振动", "驱动端振动"]
  52. counts: dict[str, int] = {}
  53. for row in records:
  54. name = str(row.get("point_name") or "").strip()
  55. if not name:
  56. continue
  57. for suffix in suffixes:
  58. if name.endswith(suffix):
  59. counts[suffix] = counts.get(suffix, 0) + 1
  60. break
  61. return counts
  62. def record(self, record: dict[str, object]) -> tuple[bool, bool]:
  63. row = {column: str(record.get(column) or "") for column in _CSV_COLUMNS}
  64. try:
  65. file_id = int(row["id"])
  66. except (TypeError, ValueError) as error:
  67. raise ValueError("id 必须为正整数") from error
  68. if file_id <= 0:
  69. raise ValueError("id 必须为正整数")
  70. with self._lock:
  71. records = self._read_records()
  72. existing: set[int] = set()
  73. for item in records:
  74. raw = str(item.get("id") or "").strip()
  75. if raw.isdigit():
  76. existing.add(int(raw))
  77. if file_id in existing:
  78. return False, True
  79. records.append(row)
  80. self._write_records(records)
  81. return True, False
  82. def remove(self, file_id: int) -> bool:
  83. if file_id <= 0:
  84. raise ValueError("id 必须为正整数")
  85. with self._lock:
  86. records = self._read_records()
  87. remaining = [
  88. row
  89. for row in records
  90. if not str(row.get("id") or "").strip().isdigit()
  91. or int(str(row.get("id") or "").strip()) != file_id
  92. ]
  93. if len(remaining) == len(records):
  94. return False
  95. self._write_records(remaining)
  96. return True
  97. pretrain_service = PretrainService()