Repository navigation
Expand file tree
/
Copy pathutils.py
More file actions
96 lines (67 loc) · 2.44 KB
/
Copy pathutils.py
File metadata and controls
96 lines (67 loc) · 2.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
from __future__ import annotations
import logging
import re
import shutil
import subprocess
from pathlib import Path
from typing import Iterable, Sequence, TypeVar
T = TypeVar("T")
class UserFacingError(Exception):
"""Error type shown directly to the user."""
class DependencyError(UserFacingError):
"""Raised when an external dependency is missing or unreachable."""
class ProcessingError(UserFacingError):
"""Raised when a processing stage fails."""
def setup_logging(log_level: int = logging.INFO) -> logging.Logger:
logger = logging.getLogger("roman_urdu_srt_generator")
if logger.handlers:
return logger
logger.setLevel(log_level)
logger.propagate = False
formatter = logging.Formatter("%(asctime)s | %(levelname)s | %(message)s")
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
logger.addHandler(stream_handler)
return logger
def ensure_directory(path: Path) -> Path:
path.mkdir(parents=True, exist_ok=True)
return path
def safe_filename(name: str) -> str:
stem = Path(name).stem.strip() or "video"
cleaned = re.sub(r"[^A-Za-z0-9._-]+", "_", stem)
cleaned = re.sub(r"_+", "_", cleaned).strip("._-")
return cleaned or "video"
def is_valid_video_name(name: str) -> bool:
suffix = Path(name).suffix.lower().lstrip(".")
return suffix in {"mp4", "mkv", "mov", "avi", "webm", "m4v", "flv", "mpeg", "mpg"}
def command_exists(command: str) -> bool:
return shutil.which(command) is not None
def run_command(
command: Sequence[str],
*,
timeout: int | None = None,
cwd: Path | None = None,
) -> subprocess.CompletedProcess[str]:
return subprocess.run(
list(command),
cwd=str(cwd) if cwd else None,
capture_output=True,
text=True,
timeout=timeout,
check=False,
shell=False,
)
def chunked(items: Sequence[T], size: int) -> Iterable[list[T]]:
if size <= 0:
raise ValueError("Chunk size must be greater than zero.")
total = len(items)
for start in range(0, total, size):
yield list(items[start : start + size])
def strip_code_fences(text: str) -> str:
stripped = text.strip()
if stripped.startswith("```"):
stripped = re.sub(r"^```[a-zA-Z0-9_-]*\s*", "", stripped)
stripped = re.sub(r"\s*```$", "", stripped)
return stripped.strip()
def normalize_whitespace(text: str) -> str:
return re.sub(r"\s+", " ", text).strip()