-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathapp.py
More file actions
834 lines (697 loc) · 34.2 KB
/
Copy pathapp.py
File metadata and controls
834 lines (697 loc) · 34.2 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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
import os
import re
import json
import time
import logging
from pathlib import Path
import shutil
import requests
from mutagen.id3 import ID3NoHeaderError
from mutagen import File as MutagenFile
from mutagen.mp3 import MP3
from mutagen.flac import FLAC
from mutagen.mp4 import MP4
from mutagen.oggvorbis import OggVorbis
from mutagen.oggopus import OggOpus
from openai import OpenAI
from tqdm import tqdm
logger = logging.getLogger(__name__)
__version__ = "1.2.0"
LOG_FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
def configure_logging(log_file="metadata_updater.log", console=True):
"""Configure root logging once. Safe to call from CLI or GUI imports."""
root = logging.getLogger()
if root.handlers:
return
root.setLevel(logging.INFO)
formatter = logging.Formatter(LOG_FORMAT)
file_handler = logging.FileHandler(log_file)
file_handler.setFormatter(formatter)
root.addHandler(file_handler)
if console:
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
root.addHandler(stream_handler)
# ==========================================
# HARDCODED CONFIGURATION
# ==========================================
# Directory settings
INPUT_FOLDER = "input" # Folder containing your audio files
OUTPUT_FOLDER = "output" # Folder where processed files will be saved
# LLM Provider Configuration
# Choose between "openai", "ollama", or "lmstudio"
LLM_PROVIDER = "ollama" # Options: "openai", "ollama", "lmstudio"
# OpenAI Configuration (only used if LLM_PROVIDER = "openai")
OPENAI_API_KEY = "YOUR_OPENAI_API_KEY_HERE" # Your OpenAI API key
# Default: GPT-5.6 Terra (balanced intelligence/cost). Any chat model on your account works.
OPENAI_MODEL = "gpt-5.6-terra"
# Ollama Configuration (only used if LLM_PROVIDER = "ollama")
OLLAMA_BASE_URL = "http://localhost:11434" # Ollama server URL (default: http://localhost:11434)
# Default: Gemma 4 E4B (edge-friendly). Use any model from `ollama list` that fits your machine.
OLLAMA_MODEL = "gemma4:e4b"
# LM Studio Configuration (only used if LLM_PROVIDER = "lmstudio")
# Use the model identifier shown in LM Studio's local server UI / Hub
LMSTUDIO_BASE_URL = "http://localhost:1234/v1" # LM Studio OpenAI-compatible API URL
# Default matches a common Gemma 4 Hub id; change to whatever you have loaded.
LMSTUDIO_MODEL = "google/gemma-4-e4b"
# Processing settings
BATCH_SIZE = 10 # Number of files to process before showing progress
RATE_LIMIT_DELAY = 1.0 # Delay between API calls in seconds
OVERWRITE = True # Whether to overwrite existing metadata
class MusicMetadataGenerator:
def __init__(self, config=None):
"""
Initialize the Music metadata generator for multiple audio formats.
"""
# Default configuration
cfg = {
"input_folder": INPUT_FOLDER,
"output_folder": OUTPUT_FOLDER,
"batch_size": BATCH_SIZE,
"rate_limit_delay": RATE_LIMIT_DELAY,
"overwrite": OVERWRITE,
"llm_provider": LLM_PROVIDER,
"openai_api_key": OPENAI_API_KEY,
"openai_model": OPENAI_MODEL,
"ollama_base_url": OLLAMA_BASE_URL,
"ollama_model": OLLAMA_MODEL,
"lmstudio_base_url": LMSTUDIO_BASE_URL,
"lmstudio_model": LMSTUDIO_MODEL,
}
if config:
# Ignore unknown keys (e.g. legacy "gui") and only apply known settings
for key in list(cfg.keys()):
if key in config and config[key] is not None:
cfg[key] = config[key]
self.cfg = cfg
self.input_folder = Path(cfg["input_folder"]).expanduser()
self.output_folder = Path(cfg["output_folder"]).expanduser()
self.batch_size = int(cfg["batch_size"])
self.rate_limit_delay = float(cfg["rate_limit_delay"])
self.overwrite = bool(cfg["overwrite"])
self.llm_provider = str(cfg["llm_provider"]).lower().strip()
# Ensure folders exist
if not str(cfg["input_folder"]).strip():
raise FileNotFoundError("Input folder is not configured")
if not self.input_folder.exists():
raise FileNotFoundError(f"Input folder not found: {self.input_folder}")
if not self.output_folder.exists():
logger.info(f"Creating output folder: {self.output_folder}")
self.output_folder.mkdir(parents=True, exist_ok=True)
# Initialize LLM client based on provider
self._initialize_llm_client()
# Statistics for reporting
self.stats = {
"total_files": 0,
"processed_files": 0,
"success": 0,
"errors": 0,
"skipped": 0
}
def _initialize_llm_client(self):
"""Initialize the appropriate LLM client based on the configured provider."""
if self.llm_provider == "openai":
try:
self.client = OpenAI(api_key=self.cfg["openai_api_key"])
self.model = self.cfg["openai_model"]
logger.info(f"Initialized OpenAI client with model: {self.model}")
except Exception as e:
logger.error(f"Failed to initialize OpenAI client: {e}")
raise
elif self.llm_provider == "lmstudio":
try:
self.client = OpenAI(base_url=self.cfg["lmstudio_base_url"], api_key="lm-studio")
self.model = self.cfg["lmstudio_model"]
# Test LM Studio connection
self._test_lmstudio_connection()
logger.info(f"Initialized LM Studio client with model: {self.model} at {self.cfg['lmstudio_base_url']}")
except Exception as e:
logger.error(f"Failed to initialize LM Studio client: {e}")
raise
elif self.llm_provider == "ollama":
try:
self.ollama_url = self.cfg["ollama_base_url"].rstrip('/')
self.model = self.cfg["ollama_model"]
# Test Ollama connection
self._test_ollama_connection()
logger.info(f"Initialized Ollama client with model: {self.model} at {self.ollama_url}")
except Exception as e:
logger.error(f"Failed to initialize Ollama client: {e}")
raise
else:
raise ValueError(f"Unsupported LLM provider: {self.llm_provider}. Use 'openai', 'ollama', or 'lmstudio'")
def _test_lmstudio_connection(self):
"""Test connection to LM Studio server."""
try:
url = self.cfg["lmstudio_base_url"].rstrip('/') + "/models"
response = requests.get(url, timeout=5)
if response.status_code != 200:
raise Exception(f"LM Studio server responded with status {response.status_code}")
except requests.exceptions.RequestException as e:
raise Exception(f"Cannot connect to LM Studio server at {self.cfg['lmstudio_base_url']}: {e}")
def _test_ollama_connection(self):
"""Test connection to Ollama server."""
try:
response = requests.get(f"{self.ollama_url}/api/tags", timeout=5)
if response.status_code != 200:
raise Exception(f"Ollama server responded with status {response.status_code}")
except requests.exceptions.RequestException as e:
raise Exception(f"Cannot connect to Ollama server at {self.ollama_url}: {e}")
def _call_ollama_api(self, prompt):
"""Make a request to Ollama API."""
try:
payload = {
"model": self.model,
"prompt": prompt,
"stream": False,
"format": "json"
}
response = requests.post(
f"{self.ollama_url}/api/generate",
json=payload,
timeout=60
)
if response.status_code != 200:
raise Exception(f"Ollama API returned status {response.status_code}: {response.text}")
result = response.json()
return result.get("response", "")
except Exception as e:
logger.error(f"Error calling Ollama API: {e}")
raise
def get_audio_files(self):
"""Find all supported audio files in the input folder."""
try:
supported_extensions = ['*.mp3', '*.flac', '*.m4a', '*.mp4', '*.ogg', '*.opus']
audio_files = []
for extension in supported_extensions:
files = list(self.input_folder.glob(f"**/{extension}"))
audio_files.extend(files)
logger.info(f"Found {len(audio_files)} audio files in {self.input_folder}")
logger.info(f"Supported formats: {', '.join([ext.replace('*.', '.') for ext in supported_extensions])}")
self.stats["total_files"] = len(audio_files)
return audio_files
except Exception as e:
logger.error(f"Error finding audio files: {e}")
return []
def clean_filename(self, filename):
"""Extract and clean the song name from the filename."""
# Remove file extension
name = os.path.splitext(filename)[0]
# Remove common prefixes, numbering, etc.
name = re.sub(r'^\d+[\s_\-\.]+', '', name) # Remove leading numbers with separators
name = re.sub(r'^\[.*?\][\s_\-\.]*', '', name) # Remove bracketed text at start
# Replace separators with spaces
name = re.sub(r'[_\-\.]+', ' ', name)
# Remove extra spaces
name = re.sub(r'\s+', ' ', name).strip()
return name
def get_metadata_from_llm(self, song_name):
"""Query the configured LLM to get metadata for a song."""
prompt = f"""
I need detailed metadata for the song titled "{song_name}".
Please provide the following information:
- Title: The full and correct title of the song
- Artists: The performers/singers of the song (as a comma-separated string, not an array)
- Album: The album name or compilation it's from
- Year: The release year (as a number)
- Composer: The composer/producer/music director
- Genre: The primary genre of the song
- Language: The language of the song's lyrics (if applicable)
Return your response ONLY as a JSON object with these fields. If you're uncertain about any field, provide your best guess but mark it with "confidence": "low". If you cannot determine a field at all, use null for its value.
Example response format:
Example 1 (English song):
{{
"title": "Yesterday",
"artists": "The Beatles",
"album": "Help!",
"year": 1965,
"composer": "John Lennon, Paul McCartney",
"genre": "Rock",
"language": "English"
}}
Example 2 (Hindi song):
{{
"title": "Tum Hi Ho",
"artists": "Arijit Singh",
"album": "Aashiqui 2",
"year": 2013,
"composer": "Mithoon",
"genre": "Indian Pop",
"language": "Hindi"
}}
"""
try:
if self.llm_provider == "openai":
return self._get_metadata_from_openai(prompt, song_name)
elif self.llm_provider == "lmstudio":
return self._get_metadata_from_lmstudio(prompt, song_name)
elif self.llm_provider == "ollama":
return self._get_metadata_from_ollama(prompt, song_name)
else:
raise ValueError(f"Unsupported LLM provider: {self.llm_provider}")
except Exception as e:
logger.error(f"Error getting metadata for '{song_name}': {e}")
return {
"error": str(e),
"title": song_name
}
def _get_metadata_from_lmstudio(self, prompt, song_name):
"""Get metadata using LM Studio API."""
try:
response = self.client.chat.completions.create(
model=self.model,
messages=[
{"role": "system", "content": "You are a music metadata expert with comprehensive knowledge of music across all genres, artists, and time periods. Provide accurate metadata in JSON format ONLY. Do not include any explanations or comments outside the JSON object."},
{"role": "user", "content": prompt}
]
)
metadata_json = response.choices[0].message.content
except Exception as e:
logger.error(f"LM Studio API call failed for '{song_name}': {e}")
return {"title": song_name, "error": f"LM Studio API call failed: {e}"}
try:
metadata = json.loads(metadata_json)
logger.debug(f"Got metadata for '{song_name}': {metadata}")
return metadata
except json.JSONDecodeError as e:
try:
json_match = re.search(r'\{.*\}', metadata_json, re.DOTALL)
if json_match:
metadata = json.loads(json_match.group())
logger.info(f"Successfully extracted JSON from LM Studio response for '{song_name}' (bypassed markdown code fences)")
return metadata
except Exception as extraction_err:
pass
logger.error(f"Failed to parse JSON from LM Studio response for '{song_name}': {e}")
logger.error(f"Raw response: {metadata_json}")
return {"title": song_name, "error": "Failed to parse LM Studio response"}
def _get_metadata_from_openai(self, prompt, song_name):
"""Get metadata using OpenAI API."""
response = self.client.chat.completions.create(
model=self.model,
response_format={"type": "json_object"},
messages=[
{"role": "system", "content": "You are a music metadata expert with comprehensive knowledge of music across all genres, artists, and time periods. Provide accurate metadata in JSON format ONLY. Do not include any explanations or comments outside the JSON object."},
{"role": "user", "content": prompt}
]
)
metadata_json = response.choices[0].message.content
try:
metadata = json.loads(metadata_json)
logger.debug(f"Got metadata for '{song_name}': {metadata}")
return metadata
except json.JSONDecodeError as e:
try:
json_match = re.search(r'\{.*\}', metadata_json, re.DOTALL)
if json_match:
metadata = json.loads(json_match.group())
logger.info(f"Successfully extracted JSON from OpenAI response for '{song_name}' (bypassed markdown code fences)")
return metadata
except Exception as extraction_err:
pass
logger.error(f"Failed to parse JSON from OpenAI response for '{song_name}': {e}")
logger.error(f"Raw response: {metadata_json}")
return {"title": song_name, "error": "Failed to parse OpenAI response"}
def _get_metadata_from_ollama(self, prompt, song_name):
"""Get metadata using Ollama API."""
system_prompt = "You are a music metadata expert with comprehensive knowledge of music across all genres, artists, and time periods. Provide accurate metadata in JSON format ONLY. Do not include any explanations or comments outside the JSON object."
full_prompt = f"{system_prompt}\n\n{prompt}"
response_text = self._call_ollama_api(full_prompt)
try:
metadata = json.loads(response_text)
logger.debug(f"Got metadata for '{song_name}': {metadata}")
return metadata
except json.JSONDecodeError as e:
try:
import re
json_match = re.search(r'\{.*\}', response_text, re.DOTALL)
if json_match:
metadata = json.loads(json_match.group())
logger.info(f"Successfully extracted JSON from Ollama response for '{song_name}' (bypassed markdown code fences)")
return metadata
except Exception as extraction_err:
pass
logger.error(f"Failed to parse JSON from Ollama response for '{song_name}': {e}")
logger.error(f"Raw response: {response_text}")
return {"title": song_name, "error": "Failed to parse Ollama response"}
def update_audio_metadata(self, file_path, metadata):
"""Update the metadata tags of an audio file with the provided metadata."""
try:
# Recreate the input folder structure inside the output folder
try:
relative_path = file_path.relative_to(self.input_folder)
except ValueError:
relative_path = Path(file_path.name)
output_path = self.output_folder / relative_path
# Ensure any subdirectories are created
output_path.parent.mkdir(parents=True, exist_ok=True)
output_path_str = str(output_path)
source_path_str = str(file_path)
# Copy the file to the output directory
logger.info(f"Copying file to output folder: {output_path_str}")
shutil.copy2(source_path_str, output_path_str)
# Load the audio file using mutagen
audiofile = MutagenFile(output_path_str)
# Check if the file was loaded properly
if audiofile is None:
logger.error(f"Failed to load audio file {output_path}")
self.stats["errors"] += 1
return False
file_ext = file_path.suffix.lower()
# Check for existing metadata and skip if overwrite is False
if not self.overwrite and self._has_existing_metadata(audiofile, file_ext):
logger.info(f"Skipping '{file_path.name}' - already has metadata and overwrite is False")
self.stats["skipped"] += 1
return False
# Update metadata based on file format
if file_ext == '.mp3':
success = self._update_mp3_tags(audiofile, metadata)
elif file_ext == '.flac':
success = self._update_flac_tags(audiofile, metadata)
elif file_ext in ['.m4a', '.mp4']:
success = self._update_mp4_tags(audiofile, metadata)
elif file_ext == '.ogg':
success = self._update_ogg_tags(audiofile, metadata)
elif file_ext == '.opus':
success = self._update_opus_tags(audiofile, metadata)
else:
logger.error(f"Unsupported file format: {file_ext}")
self.stats["errors"] += 1
return False
if success:
# Save the changes
audiofile.save()
logger.info(f"Successfully updated metadata for '{file_path.name}' saved to {output_path}")
self.stats["success"] += 1
return True
else:
self.stats["errors"] += 1
return False
except Exception as e:
logger.error(f"Error updating metadata for '{file_path.name}': {str(e)}")
self.stats["errors"] += 1
return False
def _has_existing_metadata(self, audiofile, file_ext):
"""Check if the audio file already has metadata."""
try:
if file_ext == '.mp3':
return bool(audiofile.get('TIT2') or audiofile.get('TPE1'))
elif file_ext == '.flac':
return bool(audiofile.get('TITLE') or audiofile.get('ARTIST'))
elif file_ext in ['.m4a', '.mp4']:
return bool(audiofile.get('\xa9nam') or audiofile.get('\xa9ART'))
elif file_ext in ['.ogg', '.opus']:
return bool(audiofile.get('TITLE') or audiofile.get('ARTIST'))
return False
except:
return False
def _update_mp3_tags(self, audiofile, metadata):
"""Update MP3 ID3 tags."""
try:
from mutagen.id3 import TIT2, TPE1, TALB, TDRC, TCOM, TCON, COMM
if metadata.get("title"):
audiofile['TIT2'] = TIT2(encoding=3, text=str(metadata["title"]))
if metadata.get("artists"):
artists_str = metadata["artists"] if isinstance(metadata["artists"], str) else ", ".join(str(a) for a in metadata["artists"])
audiofile['TPE1'] = TPE1(encoding=3, text=artists_str)
if metadata.get("album"):
audiofile['TALB'] = TALB(encoding=3, text=str(metadata["album"]))
if metadata.get("year"):
try:
year_str = str(metadata["year"])
if year_str.isdigit():
audiofile['TDRC'] = TDRC(encoding=3, text=year_str)
except:
pass
if metadata.get("composer"):
audiofile['TCOM'] = TCOM(encoding=3, text=str(metadata["composer"]))
if metadata.get("genre"):
audiofile['TCON'] = TCON(encoding=3, text=str(metadata["genre"]))
if metadata.get("language"):
audiofile['COMM'] = COMM(encoding=3, lang='eng', desc='Language', text=str(metadata["language"]))
return True
except Exception as e:
logger.error(f"Error updating MP3 tags: {e}")
return False
def _update_flac_tags(self, audiofile, metadata):
"""Update FLAC vorbis comments."""
try:
if metadata.get("title"):
audiofile['TITLE'] = str(metadata["title"])
if metadata.get("artists"):
artists_str = metadata["artists"] if isinstance(metadata["artists"], str) else ", ".join(str(a) for a in metadata["artists"])
audiofile['ARTIST'] = artists_str
if metadata.get("album"):
audiofile['ALBUM'] = str(metadata["album"])
if metadata.get("year"):
try:
year_str = str(metadata["year"])
if year_str.isdigit():
audiofile['DATE'] = year_str
except:
pass
if metadata.get("composer"):
audiofile['COMPOSER'] = str(metadata["composer"])
if metadata.get("genre"):
audiofile['GENRE'] = str(metadata["genre"])
if metadata.get("language"):
audiofile['LANGUAGE'] = str(metadata["language"])
return True
except Exception as e:
logger.error(f"Error updating FLAC tags: {e}")
return False
def _update_mp4_tags(self, audiofile, metadata):
"""Update MP4/M4A tags."""
try:
if metadata.get("title"):
audiofile['\xa9nam'] = str(metadata["title"])
if metadata.get("artists"):
artists_str = metadata["artists"] if isinstance(metadata["artists"], str) else ", ".join(str(a) for a in metadata["artists"])
audiofile['\xa9ART'] = artists_str
if metadata.get("album"):
audiofile['\xa9alb'] = str(metadata["album"])
if metadata.get("year"):
try:
year_str = str(metadata["year"])
if year_str.isdigit():
audiofile['\xa9day'] = year_str
except:
pass
if metadata.get("composer"):
audiofile['\xa9wrt'] = str(metadata["composer"])
if metadata.get("genre"):
audiofile['\xa9gen'] = str(metadata["genre"])
if metadata.get("language"):
audiofile['\xa9lyr'] = f"Language: {metadata['language']}"
return True
except Exception as e:
logger.error(f"Error updating MP4 tags: {e}")
return False
def _update_ogg_tags(self, audiofile, metadata):
"""Update OGG Vorbis comments."""
try:
if metadata.get("title"):
audiofile['TITLE'] = str(metadata["title"])
if metadata.get("artists"):
artists_str = metadata["artists"] if isinstance(metadata["artists"], str) else ", ".join(str(a) for a in metadata["artists"])
audiofile['ARTIST'] = artists_str
if metadata.get("album"):
audiofile['ALBUM'] = str(metadata["album"])
if metadata.get("year"):
try:
year_str = str(metadata["year"])
if year_str.isdigit():
audiofile['DATE'] = year_str
except:
pass
if metadata.get("composer"):
audiofile['COMPOSER'] = str(metadata["composer"])
if metadata.get("genre"):
audiofile['GENRE'] = str(metadata["genre"])
if metadata.get("language"):
audiofile['LANGUAGE'] = str(metadata["language"])
return True
except Exception as e:
logger.error(f"Error updating OGG tags: {e}")
return False
def _update_opus_tags(self, audiofile, metadata):
"""Update Opus comments."""
try:
if metadata.get("title"):
audiofile['TITLE'] = str(metadata["title"])
if metadata.get("artists"):
artists_str = metadata["artists"] if isinstance(metadata["artists"], str) else ", ".join(str(a) for a in metadata["artists"])
audiofile['ARTIST'] = artists_str
if metadata.get("album"):
audiofile['ALBUM'] = str(metadata["album"])
if metadata.get("year"):
try:
year_str = str(metadata["year"])
if year_str.isdigit():
audiofile['DATE'] = year_str
except:
pass
if metadata.get("composer"):
audiofile['COMPOSER'] = str(metadata["composer"])
if metadata.get("genre"):
audiofile['GENRE'] = str(metadata["genre"])
if metadata.get("language"):
audiofile['LANGUAGE'] = str(metadata["language"])
return True
except Exception as e:
logger.error(f"Error updating Opus tags: {e}")
return False
def _interruptible_sleep(self, delay, stop_event=None):
"""Sleep for delay seconds, returning early if stop_event is set."""
if delay <= 0:
return False
if stop_event is None:
time.sleep(delay)
return False
steps = max(1, int(delay * 10))
slice_len = delay / steps
for _ in range(steps):
if stop_event.is_set():
return True
time.sleep(slice_len)
return stop_event.is_set()
def process_files(self, progress_callback=None, stop_event=None):
"""
Process all audio files in the input folder.
Args:
progress_callback: Optional callable receiving progress event dicts
(used by the GUI). Events: start, file_start, file_complete,
complete, cancelled, error.
stop_event: Optional threading.Event; when set, processing stops
between files / during rate-limit delays.
"""
audio_files = self.get_audio_files()
if not audio_files:
logger.warning("No audio files found to process.")
if progress_callback:
progress_callback({
"type": "error",
"message": "No audio files found to process."
})
return
logger.info(f"Starting to process {len(audio_files)} files...")
if progress_callback:
progress_callback({"type": "start", "total": len(audio_files)})
file_iter = audio_files
if progress_callback is None:
file_iter = tqdm(audio_files, desc="Processing audio files")
for i, file_path in enumerate(file_iter):
if stop_event is not None and stop_event.is_set():
if progress_callback:
progress_callback({"type": "cancelled"})
return
try:
song_name = self.clean_filename(file_path.name)
logger.info(
f"Processing ({i+1}/{len(audio_files)}): "
f"'{song_name}' [{file_path.suffix.upper()}]"
)
if progress_callback:
progress_callback({
"type": "file_start",
"index": i + 1,
"total": len(audio_files),
"file": file_path.name,
"song_name": song_name,
})
metadata = self.get_metadata_from_llm(song_name)
if stop_event is not None and stop_event.is_set():
if progress_callback:
progress_callback({"type": "cancelled"})
return
success = self.update_audio_metadata(file_path, metadata)
if not success and "error" in metadata:
logger.error(f"Failed to update metadata: {metadata.get('error')}")
self.stats["processed_files"] += 1
if progress_callback:
progress_callback({
"type": "file_complete",
"index": i + 1,
"total": len(audio_files),
"file": file_path.name,
"success": success,
"stats": self.stats.copy(),
})
if (i + 1) % self.batch_size == 0 or i == len(audio_files) - 1:
logger.info(f"Progress: {i+1}/{len(audio_files)} files processed.")
if i < len(audio_files) - 1:
if self._interruptible_sleep(self.rate_limit_delay, stop_event):
if progress_callback:
progress_callback({"type": "cancelled"})
return
except Exception as e:
logger.error(f"Error processing file '{file_path}': {str(e)}")
self.stats["errors"] += 1
if progress_callback:
progress_callback({
"type": "file_complete",
"index": i + 1,
"total": len(audio_files),
"file": file_path.name,
"success": False,
"stats": self.stats.copy(),
})
continue
if progress_callback:
progress_callback({"type": "complete", "stats": self.stats.copy()})
def print_summary(self):
"""Print a summary of the processing results."""
logger.info("\n" + "="*50)
logger.info("PROCESSING SUMMARY")
logger.info("="*50)
logger.info(f"Total files found: {self.stats['total_files']}")
logger.info(f"Files processed: {self.stats['processed_files']}")
logger.info(f"Successful updates: {self.stats['success']}")
logger.info(f"Skipped files: {self.stats['skipped']}")
logger.info(f"Errors: {self.stats['errors']}")
logger.info("="*50 + "\n")
def main():
configure_logging(console=True)
try:
import argparse
parser = argparse.ArgumentParser(
description=f"MP3Detective v{__version__} — Music Metadata Generator"
)
parser.add_argument("--config", type=str, help="Path to config JSON file")
parser.add_argument(
"--version", action="version", version=f"MP3Detective {__version__}"
)
args = parser.parse_args()
config = {}
if args.config:
try:
with open(args.config, 'r') as f:
config = json.load(f)
except Exception as config_err:
logger.error(f"Failed to load config file: {config_err}")
print(f"Error loading config file: {config_err}")
return 1
generator = MusicMetadataGenerator(config=config)
print(f"Starting Music Metadata Generator v{__version__} (Multi-Format Support)")
print(f"Input folder: {generator.input_folder}")
print(f"Output folder: {generator.output_folder}")
print("Supported formats: MP3, FLAC, M4A, MP4, OGG, OPUS")
print(f"LLM Provider: {generator.llm_provider.upper()}")
if generator.llm_provider == "openai":
print(f"OpenAI Model: {generator.cfg.get('openai_model')}")
elif generator.llm_provider == "ollama":
print(f"Ollama Model: {generator.cfg.get('ollama_model')}")
print(f"Ollama URL: {generator.cfg.get('ollama_base_url')}")
elif generator.llm_provider == "lmstudio":
print(f"LM Studio Model: {generator.cfg.get('lmstudio_model')}")
print(f"LM Studio URL: {generator.cfg.get('lmstudio_base_url')}")
generator.process_files()
generator.print_summary()
print("\nProcess completed! Check metadata_updater.log for details.")
except Exception as e:
logger.error(f"Fatal error: {e}")
print(f"Fatal error occurred: {e}")
return 1
return 0
if __name__ == "__main__":
exit(main())