-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathac.py
More file actions
323 lines (259 loc) · 12.1 KB
/
Copy pathac.py
File metadata and controls
323 lines (259 loc) · 12.1 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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
import os
from pathlib import Path
from pydub import AudioSegment
SUPPORTED_INPUT_FORMATS = {
'.flac': 'FLAC', '.wav': 'WAV', '.aac': 'AAC', '.m4a': 'M4A',
'.ogg': 'OGG', '.wma': 'WMA', '.aiff': 'AIFF', '.ape': 'APE',
'.opus': 'Opus', '.ac3': 'AC3', '.dts': 'DTS', '.dsf': 'DSF',
'.dff': 'DFF', '.mp3': 'MP3', '.mp4': 'MP4'
}
SUPPORTED_OUTPUT_FORMATS = {
'mp3': {'name': 'MP3', 'ext': '.mp3', 'has_bitrate': True},
'aac': {'name': 'AAC', 'ext': '.aac', 'has_bitrate': True},
'ogg': {'name': 'OGG', 'ext': '.ogg', 'has_bitrate': True},
'wav': {'name': 'WAV', 'ext': '.wav', 'has_bitrate': False},
'flac': {'name': 'FLAC', 'ext': '.flac', 'has_bitrate': False},
'opus': {'name': 'Opus', 'ext': '.opus', 'has_bitrate': True}
}
BITRATE_OPTIONS = {
'1': '320k', '2': '256k', '3': '192k', '4': '160k',
'5': '128k', '6': '96k', '7': '64k'
}
def get_audio_files(folder):
audio_files = []
folder_path = Path(folder)
if not folder_path.exists():
print(f"Folder '{folder}' does not exist!")
return audio_files
for ext in SUPPORTED_INPUT_FORMATS.keys():
audio_files.extend(folder_path.glob(f'*{ext}'))
audio_files.extend(folder_path.glob(f'*{ext.upper()}'))
return sorted(set(audio_files))
def convert_audio(input_path, output_path, output_format='mp3', bitrate='192k', verbose=True):
try:
if verbose:
print(f" Loading: {input_path.name}")
audio = AudioSegment.from_file(input_path)
if verbose:
print(f" Exporting to {output_format.upper()}...")
export_params = {'format': output_format}
if SUPPORTED_OUTPUT_FORMATS[output_format]['has_bitrate']:
export_params['bitrate'] = bitrate
audio.export(output_path, **export_params)
original_size = os.path.getsize(input_path) / (1024 * 1024)
new_size = os.path.getsize(output_path) / (1024 * 1024)
return True, original_size, new_size, None
except Exception as e:
return False, 0, 0, str(e)
def batch_convert(original_folder='original', converted_folder='converted',
output_format='mp3', bitrate='192k', delete_original=False,
recursive=False, preserve_structure=True):
Path(converted_folder).mkdir(parents=True, exist_ok=True)
if recursive:
audio_files = []
for root, dirs, files in os.walk(original_folder):
for file in files:
file_path = Path(root) / file
if file_path.suffix.lower() in SUPPORTED_INPUT_FORMATS:
audio_files.append(file_path)
else:
audio_files = get_audio_files(original_folder)
if not audio_files:
print(f"No supported audio files found in '{original_folder}'")
print(f"Supported: {', '.join(SUPPORTED_INPUT_FORMATS.keys())}")
return
print(f"\nFound {len(audio_files)} audio files:")
format_count = {}
for file in audio_files:
ext = file.suffix.lower()
format_count[ext] = format_count.get(ext, 0) + 1
for ext, count in format_count.items():
print(f" • {ext}: {count} files")
output_ext = SUPPORTED_OUTPUT_FORMATS[output_format]['ext']
bitrate_str = f" (bitrate: {bitrate})" if SUPPORTED_OUTPUT_FORMATS[output_format]['has_bitrate'] else ""
print(f"\nConverting to {output_format.upper()}{bitrate_str}...")
print("-" * 60)
total_original = 0
total_new = 0
converted = 0
failed = []
for input_path in audio_files:
if preserve_structure and recursive:
relative_path = input_path.relative_to(original_folder)
output_dir = Path(converted_folder) / relative_path.parent
output_dir.mkdir(parents=True, exist_ok=True)
output_path = output_dir / (input_path.stem + output_ext)
else:
output_path = Path(converted_folder) / (input_path.stem + output_ext)
print(f"\nProcessing: {input_path.name}")
print(f" From: {SUPPORTED_INPUT_FORMATS.get(input_path.suffix.lower(), 'Unknown')}")
success, orig_size, new_size, error = convert_audio(
input_path, output_path, output_format, bitrate, verbose=True
)
if success:
if orig_size > 0:
compression = (1 - new_size/orig_size) * 100
saved = orig_size - new_size
print(f" ✓ Success!")
print(f" Size: {orig_size:.2f} MB → {new_size:.2f} MB")
print(f" Saved: {saved:.2f} MB ({compression:.1f}% {'smaller' if saved>0 else 'larger'})")
else:
print(f" ✓ Success! Size: {new_size:.2f} MB")
total_original += orig_size
total_new += new_size
converted += 1
if delete_original:
input_path.unlink()
print(f" Deleted original file")
else:
print(f" ✗ Failed: {error}")
failed.append(input_path.name)
print("\n" + "=" * 60)
print("CONVERSION SUMMARY")
print("=" * 60)
print(f"Successfully converted: {converted}/{len(audio_files)} files")
if total_original > 0 and total_new > 0:
total_saved = total_original - total_new
total_compression = (1 - total_new/total_original) * 100
print(f"\nTotal space:")
print(f" Original: {total_original:.2f} MB")
print(f" Converted: {total_new:.2f} MB")
print(f" Saved: {total_saved:.2f} MB ({total_compression:.1f}% {'reduction' if total_saved>0 else 'increase'})")
if failed:
print(f"\nFailed files ({len(failed)}):")
for file in failed:
print(f" • {file}")
print("\nConversion complete!")
def interactive_mode():
print("=" * 50)
print("AUDIO CONVERTER")
print("=" * 50)
print(f"Supported input: {', '.join(SUPPORTED_INPUT_FORMATS.keys())}")
print(f"Supported output: {', '.join(SUPPORTED_OUTPUT_FORMATS.keys())}")
print()
original = input("Source folder (default: 'original'): ").strip() or 'original'
converted = input("Destination folder (default: 'converted'): ").strip() or 'converted'
print("\nOutput format:")
formats = list(SUPPORTED_OUTPUT_FORMATS.keys())
for i, fmt in enumerate(formats, 1):
print(f"{i}. {fmt.upper()} - {SUPPORTED_OUTPUT_FORMATS[fmt]['name']}")
fmt_choice = input(f"Choice (1-{len(formats)}, default: 1): ").strip() or '1'
try:
output_format = formats[int(fmt_choice)-1]
except:
output_format = 'mp3'
bitrate = '192k'
if SUPPORTED_OUTPUT_FORMATS[output_format]['has_bitrate']:
print("\nSelect bitrate:")
print("1. 320k - Best quality")
print("2. 256k - High quality")
print("3. 192k - Balanced (recommended)")
print("4. 160k - Good")
print("5. 128k - Standard")
print("6. 96k - Small")
print("7. 64k - Smallest")
bitrate_choice = input("Choice (1-7, default: 3): ").strip() or '3'
bitrate = BITRATE_OPTIONS.get(bitrate_choice, '192k')
print("\nConversion mode:")
print("1. Standard - Fixed bitrate")
print("2. Smart - Target size reduction")
mode = input("Choice (1-2, default: 1): ").strip() or '1'
recursive = input("\nSearch subfolders recursively? (y/N): ").lower() == 'y'
if recursive:
preserve = input("Preserve folder structure? (Y/n): ").lower() != 'n'
else:
preserve = False
delete = input("Delete original files after conversion? (y/N): ").lower() == 'y'
if mode == '2' and SUPPORTED_OUTPUT_FORMATS[output_format]['has_bitrate']:
target = input("Target size reduction % (default: 50): ").strip()
target = int(target) if target.isdigit() else 50
smart_convert(original, converted, output_format, target, bitrate, recursive, preserve, delete)
else:
batch_convert(original, converted, output_format, bitrate, delete, recursive, preserve)
def smart_convert(original_folder, converted_folder, output_format='mp3',
target_reduction=50, max_bitrate='320k', min_bitrate='64k',
recursive=False, preserve=True, delete=False):
bitrates = ['320k', '256k', '192k', '160k', '128k', '96k', '64k']
try:
start_idx = bitrates.index(max_bitrate)
end_idx = bitrates.index(min_bitrate)
bitrates_to_try = bitrates[start_idx:end_idx+1]
except:
bitrates_to_try = bitrates
audio_files = get_audio_files(original_folder) if not recursive else []
if recursive:
audio_files = []
for root, dirs, files in os.walk(original_folder):
for file in files:
file_path = Path(root) / file
if file_path.suffix.lower() in SUPPORTED_INPUT_FORMATS:
audio_files.append(file_path)
if not audio_files:
print("No audio files found!")
return
print(f"\nSmart conversion targeting {target_reduction}% size reduction")
print(f"Trying bitrates: {', '.join(bitrates_to_try)}")
output_ext = SUPPORTED_OUTPUT_FORMATS[output_format]['ext']
total_original = 0
total_new = 0
converted = 0
for input_path in audio_files:
print(f"\nAnalyzing: {input_path.name}")
original_size = os.path.getsize(input_path) / (1024 * 1024)
if preserve and recursive:
relative_path = input_path.relative_to(original_folder)
output_dir = Path(converted_folder) / relative_path.parent
else:
output_dir = Path(converted_folder)
output_dir.mkdir(parents=True, exist_ok=True)
best_bitrate = None
best_new_size = None
for bitrate in bitrates_to_try:
temp_output = output_dir / f"temp_{input_path.stem}{output_ext}"
success, _, new_size, _ = convert_audio(
input_path, temp_output, output_format, bitrate, verbose=False
)
if success and original_size > 0:
reduction = (1 - new_size/original_size) * 100
print(f" {bitrate}: {new_size:.2f} MB ({reduction:.1f}% reduction)")
if reduction >= target_reduction:
best_bitrate = bitrate
best_new_size = new_size
temp_output.unlink()
break
if temp_output.exists():
temp_output.unlink()
if best_bitrate:
output_path = output_dir / (input_path.stem + output_ext)
success, _, new_size, _ = convert_audio(
input_path, output_path, output_format, best_bitrate, verbose=True
)
reduction = (1 - new_size/original_size) * 100
print(f" ✓ Using {best_bitrate} ({reduction:.1f}% reduction)")
total_original += original_size
total_new += new_size
converted += 1
if delete:
input_path.unlink()
else:
print(f" ✗ Using lowest bitrate {bitrates_to_try[-1]}")
output_path = output_dir / (input_path.stem + output_ext)
success, _, new_size, _ = convert_audio(
input_path, output_path, output_format, bitrates_to_try[-1], verbose=True
)
reduction = (1 - new_size/original_size) * 100
print(f" Achieved: {reduction:.1f}% reduction")
total_original += original_size
total_new += new_size
converted += 1
if delete:
input_path.unlink()
if total_original > 0:
total_saved = total_original - total_new
total_compression = (1 - total_new/total_original) * 100
print(f"\nSummary: {converted} files converted")
print(f" Original: {total_original:.2f} MB")
print(f" Converted: {total_new:.2f} MB")
print(f" Saved: {total_saved:.2f} MB ({total_compression:.1f}% reduction)")
if __name__ == "__main__":
interactive_mode()