pretrain_service.py 3.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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 record(self, record: dict[str, object]) -> tuple[bool, bool]:
  48. row = {column: str(record.get(column) or "") for column in _CSV_COLUMNS}
  49. try:
  50. file_id = int(row["id"])
  51. except (TypeError, ValueError) as error:
  52. raise ValueError("id 必须为正整数") from error
  53. if file_id <= 0:
  54. raise ValueError("id 必须为正整数")
  55. with self._lock:
  56. records = self._read_records()
  57. existing: set[int] = set()
  58. for item in records:
  59. raw = str(item.get("id") or "").strip()
  60. if raw.isdigit():
  61. existing.add(int(raw))
  62. if file_id in existing:
  63. return False, True
  64. records.append(row)
  65. self._write_records(records)
  66. return True, False
  67. def remove(self, file_id: int) -> bool:
  68. if file_id <= 0:
  69. raise ValueError("id 必须为正整数")
  70. with self._lock:
  71. records = self._read_records()
  72. remaining = [
  73. row
  74. for row in records
  75. if not str(row.get("id") or "").strip().isdigit()
  76. or int(str(row.get("id") or "").strip()) != file_id
  77. ]
  78. if len(remaining) == len(records):
  79. return False
  80. self._write_records(remaining)
  81. return True
  82. pretrain_service = PretrainService()