-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
182 lines (154 loc) · 5.57 KB
/
Copy pathmain.py
File metadata and controls
182 lines (154 loc) · 5.57 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
import os
import time
import threading
import subprocess
import shutil
from pathlib import Path
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
SRC = Path(os.getenv("SRC_DIR", "/music/flac")).resolve()
DST = Path(os.getenv("DST_DIR", "/music/opus")).resolve()
TRANSCODE_FORMAT = os.getenv("OUTPUT_FORMAT", "opus")
BITRATE = os.getenv("BITRATE", "160k")
AAC_VBR_QUALITY = os.getenv("AAC_VBR_QUALITY", "4")
RESCAN_INTERVAL = int(os.getenv("RESCAN_INTERVAL", "600")) # seconds
COVER_NAMES = ["cover", "folder", "album"]
COVER_FORMATS = ["jpg", "jpeg", "png", "webp"]
SUPPORTED_INPUTS = {".flac", ".alac", ".m4a", ".wav"} # ALAC is usually in .m4a
def find_cover(track_path: Path):
parent = track_path.parent
for name in COVER_NAMES:
for ext in COVER_FORMATS:
# exact match: cover.jpg
p = parent / f"{name}.{ext}"
if p.exists():
return p
# fallback: any image starting with cover/folder/album (case-insensitive)
for f in parent.iterdir():
if not f.is_file():
continue
stem = f.stem.lower()
suffix = f.suffix.lstrip(".").lower()
if stem in COVER_NAMES and suffix in COVER_FORMATS:
return f
return None
def copy_cover_if_needed(src_cover: Path, dest_dir: Path):
dest_cover = dest_dir / src_cover.name
if not dest_cover.exists():
shutil.copy2(src_cover, dest_cover)
def dst_path_for(src_file: Path):
rel = src_file.relative_to(SRC)
if TRANSCODE_FORMAT == "opus":
return (DST / rel).with_suffix(".opus")
elif TRANSCODE_FORMAT == "aac":
return (DST / rel).with_suffix(".m4a")
def transcode(src_file: Path):
out_file = dst_path_for(src_file)
out_file.parent.mkdir(parents=True, exist_ok=True)
out_dir = out_file.parent
cover = find_cover(src_file)
print(f"Transcoding: {src_file}")
if cover:
print(f"Using cover art: {cover}")
# Always copy cover to output folder as backup
copy_cover_if_needed(cover, out_dir)
if TRANSCODE_FORMAT == "opus":
cmd = [
"ffmpeg", "-y",
"-i", str(src_file),
"-c:a", "libopus",
"-b:a", BITRATE,
str(out_file)
]
elif TRANSCODE_FORMAT == "aac":
cmd = [
"ffmpeg", "-y",
"-i", str(src_file),
"-i", str(cover),
"-map", "0:a",
"-map", "1",
"-c:a", "libfdk_aac",
"-vbr", AAC_VBR_QUALITY,
"-c:v", "mjpeg",
"-disposition:v:0", "attached_pic",
"-metadata:s:v", "title=Album cover",
"-metadata:s:v", "comment=Cover (front)",
str(out_file)
]
else:
if TRANSCODE_FORMAT == "opus":
cmd = [
"ffmpeg", "-y",
"-i", str(src_file),
"-c:a", "libopus",
"-b:a", BITRATE,
str(out_file)
]
elif TRANSCODE_FORMAT == "aac":
cmd = [
"ffmpeg", "-y",
"-i", str(src_file),
"-map", "0",
"-c:a", "libfdk_aac",
"-vbr", AAC_VBR_QUALITY,
"-profile:a", "aac_low",
"-c:v", "copy",
str(out_file)
]
subprocess.run(cmd, check=False)
def is_supported_audio(path: Path) -> bool:
return path.suffix.lower() in SUPPORTED_INPUTS
class AudioHandler(FileSystemEventHandler):
def on_created(self, event):
if not event.is_directory and is_supported_audio(Path(event.src_path)):
transcode(Path(event.src_path))
def on_moved(self, event):
if not event.is_directory and is_supported_audio(Path(event.dest_path)):
transcode(Path(event.dest_path))
def on_modified(self, event):
if not event.is_directory and is_supported_audio(Path(event.src_path)):
transcode(Path(event.src_path))
def scan_and_sync():
for ext in SUPPORTED_INPUTS:
for path in SRC.rglob(f"*{ext}"):
out = dst_path_for(path)
if not out.exists():
transcode(path)
def periodic_rescan():
while True:
time.sleep(RESCAN_INTERVAL)
scan_and_sync()
if __name__ == "__main__":
print(r' /$$ /$$')
print(r' |__/ |__/')
print(r' /$$$$$$$ /$$$$$$ /$$ /$$$$$$$$ /$$ /$$ /$$')
print(r' /$$_____/ /$$__ $$| $$|____ /$$/| $$ | $$| $$')
print(r' | $$$$$$ | $$$$$$$$| $$ /$$$$/ | $$ | $$| $$')
print(r' \____ $$| $$_____/| $$ /$$__/ | $$ | $$| $$')
print(r' /$$$$$$$/| $$$$$$$| $$ /$$$$$$$$| $$$$$$/| $$')
print(r' |_______/ \_______/|__/|________/ \______/ |__/')
print("")
print("*" * 50)
print(f"Source: {SRC}")
print(f"Dest: {DST}")
print(f"Format: {TRANSCODE_FORMAT}")
if TRANSCODE_FORMAT == "opus":
print(f"Bitrate: {BITRATE}")
elif TRANSCODE_FORMAT == "aac":
print(f"Quality: {AAC_VBR_QUALITY}")
print("*" * 50)
print("")
print("Watching for new files...")
scan_and_sync()
event_handler = AudioHandler()
observer = Observer()
observer.schedule(event_handler, str(SRC), recursive=True)
observer.start()
t = threading.Thread(target=periodic_rescan, daemon=True)
t.start()
try:
while True:
time.sleep(5)
except KeyboardInterrupt:
observer.stop()
observer.join()