Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

refactor(metadata): 头像与 Logo 缓存的原子写统一到 fsutil

longmeidao553ae2c23525
diff --git a/scripts/audit_performer_portraits.py b/scripts/audit_performer_portraits.py
index d68258668..b56ab1ae9 100644
--- a/scripts/audit_performer_portraits.py
+++ b/scripts/audit_performer_portraits.py
@@ -56,7 +56,6 @@ from peach.avatar_provider import (
POLICY_VERSION,
AvatarCandidateCache,
acceptable_avatar,
- atomic_write,
inspect_avatar,
installed_avatar_hashes,
mark_duplicate_candidates,
@@ -64,6 +63,7 @@ from peach.avatar_provider import (
)
from peach.catalog_rules import is_jav_code
from peach.config import DATABASE_PATH, GENERATED_DIR
+from peach.fsutil import atomic_write_bytes
from peach.gfriends import (
GFRIENDS_RAW,
INDEX_MAX_AGE_SECONDS,
@@ -217,7 +217,7 @@ def load_gfriends_cached(
else:
# 临时文件加 os.replace:换索引这一步没有中间态,别的进程读到的要么是
# 上一份完整索引,要么是这一份,不会是半个 JSON。
- atomic_write(cache_path, response.body)
+ atomic_write_bytes(cache_path, response.body)
health.add("index_fetched")
health.add("bytes_fetched", len(response.body))
return index, False
diff --git a/scripts/harvest_kmib.py b/scripts/harvest_kmib.py
index d3659b887..b9782ed32 100644
--- a/scripts/harvest_kmib.py
+++ b/scripts/harvest_kmib.py
@@ -43,12 +43,13 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
from PIL import Image # noqa: E402
from peach.avatar_provider import ( # noqa: E402
- AvatarCandidateCache, acceptable_avatar, atomic_write, inspect_avatar,
+ AvatarCandidateCache, acceptable_avatar, inspect_avatar,
provenance_now as avatar_provenance,
)
from peach.catalog_rules import ( # noqa: E402
is_korean_mib_code, normalise_code_key, release_code_from_filename,
)
+from peach.fsutil import atomic_write_bytes # noqa: E402
from peach.config import DATABASE_PATH, GENERATED_DIR, SOURCES_DIR # noqa: E402
from peach.entities import normalize_entity_name # noqa: E402
from peach.genre_decisions import load_genre_decisions # noqa: E402
@@ -214,7 +215,7 @@ def fetch_snapshot(snapshot: Path, fetcher: Fetcher, *, refresh: bool,
if body is None:
stats["failed"].append(url)
continue
- atomic_write(target, body)
+ atomic_write_bytes(target, body)
stats["images"] += 1
return stats
@@ -409,8 +410,8 @@ def install_cover(snapshot: Path, cover_root: Path, release: dict) -> str:
data = buffer.getvalue()
except Exception:
return "无法解码"
- atomic_write(target, data)
- atomic_write(target.with_suffix(".scraping.json"), json.dumps({
+ atomic_write_bytes(target, data)
+ atomic_write_bytes(target.with_suffix(".scraping.json"), json.dumps({
"source": SOURCE, "source_url": release["cover_url"], "width": size[0],
"height": size[1], "raw_sha256": hashlib.sha256(data).hexdigest(),
"checked_at": time.time(),
diff --git a/src/peach/avatar_provider.py b/src/peach/avatar_provider.py
index 8a702563e..049d5264b 100644
--- a/src/peach/avatar_provider.py
+++ b/src/peach/avatar_provider.py
@@ -4,10 +4,8 @@ from __future__ import annotations
import hashlib
import io
import json
-import os
import threading
import time
-import uuid
from dataclasses import asdict, dataclass
from datetime import datetime, timezone
from pathlib import Path
@@ -15,6 +13,7 @@ from pathlib import Path
from PIL import Image, UnidentifiedImageError
from .avatar_face import FaceProbe, drop_sidecar, write_sidecar
+from .fsutil import atomic_write_bytes
POLICY_VERSION = "performer-avatar-provider-v1"
@@ -84,17 +83,6 @@ def file_sha256(path: Path) -> str:
return hashlib.file_digest(handle, "sha256").hexdigest()
-def atomic_write(path: Path, data: bytes) -> None:
- path.parent.mkdir(parents=True, exist_ok=True)
- temporary = path.with_name(f".{path.name}.{os.getpid()}.tmp")
- try:
- temporary.write_bytes(data)
- os.replace(temporary, path)
- except BaseException:
- temporary.unlink(missing_ok=True)
- raise
-
-
def install_entity_avatar(avatar_root: Path, kind: str, entity_id: int, body: bytes,
content_type: str, provenance: dict,
face: dict | None = None, *, probe_face: bool = True) -> Path:
@@ -111,15 +99,8 @@ def install_entity_avatar(avatar_root: Path, kind: str, entity_id: int, body: by
"""
from .previews import entity_image_key
- avatar_root.mkdir(parents=True, exist_ok=True)
- destination = avatar_root / f"{entity_image_key(kind, entity_id)}.img"
- staging = destination.with_name(f"{destination.name}.{uuid.uuid4().hex}.tmp")
- try:
- staging.write_bytes(body)
- os.replace(staging, destination)
- except BaseException:
- staging.unlink(missing_ok=True)
- raise
+ destination = atomic_write_bytes(
+ avatar_root / f"{entity_image_key(kind, entity_id)}.img", body)
Path(f"{destination}.ct").write_text(content_type, encoding="utf-8")
record = FaceProbe()(destination) if probe_face and face is None else face
if record:
@@ -177,7 +158,7 @@ class AvatarCandidateCache:
request_path = self._request_path(url)
with self._lock:
if not object_path.is_file():
- atomic_write(object_path, data)
+ atomic_write_bytes(object_path, data)
request = {
"url": url,
"sha256": avatar.sha256,
@@ -186,7 +167,7 @@ class AvatarCandidateCache:
"width": avatar.width,
"height": avatar.height,
}
- atomic_write(
+ atomic_write_bytes(
request_path,
(json.dumps(request, ensure_ascii=False, indent=2) + "\n").encode("utf-8"),
)
@@ -200,7 +181,7 @@ class AvatarCandidateCache:
# entity + content hash makes this evidence immutable. Cache reuse must not
# rewrite cached_at and make identical upstream evidence look like a new fact.
if not path.is_file():
- atomic_write(
+ atomic_write_bytes(
path,
(json.dumps(asdict(provenance), ensure_ascii=False, indent=2) + "\n").encode(
"utf-8"
diff --git a/src/peach/logo_provider.py b/src/peach/logo_provider.py
index d143c87bf..ff1ff4215 100644
--- a/src/peach/logo_provider.py
+++ b/src/peach/logo_provider.py
@@ -4,7 +4,6 @@ from __future__ import annotations
import hashlib
import io
import json
-import os
import threading
from dataclasses import asdict, dataclass
from datetime import datetime, timezone
@@ -12,6 +11,8 @@ from pathlib import Path
from PIL import Image, UnidentifiedImageError
+from .fsutil import atomic_write_bytes
+
POLICY_VERSION = "studio-logo-provider-v1"
FORMATS = {
@@ -73,17 +74,6 @@ def inspect_logo(data: bytes) -> LogoRaster | None:
)
-def atomic_write(path: Path, data: bytes) -> None:
- path.parent.mkdir(parents=True, exist_ok=True)
- temporary = path.with_name(f".{path.name}.{os.getpid()}.tmp")
- try:
- temporary.write_bytes(data)
- os.replace(temporary, path)
- except BaseException:
- temporary.unlink(missing_ok=True)
- raise
-
-
class LogoCandidateCache:
def __init__(self, root: Path):
self.root = root
@@ -106,14 +96,14 @@ class LogoCandidateCache:
object_path = self.root / "objects" / f"{raster.sha256}{raster.extension}"
with self._lock:
if not object_path.is_file():
- atomic_write(object_path, data)
+ atomic_write_bytes(object_path, data)
request = {
"url": url, "sha256": raster.sha256,
"object_name": object_path.name, "mime_type": raster.mime_type,
"width": raster.width, "height": raster.height,
"perceptual_hash": raster.perceptual_hash,
}
- atomic_write(
+ atomic_write_bytes(
self._request_path(url),
(json.dumps(request, ensure_ascii=False, indent=2) + "\n").encode("utf-8"),
)
@@ -124,7 +114,7 @@ class LogoCandidateCache:
path = self.root / "evidence" / f"{key}-{record.sha256}.json"
with self._lock:
if not path.is_file():
- atomic_write(
+ atomic_write_bytes(
path,
(json.dumps(asdict(record), ensure_ascii=False, indent=2) + "\n").encode(
"utf-8"