pretrain_service.py 2.9 KB

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