LocateAnything Demo commited on
Commit
6cc8b35
·
1 Parent(s): aceb029

fix(log): write one JSONL file per record with session_id to prevent overwrite

Browse files

Previously every container session wrote to the same per-day JSONL
(logs_<date>.jsonl). When the ZeroGPU container was recycled, the new
empty container would overwrite the dataset's accumulated file via
CommitScheduler, losing earlier sessions' data (we observed daily files
getting reset multiple times back to ~0).

Now each record is written to a unique file at:
data/<date>/<session_id>__<entry_id>.jsonl
where <session_id> is a UUID generated once per container start. Files
are written atomically (.tmp + rename). CommitScheduler now only ever
adds new files, never overwrites old sessions' data. As a side benefit,
each LFS object is uploaded exactly once instead of every interval.

Files changed (1) hide show
  1. app.py +37 -6
app.py CHANGED
@@ -464,9 +464,22 @@ except Exception as e:
464
 
465
  # ============================================================
466
  # 用户数据收集(HuggingFace Public Dataset)
 
 
 
 
 
 
 
 
 
 
 
 
467
  # ============================================================
468
  LOG_DATASET_REPO = os.environ.get("LOG_DATASET_REPO", "woshichaoren123/log")
469
  _LOG_DIR = Path(tempfile.mkdtemp(prefix="hf_log_"))
 
470
  _log_scheduler = None
471
 
472
  if LOG_DATASET_REPO and LOG_HF_TOKEN:
@@ -476,10 +489,12 @@ if LOG_DATASET_REPO and LOG_HF_TOKEN:
476
  repo_type="dataset",
477
  folder_path=str(_LOG_DIR),
478
  path_in_repo="data",
479
- every=5,
480
  token=LOG_HF_TOKEN,
 
481
  )
482
- print(f"[LOG] Dataset logging enabled → {LOG_DATASET_REPO}")
 
483
  except Exception as e:
484
  _log_scheduler = None
485
  print(f"[LOG] Dataset logging disabled: {e}")
@@ -494,12 +509,24 @@ def _pil_to_b64(pil_img):
494
  return base64.b64encode(buf.getvalue()).decode("ascii")
495
 
496
 
 
 
 
 
 
 
 
 
497
  def _log_to_dataset(
498
  input_type, category, model_mode, raw_prompt,
499
  output_text="", input_image=None, output_image=None,
500
  extra=None,
501
  ):
502
- """将用户 query、输入图片(base64)、推理结果写入按天分片的 JSONL。"""
 
 
 
 
503
  if _log_scheduler is None:
504
  return
505
  try:
@@ -517,6 +544,7 @@ def _log_to_dataset(
517
 
518
  record = {
519
  "id": entry_id,
 
520
  "timestamp": ts,
521
  "input_type": input_type,
522
  "category": category,
@@ -529,10 +557,13 @@ def _log_to_dataset(
529
  if extra:
530
  record.update(extra)
531
 
532
- log_file = _LOG_DIR / f"logs_{date_str}.jsonl"
 
 
 
 
533
  with _log_scheduler.lock:
534
- with open(log_file, "a", encoding="utf-8") as f:
535
- f.write(json.dumps(record, ensure_ascii=False) + "\n")
536
  except Exception as e:
537
  print(f"[LOG] Failed to log to dataset: {e}")
538
 
 
464
 
465
  # ============================================================
466
  # 用户数据收集(HuggingFace Public Dataset)
467
+ #
468
+ # 策略:one-record-per-file,配合按天目录 + 容器级 SESSION_ID。
469
+ # 这样可以解决两个问题:
470
+ # 1. 容器被回收时,本地 ephemeral 目录被清空。原来所有 session 都
471
+ # 写同一个 logs_<date>.jsonl,新容器起来后会用空文件把 dataset 里
472
+ # 旧的同名文件覆盖掉,造成数据丢失。
473
+ # 2. 每次 commit 都要重传整份 LFS(appended 文件 hash 变了),浪费带宽。
474
+ #
475
+ # 现在每条记录写成独立的 JSONL 文件:
476
+ # data/<date>/<SESSION_ID>__<entry_id>.jsonl
477
+ # CommitScheduler 只会“新增”文件,永远不会覆盖其它 session 的数据;
478
+ # 单文件上传后即被封存,不会重复上传。
479
  # ============================================================
480
  LOG_DATASET_REPO = os.environ.get("LOG_DATASET_REPO", "woshichaoren123/log")
481
  _LOG_DIR = Path(tempfile.mkdtemp(prefix="hf_log_"))
482
+ _SESSION_ID = uuid.uuid4().hex[:8]
483
  _log_scheduler = None
484
 
485
  if LOG_DATASET_REPO and LOG_HF_TOKEN:
 
489
  repo_type="dataset",
490
  folder_path=str(_LOG_DIR),
491
  path_in_repo="data",
492
+ every=3,
493
  token=LOG_HF_TOKEN,
494
+ squash_history=False,
495
  )
496
+ print(f"[LOG] Dataset logging enabled → {LOG_DATASET_REPO} "
497
+ f"(session={_SESSION_ID}, dir={_LOG_DIR})")
498
  except Exception as e:
499
  _log_scheduler = None
500
  print(f"[LOG] Dataset logging disabled: {e}")
 
509
  return base64.b64encode(buf.getvalue()).decode("ascii")
510
 
511
 
512
+ def _atomic_write_text(path: Path, text: str):
513
+ """原子写入:先写临时文件再 rename,避免 CommitScheduler 读到半截文件。"""
514
+ tmp_path = path.with_name(path.name + ".tmp")
515
+ with open(tmp_path, "w", encoding="utf-8") as f:
516
+ f.write(text)
517
+ os.replace(tmp_path, path)
518
+
519
+
520
  def _log_to_dataset(
521
  input_type, category, model_mode, raw_prompt,
522
  output_text="", input_image=None, output_image=None,
523
  extra=None,
524
  ):
525
+ """每条记录写到独立的 JSONL 文件,按日期分目录、文件名包含 session_id。
526
+
527
+ 最终落盘路径(也是 dataset 里的路径):
528
+ data/<YYYY-MM-DD>/<session_id>__<entry_id>.jsonl
529
+ """
530
  if _log_scheduler is None:
531
  return
532
  try:
 
544
 
545
  record = {
546
  "id": entry_id,
547
+ "session_id": _SESSION_ID,
548
  "timestamp": ts,
549
  "input_type": input_type,
550
  "category": category,
 
557
  if extra:
558
  record.update(extra)
559
 
560
+ day_dir = _LOG_DIR / date_str
561
+ day_dir.mkdir(parents=True, exist_ok=True)
562
+ log_file = day_dir / f"{_SESSION_ID}__{entry_id}.jsonl"
563
+
564
+ payload = json.dumps(record, ensure_ascii=False) + "\n"
565
  with _log_scheduler.lock:
566
+ _atomic_write_text(log_file, payload)
 
567
  except Exception as e:
568
  print(f"[LOG] Failed to log to dataset: {e}")
569