Initial commit
This commit is contained in:
@@ -0,0 +1,95 @@
|
||||
"""Formatierungshelfer fuer Zeitangaben, Groessen und Pfade."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def format_timestamp(seconds: float | int | None) -> str:
|
||||
"""Formatiert Sekunden als HH:MM:SS bzw. MM:SS."""
|
||||
if seconds is None:
|
||||
return "--:--"
|
||||
seconds = max(0, int(round(float(seconds))))
|
||||
hours, remainder = divmod(seconds, 3600)
|
||||
minutes, secs = divmod(remainder, 60)
|
||||
if hours:
|
||||
return f"{hours:02d}:{minutes:02d}:{secs:02d}"
|
||||
return f"{minutes:02d}:{secs:02d}"
|
||||
|
||||
|
||||
def format_timestamp_verbose(seconds: float | int | None) -> str:
|
||||
"""Formatiert Sekunden immer als HH:MM:SS (fuer Fundstellen in Hoerspielen)."""
|
||||
if seconds is None:
|
||||
return "--:--:--"
|
||||
seconds = max(0, int(round(float(seconds))))
|
||||
hours, remainder = divmod(seconds, 3600)
|
||||
minutes, secs = divmod(remainder, 60)
|
||||
return f"{hours:02d}:{minutes:02d}:{secs:02d}"
|
||||
|
||||
|
||||
def format_duration(seconds: float | int | None) -> str:
|
||||
"""Menschlich lesbare Dauer, z. B. '2 h 14 min'."""
|
||||
if seconds is None:
|
||||
return "unbekannt"
|
||||
total = max(0, int(round(float(seconds))))
|
||||
hours, remainder = divmod(total, 3600)
|
||||
minutes, secs = divmod(remainder, 60)
|
||||
if hours:
|
||||
return f"{hours} h {minutes:02d} min"
|
||||
if minutes:
|
||||
return f"{minutes} min {secs:02d} s"
|
||||
return f"{secs} s"
|
||||
|
||||
|
||||
def format_size(num_bytes: int | float | None) -> str:
|
||||
"""Formatiert Bytes als B/KB/MB/GB."""
|
||||
if num_bytes is None:
|
||||
return "?"
|
||||
value = float(num_bytes)
|
||||
for unit in ("B", "KB", "MB", "GB", "TB"):
|
||||
if value < 1024 or unit == "TB":
|
||||
if unit == "B":
|
||||
return f"{int(value)} {unit}"
|
||||
return f"{value:.1f} {unit}"
|
||||
value /= 1024
|
||||
return f"{value:.1f} TB"
|
||||
|
||||
|
||||
def format_score(score: float) -> str:
|
||||
"""Aehnlichkeitswert als Prozentangabe (keine statistische Wahrscheinlichkeit)."""
|
||||
return f"{score:.1f}%"
|
||||
|
||||
|
||||
def format_rate(audio_seconds: float, elapsed_seconds: float) -> str:
|
||||
"""Verarbeitungsgeschwindigkeit als Vielfaches der Echtzeit."""
|
||||
if elapsed_seconds <= 0:
|
||||
return "-"
|
||||
return f"{audio_seconds / elapsed_seconds:.2f}x Echtzeit"
|
||||
|
||||
|
||||
def format_datetime(iso_timestamp: str | None) -> str:
|
||||
"""Formatiert einen ISO-String lesbar; unbekannte Formate werden durchgereicht."""
|
||||
if not iso_timestamp:
|
||||
return "-"
|
||||
try:
|
||||
dt = datetime.fromisoformat(iso_timestamp)
|
||||
except ValueError:
|
||||
return iso_timestamp
|
||||
if dt.tzinfo is not None:
|
||||
dt = dt.astimezone()
|
||||
return dt.strftime("%Y-%m-%d %H:%M")
|
||||
|
||||
|
||||
def utc_now_iso() -> str:
|
||||
"""Aktueller Zeitpunkt als ISO-String in UTC (sekundengenau)."""
|
||||
return datetime.now(timezone.utc).replace(microsecond=0).isoformat()
|
||||
|
||||
|
||||
def shorten_path(path: str | Path, max_length: int = 80) -> str:
|
||||
"""Kuerzt lange Pfade in der Mitte."""
|
||||
text = str(path)
|
||||
if len(text) <= max_length:
|
||||
return text
|
||||
keep = max(8, (max_length - 3) // 2)
|
||||
return f"{text[:keep]}...{text[-keep:]}"
|
||||
@@ -0,0 +1,38 @@
|
||||
"""Hash-Helfer fuer die Duplikaterkennung."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
|
||||
CHUNK_SIZE = 1024 * 1024
|
||||
|
||||
|
||||
def sha256_file(path: str | Path, chunk_size: int = CHUNK_SIZE) -> str:
|
||||
"""Berechnet den SHA256-Hash einer Datei, ohne sie komplett in den RAM zu laden."""
|
||||
digest = hashlib.sha256()
|
||||
with Path(path).open("rb") as handle:
|
||||
while True:
|
||||
chunk = handle.read(chunk_size)
|
||||
if not chunk:
|
||||
break
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def quick_signature(path: str | Path, sample_size: int = 64 * 1024) -> str:
|
||||
"""Schnelle Signatur aus Groesse, erster und letzter Datenportion.
|
||||
|
||||
Nur fuer Vorpruefungen gedacht - fuer belastbare Duplikaterkennung muss
|
||||
:func:`sha256_file` verwendet werden.
|
||||
"""
|
||||
path = Path(path)
|
||||
size = path.stat().st_size
|
||||
digest = hashlib.sha256()
|
||||
digest.update(str(size).encode("ascii"))
|
||||
with path.open("rb") as handle:
|
||||
digest.update(handle.read(sample_size))
|
||||
if size > sample_size:
|
||||
handle.seek(max(sample_size, size - sample_size))
|
||||
digest.update(handle.read(sample_size))
|
||||
return digest.hexdigest()
|
||||
@@ -0,0 +1,62 @@
|
||||
"""Logging-Setup fuer SjAudioSearch.
|
||||
|
||||
Protokolliert in eine rotierende Logdatei und optional zusaetzlich auf die
|
||||
Konsole (Rich). Die CLI schaltet den Konsolen-Handler nur bei Bedarf ein.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from logging.handlers import RotatingFileHandler
|
||||
from pathlib import Path
|
||||
|
||||
from rich.logging import RichHandler
|
||||
|
||||
LOGGER_NAME = "sjaudiosearch"
|
||||
_CONFIGURED = False
|
||||
|
||||
|
||||
def setup_logging(log_path: Path, level: str = "INFO", console: bool = False) -> logging.Logger:
|
||||
"""Konfiguriert den Logger ``sjaudiosearch`` idempotent."""
|
||||
global _CONFIGURED
|
||||
|
||||
logger = logging.getLogger(LOGGER_NAME)
|
||||
numeric_level = getattr(logging, str(level).upper(), logging.INFO)
|
||||
logger.setLevel(numeric_level)
|
||||
|
||||
if _CONFIGURED:
|
||||
return logger
|
||||
|
||||
log_path = Path(log_path)
|
||||
log_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
formatter = logging.Formatter(
|
||||
"%(asctime)s | %(levelname)-8s | %(name)s | %(message)s",
|
||||
datefmt="%Y-%m-%d %H:%M:%S",
|
||||
)
|
||||
|
||||
file_handler = RotatingFileHandler(
|
||||
log_path,
|
||||
maxBytes=5 * 1024 * 1024,
|
||||
backupCount=3,
|
||||
encoding="utf-8",
|
||||
)
|
||||
file_handler.setFormatter(formatter)
|
||||
file_handler.setLevel(numeric_level)
|
||||
logger.addHandler(file_handler)
|
||||
|
||||
if console:
|
||||
console_handler = RichHandler(show_path=False, rich_tracebacks=True, markup=False)
|
||||
console_handler.setLevel(max(numeric_level, logging.INFO))
|
||||
logger.addHandler(console_handler)
|
||||
|
||||
logger.propagate = False
|
||||
_CONFIGURED = True
|
||||
return logger
|
||||
|
||||
|
||||
def get_logger(name: str | None = None) -> logging.Logger:
|
||||
"""Liefert einen Sub-Logger unterhalb von ``sjaudiosearch``."""
|
||||
if name:
|
||||
return logging.getLogger(f"{LOGGER_NAME}.{name}")
|
||||
return logging.getLogger(LOGGER_NAME)
|
||||
Reference in New Issue
Block a user