sunyoung00 commited on
Commit
fa13b66
·
verified ·
1 Parent(s): b1656e8

Delete history.py

Browse files
Files changed (1) hide show
  1. history.py +0 -406
history.py DELETED
@@ -1,406 +0,0 @@
1
- """
2
- history.py — 생성 결과 영구 저장
3
-
4
- ① 로컬 캐시 DATA_DIR/history/{id}/{result.png, thumb.jpg, source.jpg} + history_index.json
5
- ② 원격 미러 HF Dataset (HF_DATASET_REPO + HF_TOKEN) 에 묶음 커밋 — Space 가 재시작·재배포돼도 남는다.
6
- (HISTORY_REMOTE_DIR 를 주면 HF 대신 해당 폴더에 미러 — 별도 볼륨/테스트용)
7
-
8
- 원격에는 이렇게 쌓인다:
9
- faceswap/index.json 전체 목록(숨김 표시 포함)
10
- faceswap/{id}/result.png|thumb.jpg|source.jpg
11
-
12
- 설계 메모
13
- - 결과가 나오면 로컬에 먼저 쓰고 즉시 화면에 노출한다. 원격 커밋은 뒤에서 15초 단위로 묶어서 한다
14
- (HF 는 커밋 횟수 제한이 있어 장마다 커밋하면 막힌다).
15
- - HF 의 Xet 스토리지는 메모리 버퍼 커밋이 조용히 실패하므로 반드시 '파일 경로'로 커밋한다.
16
- - 재시작 후엔 원격 index.json 만 먼저 받고, 이미지는 화면에서 열 때 하나씩 내려받는다.
17
- - 목록에서 '삭제'는 숨김 표시만 한다 (저장소 파일은 지우지 않는다).
18
- """
19
- from __future__ import annotations
20
-
21
- import datetime
22
- import io
23
- import json
24
- import os
25
- import shutil
26
- import tempfile
27
- import threading
28
- import time
29
- from typing import Any, Dict, List, Optional
30
-
31
- from PIL import Image, ImageOps
32
-
33
- KST = datetime.timezone(datetime.timedelta(hours=9))
34
- NO_FOLDER = "(폴더 없이 올린 파일)"
35
- REMOTE_PREFIX = "faceswap"
36
- FILES = {"result": "result.png", "thumb": "thumb.jpg", "source": "source.jpg"}
37
- COMMIT_INTERVAL = float(os.environ.get("HISTORY_COMMIT_INTERVAL", "15"))
38
- COMMIT_MAX_IDS = 25
39
-
40
-
41
- def _pick_data_dir() -> str:
42
- if os.environ.get("DATA_DIR"):
43
- return os.environ["DATA_DIR"]
44
- if os.path.isdir("/data") and os.access("/data", os.W_OK): # HF Space 영구 스토리지(유료 옵션)
45
- return "/data/faceswap"
46
- return os.path.join(tempfile.gettempdir(), "faceswap_data")
47
-
48
-
49
- DATA_DIR = _pick_data_dir()
50
- HIST_DIR = os.path.join(DATA_DIR, "history")
51
- INDEX_PATH = os.path.join(DATA_DIR, "history_index.json")
52
- os.makedirs(HIST_DIR, exist_ok=True)
53
-
54
- _lock = threading.RLock()
55
- _entries: Dict[str, Dict[str, Any]] = {}
56
- _pending: set = set()
57
- _version = 0
58
- _committed_version = 0
59
- _last_error = ""
60
- _last_commit_ok = 0.0
61
- _restored = False
62
- _remote: Optional["_Remote"] = None
63
- _started = False
64
-
65
-
66
- # ── 원격 어댑터 ───────────────────────────────────────────────────────────────
67
- class _Remote:
68
- label = ""
69
-
70
- def ensure(self) -> None: ...
71
- def commit(self, files: Dict[str, str], message: str) -> None: ... # repo_path → 로컬 파일 경로
72
- def fetch(self, repo_path: str, dest: str) -> None: ... # 없으면 FileNotFoundError
73
-
74
-
75
- class HFRemote(_Remote):
76
- def __init__(self, repo: str, token: str):
77
- self.repo, self.token = repo, token
78
- self.label = f"HF Dataset · {repo}"
79
- self._api = None
80
-
81
- def _get_api(self):
82
- if self._api is None:
83
- from huggingface_hub import HfApi
84
- self._api = HfApi(token=self.token)
85
- return self._api
86
-
87
- def ensure(self) -> None:
88
- self._get_api().create_repo(repo_id=self.repo, repo_type="dataset", private=True, exist_ok=True)
89
-
90
- def commit(self, files: Dict[str, str], message: str) -> None:
91
- from huggingface_hub import CommitOperationAdd
92
- ops = [CommitOperationAdd(path_in_repo=k, path_or_fileobj=v) for k, v in files.items()] # 파일 경로 커밋
93
- self._get_api().create_commit(repo_id=self.repo, repo_type="dataset", operations=ops, commit_message=message)
94
-
95
- def fetch(self, repo_path: str, dest: str) -> None:
96
- from huggingface_hub import hf_hub_download
97
- try:
98
- p = hf_hub_download(repo_id=self.repo, filename=repo_path, repo_type="dataset", token=self.token)
99
- except Exception as e: # noqa: BLE001
100
- name = type(e).__name__
101
- if "EntryNotFound" in name or "RepositoryNotFound" in name or "RevisionNotFound" in name:
102
- raise FileNotFoundError(repo_path) from e
103
- raise
104
- shutil.copyfile(p, dest)
105
-
106
-
107
- class DirRemote(_Remote):
108
- def __init__(self, root: str):
109
- self.root = root
110
- self.label = f"폴더 · {root}"
111
-
112
- def ensure(self) -> None:
113
- os.makedirs(self.root, exist_ok=True)
114
-
115
- def commit(self, files: Dict[str, str], message: str) -> None:
116
- for repo_path, src in files.items():
117
- dst = os.path.join(self.root, repo_path)
118
- os.makedirs(os.path.dirname(dst), exist_ok=True)
119
- shutil.copyfile(src, dst)
120
-
121
- def fetch(self, repo_path: str, dest: str) -> None:
122
- src = os.path.join(self.root, repo_path)
123
- if not os.path.exists(src):
124
- raise FileNotFoundError(repo_path)
125
- shutil.copyfile(src, dest)
126
-
127
-
128
- # ── 인덱스 ────────────────────────────────────────────────────────────────────
129
- def _save_index_locked() -> None:
130
- tmp = INDEX_PATH + ".tmp"
131
- with open(tmp, "w", encoding="utf-8") as f:
132
- json.dump(list(_entries.values()), f, ensure_ascii=False)
133
- os.replace(tmp, INDEX_PATH)
134
-
135
-
136
- def _load_local_index() -> None:
137
- if os.path.exists(INDEX_PATH):
138
- try:
139
- for e in json.load(open(INDEX_PATH, encoding="utf-8")):
140
- _entries[e["id"]] = e
141
- except Exception as ex: # noqa: BLE001
142
- print(f"[HIST] 로컬 인덱스 읽기 실패: {ex}")
143
-
144
-
145
- def _merge_remote_index() -> None:
146
- """원격 index.json 을 받아 로컬에 없는 항목을 합친다. 같은 id 는 로컬(최신 작업)을 우선."""
147
- global _restored, _last_error
148
- if _remote is None:
149
- return
150
- tmp = os.path.join(tempfile.gettempdir(), f"remote_index_{os.getpid()}.json")
151
- try:
152
- _remote.ensure()
153
- _remote.fetch(f"{REMOTE_PREFIX}/index.json", tmp)
154
- remote = json.load(open(tmp, encoding="utf-8"))
155
- added = 0
156
- with _lock:
157
- for e in remote:
158
- if e.get("id") and e["id"] not in _entries:
159
- _entries[e["id"]] = e
160
- added += 1
161
- if added:
162
- _save_index_locked()
163
- print(f"[HIST] 원격 기록 {len(remote)}건 확인, 새로 복원 {added}건")
164
- except FileNotFoundError:
165
- print("[HIST] 원격에 아직 기록이 없습니다 (첫 실행).")
166
- finally:
167
- try:
168
- os.remove(tmp)
169
- except OSError:
170
- pass
171
- _restored = True
172
- _last_error = ""
173
-
174
-
175
- def _restore_loop() -> None:
176
- global _last_error
177
- for attempt in range(6):
178
- try:
179
- _merge_remote_index()
180
- return
181
- except Exception as e: # noqa: BLE001
182
- _last_error = f"원격 복원 실패: {e}"
183
- print(f"[HIST] {_last_error} (재시도 {attempt + 1}/6)")
184
- time.sleep(10 * (attempt + 1))
185
-
186
-
187
- # ── 원격 업로드 (뒤에서 묶음 커밋) ────────────────────────────────────────────
188
- def _commit_batch() -> bool:
189
- """대기 중인 결과를 한 번에 커밋. 성공하면 True."""
190
- global _committed_version, _last_error, _last_commit_ok
191
- if _remote is None:
192
- return False
193
- with _lock:
194
- ids = sorted(_pending)[:COMMIT_MAX_IDS]
195
- snap_version = _version
196
- if not ids and snap_version == _committed_version:
197
- return False
198
- index_copy = os.path.join(tempfile.gettempdir(), f"index_commit_{os.getpid()}.json")
199
- with open(index_copy, "w", encoding="utf-8") as f:
200
- json.dump(list(_entries.values()), f, ensure_ascii=False)
201
- files: Dict[str, str] = {}
202
- for i in ids:
203
- for name in FILES.values():
204
- p = os.path.join(HIST_DIR, i, name)
205
- if os.path.exists(p):
206
- files[f"{REMOTE_PREFIX}/{i}/{name}"] = p
207
- files[f"{REMOTE_PREFIX}/index.json"] = index_copy
208
- try:
209
- _remote.ensure()
210
- _remote.commit(files, f"faceswap: +{len(ids)} results" if ids else "faceswap: index update")
211
- except Exception as e: # noqa: BLE001
212
- _last_error = f"원격 저장 실패: {str(e)[:200]}"
213
- print(f"[HIST] {_last_error}")
214
- return False
215
- finally:
216
- try:
217
- os.remove(index_copy)
218
- except OSError:
219
- pass
220
- with _lock:
221
- _pending.difference_update(ids)
222
- if not _pending:
223
- _committed_version = snap_version
224
- _last_error = ""
225
- _last_commit_ok = time.time()
226
- print(f"[HIST] 원격 커밋 완료: 결과 {len(ids)}건")
227
- return True
228
-
229
-
230
- def _uploader_loop() -> None:
231
- oldest = 0.0
232
- backoff = COMMIT_INTERVAL
233
- while True:
234
- time.sleep(2)
235
- with _lock:
236
- has_work = bool(_pending) or _version != _committed_version
237
- n = len(_pending)
238
- if not has_work:
239
- oldest = 0.0
240
- continue
241
- oldest = oldest or time.time()
242
- if n < 10 and time.time() - oldest < backoff:
243
- continue
244
- ok = _commit_batch()
245
- oldest = 0.0
246
- backoff = COMMIT_INTERVAL if ok else min(300.0, backoff * 2)
247
-
248
-
249
- def flush(timeout: float = 25.0) -> None:
250
- """종료 직전에 대기 중인 커밋을 모두 밀어 넣는다."""
251
- end = time.time() + timeout
252
- while _remote is not None and time.time() < end:
253
- with _lock:
254
- if not _pending and _version == _committed_version:
255
- return
256
- if not _commit_batch():
257
- time.sleep(2)
258
-
259
-
260
- def init() -> None:
261
- """서버 시작 시 1회 호출."""
262
- global _remote, _started
263
- if _started:
264
- return
265
- _started = True
266
- _load_local_index()
267
- remote_dir = os.environ.get("HISTORY_REMOTE_DIR")
268
- repo, token = os.environ.get("HF_DATASET_REPO"), os.environ.get("HF_TOKEN")
269
- if remote_dir:
270
- _remote = DirRemote(remote_dir)
271
- elif repo and token:
272
- _remote = HFRemote(repo, token)
273
- elif repo and not token:
274
- print("[HIST] HF_DATASET_REPO 는 있지만 HF_TOKEN 이 없어 영구 저장을 끕니다.")
275
- if _remote:
276
- print(f"[HIST] 영구 저장 켜짐 → {_remote.label}")
277
- threading.Thread(target=_restore_loop, daemon=True).start()
278
- threading.Thread(target=_uploader_loop, daemon=True).start()
279
- else:
280
- print(f"[HIST] 영구 저장 꺼짐 — 로컬({DATA_DIR})에만 저장합니다. Space 재시작 시 사라질 수 있어요.")
281
-
282
-
283
- # ── 기록 / 조회 ───────────────────────────────────────────────────────────────
284
- def _jpeg(img: Image.Image, max_side: int, quality: int) -> bytes:
285
- img = ImageOps.exif_transpose(img).convert("RGB")
286
- img.thumbnail((max_side, max_side), Image.LANCZOS)
287
- out = io.BytesIO()
288
- img.save(out, "JPEG", quality=quality)
289
- return out.getvalue()
290
-
291
-
292
- def record(job_id: str, meta: Dict[str, Any], result_bytes: bytes, source_bytes: bytes) -> Dict[str, Any]:
293
- """결과·썸네일·비교용 원본을 로컬에 쓰고 목록에 등록한다. 원격 커밋은 뒤에서."""
294
- global _version
295
- d = os.path.join(HIST_DIR, job_id)
296
- os.makedirs(d, exist_ok=True)
297
- with open(os.path.join(d, FILES["result"]), "wb") as f:
298
- f.write(result_bytes)
299
- with open(os.path.join(d, FILES["thumb"]), "wb") as f:
300
- f.write(_jpeg(Image.open(io.BytesIO(result_bytes)), 640, 85))
301
- try: # 비교 슬라이더용 원본 (용량 절약을 위해 축소 JPEG)
302
- with open(os.path.join(d, FILES["source"]), "wb") as f:
303
- f.write(_jpeg(Image.open(io.BytesIO(source_bytes)), 1800, 88))
304
- except Exception as e: # noqa: BLE001
305
- print(f"[HIST] source 저장 건너뜀: {e}")
306
- now = datetime.datetime.now(KST)
307
- rel = meta.get("rel_path", "")
308
- entry = {
309
- **meta,
310
- "id": job_id,
311
- "folder": rel.split("/")[0] if "/" in rel else NO_FOLDER,
312
- "created_at": now.isoformat(timespec="seconds"),
313
- "date": now.strftime("%Y-%m-%d"),
314
- "time": now.strftime("%H:%M"),
315
- "hidden": False,
316
- }
317
- with _lock:
318
- _entries[job_id] = entry
319
- _save_index_locked()
320
- if _remote:
321
- _pending.add(job_id)
322
- _version_bump()
323
- return entry
324
-
325
-
326
- def _version_bump() -> None:
327
- global _version
328
- _version += 1
329
-
330
-
331
- def entry(job_id: str) -> Optional[Dict[str, Any]]:
332
- with _lock:
333
- e = _entries.get(job_id)
334
- return dict(e) if e else None
335
-
336
-
337
- def path(job_id: str, kind: str) -> Optional[str]:
338
- """로컬 파일 경로. 없으면 원격에서 내려받아 캐시한다. 못 찾으면 None."""
339
- name = FILES.get(kind)
340
- if not name or entry(job_id) is None:
341
- return None
342
- p = os.path.join(HIST_DIR, job_id, name)
343
- if os.path.exists(p):
344
- return p
345
- if _remote is None:
346
- return None
347
- os.makedirs(os.path.dirname(p), exist_ok=True)
348
- tmp = p + ".part"
349
- try:
350
- _remote.fetch(f"{REMOTE_PREFIX}/{job_id}/{name}", tmp)
351
- os.replace(tmp, p)
352
- return p
353
- except Exception as e: # noqa: BLE001
354
- print(f"[HIST] 원격에서 {job_id}/{name} 를 가져오지 못함: {e}")
355
- try:
356
- os.remove(tmp)
357
- except OSError:
358
- pass
359
- return None
360
-
361
-
362
- def all_entries() -> List[Dict[str, Any]]:
363
- """목록에서 숨긴 것까지 포함한 전체 기록(통계용)."""
364
- with _lock:
365
- return [dict(e) for e in _entries.values()]
366
-
367
-
368
- def list_entries(q: str = "", limit: int = 1000) -> List[Dict[str, Any]]:
369
- q = (q or "").strip().lower()
370
- with _lock:
371
- items = [dict(e) for e in _entries.values() if not e.get("hidden")]
372
- if q:
373
- import unicodedata
374
- q = unicodedata.normalize("NFC", q)
375
- items = [e for e in items if q in unicodedata.normalize("NFC", e.get("rel_path", "")).lower()]
376
- items.sort(key=lambda e: e.get("created_at", ""), reverse=True)
377
- return items[:limit]
378
-
379
-
380
- def hide(ids: List[str]) -> int:
381
- n = 0
382
- with _lock:
383
- for i in ids:
384
- e = _entries.get(i)
385
- if e and not e.get("hidden"):
386
- e["hidden"] = True
387
- n += 1
388
- if n:
389
- _save_index_locked()
390
- if _remote:
391
- _version_bump()
392
- return n
393
-
394
-
395
- def status() -> Dict[str, Any]:
396
- with _lock:
397
- return {
398
- "durable": _remote is not None,
399
- "remote": _remote.label if _remote else None,
400
- "restored": _restored if _remote else None,
401
- "pending": len(_pending),
402
- "unsynced": (len(_pending) > 0 or _version != _committed_version) if _remote else None,
403
- "error": _last_error or None,
404
- "count": sum(1 for e in _entries.values() if not e.get("hidden")),
405
- "dataDir": DATA_DIR,
406
- }