id
int64 0
458k
| file_name
stringlengths 4
119
| file_path
stringlengths 14
227
| content
stringlengths 24
9.96M
| size
int64 24
9.96M
| language
stringclasses 1
value | extension
stringclasses 14
values | total_lines
int64 1
219k
| avg_line_length
float64 2.52
4.63M
| max_line_length
int64 5
9.91M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 7
101
| repo_stars
int64 100
139k
| repo_forks
int64 0
26.4k
| repo_open_issues
int64 0
2.27k
| repo_license
stringclasses 12
values | repo_extraction_date
stringclasses 433
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
10,900
|
test_mp4.py
|
metabrainz_picard/test/formats/test_mp4.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2019-2021 Philipp Wolfer
# Copyright (C) 2020-2021 Laurent Monin
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import unittest
import mutagen
from picard.formats import ext_to_format
from picard.metadata import Metadata
from .common import (
CommonTests,
load_metadata,
load_raw,
save_and_load_metadata,
save_metadata,
save_raw,
skipUnlessTestfile,
)
from .coverart import CommonCoverArtTests
# prevent unittest to run tests in those classes
class CommonMP4Tests:
class MP4TestCase(CommonTests.TagFormatsTestCase):
def test_supports_tag(self):
fmt = ext_to_format(self.testfile_ext)
self.assertTrue(fmt.supports_tag('copyright'))
self.assertTrue(fmt.supports_tag('compilation'))
self.assertTrue(fmt.supports_tag('bpm'))
self.assertTrue(fmt.supports_tag('djmixer'))
self.assertTrue(fmt.supports_tag('discnumber'))
self.assertTrue(fmt.supports_tag('lyrics:lead'))
self.assertTrue(fmt.supports_tag('Custom'))
self.assertTrue(fmt.supports_tag('äöüéß\0')) # Latin 1 is supported
self.assertFalse(fmt.supports_tag('Б')) # Unsupported custom tags
for tag in self.replaygain_tags.keys():
self.assertTrue(fmt.supports_tag(tag))
def test_format(self):
metadata = load_metadata(self.filename)
self.assertIn('AAC LC', metadata['~format'])
@skipUnlessTestfile
def test_replaygain_tags_case_insensitive(self):
tags = mutagen.mp4.MP4Tags()
tags['----:com.apple.iTunes:replaygain_album_gain'] = [b'-6.48 dB']
tags['----:com.apple.iTunes:Replaygain_Album_Peak'] = [b'0.978475']
tags['----:com.apple.iTunes:replaygain_album_range'] = [b'7.84 dB']
tags['----:com.apple.iTunes:replaygain_track_gain'] = [b'-6.16 dB']
tags['----:com.apple.iTunes:REPLAYGAIN_track_peak'] = [b'0.976991']
tags['----:com.apple.iTunes:REPLAYGAIN_TRACK_RANGE'] = [b'8.22 dB']
tags['----:com.apple.iTunes:replaygain_reference_loudness'] = [b'-18.00 LUFS']
save_raw(self.filename, tags)
loaded_metadata = load_metadata(self.filename)
for (key, value) in self.replaygain_tags.items():
self.assertEqual(loaded_metadata[key], value, '%s: %r != %r' % (key, loaded_metadata[key], value))
@skipUnlessTestfile
def test_ci_tags_preserve_case(self):
# Ensure values are not duplicated on repeated save and are saved
# case preserving.
for name in ('Replaygain_Album_Peak', 'Custom', 'äöüéß\0'):
tags = mutagen.mp4.MP4Tags()
tags['----:com.apple.iTunes:' + name] = [b'foo']
save_raw(self.filename, tags)
loaded_metadata = load_metadata(self.filename)
loaded_metadata[name.lower()] = 'bar'
save_metadata(self.filename, loaded_metadata)
raw_metadata = load_raw(self.filename)
self.assertIn('----:com.apple.iTunes:' + name, raw_metadata)
self.assertEqual(
raw_metadata['----:com.apple.iTunes:' + name][0].decode('utf-8'),
loaded_metadata[name.lower()])
self.assertEqual(1, len(raw_metadata['----:com.apple.iTunes:' + name]))
self.assertNotIn('----:com.apple.iTunes:' + name.upper(), raw_metadata)
@skipUnlessTestfile
def test_delete_freeform_tags(self):
metadata = Metadata()
metadata['foo'] = 'bar'
original_metadata = save_and_load_metadata(self.filename, metadata)
self.assertEqual('bar', original_metadata['foo'])
del metadata['foo']
new_metadata = save_and_load_metadata(self.filename, metadata)
self.assertNotIn('foo', new_metadata)
@skipUnlessTestfile
def test_invalid_track_and_discnumber(self):
metadata = Metadata({
'discnumber': 'notanumber',
'tracknumber': 'notanumber',
})
loaded_metadata = save_and_load_metadata(self.filename, metadata)
self.assertNotIn('discnumber', loaded_metadata)
self.assertNotIn('tracknumber', loaded_metadata)
@skipUnlessTestfile
def test_invalid_total_tracks_and_discs(self):
metadata = Metadata({
'discnumber': '1',
'totaldiscs': 'notanumber',
'tracknumber': '2',
'totaltracks': 'notanumber',
})
loaded_metadata = save_and_load_metadata(self.filename, metadata)
self.assertEqual(metadata['discnumber'], loaded_metadata['discnumber'])
self.assertEqual('0', loaded_metadata['totaldiscs'])
self.assertEqual(metadata['tracknumber'], loaded_metadata['tracknumber'])
self.assertEqual('0', loaded_metadata['totaltracks'])
@skipUnlessTestfile
def test_invalid_int_tag(self):
for tag in ('bpm', 'movementnumber', 'movementtotal', 'showmovement'):
metadata = Metadata({tag: 'notanumber'})
loaded_metadata = save_and_load_metadata(self.filename, metadata)
self.assertNotIn(tag, loaded_metadata)
class M4ATest(CommonMP4Tests.MP4TestCase):
testfile = 'test.m4a'
supports_ratings = False
expected_info = {
'length': 106,
'~channels': '2',
'~sample_rate': '44100',
'~bitrate': '14.376',
'~bits_per_sample': '16',
'~filesize': '2559',
}
unexpected_info = ['~video']
@unittest.skipUnless(mutagen.version >= (1, 43, 0), "mutagen >= 1.43.0 required")
def test_hdvd_tag_considered_video(self):
tags = mutagen.mp4.MP4Tags()
tags['hdvd'] = [1]
save_raw(self.filename, tags)
metadata = load_metadata(self.filename)
self.assertEqual('1', metadata["~video"])
class M4VTest(CommonMP4Tests.MP4TestCase):
testfile = 'test.m4v'
supports_ratings = False
expected_info = {
'length': 106,
'~channels': '2',
'~sample_rate': '44100',
'~bitrate': '108.043',
'~bits_per_sample': '16',
'~video': '1',
'~filesize': '4065',
}
class Mp4CoverArtTest(CommonCoverArtTests.CoverArtTestCase):
testfile = 'test.m4a'
| 7,234
|
Python
|
.py
| 155
| 37.122581
| 114
| 0.620494
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,901
|
coverart.py
|
metabrainz_picard/test/formats/coverart.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2019-2021 Philipp Wolfer
# Copyright (C) 2020-2021 Laurent Monin
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import os.path
from picard import config
from picard.coverart.image import (
CoverArtImage,
TagCoverArtImage,
)
import picard.formats
from picard.metadata import Metadata
from .common import (
CommonTests,
load_metadata,
save_and_load_metadata,
skipUnlessTestfile,
)
def file_save_image(filename, image):
f = picard.formats.open_(filename)
metadata = Metadata(images=[image])
f._save(filename, metadata)
def load_coverart_file(filename):
with open(os.path.join('test', 'data', filename), 'rb') as f:
return f.read()
class DummyUnsupportedCoverArt(CoverArtImage):
def __init__(self, data=b'', mimetype='image/unknown'):
super().__init__()
self.mimetype = mimetype
self.width = 100
self.height = 100
self.extension = '.cvr'
self.set_tags_data(data)
def set_tags_data(self, data):
self._data = data
self.datalength = len(data)
@property
def data(self):
return self._data
# prevent unittest to run tests in those classes
class CommonCoverArtTests:
class CoverArtTestCase(CommonTests.BaseFileTestCase):
supports_types = True
def setUp(self):
super().setUp()
self.set_config_values({
'clear_existing_tags': False,
'preserve_images': False,
})
self.jpegdata = load_coverart_file('mb.jpg')
self.pngdata = load_coverart_file('mb.png')
@skipUnlessTestfile
def test_cover_art(self):
source_types = ["front", "booklet"]
# Use reasonable large data > 64kb.
# This checks a mutagen error with ASF files.
payload = b"a" * 1024 * 128
tests = [
CoverArtImage(data=self.jpegdata + payload, types=source_types),
CoverArtImage(data=self.pngdata + payload, types=source_types),
]
for test in tests:
file_save_image(self.filename, test)
loaded_metadata = load_metadata(self.filename)
image = loaded_metadata.images[0]
self.assertEqual(test.mimetype, image.mimetype)
self.assertEqual(test, image)
def test_cover_art_with_types(self):
expected = set('abcdefg'[:]) if self.supports_types else set('a')
loaded_metadata = save_and_load_metadata(self.filename, self._cover_metadata())
found = {chr(img.data[-1]) for img in loaded_metadata.images}
self.assertEqual(expected, found)
@skipUnlessTestfile
def test_cover_art_types_only_one_front(self):
config.setting['embed_only_one_front_image'] = True
loaded_metadata = save_and_load_metadata(self.filename, self._cover_metadata())
self.assertEqual(1, len(loaded_metadata.images))
self.assertEqual(ord('a'), loaded_metadata.images[0].data[-1])
@skipUnlessTestfile
def test_unsupported_image_format(self):
metadata = Metadata()
# Save an image with unsupported mimetype
metadata.images.append(DummyUnsupportedCoverArt(b'unsupported', 'image/unknown'))
# Save an image with supported mimetype, but invalid data
metadata.images.append(DummyUnsupportedCoverArt(b'unsupported', 'image/png'))
loaded_metadata = save_and_load_metadata(self.filename, metadata)
self.assertEqual(0, len(loaded_metadata.images))
@skipUnlessTestfile
def test_cover_art_clear_tags(self):
image = CoverArtImage(data=self.pngdata, types=['front'])
file_save_image(self.filename, image)
metadata = load_metadata(self.filename)
self.assertEqual(image, metadata.images[0])
config.setting['clear_existing_tags'] = True
config.setting['preserve_images'] = True
metadata = save_and_load_metadata(self.filename, Metadata())
self.assertEqual(image, metadata.images[0])
config.setting['preserve_images'] = False
metadata = save_and_load_metadata(self.filename, Metadata())
self.assertEqual(0, len(metadata.images))
@skipUnlessTestfile
def test_cover_art_clear_tags_preserve_images_no_existing_images(self):
config.setting['clear_existing_tags'] = True
config.setting['preserve_images'] = True
image = CoverArtImage(data=self.pngdata, types=['front'])
file_save_image(self.filename, image)
metadata = load_metadata(self.filename)
self.assertEqual(image, metadata.images[0])
def _cover_metadata(self):
imgdata = self.jpegdata
metadata = Metadata()
metadata.images.append(
TagCoverArtImage(
file='a',
tag='a',
data=imgdata + b'a',
support_types=True,
types=['booklet', 'front'],
)
)
metadata.images.append(
TagCoverArtImage(
file='b',
tag='b',
data=imgdata + b'b',
support_types=True,
types=['back'],
)
)
metadata.images.append(
TagCoverArtImage(
file='c',
tag='c',
data=imgdata + b'c',
support_types=True,
types=['front'],
)
)
metadata.images.append(
TagCoverArtImage(
file='d',
tag='d',
data=imgdata + b'd',
)
)
metadata.images.append(
TagCoverArtImage(
file='e',
tag='e',
data=imgdata + b'e',
is_front=False
)
)
metadata.images.append(
TagCoverArtImage(
file='f',
tag='f',
data=imgdata + b'f',
types=['front']
)
)
metadata.images.append(
TagCoverArtImage(
file='g',
tag='g',
data=imgdata + b'g',
types=['back'],
is_front=True
)
)
return metadata
| 7,487
|
Python
|
.py
| 187
| 28.363636
| 93
| 0.569406
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,902
|
test_mutagenext.py
|
metabrainz_picard/test/formats/test_mutagenext.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2019 Philipp Wolfer
# Copyright (C) 2020-2021 Laurent Monin
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from test.picardtestcase import PicardTestCase
from picard.formats import mutagenext
class MutagenExtTest(PicardTestCase):
def test_delall_ci(self):
tags = {
'TAGNAME:ABC': 'a',
'tagname:abc': 'a',
'TagName:Abc': 'a',
'OtherTag': 'a'
}
mutagenext.delall_ci(tags, 'tagname:Abc')
self.assertEqual({'OtherTag': 'a'}, tags)
| 1,270
|
Python
|
.py
| 32
| 35.875
| 80
| 0.716721
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,903
|
test_id3.py
|
metabrainz_picard/test/formats/test_id3.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2019 Zenara Daley
# Copyright (C) 2019-2021 Laurent Monin
# Copyright (C) 2019-2021 Philipp Wolfer
# Copyright (C) 2020 raingloom
# Copyright (C) 2021 Sophist-UK
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import os.path
import mutagen
from test.picardtestcase import PicardTestCase
from picard import config
from picard.file import File
from picard.formats import (
id3,
open_,
)
from picard.metadata import Metadata
from .common import (
CommonTests,
load_metadata,
load_raw,
save_and_load_metadata,
save_metadata,
save_raw,
skipUnlessTestfile,
)
from .coverart import CommonCoverArtTests
# prevent unittest to run tests in those classes
class CommonId3Tests:
class Id3TestCase(CommonTests.TagFormatsTestCase):
def setup_tags(self):
# Note: in ID3v23, the original date can only be stored as a year.
super().setup_tags()
self.set_tags({
'originaldate': '1980'
})
self.unsupported_tags['r128_album_gain'] = '-2857'
self.unsupported_tags['r128_track_gain'] = '-2857'
@skipUnlessTestfile
def test_id3_freeform_delete(self):
metadata = Metadata(self.tags)
metadata['Foo'] = 'Foo'
original_metadata = save_and_load_metadata(self.filename, metadata)
del metadata['Foo']
new_metadata = save_and_load_metadata(self.filename, metadata)
self.assertIn('Foo', original_metadata)
self.assertNotIn('Foo', new_metadata)
@skipUnlessTestfile
def test_id3_ufid_delete(self):
metadata = Metadata(self.tags)
metadata['musicbrainz_recordingid'] = "Foo"
original_metadata = save_and_load_metadata(self.filename, metadata)
del metadata['musicbrainz_recordingid']
new_metadata = save_and_load_metadata(self.filename, metadata)
self.assertIn('musicbrainz_recordingid', original_metadata)
self.assertNotIn('musicbrainz_recordingid', new_metadata)
@skipUnlessTestfile
def test_id3_multiple_freeform_delete(self):
metadata = Metadata(self.tags)
metadata['Foo'] = 'Foo'
metadata['Bar'] = 'Foo'
metadata['FooBar'] = 'Foo'
original_metadata = save_and_load_metadata(self.filename, metadata)
del metadata['Foo']
del metadata['Bar']
new_metadata = save_and_load_metadata(self.filename, metadata)
self.assertIn('Foo', original_metadata)
self.assertIn('Bar', original_metadata)
self.assertIn('FooBar', original_metadata)
self.assertNotIn('Foo', new_metadata)
self.assertNotIn('Bar', new_metadata)
self.assertIn('FooBar', new_metadata)
@skipUnlessTestfile
def test_id3_rename_freetext_delete(self):
tags = mutagen.id3.ID3Tags()
tags.add(mutagen.id3.TXXX(desc='Work', text='foo'))
save_raw(self.filename, tags)
raw_metadata = load_raw(self.filename)
self.assertIn('TXXX:Work', raw_metadata)
metadata = Metadata()
metadata.delete('work')
new_metadata = save_and_load_metadata(self.filename, metadata)
self.assertNotIn('work', new_metadata)
raw_metadata = load_raw(self.filename)
self.assertNotIn('TXXX:Work', raw_metadata)
self.assertNotIn('TXXX:WORK', raw_metadata)
@skipUnlessTestfile
def test_id3_freetext_ci_delete(self):
# No matter which of the names below gets deleted it always
# should remove all of them
tag_name_variants = [
'replaygain_album_gain',
'REPLAYGAIN_ALBUM_GAIN',
'Replaygain_Album_Gain',
]
for tag_in_test in tag_name_variants:
tags = mutagen.id3.ID3Tags()
for tag in tag_name_variants:
tags.add(mutagen.id3.TXXX(desc=tag, text='foo'))
save_raw(self.filename, tags)
raw_metadata = load_raw(self.filename)
for tag in tag_name_variants:
self.assertIn('TXXX:' + tag, raw_metadata)
metadata = Metadata()
metadata.delete(tag_in_test)
save_metadata(self.filename, metadata)
raw_metadata = load_raw(self.filename)
for tag in tag_name_variants:
self.assertNotIn('TXXX:' + tag, raw_metadata)
@skipUnlessTestfile
def test_id3_metadata_tofn(self):
metadata = Metadata(self.tags)
metadata = save_and_load_metadata(self.filename, metadata)
self.assertIn('originalfilename', metadata)
self.assertEqual(metadata['originalfilename'], "Foo")
@skipUnlessTestfile
def test_performer_duplication(self):
config.setting['write_id3v23'] = True
metadata = Metadata({
'album': 'Foo',
'artist': 'Foo',
'performer:piano': 'Foo',
'title': 'Foo',
})
original_metadata = save_and_load_metadata(self.filename, metadata)
new_metadata = save_and_load_metadata(self.filename, original_metadata)
self.assertEqual(len(new_metadata['performer:piano']), len(original_metadata['performer:piano']))
@skipUnlessTestfile
def test_performer_no_role_tmcl(self):
metadata = Metadata({
'performer': 'Performer',
'performer:piano': 'Performer Piano',
})
save_metadata(self.filename, metadata)
raw_metadata = load_raw(self.filename)
self.assertIn(['piano', 'Performer Piano'], raw_metadata['TMCL'].people)
self.assertIn(['performer', 'Performer'], raw_metadata['TMCL'].people)
self.assertNotIn('TXXX:performer', raw_metadata)
@skipUnlessTestfile
def test_performer_no_role_tipl(self):
config.setting['write_id3v23'] = True
metadata = Metadata({
'performer': 'Performer',
'performer:piano': 'Performer Piano',
})
save_metadata(self.filename, metadata)
raw_metadata = load_raw(self.filename)
self.assertIn(['piano', 'Performer Piano'], raw_metadata['TIPL'].people)
self.assertIn(['performer', 'Performer'], raw_metadata['TIPL'].people)
self.assertNotIn('TXXX:performer', raw_metadata)
@skipUnlessTestfile
def test_comment_delete(self):
metadata = Metadata(self.tags)
metadata['comment:bar'] = 'Foo'
metadata['comment:XXX:withlang'] = 'Foo'
original_metadata = save_and_load_metadata(self.filename, metadata)
del metadata['comment:bar']
del metadata['comment:XXX:withlang']
new_metadata = save_and_load_metadata(self.filename, metadata)
self.assertIn('comment:foo', original_metadata)
self.assertIn('comment:bar', original_metadata)
self.assertIn('comment:XXX:withlang', original_metadata)
self.assertIn('comment:foo', new_metadata)
self.assertNotIn('comment:bar', new_metadata)
self.assertNotIn('comment:XXX:withlang', new_metadata)
@skipUnlessTestfile
def test_id3v23_simple_tags(self):
config.setting['write_id3v23'] = True
metadata = Metadata(self.tags)
loaded_metadata = save_and_load_metadata(self.filename, metadata)
for (key, value) in self.tags.items():
self.assertEqual(loaded_metadata[key], value, '%s: %r != %r' % (key, loaded_metadata[key], value))
@property
def itunes_grouping_metadata(self):
metadata = Metadata()
metadata['grouping'] = 'The Grouping'
metadata['work'] = 'The Work'
return metadata
@skipUnlessTestfile
def test_standard_grouping(self):
metadata = self.itunes_grouping_metadata
config.setting['itunes_compatible_grouping'] = False
loaded_metadata = save_and_load_metadata(self.filename, metadata)
self.assertEqual(loaded_metadata['grouping'], metadata['grouping'])
self.assertEqual(loaded_metadata['work'], metadata['work'])
@skipUnlessTestfile
def test_itunes_compatible_grouping(self):
metadata = self.itunes_grouping_metadata
config.setting['itunes_compatible_grouping'] = True
loaded_metadata = save_and_load_metadata(self.filename, metadata)
self.assertEqual(loaded_metadata['grouping'], metadata['grouping'])
self.assertEqual(loaded_metadata['work'], metadata['work'])
@skipUnlessTestfile
def test_always_read_grp1(self):
metadata = self.itunes_grouping_metadata
config.setting['itunes_compatible_grouping'] = True
save_metadata(self.filename, metadata)
config.setting['itunes_compatible_grouping'] = False
loaded_metadata = load_metadata(self.filename)
self.assertIn(metadata['grouping'], loaded_metadata['grouping'])
self.assertIn(metadata['work'], loaded_metadata['grouping'])
self.assertEqual(loaded_metadata['work'], '')
@skipUnlessTestfile
def test_always_read_txxx_work(self):
metadata = self.itunes_grouping_metadata
config.setting['itunes_compatible_grouping'] = False
save_metadata(self.filename, metadata)
config.setting['itunes_compatible_grouping'] = True
loaded_metadata = load_metadata(self.filename)
self.assertIn(metadata['grouping'], loaded_metadata['work'])
self.assertIn(metadata['work'], loaded_metadata['work'])
self.assertEqual(loaded_metadata['grouping'], '')
@skipUnlessTestfile
def test_save_itunnorm_tag(self):
config.setting['clear_existing_tags'] = True
iTunNORM = '00001E86 00001E86 0000A2A3 0000A2A3 000006A6 000006A6 000078FA 000078FA 00000211 00000211'
metadata = Metadata()
metadata['comment:iTunNORM'] = iTunNORM
new_metadata = save_and_load_metadata(self.filename, metadata)
self.assertEqual(new_metadata['comment:iTunNORM'], iTunNORM)
@skipUnlessTestfile
def test_delete_itun_tags(self):
metadata = Metadata()
metadata['comment:iTunNORM'] = '00001E86 00001E86 0000A2A3 0000A2A3 000006A6 000006A6 000078FA 000078FA 00000211 00000211'
metadata['comment:iTunPGAP'] = '1'
new_metadata = save_and_load_metadata(self.filename, metadata)
self.assertIn('comment:iTunNORM', new_metadata)
self.assertIn('comment:iTunPGAP', new_metadata)
del metadata['comment:iTunNORM']
del metadata['comment:iTunPGAP']
new_metadata = save_and_load_metadata(self.filename, metadata)
self.assertNotIn('comment:iTunNORM', new_metadata)
self.assertNotIn('comment:iTunPGAP', new_metadata)
def test_rename_txxx_tags(self):
file_path = os.path.join('test', 'data', 'test-id3-rename-tags.mp3')
filename = self.copy_file_tmp(file_path, '.mp3')
raw_metadata = load_raw(filename)
self.assertIn('TXXX:Artists', raw_metadata)
self.assertNotIn('TXXX:ARTISTS', raw_metadata)
self.assertIn('TXXX:Work', raw_metadata)
self.assertNotIn('TXXX:WORK', raw_metadata)
metadata = load_metadata(filename)
self.assertEqual(metadata['artists'], 'Artist1; Artist2')
self.assertNotIn('Artists', metadata)
self.assertEqual(metadata['work'], 'The Work')
self.assertNotIn('Work', metadata)
save_metadata(filename, metadata)
raw_metadata = load_raw(filename)
self.assertNotIn('TXXX:Artists', raw_metadata)
self.assertIn('TXXX:ARTISTS', raw_metadata)
self.assertNotIn('TXXX:Work', raw_metadata)
self.assertIn('TXXX:WORK', raw_metadata)
def test_preserve_unchanged_tags_v23(self):
config.setting['write_id3v23'] = True
self.test_preserve_unchanged_tags()
@skipUnlessTestfile
def test_replaygain_tags_case_insensitive(self):
tags = mutagen.id3.ID3Tags()
tags.add(mutagen.id3.TXXX(desc='replaygain_album_gain', text='-6.48 dB'))
tags.add(mutagen.id3.TXXX(desc='Replaygain_Album_Peak', text='0.978475'))
tags.add(mutagen.id3.TXXX(desc='replaygain_album_range', text='7.84 dB'))
tags.add(mutagen.id3.TXXX(desc='replaygain_track_gain', text='-6.16 dB'))
tags.add(mutagen.id3.TXXX(desc='REPLAYGAIN_track_peak', text='0.976991'))
tags.add(mutagen.id3.TXXX(desc='REPLAYGAIN_TRACK_RANGE', text='8.22 dB'))
tags.add(mutagen.id3.TXXX(desc='replaygain_reference_loudness', text='-18.00 LUFS'))
save_raw(self.filename, tags)
loaded_metadata = load_metadata(self.filename)
for (key, value) in self.replaygain_tags.items():
self.assertEqual(loaded_metadata[key], value, '%s: %r != %r' % (key, loaded_metadata[key], value))
@skipUnlessTestfile
def test_ci_tags_save(self):
tag_name_variants = [
'replaygain_album_gain',
'REPLAYGAIN_ALBUM_GAIN',
'Replaygain_Album_Gain',
]
for tag in tag_name_variants:
metadata = Metadata({tag: 'foo'})
loaded_metadata = save_and_load_metadata(self.filename, metadata)
self.assertEqual('foo', loaded_metadata['replaygain_album_gain'])
@skipUnlessTestfile
def test_ci_tags_preserve_case(self):
# Ensure values are not duplicated on repeated save and are saved
# case preserving.
tags = mutagen.id3.ID3Tags()
tags.add(mutagen.id3.TXXX(desc='Replaygain_Album_Peak', text='0.978475'))
save_raw(self.filename, tags)
loaded_metadata = load_metadata(self.filename)
loaded_metadata['replaygain_album_peak'] = '1.0'
save_metadata(self.filename, loaded_metadata)
raw_metadata = load_raw(self.filename)
self.assertIn('TXXX:Replaygain_Album_Peak', raw_metadata)
self.assertEqual(
raw_metadata['TXXX:Replaygain_Album_Peak'].text[0],
loaded_metadata['replaygain_album_peak'])
self.assertEqual(1, len(raw_metadata['TXXX:Replaygain_Album_Peak'].text))
self.assertNotIn('TXXX:REPLAYGAIN_ALBUM_PEAK', raw_metadata)
@skipUnlessTestfile
def test_lyrics_with_description(self):
metadata = Metadata({'lyrics:foo': 'bar'})
loaded_metadata = save_and_load_metadata(self.filename, metadata)
self.assertEqual(metadata['lyrics:foo'], loaded_metadata['lyrics:foo'])
@skipUnlessTestfile
def test_syncedlyrics_preserve_language_and_description(self):
metadata = Metadata({'syncedlyrics': '[00:00.000]<00:00.000>foo1'})
metadata.add('syncedlyrics:deu:desc', '[00:00.000]<00:00.000>foo2')
metadata.add('syncedlyrics:ita', '[00:00.000]<00:00.000>foo3')
metadata.add('syncedlyrics::desc', '[00:00.000]<00:00.000>foo4')
loaded_metadata = save_and_load_metadata(self.filename, metadata)
self.assertEqual(metadata['syncedlyrics'], loaded_metadata['syncedlyrics:eng'])
self.assertEqual(metadata['syncedlyrics:deu:desc'], loaded_metadata['syncedlyrics:deu:desc'])
self.assertEqual(metadata['syncedlyrics:ita'], loaded_metadata['syncedlyrics:ita'])
self.assertEqual(metadata['syncedlyrics::desc'], loaded_metadata['syncedlyrics:eng:desc'])
@skipUnlessTestfile
def test_syncedlyrics_delete(self):
metadata = Metadata({'syncedlyrics': '[00:00.000]<00:00.000>foo1'})
metadata.delete('syncedlyrics:eng')
save_metadata(self.filename, metadata)
raw_metadata = load_raw(self.filename)
self.assertNotIn('syncedlyrics:eng', raw_metadata)
@skipUnlessTestfile
def test_invalid_track_and_discnumber(self):
metadata = Metadata({
'discnumber': 'notanumber',
'tracknumber': 'notanumber',
})
loaded_metadata = save_and_load_metadata(self.filename, metadata)
self.assertNotIn('discnumber', loaded_metadata)
self.assertNotIn('tracknumber', loaded_metadata)
@skipUnlessTestfile
def test_save_explicit_id3_frames(self):
metadata = Metadata({
'~id3:TXXX:foo': 'bar',
'~id3:TOWN': 'owner'
})
save_metadata(self.filename, metadata)
raw_metadata = load_raw(self.filename)
self.assertIn('TXXX:foo', raw_metadata)
self.assertEqual('bar', raw_metadata['TXXX:foo'])
self.assertEqual('owner', raw_metadata['TOWN'])
@skipUnlessTestfile
def test_delete_explicit_id3_frames(self):
tags = mutagen.id3.ID3Tags()
tags.add(mutagen.id3.TOWN(text='bar'))
tags.add(mutagen.id3.TXXX(desc='foo', text='bar1'))
tags.add(mutagen.id3.TXXX(desc='foo', text='bar2'))
save_raw(self.filename, tags)
raw_metadata = load_raw(self.filename)
self.assertIn('TOWN', raw_metadata)
self.assertIn('TXXX:foo', raw_metadata)
metadata = Metadata()
metadata.delete('~id3:TOWN')
metadata.delete('~id3:TXXX:foo')
metadata.delete('~id3:NOTAFRAME')
save_metadata(self.filename, metadata)
raw_metadata = load_raw(self.filename)
self.assertNotIn('TOWN', raw_metadata)
self.assertNotIn('TXXX:foo', raw_metadata)
@skipUnlessTestfile
def test_delete_tipl(self):
tags = mutagen.id3.ID3Tags()
tags.add(mutagen.id3.TIPL(people=[
['mix', 'mixer1'],
['mix', 'mixer2'],
['producer', 'producer1'],
]))
save_raw(self.filename, tags)
metadata = Metadata()
metadata.delete('mixer')
save_metadata(self.filename, metadata)
raw_metadata = load_raw(self.filename)
people = raw_metadata['TIPL'].people
self.assertIn(['producer', 'producer1'], people)
self.assertNotIn(['mix', 'mixer1'], people)
self.assertNotIn(['mix', 'mixer2'], people)
self.assertEqual(1, len(people))
@skipUnlessTestfile
def test_load_conflicting_txxx_tags(self):
tags = mutagen.id3.ID3Tags()
tags.add(mutagen.id3.TXXX(desc='title', text='foo'))
save_raw(self.filename, tags)
loaded_metadata = load_metadata(self.filename)
self.assertEqual('foo', loaded_metadata['~id3:TXXX:title'])
@skipUnlessTestfile
def test_license_single_url(self):
metadata = Metadata({
'license': 'http://example.com'
})
loaded_metadata = save_and_load_metadata(self.filename, metadata)
self.assertEqual(metadata['license'], loaded_metadata['license'])
raw_metadata = load_raw(self.filename)
self.assertEqual(metadata['license'], raw_metadata['WCOP'])
@skipUnlessTestfile
def test_license_single_non_url(self):
metadata = Metadata({
'license': 'foo'
})
loaded_metadata = save_and_load_metadata(self.filename, metadata)
self.assertEqual(metadata['license'], loaded_metadata['license'])
raw_metadata = load_raw(self.filename)
self.assertEqual(metadata['license'], raw_metadata['TXXX:LICENSE'])
@skipUnlessTestfile
def test_license_multi_url(self):
metadata = Metadata({
'license': [
'http://example.com/1',
'http://example.com/2',
]
})
loaded_metadata = save_and_load_metadata(self.filename, metadata)
self.assertEqual(metadata['license'], loaded_metadata['license'])
raw_metadata = load_raw(self.filename)
self.assertEqual(
set(metadata.getall('license')),
set(raw_metadata.get('TXXX:LICENSE').text))
@skipUnlessTestfile
def test_license_wcop_and_txxx(self):
tags = mutagen.id3.ID3Tags()
tags.add(mutagen.id3.WCOP(url='http://example.com/1'))
tags.add(mutagen.id3.TXXX(desc='license', text='http://example.com/2'))
save_raw(self.filename, tags)
loaded_metadata = load_metadata(self.filename)
loaded_licenses = loaded_metadata.getall('license')
self.assertEqual(2, len(loaded_licenses))
self.assertIn('http://example.com/1', loaded_licenses)
self.assertIn('http://example.com/2', loaded_licenses)
@skipUnlessTestfile
def test_license_upgrade_wcop(self):
tags = mutagen.id3.ID3Tags()
tags.add(mutagen.id3.WCOP(url='http://example.com/1'))
save_raw(self.filename, tags)
metadata = load_metadata(self.filename)
self.assertEqual('http://example.com/1', metadata['license'])
metadata.add('license', 'http://example.com/2')
save_metadata(self.filename, metadata)
raw_metadata = load_raw(self.filename)
self.assertNotIn('WCOP', raw_metadata)
loaded_licenses = [url for url in raw_metadata['TXXX:LICENSE']]
self.assertEqual(['http://example.com/1', 'http://example.com/2'], loaded_licenses)
@skipUnlessTestfile
def test_license_downgrade_wcop(self):
tags = mutagen.id3.ID3Tags()
licenses = ['http://example.com/1', 'http://example.com/2']
tags.add(mutagen.id3.TXXX(desc='LICENSE', text=licenses))
save_raw(self.filename, tags)
raw_metadata = load_raw(self.filename)
metadata = load_metadata(self.filename)
self.assertEqual(licenses, metadata.getall('license'))
metadata['license'] = 'http://example.com/1'
save_metadata(self.filename, metadata)
raw_metadata = load_raw(self.filename)
self.assertEqual('http://example.com/1', raw_metadata['WCOP'])
self.assertNotIn('TXXX:LICENSE', raw_metadata)
@skipUnlessTestfile
def test_license_delete(self):
tags = mutagen.id3.ID3Tags()
tags.add(mutagen.id3.WCOP(url='http://example.com/1'))
tags.add(mutagen.id3.TXXX(desc='LICENSE', text='http://example.com/2'))
save_raw(self.filename, tags)
metadata = load_metadata(self.filename)
del metadata['license']
loaded_metadata = save_and_load_metadata(self.filename, metadata)
self.assertNotIn('license', loaded_metadata)
@skipUnlessTestfile
def test_woar_not_duplicated(self):
metadata = Metadata({
'website': 'http://example.com/1'
})
loaded_metadata = save_and_load_metadata(self.filename, metadata)
self.assertEqual(metadata['website'], loaded_metadata['website'])
metadata['website'] = 'http://example.com/2'
loaded_metadata = save_and_load_metadata(self.filename, metadata)
self.assertEqual(metadata['website'], loaded_metadata['website'])
@skipUnlessTestfile
def test_woar_delete(self):
metadata = Metadata({
'website': 'http://example.com/1'
})
loaded_metadata = save_and_load_metadata(self.filename, metadata)
self.assertEqual(metadata['website'], loaded_metadata['website'])
del metadata['website']
loaded_metadata = save_and_load_metadata(self.filename, metadata)
self.assertNotIn('website', loaded_metadata)
@skipUnlessTestfile
def test_rating_email_non_latin1(self):
for rating in range(6):
config.setting['rating_user_email'] = 'foo€'
rating = '3'
metadata = Metadata({'~rating': rating})
loaded_metadata = save_and_load_metadata(self.filename, metadata)
self.assertEqual(loaded_metadata['~rating'], rating, '~rating: %r != %r' % (loaded_metadata['~rating'], rating))
@skipUnlessTestfile
def test_unchanged_metadata(self):
self.set_config_values({
'compare_ignore_tags': [],
'write_id3v23': True,
})
file = open_(self.filename)
file.orig_metadata = Metadata({
'album': 'somealbum',
'title': 'sometitle',
'date': '2021',
'originaldate': '2021',
'artists': 'foo/bar',
})
file.metadata = Metadata({
'album': 'somealbum',
'title': 'sometitle',
'date': '2021-12',
'originaldate': '2021-12-04',
'artists': ['foo', 'bar'],
})
file.state = File.NORMAL
file.update(signal=False)
self.assertEqual(file.similarity, 1.0)
self.assertEqual(file.state, File.NORMAL)
@skipUnlessTestfile
def test_releasedate_v23(self):
config.setting['write_id3v23'] = True
metadata = Metadata({
'releasedate': '2023-04-28',
})
save_metadata(self.filename, metadata)
raw_metadata = load_raw(self.filename)
self.assertEqual(metadata['releasedate'], raw_metadata['TXXX:RELEASEDATE'])
@skipUnlessTestfile
def test_releasedate_v24(self):
config.setting['write_id3v23'] = False
metadata = Metadata({
'releasedate': '2023-04-28',
})
save_metadata(self.filename, metadata)
raw_metadata = load_raw(self.filename)
self.assertEqual(metadata['releasedate'], raw_metadata['TDRL'])
class MP3Test(CommonId3Tests.Id3TestCase):
testfile = 'test.mp3'
supports_ratings = True
expected_info = {
'length': 156,
'~channels': '2',
'~sample_rate': '44100',
'~filesize': '2760',
}
unexpected_info = ['~video']
@skipUnlessTestfile
def test_remove_apev2(self):
# Add APEv2 tags
apev2_tags = mutagen.apev2.APEv2()
apev2_tags['Title'] = 'foo'
apev2_tags.save(self.filename)
self.assertEqual('foo', mutagen.apev2.APEv2(self.filename)['Title'])
config.setting['remove_ape_from_mp3'] = False
save_metadata(self.filename, Metadata())
self.assertEqual('foo', mutagen.apev2.APEv2(self.filename)['Title'])
config.setting['remove_ape_from_mp3'] = True
save_metadata(self.filename, Metadata())
self.assertRaises(mutagen.apev2.APENoHeaderError, mutagen.apev2.APEv2, self.filename)
@skipUnlessTestfile
def test_remove_apev2_no_existing_tags(self):
self.assertRaises(mutagen.apev2.APENoHeaderError, mutagen.apev2.APEv2, self.filename)
config.setting['remove_ape_from_mp3'] = True
save_metadata(self.filename, Metadata())
self.assertRaises(mutagen.apev2.APENoHeaderError, mutagen.apev2.APEv2, self.filename)
class TTATest(CommonId3Tests.Id3TestCase):
testfile = 'test.tta'
supports_ratings = True
expected_info = {
'length': 82,
'~sample_rate': '44100',
'~filesize': '2300',
}
unexpected_info = ['~video']
class DSFTest(CommonId3Tests.Id3TestCase):
testfile = 'test.dsf'
supports_ratings = True
expected_info = {
'length': 10,
'~channels': '2',
'~sample_rate': '5644800',
'~bitrate': '11289.6',
'~bits_per_sample': '1',
'~filesize': '112988',
}
unexpected_info = ['~video']
if id3.DSDIFFFile:
class DSDIFFTest(CommonId3Tests.Id3TestCase):
testfile = 'test-dsd.dff'
supports_ratings = True
expected_info = {
'length': 10,
'~channels': '2',
'~sample_rate': '5644800',
'~bitrate': '11289.6',
'~bits_per_sample': '1',
'~filesize': '14242',
}
unexpected_info = ['~video']
class DSDIFFDSTTest(CommonId3Tests.Id3TestCase):
testfile = 'test-dst.dff'
supports_ratings = True
expected_info = {
'length': 0,
'~channels': '2',
'~sample_rate': '5644800',
'~bits_per_sample': '1',
'~filesize': '2214',
}
unexpected_info = ['~video']
class AIFFTest(CommonId3Tests.Id3TestCase):
testfile = 'test.aiff'
supports_ratings = False
expected_info = {
'length': 82,
'~channels': '2',
'~sample_rate': '44100',
'~bitrate': '1411.2',
'~filesize': '14662',
}
unexpected_info = ['~video']
class Id3UtilTest(PicardTestCase):
def test_id3encoding_from_config(self):
self.assertEqual(id3.Id3Encoding.LATIN1, id3.Id3Encoding.from_config('iso-8859-1'))
self.assertEqual(id3.Id3Encoding.UTF16, id3.Id3Encoding.from_config('utf-16'))
self.assertEqual(id3.Id3Encoding.UTF8, id3.Id3Encoding.from_config('utf-8'))
def test_id3text(self):
teststring = '日本語testÖäß'
self.assertEqual(id3.id3text(teststring, id3.Id3Encoding.LATIN1), '???testÖäß')
self.assertEqual(id3.id3text(teststring, id3.Id3Encoding.UTF16), teststring)
self.assertEqual(id3.id3text(teststring, id3.Id3Encoding.UTF16BE), teststring)
self.assertEqual(id3.id3text(teststring, id3.Id3Encoding.UTF8), teststring)
class Mp3CoverArtTest(CommonCoverArtTests.CoverArtTestCase):
testfile = 'test.mp3'
class ID3FileTest(PicardTestCase):
def setUp(self):
super().setUp()
self.file = id3.ID3File('somepath/somefile.mp3')
config.setting['write_id3v23'] = False
config.setting['id3v23_join_with'] = ' / '
self.file.metadata['artist'] = ['foo', 'bar']
self.file.metadata['originaldate'] = '2020-04-01'
self.file.metadata['date'] = '2021-04-01'
def test_format_specific_metadata_v24(self):
metadata = self.file.metadata
for name, values in metadata.rawitems():
self.assertEqual(values, self.file.format_specific_metadata(metadata, name))
def test_format_specific_metadata_v23(self):
config.setting['write_id3v23'] = True
metadata = self.file.metadata
self.assertEqual(['foo / bar'], self.file.format_specific_metadata(metadata, 'artist'))
self.assertEqual(['2020'], self.file.format_specific_metadata(metadata, 'originaldate'))
self.assertEqual(['2021-04-01'], self.file.format_specific_metadata(metadata, 'date'))
def test_format_specific_metadata_v23_incomplete_date(self):
config.setting['write_id3v23'] = True
metadata = self.file.metadata
metadata['date'] = '2021-04'
self.assertEqual(['2021'], self.file.format_specific_metadata(metadata, 'date'))
def test_format_specific_metadata_override_settings(self):
settings = {
'write_id3v23': True,
'id3v23_join_with': '; ',
}
metadata = self.file.metadata
self.assertEqual(['foo; bar'], self.file.format_specific_metadata(metadata, 'artist', settings))
def test_syncedlyrics_converting_to_lrc(self):
sylt = (
[("Test", 0), ("normal\n", 500), ("behaviour", 1000)],
[("Test", 0), ("syl", 10), ("la", 20), ("bles", 30)],
[("Test newline\nin the middle", 0), ("of the text", 1000)],
[("Test empty lyrics at the end\n", 0), ("", 1000)],
[("Test timestamp estimation", 0), ("in the\nlast phrase", 1000)])
correct_lrc = (
"[00:00.000]<00:00.000>Test<00:00.500>normal\n[00:01.000]<00:01.000>behaviour",
"[00:00.000]<00:00.000>Test<00:00.010>syl<00:00.020>la<00:00.030>bles",
"[00:00.000]<00:00.000>Test newline\n[00:00.480]in the middle<00:01.000>of the text",
"[00:00.000]<00:00.000>Test empty lyrics at the end\n[00:01.000]<00:01.000>",
"[00:00.000]<00:00.000>Test timestamp estimation<00:01.000>in the\n[00:01.352]last phrase")
for sylt, correct_lrc in zip(sylt, correct_lrc):
lrc = self.file._parse_sylt_text(sylt, 2)
self.assertEqual(lrc, correct_lrc)
def test_syncedlyrics_converting_to_sylt(self):
lrc = (
"[00:00.000]<00:00.000>Test<00:00.500>normal\n[00:00.750]<00:01.000>behaviour",
"[00:00.000]Test lyrics with\n[01:00.000]only line time stamps",
"<00:00.000>Test lyrics with<01:00.000>only syllable time stamps",
"[00:00.000]<00:00.000>Test extra\n<00:00.750>[00:00.750]<00:00.750>timestamp<00:01.500>",
"Test invalid[00:00.000]input\nTest invalid[00:01.000]input",
"Test lyrics with no timestamps")
correct_sylt = (
[("Test", 0), ("normal\n", 500), ("behaviour", 1000)],
[("Test lyrics with\n", 0), ("only line time stamps", 60 * 1000)],
[("Test lyrics with", 0), ("only syllable time stamps", 60 * 1000)],
[("Test extra\n", 0), ("timestamp", 750), ("", 1500)],
[("input\nTest invalid", 0), ("input", 1000)],
[])
for lrc, correct_sylt in zip(lrc, correct_sylt):
sylt = self.file._parse_lrc_text(lrc)
self.assertEqual(sylt, correct_sylt)
| 35,175
|
Python
|
.py
| 713
| 37.935484
| 134
| 0.60743
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,904
|
__init__.py
|
metabrainz_picard/test/formats/__init__.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2019 Philipp Wolfer
# Copyright (C) 2020-2021 Laurent Monin
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
| 860
|
Python
|
.py
| 20
| 42
| 80
| 0.77381
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,905
|
test_util.py
|
metabrainz_picard/test/formats/test_util.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2024 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import os.path
from test.picardtestcase import PicardTestCase
from picard.formats import util
from picard.formats.id3 import MP3File
class FormatsOpenTest(PicardTestCase):
def setUp(self):
super().setUp()
self.set_config_values({'enabled_plugins': []})
def test_open(self):
file_path = os.path.join('test', 'data', 'test.mp3')
filename = self.copy_file_tmp(file_path, '.mp3')
filetype = util.open_(filename)
self.assertIsInstance(filetype, MP3File)
def test_open_no_extension(self):
file_path = os.path.join('test', 'data', 'test.mp3')
filename = self.copy_file_tmp(file_path, '')
filetype = util.open_(filename)
self.assertIsInstance(filetype, MP3File)
def test_open_unknown_extension(self):
file_path = os.path.join('test', 'data', 'test.mp3')
filename = self.copy_file_tmp(file_path, '.fake')
filetype = util.open_(filename)
self.assertIsInstance(filetype, MP3File)
def test_open_unknown_type(self):
file_path = os.path.join('test', 'data', 'mb.png')
filename = self.copy_file_tmp(file_path, '.ogg')
filetype = util.open_(filename)
self.assertIsNone(filetype)
| 2,056
|
Python
|
.py
| 47
| 39.06383
| 80
| 0.705
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,906
|
test_apev2.py
|
metabrainz_picard/test/formats/test_apev2.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2019, 2021 Philipp Wolfer
# Copyright (C) 2020-2021 Laurent Monin
# Copyright (C) 2021 Bob Swift
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import os
from mutagen.apev2 import (
BINARY,
APEValue,
)
from test.picardtestcase import (
PicardTestCase,
create_fake_png,
)
from picard import config
from picard.formats import (
apev2,
open_,
)
from picard.formats.mutagenext.tak import native_tak
from picard.metadata import Metadata
from .common import (
TAGS,
CommonTests,
load_metadata,
load_raw,
save_and_load_metadata,
save_metadata,
save_raw,
skipUnlessTestfile,
)
from .coverart import CommonCoverArtTests
VALID_KEYS = {
' valid Key}',
'{ $ome tag~}',
'xx',
'x' * 255,
}
INVALID_KEYS = {
'invalid\x7fkey',
'invalid\x19key',
'',
'x',
'x' * 256,
'ID3',
'TAG',
'OggS',
'MP+',
}
SUPPORTED_TAGS = set(TAGS) - apev2.UNSUPPORTED_TAGS
class CommonApeTests:
class ApeTestCase(CommonTests.TagFormatsTestCase):
def setup_tags(self):
super().setup_tags()
self.unsupported_tags['r128_album_gain'] = '-2857'
self.unsupported_tags['r128_track_gain'] = '-2857'
def test_supports_tags(self):
supports_tag = self.format.supports_tag
for key in VALID_KEYS | SUPPORTED_TAGS:
self.assertTrue(supports_tag(key), '%r should be supported' % key)
for key in INVALID_KEYS | apev2.UNSUPPORTED_TAGS:
self.assertFalse(supports_tag(key), '%r should be unsupported' % key)
@skipUnlessTestfile
def test_invalid_coverart(self):
metadata = {
'Cover Art (Front)': APEValue(b'filename.png\0NOTPNGDATA', BINARY)
}
save_raw(self.filename, metadata)
loaded_metadata = load_metadata(self.filename)
self.assertEqual(0, len(loaded_metadata.images))
@skipUnlessTestfile
def test_clear_tags_preserve_images_all(self):
imagedata = APEValue(b'filename.png\0' + create_fake_png(b'a'), BINARY)
save_raw(self.filename, {
'Cover Art (Front)': imagedata,
'Cover Art': imagedata,
'Cover Art (foo)': imagedata,
'cover art (bar)': imagedata,
})
config.setting['clear_existing_tags'] = True
config.setting['preserve_images'] = True
metadata = save_and_load_metadata(self.filename, Metadata())
self.assertEqual(4, len(metadata.images))
config.setting['preserve_images'] = False
metadata = save_and_load_metadata(self.filename, Metadata())
self.assertEqual(0, len(metadata.images))
def test_supports_extended_tags(self):
performer_tag = "performer:accordéon clavier « boutons »"
self.assertTrue(self.format.supports_tag(performer_tag))
self.assertTrue(self.format.supports_tag('lyrics:foó'))
self.assertTrue(self.format.supports_tag('comment:foó'))
def test_case_insensitive_reading(self):
self._read_case_insensitive_tag('artist', 'Artist')
self._read_case_insensitive_tag('albumartist', 'Album Artist')
self._read_case_insensitive_tag('performer:', 'Performer')
self._read_case_insensitive_tag('tracknumber', 'Track')
self._read_case_insensitive_tag('discnumber', 'Disc')
@skipUnlessTestfile
def test_ci_tags_preserve_case(self):
# Ensure values are not duplicated on repeated save and are saved
# case preserving.
for name in ('CUStom', 'ARtist'):
tags = {}
tags[name] = 'foo'
save_raw(self.filename, tags)
loaded_metadata = load_metadata(self.filename)
loaded_metadata[name.lower()] = 'bar'
save_metadata(self.filename, loaded_metadata)
raw_metadata = dict(load_raw(self.filename))
self.assertIn(name, raw_metadata)
self.assertEqual(
raw_metadata[name],
loaded_metadata[name.lower()])
self.assertEqual(1, len(raw_metadata[name]))
self.assertNotIn(name.upper(), raw_metadata)
def _read_case_insensitive_tag(self, name, ape_name):
upper_ape_name = ape_name.upper()
metadata = {
upper_ape_name: 'Some value'
}
save_raw(self.filename, metadata)
loaded_metadata = load_metadata(self.filename)
self.assertEqual(metadata[upper_ape_name], loaded_metadata[name])
save_metadata(self.filename, loaded_metadata)
raw_metadata = load_raw(self.filename)
self.assertIn(upper_ape_name, raw_metadata.keys())
self.assertEqual(metadata[upper_ape_name], raw_metadata[ape_name])
class MonkeysAudioTest(CommonApeTests.ApeTestCase):
testfile = 'test.ape'
supports_ratings = False
expected_info = {
'length': 82,
'~channels': '2',
'~sample_rate': '44100',
'~bits_per_sample': '16',
'~filesize': '2432',
}
unexpected_info = ['~video']
class WavPackTest(CommonApeTests.ApeTestCase):
testfile = 'test.wv'
supports_ratings = False
expected_info = {
'length': 82,
'~channels': '2',
'~sample_rate': '44100',
'~filesize': '2478',
}
unexpected_info = ['~video']
def setUp(self):
super().setUp()
config.setting['rename_files'] = True
config.setting['move_files'] = False
config.setting['ascii_filenames'] = False
config.setting['windows_compatibility'] = False
config.setting['windows_long_paths'] = True
config.setting['dont_write_tags'] = True
config.setting['preserve_timestamps'] = False
config.setting['delete_empty_dirs'] = False
config.setting['save_images_to_files'] = False
config.setting['file_renaming_scripts'] = {'test_id': {'script': '%title%'}}
config.setting['selected_file_naming_script_id'] = 'test_id'
def _save_with_wavpack_correction_file(self, source_file_wvc):
# Create dummy WavPack correction file
open(source_file_wvc, 'a').close()
# Open file and rename it
f = open_(self.filename)
f._copy_loaded_metadata(f._load(self.filename))
f.metadata['title'] = 'renamed_' + os.path.basename(self.filename)
self.assertTrue(os.path.isfile(self.filename))
target_file_wv = f._save_and_rename(self.filename, f.metadata)
target_file_wvc = target_file_wv + 'c'
# Register cleanups
self.addCleanup(os.unlink, target_file_wv)
self.addCleanup(os.unlink, target_file_wvc)
return (target_file_wv, target_file_wvc)
@skipUnlessTestfile
def test_save_wavpack_correction_file(self):
source_file_wvc = self.filename + 'c'
(target_file_wv, target_file_wvc) = self._save_with_wavpack_correction_file(source_file_wvc)
# Check both the WavPack file and the correction file got moved
self.assertFalse(os.path.isfile(self.filename))
self.assertFalse(os.path.isfile(source_file_wvc))
self.assertTrue(os.path.isfile(target_file_wv))
self.assertTrue(os.path.isfile(target_file_wvc))
@skipUnlessTestfile
def test_save_wavpack_correction_file_with_move_additional_files(self):
config.setting['move_files'] = True
config.setting['move_files_to'] = self.mktmpdir()
config.setting['move_additional_files'] = True
config.setting['move_additional_files_pattern'] = '*.wvc'
source_file_wvc = self.filename + 'c'
(target_file_wv, target_file_wvc) = self._save_with_wavpack_correction_file(source_file_wvc)
# Check both the WavPack file and the correction file got moved
self.assertFalse(os.path.isfile(self.filename))
self.assertFalse(os.path.isfile(source_file_wvc))
self.assertTrue(os.path.isfile(target_file_wv))
self.assertTrue(os.path.isfile(target_file_wvc))
class MusepackSV7Test(CommonApeTests.ApeTestCase):
testfile = 'test-sv7.mpc'
supports_ratings = False
expected_info = {
'length': 91,
'~channels': '2',
'~sample_rate': '44100',
'~filesize': '1605',
}
unexpected_info = ['~video']
class MusepackSV8Test(CommonApeTests.ApeTestCase):
testfile = 'test-sv8.mpc'
supports_ratings = False
expected_info = {
'length': 82,
'~channels': '2',
'~sample_rate': '44100',
'~filesize': '1569',
}
unexpected_info = ['~video']
class TAKTest(CommonApeTests.ApeTestCase):
testfile = 'test.tak'
supports_ratings = False
unexpected_info = ['~video']
def setUp(self):
super().setUp()
if native_tak:
self.expected_info = {
'length': 82,
'~channels': '2',
'~sample_rate': '44100',
'~bits_per_sample': '16',
'~filesize': '2080',
}
class OptimFROGLosslessTest(CommonApeTests.ApeTestCase):
testfile = 'test.ofr'
supports_ratings = False
expected_info = {
'length': 0,
'~channels': '2',
'~sample_rate': '48000',
'~filesize': '117',
}
unexpected_info = ['~video']
def test_format(self):
metadata = load_metadata(self.filename)
self.assertEqual(metadata['~format'], 'OptimFROG Lossless Audio')
class OptimFROGDUalStreamTest(CommonApeTests.ApeTestCase):
testfile = 'test.ofs'
supports_ratings = False
expected_info = {
'length': 0,
'~channels': '2',
'~sample_rate': '48000',
'~filesize': '117',
}
unexpected_info = ['~video']
def test_format(self):
metadata = load_metadata(self.filename)
self.assertEqual(metadata['~format'], 'OptimFROG DualStream Audio')
class ApeCoverArtTest(CommonCoverArtTests.CoverArtTestCase):
testfile = 'test.ape'
supports_types = False
class Apev2UtilTest(PicardTestCase):
def test_is_valid_key(self):
for key in VALID_KEYS:
self.assertTrue(apev2.is_valid_key(key), '%r is valid' % key)
for key in INVALID_KEYS:
self.assertFalse(apev2.is_valid_key(key), '%r is invalid' % key)
| 11,268
|
Python
|
.py
| 282
| 31.769504
| 100
| 0.628807
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,907
|
test_ac3.py
|
metabrainz_picard/test/formats/test_ac3.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2019 Philipp Wolfer
# Copyright (C) 2020-2021 Laurent Monin
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import os
import unittest
from picard import config
from picard.formats.ac3 import AC3File
from picard.formats.mutagenext.ac3 import native_ac3
from picard.metadata import Metadata
from .common import (
CommonTests,
load_metadata,
save_and_load_metadata,
)
from .test_apev2 import CommonApeTests
class AC3WithAPETest(CommonApeTests.ApeTestCase):
testfile = 'test.ac3'
supports_ratings = False
expected_info = {
'length': 104,
'~bitrate': '192.0',
'~sample_rate': '44100',
'~channels': '2',
'~filesize': '2506',
}
unexpected_info = ['~video']
def setUp(self):
super().setUp()
config.setting['ac3_save_ape'] = True
config.setting['remove_ape_from_ac3'] = True
@unittest.skipUnless(native_ac3, "mutagen.ac3 not available")
def test_info(self):
super().test_info()
class AC3NoTagsTest(CommonTests.BaseFileTestCase):
testfile = 'test-apev2.ac3'
def setUp(self):
super().setUp()
config.setting['ac3_save_ape'] = False
config.setting['remove_ape_from_ac3'] = False
def test_load_but_do_not_save_tags(self):
metadata = load_metadata(self.filename)
self.assertEqual('Test AC3 with APEv2 tags', metadata['title'])
self.assertEqual('The Artist', metadata['artist'])
metadata['artist'] = 'Foo'
metadata['title'] = 'Bar'
metadata = save_and_load_metadata(self.filename, metadata)
self.assertEqual('Test AC3 with APEv2 tags', metadata['title'])
self.assertEqual('The Artist', metadata['artist'])
def test_remove_ape_tags(self):
config.setting['remove_ape_from_ac3'] = True
metadata = Metadata({
'artist': 'Foo'
})
metadata = save_and_load_metadata(self.filename, metadata)
self.assertEqual('AC-3', metadata['~format'])
self.assertNotIn('title', metadata)
self.assertNotIn('artist', metadata)
def test_info_format(self):
metadata = load_metadata(os.path.join('test', 'data', 'test.ac3'))
self.assertEqual('AC-3', metadata['~format'])
metadata = load_metadata(os.path.join('test', 'data', 'test-apev2.ac3'))
self.assertEqual('AC-3 (APEv2)', metadata['~format'])
if native_ac3:
metadata = load_metadata(os.path.join('test', 'data', 'test.eac3'))
self.assertEqual('Enhanced AC-3', metadata['~format'])
def test_supports_tag(self):
config.setting['ac3_save_ape'] = True
self.assertTrue(AC3File.supports_tag('title'))
config.setting['ac3_save_ape'] = False
self.assertFalse(AC3File.supports_tag('title'))
@unittest.skipUnless(native_ac3, "mutagen.ac3 not available")
class EAC3Test(CommonTests.SimpleFormatsTestCase):
testfile = 'test.eac3'
expected_info = {
'~format': 'Enhanced AC-3',
'length': 104,
'~sample_rate': '44100',
'~channels': '2',
'~filesize': '2506',
}
unexpected_info = ['~video']
def setUp(self):
super().setUp()
config.setting['ac3_save_ape'] = True
def test_bitrate(self):
# For EAC3 bitrate is calculated and often a fractional value
metadata = load_metadata(os.path.join('test', 'data', 'test.ac3'))
self.assertAlmostEqual(192.0, float(metadata['~bitrate']))
| 4,235
|
Python
|
.py
| 105
| 34.428571
| 80
| 0.667964
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,908
|
test_midi.py
|
metabrainz_picard/test/formats/test_midi.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2019-2021 Philipp Wolfer
# Copyright (C) 2020-2021 Laurent Monin
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from picard.formats import midi
from .common import (
TAGS,
CommonTests,
)
class MIDITest(CommonTests.SimpleFormatsTestCase):
testfile = 'test.mid'
expected_info = {
'length': 127997,
'~format': 'Standard MIDI File',
'~filesize': '8444',
}
unexpected_info = ['~video']
def test_supports_tag(self):
for tag in TAGS:
self.assertFalse(midi.MIDIFile.supports_tag(tag))
| 1,308
|
Python
|
.py
| 36
| 33.166667
| 80
| 0.729858
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,909
|
test_aac.py
|
metabrainz_picard/test/formats/test_aac.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2019 Philipp Wolfer
# Copyright (C) 2020-2021 Laurent Monin
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import os
from picard import config
from picard.formats.apev2 import AACFile
from picard.metadata import Metadata
from .common import (
CommonTests,
load_metadata,
save_and_load_metadata,
)
from .test_apev2 import CommonApeTests
class AACTest(CommonTests.SimpleFormatsTestCase):
testfile = 'test.aac'
expected_info = {
'length': 120,
'~channels': '2',
'~sample_rate': '44100',
'~bitrate': '123.824',
'~filesize': '1896',
}
unexpected_info = ['~video']
class AACWithAPETest(CommonApeTests.ApeTestCase):
testfile = 'test-apev2.aac'
supports_ratings = False
expected_info = {
'length': 119,
'~channels': '2',
'~sample_rate': '44100',
'~bitrate': '123.824',
'~filesize': '1974',
}
unexpected_info = ['~video']
class AACNoTagsTest(CommonTests.BaseFileTestCase):
testfile = 'test-apev2.aac'
def setUp(self):
super().setUp()
config.setting['aac_save_ape'] = False
config.setting['remove_ape_from_aac'] = False
def test_load_but_do_not_save_tags(self):
metadata = load_metadata(self.filename)
self.assertEqual('Test AAC with APEv2 tags', metadata['title'])
self.assertEqual('The Artist', metadata['artist'])
metadata['artist'] = 'Foo'
metadata['title'] = 'Bar'
metadata = save_and_load_metadata(self.filename, metadata)
self.assertEqual('Test AAC with APEv2 tags', metadata['title'])
self.assertEqual('The Artist', metadata['artist'])
def test_remove_ape_tags(self):
config.setting['remove_ape_from_aac'] = True
metadata = Metadata({
'artist': 'Foo'
})
metadata = save_and_load_metadata(self.filename, metadata)
self.assertEqual('AAC', metadata['~format'])
self.assertNotIn('title', metadata)
self.assertNotIn('artist', metadata)
def test_info_format(self):
metadata = load_metadata(os.path.join('test', 'data', 'test.aac'))
self.assertEqual('AAC', metadata['~format'])
metadata = load_metadata(os.path.join('test', 'data', 'test-apev2.aac'))
self.assertEqual('AAC (APEv2)', metadata['~format'])
def test_supports_tag(self):
config.setting['aac_save_ape'] = True
self.assertTrue(AACFile.supports_tag('title'))
config.setting['aac_save_ape'] = False
self.assertFalse(AACFile.supports_tag('title'))
| 3,336
|
Python
|
.py
| 85
| 33.694118
| 80
| 0.673053
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,910
|
test_wav.py
|
metabrainz_picard/test/formats/test_wav.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2018-2020, 2022 Philipp Wolfer
# Copyright (C) 2020-2021 Laurent Monin
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from mutagen import version as mutagen_version
from picard import config
from picard.formats import WAVFile
from picard.metadata import Metadata
from .common import (
REPLAYGAIN_TAGS,
TAGS,
CommonTests,
load_metadata,
save_metadata,
skipUnlessTestfile,
)
from .test_id3 import CommonId3Tests
expected_info = {
'length': 82,
'~channels': '2',
'~sample_rate': '44100',
'~bits_per_sample': '16',
'~filesize': '14652',
}
if WAVFile.supports_tag('artist'):
from picard.formats.wav import RiffListInfo
riff_info_tags = {
'IART': 'the artist',
'ICMT': 'the comment',
'ICOP': 'the copyright',
'ICRD': 'the date',
'IGNR': 'the genre',
'INAM': 'the title',
'IPRD': 'the album',
'ITRK': 'the tracknumber',
'ICNT': 'the releasecountry',
'IENC': 'the encodedby',
'IENG': 'the engineer',
'ILNG': 'the language',
'IMED': 'the media',
'IMUS': 'the composer',
'IPRO': 'the producer',
'IWRI': 'the writer',
}
class WAVTest(CommonId3Tests.Id3TestCase):
testfile = 'test.wav'
expected_info = expected_info
unexpected_info = ['~video']
supports_ratings = True
def setUp(self):
super().setUp()
# mutagen < 1.46 has broken bitrate calculation for WAVE files
if mutagen_version >= (1, 46, 0):
self.expected_info['~bitrate'] = '1411.2'
@skipUnlessTestfile
def test_invalid_track_and_discnumber(self):
config.setting['write_wave_riff_info'] = False
super().test_invalid_track_and_discnumber()
@skipUnlessTestfile
def test_load_riff_info_fallback(self):
self._save_riff_info_tags()
metadata = load_metadata(self.filename)
self.assertEqual(metadata['artist'], 'the artist')
@skipUnlessTestfile
def test_save_riff_info(self):
metadata = Metadata({
'artist': 'the artist',
'album': 'the album'
})
save_metadata(self.filename, metadata)
info = RiffListInfo()
info.load(self.filename)
self.assertEqual(info['IART'], 'the artist')
self.assertEqual(info['IPRD'], 'the album')
@skipUnlessTestfile
def test_delete_riff_info_tag(self):
self._save_riff_info_tags()
metadata = Metadata()
del metadata['title']
save_metadata(self.filename, metadata)
info = RiffListInfo()
info.load(self.filename)
self.assertEqual(info['IART'], 'the artist')
self.assertNotIn('INAM', info)
@skipUnlessTestfile
def test_riff_save_and_load(self):
self._save_riff_info_tags()
loaded_info = RiffListInfo()
loaded_info.load(self.filename)
for key, value in loaded_info.items():
self.assertEqual(riff_info_tags[key], value)
@skipUnlessTestfile
def test_riff_info_encoding_windows_1252(self):
info = RiffListInfo()
info['INAM'] = 'fooßü‰€œžŸ文字'
info.save(self.filename)
loaded_info = RiffListInfo()
loaded_info.load(self.filename)
self.assertEqual('fooßü‰€œžŸ??', loaded_info['INAM'])
@skipUnlessTestfile
def test_riff_info_encoding_utf_8(self):
info = RiffListInfo(encoding="utf-8")
info['INAM'] = 'fooßü‰€œžŸ文字'
info.save(self.filename)
loaded_info = RiffListInfo()
loaded_info.load(self.filename)
self.assertEqual(info['INAM'], loaded_info['INAM'])
def _save_riff_info_tags(self):
info = RiffListInfo()
for key, value in riff_info_tags.items():
info[key] = value
info.save(self.filename)
else:
class WAVTest(CommonTests.SimpleFormatsTestCase):
testfile = 'test.wav'
expected_info = expected_info
unexpected_info = ['~video']
def setUp(self):
super().setUp()
self.unsupported_tags = {**TAGS, **REPLAYGAIN_TAGS}
@skipUnlessTestfile
def test_unsupported_tags(self):
self._test_unsupported_tags(self.unsupported_tags)
| 5,299
|
Python
|
.py
| 139
| 29.388489
| 80
| 0.613516
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,911
|
test_vorbis.py
|
metabrainz_picard/test/formats/test_vorbis.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2019-2022 Philipp Wolfer
# Copyright (C) 2020 Laurent Monin
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import base64
import os
from unittest.mock import patch
from mutagen.flac import (
Padding,
Picture,
SeekPoint,
SeekTable,
VCFLACDict,
)
from test.picardtestcase import (
PicardTestCase,
create_fake_png,
)
from picard import config
from picard.coverart.image import CoverArtImage
from picard.formats import vorbis
from picard.formats.util import open_ as open_format
from picard.metadata import Metadata
from .common import (
TAGS,
CommonTests,
load_metadata,
load_raw,
save_and_load_metadata,
save_metadata,
save_raw,
skipUnlessTestfile,
)
from .coverart import (
CommonCoverArtTests,
file_save_image,
load_coverart_file,
)
VALID_KEYS = [
' valid Key}',
'{ $ome tag}',
]
INVALID_KEYS = [
'',
'invalid=key',
'invalid\x19key',
'invalid~key',
]
PNG_BASE64 = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVQI12P4//8/AAX+Av7czFnnAAAAAElFTkSuQmCC'
# prevent unittest to run tests in those classes
class CommonVorbisTests:
class VorbisTestCase(CommonTests.TagFormatsTestCase):
def test_invalid_rating(self):
filename = os.path.join('test', 'data', 'test-invalid-rating.ogg')
metadata = load_metadata(filename)
self.assertEqual(metadata["~rating"], "THERATING")
def test_supports_tags(self):
supports_tag = self.format.supports_tag
for key in VALID_KEYS + list(TAGS.keys()):
self.assertTrue(supports_tag(key), '%r should be supported' % key)
for key in INVALID_KEYS:
self.assertFalse(supports_tag(key), '%r should be unsupported' % key)
@skipUnlessTestfile
def test_r128_replaygain_tags(self):
# Vorbis files other then Opus must not support the r128_* tags
tags = {
'r128_album_gain': '-2857',
'r128_track_gain': '-2857',
}
self._test_unsupported_tags(tags)
@skipUnlessTestfile
def test_invalid_metadata_block_picture_nobase64(self):
metadata = {
'metadata_block_picture': 'notbase64'
}
save_raw(self.filename, metadata)
loaded_metadata = load_metadata(self.filename)
self.assertEqual(0, len(loaded_metadata.images))
@skipUnlessTestfile
def test_invalid_metadata_block_picture_noflacpicture(self):
metadata = {
'metadata_block_picture': base64.b64encode(b'notaflacpictureblock').decode('ascii')
}
save_raw(self.filename, metadata)
loaded_metadata = load_metadata(self.filename)
self.assertEqual(0, len(loaded_metadata.images))
@skipUnlessTestfile
def test_legacy_coverart(self):
save_raw(self.filename, {'coverart': PNG_BASE64})
loaded_metadata = load_metadata(self.filename)
self.assertEqual(1, len(loaded_metadata.images))
first_image = loaded_metadata.images[0]
self.assertEqual('image/png', first_image.mimetype)
self.assertEqual(69, first_image.datalength)
@skipUnlessTestfile
def test_clear_tags_preserve_legacy_coverart(self):
save_raw(self.filename, {'coverart': PNG_BASE64})
config.setting['clear_existing_tags'] = True
config.setting['preserve_images'] = True
metadata = save_and_load_metadata(self.filename, Metadata())
self.assertEqual(1, len(metadata.images))
config.setting['preserve_images'] = False
metadata = save_and_load_metadata(self.filename, Metadata())
self.assertEqual(0, len(metadata.images))
@skipUnlessTestfile
def test_invalid_legacy_coverart_nobase64(self):
metadata = {
'coverart': 'notbase64'
}
save_raw(self.filename, metadata)
loaded_metadata = load_metadata(self.filename)
self.assertEqual(0, len(loaded_metadata.images))
@skipUnlessTestfile
def test_invalid_legacy_coverart_noimage(self):
metadata = {
'coverart': base64.b64encode(b'invalidimagedata').decode('ascii')
}
save_raw(self.filename, metadata)
loaded_metadata = load_metadata(self.filename)
self.assertEqual(0, len(loaded_metadata.images))
def test_supports_extended_tags(self):
performer_tag = "performer:accordéon clavier « boutons »"
self.assertTrue(self.format.supports_tag(performer_tag))
self.assertTrue(self.format.supports_tag('lyrics:foó'))
self.assertTrue(self.format.supports_tag('comment:foó'))
@skipUnlessTestfile
def test_delete_totaldiscs_totaltracks(self):
# Create a test file that contains only disctotal / tracktotal,
# but not totaldiscs and totaltracks
save_raw(self.filename, {
'disctotal': '3',
'tracktotal': '2',
})
metadata = Metadata()
del metadata['totaldiscs']
del metadata['totaltracks']
save_metadata(self.filename, metadata)
loaded_metadata = load_raw(self.filename)
self.assertNotIn('disctotal', loaded_metadata)
self.assertNotIn('totaldiscs', loaded_metadata)
self.assertNotIn('tracktotal', loaded_metadata)
self.assertNotIn('totaltracks', loaded_metadata)
@skipUnlessTestfile
def test_delete_invalid_tagname(self):
# Deleting tags that are not valid Vorbis tag names must not trigger
# an error
for invalid_tag in INVALID_KEYS:
metadata = Metadata()
del metadata[invalid_tag]
save_metadata(self.filename, metadata)
@skipUnlessTestfile
def test_load_strip_trailing_null_char(self):
save_raw(self.filename, {
'date': '2023-04-18\0',
'title': 'foo\0',
})
metadata = load_metadata(self.filename)
self.assertEqual('2023-04-18', metadata['date'])
self.assertEqual('foo', metadata['title'])
class FLACTest(CommonVorbisTests.VorbisTestCase):
testfile = 'test.flac'
supports_ratings = True
expected_info = {
'length': 82,
'~channels': '2',
'~sample_rate': '44100',
'~format': 'FLAC',
'~filesize': '6546',
}
unexpected_info = ['~video']
@skipUnlessTestfile
def test_preserve_waveformatextensible_channel_mask(self):
config.setting['clear_existing_tags'] = True
original_metadata = load_metadata(self.filename)
self.assertEqual(original_metadata['~waveformatextensible_channel_mask'], '0x3')
new_metadata = save_and_load_metadata(self.filename, original_metadata)
self.assertEqual(new_metadata['~waveformatextensible_channel_mask'], '0x3')
@skipUnlessTestfile
def test_clear_tags_preserve_legacy_coverart(self):
# FLAC does not use the cover art tags but has its separate image implementation
pic = Picture()
pic.data = load_coverart_file('mb.png')
save_raw(self.filename, {
'coverart': PNG_BASE64,
'metadata_block_picture': base64.b64encode(pic.write()).decode('ascii')
})
config.setting['clear_existing_tags'] = True
config.setting['preserve_images'] = True
metadata = save_and_load_metadata(self.filename, Metadata())
self.assertEqual(0, len(metadata.images))
@skipUnlessTestfile
def test_sort_pics_after_tags(self):
# First save file with pic block before tags
pic = Picture()
pic.data = load_coverart_file('mb.png')
f = load_raw(self.filename)
f.metadata_blocks.insert(1, pic)
f.save()
# Save the file with Picard
metadata = Metadata()
save_metadata(self.filename, metadata)
# Load raw file and verify picture block position
f = load_raw(self.filename)
tagindex = f.metadata_blocks.index(f.tags)
haspics = False
for b in f.metadata_blocks:
if b.code == Picture.code:
haspics = True
self.assertGreater(f.metadata_blocks.index(b), tagindex)
self.assertTrue(haspics, "Picture block expected, none found")
@patch.object(vorbis, 'flac_remove_empty_seektable')
def test_setting_fix_missing_seekpoints_flac(self, mock_flac_remove_empty_seektable):
save_metadata(self.filename, Metadata())
mock_flac_remove_empty_seektable.assert_not_called()
self.set_config_values({
'fix_missing_seekpoints_flac': True
})
save_metadata(self.filename, Metadata())
mock_flac_remove_empty_seektable.assert_called_once()
@skipUnlessTestfile
def test_flac_remove_empty_seektable_remove_empty(self):
f = load_raw(self.filename)
# Add an empty seek table
seektable = SeekTable(None)
f.seektable = seektable
f.metadata_blocks.append(seektable)
# This is a zero length file. The empty seektable should get removed
vorbis.flac_remove_empty_seektable(f)
self.assertIsNone(f.seektable)
self.assertNotIn(seektable, f.metadata_blocks)
@skipUnlessTestfile
def test_flac_remove_empty_seektable_keep_existing(self):
f = load_raw(self.filename)
# Add an non-empty seek table
seektable = SeekTable(None)
seekpoint = SeekPoint(0, 0, 0)
seektable.seekpoints.append(seekpoint)
f.seektable = seektable
f.metadata_blocks.append(seektable)
# Existing non-empty seektable should be kept
vorbis.flac_remove_empty_seektable(f)
self.assertEqual(seektable, f.seektable)
self.assertIn(seektable, f.metadata_blocks)
self.assertEqual([seekpoint], f.seektable.seekpoints)
class OggVorbisTest(CommonVorbisTests.VorbisTestCase):
testfile = 'test.ogg'
supports_ratings = True
expected_info = {
'length': 82,
'~channels': '2',
'~sample_rate': '44100',
'~filesize': '5221',
}
class OggSpxTest(CommonVorbisTests.VorbisTestCase):
testfile = 'test.spx'
supports_ratings = True
expected_info = {
'length': 89,
'~channels': '2',
'~bitrate': '29.6',
'~filesize': '608',
}
unexpected_info = ['~video']
class OggOpusTest(CommonVorbisTests.VorbisTestCase):
testfile = 'test.opus'
supports_ratings = True
expected_info = {
'length': 82,
'~channels': '2',
'~filesize': '1637',
}
unexpected_info = ['~video']
@skipUnlessTestfile
def test_r128_replaygain_tags(self):
tags = {
'r128_album_gain': '-2857',
'r128_track_gain': '-2857',
}
self._test_supported_tags(tags)
class OggTheoraTest(CommonVorbisTests.VorbisTestCase):
testfile = 'test.ogv'
supports_ratings = True
expected_info = {
'length': 520,
'~bitrate': '200.0',
'~video': '1',
'~filesize': '5298',
}
class OggFlacTest(CommonVorbisTests.VorbisTestCase):
testfile = 'test-oggflac.oga'
supports_ratings = True
expected_info = {
'length': 82,
'~channels': '2',
'~filesize': '2573',
}
unexpected_info = ['~video']
class VorbisUtilTest(PicardTestCase):
def test_sanitize_key(self):
sanitized = vorbis.sanitize_key(' \x1f=}~')
self.assertEqual(sanitized, ' }')
def test_is_valid_key(self):
for key in VALID_KEYS:
self.assertTrue(vorbis.is_valid_key(key), '%r is valid' % key)
for key in INVALID_KEYS:
self.assertFalse(vorbis.is_valid_key(key), '%r is invalid' % key)
def test_flac_sort_pics_after_tags(self):
pic1 = Picture()
pic2 = Picture()
pic3 = Picture()
tags = VCFLACDict()
pad = Padding()
blocks = []
vorbis.flac_sort_pics_after_tags(blocks)
self.assertEqual([], blocks)
blocks = [tags]
vorbis.flac_sort_pics_after_tags(blocks)
self.assertEqual([tags], blocks)
blocks = [tags, pad, pic1]
vorbis.flac_sort_pics_after_tags(blocks)
self.assertEqual([tags, pad, pic1], blocks)
blocks = [pic1, pic2, tags, pad, pic3]
vorbis.flac_sort_pics_after_tags(blocks)
self.assertEqual([tags, pic1, pic2, pad, pic3], blocks)
blocks = [pic1, pic2, pad, pic3]
vorbis.flac_sort_pics_after_tags(blocks)
self.assertEqual([pic1, pic2, pad, pic3], blocks)
class FlacCoverArtTest(CommonCoverArtTests.CoverArtTestCase):
testfile = 'test.flac'
def test_set_picture_dimensions(self):
tests = [
CoverArtImage(data=self.jpegdata),
CoverArtImage(data=self.pngdata),
]
for test in tests:
file_save_image(self.filename, test)
raw_metadata = load_raw(self.filename)
pic = raw_metadata.pictures[0]
self.assertNotEqual(pic.width, 0)
self.assertEqual(pic.width, test.width)
self.assertNotEqual(pic.height, 0)
self.assertEqual(pic.height, test.height)
def test_save_large_pics(self):
# 16 MB image
data = create_fake_png(b"a" * 1024 * 1024 * 16)
image = CoverArtImage(data=data)
file_save_image(self.filename, image)
raw_metadata = load_raw(self.filename)
# Images with more than 16 MB cannot be saved to FLAC
self.assertEqual(0, len(raw_metadata.pictures))
class OggAudioVideoFileTest(PicardTestCase):
def test_ogg_audio(self):
self._test_file_is_type(
open_format,
self._copy_file_tmp('test-oggflac.oga', '.oga'),
vorbis.OggFLACFile)
self._test_file_is_type(
open_format,
self._copy_file_tmp('test.spx', '.oga'),
vorbis.OggSpeexFile)
self._test_file_is_type(
open_format,
self._copy_file_tmp('test.ogg', '.oga'),
vorbis.OggVorbisFile)
self._test_file_is_type(
open_format,
self._copy_file_tmp('test.ogg', '.ogx'),
vorbis.OggVorbisFile)
def test_ogg_opus(self):
self._test_file_is_type(
open_format,
self._copy_file_tmp('test.opus', '.oga'),
vorbis.OggOpusFile)
self._test_file_is_type(
open_format,
self._copy_file_tmp('test.opus', '.ogg'),
vorbis.OggOpusFile)
def test_ogg_video(self):
self._test_file_is_type(
open_format,
self._copy_file_tmp('test.ogv', '.ogv'),
vorbis.OggTheoraFile)
def _test_file_is_type(self, factory, filename, expected_type):
f = factory(filename)
self.assertIsInstance(f, expected_type)
def _copy_file_tmp(self, filename, ext):
path = os.path.join('test', 'data', filename)
return self.copy_file_tmp(path, ext)
class OggCoverArtTest(CommonCoverArtTests.CoverArtTestCase):
testfile = 'test.ogg'
| 16,199
|
Python
|
.py
| 406
| 31.155172
| 107
| 0.631385
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,912
|
common.py
|
metabrainz_picard/test/formats/common.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2019 Zenara Daley
# Copyright (C) 2019-2021 Philipp Wolfer
# Copyright (C) 2020-2022 Laurent Monin
# Copyright (C) 2022 Marcin Szalowicz
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import os.path
import unittest
import mutagen
from test.picardtestcase import PicardTestCase
from picard import config
import picard.formats
from picard.formats import ext_to_format
from picard.formats.mutagenext.aac import AACAPEv2
from picard.formats.mutagenext.ac3 import AC3APEv2
from picard.formats.mutagenext.tak import TAK
from picard.formats.util import guess_format
from picard.metadata import Metadata
from picard.util.tags import FILE_INFO_TAGS
settings = {
'clear_existing_tags': False,
'preserve_images': False,
'embed_only_one_front_image': False,
'enabled_plugins': '',
'id3v23_join_with': '/',
'id3v2_encoding': 'utf-8',
'rating_steps': 6,
'rating_user_email': 'users@musicbrainz.org',
'remove_ape_from_mp3': False,
'remove_id3_from_flac': False,
'fix_missing_seekpoints_flac': False,
'remove_images_from_tags': False,
'save_images_to_tags': True,
'write_id3v1': True,
'write_id3v23': False,
'itunes_compatible_grouping': False,
'aac_save_ape': True,
'ac3_save_ape': True,
'write_wave_riff_info': True,
'remove_wave_riff_info': False,
'wave_riff_info_encoding': 'iso-8859-1',
'replace_spaces_with_underscores': False,
'replace_dir_separator': '_',
'win_compat_replacements': {},
}
def save_metadata(filename, metadata):
f = picard.formats.open_(filename)
loaded_metadata = f._load(filename)
f._copy_loaded_metadata(loaded_metadata)
f._save(filename, metadata)
def load_metadata(filename):
f = picard.formats.open_(filename)
return f._load(filename)
def save_and_load_metadata(filename, metadata):
"""Save new metadata to a file and load it again."""
save_metadata(filename, metadata)
return load_metadata(filename)
def load_raw(filename):
# First try special implementations in Picard
f = mutagen.File(filename, [AACAPEv2, AC3APEv2, TAK])
if f is None:
f = mutagen.File(filename)
return f
def save_raw(filename, tags):
f = load_raw(filename)
for k, v in tags.items():
f[k] = v
f.save()
TAGS = {
'albumartist': 'Foo',
'albumartistsort': 'Foo',
'album': 'Foo Bar',
'albumsort': 'Foo',
'arranger': 'Foo',
'artist': 'Foo',
'artistsort': 'Foo',
'asin': 'Foo',
'barcode': 'Foo',
'bpm': '80',
'catalognumber': 'Foo',
'comment': 'Foo',
'comment:foo': 'Foo',
'comment:deu:foo': 'Foo',
'compilation': '1',
'composer': 'Foo',
'composersort': 'Foo',
'conductor': 'Foo',
'copyright': 'Foo',
'date': '2004',
'director': 'Foo',
'discnumber': '1',
'discsubtitle': 'Foo',
'djmixer': 'Foo',
'encodedby': 'Foo',
'encodersettings': 'Foo',
'engineer': 'Foo',
'gapless': '1',
'genre': 'Foo',
'grouping': 'Foo',
'isrc': 'Foo',
'key': 'E#m',
'label': 'Foo',
'lyricist': 'Foo',
'lyrics': 'Foo',
'media': 'Foo',
'mixer': 'Foo',
'mood': 'Foo',
'movement': 'Foo',
'movementnumber': '2',
'movementtotal': '8',
'musicbrainz_albumartistid': '00000000-0000-0000-0000-000000000000',
'musicbrainz_albumid': '00000000-0000-0000-0000-000000000000',
'musicbrainz_artistid': '00000000-0000-0000-0000-000000000000',
'musicbrainz_discid': 'HJRFvVfxx0MU_6v8v9swQUxDmZQ-',
'musicbrainz_originalalbumid': '00000000-0000-0000-0000-000000000000',
'musicbrainz_originalartistid': '00000000-0000-0000-0000-000000000000',
'musicbrainz_releasegroupid': '00000000-0000-0000-0000-000000000000',
'musicbrainz_trackid': '00000000-0000-0000-0000-000000000000',
'musicbrainz_trmid': 'Foo',
'musicbrainz_workid': '00000000-0000-0000-0000-000000000000',
'musicip_fingerprint': 'Foo',
'musicip_puid': '00000000-0000-0000-0000-000000000000',
'originaldate': '1980-01-20',
'originalyear': '1980',
'originalfilename': 'Foo',
'performer': 'Foo',
'performer:guest vocal': 'Foo',
'podcast': '1',
'podcasturl': 'Foo',
'producer': 'Foo',
'releasedate': '2022-05-22',
'releasecountry': 'XW',
'releasestatus': 'Foo',
'releasetype': 'Foo',
'remixer': 'Foo',
'show': 'Foo',
'showmovement': '1',
'showsort': 'Foo',
'subtitle': 'Foo',
'title': 'Foo',
'titlesort': 'Foo',
'totaldiscs': '2',
'totaltracks': '10',
'tracknumber': '2',
'website': 'http://example.com',
'work': 'Foo'
}
REPLAYGAIN_TAGS = {
'replaygain_album_gain': '-6.48 dB',
'replaygain_album_peak': '0.978475',
'replaygain_album_range': '7.84 dB',
'replaygain_track_gain': '-6.16 dB',
'replaygain_track_peak': '0.976991',
'replaygain_track_range': '8.22 dB',
'replaygain_reference_loudness': '-18.00 LUFS',
}
def skipUnlessTestfile(func):
def _decorator(self, *args, **kwargs):
if not self.testfile:
raise unittest.SkipTest("No test file set")
func(self, *args, **kwargs)
return _decorator
# prevent unittest to run tests in those classes
class CommonTests:
class BaseFileTestCase(PicardTestCase):
testfile = None
testfile_ext = None
testfile_path = None
def setUp(self):
super().setUp()
self.set_config_values(settings)
if self.testfile:
_name, self.testfile_ext = os.path.splitext(self.testfile)
self.testfile_path = os.path.join('test', 'data', self.testfile)
self.testfile_ext = os.path.splitext(self.testfile)[1]
self.filename = self.copy_of_original_testfile()
self.format = ext_to_format(self.testfile_ext)
def copy_of_original_testfile(self):
return self.copy_file_tmp(self.testfile_path, self.testfile_ext)
class SimpleFormatsTestCase(BaseFileTestCase):
expected_info = {}
unexpected_info = []
@skipUnlessTestfile
def test_can_open_and_save(self):
metadata = save_and_load_metadata(self.filename, Metadata())
self.assertTrue(metadata['~format'])
@skipUnlessTestfile
def test_info(self):
if not self.expected_info:
raise unittest.SkipTest("Ratings not supported for %s" % self.format.NAME)
metadata = load_metadata(self.filename)
for key, expected_value in self.expected_info.items():
value = metadata.length if key == 'length' else metadata[key]
self.assertEqual(expected_value, value, '%s: %r != %r' % (key, expected_value, value))
for key in self.unexpected_info:
self.assertNotIn(key, metadata)
def _test_supported_tags(self, tags):
metadata = Metadata(tags)
loaded_metadata = save_and_load_metadata(self.filename, metadata)
for (key, value) in tags.items():
self.assertEqual(loaded_metadata[key], value, '%s: %r != %r' % (key, loaded_metadata[key], value))
def _test_unsupported_tags(self, tags):
metadata = Metadata(tags)
loaded_metadata = save_and_load_metadata(self.filename, metadata)
for tag in tags:
self.assertFalse(self.format.supports_tag(tag))
self.assertNotIn(tag, loaded_metadata, '%s: %r != None' % (tag, loaded_metadata[tag]))
class TagFormatsTestCase(SimpleFormatsTestCase):
def setUp(self):
super().setUp()
self.tags = TAGS.copy()
self.replaygain_tags = REPLAYGAIN_TAGS.copy()
self.unsupported_tags = {}
self.setup_tags()
def setup_tags(self):
if self.testfile:
supports_tag = self.format.supports_tag
self.unsupported_tags = {tag: val for tag, val in self.tags.items() if not supports_tag(tag)}
self.remove_tags(self.unsupported_tags.keys())
def set_tags(self, dict_tag_value=None):
if dict_tag_value:
self.tags.update(dict_tag_value)
def remove_tags(self, tag_list=None):
for tag in tag_list:
del self.tags[tag]
@skipUnlessTestfile
def test_simple_tags(self):
self._test_supported_tags(self.tags)
@skipUnlessTestfile
def test_replaygain_tags(self):
self._test_supported_tags(self.replaygain_tags)
@skipUnlessTestfile
def test_replaygain_tags_case_insensitive(self):
tags = {
'replaygain_album_gain': '-6.48 dB',
'Replaygain_Album_Peak': '0.978475',
'replaygain_album_range': '7.84 dB',
'replaygain_track_gain': '-6.16 dB',
'replaygain_track_peak': '0.976991',
'replaygain_track_range': '8.22 dB',
'replaygain_reference_loudness': '-18.00 LUFS',
}
save_raw(self.filename, tags)
loaded_metadata = load_metadata(self.filename)
for (key, value) in self.replaygain_tags.items():
self.assertEqual(loaded_metadata[key], value, '%s: %r != %r' % (key, loaded_metadata[key], value))
@skipUnlessTestfile
def test_save_does_not_modify_metadata(self):
tags = dict(self.tags)
if self.supports_ratings:
tags['~rating'] = '3'
metadata = Metadata(tags)
save_metadata(self.filename, metadata)
for (key, value) in tags.items():
self.assertEqual(metadata[key], value, '%s: %r != %r' % (key, metadata[key], value))
@skipUnlessTestfile
def test_unsupported_tags(self):
self._test_unsupported_tags(self.unsupported_tags)
@skipUnlessTestfile
def test_unsupported_tags_info_tags(self):
for tag in FILE_INFO_TAGS:
self.assertFalse(self.format.supports_tag(tag), 'Tag "%s" must not be supported' % tag)
@skipUnlessTestfile
def test_preserve_unchanged_tags(self):
metadata = Metadata(self.tags)
save_metadata(self.filename, metadata)
loaded_metadata = save_and_load_metadata(self.filename, Metadata())
for (key, value) in self.tags.items():
self.assertEqual(loaded_metadata[key], value, '%s: %r != %r' % (key, loaded_metadata[key], value))
@skipUnlessTestfile
def test_delete_simple_tags(self):
metadata = Metadata(self.tags)
if self.supports_ratings:
metadata['~rating'] = 1
original_metadata = save_and_load_metadata(self.filename, metadata)
del metadata['albumartist']
del metadata['musicbrainz_artistid']
if self.supports_ratings:
del metadata['~rating']
new_metadata = save_and_load_metadata(self.filename, metadata)
self.assertIn('albumartist', original_metadata)
self.assertNotIn('albumartist', new_metadata)
self.assertIn('musicbrainz_artistid', original_metadata)
self.assertNotIn('musicbrainz_artistid', new_metadata)
if self.supports_ratings:
self.assertIn('~rating', original_metadata)
self.assertNotIn('~rating', new_metadata)
@skipUnlessTestfile
def test_delete_tags_with_empty_description(self):
for key in ('lyrics', 'lyrics:', 'comment', 'comment:', 'performer', 'performer:'):
name = key.rstrip(':')
name_with_description = name + ':foo'
if not self.format.supports_tag(name):
continue
metadata = Metadata()
metadata[name] = 'bar'
metadata[name_with_description] = 'other'
original_metadata = save_and_load_metadata(self.filename, metadata)
self.assertIn(name, original_metadata)
del metadata[key]
new_metadata = save_and_load_metadata(self.filename, metadata)
self.assertNotIn(name, new_metadata)
# Ensure the names with description did not get deleted
if name_with_description in original_metadata:
self.assertIn(name_with_description, new_metadata)
@skipUnlessTestfile
def test_delete_tags_with_description(self):
for key in (
'comment:foo', 'comment:de:foo', 'performer:foo', 'lyrics:foo',
'comment:a*', 'comment:a[', 'performer:(x)', 'performer: Ä é '
):
if not self.format.supports_tag(key):
continue
prefix = key.split(':')[0]
metadata = Metadata()
metadata[key] = 'bar'
original_metadata = save_and_load_metadata(self.filename, metadata)
if key not in original_metadata and prefix in original_metadata:
continue # Skip if the type did not support saving this kind of tag
self.assertEqual('bar', original_metadata[key], original_metadata)
metadata[prefix] = '(foo) bar'
del metadata[key]
new_metadata = save_and_load_metadata(self.filename, metadata)
self.assertNotIn(key, new_metadata)
self.assertEqual('(foo) bar', new_metadata[prefix])
@skipUnlessTestfile
def test_delete_nonexistant_tags(self):
for key in ('title', 'foo', 'comment:foo', 'comment:de:foo',
'performer:foo', 'lyrics:foo', 'totaltracks'):
if not self.format.supports_tag(key):
continue
metadata = Metadata()
save_metadata(self.filename, metadata)
del metadata[key]
new_metadata = save_and_load_metadata(self.filename, metadata)
self.assertNotIn(key, new_metadata)
@skipUnlessTestfile
def test_delete_complex_tags(self):
metadata = Metadata(self.tags)
original_metadata = save_and_load_metadata(self.filename, metadata)
del metadata['totaldiscs']
new_metadata = save_and_load_metadata(self.filename, metadata)
self.assertIn('totaldiscs', original_metadata)
if self.testfile_ext in {'.m4a', '.m4v'}:
self.assertEqual('0', new_metadata['totaldiscs'])
else:
self.assertNotIn('totaldiscs', new_metadata)
@skipUnlessTestfile
def test_delete_performer(self):
if not self.format.supports_tag('performer:'):
raise unittest.SkipTest('Tag "performer:" not supported for %s' % self.format.NAME)
metadata = Metadata({
'performer:piano': ['Piano1', 'Piano2'],
'performer:guitar': ['Guitar1'],
})
original_metadata = save_and_load_metadata(self.filename, metadata)
self.assertIn('Piano1', original_metadata.getall('performer:piano'))
self.assertIn('Piano2', original_metadata.getall('performer:piano'))
self.assertEqual(2, len(original_metadata.getall('performer:piano')))
self.assertEqual('Guitar1', original_metadata['performer:guitar'])
del metadata['performer:piano']
new_metadata = save_and_load_metadata(self.filename, metadata)
self.assertNotIn('performer:piano', new_metadata)
self.assertEqual('Guitar1', metadata['performer:guitar'])
@skipUnlessTestfile
def test_save_performer(self):
if not self.format.supports_tag('performer:'):
raise unittest.SkipTest('Tag "performer:" not supported for %s' % self.format.NAME)
instrument = "accordéon clavier « boutons »"
artist = "桑山哲也"
tag = "performer:" + instrument
metadata = Metadata({tag: artist})
loaded_metadata = save_and_load_metadata(self.filename, metadata)
self.assertIn(tag, loaded_metadata)
self.assertEqual(artist, loaded_metadata[tag])
@skipUnlessTestfile
def test_ratings(self):
if not self.supports_ratings:
raise unittest.SkipTest("Ratings not supported")
for rating in range(6):
rating = 1
metadata = Metadata()
metadata['~rating'] = rating
loaded_metadata = save_and_load_metadata(self.filename, metadata)
self.assertEqual(int(loaded_metadata['~rating']), rating, '~rating: %r != %r' % (loaded_metadata['~rating'], rating))
@skipUnlessTestfile
def test_invalid_rating_email(self):
if not self.supports_ratings:
raise unittest.SkipTest("Ratings not supported")
metadata = Metadata()
metadata['~rating'] = 3
config.setting['rating_user_email'] = '{in\tvälid}'
loaded_metadata = save_and_load_metadata(self.filename, metadata)
self.assertEqual(loaded_metadata['~rating'], metadata['~rating'])
@skipUnlessTestfile
def test_guess_format(self):
temp_file = self.copy_of_original_testfile()
audio = guess_format(temp_file)
audio_original = picard.formats.open_(self.filename)
self.assertEqual(type(audio), type(audio_original))
@skipUnlessTestfile
def test_split_ext(self):
f = picard.formats.open_(self.filename)
self.assertEqual(f._fixed_splitext(f.filename), os.path.splitext(f.filename))
self.assertEqual(f._fixed_splitext('.test'), os.path.splitext('.test'))
if f.EXTENSIONS:
self.assertEqual(f._fixed_splitext(f.EXTENSIONS[0]), ('', f.EXTENSIONS[0]))
self.assertNotEqual(f._fixed_splitext(f.EXTENSIONS[0]), os.path.splitext(f.EXTENSIONS[0]))
@skipUnlessTestfile
def test_clear_existing_tags_off(self):
config.setting['clear_existing_tags'] = False
existing_metadata = Metadata({'artist': 'The Artist'})
save_metadata(self.filename, existing_metadata)
new_metadata = Metadata({'title': 'The Title'})
loaded_metadata = save_and_load_metadata(self.filename, new_metadata)
self.assertEqual(existing_metadata['artist'], loaded_metadata['artist'])
self.assertEqual(new_metadata['title'], loaded_metadata['title'])
@skipUnlessTestfile
def test_clear_existing_tags_on(self):
config.setting['clear_existing_tags'] = True
existing_metadata = Metadata({'artist': 'The Artist'})
save_metadata(self.filename, existing_metadata)
new_metadata = Metadata({'title': 'The Title'})
loaded_metadata = save_and_load_metadata(self.filename, new_metadata)
self.assertNotIn('artist', loaded_metadata)
self.assertEqual(new_metadata['title'], loaded_metadata['title'])
@skipUnlessTestfile
def test_lyrics_with_description(self):
metadata = Metadata({'lyrics:foó': 'bar'})
loaded_metadata = save_and_load_metadata(self.filename, metadata)
self.assertEqual(metadata['lyrics:foó'], loaded_metadata['lyrics'])
@skipUnlessTestfile
def test_comments_with_description(self):
if not self.format.supports_tag('comment:foó'):
return
metadata = Metadata({'comment:foó': 'bar'})
loaded_metadata = save_and_load_metadata(self.filename, metadata)
self.assertEqual(metadata['comment:foó'], loaded_metadata['comment:foó'])
@skipUnlessTestfile
def test_invalid_track_and_discnumber(self):
# This test assumes a non-numeric test number can be written. For
# formats not supporting this it needs to be overridden.
metadata = Metadata({
'discnumber': 'notanumber',
'tracknumber': 'notanumber',
})
loaded_metadata = save_and_load_metadata(self.filename, metadata)
self.assertEqual(loaded_metadata['discnumber'], metadata['discnumber'])
self.assertEqual(loaded_metadata['totaldiscs'], metadata['totaldiscs'])
self.assertEqual(loaded_metadata['tracknumber'], metadata['tracknumber'])
self.assertEqual(loaded_metadata['totaltracks'], metadata['totaltracks'])
@skipUnlessTestfile
def test_save_movementnumber_without_movementtotal(self):
if not self.format.supports_tag('movementnumber'):
raise unittest.SkipTest('Tag "movementnumber" not supported for %s' % self.format.NAME)
metadata = Metadata({'movementnumber': 7})
loaded_metadata = save_and_load_metadata(self.filename, metadata)
self.assertEqual(loaded_metadata['movementnumber'], metadata['movementnumber'])
self.assertNotIn('movementtotal', loaded_metadata)
| 22,042
|
Python
|
.py
| 475
| 36.393684
| 133
| 0.618117
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,913
|
test_asf.py
|
metabrainz_picard/test/formats/test_asf.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2019-2021 Philipp Wolfer
# Copyright (C) 2020-2021 Laurent Monin
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from mutagen.asf import ASFByteArrayAttribute
from test.picardtestcase import (
PicardTestCase,
create_fake_png,
)
from picard.formats import (
asf,
ext_to_format,
)
from .common import (
CommonTests,
load_metadata,
load_raw,
save_metadata,
save_raw,
skipUnlessTestfile,
)
from .coverart import CommonCoverArtTests
# prevent unittest to run tests in those classes
class CommonAsfTests:
class AsfTestCase(CommonTests.TagFormatsTestCase):
def test_supports_tag(self):
fmt = ext_to_format(self.testfile_ext)
self.assertTrue(fmt.supports_tag('copyright'))
self.assertTrue(fmt.supports_tag('compilation'))
self.assertTrue(fmt.supports_tag('bpm'))
self.assertTrue(fmt.supports_tag('djmixer'))
self.assertTrue(fmt.supports_tag('discnumber'))
self.assertTrue(fmt.supports_tag('lyrics:lead'))
for tag in self.replaygain_tags.keys():
self.assertTrue(fmt.supports_tag(tag))
@skipUnlessTestfile
def test_ci_tags_preserve_case(self):
# Ensure values are not duplicated on repeated save and are saved
# case preserving.
tags = {
'Replaygain_Album_Peak': '-6.48 dB'
}
save_raw(self.filename, tags)
loaded_metadata = load_metadata(self.filename)
loaded_metadata['replaygain_album_peak'] = '1.0'
save_metadata(self.filename, loaded_metadata)
raw_metadata = load_raw(self.filename)
self.assertIn('Replaygain_Album_Peak', raw_metadata)
self.assertEqual(raw_metadata['Replaygain_Album_Peak'][0], loaded_metadata['replaygain_album_peak'])
self.assertEqual(1, len(raw_metadata['Replaygain_Album_Peak']))
self.assertNotIn('REPLAYGAIN_ALBUM_PEAK', raw_metadata)
def _test_invalid_picture(self, invalid_picture_data):
png_data = create_fake_png(b'x')
tags = {
'WM/Picture': [
ASFByteArrayAttribute(invalid_picture_data),
ASFByteArrayAttribute(
asf.pack_image("image/png", png_data)
)
]
}
save_raw(self.filename, tags)
metadata = load_metadata(self.filename)
self.assertEqual(1, len(metadata.images))
self.assertEqual(png_data, metadata.images[0].data)
@skipUnlessTestfile
def test_ignore_invalid_wm_picture(self):
# A picture that cannot be unpacked
self._test_invalid_picture(b'notapicture')
class ASFTest(CommonAsfTests.AsfTestCase):
testfile = 'test.asf'
supports_ratings = True
expected_info = {
'length': 92,
'~channels': '2',
'~sample_rate': '44100',
'~bitrate': '128.0',
'~filesize': '3744',
}
class WMATest(CommonAsfTests.AsfTestCase):
testfile = 'test.wma'
supports_ratings = True
expected_info = {
'length': 139,
'~channels': '2',
'~sample_rate': '44100',
'~bitrate': '64.0',
'~filesize': '8164',
}
unexpected_info = ['~video']
class WMVTest(CommonAsfTests.AsfTestCase):
testfile = 'test.wmv'
supports_ratings = True
expected_info = {
'length': 565,
'~channels': '2',
'~sample_rate': '44100',
'~bitrate': '128.0',
'~video': '1',
'~filesize': '7373',
}
class AsfUtilTest(PicardTestCase):
test_cases = [
# Empty MIME, description and data
(('', b'', 2, ''), b'\x02\x00\x00\x00\x00\x00\x00\x00\x00'),
# MIME, description set, 1 byte data
(('M', b'x', 2, 'D'), b'\x02\x01\x00\x00\x00M\x00\x00\x00D\x00\x00\x00x'),
# Empty MIME and description, 3 byte data
(('', b'abc', 0, ''), b'\x00\x03\x00\x00\x00\x00\x00\x00\x00abc'),
]
def test_pack_and_unpack_image(self):
mime = 'image/png'
image_data = create_fake_png(b'x')
image_type = 4
description = 'testing'
tag_data = asf.pack_image(mime, image_data, image_type, description)
expected_length = 5 + 2 * len(mime) + 2 + 2 * len(description) + 2 + len(image_data)
self.assertEqual(tag_data[0], image_type)
self.assertEqual(len(tag_data), expected_length)
self.assertEqual(image_data, tag_data[-len(image_data):])
unpacked = asf.unpack_image(tag_data)
self.assertEqual(mime, unpacked[0])
self.assertEqual(image_data, unpacked[1])
self.assertEqual(image_type, unpacked[2])
self.assertEqual(description, unpacked[3])
def test_pack_image(self):
for args, expected in self.test_cases:
self.assertEqual(expected, asf.pack_image(*args))
def test_unpack_image(self):
for expected, packed in self.test_cases:
self.assertEqual(expected, asf.unpack_image(packed))
def test_unpack_image_value_errors(self):
self.assertRaisesRegex(ValueError, "unpack_from requires a buffer of at least 5 bytes",
asf.unpack_image, b'')
self.assertRaisesRegex(ValueError, "unpack_from requires a buffer of at least 5 bytes",
asf.unpack_image, b'\x02\x01\x00\x00')
self.assertRaisesRegex(ValueError, "mime: missing data",
asf.unpack_image, b'\x00\x00\x00\x00\x00')
self.assertRaisesRegex(ValueError, "mime: missing data",
asf.unpack_image, b'\x04\x19\x00\x00\x00a\x00')
self.assertRaisesRegex(ValueError, "desc: missing data",
asf.unpack_image, b'\x04\x19\x00\x00\x00a\x00\x00\x00a\x00')
self.assertRaisesRegex(ValueError, "image data size mismatch",
asf.unpack_image, b'\x04\x19\x00\x00\x00a\x00\x00\x00a\x00\x00\x00x')
class AsfCoverArtTest(CommonCoverArtTests.CoverArtTestCase):
testfile = 'test.asf'
class WmaCoverArtTest(CommonCoverArtTests.CoverArtTestCase):
testfile = 'test.wma'
| 7,022
|
Python
|
.py
| 164
| 34.042683
| 112
| 0.62996
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,914
|
package-pypi.yml
|
metabrainz_picard/.github/workflows/package-pypi.yml
|
name: Package for PyPI
on: [workflow_call]
permissions: {}
defaults:
run:
shell: bash
jobs:
pypi-sdist:
runs-on: ubuntu-latest
env:
CODESIGN: 0
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: 3.12
- name: Install dependencies (Linux)
if: runner.os == 'linux'
run: |
sudo apt-get update
sudo apt-get install libegl1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
python -m pip install --upgrade setuptools
pip install --upgrade -r requirements.txt
- name: Run tests
timeout-minutes: 30
run: |
python setup.py test
- name: Build Python source distribution
run: |
git clean -dfx
python setup.py clean sdist --formats=gztar,zip
- name: Prepare GPG signing key
run: |
if [ -n "$CODESIGN_GPG_URL" ] && [ -n "$AWS_ACCESS_KEY_ID" ]; then
pip3 install awscli
aws s3 cp "$CODESIGN_GPG_URL" signkey.asc.enc
openssl enc -d -aes-256-cbc -pbkdf2 -iter 600000 -in signkey.asc.enc -out signkey.asc -k "$CODESIGN_GPG_PASSWORD"
gpg --import signkey.asc
rm signkey.asc*
echo "CODESIGN=1" >> $GITHUB_ENV
else
echo "::warning::No signing key available, skipping code signing."
fi
env:
AWS_DEFAULT_REGION: eu-central-1
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
CODESIGN_GPG_URL: ${{ secrets.CODESIGN_GPG_URL }}
CODESIGN_GPG_PASSWORD: ${{ secrets.CODESIGN_GPG_PASSWORD }}
- name: Sign source archives
if: env.CODESIGN == '1'
run: |
for f in dist/*.{zip,tar.gz}; do
gpg --armor --local-user "$CODESIGN_GPG_IDENTITY" --output "${f}.asc" --detach-sig "$f"
done
env:
CODESIGN_GPG_IDENTITY: 68990DD0B1EDC129B856958167997E14D563DA7C
- name: Cleanup
if: env.CODESIGN == '1'
run: |
rm -rf "$HOME/.gnupg"
- name: Upload artifacts
uses: actions/upload-artifact@v4
with:
name: picard-sdist
path: dist/*
pypi-bdist:
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [macos-12, windows-2019]
python-version: ['3.9', '3.10', '3.11', '3.12']
steps:
- uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
- name: Install gettext (macOS)
if: runner.os == 'macOS'
run: |
brew install gettext
brew link gettext --force
echo "/usr/local/opt/gettext/bin" >> $GITHUB_PATH
- name: Install gettext (Windows)
if: runner.os == 'Windows'
run: |
& .\scripts\package\win-setup-gettext.ps1 `
-GettextVersion $Env:GETTEXT_VERSION -GettextSha256Sum $Env:GETTEXT_SHA256SUM
Add-Content $env:GITHUB_PATH (Join-Path -Path (Resolve-Path .) -ChildPath gettext\bin)
shell: pwsh
env:
GETTEXT_VERSION: 0.22.4
GETTEXT_SHA256SUM: 220068ac0b9e7aedda03534a3088e584640ac1e639800b3a0baa9410aa6d012a
- name: Install dependencies (Linux)
if: runner.os == 'linux'
run: |
sudo apt-get update
sudo apt-get install libegl1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
python -m pip install --upgrade setuptools wheel
pip install --upgrade -r requirements.txt
- name: Run tests
timeout-minutes: 30
run: |
python setup.py test
- name: Build Python binary distribution
run: |
python setup.py clean bdist_wheel
- name: Upload artifacts
uses: actions/upload-artifact@v4
with:
name: picard-bdist-${{ runner.os }}-${{ matrix.python-version }}
path: dist/*.whl
pypi-release:
runs-on: ubuntu-latest
if: startsWith(github.ref, 'refs/tags/')
needs:
- pypi-bdist
- pypi-sdist
environment:
name: pypi
url: https://pypi.org/p/picard
permissions:
id-token: write # required for PyPI upload
steps:
- uses: actions/download-artifact@v4
with:
pattern: picard-?dist*
path: dist/
merge-multiple: true
- name: Prepare distributions
run: |
ls -l dist/
# Remove zip source distribution (only a single sdist is allowed)
rm dist/picard-*.zip*
- name: Publish package distributions to PyPI
uses: pypa/gh-action-pypi-publish@release/v1
| 4,702
|
Python
|
.py
| 144
| 25.506944
| 123
| 0.61432
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,915
|
makeqrc.py
|
metabrainz_picard/resources/makeqrc.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2013-2014, 2018 Laurent Monin
# Copyright (C) 2014 Sophist-UK
# Copyright (C) 2016 Rahul Raturi
# Copyright (C) 2017 Sambhav Kothari
# Copyright (C) 2017 Ville Skytt√§
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""Build a Qt resources file with all png images found under images/
It will update qrc file only if images newer than it are found
"""
from distutils import log
from distutils.dep_util import newer
import fnmatch
import os
import re
def tryint(s):
try:
return int(s)
except BaseException:
return s
def natsort_key(s):
return [tryint(c) for c in re.split(r'(\d+)', s)]
def find_files(topdir, directory, patterns):
tdir = os.path.join(topdir, directory)
for root, dirs, files in os.walk(tdir):
for basename in files:
for pattern in patterns:
if fnmatch.fnmatch(basename, pattern):
filepath = os.path.join(root, basename)
filename = os.path.relpath(filepath, topdir)
yield filename
def main():
scriptdir = os.path.dirname(os.path.abspath(__file__))
topdir = os.path.abspath(os.path.join(scriptdir, ".."))
resourcesdir = os.path.join(topdir, "resources")
qrcfile = os.path.join(resourcesdir, "picard.qrc")
images = [i for i in find_files(resourcesdir, 'images', ['*.gif', '*.png'])]
newimages = 0
for filename in images:
filepath = os.path.join(resourcesdir, filename)
if newer(filepath, qrcfile):
newimages += 1
if newimages:
log.info("%d images newer than %s found" % (newimages, qrcfile))
with open(qrcfile, 'wb+') as f:
f.write(b'<!DOCTYPE RCC><RCC version="1.0">\n<qresource>\n')
for filename in sorted(images, key=natsort_key):
f.write((' <file>%s</file>\n' % filename.replace('\\', '/')).encode())
f.write(b'</qresource>\n</RCC>\n')
log.info("File %s written, %d images" % (qrcfile, len(images)))
if __name__ == "__main__":
log.set_verbosity(1)
main()
| 2,841
|
Python
|
.py
| 70
| 35.414286
| 89
| 0.669083
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,916
|
compile.py
|
metabrainz_picard/resources/compile.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2006 Lukáš Lalinský
# Copyright (C) 2013-2014, 2018 Laurent Monin
# Copyright (C) 2014 Shadab Zafar
# Copyright (C) 2016 Sambhav Kothari
# Copyright (C) 2022 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from distutils import log
from distutils.dep_util import newer
from distutils.spawn import (
DistutilsExecError,
find_executable,
spawn,
)
import os.path
def fix_qtcore_import(path):
with open(path, 'r') as f:
data = f.read()
data = data.replace('PySide6', 'PyQt6')
with open(path, 'w') as f:
f.write(data)
def main():
scriptdir = os.path.dirname(os.path.abspath(__file__))
topdir = os.path.abspath(os.path.join(scriptdir, ".."))
pyfile = os.path.join(topdir, "picard", "resources.py")
qrcfile = os.path.join(topdir, "resources", "picard.qrc")
if newer(qrcfile, pyfile):
rcc = 'rcc'
rcc_path = find_executable(rcc, path='/usr/lib/qt6/libexec/') or find_executable(rcc)
if rcc_path is None:
log.error("%s command not found, cannot build resource file !", rcc)
else:
cmd = [rcc_path, '-g', 'python', '-o', pyfile, qrcfile]
try:
spawn(cmd, search_path=0)
fix_qtcore_import(pyfile)
except DistutilsExecError as e:
log.error(e)
if __name__ == "__main__":
log.set_verbosity(1)
main()
| 2,180
|
Python
|
.py
| 58
| 33.017241
| 93
| 0.68072
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,917
|
__init__.py
|
metabrainz_picard/resources/__init__.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2013 Laurent Monin
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
| 819
|
Python
|
.py
| 19
| 42.105263
| 80
| 0.77375
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,918
|
edit-copy@2x.png
|
metabrainz_picard/resources/images/16x16/edit-copy@2x.png
|
‰PNG
IHDR @ @ �·�ì pHYs J J5ȧŸ tEXtSoftware www.inkscape.org›î< PLTE ÿÿÿèèèYYsUamêêßU^qcq�guŠììàn} îëßïëßïëŞ@EUU^sBHYT^s?FVAHYT^tt{‰U^zVa{dp“gt—R[tT^s¾@FVT^s_j‡alˆen~gs”iv˜lu…q§†—ËÁÁ¾ÕĞ»Öм×Ò¾ÙÓÀÚÕÂÚ×ÃÛÖÂÛ×ÄİÙÆİÙÇŞÙÇßÚÈßÚÉàÛÉáÜÊáİËâİÌâŞÍãŞÎãßÎäàĞåàĞåàÑåáÑæáÑæâÒæãÓçâÒçãÓèãÕèäÔèäÕéå×êäÖêæ×ëæØëçØëçÙëèÙìèÚìéÛíéÛíéÜîêÜîêİîêŞîëİïêİïëŞÇı tRNS $%)3X~³¿ÁÂÅÉËËËÛÛÛÜŞùıí=—Ù IDATXÃc`À„d!€��(ÀÂ\` 5@ ÂeG(`Æf€ˆ(«��Ô 1W ¡€ŸNHˆC€$¹ z Š
Èo A0jÀ¨ô7@Qˆr¢F|¨G¬£ ÜáÀ)ˆ<4�€!„ØXÂ�•ÏĞÄğ@ ˆ8¼45p3¢46ÂÜFJRö××A =çÃĞPÏ�(|µµ�€]„ƒnXˆ„c=R1ÄÜğ ½<@¦Äy!À)±fk‰Xye€'îX0!ή8€{ÈP‰/$Gã0@P;�AD#༠jÁÊ̽È0€¨05€†póL [ ‡ÓSZ IEND®B`‚
| 718
|
Python
|
.py
| 3
| 238.333333
| 710
| 0.604749
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,919
|
edit-copy.svg
|
metabrainz_picard/resources/img-src/edit-copy.svg
|
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
version="1.1"
id="Capa_1"
x="0px"
y="0px"
viewBox="0 0 58 58"
style="enable-background:new 0 0 58 58;"
xml:space="preserve"
sodipodi:docname="edit-copy.svg"
inkscape:version="1.0.1 (3bc2e813f5, 2020-09-07)"><metadata
id="metadata71"><rdf:RDF><cc:Work
rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" /><dc:title></dc:title></cc:Work></rdf:RDF></metadata><defs
id="defs69">
</defs><sodipodi:namedview
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1"
objecttolerance="10"
gridtolerance="10"
guidetolerance="10"
inkscape:pageopacity="0"
inkscape:pageshadow="2"
inkscape:window-width="1848"
inkscape:window-height="1016"
id="namedview67"
showgrid="false"
inkscape:zoom="7.4310345"
inkscape:cx="18.432788"
inkscape:cy="25.472802"
inkscape:window-x="72"
inkscape:window-y="27"
inkscape:window-maximized="1"
inkscape:current-layer="Capa_1" />
<g
id="g115"
transform="matrix(0.85892673,0,0,0.85892673,0.28214655,0)"><polygon
style="fill:#545e73"
points="2,58 49,58 49,2 34,2 30,2 30,5 21,5 21,2 17,2 2,2 "
id="polygon2" /><rect
x="21"
style="fill:#404656"
width="9"
height="5"
id="rect4"
y="0" /><polygon
style="fill:#8697cb"
points="37,2 30,2 30,5 21,5 21,2 14,2 14,8 37,8 "
id="polygon8" /></g><g
id="g972"
transform="matrix(0.90104204,0,0,0.90104204,5.5687605,5.6041745)"><rect
id="rect137"
width="36"
height="43.902"
x="20.274"
y="12.729869"
style="fill:#efebde;fill-opacity:1;stroke-width:1.244;stroke-miterlimit:4;stroke-dasharray:none" /><g
id="g82"
transform="matrix(0.87804878,0,0,0.87804878,15.883756,8.3396248)"><path
style="fill:#d5d0bb"
d="M 24,16 H 11 c -0.553,0 -1,-0.447 -1,-1 0,-0.553 0.447,-1 1,-1 h 13 c 0.553,0 1,0.447 1,1 0,0.553 -0.447,1 -1,1 z"
id="path10" /><path
style="fill:#d5d0bb"
d="M 24,47 H 11 c -0.553,0 -1,-0.447 -1,-1 0,-0.553 0.447,-1 1,-1 h 13 c 0.553,0 1,0.447 1,1 0,0.553 -0.447,1 -1,1 z"
id="path12" /><path
style="fill:#d5d0bb"
d="M 40,22 H 11 c -0.553,0 -1,-0.447 -1,-1 0,-0.553 0.447,-1 1,-1 h 29 c 0.553,0 1,0.447 1,1 0,0.553 -0.447,1 -1,1 z"
id="path14" /><path
style="fill:#d5d0bb"
d="M 40,34 H 11 c -0.553,0 -1,-0.447 -1,-1 0,-0.553 0.447,-1 1,-1 h 29 c 0.553,0 1,0.447 1,1 0,0.553 -0.447,1 -1,1 z"
id="path16" /><path
style="fill:#d5d0bb"
d="M 40,41 H 11 c -0.553,0 -1,-0.447 -1,-1 0,-0.553 0.447,-1 1,-1 h 29 c 0.553,0 1,0.447 1,1 0,0.553 -0.447,1 -1,1 z"
id="path18" /><path
style="fill:#d5d0bb"
d="M 25,28 H 11 c -0.553,0 -1,-0.447 -1,-1 0,-0.553 0.447,-1 1,-1 h 14 c 0.553,0 1,0.447 1,1 0,0.553 -0.447,1 -1,1 z"
id="path20" /><path
style="fill:#d5d0bb"
d="m 40,28 h -7 c -0.553,0 -1,-0.447 -1,-1 0,-0.553 0.447,-1 1,-1 h 7 c 0.553,0 1,0.447 1,1 0,0.553 -0.447,1 -1,1 z"
id="path22" /><path
style="fill:#d5d0bb"
d="M 29,28 C 28.729,28 28.479,27.899 28.29,27.71 28.109,27.52 28,27.26 28,27 c 0,-0.271 0.1,-0.521 0.29,-0.71 0.38,-0.38 1.04,-0.37 1.42,0 0.189,0.189 0.29,0.439 0.29,0.71 0,0.27 -0.11,0.52 -0.29,0.71 C 29.52,27.89 29.27,28 29,28 Z"
id="path24" /></g></g><g
id="g32">
</g>
<g
id="g36">
</g>
<g
id="g38">
</g>
<g
id="g40">
</g>
<g
id="g42">
</g>
<g
id="g44">
</g>
<g
id="g46">
</g>
<g
id="g48">
</g>
<g
id="g50">
</g>
<g
id="g52">
</g>
<g
id="g54">
</g>
<g
id="g56">
</g>
<g
id="g58">
</g>
<g
id="g60">
</g>
<g
id="g62">
</g>
<g
id="g64">
</g>
</svg>
| 4,187
|
Python
|
.py
| 139
| 25.496403
| 239
| 0.586103
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,920
|
profile.py
|
metabrainz_picard/picard/profile.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2021 Vladislav Karbovskii
# Copyright (C) 2021-2023 Bob Swift
# Copyright (C) 2021-2023 Philipp Wolfer
# Copyright (C) 2021-2024 Laurent Monin
# Copyright (C) 2022 Marcin Szalowicz
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from collections import (
defaultdict,
namedtuple,
)
SettingDesc = namedtuple('SettingDesc', ('name', 'highlights'))
_settings_groups = {}
_groups_order = defaultdict(lambda: -1)
_groups_count = 0
_known_settings = set()
def profile_groups_order(group):
global _groups_count
if _groups_order[group] == -1:
_groups_order[group] = _groups_count
_groups_count += 1
def profile_groups_add_setting(group, option_name, highlights, title=None):
if group not in _settings_groups:
_settings_groups[group] = {'title': title or group}
if 'settings' not in _settings_groups[group]:
_settings_groups[group]['settings'] = []
_settings_groups[group]['settings'].append(SettingDesc(option_name, highlights))
_known_settings.add(option_name)
def profile_groups_all_settings():
return _known_settings
def profile_groups_settings(group):
if group in _settings_groups:
if 'settings' in _settings_groups[group]:
yield from _settings_groups[group]['settings']
def profile_groups_keys():
"""Iterable of all setting groups keys.
Yields:
str: Key
"""
yield from _settings_groups.keys()
def profile_groups_group_from_page(page):
try:
return _settings_groups[page.NAME]
except (AttributeError, KeyError):
return None
def profile_groups_values():
"""Returns values sorted by (groups_order, group name)"""
for k in sorted(_settings_groups, key=lambda k: (_groups_order[k], k)):
yield _settings_groups[k]
def profile_groups_reset():
"""Used when testing"""
global _settings_groups, _groups_order, _groups_count, _known_settings
_settings_groups = {}
_groups_order = defaultdict(lambda: -1)
_groups_count = 0
_known_settings = set()
| 2,785
|
Python
|
.py
| 72
| 34.875
| 84
| 0.715347
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,921
|
item.py
|
metabrainz_picard/picard/item.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2006-2007 Lukáš Lalinský
# Copyright (C) 2010, 2018, 2020-2022 Philipp Wolfer
# Copyright (C) 2011-2012 Michael Wiencek
# Copyright (C) 2012 Chad Wilson
# Copyright (C) 2013, 2020-2021, 2023-2024 Laurent Monin
# Copyright (C) 2014 Sophist-UK
# Copyright (C) 2021 Gabriel Ferreira
# Copyright (C) 2021 Petit Minion
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from collections import Counter
from PyQt6 import QtCore
from picard import log
from picard.config import get_config
from picard.i18n import ngettext
from picard.metadata import Metadata
from picard.util import IgnoreUpdatesContext
from picard.util.imagelist import ImageList
class Item:
def __init__(self):
self.ui_item = None
@property
def can_save(self):
"""Return if this object can be saved."""
return False
@property
def can_remove(self):
"""Return if this object can be removed."""
return False
@property
def can_edit_tags(self):
"""Return if this object supports tag editing."""
return False
@property
def can_analyze(self):
"""Return if this object can be fingerprinted."""
return False
@property
def can_autotag(self):
"""Return if this object can be autotagged."""
return False
@property
def can_refresh(self):
"""Return if this object can be refreshed."""
return False
@property
def can_view_info(self):
return False
@property
def can_submit(self):
"""Return True if this object can be submitted to MusicBrainz.org."""
return False
@property
def can_show_coverart(self):
"""Return if this object supports cover art."""
return self.can_edit_tags
@property
def can_browser_lookup(self):
return True
@property
def is_album_like(self):
return False
@property
def can_link_fingerprint(self):
"""Return True if this item can provide a recording ID for linking to AcoustID."""
return False
def load(self, priority=False, refresh=False):
pass
@property
def tracknumber(self):
"""The track number as an int."""
try:
return int(self.metadata['tracknumber'])
except BaseException:
return 0
@property
def discnumber(self):
"""The disc number as an int."""
try:
return int(self.metadata['discnumber'])
except BaseException:
return 0
@property
def errors(self):
if not hasattr(self, '_errors'):
self._errors = []
return self._errors
def error_append(self, msg):
log.error("%r: %s", self, msg)
self.errors.append(msg)
def clear_errors(self):
self._errors = []
@property
def _images(self):
return self.metadata.images
def cover_art_description(self):
"""Return the number of cover art images for display in the UI
Returns:
A string with the cover art image count, or empty string if not applicable
"""
if not self.can_show_coverart:
return ''
return str(len(self._images))
def cover_art_description_detailed(self):
"""Return a detailed text about the images and whether they are the same across
all tracks for images in `images` for display in the UI
Returns:
A string explaining the cover art image count.
"""
if not self.can_show_coverart:
return ''
number_of_images = len(self._images)
if getattr(self, 'has_common_images', True):
return ngettext("%i image", "%i images",
number_of_images) % number_of_images
else:
return ngettext("%i image not in all tracks", "%i different images among tracks",
number_of_images) % number_of_images
def cover_art_dimensions(self):
front_image = self.metadata.images.get_front_image()
if front_image:
return front_image.dimensions_as_string()
return ''
class ImageListState:
def __init__(self):
self.images = {}
self.has_common_images = True
self.first_obj = True
def process_images(self, src_obj_metadata):
src_dict = src_obj_metadata.images.hash_dict()
prev_len = len(self.images)
self.images.update(src_dict)
if len(self.images) != prev_len:
if not self.first_obj:
self.has_common_images = False
if self.first_obj:
self.first_obj = False
class MetadataItem(QtCore.QObject, Item):
metadata_images_changed = QtCore.pyqtSignal()
def __init__(self, obj_id=None):
super().__init__()
self.id = obj_id
self.metadata = Metadata()
self.orig_metadata = Metadata()
self.update_children_metadata_attrs = {}
self.iter_children_items_metadata_ignore_attrs = {}
self.suspend_metadata_images_update = IgnoreUpdatesContext()
self._genres = Counter()
@property
def tagger(self):
return QtCore.QCoreApplication.instance()
@tagger.setter
def tagger(self, value):
# We used to set tagger property in subclasses, but that's not needed anymore
assert value == QtCore.QCoreApplication.instance()
import inspect
stack = inspect.stack()
f = stack[1]
log.warning("MetadataItem.tagger property set at %s:%d in %s", f.filename, f.lineno, f.function)
def update_metadata_images(self):
if not self.suspend_metadata_images_update and self.can_show_coverart:
if self.update_metadata_images_from_children():
self.metadata_images_changed.emit()
def keep_original_images(self):
with self.suspend_metadata_images_update:
for file in list(self.files):
if file.can_show_coverart:
file.keep_original_images()
self.update_metadata_images()
def children_metadata_items(self):
"""Yield MetadataItems that are children of the current object"""
def iter_children_items_metadata(self, metadata_attr):
for s in self.children_metadata_items():
if metadata_attr in s.iter_children_items_metadata_ignore_attrs:
continue
yield getattr(s, metadata_attr)
@staticmethod
def get_sources_metadata_images(sources_metadata):
images = set()
for s in sources_metadata:
images = images.union(s.images)
return images
def remove_metadata_images_from_children(self, removed_sources):
"""Remove the images in the metadata of `removed_sources` from the metadata.
Args:
removed_sources: List of child objects (`Track` or `File`) which's metadata images should be removed from
"""
changed = False
for metadata_attr in self.update_children_metadata_attrs:
removed_images = self.get_sources_metadata_images(getattr(s, metadata_attr) for s in removed_sources)
sources_metadata = list(self.iter_children_items_metadata(metadata_attr))
metadata = getattr(self, metadata_attr)
changed |= metadata.remove_images(sources_metadata, removed_images)
return changed
def add_metadata_images_from_children(self, added_sources):
"""Add the images in the metadata of `added_sources` to the metadata.
Args:
added_sources: List of child objects (`Track` or `File`) which's metadata images should be added to current object
"""
changed = False
for metadata_attr in self.update_children_metadata_attrs:
added_images = self.get_sources_metadata_images(getattr(s, metadata_attr) for s in added_sources)
metadata = getattr(self, metadata_attr)
changed |= metadata.add_images(added_images)
return changed
def update_metadata_images_from_children(self):
"""Update the metadata images of the current object based on its children.
Based on the type of the current object, this will update `self.metadata.images` to
represent the metadata images of all children (`Track` or `File` objects).
This method will iterate over all children and completely rebuild
`self.metadata.images`. Whenever possible the more specific functions
`add_metadata_images_from_children` or `remove_metadata_images_from_children` should be used.
Returns:
bool: True, if images where changed, False otherwise
"""
changed = False
for metadata_attr in self.update_children_metadata_attrs:
state = ImageListState()
for src_obj_metadata in self.iter_children_items_metadata(metadata_attr):
state.process_images(src_obj_metadata)
updated_images = ImageList(state.images.values())
metadata = getattr(self, metadata_attr)
changed |= set(updated_images.hash_dict()) != set(metadata.images.hash_dict())
metadata.images = updated_images
metadata.has_common_images = state.has_common_images
return changed
@property
def genres(self):
return self._genres
def add_genre(self, name, count):
if name:
self._genres[name] += count
@staticmethod
def set_genre_inc_params(inc, config=None):
require_authentication = False
config = config or get_config()
if config.setting['use_genres']:
use_folksonomy = config.setting['folksonomy_tags']
if config.setting['only_my_genres']:
require_authentication = True
inc |= {'user-tags'} if use_folksonomy else {'user-genres'}
else:
inc |= {'tags'} if use_folksonomy else {'genres'}
return require_authentication
class FileListItem(MetadataItem):
def __init__(self, obj_id=None, files=None):
super().__init__(obj_id)
self.files = files or []
self.update_children_metadata_attrs = {'metadata', 'orig_metadata'}
def iterfiles(self, save=False):
yield from self.files
def children_metadata_items(self):
yield from self.files
| 11,112
|
Python
|
.py
| 269
| 33.089219
| 126
| 0.650297
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,922
|
releasegroup.py
|
metabrainz_picard/picard/releasegroup.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2012-2013 Michael Wiencek
# Copyright (C) 2013, 2018-2020, 2023-2024 Laurent Monin
# Copyright (C) 2014, 2017 Sophist-UK
# Copyright (C) 2017 Wieland Hoffmann
# Copyright (C) 2017-2018 Sambhav Kothari
# Copyright (C) 2018 Vishal Choudhary
# Copyright (C) 2019, 2021-2022 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from collections import defaultdict
from functools import partial
from itertools import combinations
import traceback
from picard import log
from picard.i18n import (
N_,
gettext as _,
pgettext_attributes,
)
from picard.item import MetadataItem
from picard.mbjson import (
countries_from_node,
label_info_from_node,
media_formats_from_node,
)
from picard.util import (
countries_shortlist,
uniqify,
)
VERSIONS_MAX_TRACKS = 10
VERSIONS_NAME_KEYS = ('tracks', 'year', 'country', 'format', 'label', 'catnum')
VERSIONS_HEADINGS = {
'tracks': N_("Tracks"),
'year': N_("Year"),
'country': N_("Country"),
'format': N_("Format"),
'label': N_("Label"),
'catnum': N_("Cat No"),
}
# additional keys displayed only for disambiguation
VERSIONS_EXTRA_HEADINGS = {
'packaging': N_("Packaging"),
'barcode': N_("Barcode"),
'disambiguation': N_("Disambiguation"),
}
VERSIONS_EXTRA_KEYS = ('packaging', 'barcode', 'disambiguation')
def prepare_releases_for_versions(releases):
for node in releases:
labels, catnums = label_info_from_node(node['label-info'])
countries = countries_from_node(node)
if countries:
country_label = countries_shortlist(countries)
else:
country_label = node.get('country', '') or '??'
if len(node['media']) > VERSIONS_MAX_TRACKS:
tracks = "+".join(str(m['track-count']) for m in node['media'][:VERSIONS_MAX_TRACKS]) + '+…'
else:
tracks = "+".join(str(m['track-count']) for m in node['media'])
formats = []
for medium in node['media']:
if 'format' in medium:
formats.append(medium['format'])
yield {
'id': node['id'],
'year': node['date'][:4] if 'date' in node else '????',
'country': country_label,
'format': media_formats_from_node(node['media']),
'label': ', '.join(' '.join(x.split(' ')[:2]) for x in set(labels)),
'catnum': ', '.join(set(catnums)),
'tracks': tracks,
'barcode': node.get('barcode', '') or _('[no barcode]'),
'packaging': pgettext_attributes('release_packaging', node.get('packaging', '') or '??'),
'disambiguation': node.get('disambiguation', ''),
'_disambiguate_name': list(),
'totaltracks': sum(m['track-count'] for m in node['media']),
'countries': countries,
'formats': formats,
}
class ReleaseGroup(MetadataItem):
def __init__(self, rg_id):
super().__init__(rg_id)
self.loaded = False
self.versions = []
self.version_headings = " / ".join(_(VERSIONS_HEADINGS[k]) for k in VERSIONS_NAME_KEYS)
self.loaded_albums = set()
self.refcount = 0
self.versions_count = None
def load_versions(self, callback):
kwargs = {'release-group': self.id, 'limit': 100}
self.tagger.mb_api.browse_releases(partial(self._request_finished, callback), **kwargs)
def _parse_versions(self, document):
"""Parse document and return a list of releases"""
del self.versions[:]
try:
releases = document['releases']
except (TypeError, KeyError):
return
self.versions_count = document.get('release-count', None)
versions = defaultdict(list)
# Group versions by same display name
for release in prepare_releases_for_versions(releases):
name = " / ".join(release[k] for k in VERSIONS_NAME_KEYS)
if name == release['tracks']:
name = "%s / %s" % (_('[no release info]'), name)
versions[name].append(release)
# de-duplicate names if possible
for name in versions:
for a, b in combinations(versions[name], 2):
for key in VERSIONS_EXTRA_KEYS:
(value1, value2) = (a[key], b[key])
if value1 != value2:
a['_disambiguate_name'].append(value1)
b['_disambiguate_name'].append(value2)
# build the final list of versions, using the disambiguation if needed
for name in versions:
for release in versions[name]:
dis = " / ".join(filter(None, uniqify(release['_disambiguate_name'])))
disname = name if not dis else name + ' / ' + dis
extra = "\n".join(
"%s: %s" % (_(VERSIONS_EXTRA_HEADINGS[k]), release[k])
for k in VERSIONS_EXTRA_KEYS if release[k]
)
version = {
'id': release['id'],
'name': disname.replace("&", "&&"),
'totaltracks': release['totaltracks'],
'countries': release['countries'],
'formats': release['formats'],
'extra': extra,
}
self.versions.append(version)
def _request_finished(self, callback, document, http, error):
try:
if error:
log.error("%r", http.errorString())
else:
try:
self._parse_versions(document)
except BaseException:
error = True
log.error(traceback.format_exc())
finally:
self.loaded = True
callback()
def remove_album(self, album_id):
self.loaded_albums.discard(album_id)
self.refcount -= 1
if self.refcount == 0:
del self.tagger.release_groups[self.id]
| 6,773
|
Python
|
.py
| 165
| 32.230303
| 106
| 0.588673
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,923
|
cluster.py
|
metabrainz_picard/picard/cluster.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2004 Robert Kaye
# Copyright (C) 2006-2008, 2011 Lukáš Lalinský
# Copyright (C) 2008 Hendrik van Antwerpen
# Copyright (C) 2008 Will
# Copyright (C) 2010-2011, 2014, 2018-2024 Philipp Wolfer
# Copyright (C) 2011-2013 Michael Wiencek
# Copyright (C) 2012 Chad Wilson
# Copyright (C) 2012 Wieland Hoffmann
# Copyright (C) 2013-2015, 2018-2021, 2023-2024 Laurent Monin
# Copyright (C) 2014, 2017 Sophist-UK
# Copyright (C) 2016 Rahul Raturi
# Copyright (C) 2016-2017 Sambhav Kothari
# Copyright (C) 2017 Antonio Larrosa
# Copyright (C) 2018 Vishal Choudhary
# Copyright (C) 2020 Gabriel Ferreira
# Copyright (C) 2020 Ray Bouchard
# Copyright (C) 2021 Petit Minion
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from collections import (
Counter,
defaultdict,
)
from operator import attrgetter
import re
from picard.config import get_config
from picard.file import File
from picard.i18n import (
N_,
gettext as _,
)
from picard.item import (
FileListItem,
Item,
)
from picard.metadata import SimMatchRelease
from picard.track import Track
from picard.util import (
album_artist_from_path,
find_best_match,
format_time,
)
from picard.ui.enums import MainAction
# Weights for different elements when comparing a cluster to a release
CLUSTER_COMPARISON_WEIGHTS = {
'album': 17,
'albumartist': 6,
'date': 4,
'format': 2,
'releasecountry': 2,
'releasetype': 10,
'totalalbumtracks': 5,
}
class FileList(FileListItem):
def __init__(self, files=None):
super().__init__(files=files)
if self.files and self.can_show_coverart:
for file in self.files:
file.metadata_images_changed.connect(self.update_metadata_images)
self.update_metadata_images_from_children()
def update(self, signal=True):
pass
@property
def can_show_coverart(self):
return True
class Cluster(FileList):
def __init__(self, name, artist="", special=False, related_album=None, hide_if_empty=False):
super().__init__()
self.metadata['album'] = name
self.metadata['albumartist'] = artist
self.metadata['totaltracks'] = 0
self.special = special
self.hide_if_empty = hide_if_empty
self.related_album = related_album
self.lookup_task = None
def __repr__(self):
if self.related_album:
return '<Cluster %s %r>' % (
self.related_album.id,
self.related_album.metadata['album'] + '/' + self.metadata['album']
)
return '<Cluster %r>' % self.metadata['album']
def __len__(self):
return len(self.files)
@property
def album(self):
return self.related_album
def _update_related_album(self, added_files=None, removed_files=None):
if self.related_album:
if added_files:
self.related_album.add_metadata_images_from_children(added_files)
if removed_files:
self.related_album.remove_metadata_images_from_children(removed_files)
self.related_album.update()
def add_files(self, files, new_album=True):
added_files = set(files) - set(self.files)
if not added_files:
return
for file in added_files:
self.metadata.length += file.metadata.length
file._move(self)
file.update(signal=False)
if self.can_show_coverart:
file.metadata_images_changed.connect(self.update_metadata_images)
added_files = sorted(added_files, key=attrgetter('discnumber', 'tracknumber', 'base_filename'))
self.files.extend(added_files)
self.update(signal=False)
if self.can_show_coverart:
self.add_metadata_images_from_children(added_files)
self.ui_item.add_files(added_files)
if new_album:
self._update_related_album(added_files=added_files)
def add_file(self, file, new_album=True):
self.add_files([file], new_album=new_album)
def remove_file(self, file, new_album=True):
self.tagger.window.set_processing(True)
self.metadata.length -= file.metadata.length
self.files.remove(file)
self.update(signal=False)
self.ui_item.remove_file(file)
if self.can_show_coverart:
file.metadata_images_changed.disconnect(self.update_metadata_images)
self.remove_metadata_images_from_children([file])
if new_album:
self._update_related_album(removed_files=[file])
self.tagger.window.set_processing(False)
if not self.special and self.get_num_files() == 0:
self.tagger.remove_cluster(self)
def update(self, signal=True):
self.metadata['~totalalbumtracks'] = self.metadata['totaltracks'] = len(self.files)
if signal and self.ui_item:
self.ui_item.update()
def get_num_files(self):
return len(self.files)
@property
def can_save(self):
"""Return if this object can be saved."""
return bool(self.files)
@property
def can_remove(self):
"""Return if this object can be removed."""
return not self.special
@property
def can_edit_tags(self):
"""Return if this object supports tag editing."""
return True
@property
def can_analyze(self):
"""Return if this object can be fingerprinted."""
return any(_file.can_analyze for _file in self.files)
@property
def can_autotag(self):
return True
@property
def can_refresh(self):
return False
@property
def can_browser_lookup(self):
return not self.special
@property
def can_view_info(self):
return bool(self.files)
@property
def can_submit(self):
return not self.special and bool(self.files)
@property
def is_album_like(self):
return True
def column(self, column):
if column == 'title':
return '%s (%d)' % (self.metadata['album'], len(self.files))
elif self.special and column in {'~length', 'album', 'covercount'}:
return ''
elif column == '~length':
return format_time(self.metadata.length)
elif column == 'artist':
return self.metadata['albumartist']
elif column == 'tracknumber':
return self.metadata['totaltracks']
elif column == 'discnumber':
return self.metadata['totaldiscs']
elif column == 'covercount':
return self.cover_art_description()
elif column == 'coverdimensions':
return self.cover_art_dimensions()
return self.metadata[column]
def _lookup_finished(self, document, http, error):
self.lookup_task = None
try:
releases = document['releases']
except (KeyError, TypeError):
releases = None
def statusbar(message):
self.tagger.window.set_statusbar_message(
message,
{'album': self.metadata['album']},
timeout=3000
)
best_match_release = None
if releases:
config = get_config()
best_match_release = self._match_to_release(releases, threshold=config.setting['cluster_lookup_threshold'])
if best_match_release:
statusbar(N_("Cluster %(album)s identified!"))
self.tagger.move_files_to_album(self.files, best_match_release['id'])
else:
statusbar(N_("No matching releases for cluster %(album)s"))
def _match_to_release(self, releases, threshold=0):
# multiple matches -- calculate similarities to each of them
def candidates():
for release in releases:
match_ = self.metadata.compare_to_release(release, CLUSTER_COMPARISON_WEIGHTS)
if match_.similarity >= threshold:
yield match_
no_match = SimMatchRelease(similarity=-1, release=None)
best_match = find_best_match(candidates(), no_match)
return best_match.result.release
def lookup_metadata(self):
"""Try to identify the cluster using the existing metadata."""
if self.lookup_task:
return
self.tagger.window.set_statusbar_message(
N_("Looking up the metadata for cluster %(album)s…"),
{'album': self.metadata['album']}
)
config = get_config()
self.lookup_task = self.tagger.mb_api.find_releases(self._lookup_finished,
artist=self.metadata['albumartist'],
release=self.metadata['album'],
tracks=str(len(self.files)),
limit=config.setting['query_limit'])
def clear_lookup_task(self):
if self.lookup_task:
self.tagger.webservice.remove_task(self.lookup_task)
self.lookup_task = None
@staticmethod
def cluster(files):
"""Group the provided files into clusters, based on album tag in metadata.
Args:
files: List of File objects.
Yields:
FileCluster objects
"""
config = get_config()
various_artists = config.setting['va_name']
cluster_list = defaultdict(FileCluster)
for file in files:
# If the file is attached to a track we should use the original
# metadata for clustering. This is often used by users when moving
# mismatched files back from the right pane to the left.
if isinstance(file.parent_item, Track):
metadata = file.orig_metadata
else:
metadata = file.metadata
artist = metadata['albumartist'] or metadata['artist']
album = metadata['album']
# Improve clustering from directory structure if no existing tags
# Only used for grouping and to provide cluster title / artist - not added to file tags.
album, artist = album_artist_from_path(file.filename, album, artist)
token = tokenize(album)
if token:
cluster_list[token].add(album, artist or various_artists, file)
yield from cluster_list.values()
class UnclusteredFiles(Cluster):
"""Special cluster for 'Unmatched Files' which have not been clustered."""
def __init__(self):
super().__init__(_("Unclustered Files"), special=True)
def add_files(self, files, new_album=True):
super().add_files(files, new_album=new_album)
self.tagger.window.enable_action(MainAction.CLUSTER, self.files)
def remove_file(self, file, new_album=True):
super().remove_file(file, new_album=new_album)
self.tagger.window.enable_action(MainAction.CLUSTER, self.files)
def lookup_metadata(self):
self.tagger.autotag(self.files)
@property
def can_edit_tags(self):
return False
@property
def can_autotag(self):
return bool(self.files)
@property
def can_view_info(self):
return False
@property
def can_remove(self):
return bool(self.files)
@property
def can_show_coverart(self):
return False
class ClusterList(list, Item):
"""A list of clusters."""
def __init__(self):
super().__init__()
def __hash__(self):
return id(self)
def __bool__(self):
# An existing Item object should not be considered False, even if it
# is based on a list.
return True
def iterfiles(self, save=False):
for cluster in self:
yield from cluster.iterfiles(save)
@property
def can_save(self):
return len(self) > 0
@property
def can_analyze(self):
return any(cluster.can_analyze for cluster in self)
@property
def can_autotag(self):
return len(self) > 0
@property
def can_browser_lookup(self):
return False
def lookup_metadata(self):
for cluster in self:
cluster.lookup_metadata()
class FileCluster:
def __init__(self):
self._files = []
self._artist_counts = Counter()
self._artists = defaultdict(Counter)
self._titles = Counter()
def add(self, album, artist, file):
self._files.append(file)
token = tokenize(artist)
self._artist_counts[token] += 1
self._artists[token][artist] += 1
self._titles[album] += 1
@property
def files(self):
yield from (file for file in self._files if file.state != File.REMOVED)
@property
def artist(self):
tokenized_artist = self._artist_counts.most_common(1)[0][0]
candidates = self._artists[tokenized_artist]
return candidates.most_common(1)[0][0]
@property
def title(self):
# Find the most common title
return self._titles.most_common(1)[0][0]
_re_non_alphanum = re.compile(r'\W', re.UNICODE)
_re_spaces = re.compile(r'\s', re.UNICODE)
def tokenize(word):
word = word.lower()
token = _re_non_alphanum.sub('', word)
return token if token else _re_spaces.sub('', word)
| 13,920
|
Python
|
.py
| 364
| 30.392857
| 119
| 0.638969
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,924
|
config.py
|
metabrainz_picard/picard/config.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2006-2007, 2014, 2017 Lukáš Lalinský
# Copyright (C) 2008, 2014, 2019-2023 Philipp Wolfer
# Copyright (C) 2012, 2017 Wieland Hoffmann
# Copyright (C) 2012-2014 Michael Wiencek
# Copyright (C) 2013-2016, 2018-2024 Laurent Monin
# Copyright (C) 2016 Suhas
# Copyright (C) 2016-2018 Sambhav Kothari
# Copyright (C) 2017 Sophist-UK
# Copyright (C) 2018 Vishal Choudhary
# Copyright (C) 2020-2021 Gabriel Ferreira
# Copyright (C) 2021-2023 Bob Swift
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from collections import defaultdict
import os
import shutil
from PyQt6 import QtCore
from picard import (
PICARD_APP_NAME,
PICARD_ORG_NAME,
PICARD_VERSION,
log,
)
from picard.profile import profile_groups_all_settings
from picard.version import Version
class Memovar:
def __init__(self):
self.dirty = True
self.value = None
class ConfigUpgradeError(Exception):
pass
class ConfigSection(QtCore.QObject):
"""Configuration section."""
def __init__(self, config, name):
super().__init__()
self.__qt_config = config
self.__name = name
self.__prefix = self.__name + '/'
self._memoization = defaultdict(Memovar)
def key(self, name):
return self.__prefix + name
def __getitem__(self, name):
opt = Option.get(self.__name, name)
if opt is None:
return None
return self.value(name, opt, opt.default)
def __setitem__(self, name, value):
key = self.key(name)
self.__qt_config.setValue(key, value)
self._memoization[key].dirty = True
def __contains__(self, name):
return self.__qt_config.contains(self.key(name))
def as_dict(self):
return {
key: self[key] for section, key
in list(Option.registry)
if section == self.__name
}
def remove(self, name):
key = self.key(name)
config = self.__qt_config
if config.contains(key):
config.remove(key)
try:
del self._memoization[key]
except KeyError:
pass
def raw_value(self, name, qtype=None):
"""Return an option value without any type conversion."""
key = self.key(name)
if qtype is not None:
value = self.__qt_config.value(key, type=qtype)
else:
value = self.__qt_config.value(key)
return value
def value(self, name, option_type, default=None):
"""Return an option value converted to the given Option type."""
if name in self:
key = self.key(name)
memovar = self._memoization[key]
if memovar.dirty:
try:
value = self.raw_value(name, qtype=option_type.qtype)
value = option_type.convert(value)
memovar.dirty = False
memovar.value = value
except Exception as why:
log.error('Cannot read %s value: %s', self.key(name), why, exc_info=True)
value = default
return value
else:
return memovar.value
return default
class SettingConfigSection(ConfigSection):
"""Custom subclass to automatically accommodate saving and retrieving values based on user profile settings.
"""
PROFILES_KEY = 'user_profiles'
SETTINGS_KEY = 'user_profile_settings'
@classmethod
def init_profile_options(cls):
ListOption.add_if_missing('profiles', cls.PROFILES_KEY, [])
Option.add_if_missing('profiles', cls.SETTINGS_KEY, {})
def __init__(self, config, name):
super().__init__(config, name)
self.__qt_config = config
self.__name = name
self.__prefix = self.__name + '/'
self._memoization = defaultdict(Memovar)
self.init_profile_options()
self.profiles_override = None
self.settings_override = None
def _get_active_profile_ids(self):
if self.profiles_override is None:
profiles = self.__qt_config.profiles[self.PROFILES_KEY]
else:
profiles = self.profiles_override
if profiles is None:
return
for profile in profiles:
if profile['enabled']:
yield profile['id']
def _get_active_profile_settings(self):
for profile_id in self._get_active_profile_ids():
yield profile_id, self._get_profile_settings(profile_id)
def _get_profile_settings(self, profile_id):
if self.settings_override is None:
# Set to None if profile_id not in profile settings
profile_settings = self.__qt_config.profiles[self.SETTINGS_KEY][profile_id] if profile_id in self.__qt_config.profiles[self.SETTINGS_KEY] else None
else:
# Set to None if profile_id not in settings_override
profile_settings = self.settings_override[profile_id] if profile_id in self.settings_override else None
if profile_settings is None:
log.error("Unable to find settings for user profile '%s'", profile_id)
return {}
return profile_settings
def __getitem__(self, name):
# Don't process settings that are not profile-specific
if name in profile_groups_all_settings():
for profile_id, settings in self._get_active_profile_settings():
if name in settings and settings[name] is not None:
return settings[name]
opt = Option.get(self.__name, name)
if opt is None:
return None
return self.value(name, opt, opt.default)
def __setitem__(self, name, value):
# Don't process settings that are not profile-specific
if name in profile_groups_all_settings():
for profile_id, settings in self._get_active_profile_settings():
if name in settings:
self._save_profile_setting(profile_id, name, value)
return
key = self.key(name)
self.__qt_config.setValue(key, value)
self._memoization[key].dirty = True
def _save_profile_setting(self, profile_id, name, value):
profile_settings = self.__qt_config.profiles[self.SETTINGS_KEY]
profile_settings[profile_id][name] = value
key = self.__qt_config.profiles.key(self.SETTINGS_KEY)
self.__qt_config.setValue(key, profile_settings)
self._memoization[key].dirty = True
def set_profiles_override(self, new_profiles=None):
self.profiles_override = new_profiles
def set_settings_override(self, new_settings=None):
self.settings_override = new_settings
class Config(QtCore.QSettings):
"""Configuration.
QSettings is not thread safe, each thread must use its own instance of this class.
Use `get_config()` to obtain a Config instance for the current thread.
Changes to one Config instances are automatically available to all other instances.
Use `Config.from_app` or `Config.from_file` to obtain a new `Config` instance.
See: https://doc.qt.io/qt-5/qsettings.html#accessing-settings-from-multiple-threads-or-processes-simultaneously
"""
def __init__(self):
# Do not call `QSettings.__init__` here. The proper overloaded `QSettings.__init__`
# gets called in `from_app` or `from_config`. Only those class methods must be used
# to create a new instance of `Config`.
pass
def __initialize(self):
"""Common initializer method for :meth:`from_app` and
:meth:`from_file`."""
self.setAtomicSyncRequired(False) # See comment in event()
self.application = ConfigSection(self, 'application')
self.profiles = ConfigSection(self, 'profiles')
self.setting = SettingConfigSection(self, 'setting')
self.persist = ConfigSection(self, 'persist')
if 'version' not in self.application or not self.application['version']:
TextOption('application', 'version', '0.0.0dev0')
self._version = Version.from_string(self.application['version'])
@classmethod
def from_app(cls, parent):
"""Build a Config object using the default configuration file
location."""
this = cls()
QtCore.QSettings.__init__(this, QtCore.QSettings.Format.IniFormat,
QtCore.QSettings.Scope.UserScope, PICARD_ORG_NAME,
PICARD_APP_NAME, parent)
# Check if there is a config file specifically for this version
versioned_config_file = this._versioned_config_filename(PICARD_VERSION)
if os.path.isfile(versioned_config_file):
return cls.from_file(parent, versioned_config_file)
# If there are no settings, copy existing settings from old format
# (registry on windows systems)
if not this.allKeys():
oldFormat = QtCore.QSettings(PICARD_ORG_NAME, PICARD_APP_NAME)
for k in oldFormat.allKeys():
this.setValue(k, oldFormat.value(k))
this.sync()
this.__initialize()
this._backup_settings()
return this
@classmethod
def from_file(cls, parent, filename):
"""Build a Config object using a user-provided configuration file
path."""
this = cls()
QtCore.QSettings.__init__(this, filename, QtCore.QSettings.Format.IniFormat,
parent)
this.__initialize()
return this
def run_upgrade_hooks(self, hooks):
"""Executes passed hooks to upgrade config version to the latest"""
if self._version == Version(0, 0, 0, 'dev', 0):
# This is a freshly created config
self._write_version(PICARD_VERSION)
return
if not hooks:
return
if self._version >= PICARD_VERSION:
if self._version > PICARD_VERSION:
print("Warning: config file %s was created by a more recent "
"version of Picard (current is %s)" % (
self._version,
PICARD_VERSION
))
return
for version in list(hooks):
hook = hooks[version]
if self._version < version:
try:
if hook.__doc__:
log.debug("Config upgrade %s -> %s: %s" % (
self._version,
version,
hook.__doc__.strip()))
hook(self)
except BaseException as e:
raise ConfigUpgradeError(
"Error during config upgrade from version %s to %s "
"using %s()" % (
self._version,
version,
hook.__name__,
)) from e
else:
del hooks[version]
self._write_version(version)
else:
# hook is not applicable, mark as done
del hooks[version]
if not hooks:
# all hooks were executed, ensure config is marked with latest version
self._write_version(PICARD_VERSION)
def _backup_settings(self):
if Version(0, 0, 0) < self._version < PICARD_VERSION:
backup_path = self._versioned_config_filename()
self._save_backup(backup_path)
def _save_backup(self, backup_path):
log.info("Backing up config file to %s", backup_path)
try:
shutil.copyfile(self.fileName(), backup_path)
except OSError:
log.error("Failed backing up config file to %s", backup_path)
return False
return True
def _write_version(self, new_version):
self._version = new_version
self.application['version'] = str(self._version)
self.sync()
def _versioned_config_filename(self, version=None):
if not version:
version = self._version
return os.path.join(os.path.dirname(self.fileName()), '%s-%s.ini' % (
self.applicationName(), version.short_str()))
def save_user_backup(self, backup_path):
if backup_path == self.fileName():
log.warning("Attempt to backup configuration file to the same path.")
return False
return self._save_backup(backup_path)
class OptionError(Exception):
def __init__(self, message, section, name):
super().__init__("Option %s/%s: %s" % (section, name, message))
class Option(QtCore.QObject):
"""Generic option."""
registry = {}
qtype = None
def __init__(self, section, name, default, title=None):
key = (section, name)
if key in self.registry:
raise OptionError("Already declared", section, name)
super().__init__()
self.section = section
self.name = name
self.default = default
self.title = title
self.registry[key] = self
@classmethod
def get(cls, section, name):
return cls.registry.get((section, name))
@classmethod
def get_default(cls, section, name):
opt = cls.get(section, name)
if opt is None:
raise OptionError("No such option", section, name)
return opt.default
@classmethod
def get_title(cls, section, name):
opt = cls.get(section, name)
if opt is None:
raise OptionError("No such option", section, name)
return opt.title
@classmethod
def add_if_missing(cls, section, name, default, *args, **kwargs):
if not cls.exists(section, name):
cls(section, name, default, *args, **kwargs)
@classmethod
def exists(cls, section, name):
return (section, name) in cls.registry
def convert(self, value):
return type(self.default)(value)
class TextOption(Option):
convert = str
qtype = 'QString'
class BoolOption(Option):
convert = bool
qtype = bool
class IntOption(Option):
convert = int
class FloatOption(Option):
convert = float
class ListOption(Option):
def convert(self, value):
if value is None:
return []
elif isinstance(value, str):
raise ValueError('Expected list or list like object, got "%r"' % value)
return list(value)
config = None
setting = None
persist = None
profiles = None
def setup_config(app=None, filename=None):
if app is None:
app = QtCore.QCoreApplication.instance()
global config, setting, persist, profiles
if filename is None:
config = Config.from_app(app)
else:
config = Config.from_file(app, filename)
setting = config.setting
persist = config.persist
profiles = config.profiles
def get_config():
"""Returns a config object for the current thread.
Config objects for threads are created on demand and cached for later use.
"""
return config
def load_new_config(filename=None):
config_file = get_config().fileName()
try:
shutil.copy(filename, config_file)
except OSError:
log.error("Failed restoring config file from %s", filename)
return False
setup_config(filename=config_file)
return True
| 16,188
|
Python
|
.py
| 392
| 31.923469
| 159
| 0.615336
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,925
|
track.py
|
metabrainz_picard/picard/track.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2004 Robert Kaye
# Copyright (C) 2006-2007, 2011 Lukáš Lalinský
# Copyright (C) 2008 Gary van der Merwe
# Copyright (C) 2009 Carlin Mangar
# Copyright (C) 2010, 2014-2015, 2018-2023 Philipp Wolfer
# Copyright (C) 2011 Chad Wilson
# Copyright (C) 2011 Wieland Hoffmann
# Copyright (C) 2011-2013 Michael Wiencek
# Copyright (C) 2014, 2017 Sophist-UK
# Copyright (C) 2014-2015, 2018-2024 Laurent Monin
# Copyright (C) 2016 Mark Trolley
# Copyright (C) 2016 Rahul Raturi
# Copyright (C) 2016 Suhas
# Copyright (C) 2017 Antonio Larrosa
# Copyright (C) 2017-2018 Sambhav Kothari
# Copyright (C) 2018 Calvin Walton
# Copyright (C) 2018 Vishal Choudhary
# Copyright (C) 2019 Joel Lintunen
# Copyright (C) 2020, 2022 Adam James
# Copyright (C) 2021 Gabriel Ferreira
# Copyright (C) 2021 Petit Minion
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from collections import (
Counter,
defaultdict,
)
import re
import traceback
from PyQt6 import QtCore
from picard import log
from picard.config import get_config
from picard.const import (
DATA_TRACK_TITLE,
SILENCE_TRACK_TITLE,
VARIOUS_ARTISTS_ID,
)
from picard.file import (
run_file_post_addition_to_track_processors,
run_file_post_removal_from_track_processors,
)
from picard.i18n import gettext as _
from picard.item import (
FileListItem,
MetadataItem,
)
from picard.mbjson import recording_to_metadata
from picard.metadata import (
Metadata,
MultiMetadataProxy,
run_track_metadata_processors,
)
from picard.script import (
ScriptError,
ScriptParser,
iter_active_tagging_scripts,
)
from picard.util import pattern_as_regex
from picard.util.imagelist import ImageList
from picard.util.textencoding import asciipunct
class TagGenreFilter:
def __init__(self, filters):
self.errors = dict()
self.match_regexes = defaultdict(list)
for lineno, line in enumerate(filters.splitlines()):
line = line.strip()
if line and line[0] in {'+', '-'}:
_list = line[0]
remain = line[1:].strip()
if not remain:
continue
try:
regex_search = pattern_as_regex(remain, allow_wildcards=True, flags=re.IGNORECASE)
self.match_regexes[_list].append(regex_search)
except re.error as e:
log.error("Failed to compile regex /%s/: %s", remain, e)
self.errors[lineno] = str(e)
def skip(self, tag):
if not self.match_regexes:
return False
for regex in self.match_regexes['+']:
if regex.search(tag):
return False
for regex in self.match_regexes['-']:
if regex.search(tag):
return True
return False
def filter(self, counter: Counter, minusage=0) -> Counter:
result = Counter()
for name, count in counter.items():
if not self.skip(name):
result[name] = count
if not result:
return result
topcount = result.most_common(1)[0][1]
for name, count in counter.items():
percent = 100 * count // topcount
if percent < minusage:
del result[name]
return result
def format_errors(self):
fmt = _("Error line %(lineno)d: %(error)s")
for lineno, error in self.errors.items():
yield fmt % {'lineno': lineno + 1, 'error': error}
class TrackArtist(MetadataItem):
def __init__(self, ta_id):
super().__init__(ta_id)
class Track(FileListItem):
def __init__(self, track_id, album=None):
super().__init__(track_id)
self.album = album
self.scripted_metadata = Metadata()
self._track_artists = []
self._orig_images = None
self.iter_children_items_metadata_ignore_attrs = {'orig_metadata'}
@property
def num_linked_files(self):
return len(self.files)
def __repr__(self):
return '<Track %s %r>' % (self.id, self.metadata["title"])
def add_file(self, file, new_album=True):
track_will_expand = False
if file not in self.files:
track_will_expand = self.num_linked_files == 1
if not self.files: # The track uses original metadata from the file only
self._orig_images = self.orig_metadata.images
self.orig_metadata.images = ImageList()
self.files.append(file)
self.update_file_metadata(file)
self.add_metadata_images_from_children([file])
self.album.add_file(self, file, new_album=new_album)
file.metadata_images_changed.connect(self.update_metadata_images)
run_file_post_addition_to_track_processors(self, file)
if track_will_expand:
# Files get expanded, ensure the existing item renders correctly
self.files[0].update_item()
def update_file_metadata(self, file):
if file not in self.files:
return
# Run the scripts for the file to allow usage of
# file specific metadata and variables
config = get_config()
if config.setting['clear_existing_tags']:
metadata = Metadata(self.orig_metadata)
metadata_proxy = MultiMetadataProxy(metadata, file.metadata)
self.run_scripts(metadata_proxy)
else:
metadata = Metadata(file.metadata)
metadata.update(self.orig_metadata)
self.run_scripts(metadata)
# Apply changes to the track's metadata done manually after the scripts ran
meta_diff = self.metadata.diff(self.scripted_metadata)
metadata.update(meta_diff)
# Images are not affected by scripting, always use the tracks current images
metadata.images = self.metadata.images
file.copy_metadata(metadata)
file.update(signal=False)
self.update()
def remove_file(self, file, new_album=True):
if file not in self.files:
return
self.files.remove(file)
file.metadata_images_changed.disconnect(self.update_metadata_images)
file.copy_metadata(file.orig_metadata, preserve_deleted=False)
self.album.remove_file(self, file, new_album=new_album)
self.remove_metadata_images_from_children([file])
if not self.files and self._orig_images:
self.orig_metadata.images = self._orig_images
self.metadata.images = self._orig_images.copy()
run_file_post_removal_from_track_processors(self, file)
self.update()
if self.ui_item.isSelected():
self.tagger.window.refresh_metadatabox()
@staticmethod
def run_scripts(metadata, strip_whitespace=False):
for script in iter_active_tagging_scripts():
parser = ScriptParser()
try:
parser.eval(script.content, metadata)
except ScriptError:
log.exception("Failed to run tagger script %s on track", script.name)
if strip_whitespace:
metadata.strip_whitespace()
def update(self):
if self.ui_item:
self.ui_item.update()
def is_linked(self):
return self.num_linked_files > 0
@property
def can_save(self):
"""Return if this object can be saved."""
return any(file.can_save for file in self.files)
@property
def can_remove(self):
"""Return if this object can be removed."""
return any(file.can_remove for file in self.files)
@property
def can_edit_tags(self):
"""Return if this object supports tag editing."""
return True
@property
def can_view_info(self):
return self.num_linked_files == 1 or bool(self.metadata.images)
@property
def can_link_fingerprint(self):
"""Return True if this item can provide a recording ID for linking to AcoustID."""
return True
def column(self, column):
m = self.metadata
if column == 'title':
prefix = "%s-" % m['discnumber'] if m['discnumber'] and m['totaldiscs'] != "1" else ""
return "%s%s %s" % (prefix, m['tracknumber'].zfill(2), m['title'])
elif column == 'covercount':
return self.cover_art_description()
elif column == 'coverdimensions':
return self.cover_art_dimensions()
elif column in m:
return m[column]
elif self.num_linked_files == 1:
return self.files[0].column(column)
def is_video(self):
return self.metadata['~video'] == '1'
def is_pregap(self):
return self.metadata['~pregap'] == '1'
def is_data(self):
return self.metadata['~datatrack'] == '1'
def is_silence(self):
return self.metadata['~silence'] == '1'
def is_complete(self):
return self.ignored_for_completeness() or self.num_linked_files == 1
def ignored_for_completeness(self):
config = get_config()
if self.is_video() and config.setting['completeness_ignore_videos']:
return True
if self.is_pregap() and config.setting['completeness_ignore_pregap']:
return True
if self.is_data() and config.setting['completeness_ignore_data']:
return True
if self.is_silence() and config.setting['completeness_ignore_silence']:
return True
return False
def append_track_artist(self, ta_id):
"""Append artist id to the list of track artists
and return an TrackArtist instance"""
track_artist = TrackArtist(ta_id)
self._track_artists.append(track_artist)
return track_artist
def _customize_metadata(self):
config = get_config()
tm = self.metadata
# Custom VA name
if tm['musicbrainz_artistid'] == VARIOUS_ARTISTS_ID:
tm['artistsort'] = tm['artist'] = config.setting['va_name']
if tm['title'] == DATA_TRACK_TITLE:
tm['~datatrack'] = '1'
if tm['title'] == SILENCE_TRACK_TITLE:
tm['~silence'] = '1'
if config.setting['use_genres']:
self._convert_folksonomy_tags_to_genre()
# Convert Unicode punctuation
if config.setting['convert_punctuation']:
tm.apply_func(asciipunct)
@staticmethod
def _genres_to_metadata(genres, limit=None, minusage=0, filters='', join_with=None):
if limit is not None and limit < 1:
return []
# Ignore tags with zero or lower score
genres = +genres
if not genres:
return []
# Filter by name and usage
genres_filter = TagGenreFilter(filters)
genres = genres_filter.filter(genres, minusage=minusage)
# Find most common genres
most_common_genres = genres.most_common(limit)
genres_list = [name.title() for name, _count in most_common_genres]
genres_list.sort()
# And generate the genre metadata tag
if join_with:
return [join_with.join(genres_list)]
else:
return genres_list
def _convert_folksonomy_tags_to_genre(self):
config = get_config()
# Combine release and track genres
genres = Counter(self.genres)
genres += self.album.genres
if self.album.release_group:
genres += self.album.release_group.genres
if not genres and config.setting['artists_genres']:
# For compilations use each track's artists to look up genres
if self.metadata['musicbrainz_albumartistid'] == VARIOUS_ARTISTS_ID:
for artist in self._track_artists:
genres += artist.genres
else:
for artist in self.album.get_album_artists():
genres += artist.genres
self.metadata['genre'] = self._genres_to_metadata(
genres,
limit=config.setting['max_genres'],
minusage=config.setting['min_genre_usage'],
filters=config.setting['genres_filter'],
join_with=config.setting['join_genres']
)
class NonAlbumTrack(Track):
def __init__(self, nat_id):
tagger = QtCore.QCoreApplication.instance()
super().__init__(nat_id, tagger.nats)
self.callback = None
self.loaded = False
self.status = None
@property
def can_refresh(self):
return True
def column(self, column):
if column == "title":
if self.status is not None:
return self.status
else:
return self.metadata['title']
return super().column(column)
def load(self, priority=False, refresh=False):
self.metadata.copy(self.album.metadata, copy_images=False)
self.genres.clear()
self.status = _("[loading recording information]")
self.clear_errors()
self.loaded = False
self.album.update(update_tracks=True)
config = get_config()
require_authentication = False
inc = {
'aliases',
'artist-credits',
'artists',
}
if config.setting['track_ars']:
inc |= {
'artist-rels',
'recording-rels',
'series-rels',
'url-rels',
'work-level-rels',
'work-rels',
}
require_authentication = self.set_genre_inc_params(inc, config) or require_authentication
if config.setting['enable_ratings']:
require_authentication = True
inc |= {'user-ratings'}
self.tagger.mb_api.get_track_by_id(
self.id,
self._recording_request_finished,
inc=inc,
mblogin=require_authentication,
priority=priority,
refresh=refresh
)
@property
def can_remove(self):
return True
def _recording_request_finished(self, recording, http, error):
if error:
self._set_error(http.errorString())
return
try:
self._parse_recording(recording)
for file in self.files:
self.update_file_metadata(file)
except Exception:
self._set_error(traceback.format_exc())
def _set_error(self, error):
self.error_append(error)
self.status = _("[could not load recording %s]") % self.id
self.album.update(update_tracks=True)
def _parse_recording(self, recording):
m = self.metadata
recording_to_metadata(recording, m, self)
self._customize_metadata()
run_track_metadata_processors(self.album, m, recording)
self.orig_metadata.copy(m)
self.run_scripts(m, strip_whitespace=True)
self.loaded = True
self.status = None
if self.callback:
self.callback()
self.callback = None
self.album.update(update_tracks=True)
def _customize_metadata(self):
super()._customize_metadata()
self.metadata['album'] = self.album.metadata['album']
if self.metadata['~recording_firstreleasedate']:
self.metadata['originaldate'] = self.metadata['~recording_firstreleasedate']
self.metadata['originalyear'] = self.metadata['originaldate'][:4]
def run_when_loaded(self, func):
if self.loaded:
func()
else:
self.callback = func
| 16,266
|
Python
|
.py
| 413
| 30.607748
| 102
| 0.622332
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,926
|
plugin.py
|
metabrainz_picard/picard/plugin.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2007-2008 Lukáš Lalinský
# Copyright (C) 2009 Carlin Mangar
# Copyright (C) 2009, 2014, 2017-2021, 2023 Philipp Wolfer
# Copyright (C) 2011 johnny64
# Copyright (C) 2011-2013 Michael Wiencek
# Copyright (C) 2013 Sebastian Ramacher
# Copyright (C) 2013 Wieland Hoffmann
# Copyright (C) 2013 brainz34
# Copyright (C) 2013-2014 Sophist-UK
# Copyright (C) 2014 Johannes Dewender
# Copyright (C) 2014 Shadab Zafar
# Copyright (C) 2014-2015, 2018-2021, 2023-2024 Laurent Monin
# Copyright (C) 2016-2018 Sambhav Kothari
# Copyright (C) 2017 Frederik “Freso” S. Olesen
# Copyright (C) 2018 Vishal Choudhary
# Copyright (C) 2023 tuspar
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from collections import defaultdict
import os.path
from picard import log
from picard.config import get_config
from picard.const import USER_PLUGIN_DIR
from picard.version import (
Version,
VersionError,
)
try:
from markdown import markdown
except ImportError:
def markdown(text):
# Simple fallback, just make sure line breaks are applied
if not text:
return ''
return text.strip().replace('\n', '<br>\n')
_PLUGIN_MODULE_PREFIX = "picard.plugins."
_PLUGIN_MODULE_PREFIX_LEN = len(_PLUGIN_MODULE_PREFIX)
_extension_points = []
def _unregister_module_extensions(module):
for ep in _extension_points:
ep.unregister_module(module)
class ExtensionPoint:
def __init__(self, label=None):
if label is None:
import uuid
self.label = uuid.uuid4()
else:
self.label = label
self.__dict = defaultdict(list)
_extension_points.append(self)
def register(self, module, item):
if module.startswith(_PLUGIN_MODULE_PREFIX):
name = module[_PLUGIN_MODULE_PREFIX_LEN:]
log.debug("ExtensionPoint: %s register <- plugin=%r item=%r", self.label, name, item)
else:
name = None
# uncomment to debug internal extensions loaded at startup
# print("ExtensionPoint: %s register <- item=%r" % (self.label, item))
self.__dict[name].append(item)
def unregister_module(self, name):
try:
del self.__dict[name]
except KeyError:
# NOTE: needed due to defaultdict behaviour:
# >>> d = defaultdict(list)
# >>> del d['a']
# KeyError: 'a'
# >>> d['a']
# []
# >>> del d['a']
# >>> #^^ no exception, after first read
pass
def __iter__(self):
config = get_config()
enabled_plugins = config.setting['enabled_plugins'] if config else []
for name in self.__dict:
if name is None or name in enabled_plugins:
yield from self.__dict[name]
def __repr__(self):
return f"ExtensionPoint(label='{self.label}')"
class PluginShared:
def __init__(self):
super().__init__()
class PluginWrapper(PluginShared):
def __init__(self, module, plugindir, file=None, manifest_data=None):
super().__init__()
self.module = module
self.compatible = False
self.dir = os.path.normpath(plugindir)
self._file = file
self.data = manifest_data or self.module.__dict__
@property
def name(self):
try:
return self.data['PLUGIN_NAME']
except KeyError:
return self.module_name
@property
def module_name(self):
name = self.module.__name__
if name.startswith(_PLUGIN_MODULE_PREFIX):
name = name[_PLUGIN_MODULE_PREFIX_LEN:]
return name
@property
def author(self):
try:
return self.data['PLUGIN_AUTHOR']
except KeyError:
return ""
@property
def description(self):
try:
return markdown(self.data['PLUGIN_DESCRIPTION'])
except KeyError:
return ""
@property
def version(self):
try:
return Version.from_string(self.data['PLUGIN_VERSION'])
except (KeyError, VersionError):
return Version(0, 0, 0)
@property
def api_versions(self):
try:
return self.data['PLUGIN_API_VERSIONS']
except KeyError:
return []
@property
def file(self):
if not self._file:
return self.module.__file__
else:
return self._file
@property
def license(self):
try:
return self.data['PLUGIN_LICENSE']
except KeyError:
return ""
@property
def license_url(self):
try:
return self.data['PLUGIN_LICENSE_URL']
except KeyError:
return ""
@property
def user_guide_url(self):
try:
return self.data['PLUGIN_USER_GUIDE_URL']
except KeyError:
return ""
@property
def files_list(self):
return self.file[len(self.dir)+1:]
@property
def is_user_installed(self):
return self.dir == USER_PLUGIN_DIR
class PluginData(PluginShared):
"""Used to store plugin data from JSON API"""
def __init__(self, d, module_name):
self.__dict__ = d
super().__init__()
self.module_name = module_name
def __getattribute__(self, name):
try:
return super().__getattribute__(name)
except AttributeError:
log.debug("Attribute %r not found for plugin %r", name, self.module_name)
return None
@property
def version(self):
try:
return Version.from_string(self.__dict__['version'])
except (KeyError, VersionError):
return Version(0, 0, 0)
@property
def files_list(self):
return ", ".join(self.files.keys())
class PluginFunctions:
"""
Store ExtensionPoint in a defaultdict with priority as key
run() method will execute entries with higher priority value first
"""
def __init__(self, label=None):
self.functions = defaultdict(lambda: ExtensionPoint(label=label))
def register(self, module, item, priority=0):
self.functions[priority].register(module, item)
def _get_functions(self):
"""Returns registered functions by order of priority (highest first) and registration"""
for priority, functions in sorted(self.functions.items(),
key=lambda i: i[0],
reverse=True):
yield from functions
def run(self, *args, **kwargs):
"""Execute registered functions with passed parameters honouring priority"""
for function in self._get_functions():
function(*args, **kwargs)
| 7,516
|
Python
|
.py
| 213
| 27.71831
| 97
| 0.624172
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,927
|
similarity.py
|
metabrainz_picard/picard/similarity.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2006-2007 Lukáš Lalinský
# Copyright (C) 2008 Will
# Copyright (C) 2011-2012 Michael Wiencek
# Copyright (C) 2013, 2018-2021 Laurent Monin
# Copyright (C) 2017 Sambhav Kothari
# Copyright (C) 2017 Ville Skyttä
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import re
from picard.util import strip_non_alnum
from picard.util.astrcmp import astrcmp
def normalize(orig_string):
"""Strips non-alphanumeric characters from a string unless doing so would make it blank."""
string = strip_non_alnum(orig_string.lower())
if not string:
string = orig_string
return string
def similarity(a1, b1):
"""Calculates similarity of single words as a function of their edit distance."""
a2 = normalize(a1)
if a2:
b2 = normalize(b1)
else:
b2 = ""
return astrcmp(a2, b2)
_split_words_re = re.compile(r'\W+', re.UNICODE)
def similarity2(a, b):
"""Calculates similarity of a multi-word strings."""
if not a or not b:
return 0.0
if a == b:
return 1.0
alist = list(filter(bool, _split_words_re.split(a.lower())))
blist = list(filter(bool, _split_words_re.split(b.lower())))
alen, blen = len(alist), len(blist)
if not alen or not blen:
return 0.0
if alen > blen:
alist, blist = blist, alist
alen, blen = blen, alen
score = 0.0
for av in alist:
ms = 0.0
mp = None
for position, bv in enumerate(blist):
s = astrcmp(av, bv)
if s > ms:
ms = s
mp = position
if mp is not None:
score += ms
if ms > 0.6:
del blist[mp]
# division by zero cannot happen, alen > 0 at this point
return score / (alen + len(blist) * 0.4)
| 2,532
|
Python
|
.py
| 71
| 30.507042
| 95
| 0.665438
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,928
|
mbjson.py
|
metabrainz_picard/picard/mbjson.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2017 David Mandelberg
# Copyright (C) 2017-2018 Sambhav Kothari
# Copyright (C) 2017-2023 Laurent Monin
# Copyright (C) 2018-2023 Philipp Wolfer
# Copyright (C) 2019 Michael Wiencek
# Copyright (C) 2020 dukeyin
# Copyright (C) 2020, 2023 David Kellner
# Copyright (C) 2021 Bob Swift
# Copyright (C) 2021 Vladislav Karbovskii
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from types import SimpleNamespace
from picard import log
from picard.config import get_config
from picard.const import (
ALIAS_TYPE_ARTIST_NAME_ID,
ALIAS_TYPE_LEGAL_NAME_ID,
RELEASE_FORMATS,
)
from picard.util import (
format_time,
linear_combination_of_weights,
parse_amazon_url,
translate_from_sortname,
)
from picard.util.script_detector_weighted import detect_script_weighted
_ARTIST_REL_TYPES = {
'arranger': 'arranger',
'audio': 'engineer',
'chorus master': 'performer:chorus master',
'composer': 'composer',
'concertmaster': 'performer:concertmaster',
'conductor': 'conductor',
'engineer': 'engineer',
'instrument arranger': 'arranger',
'librettist': 'lyricist',
'live sound': 'engineer',
'lyricist': 'lyricist',
# 'mastering': 'engineer',
'mix-DJ': 'djmixer',
'mix': 'mixer',
'orchestrator': 'arranger',
'performing orchestra': 'performer:orchestra',
'producer': 'producer',
# 'recording': 'engineer',
'remixer': 'remixer',
'sound': 'engineer',
'audio director': 'director',
'video director': 'director',
'vocal arranger': 'arranger',
'writer': 'writer',
}
_TRACK_TO_METADATA = {
'number': '~musicbrainz_tracknumber',
'position': 'tracknumber',
'title': 'title',
}
_MEDIUM_TO_METADATA = {
'format': 'media',
'position': 'discnumber',
'title': 'discsubtitle',
}
_RECORDING_TO_METADATA = {
'disambiguation': '~recordingcomment',
'first-release-date': '~recording_firstreleasedate',
'title': 'title',
}
_RELEASE_TO_METADATA = {
'annotation': '~releaseannotation',
'asin': 'asin',
'barcode': 'barcode',
'country': 'releasecountry',
'date': 'date',
'disambiguation': '~releasecomment',
'title': 'album',
}
_ARTIST_TO_METADATA = {
'gender': 'gender',
'name': 'name',
'type': 'type',
}
_RELEASE_GROUP_TO_METADATA = {
'disambiguation': '~releasegroupcomment',
'first-release-date': '~releasegroup_firstreleasedate',
'title': '~releasegroup',
}
_PREFIX_ATTRS = {'guest', 'additional', 'minor', 'solo'}
_BLANK_SPECIAL_RELTYPES = {'vocal': 'vocals'}
def _parse_attributes(attrs, reltype, attr_credits):
prefixes = []
nouns = []
for attr in attrs:
if attr in attr_credits:
attr = attr_credits[attr]
if attr in _PREFIX_ATTRS:
prefixes.append(attr)
else:
nouns.append(attr)
if len(nouns) > 1:
result = "%s and %s" % (", ".join(nouns[:-1]), nouns[-1:][0])
elif len(nouns) == 1:
result = nouns[0]
else:
result = _BLANK_SPECIAL_RELTYPES.get(reltype, "")
prefix = " ".join(prefixes)
return " ".join([prefix, result]).strip()
def _relation_attributes(relation):
try:
return tuple(relation['attributes'])
except KeyError:
return tuple()
def _relations_to_metadata_target_type_artist(relation, m, context):
artist = relation['artist']
translated_name, sort_name = _translate_artist_node(artist, config=context.config)
has_translation = (translated_name != artist['name'])
if not has_translation and context.use_credited_as and 'target-credit' in relation:
credited_as = relation['target-credit']
if credited_as:
translated_name = credited_as
reltype = relation['type']
attribs = _relation_attributes(relation)
if reltype in {'vocal', 'instrument', 'performer'}:
if context.use_instrument_credits:
attr_credits = relation.get('attribute-credits', {})
else:
attr_credits = {}
name = 'performer:' + _parse_attributes(attribs, reltype, attr_credits)
elif reltype == 'mix-DJ' and attribs:
if not hasattr(m, '_djmix_ars'):
m._djmix_ars = {}
for attr in attribs:
m._djmix_ars.setdefault(attr.split()[1], []).append(translated_name)
return
else:
try:
name = _ARTIST_REL_TYPES[reltype]
except KeyError:
return
if context.instrumental and name == 'lyricist':
return
m.add_unique(name, translated_name)
if name == 'composer':
m.add_unique('composersort', sort_name)
elif name == 'lyricist':
m.add_unique('~lyricistsort', sort_name)
elif name == 'writer':
m.add_unique('~writersort', sort_name)
def _relations_to_metadata_target_type_work(relation, m, context):
if relation['type'] == 'performance':
performance_attributes = _relation_attributes(relation)
for attribute in performance_attributes:
m.add_unique('~performance_attributes', attribute)
instrumental = 'instrumental' in performance_attributes
work_to_metadata(relation['work'], m, instrumental)
def _relations_to_metadata_target_type_url(relation, m, context):
if relation['type'] == 'amazon asin' and 'asin' not in m:
amz = parse_amazon_url(relation['url']['resource'])
if amz is not None:
m['asin'] = amz['asin']
elif relation['type'] == 'license':
url = relation['url']['resource']
m.add('license', url)
def _relations_to_metadata_target_type_series(relation, m, context):
if relation['type'] == 'part of':
entity = context.entity
series = relation['series']
var_prefix = f'~{entity}_' if entity else '~'
name = f'{var_prefix}series'
mbid = f'{var_prefix}seriesid'
comment = f'{var_prefix}seriescomment'
number = f'{var_prefix}seriesnumber'
if not context.metadata_was_cleared['series']:
# Clear related metadata first to prevent accumulation
# of identical value, see PICARD-2700 issue
m.unset(name)
m.unset(mbid)
m.unset(comment)
m.unset(number)
# That's to ensure it is done only once
context.metadata_was_cleared['series'] = True
m.add(name, series['name'])
m.add(mbid, series['id'])
m.add(comment, series['disambiguation'])
m.add(number, relation['attribute-values'].get('number', ''))
class RelFunc(SimpleNamespace):
clear_metadata_first = False
func = None
_RELATIONS_TO_METADATA_TARGET_TYPE_FUNC = {
'artist': RelFunc(func=_relations_to_metadata_target_type_artist),
'series': RelFunc(
func=_relations_to_metadata_target_type_series,
clear_metadata_first=True
),
'url': RelFunc(func=_relations_to_metadata_target_type_url),
'work': RelFunc(func=_relations_to_metadata_target_type_work),
}
def _relations_to_metadata(relations, m, instrumental=False, config=None, entity=None):
config = config or get_config()
context = SimpleNamespace(
config=config,
entity=entity,
instrumental=instrumental,
use_credited_as=not config.setting['standardize_artists'],
use_instrument_credits=not config.setting['standardize_instruments'],
metadata_was_cleared=dict(),
)
for relation in relations:
target = relation['target-type']
if target in _RELATIONS_TO_METADATA_TARGET_TYPE_FUNC:
relfunc = _RELATIONS_TO_METADATA_TARGET_TYPE_FUNC[target]
if target not in context.metadata_was_cleared:
context.metadata_was_cleared[target] = not relfunc.clear_metadata_first
relfunc.func(relation, m, context)
def _locales_from_aliases(aliases):
def check_higher_score(locale_dict, locale, score):
return locale not in locale_dict or score > locale_dict[locale][0]
full_locales = {}
root_locales = {}
for alias in aliases:
if not alias.get('primary'):
continue
full_locale = alias.get('locale')
if not full_locale:
continue
root_locale = full_locale.split('_')[0]
full_parts = []
root_parts = []
score = 0.8
full_parts.append((score, 5))
if '_' in full_locale:
score = 0.4
root_parts.append((score, 5))
type_id = alias.get('type-id')
if type_id == ALIAS_TYPE_ARTIST_NAME_ID:
score = 0.8
elif type_id == ALIAS_TYPE_LEGAL_NAME_ID:
score = 0.5
else:
# as 2014/09/19, only Artist or Legal names should have the
# Primary flag
score = 0.0
full_parts.append((score, 5))
root_parts.append((score, 5))
comb = linear_combination_of_weights(full_parts)
if check_higher_score(full_locales, full_locale, comb):
full_locales[full_locale] = (comb, (alias['name'], alias['sort-name']))
comb = linear_combination_of_weights(root_parts)
if check_higher_score(root_locales, root_locale, comb):
root_locales[root_locale] = (comb, (alias['name'], alias['sort-name']))
return full_locales, root_locales
def _translate_artist_node(node, config=None):
config = config or get_config()
translated_name, sort_name = None, None
if config.setting['translate_artist_names']:
if config.setting['translate_artist_names_script_exception']:
log_text = 'Script alpha characters found in "{0}": '.format(node['name'],)
detected_scripts = detect_script_weighted(node['name'])
if detected_scripts:
log_text += "; ".join(
"{0} ({1:.1f}%)".format(scr_id, detected_scripts[scr_id] * 100)
for scr_id in detected_scripts
)
else:
log_text += "None"
log.debug(log_text)
if detected_scripts:
script_exceptions = config.setting['script_exceptions']
if script_exceptions:
log_text = " found in selected scripts: " + "; ".join(
"{0} ({1}%)".format(scr[0], scr[1])
for scr in script_exceptions
)
for script_id, script_weighting in script_exceptions:
if script_id not in detected_scripts:
continue
if detected_scripts[script_id] >= script_weighting / 100:
log.debug("Match" + log_text)
return node['name'], node['sort-name']
log.debug("No match" + log_text)
else:
log.warning("No scripts selected for translation exception match check.")
# Prepare dictionaries of available locale aliases
if 'aliases' in node:
full_locales, root_locales = _locales_from_aliases(node['aliases'])
# First pass to match full locale if available
for locale in config.setting['artist_locales']:
if locale in full_locales:
return full_locales[locale][1]
# Second pass to match root locale if available
for locale in config.setting['artist_locales']:
lang = locale.split('_')[0]
if lang in root_locales:
return root_locales[lang][1]
# No matches found in available alias locales
sort_name = node['sort-name']
translated_name = translate_from_sortname(node['name'] or '', sort_name)
else:
translated_name, sort_name = node['name'], node['sort-name']
return (translated_name, sort_name)
def artist_credit_from_node(node):
artist_name = ''
artist_sort_name = ''
artist_names = []
artist_sort_names = []
config = get_config()
use_credited_as = not config.setting['standardize_artists']
for artist_info in node:
artist = artist_info['artist']
translated_name, sort_name = _translate_artist_node(artist, config=config)
has_translation = (translated_name != artist['name'])
if has_translation:
name = translated_name
elif use_credited_as and 'name' in artist_info:
name = artist_info['name']
else:
name = artist['name']
artist_name += name
artist_sort_name += sort_name or ''
artist_names.append(name)
artist_sort_names.append(sort_name or '')
if 'joinphrase' in artist_info:
artist_name += artist_info['joinphrase'] or ''
artist_sort_name += artist_info['joinphrase'] or ''
return (artist_name, artist_sort_name, artist_names, artist_sort_names)
def artist_credit_to_metadata(node, m, release=False):
ids = [n['artist']['id'] for n in node]
artist_name, artist_sort_name, artist_names, artist_sort_names = artist_credit_from_node(node)
if release:
m['musicbrainz_albumartistid'] = ids
m['albumartist'] = artist_name
m['albumartistsort'] = artist_sort_name
m['~albumartists'] = artist_names
m['~albumartists_sort'] = artist_sort_names
else:
m['musicbrainz_artistid'] = ids
m['artist'] = artist_name
m['artistsort'] = artist_sort_name
m['artists'] = artist_names
m['~artists_sort'] = artist_sort_names
def _release_event_iter(node):
if 'release-events' in node:
yield from node['release-events']
def _country_from_release_event(release_event):
try:
return release_event['area']['iso-3166-1-codes'][0]
# TypeError in case object is None
except (KeyError, IndexError, TypeError):
pass
return None
def countries_from_node(node):
countries = []
for release_event in _release_event_iter(node):
country_code = _country_from_release_event(release_event)
if country_code:
countries.append(country_code)
return sorted(countries)
def release_dates_and_countries_from_node(node):
dates = []
countries = []
for release_event in _release_event_iter(node):
dates.append(release_event['date'] or '')
country_code = _country_from_release_event(release_event)
if country_code:
countries.append(country_code)
return dates, countries
def label_info_from_node(node):
labels = []
catalog_numbers = []
for label_info in node:
if 'label' in label_info and label_info['label'] and 'name' in label_info['label']:
label = label_info['label']['name']
if label and label not in labels:
labels.append(label)
if 'catalog-number' in label_info:
cat_num = label_info['catalog-number']
if cat_num and cat_num not in catalog_numbers:
catalog_numbers.append(cat_num)
return (labels, catalog_numbers)
def media_formats_from_node(node):
formats_count = {}
formats_order = []
for medium in node:
text = medium.get('format', "(unknown)") or "(unknown)"
if text in formats_count:
formats_count[text] += 1
else:
formats_count[text] = 1
formats_order.append(text)
formats = []
for medium_format in formats_order:
count = formats_count[medium_format]
medium_format = RELEASE_FORMATS.get(medium_format, medium_format)
if count > 1:
medium_format = str(count) + "×" + medium_format
formats.append(medium_format)
return " + ".join(formats)
def _node_skip_empty_iter(node):
for key, value in node.items():
if value or value == 0:
yield key, value
def track_to_metadata(node, track):
m = track.metadata
recording_to_metadata(node['recording'], m, track)
m.add_unique('musicbrainz_trackid', node['id'])
# overwrite with data we have on the track
for key, value in _node_skip_empty_iter(node):
if key in _TRACK_TO_METADATA:
m[_TRACK_TO_METADATA[key]] = value
elif key == 'length' and value:
m.length = value
elif key == 'artist-credit':
artist_credit_to_metadata(value, m)
if m.length:
m['~length'] = format_time(m.length)
def recording_to_metadata(node, m, track=None):
m.length = 0
m.add_unique('musicbrainz_recordingid', node['id'])
config = get_config()
for key, value in _node_skip_empty_iter(node):
if key in _RECORDING_TO_METADATA:
m[_RECORDING_TO_METADATA[key]] = value
elif key == 'user-rating':
m['~rating'] = value['value']
elif key == 'length':
m.length = value
elif key == 'artist-credit':
artist_credit_to_metadata(value, m)
# set tags from artists
if track:
for credit in value:
artist = credit['artist']
artist_obj = track.append_track_artist(artist['id'])
add_genres_from_node(artist, artist_obj)
elif key == 'relations':
_relations_to_metadata(value, m, config=config, entity='recording')
elif key == 'isrcs':
add_isrcs_to_metadata(value, m)
elif key == 'video' and value:
m['~video'] = '1'
add_genres_from_node(node, track)
if m['title']:
m['~recordingtitle'] = m['title']
if m.length:
m['~length'] = format_time(m.length)
def work_to_metadata(work, m, instrumental=False):
m.add_unique('musicbrainz_workid', work['id'])
if instrumental:
m.add_unique('language', 'zxx') # no lyrics
elif 'languages' in work:
for language in work['languages']:
m.add_unique('language', language)
elif 'language' in work:
m.add_unique('language', work['language'])
if 'title' in work:
m.add_unique('work', work['title'])
if 'disambiguation' in work:
m.add_unique('~workcomment', work['disambiguation'])
if 'relations' in work:
_relations_to_metadata(work['relations'], m, instrumental, entity='work')
def medium_to_metadata(node, m):
for key, value in _node_skip_empty_iter(node):
if key in _MEDIUM_TO_METADATA:
m[_MEDIUM_TO_METADATA[key]] = value
totaltracks = node.get('track-count', 0)
if node.get('pregap'):
totaltracks += 1
if totaltracks:
m['totaltracks'] = totaltracks
def artist_to_metadata(node, m):
"""Make meatadata dict from a JSON 'artist' node."""
m.add_unique('musicbrainz_artistid', node['id'])
for key, value in _node_skip_empty_iter(node):
if key in _ARTIST_TO_METADATA:
m[_ARTIST_TO_METADATA[key]] = value
elif key == 'area':
m['area'] = value['name']
elif key == 'life-span':
if 'begin' in value:
m['begindate'] = value['begin']
if 'ended' in value:
ended = value['ended']
if ended and 'end' in value:
m['enddate'] = value['end']
elif key == 'begin-area':
m['beginarea'] = value['name']
elif key == 'end-area':
m['endarea'] = value['name']
def release_to_metadata(node, m, album=None):
"""Make metadata dict from a JSON 'release' node."""
config = get_config()
m.add_unique('musicbrainz_albumid', node['id'])
for key, value in _node_skip_empty_iter(node):
if key in _RELEASE_TO_METADATA:
m[_RELEASE_TO_METADATA[key]] = value
elif key == 'status':
m['releasestatus'] = value.lower()
elif key == 'artist-credit':
artist_credit_to_metadata(value, m, release=True)
# set tags from artists
if album is not None:
for credit in value:
artist = credit['artist']
artist_obj = album.append_album_artist(artist['id'])
add_genres_from_node(artist, artist_obj)
elif key == 'relations' and config.setting['release_ars']:
_relations_to_metadata(value, m, config=config, entity='release')
elif key == 'label-info':
m['label'], m['catalognumber'] = label_info_from_node(value)
elif key == 'text-representation':
if 'language' in value:
m['~releaselanguage'] = value['language']
if 'script' in value:
m['script'] = value['script']
m['~releasecountries'] = release_countries = countries_from_node(node)
# The MB web service returns the first release country in the country tag.
# If the user has configured preferred release countries, use the first one
# if it is one in the complete list of release countries.
for country in config.setting['preferred_release_countries']:
if country in release_countries:
m['releasecountry'] = country
break
add_genres_from_node(node, album)
def release_group_to_metadata(node, m, release_group=None):
"""Make metadata dict from a JSON 'release-group' node taken from inside a 'release' node."""
config = get_config()
m.add_unique('musicbrainz_releasegroupid', node['id'])
for key, value in _node_skip_empty_iter(node):
if key in _RELEASE_GROUP_TO_METADATA:
m[_RELEASE_GROUP_TO_METADATA[key]] = value
elif key == 'primary-type':
m['~primaryreleasetype'] = value.lower()
elif key == 'secondary-types':
add_secondary_release_types(value, m)
elif key == 'relations' and config.setting['release_ars']:
_relations_to_metadata(value, m, config=config, entity='releasegroup')
add_genres_from_node(node, release_group)
if m['~releasegroup_firstreleasedate']:
m['originaldate'] = m['~releasegroup_firstreleasedate']
m['originalyear'] = m['originaldate'][:4]
m['releasetype'] = m.getall('~primaryreleasetype') + m.getall('~secondaryreleasetype')
def add_secondary_release_types(node, m):
for secondary_type in node:
m.add_unique('~secondaryreleasetype', secondary_type.lower())
def add_genres_from_node(node, obj):
if obj is None:
return
if 'genres' in node:
add_genres(node['genres'], obj)
if 'tags' in node:
add_genres(node['tags'], obj)
if 'user-genres' in node:
add_user_genres(node['user-genres'], obj)
if 'user-tags' in node:
add_user_genres(node['user-tags'], obj)
def add_genres(node, obj):
for tag in node:
obj.add_genre(tag['name'], tag['count'])
def add_user_genres(node, obj):
for tag in node:
obj.add_genre(tag['name'], 1)
def add_isrcs_to_metadata(node, metadata):
for isrc in node:
metadata.add('isrc', isrc)
def get_score(node):
"""Returns the score attribute for a node.
The score is expected to be an integer between 0 and 100, it is returned as
a value between 0.0 and 1.0. If there is no score attribute or it has an
invalid value 1.0 will be returned.
"""
try:
return int(node.get('score', 100)) / 100
except (TypeError, ValueError):
return 1.0
| 24,080
|
Python
|
.py
| 589
| 32.792869
| 98
| 0.617166
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,929
|
album.py
|
metabrainz_picard/picard/album.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2004 Robert Kaye
# Copyright (C) 2006-2009, 2011-2012, 2014 Lukáš Lalinský
# Copyright (C) 2008 Gary van der Merwe
# Copyright (C) 2008 Hendrik van Antwerpen
# Copyright (C) 2008 ojnkpjg
# Copyright (C) 2008-2011, 2014, 2018-2023 Philipp Wolfer
# Copyright (C) 2009 Nikolai Prokoschenko
# Copyright (C) 2011-2012 Chad Wilson
# Copyright (C) 2011-2013, 2019 Michael Wiencek
# Copyright (C) 2012-2013, 2016-2017 Wieland Hoffmann
# Copyright (C) 2013, 2018 Calvin Walton
# Copyright (C) 2013-2015, 2017 Sophist-UK
# Copyright (C) 2013-2015, 2017-2024 Laurent Monin
# Copyright (C) 2016 Suhas
# Copyright (C) 2016-2018 Sambhav Kothari
# Copyright (C) 2017 Antonio Larrosa
# Copyright (C) 2018 Vishal Choudhary
# Copyright (C) 2019 Joel Lintunen
# Copyright (C) 2020-2021 Gabriel Ferreira
# Copyright (C) 2021 Petit Minion
# Copyright (C) 2022 skelly37
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from collections import (
OrderedDict,
defaultdict,
namedtuple,
)
from enum import IntEnum
import traceback
from PyQt6 import QtNetwork
from picard import log
from picard.cluster import Cluster
from picard.collection import add_release_to_user_collections
from picard.config import get_config
from picard.const import VARIOUS_ARTISTS_ID
from picard.file import File
from picard.i18n import (
N_,
gettext as _,
)
from picard.item import MetadataItem
from picard.mbjson import (
medium_to_metadata,
release_group_to_metadata,
release_to_metadata,
track_to_metadata,
)
from picard.metadata import (
Metadata,
run_album_metadata_processors,
run_track_metadata_processors,
)
from picard.plugin import PluginFunctions
from picard.script import (
ScriptError,
ScriptParser,
iter_active_tagging_scripts,
)
from picard.track import Track
from picard.util import (
find_best_match,
format_time,
mbid_validate,
)
from picard.util.textencoding import asciipunct
RECORDING_QUERY_LIMIT = 100
def _create_artist_node_dict(source_node):
return {x['artist']['id']: x['artist'] for x in source_node['artist-credit']}
def _copy_artist_nodes(source, target_node):
for credit in target_node['artist-credit']:
artist_node = source.get(credit['artist']['id'])
if artist_node:
credit['artist'] = artist_node
class AlbumArtist(MetadataItem):
def __init__(self, album_artist_id):
super().__init__(album_artist_id)
class AlbumStatus(IntEnum):
NONE = 0
LOADING = 1
ERROR = 2
LOADED = 3
class ParseResult(IntEnum):
PARSED = 0
REDIRECT = 1
MISSING_TRACK_RELS = 2
class Album(MetadataItem):
def __init__(self, album_id, discid=None):
super().__init__(album_id)
self.tracks = []
self.loaded = False
self.load_task = None
self.release_group = None
self._files_count = 0
self._requests = 0
self._tracks_loaded = False
self._discids = set()
self._recordings_map = {}
if discid:
self._discids.add(discid)
self._after_load_callbacks = []
self.unmatched_files = Cluster(_("Unmatched Files"), special=True, related_album=self, hide_if_empty=True)
self.unmatched_files.metadata_images_changed.connect(self.update_metadata_images)
self.status = AlbumStatus.NONE
self._album_artists = []
self.update_children_metadata_attrs = {'metadata', 'orig_metadata'}
def __repr__(self):
return '<Album %s %r>' % (self.id, self.metadata['album'])
def iterfiles(self, save=False):
for track in self.tracks:
yield from track.iterfiles()
if not save:
yield from self.unmatched_files.iterfiles()
def iter_correctly_matched_tracks(self):
yield from (track for track in self.tracks if track.num_linked_files == 1)
def append_album_artist(self, album_artist_id):
"""Append artist id to the list of album artists
and return an AlbumArtist instance"""
album_artist = AlbumArtist(album_artist_id)
self._album_artists.append(album_artist)
return album_artist
def add_discid(self, discid):
if not discid:
return
self._discids.add(discid)
for track in self.tracks:
medium_discids = track.metadata.getall('~musicbrainz_discids')
track_discids = list(self._discids.intersection(medium_discids))
if track_discids:
track.metadata['musicbrainz_discid'] = track_discids
track.update()
for file in track.files:
file.metadata['musicbrainz_discid'] = track_discids
file.update()
def get_next_track(self, track):
try:
index = self.tracks.index(track)
return self.tracks[index + 1]
except (IndexError, ValueError):
return None
def get_album_artists(self):
"""Returns the list of album artists (as AlbumArtist objects)"""
return self._album_artists
def _run_album_metadata_processors(self):
try:
run_album_metadata_processors(self, self._new_metadata, self._release_node)
except BaseException:
self.error_append(traceback.format_exc())
def _parse_release(self, release_node):
log.debug("Loading release %r …", self.id)
self._tracks_loaded = False
release_id = release_node['id']
if release_id != self.id:
self.tagger.mbid_redirects[self.id] = release_id
album = self.tagger.albums.get(release_id)
if album:
log.debug("Release %r already loaded", release_id)
album.match_files(self.unmatched_files.files)
album.update()
self.tagger.remove_album(self)
return ParseResult.REDIRECT
else:
del self.tagger.albums[self.id]
self.tagger.albums[release_id] = self
self.id = release_id
self._release_node = release_node
# Make the release artist nodes available, since they may
# contain supplementary data (aliases, tags, genres, ratings)
# which aren't present in the release group, track, or
# recording artist nodes. We can copy them into those places
# wherever the IDs match, so that the data is shared and
# available for use in mbjson.py and external plugins.
self._release_artist_nodes = _create_artist_node_dict(release_node)
# Get release metadata
m = self._new_metadata
m.length = 0
rg_node = release_node['release-group']
rg = self.release_group = self.tagger.get_release_group_by_id(rg_node['id'])
rg.loaded_albums.add(self.id)
rg.refcount += 1
_copy_artist_nodes(self._release_artist_nodes, rg_node)
release_group_to_metadata(rg_node, rg.metadata, rg)
m.copy(rg.metadata)
release_to_metadata(release_node, m, album=self)
config = get_config()
# Custom VA name
if m['musicbrainz_albumartistid'] == VARIOUS_ARTISTS_ID:
m['albumartistsort'] = m['albumartist'] = config.setting['va_name']
# Convert Unicode punctuation
if config.setting['convert_punctuation']:
m.apply_func(asciipunct)
m['totaldiscs'] = len(release_node['media'])
# Add album to collections
add_release_to_user_collections(release_node)
if config.setting['track_ars']:
# Detect if track relationships did not get loaded
try:
for medium_node in release_node['media']:
if medium_node['track-count']:
if 'relations' in medium_node['tracks'][0]['recording']:
return ParseResult.PARSED
else:
return ParseResult.MISSING_TRACK_RELS
except KeyError:
pass
return ParseResult.PARSED
def _release_request_finished(self, document, http, error):
if self.load_task is None:
return
self.load_task = None
parse_result = None
try:
if error:
self.error_append(http.errorString())
# Fix for broken NAT releases
if error == QtNetwork.QNetworkReply.NetworkError.ContentNotFoundError:
config = get_config()
nats = False
nat_name = config.setting['nat_name']
files = list(self.unmatched_files.files)
for file in files:
recordingid = file.metadata['musicbrainz_recordingid']
if mbid_validate(recordingid) and file.metadata['album'] == nat_name:
nats = True
self.tagger.move_file_to_nat(file, recordingid)
self.tagger.nats.update()
if nats and not self.get_num_unmatched_files():
self.tagger.remove_album(self)
error = False
else:
try:
parse_result = self._parse_release(document)
config = get_config()
if parse_result == ParseResult.MISSING_TRACK_RELS:
log.debug("Recording relationships not loaded in initial request for %r, issuing separate requests", self)
self._request_recording_relationships()
elif parse_result == ParseResult.PARSED:
self._run_album_metadata_processors()
elif parse_result == ParseResult.REDIRECT:
error = False
except Exception:
error = True
self.error_append(traceback.format_exc())
finally:
self._requests -= 1
if parse_result == ParseResult.PARSED or error:
self._finalize_loading(error)
def _request_recording_relationships(self, offset=0, limit=RECORDING_QUERY_LIMIT):
inc = (
'artist-rels',
'recording-rels',
'release-rels',
'url-rels',
'work-rels',
'work-level-rels',
)
log.debug("Loading recording relationships for %r (offset=%i, limit=%i)", self, offset, limit)
self._requests += 1
self.load_task = self.tagger.mb_api.browse_recordings(
self._recordings_request_finished,
inc=inc,
release=self.id,
limit=limit,
offset=offset,
)
def _recordings_request_finished(self, document, http, error):
if error:
self.error_append(http.errorString())
self._requests -= 1
self._finalize_loading(error)
else:
for recording in document.get('recordings', []):
recording_id = recording.get('id')
if recording_id:
self._recordings_map[recording_id] = recording
count = document.get('recording-count', 0)
offset = document.get('recording-offset', 0)
next_offset = offset + RECORDING_QUERY_LIMIT
if next_offset < count:
self._requests -= 1
self._request_recording_relationships(offset=next_offset)
else:
# Merge separately loaded recording relationships into release node
self._merge_release_recording_relationships()
self._run_album_metadata_processors()
self._requests -= 1
self._finalize_loading(error)
def _merge_recording_relationships(self, track_node):
if 'relations' not in track_node['recording']:
recording = self._recordings_map.get(track_node['recording']['id'])
if recording:
track_node['recording']['relations'] = recording.get('relations', [])
def _merge_release_recording_relationships(self):
for medium_node in self._release_node['media']:
pregap_node = medium_node.get('pregap')
if pregap_node:
self._merge_recording_relationships(pregap_node)
for track_node in medium_node.get('tracks', []):
self._merge_recording_relationships(track_node)
for track_node in medium_node.get('data-tracks', []):
self._merge_recording_relationships(track_node)
self._recordings_map = {}
def _finalize_loading_track(self, track_node, metadata, artists, extra_metadata=None):
# As noted in `_parse_release` above, the release artist nodes
# may contain supplementary data that isn't present in track
# artist nodes. Similarly, the track artists may contain
# information which the recording artists don't. Copy this
# information across to wherever the artist IDs match.
_copy_artist_nodes(self._release_artist_nodes, track_node)
_copy_artist_nodes(self._release_artist_nodes, track_node['recording'])
_copy_artist_nodes(_create_artist_node_dict(track_node), track_node['recording'])
track = Track(track_node['recording']['id'], self)
self._new_tracks.append(track)
# Get track metadata
tm = track.metadata
tm.copy(metadata)
track_to_metadata(track_node, track)
track._customize_metadata()
self._new_metadata.length += tm.length
artists.add(tm['artist'])
if extra_metadata:
tm.update(extra_metadata)
# Run track metadata plugins
try:
run_track_metadata_processors(self, tm, track_node, self._release_node)
except BaseException:
self.error_append(traceback.format_exc())
return track
def _load_tracks(self):
artists = set()
all_media = []
absolutetracknumber = 0
def _load_track(node, mm, artists, extra_metadata):
nonlocal absolutetracknumber
absolutetracknumber += 1
extra_metadata['~absolutetracknumber'] = absolutetracknumber
self._finalize_loading_track(node, mm, artists, extra_metadata)
va = self._new_metadata['musicbrainz_albumartistid'] == VARIOUS_ARTISTS_ID
djmix_ars = {}
if hasattr(self._new_metadata, '_djmix_ars'):
djmix_ars = self._new_metadata._djmix_ars
for medium_node in self._release_node['media']:
mm = Metadata()
mm.copy(self._new_metadata)
medium_to_metadata(medium_node, mm)
fmt = medium_node.get('format')
if fmt:
all_media.append(fmt)
for dj in djmix_ars.get(mm['discnumber'], []):
mm.add('djmixer', dj)
if va:
mm['compilation'] = '1'
else:
del mm['compilation']
if 'discs' in medium_node:
discids = [disc.get('id') for disc in medium_node['discs']]
mm['~musicbrainz_discids'] = discids
mm['musicbrainz_discid'] = list(self._discids.intersection(discids))
pregap_node = medium_node.get('pregap')
if pregap_node:
mm['~discpregap'] = '1'
_load_track(pregap_node, mm, artists, {'~pregap': '1'})
for track_node in medium_node.get('tracks', []):
_load_track(track_node, mm, artists, {})
for track_node in medium_node.get('data-tracks', []):
_load_track(track_node, mm, artists, {'~datatrack': '1'})
totalalbumtracks = absolutetracknumber
self._new_metadata['~totalalbumtracks'] = totalalbumtracks
# Generate a list of unique media, but keep order of first appearance
self._new_metadata['media'] = " / ".join(list(OrderedDict.fromkeys(all_media)))
multiartists = len(artists) > 1
for track in self._new_tracks:
track.metadata['~totalalbumtracks'] = totalalbumtracks
if multiartists:
track.metadata['~multiartist'] = '1'
del self._release_node
del self._release_artist_nodes
self._tracks_loaded = True
def _finalize_loading_album(self):
with self.suspend_metadata_images_update:
for track in self._new_tracks:
track.orig_metadata.copy(track.metadata)
track.metadata_images_changed.connect(self.update_metadata_images)
# Prepare parser for user's script
for script in iter_active_tagging_scripts():
parser = ScriptParser()
for track in self._new_tracks:
# Run tagger script for each track
try:
parser.eval(script.content, track.metadata)
except ScriptError:
log.exception("Failed to run tagger script %s on track", script.name)
track.metadata.strip_whitespace()
track.scripted_metadata.update(track.metadata)
# Run tagger script for the album itself
try:
parser.eval(script.content, self._new_metadata)
except ScriptError:
log.exception("Failed to run tagger script %s on album", script.name)
self._new_metadata.strip_whitespace()
unmatched_files = [file for track in self.tracks for file in track.files]
self.metadata = self._new_metadata
self.orig_metadata.copy(self.metadata)
self.orig_metadata.images.clear()
self.tracks = self._new_tracks
del self._new_metadata
del self._new_tracks
self.loaded = True
self.status = AlbumStatus.LOADED
self.match_files(unmatched_files + self.unmatched_files.files)
self.update_metadata_images()
self.update()
self.tagger.window.set_statusbar_message(
N_('Album %(id)s loaded: %(artist)s - %(album)s'),
{
'id': self.id,
'artist': self.metadata['albumartist'],
'album': self.metadata['album']
},
timeout=3000
)
for func, always in self._after_load_callbacks:
func()
self._after_load_callbacks = []
if self.ui_item.isSelected():
self.tagger.window.refresh_metadatabox()
self.tagger.window.cover_art_box.update_metadata()
def _finalize_loading(self, error):
if self.loaded:
# This is not supposed to happen, _finalize_loading should only
# be called once after all requests finished.
import inspect
stack = inspect.stack()
args = [self]
msg = "Album._finalize_loading called for already loaded album %r"
if len(stack) > 1:
f = stack[1]
msg += " at %s:%d in %s"
args.extend((f.filename, f.lineno, f.function))
log.warning(msg, *args)
return
if error:
self.metadata.clear()
self.status = AlbumStatus.ERROR
self.update()
if not self._requests:
del self._new_metadata
del self._new_tracks
self.loaded = True
for func, always in self._after_load_callbacks:
if always:
func()
return
if self._requests > 0:
return
if not self._tracks_loaded:
self._load_tracks()
if not self._requests:
self._finalize_loading_album()
def load(self, priority=False, refresh=False):
if self._requests:
log.info("Not reloading, some requests are still active.")
return
self.tagger.window.set_statusbar_message(
N_("Loading album %(id)s …"),
{'id': self.id}
)
self.loaded = False
self.status = AlbumStatus.LOADING
if self.release_group:
self.release_group.loaded = False
self.release_group.genres.clear()
self.metadata.clear()
self.genres.clear()
self.update(update_selection=False)
self._new_metadata = Metadata()
self._new_tracks = []
self._requests = 1
self.clear_errors()
config = get_config()
require_authentication = False
inc = {
'aliases',
'annotation',
'artist-credits',
'artists',
'collections',
'discids',
'isrcs',
'labels',
'media',
'recordings',
'release-groups',
}
if self.tagger.webservice.oauth_manager.is_authorized():
require_authentication = True
inc |= {'user-collections'}
if config.setting['release_ars'] or config.setting['track_ars']:
inc |= {
'artist-rels',
'recording-rels',
'release-group-level-rels',
'release-rels',
'series-rels',
'url-rels',
'work-rels',
}
if config.setting['track_ars']:
inc |= {
'recording-level-rels',
'work-level-rels',
}
require_authentication = self.set_genre_inc_params(inc, config) or require_authentication
if config.setting['enable_ratings']:
require_authentication = True
inc |= {'user-ratings'}
self.load_task = self.tagger.mb_api.get_release_by_id(
self.id,
self._release_request_finished,
inc=inc,
mblogin=require_authentication,
priority=priority,
refresh=refresh
)
def run_when_loaded(self, func, always=False):
if self.loaded:
func()
else:
self._after_load_callbacks.append((func, always))
def stop_loading(self):
if self.load_task:
self.tagger.webservice.remove_task(self.load_task)
self.load_task = None
def update(self, update_tracks=True, update_selection=True):
if self.ui_item:
self.ui_item.update(update_tracks, update_selection=update_selection)
def add_file(self, track, file, new_album=True):
self._files_count += 1
if new_album:
self.update(update_tracks=False)
self.add_metadata_images_from_children([file])
def remove_file(self, track, file, new_album=True):
self._files_count -= 1
if new_album:
self.update(update_tracks=False)
self.remove_metadata_images_from_children([file])
@staticmethod
def _match_files(files, tracks, unmatched_files, threshold=0):
"""Match files to tracks on this album, based on metadata similarity or recordingid."""
tracks_cache = defaultdict(lambda: None)
def build_tracks_cache():
for track in tracks:
tm_recordingid = track.orig_metadata['musicbrainz_recordingid']
tm_trackid = track.orig_metadata['musicbrainz_trackid']
tm_tracknumber = track.orig_metadata['tracknumber']
tm_discnumber = track.orig_metadata['discnumber']
for tup in (
(tm_recordingid, tm_tracknumber, tm_discnumber),
(tm_recordingid, tm_tracknumber),
(tm_recordingid, ),
(tm_trackid, tm_tracknumber, tm_discnumber),
(tm_trackid, tm_tracknumber),
(tm_trackid, )):
tracks_cache[tup] = track
SimMatchAlbum = namedtuple('SimMatchAlbum', 'similarity track')
no_match = SimMatchAlbum(similarity=-1, track=unmatched_files)
for file in list(files):
if file.state == File.REMOVED:
continue
# if we have a recordingid or trackid to match against, use that in priority
# if recordingid and trackid do point to different tracks, compare the file
# and track durations to find the better match.
recid = file.match_recordingid or file.metadata['musicbrainz_recordingid']
trackid = file.metadata['musicbrainz_trackid']
tracknumber = file.metadata['tracknumber']
discnumber = file.metadata['discnumber']
def mbid_candidates():
for mbid in (recid, trackid):
if mbid and mbid_validate(mbid):
if not tracks_cache:
build_tracks_cache()
track = (tracks_cache[(mbid, tracknumber, discnumber)]
or tracks_cache[(mbid, tracknumber)]
or tracks_cache[(mbid, )])
if track:
similarity = track.metadata.length_score(track.metadata.length, file.metadata.length)
yield SimMatchAlbum(similarity=similarity, track=track)
best_match = find_best_match(mbid_candidates(), no_match)
if best_match.result != no_match:
yield (file, best_match.result.track)
continue
# try to match by similarity
def similarity_candidates():
for track in tracks:
similarity = track.metadata.compare(file.orig_metadata)
if similarity >= threshold:
yield SimMatchAlbum(similarity=similarity, track=track)
best_match = find_best_match(similarity_candidates(), no_match)
yield (file, best_match.result.track)
def match_files(self, files):
"""Match and move files to tracks on this album, based on metadata similarity or recordingid."""
if self.loaded:
config = get_config()
threshold = config.setting['track_matching_threshold']
moves = self._match_files(files, self.tracks, self.unmatched_files, threshold=threshold)
with self.tagger.window.metadata_box.ignore_updates:
for file, target in moves:
file.move(target)
else:
with self.tagger.window.metadata_box.ignore_updates:
for file in list(files):
file.move(self.unmatched_files)
@property
def can_save(self):
return self._files_count > 0
@property
def can_remove(self):
return True
@property
def can_edit_tags(self):
return True
@property
def can_analyze(self):
return False
@property
def can_autotag(self):
return False
@property
def can_refresh(self):
return True
@property
def can_view_info(self):
return self.loaded or bool(self.errors)
@property
def is_album_like(self):
return True
def get_num_matched_tracks(self):
return sum(1 for track in self.tracks if track.is_linked())
def get_num_unmatched_files(self):
return len(self.unmatched_files.files)
def get_num_total_files(self):
return self._files_count + len(self.unmatched_files.files)
def is_complete(self):
if not self.tracks:
return False
for track in self.tracks:
if not track.is_complete():
return False
return not self.get_num_unmatched_files()
def is_modified(self):
return any(self._iter_unsaved_files())
def get_num_unsaved_files(self):
return sum(1 for file in self._iter_unsaved_files())
def _iter_unsaved_files(self):
yield from (file for file in self.iterfiles(save=True) if not file.is_saved())
def column(self, column):
if column == 'title':
if self.status == AlbumStatus.LOADING:
title = _("[loading album information]")
elif self.status == AlbumStatus.ERROR:
title = _("[could not load album %s]") % self.id
else:
title = self.metadata['album']
if self.tracks:
elems = ['%d/%d' % (self.get_num_matched_tracks(), len(self.tracks))]
unmatched = self.get_num_unmatched_files()
if unmatched:
elems.append('%d?' % (unmatched,))
unsaved = self.get_num_unsaved_files()
if unsaved:
elems.append('%d*' % (unsaved,))
ca_detailed = self.cover_art_description_detailed()
if ca_detailed:
elems.append(ca_detailed)
return '%s\u200E (%s)' % (title, '; '.join(elems))
else:
return title
elif column == '~length':
length = self.metadata.length
if length:
return format_time(length)
else:
return ''
elif column == 'artist':
return self.metadata['albumartist']
elif column == 'tracknumber':
return self.metadata['~totalalbumtracks']
elif column == 'discnumber':
return self.metadata['totaldiscs']
elif column == 'covercount':
return self.cover_art_description()
elif column == 'coverdimensions':
return self.cover_art_dimensions()
else:
return self.metadata[column]
def switch_release_version(self, mbid):
if mbid == self.id:
return
for file in list(self.iterfiles(True)):
file.move(self.unmatched_files)
album = self.tagger.albums.get(mbid)
if album:
album.match_files(self.unmatched_files.files)
album.update()
self.tagger.remove_album(self)
else:
del self.tagger.albums[self.id]
self.release_group.loaded_albums.discard(self.id)
self.id = mbid
self.tagger.albums[mbid] = self
self.load(priority=True, refresh=True)
def update_metadata_images(self):
if self.suspend_metadata_images_update:
return
if self.update_metadata_images_from_children():
self.update(update_tracks=False)
self.metadata_images_changed.emit()
def keep_original_images(self):
with self.suspend_metadata_images_update:
for track in self.tracks:
track.keep_original_images()
for file in list(self.unmatched_files.files):
file.keep_original_images()
def children_metadata_items(self):
for track in self.tracks:
yield track
yield from track.files
yield from self.unmatched_files.files
class NatAlbum(Album):
def __init__(self):
super().__init__('NATS')
self.loaded = True
self.update()
def update(self, update_tracks=True, update_selection=True):
config = get_config()
old_album_title = self.metadata['album']
self.metadata['album'] = config.setting['nat_name']
with self.suspend_metadata_images_update:
for track in self.tracks:
if old_album_title == track.metadata['album']:
track.metadata['album'] = self.metadata['album']
for file in track.files:
track.update_file_metadata(file)
super().update(update_tracks=update_tracks, update_selection=update_selection)
def _finalize_loading(self, error):
self.update()
@property
def can_refresh(self):
return False
@property
def can_browser_lookup(self):
return False
@property
def can_view_info(self):
return False
album_post_removal_processors = PluginFunctions(label='album_post_removal_processors')
def run_album_post_removal_processors(album_object):
album_post_removal_processors.run(album_object)
| 33,097
|
Python
|
.py
| 774
| 31.414729
| 130
| 0.590382
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,930
|
oauth.py
|
metabrainz_picard/picard/oauth.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2014 Lukáš Lalinský
# Copyright (C) 2015 Sophist-UK
# Copyright (C) 2015 Wieland Hoffmann
# Copyright (C) 2015, 2018, 2021-2022, 2024 Philipp Wolfer
# Copyright (C) 2016-2017 Sambhav Kothari
# Copyright (C) 2017 Frederik “Freso” S. Olesen
# Copyright (C) 2018-2024 Laurent Monin
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from base64 import urlsafe_b64encode
from functools import partial
from hashlib import sha256
from json.decoder import JSONDecodeError
import secrets
import time
import urllib.parse
from picard import log
from picard.config import get_config
from picard.const import (
MUSICBRAINZ_OAUTH_CLIENT_ID,
MUSICBRAINZ_OAUTH_CLIENT_SECRET,
)
from picard.i18n import gettext as _
from picard.util import (
build_qurl,
load_json,
)
OOB_URI = 'urn:ietf:wg:oauth:2.0:oob'
class OAuthInvalidStateError(Exception):
pass
class OAuthManager:
def __init__(self, webservice):
self.webservice = webservice
# Associates state tokens with callbacks
self.__states = {}
self._redirect_uri = OOB_URI
@property
def redirect_uri(self):
return self._redirect_uri
@redirect_uri.setter
def redirect_uri(self, redirect_uri):
if not redirect_uri:
self._redirect_uri = OOB_URI
else:
self._redirect_uri = redirect_uri
@property
def is_oob(self):
return self.redirect_uri == OOB_URI
@property
def setting(self):
config = get_config()
return config.setting
@property
def persist(self):
config = get_config()
return config.persist
@property
def host(self):
return self.setting['server_host']
@property
def port(self):
return self.setting['server_port']
@property
def refresh_token(self):
return self.persist['oauth_refresh_token']
@refresh_token.setter
def refresh_token(self, value):
self.persist['oauth_refresh_token'] = value
@refresh_token.deleter
def refresh_token(self):
self.persist.remove('oauth_refresh_token')
@property
def refresh_token_scopes(self):
return self.persist['oauth_refresh_token_scopes']
@refresh_token_scopes.setter
def refresh_token_scopes(self, value):
self.persist['oauth_refresh_token_scopes'] = value
@refresh_token_scopes.deleter
def refresh_token_scopes(self):
self.persist.remove('oauth_refresh_token_scopes')
@property
def access_token(self):
return self.persist['oauth_access_token']
@access_token.setter
def access_token(self, value):
self.persist['oauth_access_token'] = value
@access_token.deleter
def access_token(self):
self.persist.remove('oauth_access_token')
@property
def access_token_expires(self):
return self.persist['oauth_access_token_expires']
@access_token_expires.setter
def access_token_expires(self, value):
self.persist['oauth_access_token_expires'] = value
@access_token_expires.deleter
def access_token_expires(self):
self.persist.remove('oauth_access_token_expires')
@property
def username(self):
return self.persist['oauth_username']
@username.setter
def username(self, value):
self.persist['oauth_username'] = value
def is_authorized(self):
return bool(self.refresh_token and self.refresh_token_scopes)
def is_logged_in(self):
return self.is_authorized() and bool(self.username)
def revoke_tokens(self, callback):
# Actually revoke the tokens on MB.
# From https://musicbrainz.org/doc/Development/OAuth2#Revoking_a_token :
# "If your application is installed or offline and token is a
# refresh token, we'll revoke the entire authorization grant associated
# with that token."
log.debug("OAuth: Revoking authorization grant")
self._revoke_token(self.refresh_token, callback)
def _revoke_token(self, token, callback):
params = {
'token': token,
'client_id': MUSICBRAINZ_OAUTH_CLIENT_ID,
'client_secret': MUSICBRAINZ_OAUTH_CLIENT_SECRET,
}
self.webservice.post_url(
url=self.url(path="/oauth2/revoke"),
data=self._query_data(params),
handler=partial(self._on_revoke_token_finished, callback),
mblogin=True,
priority=True,
important=True,
request_mimetype='application/x-www-form-urlencoded',
parse_response_type=False,
)
def _on_revoke_token_finished(self, callback, data, http, error):
successful = False
error_msg = None
try:
if error:
log.error("OAuth: revoking token failed: %s", error)
error_msg = self._extract_error_description(http, data)
else:
self.forget_refresh_token()
self.forget_access_token()
successful = True
except Exception as e:
log.error("OAuth: Unexpected error handling token revocation response: %r", e)
error_msg = _("Unexpected token revocation error")
finally:
callback(successful=successful, error_msg=error_msg)
def forget_refresh_token(self):
del self.refresh_token
del self.refresh_token_scopes
def forget_access_token(self):
del self.access_token
del self.access_token_expires
def get_access_token(self, callback):
if not self.is_authorized():
callback(access_token=None)
else:
if self.access_token and time.time() < self.access_token_expires:
callback(access_token=self.access_token)
else:
self.forget_access_token()
self.refresh_access_token(callback)
def url(self, path=None, params=None):
return build_qurl(
self.host, self.port, path=path,
queryargs=params
)
def _create_code_challenge(self):
# see https://datatracker.ietf.org/doc/html/rfc7636#section-4.1
# and https://datatracker.ietf.org/doc/html/rfc7636#appendix-B
code_verifier = base64url_encode(secrets.token_bytes(32))
self.__code_verifier = code_verifier.decode('ASCII')
code_challenge = s256_encode(code_verifier) # code_challenge_method=S256
return code_challenge.decode('ASCII')
def _create_auth_state(self, callback):
state = secrets.token_urlsafe(16)
self.__states[state] = callback
return state
def verify_state(self, state):
"""Verifies a state variable used in an authorization URL.
On success returns a callback associated with this state.
If the state is invalid raises OAuthInvalidStateError. Can only be
called once on a state, the state itself will be revoked afterwards.
"""
try:
callback = self.__states[state]
del self.__states[state]
return callback
except KeyError:
raise OAuthInvalidStateError
def get_authorization_url(self, scopes, callback: callable):
params = {
'response_type': 'code',
'client_id': MUSICBRAINZ_OAUTH_CLIENT_ID,
'redirect_uri': self.redirect_uri,
'code_challenge_method': 'S256',
'code_challenge': self._create_code_challenge(),
'scope': scopes,
'access_type': 'offline',
}
if not self.is_oob:
params['state'] = self._create_auth_state(callback)
return bytes(self.url(path="/oauth2/authorize", params=params).toEncoded()).decode()
def set_refresh_token(self, refresh_token, scopes):
log.debug("OAuth: got refresh_token %s with scopes %s", refresh_token, scopes)
self.refresh_token = refresh_token
self.refresh_token_scopes = scopes
def set_access_token(self, access_token, expires_in):
log.debug("OAuth: got access_token %s that expires in %s seconds", access_token, expires_in)
self.access_token = access_token
self.access_token_expires = int(time.time() + expires_in - 60)
@staticmethod
def _query_data(params):
return urllib.parse.urlencode({key: value for key, value in params.items() if key})
def refresh_access_token(self, callback):
log.debug("OAuth: refreshing access_token with a refresh_token %s", self.refresh_token)
params = {
'grant_type': 'refresh_token',
'refresh_token': self.refresh_token,
'client_id': MUSICBRAINZ_OAUTH_CLIENT_ID,
'client_secret': MUSICBRAINZ_OAUTH_CLIENT_SECRET,
}
self.webservice.post_url(
url=self.url(path="/oauth2/token"),
data=self._query_data(params),
handler=partial(self.on_refresh_access_token_finished, callback),
mblogin=True,
priority=True,
important=True,
request_mimetype='application/x-www-form-urlencoded',
)
def on_refresh_access_token_finished(self, callback, data, http, error):
access_token = None
try:
if error:
log.error("OAuth: access_token refresh failed: %s", data)
if self._http_code(http) == 400:
response = load_json(data)
if response['error'] == 'invalid_grant':
self.forget_refresh_token()
else:
access_token = data['access_token']
self.set_access_token(access_token, data['expires_in'])
except Exception as e:
log.error("OAuth: Unexpected error handling access token response: %r", e)
finally:
callback(access_token=access_token)
def exchange_authorization_code(self, authorization_code, scopes, callback):
log.debug("OAuth: exchanging authorization_code %s for an access_token", authorization_code)
params = {
'grant_type': 'authorization_code',
'code': authorization_code,
'client_id': MUSICBRAINZ_OAUTH_CLIENT_ID,
'client_secret': MUSICBRAINZ_OAUTH_CLIENT_SECRET,
'redirect_uri': self.redirect_uri,
'code_verifier': self.__code_verifier,
}
self.webservice.post_url(
url=self.url(path="/oauth2/token"),
data=self._query_data(params),
handler=partial(self.on_exchange_authorization_code_finished, scopes, callback),
mblogin=True,
priority=True,
important=True,
request_mimetype='application/x-www-form-urlencoded',
)
def on_exchange_authorization_code_finished(self, scopes, callback, data, http, error):
successful = False
error_msg = None
try:
if error:
log.error("OAuth: authorization_code exchange failed: %s", data)
error_msg = self._extract_error_description(http, data)
else:
self.set_refresh_token(data['refresh_token'], scopes)
self.set_access_token(data['access_token'], data['expires_in'])
successful = True
except Exception as e:
log.error("OAuth: Unexpected error handling authorization code response: %r", e)
error_msg = _("Unexpected authentication error")
finally:
callback(successful=successful, error_msg=error_msg)
def fetch_username(self, callback):
log.debug("OAuth: fetching username")
self.webservice.get_url(
url=self.url(path="/oauth2/userinfo"),
handler=partial(self.on_fetch_username_finished, callback),
mblogin=True,
priority=True,
important=True,
)
def on_fetch_username_finished(self, callback, data, http, error):
successful = False
error_msg = None
try:
if error:
log.error("OAuth: username fetching failed: %s", data)
error_msg = self._extract_error_description(http, data)
else:
self.username = data['sub']
log.debug("OAuth: got username %s", self.username)
successful = True
except Exception as e:
log.error("OAuth: Unexpected error handling username fetch response: %r", e)
error_msg = _("Unexpected authentication error")
finally:
callback(successful=successful, error_msg=error_msg)
def _http_code(self, http):
return self.webservice.http_response_code(http)
def _extract_error_description(self, http, data):
try:
response = load_json(data)
return response['error_description']
except (JSONDecodeError, KeyError, TypeError):
return _("Unexpected request error (HTTP code %s)") % self._http_code(http)
def s256_encode(input: bytes) -> bytes:
"""Implements the S256 code challenge encoding as defined for PKCE in RFC 7636.
The input data gets hashed by SHA256 and Base64url encoded.
See also https://datatracker.ietf.org/doc/html/rfc7636#section-4.2
Args:
input (bytes): Input bytes to encode. Is expected to consist only of ASCII characters.
Returns:
bytes: encoded data
"""
return base64url_encode(sha256(input).digest())
def base64url_encode(input: bytes) -> bytes:
"""Implements the Base64url Encoding as defined for PKCE in RFC 7636.
Base64 encoding using the URL- and filename-safe character set
defined in Section 5 of [RFC4648], with all trailing '='
characters omitted (as permitted by Section 3.2 of [RFC4648]) and
without the inclusion of any line breaks, whitespace, or other
additional characters.
See also https://datatracker.ietf.org/doc/html/rfc7636#appendix-A
Args:
s (bytes): Input bytes to encode.
Returns:
bytes: Base64url encoded data
"""
return urlsafe_b64encode(input).rstrip(b'=')
| 14,894
|
Python
|
.py
| 356
| 33.123596
| 100
| 0.644497
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,931
|
file.py
|
metabrainz_picard/picard/file.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2004 Robert Kaye
# Copyright (C) 2006-2009, 2011-2013, 2017 Lukáš Lalinský
# Copyright (C) 2007-2011, 2015, 2018-2024 Philipp Wolfer
# Copyright (C) 2008 Gary van der Merwe
# Copyright (C) 2008-2009 Nikolai Prokoschenko
# Copyright (C) 2009 Carlin Mangar
# Copyright (C) 2009 David Hilton
# Copyright (C) 2011-2014 Michael Wiencek
# Copyright (C) 2012 Erik Wasser
# Copyright (C) 2012 Johannes Weißl
# Copyright (C) 2012 noobie
# Copyright (C) 2012-2014 Wieland Hoffmann
# Copyright (C) 2013 Calvin Walton
# Copyright (C) 2013-2014 Ionuț Ciocîrlan
# Copyright (C) 2013-2014, 2017, 2021 Sophist-UK
# Copyright (C) 2013-2014, 2017-2024 Laurent Monin
# Copyright (C) 2016 Rahul Raturi
# Copyright (C) 2016 Ville Skyttä
# Copyright (C) 2016-2018 Sambhav Kothari
# Copyright (C) 2017-2018 Antonio Larrosa
# Copyright (C) 2019 Joel Lintunen
# Copyright (C) 2020 Ray Bouchard
# Copyright (C) 2020-2021 Gabriel Ferreira
# Copyright (C) 2021 Petit Minion
# Copyright (C) 2021, 2023 Bob Swift
# Copyright (C) 2024 Suryansh Shakya
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from collections import Counter
from enum import (
Enum,
auto,
)
import fnmatch
from functools import partial
import os
import os.path
import re
import shutil
import time
from mutagen._util import MutagenError
from picard import (
PICARD_APP_NAME,
log,
)
from picard.config import get_config
from picard.const.defaults import DEFAULT_TIME_FORMAT
from picard.const.sys import (
IS_MACOS,
IS_WIN,
)
from picard.i18n import (
N_,
gettext as _,
)
from picard.item import MetadataItem
from picard.metadata import (
Metadata,
SimMatchTrack,
)
from picard.plugin import PluginFunctions
from picard.script import get_file_naming_script
from picard.util import (
any_exception_isinstance,
bytes2human,
decode_filename,
emptydir,
encode_filename,
find_best_match,
format_time,
is_absolute_path,
normpath,
thread,
tracknum_and_title_from_filename,
)
from picard.util.filenaming import (
get_available_filename,
make_save_path,
make_short_filename,
move_ensure_casing,
)
from picard.util.preservedtags import PreservedTags
from picard.util.scripttofilename import script_to_filename_with_metadata
from picard.util.tags import (
CALCULATED_TAGS,
FILE_INFO_TAGS,
PRESERVED_TAGS,
)
FILE_COMPARISON_WEIGHTS = {
'album': 5,
'artist': 4,
'date': 4,
'format': 2,
'isvideo': 2,
'length': 10,
'releasecountry': 2,
'releasetype': 14,
'title': 13,
'totaltracks': 4,
}
class FileErrorType(Enum):
UNKNOWN = auto()
NOTFOUND = auto()
NOACCESS = auto()
PARSER = auto()
class File(MetadataItem):
NAME = None
UNDEFINED = -1
PENDING = 0
NORMAL = 1
CHANGED = 2
ERROR = 3
REMOVED = 4
LOOKUP_METADATA = 1
LOOKUP_ACOUSTID = 2
EXTENSIONS = []
class PreserveTimesStatError(Exception):
pass
class PreserveTimesUtimeError(Exception):
pass
# in order to significantly speed up performance, the number of pending
# files is cached, set @state.setter
num_pending_files = 0
def __init__(self, filename):
super().__init__()
self.filename = filename
self.base_filename = os.path.basename(filename)
self._state = File.UNDEFINED
self.state = File.PENDING
self.error_type = FileErrorType.UNKNOWN
self.similarity = 1.0
self.parent_item = None
self.lookup_task = None
self.acoustid_fingerprint = None
self.acoustid_length = 0
self.match_recordingid = None
def __repr__(self):
return '<%s %r>' % (type(self).__name__, self.base_filename)
# pylint: disable=no-self-use
def format_specific_metadata(self, metadata, tag, settings=None):
"""Can be overridden to customize how a tag is displayed in the UI.
This is useful if a tag saved to the underlying format will differ from
the internal representation in a way that would cause data loss. This is e.g.
the case for some ID3v2.3 tags.
Args:
metadata: The metadata object to read the tag from
tag: Name of the tag
settings: Dictionary of settings. If not set, config.setting should be used
Returns:
An array of values for the tag
"""
return metadata.getall(tag)
def _format_specific_copy(self, metadata, settings=None):
"""Creates a copy of metadata, but applies format_specific_metadata() to the values.
"""
copy = Metadata(
deleted_tags=metadata.deleted_tags,
images=metadata.images,
length=metadata.length)
for name in metadata:
copy[name] = self.format_specific_metadata(metadata, name, settings)
return copy
def _set_error(self, error):
self.state = File.ERROR
if any_exception_isinstance(error, FileNotFoundError):
self.error_type = FileErrorType.NOTFOUND
elif any_exception_isinstance(error, PermissionError):
self.error_type = FileErrorType.NOACCESS
elif any_exception_isinstance(error, MutagenError):
self.error_type = FileErrorType.PARSER
self.error_append(_("The file failed to parse, either the file is damaged or has an unsupported file format."))
else:
self.error_type = FileErrorType.UNKNOWN
self.error_append(str(error))
def load(self, callback):
thread.run_task(
partial(self._load_check, self.filename),
partial(self._loading_finished, callback),
priority=1)
def _load_check(self, filename):
# Check that file has not been removed since thread was queued
# Don't load if we are stopping.
if self.state != File.PENDING:
log.debug("File not loaded because it was removed: %r", self.filename)
return None
if self.tagger.stopping:
log.debug("File not loaded because %s is stopping: %r", PICARD_APP_NAME, self.filename)
return None
return self._load(filename)
def _load(self, filename):
"""Load metadata from the file."""
raise NotImplementedError
def _loading_finished(self, callback, result=None, error=None):
if self.state != File.PENDING or self.tagger.stopping:
return
config = get_config()
if error is not None:
self._set_error(error)
# If loading failed, force format guessing and try loading again
from picard.formats.util import guess_format
try:
alternative_file = guess_format(self.filename)
except (FileNotFoundError, OSError):
log.error("Guessing format of %s failed", self.filename, exc_info=True)
alternative_file = None
if alternative_file:
# Do not retry reloading exactly the same file format
if type(alternative_file) != type(self): # pylint: disable=unidiomatic-typecheck # noqa: E721
log.debug("Loading %r failed, retrying as %r", self, alternative_file)
self.remove()
alternative_file.load(callback)
return
else:
alternative_file.remove() # cleanup unused File object
from picard.formats import supported_extensions
file_name, file_extension = os.path.splitext(self.base_filename)
if file_extension not in supported_extensions():
log.error("Unsupported media file %r wrongly loaded. Removing …", self)
callback(self, remove_file=True)
return
else:
self.clear_errors()
self.state = self.NORMAL
postprocessors = []
if config.setting['guess_tracknumber_and_title']:
postprocessors.append(self._guess_tracknumber_and_title)
self._copy_loaded_metadata(result, postprocessors)
# use cached fingerprint from file metadata
if not config.setting['ignore_existing_acoustid_fingerprints']:
fingerprints = self.metadata.getall('acoustid_fingerprint')
if fingerprints:
self.set_acoustid_fingerprint(fingerprints[0])
run_file_post_load_processors(self)
callback(self)
def _copy_loaded_metadata(self, metadata, postprocessors=None):
metadata['~length'] = format_time(metadata.length)
if postprocessors:
for processor in postprocessors:
processor(metadata)
self.orig_metadata = metadata
self.metadata.copy(metadata)
def _guess_tracknumber_and_title(self, metadata):
missing = {'tracknumber', 'title'} - set(metadata)
if missing:
guessed = tracknum_and_title_from_filename(self.base_filename)
for m in missing:
metadata[m] = getattr(guessed, m)
def _copy_file_info_tags(self, to_metadata, from_metadata):
for tag in FILE_INFO_TAGS:
to_metadata[tag] = from_metadata[tag]
def copy_metadata(self, metadata, preserve_deleted=True):
saved_metadata = {}
# Keep current value for special tags that got calculated from audio content
for tag in CALCULATED_TAGS:
if tag not in metadata.deleted_tags and self.metadata[tag]:
saved_metadata[tag] = self.metadata[tag]
# Keep original values of preserved tags
preserved_tags = PreservedTags()
for tag, values in self.orig_metadata.rawitems():
if tag in preserved_tags or tag in PRESERVED_TAGS:
saved_metadata[tag] = values
deleted_tags = self.metadata.deleted_tags
images_changed = self.metadata.images != metadata.images
self.metadata.copy(metadata)
self._copy_file_info_tags(metadata, self.orig_metadata)
if preserve_deleted:
for tag in deleted_tags:
del self.metadata[tag]
self.metadata.update(saved_metadata)
if images_changed:
self.metadata_images_changed.emit()
def keep_original_images(self):
if self.metadata.images != self.orig_metadata.images:
self.metadata.images = self.orig_metadata.images.copy()
self.update(signal=False)
self.metadata_images_changed.emit()
def has_error(self):
return self.state == File.ERROR
def save(self):
self.set_pending()
metadata = Metadata()
metadata.copy(self.metadata)
thread.run_task(
partial(self._save_and_rename, self.filename, metadata),
self._saving_finished,
thread_pool=self.tagger.save_thread_pool)
def _preserve_times(self, filename, func):
"""Save filename times before calling func, and set them again"""
try:
# https://docs.python.org/3/library/os.html#os.utime
# Since Python 3.3, ns parameter is available
# The best way to preserve exact times is to use the st_atime_ns and st_mtime_ns
# fields from the os.stat() result object with the ns parameter to utime.
st = os.stat(filename)
except OSError as why:
errmsg = "Couldn't read timestamps from %r: %s" % (filename, why)
raise self.PreserveTimesStatError(errmsg) from None
# if we can't read original times, don't call func and let caller handle this
func()
try:
os.utime(filename, ns=(st.st_atime_ns, st.st_mtime_ns))
except OSError as why:
errmsg = "Couldn't preserve timestamps for %r: %s" % (filename, why)
raise self.PreserveTimesUtimeError(errmsg) from None
return (st.st_atime_ns, st.st_mtime_ns)
def _save_and_rename(self, old_filename, metadata):
"""Save the metadata."""
config = get_config()
# Check that file has not been removed since thread was queued
# Also don't save if we are stopping.
if self.state == File.REMOVED:
log.debug("File not saved because it was removed: %r", self.filename)
return None
if self.tagger.stopping:
log.debug("File not saved because %s is stopping: %r", PICARD_APP_NAME, self.filename)
return None
new_filename = old_filename
if not config.setting['dont_write_tags']:
save = partial(self._save, old_filename, metadata)
if config.setting['preserve_timestamps']:
try:
self._preserve_times(old_filename, save)
except self.PreserveTimesUtimeError as why:
log.warning(why)
else:
save()
# Rename files
if config.setting['rename_files'] or config.setting['move_files']:
new_filename = self._rename(old_filename, metadata, config.setting)
# Move extra files (images, playlists, etc.)
self._move_additional_files(old_filename, new_filename, config)
# Delete empty directories
if config.setting['delete_empty_dirs']:
dirname = os.path.dirname(old_filename)
try:
emptydir.rm_empty_dir(dirname)
head, tail = os.path.split(dirname)
if not tail:
head, tail = os.path.split(head)
while head and tail:
emptydir.rm_empty_dir(head)
head, tail = os.path.split(head)
except OSError as why:
log.warning("Error removing directory: %s", why)
except emptydir.SkipRemoveDir as why:
log.debug("Not removing empty directory: %s", why)
# Save cover art images
if config.setting['save_images_to_files']:
self._save_images(os.path.dirname(new_filename), metadata)
return new_filename
def _saving_finished(self, result=None, error=None):
# Handle file removed before save
# Result is None if save was skipped
if ((self.state == File.REMOVED or self.tagger.stopping)
and result is None):
return
old_filename = new_filename = self.filename
if error is not None:
self._set_error(error)
else:
self.filename = new_filename = result
self.base_filename = os.path.basename(new_filename)
length = self.orig_metadata.length
temp_info = {}
self._copy_file_info_tags(temp_info, self.orig_metadata)
images_changed = self.orig_metadata.images != self.metadata.images
# Copy new metadata to original metadata, applying format specific
# conversions (e.g. for ID3v2.3)
config = get_config()
new_metadata = self._format_specific_copy(self.metadata, config.setting)
if config.setting['clear_existing_tags']:
self.orig_metadata = new_metadata
else:
self.orig_metadata.update(new_metadata)
# After saving deleted tags should no longer be marked deleted
self.metadata.clear_deleted()
self.orig_metadata.clear_deleted()
self.orig_metadata.length = length
self.orig_metadata['~length'] = format_time(length)
self.orig_metadata.update(temp_info)
self.clear_errors()
self.clear_pending(signal=False)
self._update_filesystem_metadata(self.orig_metadata)
if images_changed:
self.metadata_images_changed.emit()
# run post save hook
run_file_post_save_processors(self)
# Force update to ensure file status icon changes immediately after save
self.update()
if self.state != File.REMOVED:
del self.tagger.files[old_filename]
self.tagger.files[new_filename] = self
if self.tagger.stopping:
log.debug("Save of %r completed before stopping Picard", self.filename)
def _save(self, filename, metadata):
"""Save the metadata."""
raise NotImplementedError
def _script_to_filename(self, naming_format, file_metadata, file_extension, settings=None):
if settings is None:
config = get_config()
settings = config.setting
metadata = Metadata()
if settings['clear_existing_tags']:
# script_to_filename_with_metadata guarantees this is not modified
metadata = file_metadata
else:
metadata.copy(self.orig_metadata)
metadata.update(file_metadata)
(filename, new_metadata) = script_to_filename_with_metadata(
naming_format, metadata, file=self, settings=settings)
basename = os.path.basename(filename)
if not basename:
old_name = os.path.splitext(os.path.basename(self.filename))[0]
filename = os.path.join(os.path.dirname(filename), old_name)
# NOTE: the filename generated by the naming script does not have a file extension
ext = new_metadata.get('~extension', file_extension)
return filename + '.' + ext.lstrip('.')
def _fixed_splitext(self, filename):
# In case the filename is blank and only has the extension
# the real extension is in new_filename and ext is blank
new_filename, ext = os.path.splitext(filename)
if ext == '' and new_filename.lower() in self.EXTENSIONS:
ext = new_filename
new_filename = ''
return new_filename, ext
def _clean_file_extension(self, filename):
"""Takes a filename and converts the extension to lowercase.
If the file has no extension a default extension for the format is used.
Args:
filename: The filename
Returns: A tuple containing the filename with fixed extension and the extension itself.
"""
filename, ext = self._fixed_splitext(filename)
if not ext and self.EXTENSIONS:
ext = self.EXTENSIONS[0]
ext = ext.lower()
return (filename + ext, ext)
def _format_filename(self, new_dirname, new_filename, metadata, settings, naming_format):
old_filename = new_filename
new_filename, ext = self._clean_file_extension(new_filename)
if naming_format:
new_filename = self._script_to_filename(naming_format, metadata, ext, settings)
if not settings['rename_files']:
new_filename = os.path.join(os.path.dirname(new_filename), old_filename)
if not settings['move_files']:
new_filename = os.path.basename(new_filename)
win_compat = IS_WIN or settings['windows_compatibility']
win_shorten_path = win_compat and not settings['windows_long_paths']
new_filename = make_short_filename(new_dirname, new_filename, win_shorten_path=win_shorten_path)
new_filename = make_save_path(new_filename, win_compat=win_compat, mac_compat=IS_MACOS)
return new_filename
def make_filename(self, filename, metadata, settings=None, naming_format=None):
"""Constructs file name based on metadata and file naming formats."""
if settings is None:
config = get_config()
settings = config.setting
if naming_format is None:
naming_format = get_file_naming_script(settings)
if settings['move_files']:
new_dirname = settings['move_files_to']
if not is_absolute_path(new_dirname):
new_dirname = os.path.join(os.path.dirname(filename), new_dirname)
else:
new_dirname = os.path.dirname(filename)
new_filename = os.path.basename(filename)
if settings['rename_files'] or settings['move_files']:
new_filename = self._format_filename(new_dirname, new_filename, metadata, settings, naming_format)
new_path = os.path.join(new_dirname, new_filename)
return normpath(new_path)
def _rename(self, old_filename, metadata, settings=None):
new_filename = self.make_filename(old_filename, metadata, settings)
if old_filename == new_filename:
return old_filename
new_dirname = os.path.dirname(new_filename)
if not os.path.isdir(new_dirname):
os.makedirs(new_dirname)
new_filename = get_available_filename(new_filename, old_filename)
log.debug("Moving file %r => %r", old_filename, new_filename)
move_ensure_casing(old_filename, new_filename)
return new_filename
def _save_images(self, dirname, metadata):
"""Save the cover images to disk."""
if not metadata.images:
return
counters = Counter()
images = []
config = get_config()
if config.setting['save_only_one_front_image']:
front = metadata.images.get_front_image()
if front:
images.append(front)
if not images:
images = metadata.images
for image in images:
image.save(dirname, metadata, counters)
def _move_additional_files(self, old_filename, new_filename, config):
"""Move extra files, like images, playlists…"""
if config.setting['move_files'] and config.setting['move_additional_files']:
new_path = os.path.dirname(new_filename)
old_path = os.path.dirname(old_filename)
if new_path != old_path:
patterns_string = config.setting['move_additional_files_pattern']
patterns = self._compile_move_additional_files_pattern(patterns_string)
try:
moves = self._get_additional_files_moves(old_path, new_path, patterns)
self._apply_additional_files_moves(moves)
except OSError as why:
log.error("Failed to scan %r: %s", old_path, why)
@staticmethod
def _compile_move_additional_files_pattern(patterns_string):
return {
(re.compile(fnmatch.translate(pattern), re.IGNORECASE), pattern.startswith('.'))
for pattern in set(patterns_string.lower().split())
}
def _get_additional_files_moves(self, old_path, new_path, patterns):
if patterns:
with os.scandir(old_path) as scan:
for entry in scan:
is_hidden = entry.name.startswith('.')
for pattern_regex, match_hidden in patterns:
if is_hidden and not match_hidden:
continue
if pattern_regex.match(entry.name):
new_file_path = os.path.join(new_path, entry.name)
yield (entry.path, new_file_path)
break # we are done with this file
def _apply_additional_files_moves(self, moves):
for old_file_path, new_file_path in moves:
# FIXME we shouldn't do this from a thread!
if self.tagger.files.get(decode_filename(old_file_path)):
log.debug("File loaded in the tagger, not moving %r", old_file_path)
continue
log.debug("Moving %r to %r", old_file_path, new_file_path)
try:
shutil.move(old_file_path, new_file_path)
except OSError as why:
log.error("Failed to move %r to %r: %s", old_file_path,
new_file_path, why)
def remove(self, from_parent_item=True):
if from_parent_item and self.parent_item:
log.debug("Removing %r from %r", self, self.parent_item)
self.parent_item.remove_file(self)
self.tagger.acoustidmanager.remove(self)
self.state = File.REMOVED
def move(self, to_parent_item):
# To be able to move a file the target must implement add_file(file)
if hasattr(to_parent_item, 'add_file') and to_parent_item != self.parent_item:
log.debug("Moving %r from %r to %r", self, self.parent_item, to_parent_item)
self.clear_lookup_task()
self.tagger._acoustid.stop_analyze(self)
new_album = True
if self.parent_item:
new_album = self.parent_item.album != to_parent_item.album
self.clear_pending()
self.parent_item.remove_file(self, new_album=new_album)
self.parent_item = to_parent_item
self.parent_item.add_file(self, new_album=new_album)
self.acoustid_update()
return True
else:
return False
def _move(self, to_parent_item):
if to_parent_item != self.parent_item:
log.debug("Moving %r from %r to %r", self, self.parent_item, to_parent_item)
if self.parent_item:
self.parent_item.remove_file(self)
self.parent_item = to_parent_item
self.acoustid_update()
def set_acoustid_fingerprint(self, fingerprint, length=None):
if not fingerprint:
self.acoustid_fingerprint = None
self.acoustid_length = 0
self.tagger.acoustidmanager.remove(self)
elif fingerprint != self.acoustid_fingerprint:
self.acoustid_fingerprint = fingerprint
self.acoustid_length = length or self.metadata.length // 1000
self.tagger.acoustidmanager.add(self, None)
self.acoustid_update()
config = get_config()
if config.setting['save_acoustid_fingerprints']:
self.metadata['acoustid_fingerprint'] = fingerprint
def acoustid_update(self):
recording_id = None
if self.parent_item and self.parent_item.can_link_fingerprint:
recording_id = self.parent_item.orig_metadata['musicbrainz_recordingid']
if not recording_id:
recording_id = self.metadata['musicbrainz_recordingid']
self.tagger.acoustidmanager.update(self, recording_id)
self.update_item()
@classmethod
def supports_tag(cls, name):
"""Returns whether tag ``name`` can be saved to the file."""
return True
def is_saved(self):
return self.similarity == 1.0 and self.state == File.NORMAL
def _tags_to_update(self, ignored_tags):
for name in set(self.metadata) | set(self.orig_metadata):
if name.startswith('~'):
continue
if name in ignored_tags:
continue
if not self.supports_tag(name):
continue
yield name
def update(self, signal=True):
if not (self.state == File.ERROR and self.errors):
config = get_config()
clear_existing_tags = config.setting['clear_existing_tags']
ignored_tags = set(config.setting['compare_ignore_tags'])
for name in self._tags_to_update(ignored_tags):
new_values = self.format_specific_metadata(self.metadata, name, config.setting)
if not (
new_values
or clear_existing_tags
or name in self.metadata.deleted_tags
):
continue
orig_values = self.orig_metadata.getall(name)
if orig_values != new_values:
self.similarity = self.orig_metadata.compare(self.metadata, ignored_tags)
if self.state == File.NORMAL:
self.state = File.CHANGED
break
else:
self.similarity = 1.0
if self.state in (File.CHANGED, File.NORMAL):
if (self.metadata.images
and self.orig_metadata.images != self.metadata.images):
self.state = File.CHANGED
else:
self.state = File.NORMAL
if signal:
log.debug("Updating file %r", self)
self.update_item()
@property
def can_save(self):
"""Return if this object can be saved."""
return True
@property
def can_remove(self):
"""Return if this object can be removed."""
return True
@property
def can_edit_tags(self):
"""Return if this object supports tag editing."""
return True
@property
def can_analyze(self):
"""Return if this object can be fingerprinted."""
return True
@property
def can_autotag(self):
return True
@property
def can_refresh(self):
return False
@property
def can_view_info(self):
return True
def _info(self, metadata, file):
if hasattr(file.info, 'length'):
metadata.length = int(file.info.length * 1000)
if hasattr(file.info, 'bitrate') and file.info.bitrate:
metadata['~bitrate'] = file.info.bitrate / 1000.0
if hasattr(file.info, 'sample_rate') and file.info.sample_rate:
metadata['~sample_rate'] = file.info.sample_rate
if hasattr(file.info, 'channels') and file.info.channels:
metadata['~channels'] = file.info.channels
if hasattr(file.info, 'bits_per_sample') and file.info.bits_per_sample:
metadata['~bits_per_sample'] = file.info.bits_per_sample
if self.NAME:
metadata['~format'] = self.NAME
else:
metadata['~format'] = self.__class__.__name__.replace('File', '')
self._update_filesystem_metadata(metadata)
def _update_filesystem_metadata(self, metadata):
metadata['~dirname'] = os.path.dirname(self.filename)
filename_no_ext, extension = os.path.splitext(os.path.basename(self.filename))
metadata['~filename'] = filename_no_ext
metadata['~extension'] = extension.lower()[1:]
filename_encoded = encode_filename(self.filename)
try:
metadata['~filesize'] = os.path.getsize(filename_encoded)
created = os.path.getctime(filename_encoded)
created_timestamp = time.strftime(DEFAULT_TIME_FORMAT, time.localtime(created))
metadata['~file_created_timestamp'] = created_timestamp
modified = os.path.getmtime(filename_encoded)
modified_timestamp = time.strftime(DEFAULT_TIME_FORMAT, time.localtime(modified))
metadata['~file_modified_timestamp'] = modified_timestamp
except OSError as ex:
log.error(f"File access error: {ex}")
@property
def state(self):
"""Current state of the File object"""
return self._state
@state.setter
def state(self, state):
if state == self._state:
return
if state == File.PENDING:
File.num_pending_files += 1
self.tagger.tagger_stats_changed.emit()
elif self._state == File.PENDING:
File.num_pending_files -= 1
self.tagger.tagger_stats_changed.emit()
self._state = state
def column(self, column):
m = self.metadata
if column == 'title' and not m['title']:
return self.base_filename
elif column == 'covercount':
return self.cover_art_description()
elif column == 'coverdimensions':
return self.cover_art_dimensions()
value = m[column]
if not value and not get_config().setting['clear_existing_tags']:
value = self.orig_metadata[column]
if column == '~filesize':
try:
value = bytes2human.binary(value)
except ValueError:
pass
return value
def _lookup_finished(self, lookuptype, document, http, error):
self.lookup_task = None
if self.state == File.REMOVED:
return
if error:
log.error("Network error encountered during the lookup for %s. Error code: %s",
self.filename, error)
try:
tracks = document['recordings']
except (KeyError, TypeError):
tracks = None
def statusbar(message):
self.tagger.window.set_statusbar_message(
message,
{'filename': self.filename},
timeout=3000
)
if tracks:
if lookuptype == File.LOOKUP_ACOUSTID:
threshold = 0
else:
config = get_config()
threshold = config.setting['file_lookup_threshold']
trackmatch = self._match_to_track(tracks, threshold=threshold)
if trackmatch is None:
statusbar(N_("No matching tracks above the threshold for file '%(filename)s'"))
else:
statusbar(N_("File '%(filename)s' identified!"))
(recording_id, release_group_id, release_id, acoustid, node) = trackmatch
if lookuptype == File.LOOKUP_ACOUSTID:
self.metadata['acoustid_id'] = acoustid
self.tagger.acoustidmanager.add(self, recording_id)
if release_group_id is not None:
releasegroup = self.tagger.get_release_group_by_id(release_group_id)
releasegroup.loaded_albums.add(release_id)
self.tagger.move_file_to_track(self, release_id, recording_id)
else:
self.tagger.move_file_to_nat(self, recording_id)
else:
statusbar(N_("No matching tracks for file '%(filename)s'"))
self.clear_pending()
def _match_to_track(self, tracks, threshold=0):
# multiple matches -- calculate similarities to each of them
candidates = (
self.metadata.compare_to_track(track, FILE_COMPARISON_WEIGHTS)
for track in tracks
)
no_match = SimMatchTrack(similarity=-1, releasegroup=None, release=None, track=None)
best_match = find_best_match(candidates, no_match)
if best_match.similarity < threshold:
return None
else:
track_id = best_match.result.track['id']
release_group_id, release_id, node = None, None, None
acoustid = best_match.result.track.get('acoustid', None)
if best_match.result.release:
release_group_id = best_match.result.releasegroup['id']
release_id = best_match.result.release['id']
elif 'title' in best_match.result.track:
node = best_match.result.track
return (track_id, release_group_id, release_id, acoustid, node)
def lookup_metadata(self):
"""Try to identify the file using the existing metadata."""
if self.lookup_task:
return
self.tagger.window.set_statusbar_message(
N_("Looking up the metadata for file %(filename)s …"),
{'filename': self.filename}
)
self.clear_lookup_task()
metadata = self.metadata
self.set_pending()
config = get_config()
self.lookup_task = self.tagger.mb_api.find_tracks(
partial(self._lookup_finished, File.LOOKUP_METADATA),
track=metadata['title'],
artist=metadata['artist'],
release=metadata['album'],
tnum=metadata['tracknumber'],
tracks=metadata['totaltracks'],
qdur=str(metadata.length // 2000),
isrc=metadata['isrc'],
limit=config.setting['query_limit'])
def clear_lookup_task(self):
if self.lookup_task:
self.tagger.webservice.remove_task(self.lookup_task)
self.lookup_task = None
def set_pending(self):
if self.state != File.REMOVED:
self.state = File.PENDING
self.update_item(update_selection=False)
def clear_pending(self, signal=True):
if self.state == File.PENDING:
self.state = File.NORMAL
# Update file to recalculate changed state
self.update(signal=False)
if signal:
self.update_item(update_selection=False)
def update_item(self, update_selection=True):
if self.ui_item:
self.ui_item.update(update_selection=update_selection)
def iterfiles(self, save=False):
yield self
file_post_load_processors = PluginFunctions(label='file_post_load_processors')
file_post_addition_to_track_processors = PluginFunctions(label='file_post_addition_to_track_processors')
file_post_removal_to_track_processors = PluginFunctions(label='file_post_removal_from_track_processors')
file_post_save_processors = PluginFunctions(label='file_post_save_processors')
def run_file_post_load_processors(file_object):
file_post_load_processors.run(file_object)
def run_file_post_addition_to_track_processors(track_object, file_object):
file_post_addition_to_track_processors.run(track_object, file_object)
def run_file_post_removal_from_track_processors(track_object, file_object):
file_post_removal_to_track_processors.run(track_object, file_object)
def run_file_post_save_processors(file_object):
file_post_save_processors.run(file_object)
| 38,166
|
Python
|
.py
| 854
| 34.425059
| 123
| 0.621856
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,932
|
collection.py
|
metabrainz_picard/picard/collection.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2013 Michael Wiencek
# Copyright (C) 2014 Lukáš Lalinský
# Copyright (C) 2014, 2017 Sophist-UK
# Copyright (C) 2014, 2017-2021, 2023-2024 Laurent Monin
# Copyright (C) 2016-2017 Sambhav Kothari
# Copyright (C) 2019, 2021-2022, 2024 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from functools import partial
from PyQt6 import QtCore
from picard import log
from picard.config import get_config
from picard.i18n import (
N_,
ngettext,
)
from picard.webservice.api_helpers import MBAPIHelper
user_collections = {}
class Collection:
def __init__(self, collection_id: str, mb_api: MBAPIHelper):
self.tagger = QtCore.QCoreApplication.instance()
self.id = collection_id
self.name = ''
self.size = 0
self.pending_releases = set()
self.releases = set()
self._mb_api = mb_api
@property
def size(self):
return self._size
@size.setter
def size(self, value):
self._size = int(value)
def __repr__(self):
return '<Collection %s (%s)>' % (self.name, self.id)
def _modify(self, api_method, success_handler, releases, callback):
releases -= self.pending_releases
if releases:
self.pending_releases |= releases
when_done = partial(self._finished, success_handler, releases, callback)
api_method(self.id, list(releases), when_done)
def add_releases(self, releases, callback):
api_method = self._mb_api.put_to_collection
self._modify(api_method, self._success_add, set(releases), callback)
def remove_releases(self, releases, callback):
api_method = self._mb_api.delete_from_collection
self._modify(api_method, self._success_remove, set(releases), callback)
def _finished(self, success_handler, releases, callback, document, reply, error):
self.pending_releases -= releases
if not error:
success_handler(releases, callback)
else:
self._error(reply)
def _error(self, reply):
self.tagger.window.set_statusbar_message(
N_("Error while modifying collections: %(error)s"),
{'error': reply.errorString()},
echo=log.error
)
def _success_add(self, releases, callback):
count = len(releases)
self.releases |= releases
self.size += count
status_msg = ngettext(
'Added %(count)i release to collection "%(name)s"',
'Added %(count)i releases to collection "%(name)s"',
count)
debug_msg = 'Added %(count)i release(s) to collection "%(name)s"'
self._success(count, callback, status_msg, debug_msg)
def _success_remove(self, releases, callback):
count = len(releases)
self.releases -= releases
self.size -= count
status_msg = ngettext(
'Removed %(count)i release from collection "%(name)s"',
'Removed %(count)i releases from collection "%(name)s"',
count)
debug_msg = 'Removed %(count)i release(s) from collection "%(name)s"'
self._success(count, callback, status_msg, debug_msg)
def _success(self, count, callback, status_msg, debug_msg):
callback()
mparms = {'count': count, 'name': self.name}
log.debug(debug_msg % mparms)
self.tagger.window.set_statusbar_message(status_msg, mparms, translate=None, echo=None)
def get_user_collection(collection_id):
collection = user_collections.get(collection_id)
if collection is None:
tagger = QtCore.QCoreApplication.instance()
collection = user_collections[collection_id] = Collection(collection_id, tagger.mb_api)
return collection
def load_user_collections(callback=None):
tagger = QtCore.QCoreApplication.instance()
def request_finished(document, reply, error):
if error:
tagger.window.set_statusbar_message(
N_("Error loading collections: %(error)s"),
{'error': reply.errorString()},
echo=log.error
)
return
if document and 'collections' in document:
collection_list = document['collections']
new_collections = set()
for node in collection_list:
if node['entity-type'] != 'release':
continue
col_id = node['id']
new_collections.add(col_id)
collection = get_user_collection(col_id)
collection.name = node['name']
collection.size = node['release-count']
# remove collections which aren't returned by the web service anymore
old_collections = set(user_collections) - new_collections
for collection_id in old_collections:
del user_collections[collection_id]
log.debug("User collections: %r", [(k, v.name) for k, v in user_collections.items()])
if callback:
callback()
if tagger.webservice.oauth_manager.is_authorized():
tagger.mb_api.get_collection_list(partial(request_finished))
else:
user_collections.clear()
def add_release_to_user_collections(release_node):
"""Add album to collections"""
# Check for empty collection list
if 'collections' in release_node:
release_id = release_node['id']
config = get_config()
username = config.persist['oauth_username'].lower()
for node in release_node['collections']:
if node['editor'].lower() == username:
collection = get_user_collection(node['id'])
collection.name = node['name']
collection.size = node['release-count']
collection.releases.add(release_id)
log.debug("Adding release %r to %r", release_id, collection)
| 6,631
|
Python
|
.py
| 152
| 35.421053
| 97
| 0.644475
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,933
|
options.py
|
metabrainz_picard/picard/options.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2024 Laurent Monin
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import logging
from PyQt6 import QtCore
from picard.config import (
BoolOption,
FloatOption,
IntOption,
ListOption,
Option,
TextOption,
)
from picard.const import MUSICBRAINZ_SERVERS
from picard.const.defaults import (
DEFAULT_AUTOBACKUP_DIRECTORY,
DEFAULT_CA_NEVER_REPLACE_TYPE_EXCLUDE,
DEFAULT_CA_NEVER_REPLACE_TYPE_INCLUDE,
DEFAULT_CA_PROVIDERS,
DEFAULT_CAA_IMAGE_SIZE,
DEFAULT_CAA_IMAGE_TYPE_EXCLUDE,
DEFAULT_CAA_IMAGE_TYPE_INCLUDE,
DEFAULT_CACHE_SIZE_IN_BYTES,
DEFAULT_COVER_CONVERTING_FORMAT,
DEFAULT_COVER_IMAGE_FILENAME,
DEFAULT_COVER_MAX_SIZE,
DEFAULT_COVER_MIN_SIZE,
DEFAULT_COVER_RESIZE_MODE,
DEFAULT_CURRENT_BROWSER_PATH,
DEFAULT_DRIVES,
DEFAULT_FPCALC_THREADS,
DEFAULT_LOCAL_COVER_ART_REGEX,
DEFAULT_LONG_PATHS,
DEFAULT_MUSIC_DIR,
DEFAULT_PROGRAM_UPDATE_LEVEL,
DEFAULT_QUERY_LIMIT,
DEFAULT_RELEASE_TYPE_SCORES,
DEFAULT_REPLACEMENT,
DEFAULT_SHOW_MENU_ICONS,
DEFAULT_STARTING_DIR,
DEFAULT_THEME_NAME,
DEFAULT_TOOLBAR_LAYOUT,
DEFAULT_TOP_TAGS,
DEFAULT_WIN_COMPAT_REPLACEMENTS,
)
from picard.i18n import N_
from picard.ui.colors import InterfaceColors
# Note: There are two steps to adding an option to an option page:
#
# 1. The option is added to the appropriate section below.
# If it's using a default value that may be used elsewhere,
# a constant starting with `DEFAULT_` can be added to `const/defaults.py`
# and imported here.
#
# The `title` parameter of `Option` is required for options that may be
# used in user profiles.
# The translated title will be displayed in Profiles option page.
#
# 2. If the option is a 'setting' which is edited in one of the option pages,
# then the option can be registered in the `__init__()` method of the
# matching `OptionPage` declaration with a call to the page's
# `register_setting()` method.
#
# Registering a setting allows it to be reset to the default when the user
# asks for it on the corresponding option page.
#
# If the setting can be overriden in profiles, the `highlights` parameter
# has to be set a list of widget names associated with the option.
#
#
# Please, try to keep options ordered by section and name in their own group.
# picard/coverart/providers/caa.py
# Cover Art Archive Cover Art Archive: Release
BoolOption('setting', 'caa_approved_only', False)
IntOption('setting', 'caa_image_size', DEFAULT_CAA_IMAGE_SIZE)
ListOption('setting', 'caa_image_types', DEFAULT_CAA_IMAGE_TYPE_INCLUDE)
ListOption('setting', 'caa_image_types_to_omit', DEFAULT_CAA_IMAGE_TYPE_EXCLUDE)
BoolOption('setting', 'caa_restrict_image_types', True)
# picard/coverart/providers/local.py
# Local Files
TextOption('setting', 'local_cover_regex', DEFAULT_LOCAL_COVER_ART_REGEX)
# picard/ui/cdlookup.py
#
Option('persist', 'cdlookupdialog_header_state', QtCore.QByteArray())
# picard/ui/filebrowser.py
#
TextOption('persist', 'current_browser_path', DEFAULT_CURRENT_BROWSER_PATH)
BoolOption('persist', 'show_hidden_files', False)
# Store Album View Header State
#
Option('persist', 'album_view_header_state', QtCore.QByteArray())
BoolOption('persist', 'album_view_header_locked', False)
# Store File View Header State
#
Option('persist', 'file_view_header_state', QtCore.QByteArray())
BoolOption('persist', 'file_view_header_locked', False)
# picard/ui/logview.py
#
IntOption('setting', 'log_verbosity', logging.WARNING)
# picard/ui/mainwindow.py
#
TextOption('persist', 'current_directory', "")
FloatOption('persist', 'mediaplayer_playback_rate', 1.0)
IntOption('persist', 'mediaplayer_volume', 50)
BoolOption('persist', 'view_cover_art', True)
BoolOption('persist', 'view_file_browser', False)
BoolOption('persist', 'view_metadata_view', True)
BoolOption('persist', 'view_toolbar', True)
BoolOption('persist', 'window_maximized', False)
Option('persist', 'window_state', QtCore.QByteArray())
# picard/ui/metadatabox.py
#
Option('persist', 'metadatabox_header_state', QtCore.QByteArray())
BoolOption('persist', 'show_changes_first', False)
# picard/ui/options/advanced.py
# Advanced
ListOption('setting', 'compare_ignore_tags', [], title=N_("Tags to ignore for comparison"))
BoolOption('setting', 'completeness_ignore_data', False, title=N_("Completeness check ignore: Data tracks"))
BoolOption('setting', 'completeness_ignore_pregap', False, title=N_("Completeness check ignore: Pregap tracks"))
BoolOption('setting', 'completeness_ignore_silence', False, title=N_("Completeness check ignore: Silent tracks"))
BoolOption('setting', 'completeness_ignore_videos', False, title=N_("Completeness check ignore: Video tracks"))
BoolOption('setting', 'ignore_hidden_files', False, title=N_("Ignore hidden files"))
TextOption('setting', 'ignore_regex', '', title=N_("Ignore file paths matching a regular expression"))
IntOption('setting', 'ignore_track_duration_difference_under', 2, title=N_("Ignore track duration difference under x seconds"))
IntOption('setting', 'query_limit', DEFAULT_QUERY_LIMIT, title=N_("Maximum number of entities to return per MusicBrainz query"))
BoolOption('setting', 'recursively_add_files', True, title=N_("Include sub-folders when adding files from folder"))
# picard/ui/options/cdlookup.py
# CD Lookup
TextOption('setting', 'cd_lookup_device', ','.join(DEFAULT_DRIVES))
# picard/ui/options/cover.py
# Cover Art
ListOption('setting', 'ca_providers', DEFAULT_CA_PROVIDERS, title=N_("Cover art providers"))
TextOption('setting', 'cover_image_filename', DEFAULT_COVER_IMAGE_FILENAME, title=N_("File name for images"))
BoolOption('setting', 'embed_only_one_front_image', True, title=N_("Embed only a single front image"))
BoolOption('setting', 'dont_replace_with_smaller_cover', False, title=N_("Never replace cover images with smaller ones"))
BoolOption('setting', 'dont_replace_cover_of_types', False, title=N_("Never replace cover images of the given types"))
ListOption('setting', 'dont_replace_included_types', DEFAULT_CA_NEVER_REPLACE_TYPE_INCLUDE, title=N_("Never replace cover images of these types"))
ListOption('setting', 'dont_replace_excluded_types', DEFAULT_CA_NEVER_REPLACE_TYPE_EXCLUDE, title=N_("Always replace cover images of these types"))
BoolOption('setting', 'image_type_as_filename', False, title=N_("Always use the primary image type as the file name for non-front images"))
BoolOption('setting', 'save_images_overwrite', False, title=N_("Overwrite existing image files"))
BoolOption('setting', 'save_images_to_files', False, title=N_("Save cover images as separate files"))
BoolOption('setting', 'save_images_to_tags', True, title=N_("Embed cover images into tags"))
BoolOption('setting', 'save_only_one_front_image', False, title=N_("Save only a single front image as separate file"))
# picard/ui/options/cover_processing.py
# Cover Art Image Processing
BoolOption('setting', 'filter_cover_by_size', False)
IntOption('setting', 'cover_minimum_width', DEFAULT_COVER_MIN_SIZE)
IntOption('setting', 'cover_minimum_height', DEFAULT_COVER_MIN_SIZE)
BoolOption('setting', 'cover_tags_enlarge', False)
BoolOption('setting', 'cover_tags_resize', False)
IntOption('setting', 'cover_tags_resize_target_width', DEFAULT_COVER_MAX_SIZE)
IntOption('setting', 'cover_tags_resize_target_height', DEFAULT_COVER_MAX_SIZE)
IntOption('setting', 'cover_tags_resize_mode', DEFAULT_COVER_RESIZE_MODE)
BoolOption('setting', 'cover_tags_convert_images', False)
TextOption('setting', 'cover_tags_convert_to_format', DEFAULT_COVER_CONVERTING_FORMAT)
BoolOption('setting', 'cover_file_enlarge', False)
BoolOption('setting', 'cover_file_resize', False)
IntOption('setting', 'cover_file_resize_target_width', DEFAULT_COVER_MAX_SIZE)
IntOption('setting', 'cover_file_resize_target_height', DEFAULT_COVER_MAX_SIZE)
IntOption('setting', 'cover_file_resize_mode', DEFAULT_COVER_RESIZE_MODE)
BoolOption('setting', 'cover_file_convert_images', False)
TextOption('setting', 'cover_file_convert_to_format', DEFAULT_COVER_CONVERTING_FORMAT)
# picard/ui/options/dialog.py
# Attached Profiles
TextOption('persist', 'options_last_active_page', '')
ListOption('persist', 'options_pages_tree_state', [])
# picard/ui/options/fingerprinting.py
# Fingerprinting
TextOption('setting', 'acoustid_apikey', '')
TextOption('setting', 'acoustid_fpcalc', '')
TextOption('setting', 'fingerprinting_system', 'acoustid')
IntOption('setting', 'fpcalc_threads', DEFAULT_FPCALC_THREADS)
BoolOption('setting', 'ignore_existing_acoustid_fingerprints', False)
BoolOption('setting', 'save_acoustid_fingerprints', False)
# picard/ui/options/general.py
# General
IntOption('persist', 'last_update_check', 0)
TextOption('persist', 'oauth_access_token', '')
IntOption('persist', 'oauth_access_token_expires', 0)
TextOption('persist', 'oauth_refresh_token', '')
TextOption('persist', 'oauth_refresh_token_scopes', '')
TextOption('persist', 'oauth_username', '')
BoolOption('setting', 'analyze_new_files', False, title=N_("Automatically scan all new files"))
BoolOption('setting', 'check_for_plugin_updates', False, title=N_("Check for plugin updates during startup"))
BoolOption('setting', 'check_for_updates', True, title=N_("Check for program updates during startup"))
BoolOption('setting', 'cluster_new_files', False, title=N_("Automatically cluster all new files"))
BoolOption('setting', 'ignore_file_mbids', False, title=N_("Ignore MBIDs when loading new files"))
TextOption('setting', 'server_host', MUSICBRAINZ_SERVERS[0], title=N_("Server address"))
IntOption('setting', 'server_port', 443, title=N_("Port"))
IntOption('setting', 'update_check_days', 7, title=N_("Days between update checks"))
IntOption('setting', 'update_level', DEFAULT_PROGRAM_UPDATE_LEVEL, title=N_("Updates to check"))
BoolOption('setting', 'use_server_for_submission', False)
# picard/ui/options/genres.py
# Genres
BoolOption('setting', 'artists_genres', False, title=N_("Use album artist genres"))
BoolOption('setting', 'folksonomy_tags', False, title=N_("Use folksonomy tags as genre"))
TextOption('setting', 'genres_filter', '-seen live\n-favorites\n-fixme\n-owned', title=N_("Genres to include or exclude"))
TextOption('setting', 'join_genres', '', title=N_("Join multiple genres with"))
IntOption('setting', 'max_genres', 5, title=N_("Maximum number of genres"))
IntOption('setting', 'min_genre_usage', 90, title=N_("Minimal genre usage"))
BoolOption('setting', 'only_my_genres', False, title=N_("Use only my genres"))
BoolOption('setting', 'use_genres', False, title=N_("Use genres from MusicBrainz"))
# picard/ui/options/interface.py
# User Interface
BoolOption('setting', 'allow_multi_dirs_selection', False, title=N_("Allow selection of multiple directories"))
BoolOption('setting', 'builtin_search', True, title=N_("Use builtin search rather than looking in browser"))
BoolOption('setting', 'filebrowser_horizontal_autoscroll', True, title=N_("Adjust horizontal position in file browser automatically"))
BoolOption('setting', 'file_save_warning', True, title=N_("Show a confirmation dialog when saving files"))
TextOption('setting', 'load_image_behavior', 'append')
BoolOption('setting', 'quit_confirmation', True, title=N_("Show a quit confirmation dialog for unsaved changes"))
BoolOption('setting', 'show_menu_icons', DEFAULT_SHOW_MENU_ICONS, title=N_("Show icons in menus"))
BoolOption('setting', 'show_new_user_dialog', True, title=N_("Show a usage warning dialog when Picard starts"))
BoolOption('setting', 'starting_directory', False, title=N_("Begin browsing in a specific directory"))
TextOption('setting', 'starting_directory_path', DEFAULT_STARTING_DIR, title=N_("Directory to begin browsing"))
BoolOption('setting', 'toolbar_show_labels', True, title=N_("Show text labels under icons"))
TextOption('setting', 'ui_language', '', title=N_("User interface language"))
TextOption('setting', 'ui_theme', DEFAULT_THEME_NAME, title=N_("User interface color theme"))
BoolOption('setting', 'use_adv_search_syntax', False, title=N_("Use advanced search syntax"))
# picard/ui/options/interface_colors.py
# Colors
Option('setting', 'interface_colors', InterfaceColors(dark_theme=False).get_colors(), title=N_("Colors to use for light theme"))
Option('setting', 'interface_colors_dark', InterfaceColors(dark_theme=True).get_colors(), title=N_("Colors to use for dark theme"))
# picard/ui/options/interface_toolbar.py
# Action Toolbar
def make_default_toolbar_layout():
for e in DEFAULT_TOOLBAR_LAYOUT:
if e == '-':
yield e
else:
# we want the string matching the MainAction
yield e.value
ListOption('setting', 'toolbar_layout', list(make_default_toolbar_layout()), title=N_("Layout of the tool bar"))
# picard/ui/options/interface_top_tags.py
# Top Tags
ListOption('setting', 'metadatabox_top_tags', DEFAULT_TOP_TAGS, title=N_("Tags to show at the top"))
# picard/ui/options/maintenance.py
# Maintenance
TextOption('setting', 'autobackup_directory', DEFAULT_AUTOBACKUP_DIRECTORY, title=N_("Automatic backup destination directory"))
# picard/ui/options/matching.py
# Matching
FloatOption('setting', 'cluster_lookup_threshold', 0.7, title=N_("Minimal similarity for cluster lookups"))
FloatOption('setting', 'file_lookup_threshold', 0.7, title=N_("Minimal similarity for file lookups"))
FloatOption('setting', 'track_matching_threshold', 0.4, title=N_("Minimal similarity for matching files to tracks"))
# picard/ui/options/metadata.py
# Metadata
ListOption('setting', 'artist_locales', ['en'], title=N_("Translation locales"))
BoolOption('setting', 'convert_punctuation', False, title=N_("Convert Unicode punctuation characters to ASCII"))
BoolOption('setting', 'guess_tracknumber_and_title', True, title=N_("Guess track number and title from filename if empty"))
TextOption('setting', 'nat_name', '[standalone recordings]', title=N_("Standalone recordings name"))
BoolOption('setting', 'release_ars', True, title=N_("Use release relationships"))
ListOption('setting', 'script_exceptions', [], title=N_("Translation script exceptions"))
BoolOption('setting', 'standardize_artists', False, title=N_("Use standardized artist names"))
BoolOption('setting', 'standardize_instruments', True, title=N_("Use standardized instrument and vocal credits"))
BoolOption('setting', 'track_ars', False, title=N_("Use track and release relationships"))
BoolOption('setting', 'translate_artist_names', False, title=N_("Translate artist names"))
BoolOption('setting', 'translate_artist_names_script_exception', False, title=N_("Translate artist names exception"))
TextOption('setting', 'va_name', "Various Artists", title=N_("Various Artists name"))
# picard/ui/options/network.py
# Network
BoolOption('setting', 'browser_integration', True, title=N_("Browser integration"))
BoolOption('setting', 'browser_integration_localhost_only', True, title=N_("Listen only on localhost"))
IntOption('setting', 'browser_integration_port', 8000, title=N_("Default listening port"))
IntOption('setting', 'network_cache_size_bytes', DEFAULT_CACHE_SIZE_IN_BYTES, title=N_("Network cache size in bytes"))
IntOption('setting', 'network_transfer_timeout_seconds', 30, title=N_("Request timeout in seconds"))
TextOption('setting', 'proxy_password', '', title=N_("Proxy password"))
TextOption('setting', 'proxy_server_host', '', title=N_("Proxy server address"))
IntOption('setting', 'proxy_server_port', 80, title=N_("Proxy server port"))
TextOption('setting', 'proxy_type', 'http', title=N_("Type of proxy server"))
TextOption('setting', 'proxy_username', '', title=N_("Proxy username"))
BoolOption('setting', 'use_proxy', False, title=N_("Use a web proxy server"))
# picard/ui/options/plugins.py
# Plugins
Option('persist', 'plugins_list_sort_order', QtCore.Qt.SortOrder.AscendingOrder)
Option('persist', 'plugins_list_sort_section', 0)
Option('persist', 'plugins_list_state', QtCore.QByteArray())
ListOption('setting', 'enabled_plugins', [])
# picard/ui/options/profiles.py
# Option Profiles
IntOption('persist', 'last_selected_profile_pos', 0)
ListOption('persist', 'profile_settings_tree_expanded_list', [])
# picard/ui/options/ratings.py
# Ratings
BoolOption('setting', 'enable_ratings', False, title=N_("Enable track ratings"))
IntOption('setting', 'rating_steps', 6)
TextOption('setting', 'rating_user_email', 'users@musicbrainz.org', title=N_("Email to use when saving ratings"))
BoolOption('setting', 'submit_ratings', True, title=N_("Submit ratings to MusicBrainz"))
# picard/ui/options/releases.py
# Preferred Releases
ListOption('setting', 'preferred_release_countries', [], title=N_("Preferred release countries"))
ListOption('setting', 'preferred_release_formats', [], title=N_("Preferred medium formats"))
ListOption('setting', 'release_type_scores', DEFAULT_RELEASE_TYPE_SCORES, title=N_("Preferred release types"))
# picard/ui/options/renaming.py
# File Naming
BoolOption('setting', 'delete_empty_dirs', True, title=N_("Delete empty directories"))
BoolOption('setting', 'move_additional_files', False, title=N_("Move additional files"))
TextOption('setting', 'move_additional_files_pattern', "*.jpg *.png", title=N_("Additional file patterns"))
BoolOption('setting', 'move_files', False, title=N_("Move files"))
TextOption('setting', 'move_files_to', DEFAULT_MUSIC_DIR, title=N_("Destination directory"))
BoolOption('setting', 'rename_files', False, title=N_("Rename files"))
# picard/ui/options/renaming_compat.py
# Compatibility
BoolOption('setting', 'ascii_filenames', False, title=N_("Replace non-ASCII characters"))
TextOption('setting', 'replace_dir_separator', DEFAULT_REPLACEMENT, title=N_("Replacement character to use for directory separators"))
BoolOption('setting', 'replace_spaces_with_underscores', False, title=N_("Replace spaces with underscores"))
Option('setting', 'win_compat_replacements', DEFAULT_WIN_COMPAT_REPLACEMENTS, title=N_("Replacement characters used for Windows compatibility"))
BoolOption('setting', 'windows_compatibility', True, title=N_("Windows compatibility"))
BoolOption('setting', 'windows_long_paths', DEFAULT_LONG_PATHS, title=N_("Windows long path support"))
# picard/ui/options/scripting.py
# Scripting
IntOption('persist', 'last_selected_script_pos', 0)
BoolOption('setting', 'enable_tagger_scripts', False, title=N_("Enable tagger scripts"))
ListOption('setting', 'list_of_scripts', [], title=N_("Tagger scripts"))
# picard/ui/options/tags.py
# Tags
BoolOption('setting', 'clear_existing_tags', False, title=N_("Clear existing tags"))
BoolOption('setting', 'dont_write_tags', False, title=N_("Don't write tags"))
BoolOption('setting', 'fix_missing_seekpoints_flac', False, title=N_("Fix missing seekpoints for FLAC files"))
ListOption('setting', 'preserved_tags', [], title=N_("Preserved tags list"))
BoolOption('setting', 'preserve_images', False, title=N_("Keep embedded images when clearing tags"))
BoolOption('setting', 'preserve_timestamps', False, title=N_("Preserve timestamps of tagged files"))
BoolOption('setting', 'remove_ape_from_mp3', False, title=N_("Remove APEv2 tags from MP3 files"))
BoolOption('setting', 'remove_id3_from_flac', False, title=N_("Remove ID3 tags from FLAC files"))
# picard/ui/options/tags_compatibility_aac.py
# AAC
BoolOption('setting', 'aac_save_ape', True, title=N_("Save APEv2 tags to AAC"))
BoolOption('setting', 'remove_ape_from_aac', False, title=N_("Remove APEv2 tags from AAC files"))
# picard/ui/options/tags_compatibility_ac3.py
# AC3
BoolOption('setting', 'ac3_save_ape', True, title=N_("Save APEv2 tags to AC3"))
BoolOption('setting', 'remove_ape_from_ac3', False, title=N_("Remove APEv2 tags from AC3 files"))
# picard/ui/options/tags_compatibility_id3.py
# ID3
TextOption('setting', 'id3v23_join_with', '/', title=N_("ID3v2.3 join character"))
TextOption('setting', 'id3v2_encoding', 'utf-8', title=N_("ID3v2 text encoding"))
BoolOption('setting', 'itunes_compatible_grouping', False, title=N_("Save iTunes compatible grouping and work"))
BoolOption('setting', 'write_id3v1', True, title=N_("Write ID3v1 tags"))
BoolOption('setting', 'write_id3v23', False, title=N_("ID3v2 version to write"))
# picard/ui/options/tags_compatibility_wave.py
# WAVE
BoolOption('setting', 'remove_wave_riff_info', False, title=N_("Remove existing RIFF INFO tags from WAVE files"))
TextOption('setting', 'wave_riff_info_encoding', 'windows-1252', title=N_("RIFF INFO text encoding"))
BoolOption('setting', 'write_wave_riff_info', True, title=N_("Write RIFF INFO tags to WAVE files"))
# picard/ui/scripteditor.py
# File naming script editor Script Details
BoolOption('persist', 'script_editor_show_documentation', False)
Option('setting', 'file_renaming_scripts', {})
TextOption('setting', 'selected_file_naming_script_id', '', title=N_("Selected file naming script"))
# picard/ui/searchdialog/album.py
#
Option('persist', 'albumsearchdialog_header_state', QtCore.QByteArray())
# picard/ui/searchdialog/artist.py
#
Option('persist', 'artistsearchdialog_header_state', QtCore.QByteArray())
# picard/ui/searchdialog/track.py
#
Option('persist', 'tracksearchdialog_header_state', QtCore.QByteArray())
# picard/ui/tagsfromfilenames.py
#
TextOption('persist', 'tags_from_filenames_format', '')
# picard/ui/widgets/scripttextedit.py
#
BoolOption('persist', 'script_editor_tooltips', True)
BoolOption('persist', 'script_editor_wordwrap', False)
def init_options():
pass
| 22,182
|
Python
|
.py
| 381
| 56.545932
| 147
| 0.752897
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,934
|
i18n.py
|
metabrainz_picard/picard/i18n.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2012 Frederik “Freso” S. Olesen
# Copyright (C) 2013-2014, 2018-2024 Laurent Monin
# Copyright (C) 2017 Sambhav Kothari
# Copyright (C) 2017-2024 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import gettext as module_gettext
import locale
import os
import re
from PyQt6.QtCore import (
QCollator,
QLocale,
)
from picard.const.sys import (
IS_MACOS,
IS_WIN,
)
_logger = None
_qcollator = QCollator()
_qcollator_numeric = QCollator()
_qcollator_numeric.setNumericMode(True)
_null_translations = module_gettext.NullTranslations()
_translation = {
'main': _null_translations,
'attributes': _null_translations,
'constants': _null_translations,
'countries': _null_translations,
}
def set_locale_from_env():
"""
Depending on environment, locale.setlocale(locale.LC_ALL, '') can fail.
Returns a string LANG[.ENCODING]
>>> import locale
>>> import os
>>> os.environ['LANG'] = 'buggy'
>>> locale.setlocale(locale.LC_ALL, '')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.10/locale.py", line 620, in setlocale
return _setlocale(category, locale)
locale.Error: unsupported locale setting
>>> locale.setlocale(locale.LC_ALL, 'C')
'C'
>>> locale.getlocale(locale.LC_ALL)
(None, None)
>>> os.environ['LANG'] = 'en_US.UTF-8'
>>> locale.setlocale(locale.LC_ALL, '')
'en_US.UTF-8'
>>> locale.getlocale(locale.LC_ALL)
('en_US', 'UTF-8')
"""
try:
current_locale = locale.setlocale(locale.LC_ALL, '')
except locale.Error:
# default to 'C' locale if it couldn't be set from env
current_locale = locale.setlocale(locale.LC_ALL, 'C')
_logger("Setting locale from env: %r", current_locale)
return current_locale
if IS_WIN:
from ctypes import windll
def _get_default_locale():
try:
return locale.windows_locale[windll.kernel32.GetUserDefaultUILanguage()]
except KeyError:
return None
elif IS_MACOS:
import Foundation
def _get_default_locale():
defaults = Foundation.NSUserDefaults.standardUserDefaults()
return defaults.objectForKey_('AppleLanguages')[0].replace('-', '_')
else:
def _get_default_locale():
return None
def _try_encodings():
"""Generate encodings to try, starting with preferred encoding if possible"""
preferred_encoding = locale.getpreferredencoding()
if preferred_encoding != 'UTF-8':
yield preferred_encoding
yield from ('UTF-8', None)
def _try_locales(language):
"""Try setting the locale from language with preferred/UTF-8/no encoding"""
for encoding in _try_encodings():
if encoding:
yield locale.normalize(language + '.' + encoding)
else:
yield language
def _load_translation(domain, localedir, language):
try:
_logger("Loading gettext translation for %s, localedir=%r, language=%r", domain, localedir, language)
return module_gettext.translation(domain, localedir, languages=[language])
except OSError as e:
_logger(e)
return module_gettext.NullTranslations()
def _log_lang_env_vars():
env_vars = []
lc_keys = sorted(k for k in os.environ.keys() if k.startswith('LC_'))
for k in ('LANG', 'LANGUAGE') + tuple(lc_keys):
if k in os.environ:
env_vars.append(k + '=' + os.environ[k])
_logger("Env vars: %s", ' '.join(env_vars))
def setup_gettext(localedir, ui_language=None, logger=None):
"""Setup locales, load translations, install gettext functions."""
global _logger, _qcollator, _qcollator_numeric
if not logger:
_logger = lambda *a, **b: None # noqa: E731
else:
_logger = logger
if ui_language:
_logger("UI language: %r", ui_language)
try_locales = list(_try_locales(ui_language))
else:
_logger("UI language: system")
_log_lang_env_vars()
try_locales = []
default_locale = _get_default_locale()
if default_locale:
try_locales.append(default_locale)
_logger("Trying locales: %r", try_locales)
current_locale = None
for loc in try_locales:
try:
current_locale = locale.setlocale(locale.LC_ALL, loc)
_logger("Set locale to: %r", current_locale)
break
except locale.Error:
_logger("Failed to set locale: %r", loc)
if ui_language:
# UI locale may differ from env, those have to match files in po/
current_locale = ui_language
if current_locale is None:
current_locale = set_locale_from_env()
_logger("Using locale: %r", current_locale)
QLocale.setDefault(QLocale(current_locale))
_qcollator = QCollator()
_qcollator_numeric = QCollator()
_qcollator_numeric.setNumericMode(True)
global _translation
_translation = {
'main': _load_translation('picard', localedir, language=current_locale),
'attributes': _load_translation('picard-attributes', localedir, language=current_locale),
'constants': _load_translation('picard-constants', localedir, language=current_locale),
'countries': _load_translation('picard-countries', localedir, language=current_locale),
}
_logger(_translation)
def gettext(message: str) -> str:
"""Translate the messsage using the current translator."""
# Calling gettext("") by default returns the header of the PO file for the
# current locale. This is unexpected. Return an empty string instead.
if message == "":
return message
return _translation['main'].gettext(message)
def _(message: str) -> str:
"""Alias for gettext"""
return gettext(message)
def N_(message: str) -> str:
"""No-op marker for translatable strings"""
return message
def ngettext(singular: str, plural: str, n: int) -> str:
return _translation['main'].ngettext(singular, plural, n)
def pgettext_attributes(context: str, message: str) -> str:
return _translation['attributes'].pgettext(context, message)
def gettext_attributes(message: str) -> str:
return _translation['attributes'].gettext(message)
def gettext_countries(message: str) -> str:
return _translation['countries'].gettext(message)
def gettext_constants(message: str) -> str:
return _translation['constants'].gettext(message)
def sort_key(string, numeric=False):
"""Transforms a string to one that can be used in locale-aware comparisons.
Args:
string: The string to convert
numeric: Boolean indicating whether to use number aware sorting (natural sorting)
Returns: An object that can be compared locale-aware
"""
# QCollator.sortKey is broken, see https://bugreports.qt.io/browse/QTBUG-128170
if IS_WIN:
return _sort_key_strxfrm(string, numeric)
else:
return _sort_key_qt(string, numeric)
RE_NUMBER = re.compile(r'(\d+)')
def _digits_replace(matchobj):
s = matchobj.group(0)
return str(int(s)) if s.isdecimal() else s
def _sort_key_qt(string, numeric=False):
collator = _qcollator_numeric if numeric else _qcollator
# On macOS / Windows the numeric sorting does not work reliable with non-latin
# scripts. Replace numbers in the sort string with their latin equivalent.
if numeric and (IS_MACOS or IS_WIN):
string = RE_NUMBER.sub(_digits_replace, string)
# On macOS numeric sorting of strings entirely consisting of numeric characters fails
# and always sorts alphabetically (002 < 1). Always prefix with an alphabetic character
# to work around that.
return collator.sortKey('a' + string.replace('\0', ''))
def _sort_key_strxfrm(string, numeric=False):
if numeric:
return [int(s) if s.isdecimal() else _strxfrm(s)
for s in RE_NUMBER.split(str(string).replace('\0', ''))]
else:
return _strxfrm(string)
def _strxfrm(string):
try:
return locale.strxfrm(string)
except (OSError, ValueError):
return string.lower()
| 8,849
|
Python
|
.py
| 221
| 34.642534
| 109
| 0.684463
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,935
|
metadata.py
|
metabrainz_picard/picard/metadata.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2006-2008, 2011 Lukáš Lalinský
# Copyright (C) 2009, 2015, 2018-2023 Philipp Wolfer
# Copyright (C) 2011-2014 Michael Wiencek
# Copyright (C) 2012 Chad Wilson
# Copyright (C) 2012 Johannes Weißl
# Copyright (C) 2012-2014, 2018, 2020 Wieland Hoffmann
# Copyright (C) 2013-2014, 2016, 2018-2024 Laurent Monin
# Copyright (C) 2013-2014, 2017 Sophist-UK
# Copyright (C) 2016 Rahul Raturi
# Copyright (C) 2016-2017 Sambhav Kothari
# Copyright (C) 2017-2018 Antonio Larrosa
# Copyright (C) 2018 Vishal Choudhary
# Copyright (C) 2018 Xincognito10
# Copyright (C) 2020 Gabriel Ferreira
# Copyright (C) 2020 Ray Bouchard
# Copyright (C) 2021 Petit Minion
# Copyright (C) 2022 Bob Swift
# Copyright (C) 2022 skelly37
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from collections import namedtuple
from collections.abc import (
Iterable,
MutableMapping,
)
from functools import partial
from PyQt6 import QtCore
from picard.config import get_config
from picard.mbjson import (
artist_credit_from_node,
get_score,
)
from picard.plugin import PluginFunctions
from picard.similarity import similarity2
from picard.util import (
ReadWriteLockContext,
extract_year_from_date,
linear_combination_of_weights,
)
from picard.util.imagelist import ImageList
from picard.util.tags import PRESERVED_TAGS
MULTI_VALUED_JOINER = '; '
# lengths difference over this number of milliseconds will give a score of 0.0
# equal lengths will give a score of 1.0
# example
# a b score
# 20000 0 0.333333333333
# 20000 10000 0.666666666667
# 20000 20000 1.0
# 20000 30000 0.666666666667
# 20000 40000 0.333333333333
# 20000 50000 0.0
LENGTH_SCORE_THRES_MS = 30000
SimMatchTrack = namedtuple('SimMatchTrack', 'similarity releasegroup release track')
SimMatchRelease = namedtuple('SimMatchRelease', 'similarity release')
def weights_from_release_type_scores(parts, release, release_type_scores,
weight_release_type=1):
# This function generates a score that determines how likely this release will be selected in a lookup.
# The score goes from 0 to 1 with 1 being the most likely to be chosen and 0 the least likely
# This score is based on the preferences of release-types found in this release
# This algorithm works by taking the scores of the primary type (and secondary if found) and averages them
# If no types are found, it is set to the score of the 'Other' type or 0.5 if 'Other' doesnt exist
# It appends (score, weight_release_type) to passed parts list
# if our preference is zero for the release_type, force to never return this recording
# by using a large zero weight. This means it only gets picked if there are no others at all.
skip_release = False
type_scores = dict(release_type_scores)
score = 0.0
other_score = type_scores.get('Other', 0.5)
if 'release-group' in release and 'primary-type' in release['release-group']:
types_found = [release['release-group']['primary-type']]
if 'secondary-types' in release['release-group']:
types_found += release['release-group']['secondary-types']
for release_type in types_found:
type_score = type_scores.get(release_type, other_score)
if type_score == 0:
skip_release = True
score += type_score
score /= len(types_found)
else:
score = other_score
if skip_release:
parts.append((0, 9999))
else:
parts.append((score, weight_release_type))
def weights_from_preferred_countries(parts, release,
preferred_countries,
weight):
total_countries = len(preferred_countries)
if total_countries:
score = 0.0
if "country" in release:
try:
i = preferred_countries.index(release['country'])
score = float(total_countries - i) / float(total_countries)
except ValueError:
pass
parts.append((score, weight))
def weights_from_preferred_formats(parts, release, preferred_formats, weight):
total_formats = len(preferred_formats)
if total_formats and 'media' in release:
score = 0.0
subtotal = 0
for medium in release['media']:
if "format" in medium:
try:
i = preferred_formats.index(medium['format'])
score += float(total_formats - i) / float(total_formats)
except ValueError:
pass
subtotal += 1
if subtotal > 0:
score /= subtotal
parts.append((score, weight))
def trackcount_score(actual, expected):
return 0.0 if actual > expected else 0.3 if actual < expected else 1.0
class Metadata(MutableMapping):
"""List of metadata items with dict-like access."""
__weights = [
('title', 22),
('artist', 6),
('album', 12),
('tracknumber', 6),
('totaltracks', 5),
('discnumber', 5),
('totaldiscs', 4),
]
__date_match_factors = {
'exact': 1.00,
'year': 0.95,
'close_year': 0.85,
'exists_vs_null': 0.65,
'no_release_date': 0.25,
'differed': 0.0
}
multi_valued_joiner = MULTI_VALUED_JOINER
def __init__(self, *args, deleted_tags=None, images=None, length=None, **kwargs):
self._lock = ReadWriteLockContext()
self._store = dict()
self.deleted_tags = set()
self.length = 0
self.images = ImageList()
self.has_common_images = True
if args or kwargs:
self.update(*args, **kwargs)
if images is not None:
for image in images:
self.images.append(image)
if deleted_tags is not None:
for tag in deleted_tags:
del self[tag]
if length is not None:
self.length = int(length)
def __bool__(self):
return bool(len(self))
def __len__(self):
return len(self._store) + len(self.images)
@staticmethod
def length_score(a, b):
if a is None or b is None:
return 0.0
return (1.0 - min(abs(a - b),
LENGTH_SCORE_THRES_MS) / float(LENGTH_SCORE_THRES_MS))
def compare(self, other, ignored=None):
parts = []
if ignored is None:
ignored = []
with self._lock.lock_for_read():
if self.length and other.length and '~length' not in ignored:
score = self.length_score(self.length, other.length)
parts.append((score, 8))
for name, weight in self.__weights:
if name in ignored:
continue
a = self[name]
b = other[name]
if a and b:
if name in {'tracknumber', 'totaltracks', 'discnumber', 'totaldiscs'}:
try:
ia = int(a)
ib = int(b)
except ValueError:
ia = a
ib = b
score = 1.0 - (int(ia != ib))
else:
score = similarity2(a, b)
parts.append((score, weight))
elif (a and name in other.deleted_tags
or b and name in self.deleted_tags):
parts.append((0, weight))
return linear_combination_of_weights(parts)
def compare_to_release(self, release, weights):
"""
Compare metadata to a MusicBrainz release. Produces a probability as a
linear combination of weights that the metadata matches a certain album.
"""
parts = self.compare_to_release_parts(release, weights)
sim = linear_combination_of_weights(parts) * get_score(release)
return SimMatchRelease(similarity=sim, release=release)
def compare_to_release_parts(self, release, weights):
parts = []
with self._lock.lock_for_read():
if 'album' in self and 'album' in weights:
b = release['title']
parts.append((similarity2(self['album'], b), weights['album']))
if 'albumartist' in self and 'albumartist' in weights:
a = self['albumartist']
b = artist_credit_from_node(release['artist-credit'])[0]
parts.append((similarity2(a, b), weights['albumartist']))
if 'totaltracks' in weights:
try:
a = int(self['totaltracks'])
if 'media' in release:
score = 0.0
for media in release['media']:
b = media.get('track-count', 0)
score = max(score, trackcount_score(a, b))
if score == 1.0:
break
else:
b = release['track-count']
score = trackcount_score(a, b)
parts.append((score, weights['totaltracks']))
except (ValueError, KeyError):
pass
if 'totalalbumtracks' in weights:
try:
a = int(self['~totalalbumtracks'] or self['totaltracks'])
b = release['track-count']
score = trackcount_score(a, b)
parts.append((score, weights['totalalbumtracks']))
except (ValueError, KeyError):
pass
# Date Logic
date_match_factor = 0.0
if 'date' in weights:
if 'date' in release and release['date'] != '':
release_date = release['date']
if 'date' in self:
metadata_date = self['date']
if release_date == metadata_date:
# release has a date and it matches what our metadata had exactly.
date_match_factor = self.__date_match_factors['exact']
else:
release_year = extract_year_from_date(release_date)
if release_year is not None:
metadata_year = extract_year_from_date(metadata_date)
if metadata_year is not None:
if release_year == metadata_year:
# release has a date and it matches what our metadata had for year exactly.
date_match_factor = self.__date_match_factors['year']
elif abs(release_year - metadata_year) <= 2:
# release has a date and it matches what our metadata had closely (year +/- 2).
date_match_factor = self.__date_match_factors['close_year']
else:
# release has a date but it does not match ours (all else equal,
# its better to have an unknown date than a wrong date, since
# the unknown could actually be correct)
date_match_factor = self.__date_match_factors['differed']
else:
# release has a date but we don't have one (all else equal, we prefer
# tracks that have non-blank date values)
date_match_factor = self.__date_match_factors['exists_vs_null']
else:
# release has a no date (all else equal, we don't prefer this
# release since its date is missing)
date_match_factor = self.__date_match_factors['no_release_date']
parts.append((date_match_factor, weights['date']))
config = get_config()
if 'releasecountry' in weights:
weights_from_preferred_countries(parts, release,
config.setting['preferred_release_countries'],
weights['releasecountry'])
if 'format' in weights:
weights_from_preferred_formats(parts, release,
config.setting['preferred_release_formats'],
weights['format'])
if 'releasetype' in weights:
weights_from_release_type_scores(parts, release,
config.setting['release_type_scores'],
weights['releasetype'])
if 'release-group' in release:
tagger = QtCore.QCoreApplication.instance()
rg = tagger.get_release_group_by_id(release['release-group']['id'])
if release['id'] in rg.loaded_albums:
parts.append((1.0, 6))
return parts
def compare_to_track(self, track, weights):
parts = []
releases = []
with self._lock.lock_for_read():
if 'title' in self:
a = self['title']
b = track.get('title', '')
parts.append((similarity2(a, b), weights["title"]))
if 'artist' in self:
a = self['artist']
artist_credits = track.get('artist-credit', [])
b = artist_credit_from_node(artist_credits)[0]
parts.append((similarity2(a, b), weights["artist"]))
a = self.length
if a > 0 and 'length' in track:
b = track['length']
score = self.length_score(a, b)
parts.append((score, weights["length"]))
if 'isvideo' in weights:
metadata_is_video = self['~video'] == '1'
track_is_video = bool(track.get('video'))
score = 1 if metadata_is_video == track_is_video else 0
parts.append((score, weights['isvideo']))
if "releases" in track:
releases = track['releases']
search_score = get_score(track)
if not releases:
config = get_config()
score = dict(config.setting['release_type_scores']).get('Other', 0.5)
parts.append((score, _get_total_release_weight(weights)))
sim = linear_combination_of_weights(parts) * search_score
return SimMatchTrack(similarity=sim, releasegroup=None, release=None, track=track)
result = SimMatchTrack(similarity=-1, releasegroup=None, release=None, track=None)
for release in releases:
release_parts = self.compare_to_release_parts(release, weights)
sim = linear_combination_of_weights(parts + release_parts) * search_score
if sim > result.similarity:
rg = release['release-group'] if "release-group" in release else None
result = SimMatchTrack(similarity=sim, releasegroup=rg, release=release, track=track)
return result
def copy(self, other, copy_images=True):
self.clear()
with self._lock.lock_for_write():
self._update_from_metadata(other, copy_images)
def update(self, *args, **kwargs):
with self._lock.lock_for_write():
one_arg = len(args) == 1
if one_arg and (isinstance(args[0], self.__class__) or isinstance(args[0], MultiMetadataProxy)):
self._update_from_metadata(args[0])
elif one_arg and isinstance(args[0], MutableMapping):
# update from MutableMapping (ie. dict)
for k, v in args[0].items():
self._set(k, v)
elif args or kwargs:
# update from a dict-like constructor parameters
for k, v in dict(*args, **kwargs).items():
self._set(k, v)
else:
# no argument, raise TypeError to mimic dict.update()
raise TypeError("descriptor 'update' of '%s' object needs an argument" % self.__class__.__name__)
def diff(self, other):
"""Returns a new Metadata object with only the tags that changed in self compared to other"""
with self._lock.lock_for_read():
m = Metadata()
for tag, values in self.rawitems():
other_values = other.getall(tag)
if other_values != values:
m[tag] = values
m.deleted_tags = self.deleted_tags - other.deleted_tags
return m
def _update_from_metadata(self, other, copy_images=True):
for k, v in other.rawitems():
self._set(k, v[:])
for tag in other.deleted_tags:
self._del(tag)
if copy_images and other.images:
self.images = other.images.copy()
if other.length:
self.length = other.length
def clear(self):
with self._lock.lock_for_write():
self._store.clear()
self.images = ImageList()
self.length = 0
self.clear_deleted()
def clear_deleted(self):
self.deleted_tags = set()
@staticmethod
def normalize_tag(name):
return name.rstrip(':')
def getall(self, name):
with self._lock.lock_for_read():
return self._store.get(self.normalize_tag(name), [])
def getraw(self, name):
with self._lock.lock_for_read():
return self._store[self.normalize_tag(name)]
def get(self, key, default=None):
with self._lock.lock_for_read():
values = self._store.get(self.normalize_tag(key), None)
if values:
return self.multi_valued_joiner.join(values)
else:
return default
def __getitem__(self, name):
return self.get(name, '')
def _set(self, name, values):
name = self.normalize_tag(name)
if isinstance(values, str) or not isinstance(values, Iterable):
values = [values]
values = [str(value) for value in values if value or value == 0 or value == '']
# Remove if there is only a single empty or blank element.
if values and (len(values) > 1 or values[0]):
self._store[name] = values
self.deleted_tags.discard(name)
elif name in self._store:
self._del(name)
def set(self, name, values):
with self._lock.lock_for_write():
self._set(name, values)
def __setitem__(self, name, values):
self.set(name, values)
def __contains__(self, name):
with self._lock.lock_for_read():
return self._store.__contains__(self.normalize_tag(name))
def _del(self, name):
name = self.normalize_tag(name)
try:
del self._store[name]
except KeyError:
pass
finally:
self.deleted_tags.add(name)
def __delitem__(self, name):
with self._lock.lock_for_write():
self._del(name)
def delete(self, name):
del self[self.normalize_tag(name)]
def add(self, name, value):
if value or value == 0:
with self._lock.lock_for_write():
name = self.normalize_tag(name)
self._store.setdefault(name, []).append(str(value))
self.deleted_tags.discard(name)
def add_unique(self, name, value):
name = self.normalize_tag(name)
if value not in self.getall(name):
self.add(name, value)
def unset(self, name):
"""Removes a tag from the metadata, but does not mark it for deletion.
Args:
name: name of the tag to unset
"""
with self._lock.lock_for_write():
name = self.normalize_tag(name)
try:
del self._store[name]
except KeyError:
pass
def __iter__(self):
with self._lock.lock_for_read():
yield from self._store
def items(self):
with self._lock.lock_for_read():
for name, values in self._store.items():
for value in values:
yield name, value
def rawitems(self):
"""Returns the metadata items.
>>> m.rawitems()
[("key1", ["value1", "value2"]), ("key2", ["value3"])]
"""
return self._store.items()
def apply_func(self, func):
with self._lock.lock_for_write():
for name, values in list(self.rawitems()):
if name not in PRESERVED_TAGS:
self._set(name, (func(value) for value in values))
def strip_whitespace(self):
"""Strip leading/trailing whitespace.
>>> m = Metadata()
>>> m["foo"] = " bar "
>>> m["foo"]
" bar "
>>> m.strip_whitespace()
>>> m["foo"]
"bar"
"""
self.apply_func(str.strip)
def __repr__(self):
return "%s(%r, deleted_tags=%r, length=%r, images=%r)" % (self.__class__.__name__, self._store, self.deleted_tags, self.length, self.images)
def __str__(self):
return ("store: %r\ndeleted: %r\nimages: %r\nlength: %r" % (self._store, self.deleted_tags, [str(img) for img in self.images], self.length))
def add_images(self, added_images):
if not added_images:
return False
current_images = set(self.images)
if added_images.isdisjoint(current_images):
self.images = ImageList(current_images.union(added_images))
self.has_common_images = False
return True
return False
def remove_images(self, sources, removed_images):
"""Removes `removed_images` from `images`, but only if they are not included in `sources`.
Args:
sources: List of source `Metadata` objects
removed_images: Set of `CoverArt` to removed
Returns:
True if self.images was modified, False else
"""
if not self.images or not removed_images:
return False
if not sources:
self.images = ImageList()
self.has_common_images = True
return True
current_images = set(self.images)
if self.has_common_images and current_images == removed_images:
return False
common_images = True # True, if all children share the same images
previous_images = None
# Iterate over all sources and check whether the images proposed to be
# removed are used in any sources. Images used in existing sources
# must not be removed.
for source_metadata in sources:
source_images = set(source_metadata.images)
if previous_images and common_images and previous_images != source_images:
common_images = False
previous_images = set(source_metadata.images) # Remember for next iteration
removed_images = removed_images.difference(source_images)
if not removed_images and not common_images:
return False # No images left to remove, abort immediately
new_images = current_images.difference(removed_images)
self.images = ImageList(new_images)
self.has_common_images = common_images
return True
class MultiMetadataProxy:
"""
Wraps a writable Metadata object together with another
readonly Metadata object.
Changes are written to the writable object, while values are
read from both the writable and the readonly object (with the writable
object taking precedence). The use case is to provide access to Metadata
values without making them part of the actual Metadata. E.g. allow track
metadata to use file specific metadata, without making it actually part
of the track.
"""
WRITE_METHODS = [
'add_unique',
'add',
'apply_func',
'clear_deleted',
'clear',
'copy',
'delete',
'pop',
'set',
'strip_whitespace',
'unset',
'update',
]
def __init__(self, metadata, *readonly_metadata):
self.metadata = metadata
self.combined_metadata = Metadata()
for m in reversed(readonly_metadata):
self.combined_metadata.update(m)
self.combined_metadata.update(metadata)
def __getattr__(self, name):
if name in self.WRITE_METHODS:
return partial(self.__write, name)
else:
attribute = self.combined_metadata.__getattribute__(name)
if callable(attribute):
return partial(self.__read, name)
else:
return attribute
def __setattr__(self, name, value):
if name in {'metadata', 'combined_metadata'}:
super().__setattr__(name, value)
else:
self.metadata.__setattr__(name, value)
self.combined_metadata.__setattr__(name, value)
def __write(self, name, *args, **kwargs):
func1 = self.metadata.__getattribute__(name)
func2 = self.combined_metadata.__getattribute__(name)
func1(*args, **kwargs)
return func2(*args, **kwargs)
def __read(self, name, *args, **kwargs):
func = self.combined_metadata.__getattribute__(name)
return func(*args, **kwargs)
def __getitem__(self, name):
return self.__read('__getitem__', name)
def __setitem__(self, name, values):
return self.__write('__setitem__', name, values)
def __delitem__(self, name):
return self.__write('__delitem__', name)
def __iter__(self):
return self.__read('__iter__')
def __len__(self):
return self.__read('__len__')
def __contains__(self, name):
return self.__read('__contains__', name)
def __repr__(self):
return self.__read('__repr__')
def _get_total_release_weight(weights):
release_weights = ('album', 'totaltracks', 'totalalbumtracks', 'releasetype',
'releasecountry', 'format', 'date')
return sum(weights[w] for w in release_weights if w in weights)
album_metadata_processors = PluginFunctions(label='album_metadata_processors')
track_metadata_processors = PluginFunctions(label='track_metadata_processors')
def run_album_metadata_processors(album_object, metadata, release):
album_metadata_processors.run(album_object, metadata, release)
def run_track_metadata_processors(album_object, metadata, track, release=None):
track_metadata_processors.run(album_object, metadata, track, release)
| 27,675
|
Python
|
.py
| 617
| 33.137763
| 148
| 0.573428
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,936
|
config_upgrade.py
|
metabrainz_picard/picard/config_upgrade.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2013-2014 Michael Wiencek
# Copyright (C) 2013-2016, 2018-2024 Laurent Monin
# Copyright (C) 2014, 2017 Lukáš Lalinský
# Copyright (C) 2014, 2018-2024 Philipp Wolfer
# Copyright (C) 2015 Ohm Patel
# Copyright (C) 2016 Suhas
# Copyright (C) 2016-2017 Sambhav Kothari
# Copyright (C) 2021 Gabriel Ferreira
# Copyright (C) 2021, 2023 Bob Swift
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from inspect import (
getmembers,
isfunction,
)
import os
import re
import sys
from PyQt6 import QtWidgets
from picard import (
PICARD_VERSION,
log,
)
from picard.config import (
BoolOption,
IntOption,
TextOption,
)
from picard.const.defaults import (
DEFAULT_FILE_NAMING_FORMAT,
DEFAULT_REPLACEMENT,
DEFAULT_SCRIPT_NAME,
)
from picard.const.sys import IS_FROZEN
from picard.i18n import (
gettext as _,
gettext_constants,
)
from picard.util import unique_numbered_title
from picard.version import (
Version,
VersionError,
)
# All upgrade functions have to start with following prefix
UPGRADE_FUNCTION_PREFIX = 'upgrade_to_v'
# TO ADD AN UPGRADE HOOK:
# ----------------------
#
# Add a new method here, named using the following scheme:
# UPGRADE_FUNCTION_PREFIX + version with dots replaced by underscores
#
# For example:
# `upgrade_to_v1_0_0dev1()` for an upgrade hook upgrading to 1.0.0dev1
#
# It will be automatically detected and registered by `upgrade_config()`.
# After adding an upgrade hook you have to update `PICARD_VERSION` to match it.
#
# The only parameter passed is when hooks are executed at startup is `config`,
# but extra parameters might be needed for tests.
#
# To rename old option to new one, use helper method `rename_option()`.
#
# Note: it is important to describe changes made by the method using a docstring.
# The text can be logged when the hook is executed.
def upgrade_to_v1_0_0final0(config, interactive=True, merge=True):
"""In version 1.0, the file naming formats for single and various artist releases were merged.
"""
_s = config.setting
def remove_va_file_naming_format(merge=True):
if merge:
_s['file_naming_format'] = (
"$if($eq(%%compilation%%,1),\n$noop(Various Artist "
"albums)\n%s,\n$noop(Single Artist Albums)\n%s)" % (
_s.value('va_file_naming_format', TextOption),
_s['file_naming_format']
))
_s.remove('va_file_naming_format')
_s.remove('use_va_format')
if 'va_file_naming_format' in _s and 'use_va_format' in _s:
if _s.value('use_va_format', BoolOption):
remove_va_file_naming_format()
if interactive:
msgbox = QtWidgets.QMessageBox()
msgbox.information(msgbox,
_("Various Artists file naming scheme removal"),
_("The separate file naming scheme for various artists "
"albums has been removed in this version of Picard.\n"
"Your file naming scheme has automatically been "
"merged with that of single artist albums."),
QtWidgets.QMessageBox.StandardButton.Ok)
elif (_s.value('va_file_naming_format', TextOption)
!= r"$if2(%albumartist%,%artist%)/%album%/$if($gt(%totaldis"
"cs%,1),%discnumber%-,)$num(%tracknumber%,2) %artist% - "
"%title%"):
if interactive:
msgbox = QtWidgets.QMessageBox()
msgbox.setWindowTitle(_("Various Artists file naming scheme removal"))
msgbox.setText(_("The separate file naming scheme for various artists "
"albums has been removed in this version of Picard.\n"
"You currently do not use this option, but have a "
"separate file naming scheme defined.\n"
"Do you want to remove it or merge it with your file "
"naming scheme for single artist albums?"))
msgbox.setIcon(QtWidgets.QMessageBox.Icon.Question)
merge_button = msgbox.addButton(_("Merge"), QtWidgets.QMessageBox.ButtonRole.AcceptRole)
msgbox.addButton(_("Remove"), QtWidgets.QMessageBox.ButtonRole.DestructiveRole)
msgbox.exec()
merge = msgbox.clickedButton() == merge_button
remove_va_file_naming_format(merge=merge)
else:
# default format, disabled
remove_va_file_naming_format(merge=False)
def upgrade_to_v1_3_0dev1(config):
"""Option "windows_compatible_filenames" was renamed "windows_compatibility" (PICARD-110).
"""
old_opt = 'windows_compatible_filenames'
new_opt = 'windows_compatibility'
rename_option(config, old_opt, new_opt, BoolOption, True)
def upgrade_to_v1_3_0dev2(config):
"""Option "preserved_tags" is now using comma instead of spaces as tag separator (PICARD-536)
"""
_s = config.setting
opt = 'preserved_tags'
if opt in _s and isinstance(_s[opt], str):
_s[opt] = re.sub(r"\s+", ",", _s[opt].strip())
def upgrade_to_v1_3_0dev3(config):
"""Options were made to support lists (solving PICARD-144 and others)
"""
_s = config.setting
option_separators = {
'preferred_release_countries': ' ',
'preferred_release_formats': ' ',
'enabled_plugins': None,
'caa_image_types': None,
'metadata_box_sizes': None,
}
for (opt, sep) in option_separators.items():
if opt in _s:
try:
_s[opt] = _s.raw_value(opt, qtype='QString').split(sep)
except AttributeError:
pass
def upgrade_to_v1_3_0dev4(config):
"""Option "release_type_scores" is now a list of tuples
"""
_s = config.setting
def load_release_type_scores(setting):
scores = []
values = setting.split()
for i in range(0, len(values), 2):
try:
score = float(values[i + 1])
except IndexError:
score = 0.0
scores.append((values[i], score))
return scores
opt = 'release_type_scores'
if opt in _s:
try:
_s[opt] = load_release_type_scores(_s.raw_value(opt, qtype='QString'))
except AttributeError:
pass
def upgrade_to_v1_4_0dev2(config):
"""Options "username" and "password" are removed and
replaced with OAuth tokens
"""
_s = config.setting
opts = ['username', 'password']
for opt in opts:
_s.remove(opt)
def upgrade_to_v1_4_0dev3(config):
"""Cover art providers options were moved to a list of tuples"""
_s = config.setting
map_ca_provider = [
('ca_provider_use_amazon', 'Amazon'),
('ca_provider_use_caa', 'Cover Art Archive'),
('ca_provider_use_whitelist', 'Whitelist'),
('ca_provider_use_caa_release_group_fallback', 'CaaReleaseGroup')
]
newopts = []
for old, new in map_ca_provider:
if old in _s:
newopts.append((new, _s.value(old, BoolOption, True)))
_s['ca_providers'] = newopts
OLD_DEFAULT_FILE_NAMING_FORMAT_v1_3 = "$if2(%albumartist%,%artist%)/" \
"$if($ne(%albumartist%,),%album%/)" \
"$if($gt(%totaldiscs%,1),%discnumber%-,)" \
"$if($ne(%albumartist%,),$num(%tracknumber%,2) ,)" \
"$if(%_multiartist%,%artist% - ,)" \
"%title%"
def upgrade_to_v1_4_0dev4(config):
"""Adds trailing comma to default file names for scripts"""
_s = config.setting
if _s['file_naming_format'] == OLD_DEFAULT_FILE_NAMING_FORMAT_v1_3:
_s['file_naming_format'] = DEFAULT_FILE_NAMING_FORMAT
def upgrade_to_v1_4_0dev5(config):
"""Using Picard.ini configuration file on all platforms"""
# this is done in Config.__init__()
def upgrade_to_v1_4_0dev6(config):
"""Adds support for multiple and selective tagger scripts"""
_s = config.setting
old_enabled_option = 'enable_tagger_script'
old_script_text_option = 'tagger_script'
list_of_scripts = []
if old_enabled_option in _s:
_s['enable_tagger_scripts'] = _s.value(old_enabled_option, BoolOption, False)
if old_script_text_option in _s:
old_script_text = _s.value(old_script_text_option, TextOption, "")
if old_script_text:
old_script = (
0,
unique_numbered_title(gettext_constants(DEFAULT_SCRIPT_NAME), list_of_scripts),
_s['enable_tagger_scripts'],
old_script_text,
)
list_of_scripts.append(old_script)
_s['list_of_scripts'] = list_of_scripts
_s.remove(old_enabled_option)
_s.remove(old_script_text_option)
def upgrade_to_v1_4_0dev7(config):
"""Option "save_only_front_images_to_tags" was renamed to "embed_only_one_front_image"."""
old_opt = 'save_only_front_images_to_tags'
new_opt = 'embed_only_one_front_image'
rename_option(config, old_opt, new_opt, BoolOption, True)
def upgrade_to_v2_0_0dev3(config):
"""Option "caa_image_size" value has different meaning."""
_s = config.setting
opt = 'caa_image_size'
if opt in _s:
# caa_image_size option was storing index of a combobox item as size
# therefore it depends on items order and/or number, which is bad
# To keep the option as is, values >= 250 are stored for thumbnails and -1 is
# used for full size.
_CAA_SIZE_COMPAT = {
0: 250,
1: 500,
2: -1,
}
value = _s[opt]
if value in _CAA_SIZE_COMPAT:
_s[opt] = _CAA_SIZE_COMPAT[value]
def upgrade_to_v2_1_0dev1(config):
"""Upgrade genre related options"""
_s = config.setting
if 'folksonomy_tags' in _s and _s['folksonomy_tags']:
_s['use_genres'] = True
rename_option(config, 'max_tags', 'max_genres', IntOption, 5)
rename_option(config, 'min_tag_usage', 'min_genre_usage', IntOption, 90)
rename_option(config, 'ignore_tags', 'ignore_genres', TextOption, '')
rename_option(config, 'join_tags', 'join_genres', TextOption, '')
rename_option(config, 'only_my_tags', 'only_my_genres', BoolOption, False)
rename_option(config, 'artists_tags', 'artists_genres', BoolOption, False)
def upgrade_to_v2_2_0dev3(config):
"""Option ignore_genres was replaced by option genres_filter"""
_s = config.setting
old_opt = 'ignore_genres'
if old_opt in _s:
if _s[old_opt]:
new_opt = 'genres_filter'
tags = ['-' + e.strip().lower() for e in _s[old_opt].split(',')]
_s[new_opt] = '\n'.join(tags)
_s.remove(old_opt)
OLD_DEFAULT_FILE_NAMING_FORMAT_v2_1 = "$if2(%albumartist%,%artist%)/" \
"$if($ne(%albumartist%,),%album%/,)" \
"$if($gt(%totaldiscs%,1),%discnumber%-,)" \
"$if($ne(%albumartist%,),$num(%tracknumber%,2) ,)" \
"$if(%_multiartist%,%artist% - ,)" \
"%title%"
def upgrade_to_v2_2_0dev4(config):
"""Improved default file naming script"""
_s = config.setting
if _s['file_naming_format'] == OLD_DEFAULT_FILE_NAMING_FORMAT_v2_1:
_s['file_naming_format'] = DEFAULT_FILE_NAMING_FORMAT
def upgrade_to_v2_4_0beta3(config):
"""Convert preserved tags to list"""
_s = config.setting
opt = 'preserved_tags'
value = _s.raw_value(opt, qtype='QString')
if not isinstance(value, list):
_s[opt] = [t.strip() for t in value.split(',')]
def upgrade_to_v2_5_0dev1(config):
"""Rename whitelist cover art provider"""
_s = config.setting
_s['ca_providers'] = [
('UrlRelationships' if n == 'Whitelist' else n, s)
for n, s in _s['ca_providers']
]
def upgrade_to_v2_5_0dev2(config):
"""Reset main view splitter states"""
config.persist['splitter_state'] = b''
config.persist['bottom_splitter_state'] = b''
def upgrade_to_v2_6_0dev1(config):
"""Unset fpcalc path in environments where auto detection is preferred."""
if IS_FROZEN or config.setting['acoustid_fpcalc'].startswith('/snap/picard/'):
config.setting['acoustid_fpcalc'] = ''
def upgrade_to_v2_6_0beta2(config):
"""Rename caa_image_type_as_filename and caa_save_single_front_image options"""
rename_option(config, 'caa_image_type_as_filename', 'image_type_as_filename', BoolOption, False)
rename_option(config, 'caa_save_single_front_image', 'save_only_one_front_image', BoolOption, False)
def upgrade_to_v2_6_0beta3(config):
"""Replace use_system_theme with ui_theme options"""
from picard.ui.theme import UiTheme
_s = config.setting
if _s.value('use_system_theme', BoolOption):
_s['ui_theme'] = str(UiTheme.SYSTEM)
_s.remove('use_system_theme')
def upgrade_to_v2_7_0dev2(config):
"""Replace manually set persistent splitter settings with automated system.
"""
def upgrade_persisted_splitter(new_persist_key, key_map):
_p = config.persist
splitter_dict = {}
for (old_splitter_key, new_splitter_key) in key_map:
if old_splitter_key in _p:
if v := _p.raw_value(old_splitter_key):
splitter_dict[new_splitter_key] = v
_p.remove(old_splitter_key)
_p[new_persist_key] = splitter_dict
# MainWindow splitters
upgrade_persisted_splitter(
new_persist_key='splitters_MainWindow',
key_map=[
('bottom_splitter_state', 'main_window_bottom_splitter'),
('splitter_state', 'main_panel_splitter'),
]
)
# ScriptEditorDialog splitters
upgrade_persisted_splitter(
new_persist_key='splitters_ScriptEditorDialog',
key_map=[
('script_editor_splitter_samples', 'splitter_between_editor_and_examples'),
('script_editor_splitter_samples_before_after', 'splitter_between_before_and_after'),
('script_editor_splitter_documentation', 'splitter_between_editor_and_documentation'),
]
)
# OptionsDialog splitters
upgrade_persisted_splitter(
new_persist_key='splitters_OptionsDialog',
key_map=[
('options_splitter', 'dialog_splitter'),
('scripting_splitter', 'scripting_options_splitter'),
]
)
def upgrade_to_v2_7_0dev3(config):
"""Save file naming scripts to dictionary.
"""
from picard.script import get_file_naming_script_presets
from picard.script.serializer import (
FileNamingScriptInfo,
ScriptSerializerFromFileError,
)
scripts = {}
for item in config.setting.raw_value('file_naming_scripts') or []:
try:
script_item = FileNamingScriptInfo().create_from_yaml(item, create_new_id=False)
scripts[script_item['id']] = script_item.to_dict()
except ScriptSerializerFromFileError:
log.error("Error converting file naming script")
script_list = set(scripts.keys()) | set(map(lambda item: item['id'], get_file_naming_script_presets()))
if config.setting['selected_file_naming_script_id'] not in script_list:
script_item = FileNamingScriptInfo(
script=config.setting.value('file_naming_format', TextOption),
title=_("Primary file naming script"),
readonly=False,
deletable=True,
)
scripts[script_item['id']] = script_item.to_dict()
config.setting['selected_file_naming_script_id'] = script_item['id']
config.setting['file_renaming_scripts'] = scripts
config.setting.remove('file_naming_scripts')
config.setting.remove('file_naming_format')
def upgrade_to_v2_7_0dev4(config):
"""Replace artist_script_exception with artist_script_exceptions"""
_s = config.setting
if script := _s.value('artist_script_exception', TextOption):
_s['artist_script_exceptions'] = [script]
_s.remove('artist_script_exception')
if locale := _s.value('artist_locale', TextOption):
_s['artist_locales'] = [locale]
_s.remove('artist_locale')
def upgrade_to_v2_7_0dev5(config):
"""Replace artist_script_exceptions with script_exceptions and remove artist_script_exception_weighting"""
_s = config.setting
weighting = _s.value('artist_script_exception_weighting', IntOption) or 0
if 'artist_script_exceptions' in _s:
artist_script_exceptions = _s.raw_value('artist_script_exceptions') or []
else:
artist_script_exceptions = []
_s['script_exceptions'] = [(script_exception, weighting) for script_exception in artist_script_exceptions]
_s.remove('artist_script_exceptions')
_s.remove('artist_script_exception_weighting')
def upgrade_to_v2_8_0dev2(config):
"""Remove AcousticBrainz settings from options"""
toolbar_layout = config.setting['toolbar_layout']
try:
toolbar_layout.remove('extract_and_submit_acousticbrainz_features_action')
config.setting['toolbar_layout'] = toolbar_layout
except ValueError:
pass
def upgrade_to_v2_9_0alpha2(config):
"""Add preset file naming scripts to editable user scripts disctionary"""
from picard.script import get_file_naming_script_presets
scripts = config.setting['file_renaming_scripts']
for item in get_file_naming_script_presets():
scripts[item['id']] = item.to_dict()
config.setting['file_renaming_scripts'] = scripts
def upgrade_to_v3_0_0dev1(config):
"""Clear Qt5 state config"""
# A lot of persisted data is serialized Qt5 data that is not compatible with Qt6.
# Keep only the data that is still useful and definitely supported.
keep_persist = (
'current_browser_path',
'current_directory',
'mediaplayer_playback_rate',
'mediaplayer_volume',
'oauth_access_token_expires',
'oauth_access_token',
'oauth_refresh_token_scopes',
'oauth_refresh_token',
'oauth_username',
'script_editor_show_documentation',
'script_editor_tooltips',
'script_editor_wordwrap',
'show_changes_first',
'show_hidden_files',
'tags_from_filenames_format',
'view_cover_art',
'view_file_browser',
'view_metadata_view',
'view_toolbar',
)
# We need to make sure to load all keys in the config file, not just
# those for which an initialized Option exists.
for key in config.allKeys():
if key.startswith('persist/') and key[8:] not in keep_persist:
config.remove(key)
def upgrade_to_v3_0_0dev2(config):
"""Reset option dialog splitter states"""
config.persist['splitters_OptionsDialog'] = b''
def upgrade_to_v3_0_0dev3(config):
"""Option "toolbar_multiselect" was renamed to "allow_multi_dirs_selection"."""
old_opt = 'toolbar_multiselect'
new_opt = 'allow_multi_dirs_selection'
rename_option(config, old_opt, new_opt, BoolOption, False)
def upgrade_to_v3_0_0dev4(config):
"""Reset "file/album_view_header_state" if there were saved while locked."""
if config.persist['album_view_header_locked']:
config.persist.remove('album_view_header_state')
if config.persist['file_view_header_locked']:
config.persist.remove('file_view_header_state')
def upgrade_to_v3_0_0dev5(config):
"""Ensure "replace_dir_separator" contains no directory separator"""
replace_dir_separator = config.setting['replace_dir_separator']
replace_dir_separator = replace_dir_separator.replace(os.sep, DEFAULT_REPLACEMENT)
if os.altsep:
replace_dir_separator = replace_dir_separator.replace(os.altsep, DEFAULT_REPLACEMENT)
config.setting['replace_dir_separator'] = replace_dir_separator
def rename_option(config, old_opt, new_opt, option_type, default):
_s = config.setting
if old_opt in _s:
_s[new_opt] = _s.value(old_opt, option_type, default)
_s.remove(old_opt)
_p = config.profiles
_s.init_profile_options()
all_settings = _p['user_profile_settings']
for profile in _p['user_profiles']:
id = profile['id']
if id in all_settings and old_opt in all_settings[id]:
all_settings[id][new_opt] = all_settings[id][old_opt]
all_settings[id].pop(old_opt)
_p['user_profile_settings'] = all_settings
class UpgradeHooksAutodetectError(Exception):
pass
def autodetect_upgrade_hooks(module_name=None, prefix=UPGRADE_FUNCTION_PREFIX):
"""Detect upgrade hooks methods"""
if module_name is None:
module_name = __name__
def is_upgrade_hook(f):
"""Check if passed function is an upgrade hook"""
return (
isfunction(f)
and f.__module__ == module_name
and f.__name__.startswith(prefix)
)
# Build a dict with version as key and function as value
hooks = dict()
for name, hook in getmembers(sys.modules[module_name], predicate=is_upgrade_hook):
try:
version = Version.from_string(name[len(prefix):])
except VersionError as e:
raise UpgradeHooksAutodetectError(
"Failed to extract version from %s()" % hook.__name__
) from e
if version in hooks:
raise UpgradeHooksAutodetectError(
"Conflicting functions for version %s: %s vs %s" % (version, hooks[version], hook)
)
if version > PICARD_VERSION:
raise UpgradeHooksAutodetectError(
"Upgrade hook %s has version %s > Picard version %s"
% (hook.__name__, version, PICARD_VERSION)
)
hooks[version] = hook
return dict(sorted(hooks.items()))
def upgrade_config(config):
"""Execute detected upgrade hooks"""
config.run_upgrade_hooks(autodetect_upgrade_hooks())
| 22,596
|
Python
|
.py
| 523
| 35.931166
| 110
| 0.645257
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,937
|
__init__.py
|
metabrainz_picard/picard/__init__.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2006-2008, 2011-2014 Lukáš Lalinský
# Copyright (C) 2009, 2018-2024 Philipp Wolfer
# Copyright (C) 2012 Chad Wilson
# Copyright (C) 2012-2013 Michael Wiencek
# Copyright (C) 2013-2024 Laurent Monin
# Copyright (C) 2015 Ohm Patel
# Copyright (C) 2015 Sophist-UK
# Copyright (C) 2016 Suhas
# Copyright (C) 2016-2017 Wieland Hoffmann
# Copyright (C) 2016-2018 Sambhav Kothari
# Copyright (C) 2017 Ville Skyttä
# Copyright (C) 2018, 2021, 2023 Bob Swift
# Copyright (C) 2021 Gabriel Ferreira
# Copyright (C) 2022 skelly37
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import sys
from picard.version import Version
PICARD_ORG_NAME = "MusicBrainz"
PICARD_APP_NAME = "Picard"
PICARD_DISPLAY_NAME = "MusicBrainz Picard"
PICARD_APP_ID = "org.musicbrainz.Picard"
PICARD_DESKTOP_NAME = PICARD_APP_ID + ".desktop"
PICARD_VERSION = Version(3, 0, 0, 'dev', 5)
# optional build version
# it should be in the form '<platform>_<YYMMDDHHMMSS>'
# ie. win32_20140415091256
PICARD_BUILD_VERSION_STR = ""
PICARD_VERSION_STR = str(PICARD_VERSION)
PICARD_VERSION_STR_SHORT = PICARD_VERSION.short_str()
if PICARD_BUILD_VERSION_STR:
__version__ = "%s+%s" % (PICARD_VERSION_STR, PICARD_BUILD_VERSION_STR)
PICARD_FANCY_VERSION_STR = "%s (%s)" % (PICARD_VERSION_STR_SHORT,
PICARD_BUILD_VERSION_STR)
else:
__version__ = PICARD_VERSION_STR_SHORT
PICARD_FANCY_VERSION_STR = PICARD_VERSION_STR_SHORT
# Keep those ordered
api_versions = [
"3.0",
]
api_versions_tuple = [Version.from_string(v) for v in api_versions]
def crash_handler(exc: Exception = None):
"""Implements minimal handling of an exception crashing the application.
This function tries to log the exception to a log file and display
a minimal crash dialog to the user.
This function is supposed to be called from inside an except blog.
"""
# Allow disabling the graphical crash handler for debugging and CI purposes.
if set(sys.argv) & {'--no-crash-dialog', '-v', '--version', '-V', '--long-version', '-h', '--help'}:
return
# First try to get traceback information and write it to a log file
# with minimum chance to fail.
from tempfile import NamedTemporaryFile
import traceback
if exc:
if sys.version_info < (3, 10):
trace_list = traceback.format_exception(None, exc, exc.__traceback__)
else:
trace_list = traceback.format_exception(exc) # pylint: disable=no-value-for-parameter
trace = "".join(trace_list)
else:
trace = traceback.format_exc()
logfile = None
try:
with NamedTemporaryFile(suffix='.log', prefix='picard-crash-', delete=False) as f:
f.write(trace.encode(errors="replace"))
logfile = f.name
except: # noqa: E722,F722 # pylint: disable=bare-except
print("Failed writing log file {0}".format(logfile), file=sys.stderr)
logfile = None
# Display the crash information to the user as a dialog. This requires
# importing Qt6 and has some potential to fail if things are broken.
from PyQt6.QtCore import (
QCoreApplication,
Qt,
QUrl,
)
from PyQt6.QtWidgets import (
QApplication,
QMessageBox,
)
app = QCoreApplication.instance()
if not app:
app = QApplication(sys.argv)
msgbox = QMessageBox()
msgbox.setIcon(QMessageBox.Icon.Critical)
msgbox.setWindowTitle("Picard terminated unexpectedly")
msgbox.setTextFormat(Qt.TextFormat.RichText)
msgbox.setText(
'An unexpected error has caused Picard to crash. '
'Please report this issue on the <a href="https://tickets.metabrainz.org/projects/PICARD">MusicBrainz bug tracker</a>.')
if logfile:
logfile_url = QUrl.fromLocalFile(logfile)
msgbox.setInformativeText(
'A logfile has been written to <a href="{0}">{1}</a>.'
.format(logfile_url.url(), logfile))
msgbox.setDetailedText(trace)
msgbox.setStandardButtons(QMessageBox.StandardButton.Close)
msgbox.setDefaultButton(QMessageBox.StandardButton.Close)
msgbox.exec()
app.quit()
def register_excepthook():
def _global_exception_handler(exctype, value, traceback):
from picard import crash_handler
crash_handler(exc=value)
sys.__excepthook__(exctype, value, traceback)
sys.excepthook = _global_exception_handler
| 5,171
|
Python
|
.py
| 124
| 36.887097
| 128
| 0.70573
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,938
|
pluginmanager.py
|
metabrainz_picard/picard/pluginmanager.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2007 Lukáš Lalinský
# Copyright (C) 2014 Shadab Zafar
# Copyright (C) 2015-2021, 2023-2024 Laurent Monin
# Copyright (C) 2019 Wieland Hoffmann
# Copyright (C) 2019-2020, 2022-2023 Philipp Wolfer
# Copyright (C) 2022 skelly37
# Copyright (C) 2023 Bob Swift
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from functools import partial
import importlib
from importlib.abc import MetaPathFinder
import json
import os.path
import shutil
import sys
import tempfile
import zipfile
import zipimport
from PyQt6 import QtCore
from picard import log
from picard.const import (
PLUGINS_API,
USER_PLUGIN_DIR,
)
from picard.const.sys import IS_FROZEN
from picard.i18n import (
N_,
gettext as _,
)
from picard.plugin import (
_PLUGIN_MODULE_PREFIX,
PluginData,
PluginWrapper,
_unregister_module_extensions,
)
import picard.plugins
from picard.version import (
Version,
VersionError,
)
_SUFFIXES = tuple(importlib.machinery.all_suffixes())
_PACKAGE_ENTRIES = ("__init__.py", "__init__.pyc", "__init__.pyo")
_PLUGIN_PACKAGE_SUFFIX = ".picard"
_PLUGIN_PACKAGE_SUFFIX_LEN = len(_PLUGIN_PACKAGE_SUFFIX)
_FILEEXTS = ('.py', '.pyc', '.pyo', '.zip')
_UPDATE_SUFFIX = '.update'
_UPDATE_SUFFIX_LEN = len(_UPDATE_SUFFIX)
_extension_points = []
def is_update(path):
return path.endswith(_UPDATE_SUFFIX)
def strip_update_suffix(path):
if not is_update(path):
return path
return path[:-_UPDATE_SUFFIX_LEN]
def is_zip(path):
return path.endswith('.zip')
def strip_zip_suffix(path):
if not is_zip(path):
return path
return path[:-4]
def is_package(path):
return path.endswith(_PLUGIN_PACKAGE_SUFFIX)
def strip_package_suffix(path):
if not is_package(path):
return path
return path[:-_PLUGIN_PACKAGE_SUFFIX_LEN]
def is_zipped_package(path):
return path.endswith(_PLUGIN_PACKAGE_SUFFIX + '.zip')
def _plugin_name_from_path(path):
path = os.path.normpath(path)
if is_zip(path):
name = os.path.basename(strip_zip_suffix(path))
if is_package(name):
return strip_package_suffix(name)
else:
return name
elif os.path.isdir(path):
for entry in _PACKAGE_ENTRIES:
if os.path.isfile(os.path.join(path, entry)):
return os.path.basename(path)
else:
file = os.path.basename(path)
if file in _PACKAGE_ENTRIES:
return None
name, ext = os.path.splitext(file)
if ext in _SUFFIXES:
return name
return None
def load_zip_manifest(archive_path):
if is_zipped_package(archive_path):
try:
archive = zipfile.ZipFile(archive_path)
with archive.open('MANIFEST.json') as f:
return json.loads(str(f.read().decode()))
except Exception as why:
log.warning("Failed to load manifest data from json: %s", why)
return None
def zip_import(path):
if (not is_zip(path) or not os.path.isfile(path)):
return None
try:
return zipimport.zipimporter(path)
except zipimport.ZipImportError as why:
log.error("ZIP import error: %s", why)
return None
def _compatible_api_versions(api_versions):
versions = [Version.from_string(v) for v in list(api_versions)]
return set(versions) & set(picard.api_versions_tuple)
_plugin_dirs = []
def plugin_dirs():
yield from _plugin_dirs
def init_default_plugin_dirs():
# Add user plugin dir first
if not os.path.exists(USER_PLUGIN_DIR):
os.makedirs(USER_PLUGIN_DIR)
register_plugin_dir(USER_PLUGIN_DIR)
# Register system wide plugin dir
if IS_FROZEN:
toppath = sys.argv[0]
else:
toppath = os.path.abspath(__file__)
topdir = os.path.dirname(toppath)
plugin_dir = os.path.join(topdir, "plugins")
register_plugin_dir(plugin_dir)
def register_plugin_dir(path):
if path not in _plugin_dirs:
_plugin_dirs.append(path)
def plugin_dir_for_path(path):
for plugin_dir in plugin_dirs():
try:
if os.path.commonpath((path, plugin_dir)) == plugin_dir:
return plugin_dir
except ValueError:
pass
return path
class PluginManager(QtCore.QObject):
plugin_installed = QtCore.pyqtSignal(PluginWrapper, bool)
plugin_updated = QtCore.pyqtSignal(str, bool)
plugin_removed = QtCore.pyqtSignal(str, bool)
plugin_errored = QtCore.pyqtSignal(str, str, bool)
updates_available = QtCore.pyqtSignal(list)
def __init__(self, plugins_directory=None):
super().__init__()
self.tagger = QtCore.QCoreApplication.instance()
self.plugins = []
self._available_plugins = None # None=never loaded, [] = empty
if plugins_directory is None:
plugins_directory = USER_PLUGIN_DIR
self.plugins_directory = os.path.normpath(plugins_directory)
init_default_plugin_dirs()
@property
def available_plugins(self):
return self._available_plugins
def plugin_error(self, name, error, *args, **kwargs):
"""Log a plugin loading error for the plugin `name` and signal the
error via the `plugin_errored` signal.
A string consisting of all `args` interpolated into `error` will be
passed to the function given via the `log_func` keyword argument
(default: log.error) and as the error message to the `plugin_errored`
signal.
Instead of using `args` the interpolation parameters can also be passed
with the `params` keyword parameter. This is specifically useful to
pass a dictionary when using named placeholders."""
params = kwargs.get('params', args)
if params:
error = error % params
log_func = kwargs.get('log_func', log.error)
log_func(error)
self.plugin_errored.emit(name, error, False)
def _marked_for_update(self):
for file in os.listdir(self.plugins_directory):
if file.endswith(_UPDATE_SUFFIX):
source_path = os.path.join(self.plugins_directory, file)
target_path = strip_update_suffix(source_path)
plugin_name = _plugin_name_from_path(target_path)
if plugin_name:
yield (source_path, target_path, plugin_name)
else:
log.error('Cannot get plugin name from %r', source_path)
def handle_plugin_updates(self):
for source_path, target_path, plugin_name in self._marked_for_update():
self._remove_plugin(plugin_name)
os.rename(source_path, target_path)
log.debug("Updating plugin %r (%r))", plugin_name, target_path)
def load_plugins_from_directory(self, plugindir):
plugindir = os.path.normpath(plugindir)
if not os.path.isdir(plugindir):
log.info("Plugin directory %r doesn't exist", plugindir)
return
if plugindir == self.plugins_directory:
# .update trick is only for plugins installed through the Picard UI
# and only for plugins in plugins_directory (USER_PLUGIN_DIR by default)
self.handle_plugin_updates()
# now load found plugins
names = set()
for path in (os.path.join(plugindir, file) for file in os.listdir(plugindir)):
name = _plugin_name_from_path(path)
if name:
names.add(name)
log.debug("Looking for plugins in directory %r, %d names found",
plugindir,
len(names))
for name in sorted(names):
try:
self._load_plugin(name)
except Exception:
self.plugin_error(name, _("Unable to load plugin '%s'"), name, log_func=log.exception)
def _get_plugin_index_by_name(self, name):
for index, plugin in enumerate(self.plugins):
if name == plugin.module_name:
return (plugin, index)
return (None, None)
def _load_plugin(self, name):
existing_plugin, existing_plugin_index = self._get_plugin_index_by_name(name)
if existing_plugin:
log.debug("Ignoring already loaded plugin %r (version %r at %r)",
existing_plugin.module_name,
existing_plugin.version,
existing_plugin.file)
return
spec = None
module_pathname = None
zip_importer = None
manifest_data = None
full_module_name = _PLUGIN_MODULE_PREFIX + name
# Legacy loading of ZIP plugins. In Python >= 3.10 this is all handled
# by PluginMetaPathFinder. Remove once Python 3.9 is no longer supported.
if not hasattr(zipimport.zipimporter, 'find_spec'):
(zip_importer, plugin_dir, module_pathname, manifest_data) = self._legacy_load_zip_plugin(name)
if not module_pathname:
spec = PluginMetaPathFinder().find_spec(full_module_name, [])
if not spec or not spec.loader:
errorfmt = _('Failed loading plugin "%(plugin)s"')
self.plugin_error(name, errorfmt, params={
'plugin': name,
})
return None
module_pathname = spec.origin
if isinstance(spec.loader, zipimport.zipimporter):
manifest_data = load_zip_manifest(spec.loader.archive)
if os.path.basename(module_pathname) == '__init__.py':
module_pathname = os.path.dirname(module_pathname)
plugin_dir = plugin_dir_for_path(module_pathname)
plugin = None
try:
if zip_importer: # Legacy ZIP import for Python < 3.10
plugin_module = zip_importer.load_module(full_module_name)
else:
plugin_module = importlib.util.module_from_spec(spec)
# This is kind of a hack. The module will be in sys.modules
# after exec_module has run. But if inside of the loaded plugin
# there are relative imports it would load the same plugin
# module twice. This executes the plugins code twice and leads
# to potential side effects.
sys.modules[full_module_name] = plugin_module
try:
spec.loader.exec_module(plugin_module)
except: # noqa: E722
del sys.modules[full_module_name]
raise
plugin = PluginWrapper(plugin_module, plugin_dir,
file=module_pathname, manifest_data=manifest_data)
compatible_versions = _compatible_api_versions(plugin.api_versions)
if compatible_versions:
log.debug("Loading plugin %r version %s, compatible with API: %s",
plugin.name,
plugin.version,
", ".join([v.short_str() for v in
sorted(compatible_versions)]))
plugin.compatible = True
setattr(picard.plugins, name, plugin_module)
if existing_plugin:
self.plugins[existing_plugin_index] = plugin
else:
self.plugins.append(plugin)
else:
errorfmt = _('Plugin "%(plugin)s" from "%(filename)s" is not '
'compatible with this version of Picard.')
params = {'plugin': plugin.name, 'filename': plugin.file}
self.plugin_error(plugin.name, errorfmt, params=params, log_func=log.warning)
except VersionError as e:
errorfmt = _('Plugin "%(plugin)s" has an invalid API version string: %(error)s')
self.plugin_error(name, errorfmt, params={
'plugin': name,
'error': e,
})
except BaseException:
errorfmt = _('Plugin "%(plugin)s"')
self.plugin_error(name, errorfmt, log_func=log.exception,
params={'plugin': name})
return plugin
def _legacy_load_zip_plugin(self, name):
for plugin_dir in plugin_dirs():
zipfilename = os.path.join(plugin_dir, name + '.zip')
zip_importer = zip_import(zipfilename)
if zip_importer:
if not zip_importer.find_module(name):
errorfmt = _('Failed loading zipped plugin "%(plugin)s" from "%(filename)s"')
self.plugin_error(name, errorfmt, params={
'plugin': name,
'filename': zipfilename,
})
return (None, None, None, None)
module_pathname = zip_importer.get_filename(name)
manifest_data = load_zip_manifest(zip_importer.archive)
return (zip_importer, plugin_dir, module_pathname, manifest_data)
return (None, None, None, None)
def _get_existing_paths(self, plugin_name, fileexts):
dirpath = os.path.join(self.plugins_directory, plugin_name)
if not os.path.isdir(dirpath):
dirpath = None
filenames = {plugin_name + ext for ext in fileexts}
filepaths = [os.path.join(self.plugins_directory, f)
for f in os.listdir(self.plugins_directory)
if f in filenames
]
return (dirpath, filepaths)
def _remove_plugin_files(self, plugin_name, with_update=False):
plugin_name = strip_zip_suffix(plugin_name)
log.debug("Remove plugin files and dirs : %r", plugin_name)
dirpath, filepaths = self._get_existing_paths(plugin_name, _FILEEXTS)
if dirpath:
if os.path.islink(dirpath):
log.debug("Removing symlink %r", dirpath)
os.remove(dirpath)
elif os.path.isdir(dirpath):
log.debug("Removing directory %r", dirpath)
shutil.rmtree(dirpath)
if filepaths:
for filepath in filepaths:
log.debug("Removing file %r", filepath)
os.remove(filepath)
if with_update:
update = filepath + _UPDATE_SUFFIX
if os.path.isfile(update):
log.debug("Removing file %r", update)
os.remove(update)
def _remove_plugin(self, plugin_name, with_update=False):
self._remove_plugin_files(plugin_name, with_update)
_unregister_module_extensions(plugin_name)
self.plugins = [p for p in self.plugins if p.module_name != plugin_name]
def remove_plugin(self, plugin_name, with_update=False):
self._remove_plugin(plugin_name, with_update=with_update)
self.plugin_removed.emit(plugin_name, False)
def _install_plugin_zip(self, plugin_name, plugin_data, update=False):
# zipped module from download
zip_plugin = plugin_name + '.zip'
dst = os.path.join(self.plugins_directory, zip_plugin)
if update:
dst += _UPDATE_SUFFIX
if os.path.isfile(dst):
os.remove(dst)
with tempfile.NamedTemporaryFile(dir=self.plugins_directory) as zipfile:
zipfile.write(plugin_data)
zipfile.flush()
os.fsync(zipfile.fileno())
try:
os.link(zipfile.name, dst)
except OSError:
with open(dst, 'wb') as dstfile:
zipfile.seek(0)
shutil.copyfileobj(zipfile, dstfile)
log.debug("Plugin (zipped) saved to %r", dst)
def _install_plugin_file(self, path, update=False):
dst = os.path.join(self.plugins_directory, os.path.basename(path))
if update:
dst += _UPDATE_SUFFIX
if os.path.isfile(dst):
os.remove(dst)
shutil.copy2(path, dst)
log.debug("Plugin (file) saved to %r", dst)
def _install_plugin_dir(self, plugin_name, path, update=False):
dst = os.path.join(self.plugins_directory, plugin_name)
if update:
dst += _UPDATE_SUFFIX
if os.path.isdir(dst):
shutil.rmtree(dst)
shutil.copytree(path, dst)
log.debug("Plugin (directory) saved to %r", dst)
def install_plugin(self, path, update=False, plugin_name=None, plugin_data=None):
"""
path is either:
1) /some/dir/name.py
2) /some/dir/name (directory containing __init__.py)
3) /some/dir/name.zip (containing either 1 or 2)
"""
assert path or plugin_name, "path is required if plugin_name is empty"
if not plugin_name:
plugin_name = _plugin_name_from_path(path)
if plugin_name:
try:
if plugin_data:
self._install_plugin_zip(plugin_name, plugin_data, update=update)
elif os.path.isfile(path):
self._install_plugin_file(path, update=update)
elif os.path.isdir(path):
self._install_plugin_dir(plugin_name, path, update=update)
except OSError as why:
log.error("Unable to copy plugin '%s' to %r: %s", plugin_name, self.plugins_directory, why)
return
if not update:
try:
installed_plugin = self._load_plugin(plugin_name)
if not installed_plugin:
raise RuntimeError("Failed loading newly installed plugin %s" % plugin_name)
except Exception as e:
log.error("Unable to load plugin '%s': %s", plugin_name, e)
self._remove_plugin(plugin_name)
else:
self.plugin_installed.emit(installed_plugin, False)
else:
self.plugin_updated.emit(plugin_name, False)
def query_available_plugins(self, callback=None):
self.tagger.webservice.get_url(
url=PLUGINS_API['urls']['plugins'],
handler=partial(self._plugins_json_loaded, callback=callback),
priority=True,
important=True,
)
def is_available(self, plugin_name):
return any(p.module_name == plugin_name for p in self._available_plugins)
def _plugins_json_loaded(self, response, reply, error, callback=None):
if error:
self.tagger.window.set_statusbar_message(
N_("Error loading plugins list: %(error)s"),
{'error': reply.errorString()},
echo=log.error
)
self._available_plugins = []
else:
try:
self._available_plugins = [PluginData(data, key) for key, data in
response['plugins'].items()
if _compatible_api_versions(data['api_versions'])]
except (AttributeError, KeyError, TypeError):
self._available_plugins = []
if callback:
callback()
# pylint: disable=no-self-use
def enabled(self, name):
return True
def _plugins_have_new_versions(self):
"""Compare available plugins versions with installed plugins ones
and yield plugin names of plugins that have new versions"""
if self.available_plugins is not None:
available_versions = {p.module_name: p.version for p in self.available_plugins}
for plugin in self.plugins:
if plugin.module_name not in available_versions:
continue
if available_versions[plugin.module_name] > plugin.version:
yield plugin.name
def check_update(self):
if self.available_plugins is None:
self.query_available_plugins(self._notify_updates)
else:
self._notify_updates()
def _notify_updates(self):
plugins_with_updates = list(self._plugins_have_new_versions())
if plugins_with_updates:
self.updates_available.emit(plugins_with_updates)
class PluginMetaPathFinder(MetaPathFinder):
def find_spec(self, fullname, path, target=None):
if not fullname.startswith(_PLUGIN_MODULE_PREFIX):
return None
plugin_name = fullname[len(_PLUGIN_MODULE_PREFIX):]
for plugin_dir in plugin_dirs():
for file_path in self._plugin_file_paths(plugin_dir, plugin_name):
if os.path.exists(file_path):
spec = self._spec_from_path(fullname, file_path)
if spec and spec.loader:
return spec
def _spec_from_path(self, fullname, file_path):
if file_path.endswith('.zip'):
return self._spec_from_zip(fullname, file_path)
else:
return importlib.util.spec_from_file_location(fullname, file_path)
def _spec_from_zip(self, fullname, file_path):
zip_importer = zip_import(file_path)
if zip_importer:
return zip_importer.find_spec(fullname)
@staticmethod
def _plugin_file_paths(plugin_dir, plugin_name):
for entry in _PACKAGE_ENTRIES:
yield os.path.join(plugin_dir, plugin_name, entry)
for ext in _FILEEXTS:
# On Python < 3.10 ZIP file loading is handled in PluginManager._load_plugin
if ext == '.zip' and not hasattr(zipimport.zipimporter, 'find_spec'):
continue
yield os.path.join(plugin_dir, plugin_name + ext)
sys.meta_path.append(PluginMetaPathFinder())
| 22,500
|
Python
|
.py
| 507
| 33.595661
| 107
| 0.605305
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,939
|
log.py
|
metabrainz_picard/picard/log.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2007, 2011 Lukáš Lalinský
# Copyright (C) 2008-2010, 2019, 2021-2023 Philipp Wolfer
# Copyright (C) 2012-2013 Michael Wiencek
# Copyright (C) 2013, 2015, 2018-2021, 2023-2024 Laurent Monin
# Copyright (C) 2016-2018 Sambhav Kothari
# Copyright (C) 2017 Sophist-UK
# Copyright (C) 2018 Wieland Hoffmann
# Copyright (C) 2021 Gabriel Ferreira
# Copyright (C) 2024 Bob Swift
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from collections import (
OrderedDict,
deque,
namedtuple,
)
from importlib.machinery import PathFinder
import logging
from pathlib import (
Path,
PurePosixPath,
)
from threading import Lock
from PyQt6 import QtCore
from picard.const import USER_PLUGIN_DIR
from picard.const.sys import (
FROZEN_TEMP_PATH,
IS_FROZEN,
)
from picard.debug_opts import DebugOpt
from picard.i18n import N_
# Get the absolute path for the picard module
if IS_FROZEN:
picard_module_path = Path(FROZEN_TEMP_PATH).joinpath('picard').resolve()
else:
picard_module_path = Path(PathFinder().find_spec('picard').origin).resolve()
if not picard_module_path.is_dir():
picard_module_path = picard_module_path.parent
_MAX_TAIL_LEN = 10**6
def set_level(level):
main_logger.setLevel(level)
def get_effective_level():
return main_logger.getEffectiveLevel()
_feat = namedtuple('_feat', ['name', 'prefix', 'color_key'])
levels_features = OrderedDict([
(logging.ERROR, _feat(N_('Error'), 'E', 'log_error')),
(logging.WARNING, _feat(N_('Warning'), 'W', 'log_warning')),
(logging.INFO, _feat(N_('Info'), 'I', 'log_info')),
(logging.DEBUG, _feat(N_('Debug'), 'D', 'log_debug')),
])
# COMMON CLASSES
TailLogTuple = namedtuple(
'TailLogTuple', ['pos', 'message', 'level'])
class TailLogHandler(logging.Handler):
def __init__(self, log_queue, tail_logger, log_queue_lock):
super().__init__()
self.log_queue = log_queue
self.tail_logger = tail_logger
self.log_queue_lock = log_queue_lock
self.pos = 0
def emit(self, record):
with self.log_queue_lock:
self.log_queue.append(
TailLogTuple(
self.pos,
self.format(record),
record.levelno
)
)
self.pos += 1
self.tail_logger.updated.emit()
def _calculate_bounds(previous_position, first_position, last_position, queue_length):
# If first item of the queue is bigger than prev, use first item position - 1 as prev
# e.g. queue = [8, 9, 10] , prev = 6, new_prev = 8-1 = 7
if previous_position < first_position:
previous_position = first_position-1
# The offset of the first item in the queue is
# equal to the length of the queue, minus the length to be printed
offset = queue_length - (last_position - previous_position)
# If prev > last_position, offset will be bigger than queue length offset > queue_length
# This will force an empty list
if offset > queue_length:
offset = queue_length
# If offset < 1, there is a discontinuity in the queue positions
# Setting queue_length to 0 informs the caller that something is wrong and the slow path should be taken
return offset, queue_length
class TailLogger(QtCore.QObject):
updated = QtCore.pyqtSignal()
def __init__(self, maxlen):
super().__init__()
self._log_queue = deque(maxlen=maxlen)
self._queue_lock = Lock()
self.log_handler = TailLogHandler(self._log_queue, self, self._queue_lock)
def contents(self, prev=-1):
with self._queue_lock:
if self._log_queue:
offset, length = _calculate_bounds(prev, self._log_queue[0].pos, self._log_queue[-1].pos, len(self._log_queue))
if offset >= 0:
yield from (self._log_queue[i] for i in range(offset, length))
# If offset < 0, there is a discontinuity in the queue positions
# Use a slower approach to get the new content.
else:
yield from (x for x in self._log_queue if x.pos > prev)
def clear(self):
with self._queue_lock:
self._log_queue.clear()
# MAIN LOGGER
main_logger = logging.getLogger('main')
# do not pass logging messages to the handlers of ancestor loggers (PICARD-2651)
main_logger.propagate = False
main_logger.setLevel(logging.INFO)
def name_filter(record):
# In case the module exists within picard, remove the picard prefix
# else, in case of something like a plugin, keep the path as it is.
# It provides a significant but short name from the filepath of the module
path = Path(record.pathname).with_suffix('')
# PyInstaller paths are already relative
# FIXME: With Python 3.9 this should better use
# path.is_relative_to(picard_module_path.parent)
# to avoid the exception handling.
if path.is_absolute():
try:
path = path.resolve().relative_to(picard_module_path)
except ValueError:
pass
if path.is_absolute() and not DebugOpt.PLUGIN_FULLPATH.enabled:
try:
path = path.resolve().relative_to(USER_PLUGIN_DIR)
parts = list(path.parts)
parts.insert(0, 'plugins')
path = Path(*parts)
except ValueError:
pass
parts = list(path.parts)
if parts[-1] == '__init__':
del parts[-1]
if parts[0] == path.anchor:
parts[0] = '/'
# Remove the plugin module file if the file name is the same as
# the immediately preceeding plugin zip file name, similar to the
# way that the final `__init__.py` file is removed.
if len(parts) > 1 and parts[-1] + '.zip' == parts[-2]:
del parts[-1]
record.name = str(PurePosixPath(*parts))
return True
main_logger.addFilter(name_filter)
main_tail = TailLogger(_MAX_TAIL_LEN)
main_fmt = '%(levelname).1s: %(asctime)s,%(msecs)03d %(name)s.%(funcName)s:%(lineno)d: %(message)s'
main_time_fmt = '%H:%M:%S'
main_inapp_fmt = main_fmt
main_inapp_time_fmt = main_time_fmt
main_handler = main_tail.log_handler
main_formatter = logging.Formatter(main_inapp_fmt, main_inapp_time_fmt)
main_handler.setFormatter(main_formatter)
main_logger.addHandler(main_handler)
main_console_handler = logging.StreamHandler()
main_console_formatter = logging.Formatter(main_fmt, main_time_fmt)
main_console_handler.setFormatter(main_console_formatter)
main_logger.addHandler(main_console_handler)
debug = main_logger.debug
info = main_logger.info
warning = main_logger.warning
error = main_logger.error
exception = main_logger.exception
log = main_logger.log
# HISTORY LOGGING
history_logger = logging.getLogger('history')
# do not pass logging messages to the handlers of ancestor loggers (PICARD-2651)
history_logger.propagate = False
history_logger.setLevel(logging.INFO)
history_tail = TailLogger(_MAX_TAIL_LEN)
history_handler = history_tail.log_handler
history_formatter = logging.Formatter('%(asctime)s - %(message)s')
history_handler.setFormatter(history_formatter)
history_logger.addHandler(history_handler)
def history_info(message, *args):
history_logger.info(message, *args)
| 7,997
|
Python
|
.py
| 193
| 36.150259
| 127
| 0.688381
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,940
|
debug_opts.py
|
metabrainz_picard/picard/debug_opts.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2024 Laurent Monin
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from enum import Enum
from picard.i18n import N_
class DebugOptEnum(int, Enum):
__registry__ = set()
def __new__(cls, value: int, title: str, description: str) -> None:
value = int(value)
obj = super().__new__(cls, value)
obj._value_ = value
obj.title = title
obj.description = description
return obj
@property
def optname(self):
return self.name.lower()
@property
def enabled(self):
return self in self.__registry__
@enabled.setter
def enabled(self, enable: bool):
if enable:
self.__registry__.add(self)
else:
self.__registry__.discard(self)
@classmethod
def opt_names(cls):
"""Returns a comma-separated list of all possible debug options"""
return ','.join(sorted(o.optname for o in cls))
@classmethod
def from_string(cls, string: str):
"""Parse command line argument, a string with comma-separated values,
and enable corresponding debug options"""
opts = {str(o).strip().lower() for o in string.split(',')}
for o in cls:
o.enabled = o.optname in opts
@classmethod
def to_string(cls):
"""Returns a comma-separated list of all enabled debug options"""
return ','.join(sorted(o.optname for o in cls.__registry__))
@classmethod
def set_registry(cls, registry: set):
"""Defines a new set to store enabled debug options"""
cls.__registry__ = registry
@classmethod
def get_registry(cls):
"""Returns current storage for enabled debug options"""
return cls.__registry__
class DebugOpt(DebugOptEnum):
PLUGIN_FULLPATH = 1, N_('Plugin Fullpath'), N_('Log plugin full paths')
WS_POST = 2, N_('Web Service Post Data'), N_('Log data of web service post requests')
WS_REPLIES = 3, N_('Web Service Replies'), N_('Log content of web service replies')
| 2,766
|
Python
|
.py
| 69
| 34.57971
| 89
| 0.670395
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,941
|
tagger.py
|
metabrainz_picard/picard/tagger.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2004 Robert Kaye
# Copyright (C) 2006-2009, 2011-2014, 2017 Lukáš Lalinský
# Copyright (C) 2008 Gary van der Merwe
# Copyright (C) 2008 amckinle
# Copyright (C) 2008-2010, 2014-2015, 2018-2024 Philipp Wolfer
# Copyright (C) 2009 Carlin Mangar
# Copyright (C) 2010 Andrew Barnert
# Copyright (C) 2011-2014 Michael Wiencek
# Copyright (C) 2011-2014, 2017-2019 Wieland Hoffmann
# Copyright (C) 2012 Chad Wilson
# Copyright (C) 2013 Calvin Walton
# Copyright (C) 2013 Ionuț Ciocîrlan
# Copyright (C) 2013 brainz34
# Copyright (C) 2013-2014, 2017 Sophist-UK
# Copyright (C) 2013-2015, 2017-2024 Laurent Monin
# Copyright (C) 2016 Rahul Raturi
# Copyright (C) 2016 Simon Legner
# Copyright (C) 2016 Suhas
# Copyright (C) 2016-2018 Sambhav Kothari
# Copyright (C) 2017-2018 Vishal Choudhary
# Copyright (C) 2018 virusMac
# Copyright (C) 2018, 2022-2023 Bob Swift
# Copyright (C) 2019 Joel Lintunen
# Copyright (C) 2020 Julius Michaelis
# Copyright (C) 2020-2021 Gabriel Ferreira
# Copyright (C) 2022 Kamil
# Copyright (C) 2022 skelly37
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import argparse
from functools import partial
from hashlib import blake2b
import logging
import os
import platform
import re
import shutil
import signal
import sys
from textwrap import fill
import time
from urllib.parse import urlparse
from uuid import uuid4
from PyQt6 import (
QtCore,
QtGui,
QtWidgets,
)
from picard import (
PICARD_APP_ID,
PICARD_APP_NAME,
PICARD_FANCY_VERSION_STR,
PICARD_ORG_NAME,
acoustid,
log,
)
from picard.acoustid.manager import AcoustIDManager
from picard.album import (
Album,
NatAlbum,
run_album_post_removal_processors,
)
from picard.audit import setup_audit
from picard.browser.browser import BrowserIntegration
from picard.browser.filelookup import FileLookup
from picard.cluster import (
Cluster,
ClusterList,
UnclusteredFiles,
)
from picard.collection import load_user_collections
from picard.config import (
get_config,
setup_config,
)
from picard.config_upgrade import upgrade_config
from picard.const import USER_DIR
from picard.const.sys import (
IS_HAIKU,
IS_MACOS,
IS_WIN,
)
from picard.debug_opts import DebugOpt
from picard.disc import (
Disc,
dbpoweramplog,
eaclog,
whipperlog,
)
from picard.file import File
from picard.formats import open_ as open_file
from picard.i18n import (
N_,
gettext as _,
setup_gettext,
)
from picard.item import MetadataItem
from picard.options import init_options
from picard.pluginmanager import (
PluginManager,
plugin_dirs,
)
from picard.releasegroup import ReleaseGroup
from picard.track import (
NonAlbumTrack,
Track,
)
from picard.util import (
check_io_encoding,
encode_filename,
is_hidden,
iter_files_from_objects,
mbid_validate,
normpath,
periodictouch,
pipe,
process_events_iter,
system_supports_long_paths,
thread,
versions,
webbrowser2,
)
from picard.util.cdrom import (
DISCID_NOT_LOADED_MESSAGE,
discid as _discid,
get_cdrom_drives,
)
from picard.util.checkupdate import UpdateCheckManager
from picard.util.remotecommands import (
REMOTE_COMMANDS,
RemoteCommands,
)
from picard.webservice import WebService
from picard.webservice.api_helpers import (
AcoustIdAPIHelper,
MBAPIHelper,
)
import picard.resources # noqa: F401 # pylint: disable=unused-import
from picard.ui import (
FONT_FAMILY_MONOSPACE,
theme,
)
from picard.ui.mainwindow import MainWindow
from picard.ui.searchdialog.album import AlbumSearchDialog
from picard.ui.searchdialog.artist import ArtistSearchDialog
from picard.ui.searchdialog.track import TrackSearchDialog
from picard.ui.util import FileDialog
# A "fix" for https://bugs.python.org/issue1438480
def _patched_shutil_copystat(src, dst, *, follow_symlinks=True):
try:
_orig_shutil_copystat(src, dst, follow_symlinks=follow_symlinks)
except OSError:
pass
_orig_shutil_copystat = shutil.copystat
shutil.copystat = _patched_shutil_copystat
class ParseItemsToLoad:
WINDOWS_DRIVE_TEST = re.compile(r"^[a-z]\:", re.IGNORECASE)
def __init__(self, items):
self.files = set()
self.mbids = set()
self.urls = set()
for item in items:
parsed = urlparse(item)
log.debug(f"Parsed: {repr(parsed)}")
if not parsed.scheme:
self.files.add(item)
if parsed.scheme == 'file':
# remove file:// prefix safely
self.files.add(item[7:])
elif parsed.scheme == 'mbid':
self.mbids.add(parsed.netloc + parsed.path)
elif parsed.scheme in {'http', 'https'}:
# .path returns / before actual link
self.urls.add(parsed.path[1:])
elif IS_WIN and self.WINDOWS_DRIVE_TEST.match(item):
# Treat all single-character schemes as part of the file spec to allow
# specifying a drive identifier on Windows systems.
self.files.add(item)
# needed to indicate whether Picard should be brought to the front
def non_executable_items(self):
return bool(self.files or self.mbids or self.urls)
def __bool__(self):
return bool(self.files or self.mbids or self.urls)
def __str__(self):
return f"files: {repr(self.files)} mbids: f{repr(self.mbids)} urls: {repr(self.urls)}"
class Tagger(QtWidgets.QApplication):
tagger_stats_changed = QtCore.pyqtSignal()
listen_port_changed = QtCore.pyqtSignal(int)
cluster_added = QtCore.pyqtSignal(Cluster)
cluster_removed = QtCore.pyqtSignal(Cluster)
album_added = QtCore.pyqtSignal(Album)
album_removed = QtCore.pyqtSignal(Album)
__instance = None
_debug = False
_no_restore = False
def __init__(self, picard_args, localedir, autoupdate, pipe_handler=None):
# Initialize these variables early as they are needed for a clean
# shutdown.
self._acoustid = None
self.browser_integration = None
self.exit_cleanup = []
self.pipe_handler = None
self.priority_thread_pool = None
self.save_thread_pool = None
self.stopping = False
self.thread_pool = None
self.webservice = None
super().__init__(sys.argv)
self.__class__.__instance = self
init_options()
setup_config(app=self, filename=picard_args.config_file)
config = get_config()
theme.setup(self)
self._to_load = picard_args.processable
self.autoupdate_enabled = autoupdate
self._no_restore = picard_args.no_restore
self._no_plugins = picard_args.no_plugins
self.set_log_level(config.setting['log_verbosity'])
if picard_args.debug or 'PICARD_DEBUG' in os.environ:
self.set_log_level(logging.DEBUG)
if picard_args.audit:
setup_audit(picard_args.audit)
if picard_args.debug_opts:
DebugOpt.from_string(picard_args.debug_opts)
# Main thread pool used for most background tasks
self.thread_pool = QtCore.QThreadPool(self)
# Two threads are needed for the pipe handler and command processing.
# At least one thread is required to run other Picard background tasks.
self.thread_pool.setMaxThreadCount(max(3, QtCore.QThread.idealThreadCount()))
# Provide a separate thread pool for operations that should not be
# delayed by longer background processing tasks, e.g. because the user
# expects instant feedback instead of waiting for a long list of
# operations to finish.
self.priority_thread_pool = QtCore.QThreadPool(self)
self.priority_thread_pool.setMaxThreadCount(1)
# Use a separate thread pool for file saving, with a thread count of 1,
# to avoid race conditions in File._save_and_rename.
self.save_thread_pool = QtCore.QThreadPool(self)
self.save_thread_pool.setMaxThreadCount(1)
# Setup pipe handler for managing single app instance and commands.
self.pipe_handler = pipe_handler
if self.pipe_handler:
self._command_thread_running = False
self.pipe_handler.pipe_running = True
thread.run_task(self.pipe_server, self._pipe_server_finished)
self._init_remote_commands()
if not IS_WIN:
# Set up signal handling
# It's not possible to call all available functions from signal
# handlers, therefore we need to set up a QSocketNotifier to listen
# on a socket. Sending data through a socket can be done in a
# signal handler, so we use the socket to notify the application of
# the signal.
# This code is adopted from
# https://qt-project.org/doc/qt-4.8/unix-signals.html
# To not make the socket module a requirement for the Windows
# installer, import it here and not globally
import socket
self.signalfd = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM, 0)
self.signalnotifier = QtCore.QSocketNotifier(self.signalfd[1].fileno(),
QtCore.QSocketNotifier.Type.Read, self)
self.signalnotifier.activated.connect(self.sighandler)
signal.signal(signal.SIGHUP, self.signal)
signal.signal(signal.SIGINT, self.signal)
signal.signal(signal.SIGTERM, self.signal)
# Setup logging
log.debug("Starting Picard from %r", os.path.abspath(__file__))
log.debug("Platform: %s %s %s", platform.platform(),
platform.python_implementation(), platform.python_version())
log.debug("Versions: %s", versions.as_string())
log.debug("Configuration file path: %r", config.fileName())
log.debug("User directory: %r", os.path.abspath(USER_DIR))
log.debug("System long path support: %r", system_supports_long_paths())
# log interesting environment variables
log.debug("Qt Env.: %s", " ".join("%s=%r" % (k, v) for k, v in os.environ.items() if k.startswith('QT_')))
check_io_encoding()
# Must be before config upgrade because upgrade dialogs need to be
# translated
setup_gettext(localedir, config.setting['ui_language'], log.debug)
upgrade_config(config)
self.webservice = WebService()
self.mb_api = MBAPIHelper(self.webservice)
load_user_collections()
# Initialize fingerprinting
acoustid_api = AcoustIdAPIHelper(self.webservice)
self._acoustid = acoustid.AcoustIDClient(acoustid_api)
self._acoustid.init()
self.acoustidmanager = AcoustIDManager(acoustid_api)
self.enable_menu_icons(config.setting['show_menu_icons'])
# Load plugins
self.pluginmanager = PluginManager()
if not self._no_plugins:
for plugin_dir in plugin_dirs():
self.pluginmanager.load_plugins_from_directory(plugin_dir)
self.browser_integration = BrowserIntegration()
self.browser_integration.listen_port_changed.connect(self.on_listen_port_changed)
self._pending_files_count = 0
self.files = {}
self.clusters = ClusterList()
self.albums = {}
self.release_groups = {}
self.mbid_redirects = {}
self.unclustered_files = UnclusteredFiles()
self.nats = None
self.window = MainWindow(disable_player=picard_args.no_player)
# On macOS temporary files get deleted after 3 days not being accessed.
# Touch these files regularly to keep them alive if Picard
# is left running for a long time.
if IS_MACOS:
periodictouch.enable_timer()
# Load release version information
if self.autoupdate_enabled:
self.updatecheckmanager = UpdateCheckManager(self)
@property
def is_wayland(self):
return self.platformName() == 'wayland'
def pipe_server(self):
IGNORED = {pipe.Pipe.MESSAGE_TO_IGNORE, pipe.Pipe.NO_RESPONSE_MESSAGE}
while self.pipe_handler.pipe_running:
messages = [x for x in self.pipe_handler.read_from_pipe() if x not in IGNORED]
if messages:
log.debug("pipe messages: %r", messages)
self.load_to_picard(messages)
def _pipe_server_finished(self, result=None, error=None):
if error:
log.error("pipe server failed: %r", error)
else:
log.debug("pipe server stopped")
def start_process_commands(self):
if not self._command_thread_running:
self._command_thread_running = True
thread.run_task(self.run_commands, self._run_commands_finished)
def run_commands(self):
while not self.stopping:
if not RemoteCommands.command_queue.empty() and not RemoteCommands.get_running():
(cmd, arg) = RemoteCommands.command_queue.get()
if cmd in self.commands:
arg = arg.strip()
log.info("Executing command: %s %r", cmd, arg)
if cmd == 'QUIT':
thread.to_main(self.commands[cmd], arg)
else:
RemoteCommands.set_running(True)
original_priority_thread_count = self.priority_thread_pool.activeThreadCount()
original_main_thread_count = self.thread_pool.activeThreadCount()
original_save_thread_count = self.save_thread_pool.activeThreadCount()
thread.to_main_with_blocking(self.commands[cmd], arg)
# Continue to show the task as running until all of the following
# conditions are met:
#
# - main thread pool active tasks count is less than or equal to the
# count at the start of task execution
#
# - priority thread pool active tasks count is less than or equal to
# the count at the start of task execution
#
# - save thread pool active tasks count is less than or equal to the
# count at the start of task execution
#
# - there are no pending webservice requests
#
# - there are no acoustid fingerprinting tasks running
while True:
time.sleep(0.1)
if self.priority_thread_pool.activeThreadCount() > original_priority_thread_count or \
self.thread_pool.activeThreadCount() > original_main_thread_count or \
self.save_thread_pool.activeThreadCount() > original_save_thread_count or \
self.webservice.num_pending_web_requests or \
self._acoustid._running:
continue
break
log.info("Completed command: %s %r", cmd, arg)
RemoteCommands.set_running(False)
else:
log.error("Unknown command: %r", cmd)
RemoteCommands.command_queue.task_done()
elif RemoteCommands.command_queue.empty():
# All commands finished, stop processing
self._command_thread_running = False
break
time.sleep(.01)
def _run_commands_finished(self, result=None, error=None):
if error:
log.error("command executor failed: %r", error)
else:
log.debug("command executor stopped")
def load_to_picard(self, items):
commands = []
for item in items:
parts = str(item).split(maxsplit=1)
commands.append((parts[0], parts[1:] or ['']))
RemoteCommands.parse_commands_to_queue(commands)
self.start_process_commands()
def iter_album_files(self):
for album in self.albums.values():
yield from album.iterfiles()
def iter_all_files(self):
yield from self.unclustered_files.files
yield from self.iter_album_files()
yield from self.clusters.iterfiles()
def _init_remote_commands(self):
self.commands = {name: getattr(self, remcmd.method_name) for name, remcmd in REMOTE_COMMANDS.items()}
def handle_command_clear_logs(self, argstring):
self.window.log_dialog.clear()
self.window.history_dialog.clear()
def handle_command_cluster(self, argstring):
self.cluster(self.unclustered_files.files)
def handle_command_fingerprint(self, argstring):
for album_name in self.albums:
self.analyze(self.albums[album_name].iterfiles())
def handle_command_from_file(self, argstring):
RemoteCommands.get_commands_from_file(argstring)
def handle_command_load(self, argstring):
parsed_items = ParseItemsToLoad([argstring])
log.debug(str(parsed_items))
if parsed_items.files:
self.add_paths(parsed_items.files)
if parsed_items.urls or parsed_items.mbids:
file_lookup = self.get_file_lookup()
for item in parsed_items.mbids | parsed_items.urls:
file_lookup.mbid_lookup(item)
def handle_command_lookup(self, argstring):
if argstring:
argstring = argstring.upper()
if not argstring or argstring == 'ALL':
self.autotag(self.clusters)
self.autotag(self.unclustered_files.files)
elif argstring == 'CLUSTERED':
self.autotag(self.clusters)
elif argstring == 'UNCLUSTERED':
self.autotag(self.unclustered_files.files)
else:
log.error("Invalid LOOKUP command argument: '%s'", argstring)
def handle_command_lookup_cd(self, argstring):
if not _discid:
log.error(DISCID_NOT_LOADED_MESSAGE)
return
disc = Disc()
devices = get_cdrom_drives()
if not argstring:
if devices:
device = devices[0]
else:
device = None
elif argstring in devices:
device = argstring
else:
thread.run_task(
partial(self._parse_disc_ripping_log, disc, argstring),
partial(self._lookup_disc, disc),
traceback=self._debug)
return
thread.run_task(
partial(disc.read, encode_filename(device)),
partial(self._lookup_disc, disc),
traceback=self._debug)
def handle_command_pause(self, argstring):
arg = argstring.strip()
if arg:
try:
delay = float(arg)
if delay < 0:
raise ValueError
log.debug("Pausing command execution by %d seconds.", delay)
thread.run_task(partial(time.sleep, delay))
except ValueError:
log.error(f"Invalid command pause time specified: {repr(argstring)}")
else:
log.error("No command pause time specified.")
def handle_command_quit(self, argstring):
if argstring.upper() == 'FORCE' or self.window.show_quit_confirmation():
self.quit()
else:
log.info("QUIT command cancelled by the user.")
RemoteCommands.set_quit(False) # Allow queueing more commands.
return
def handle_command_remove(self, argstring):
for file in self.iter_all_files():
if file.filename == argstring:
self.remove([file])
return
def handle_command_remove_all(self, argstring):
for file in self.iter_all_files():
self.remove([file])
def handle_command_remove_empty(self, argstring):
_albums = [a for a in self.albums.values()]
for album in _albums:
if not any(album.iterfiles()):
self.remove_album(album)
for cluster in self.clusters:
if not any(cluster.iterfiles()):
self.remove_cluster(cluster)
def handle_command_remove_saved(self, argstring):
for track in self.iter_album_files():
if track.state == File.NORMAL:
self.remove([track])
def handle_command_remove_unclustered(self, argstring):
self.remove(self.unclustered_files.files)
def handle_command_save_matched(self, argstring):
for album in self.albums.values():
for track in album.iter_correctly_matched_tracks():
track.files[0].save()
def handle_command_save_modified(self, argstring):
for track in self.iter_album_files():
if track.state == File.CHANGED:
track.save()
def handle_command_scan(self, argstring):
self.analyze(self.unclustered_files.files)
def handle_command_show(self, argstring):
self.bring_tagger_front()
def handle_command_submit_fingerprints(self, argstring):
self.acoustidmanager.submit()
def handle_command_write_logs(self, argstring):
try:
with open(argstring, 'w', encoding='utf-8') as f:
for x in self.window.log_dialog.log_tail.contents():
f.write(f"{x.message}\n")
except Exception as e:
log.error("Error writing logs to a file: %s", e)
def enable_menu_icons(self, enabled):
self.setAttribute(QtCore.Qt.ApplicationAttribute.AA_DontShowIconsInMenus, not enabled)
def register_cleanup(self, func):
self.exit_cleanup.append(func)
def run_cleanup(self):
for f in self.exit_cleanup:
f()
def set_log_level(self, level):
self._debug = level == logging.DEBUG
log.set_level(level)
def on_listen_port_changed(self, port):
self.webservice.oauth_manager.redirect_uri = self._mb_login_redirect_uri()
self.listen_port_changed.emit(port)
def _mb_login_dialog(self, parent):
if not parent:
parent = self.window
dialog = QtWidgets.QInputDialog(parent)
dialog.setWindowModality(QtCore.Qt.WindowModality.WindowModal)
dialog.setWindowTitle(_("MusicBrainz Account"))
dialog.setLabelText(_("Authorization code:"))
status = dialog.exec()
if status == QtWidgets.QDialog.DialogCode.Accepted:
return dialog.textValue()
else:
return None
def _mb_login_redirect_uri(self):
if self.browser_integration and self.browser_integration.is_running:
return f'http://localhost:{self.browser_integration.port}/auth'
else:
# If browser integration is disabled or not running on the standard
# port use out-of-band flow (with manual copying of the token).
return None
def mb_login(self, callback, parent=None):
oauth_manager = self.webservice.oauth_manager
scopes = 'profile tag rating collection submit_isrc submit_barcode'
authorization_url = oauth_manager.get_authorization_url(
scopes, partial(self.on_mb_authorization_finished, callback))
webbrowser2.open(authorization_url)
if oauth_manager.is_oob:
authorization_code = self._mb_login_dialog(parent)
if authorization_code is not None:
self.webservice.oauth_manager.exchange_authorization_code(
authorization_code, scopes,
partial(self.on_mb_authorization_finished, callback))
else:
callback(False, None)
def on_mb_authorization_finished(self, callback, successful=False, error_msg=None):
if successful:
self.webservice.oauth_manager.fetch_username(
partial(self.on_mb_login_finished, callback))
else:
callback(False, error_msg)
def on_mb_login_finished(self, callback, successful, error_msg):
if successful:
load_user_collections()
callback(successful, error_msg)
def mb_logout(self, callback):
self.webservice.oauth_manager.revoke_tokens(
partial(self.on_mb_logout_finished, callback)
)
def on_mb_logout_finished(self, callback, successful, error_msg):
if successful:
load_user_collections()
callback(successful, error_msg)
def move_files_to_album(self, files, albumid=None, album=None):
"""Move `files` to tracks on album `albumid`."""
if album is None:
album = self.load_album(albumid)
album.match_files(files)
def move_file_to_album(self, file, albumid):
"""Move `file` to a track on album `albumid`."""
self.move_files_to_album([file], albumid)
def move_file_to_track(self, file, albumid, recordingid):
"""Move `file` to recording `recordingid` on album `albumid`."""
album = self.load_album(albumid)
file.match_recordingid = recordingid
album.match_files([file])
def create_nats(self):
if self.nats is None:
self.nats = NatAlbum()
self.albums['NATS'] = self.nats
self.album_added.emit(self.nats)
self.nats.ui_item.setExpanded(True)
return self.nats
def move_file_to_nat(self, file, recordingid, node=None):
self.create_nats()
file.move(self.nats.unmatched_files)
nat = self.load_nat(recordingid, node=node)
nat.run_when_loaded(partial(file.move, nat))
if nat.loaded:
self.nats.update()
def quit(self):
self.exit()
super().quit()
def exit(self):
if self.stopping:
return
self.stopping = True
log.debug("Picard stopping")
if self._acoustid:
self._acoustid.done()
if self.pipe_handler:
self.pipe_handler.stop()
if self.webservice:
self.webservice.stop()
if self.thread_pool:
self.thread_pool.waitForDone()
if self.save_thread_pool:
self.save_thread_pool.waitForDone()
if self.priority_thread_pool:
self.priority_thread_pool.waitForDone()
if self.browser_integration:
self.browser_integration.stop()
self.run_cleanup()
QtCore.QCoreApplication.processEvents()
def _run_init(self):
if self._to_load:
self.load_to_picard(self._to_load)
del self._to_load
def run(self):
self.update_browser_integration()
self.window.show()
QtCore.QTimer.singleShot(0, self._run_init)
res = self.exec()
self.exit()
return res
def update_browser_integration(self):
config = get_config()
if config.setting['browser_integration']:
self.browser_integration.start()
else:
self.browser_integration.stop()
def event(self, event):
if isinstance(event, thread.ProxyToMainEvent):
event.run()
elif event.type() == QtCore.QEvent.Type.FileOpen:
file = event.file()
self.add_paths([file])
if IS_HAIKU:
self.bring_tagger_front()
# We should just return True here, except that seems to
# cause the event's sender to get a -9874 error, so
# apparently there's some magic inside QFileOpenEvent...
return 1
return super().event(event)
def _file_loaded(self, file, target=None, remove_file=False, unmatched_files=None):
config = get_config()
self._pending_files_count -= 1
if self._pending_files_count == 0:
self.window.set_sorting(True)
if remove_file:
file.remove()
return
if file is None:
return
if file.has_error():
self.unclustered_files.add_file(file)
return
file_moved = False
if not config.setting['ignore_file_mbids']:
recordingid = file.metadata.getall('musicbrainz_recordingid')
recordingid = recordingid[0] if recordingid else ''
is_valid_recordingid = mbid_validate(recordingid)
albumid = file.metadata.getall('musicbrainz_albumid')
albumid = albumid[0] if albumid else ''
is_valid_albumid = mbid_validate(albumid)
if is_valid_albumid and is_valid_recordingid:
log.debug("%r has release (%s) and recording (%s) MBIDs, moving to track…",
file, albumid, recordingid)
self.move_file_to_track(file, albumid, recordingid)
file_moved = True
elif is_valid_albumid:
log.debug("%r has only release MBID (%s), moving to album…",
file, albumid)
self.move_file_to_album(file, albumid)
file_moved = True
elif is_valid_recordingid:
log.debug("%r has only recording MBID (%s), moving to non-album track…",
file, recordingid)
self.move_file_to_nat(file, recordingid)
file_moved = True
if not file_moved:
target = self.move_file(file, target)
if target and target != self.unclustered_files:
file_moved = True
if not file_moved and unmatched_files is not None:
unmatched_files.append(file)
# fallback on analyze if nothing else worked
if not file_moved and config.setting['analyze_new_files'] and file.can_analyze:
log.debug("Trying to analyze %r …", file)
self.analyze([file])
# Auto cluster newly added files if they are not explicitly moved elsewhere
if self._pending_files_count == 0 and unmatched_files and config.setting['cluster_new_files']:
self.cluster(unmatched_files)
def move_file(self, file, target):
"""Moves a file to target, if possible
Returns the actual target the files has been moved to or None
"""
if isinstance(target, Album):
self.move_files_to_album([file], album=target)
else:
if isinstance(target, File) and target.parent_item:
target = target.parent_item
if not file.move(target):
# Ensure a file always has a parent so it shows up in UI
if not file.parent_item:
target = self.unclustered_files
file.move(target)
# Unsupported target, do not move the file
else:
target = None
return target
def move_files(self, files, target, move_to_multi_tracks=True):
if target is None:
log.debug("Aborting move since target is invalid")
return
with self.window.suspend_sorting, self.window.metadata_box.ignore_updates:
if isinstance(target, Cluster):
for file in process_events_iter(files):
file.move(target)
elif isinstance(target, Track):
album = target.album
for file in process_events_iter(files):
file.move(target)
if move_to_multi_tracks: # Assign next file to following track
target = album.get_next_track(target) or album.unmatched_files
elif isinstance(target, File):
for file in process_events_iter(files):
file.move(target.parent_item)
elif isinstance(target, Album):
self.move_files_to_album(files, album=target)
elif isinstance(target, ClusterList):
self.cluster(files)
def add_files(self, filenames, target=None):
"""Add files to the tagger."""
ignoreregex = None
config = get_config()
pattern = config.setting['ignore_regex']
if pattern:
try:
ignoreregex = re.compile(pattern)
except re.error as e:
log.error("Failed evaluating regular expression for ignore_regex: %s", e)
ignore_hidden = config.setting["ignore_hidden_files"]
new_files = []
for filename in filenames:
filename = normpath(filename)
if ignore_hidden and is_hidden(filename):
log.debug("File ignored (hidden): %r", filename)
continue
# Ignore .smbdelete* files which Applie iOS SMB creates by renaming a file when it cannot delete it
if os.path.basename(filename).startswith(".smbdelete"):
log.debug("File ignored (.smbdelete): %r", filename)
continue
if ignoreregex is not None and ignoreregex.search(filename):
log.info("File ignored (matching %r): %r", pattern, filename)
continue
if filename not in self.files:
file = open_file(filename)
if file:
self.files[filename] = file
new_files.append(file)
QtCore.QCoreApplication.processEvents()
if new_files:
log.debug("Adding files %r", new_files)
new_files.sort(key=lambda x: x.filename)
self.window.set_sorting(False)
self._pending_files_count += len(new_files)
unmatched_files = []
for i, file in enumerate(new_files):
file.load(partial(self._file_loaded, target=target, unmatched_files=unmatched_files))
# Calling processEvents helps processing the _file_loaded
# callbacks in between, which keeps the UI more responsive.
# Avoid calling it to often to not slow down the loading to much
# Using an uneven number to have the unclustered file counter
# not look stuck in certain digits.
if i % 17 == 0:
QtCore.QCoreApplication.processEvents()
@staticmethod
def _scan_paths_recursive(paths, recursive, ignore_hidden):
local_paths = list(paths)
while local_paths:
current_path = normpath(local_paths.pop(0))
try:
if os.path.isdir(current_path):
for entry in os.scandir(current_path):
if ignore_hidden and is_hidden(entry.path):
continue
if recursive and entry.is_dir():
local_paths.append(entry.path)
else:
yield entry.path
else:
yield current_path
except OSError as err:
log.warning(err)
def add_paths(self, paths, target=None):
config = get_config()
files = self._scan_paths_recursive(paths,
config.setting['recursively_add_files'],
config.setting["ignore_hidden_files"])
self.add_files(files, target=target)
def get_file_lookup(self):
"""Return a FileLookup object."""
config = get_config()
return FileLookup(self, config.setting['server_host'],
config.setting['server_port'],
self.browser_integration.port)
def search(self, text, search_type, adv=False, mbid_matched_callback=None, force_browser=False):
"""Search on the MusicBrainz website."""
search_types = {
'track': {
'entity': 'recording',
'dialog': TrackSearchDialog
},
'album': {
'entity': 'release',
'dialog': AlbumSearchDialog
},
'artist': {
'entity': 'artist',
'dialog': ArtistSearchDialog
},
}
if search_type not in search_types:
return
search = search_types[search_type]
lookup = self.get_file_lookup()
config = get_config()
if config.setting["builtin_search"] and not force_browser:
if not lookup.mbid_lookup(text, search['entity'],
mbid_matched_callback=mbid_matched_callback):
dialog = search['dialog'](self.window)
dialog.search(text)
dialog.exec()
else:
lookup.search_entity(search['entity'], text, adv,
mbid_matched_callback=mbid_matched_callback,
force_browser=force_browser)
def collection_lookup(self):
"""Lookup the users collections on the MusicBrainz website."""
lookup = self.get_file_lookup()
config = get_config()
lookup.collection_lookup(config.persist['oauth_username'])
def browser_lookup(self, item):
"""Lookup the object's metadata on the MusicBrainz website."""
lookup = self.get_file_lookup()
metadata = item.metadata
# Only lookup via MB IDs if matched to a MetadataItem; otherwise ignore and use metadata details
if isinstance(item, MetadataItem):
itemid = item.id
if isinstance(item, Track):
lookup.recording_lookup(itemid)
elif isinstance(item, Album):
lookup.album_lookup(itemid)
else:
lookup.tag_lookup(
metadata['albumartist'] if item.is_album_like else metadata['artist'],
metadata['album'],
metadata['title'],
metadata['tracknumber'],
'' if item.is_album_like else str(metadata.length),
item.filename if isinstance(item, File) else '')
def get_files_from_objects(self, objects, save=False):
"""Return list of unique files from list of albums, clusters, tracks or files.
Note: Consider using picard.util.iter_files_from_objects instead, which returns an iterator.
"""
return list(iter_files_from_objects(objects, save=save))
def save(self, objects):
"""Save the specified objects."""
for file in iter_files_from_objects(objects, save=True):
file.save()
def load_mbid(self, type, mbid):
self.bring_tagger_front()
if type == 'album':
self.load_album(mbid)
elif type == 'nat':
self.load_nat(mbid)
else:
log.warning("Unknown type to load: %s", type)
def load_album(self, album_id, discid=None):
album_id = self.mbid_redirects.get(album_id, album_id)
album = self.albums.get(album_id)
if album:
log.debug("Album %s already loaded.", album_id)
album.add_discid(discid)
return album
album = Album(album_id, discid=discid)
self.albums[album_id] = album
self.album_added.emit(album)
album.load()
return album
def load_nat(self, nat_id, node=None):
self.create_nats()
nat = self.get_nat_by_id(nat_id)
if nat:
log.debug("NAT %s already loaded.", nat_id)
return nat
nat = NonAlbumTrack(nat_id)
self.nats.tracks.append(nat)
self.nats.update(True)
if node:
nat._parse_recording(node)
else:
nat.load()
return nat
def get_nat_by_id(self, nat_id):
if self.nats is not None:
for nat in self.nats.tracks:
if nat.id == nat_id:
return nat
def get_release_group_by_id(self, rg_id):
return self.release_groups.setdefault(rg_id, ReleaseGroup(rg_id))
def remove_files(self, files, from_parent=True):
"""Remove files from the tagger."""
for file in files:
if file.filename in self.files:
file.clear_lookup_task()
self._acoustid.stop_analyze(file)
del self.files[file.filename]
file.remove(from_parent)
self.tagger_stats_changed.emit()
def remove_album(self, album):
"""Remove the specified album."""
log.debug("Removing %r", album)
if album.id not in self.albums:
return
album.stop_loading()
self.remove_files(list(album.iterfiles()))
del self.albums[album.id]
if album.release_group:
album.release_group.remove_album(album.id)
if album == self.nats:
self.nats = None
self.album_removed.emit(album)
run_album_post_removal_processors(album)
self.tagger_stats_changed.emit()
def remove_nat(self, track):
"""Remove the specified non-album track."""
log.debug("Removing %r", track)
self.remove_files(list(track.iterfiles()))
if not self.nats:
return
self.nats.tracks.remove(track)
if not self.nats.tracks:
self.remove_album(self.nats)
else:
self.nats.update(True)
def remove_cluster(self, cluster):
"""Remove the specified cluster."""
if not cluster.special:
log.debug("Removing %r", cluster)
files = list(cluster.files)
cluster.files = []
cluster.clear_lookup_task()
self.remove_files(files, from_parent=False)
self.clusters.remove(cluster)
self.cluster_removed.emit(cluster)
def remove(self, objects):
"""Remove the specified objects."""
files = []
with self.window.ignore_selection_changes:
for obj in objects:
if isinstance(obj, File):
files.append(obj)
elif isinstance(obj, NonAlbumTrack):
self.remove_nat(obj)
elif isinstance(obj, Track):
files.extend(obj.files)
elif isinstance(obj, Album):
self.window.set_statusbar_message(
N_("Removing album %(id)s: %(artist)s - %(album)s"),
{
'id': obj.id,
'artist': obj.metadata['albumartist'],
'album': obj.metadata['album']
}
)
self.remove_album(obj)
elif isinstance(obj, UnclusteredFiles):
files.extend(list(obj.files))
elif isinstance(obj, Cluster):
self.remove_cluster(obj)
if files:
self.remove_files(files)
def _lookup_disc(self, disc, result=None, error=None):
self.restore_cursor()
if error is not None:
QtWidgets.QMessageBox.critical(self.window, _("CD Lookup Error"),
_("Error while reading CD:\n\n%s") % error)
else:
disc.lookup()
def lookup_cd(self, action):
"""Reads CD from the selected drive and tries to lookup the DiscID on MusicBrainz."""
config = get_config()
if isinstance(action, QtGui.QAction):
data = action.data()
if data == 'logfile:eac':
return self.lookup_discid_from_logfile()
else:
device = data
elif config.setting['cd_lookup_device'] != '':
device = config.setting['cd_lookup_device'].split(',', 1)[0]
else:
# rely on python-discid auto detection
device = None
disc = Disc()
self.set_wait_cursor()
thread.run_task(
partial(disc.read, encode_filename(device)),
partial(self._lookup_disc, disc),
traceback=self._debug)
def lookup_discid_from_logfile(self):
file_chooser = FileDialog(parent=self.window)
file_chooser.setNameFilters([
_("All supported log files") + " (*.log *.txt)",
_("EAC / XLD / Whipper / fre:ac log files") + " (*.log)",
_("dBpoweramp log files") + " (*.txt)",
_("All files") + " (*)",
])
if file_chooser.exec():
files = file_chooser.selectedFiles()
disc = Disc()
self.set_wait_cursor()
thread.run_task(
partial(self._parse_disc_ripping_log, disc, files[0]),
partial(self._lookup_disc, disc),
traceback=self._debug)
def _parse_disc_ripping_log(self, disc, path):
log_readers = (
eaclog.toc_from_file,
whipperlog.toc_from_file,
dbpoweramplog.toc_from_file,
)
for reader in log_readers:
module_name = reader.__module__
try:
log.debug('Trying to parse "%s" with %s…', path, module_name)
toc = reader(path)
break
except Exception:
log.debug('Failed parsing ripping log "%s" with %s', path, module_name, exc_info=True)
else:
msg = N_('Failed parsing ripping log "%s"')
log.warning(msg, path)
raise Exception(_(msg) % path)
disc.put(toc)
@property
def use_acoustid(self):
config = get_config()
return config.setting['fingerprinting_system'] == 'acoustid'
def analyze(self, objs):
"""Analyze the file(s)."""
if not self.use_acoustid:
return
for file in iter_files_from_objects(objs):
if file.can_analyze:
file.set_pending()
self._acoustid.analyze(file, partial(file._lookup_finished, File.LOOKUP_ACOUSTID))
def generate_fingerprints(self, objs):
"""Generate the fingerprints without matching the files."""
if not self.use_acoustid:
return
def finished(file, result):
file.clear_pending()
for file in iter_files_from_objects(objs):
file.set_pending()
self._acoustid.fingerprint(file, partial(finished, file))
# =======================================================================
# Metadata-based lookups
# =======================================================================
def autotag(self, objects):
for obj in objects:
if obj.can_autotag:
obj.lookup_metadata()
# =======================================================================
# Clusters
# =======================================================================
def cluster(self, objs, callback=None):
"""Group files with similar metadata to 'clusters'."""
files = tuple(iter_files_from_objects(objs))
if log.get_effective_level() == logging.DEBUG:
limit = 5
count = len(files)
remain = max(0, count - limit)
log.debug(
"Clustering %d files: %r%s", count, files[:limit],
f" and {remain} more files..." if remain else ""
)
thread.run_task(
partial(self._do_clustering, files),
partial(self._clustering_finished, callback))
def _do_clustering(self, files):
# The clustering algorithm should completely run in the thread,
# hence do not return the iterator.
return tuple(Cluster.cluster(files))
def _clustering_finished(self, callback, result=None, error=None):
if error:
log.error("Error while clustering: %r", error)
return
with self.window.suspend_sorting:
for file_cluster in process_events_iter(result):
files = set(file_cluster.files)
if len(files) > 1:
cluster = self.load_cluster(file_cluster.title, file_cluster.artist)
else:
cluster = self.unclustered_files
cluster.add_files(files)
if callback:
callback()
def load_cluster(self, name, artist):
for cluster in self.clusters:
cm = cluster.metadata
if name == cm['album'] and artist == cm['albumartist']:
return cluster
cluster = Cluster(name, artist)
self.clusters.append(cluster)
self.cluster_added.emit(cluster)
return cluster
# =======================================================================
# Utils
# =======================================================================
def set_wait_cursor(self):
"""Sets the waiting cursor."""
super().setOverrideCursor(
QtGui.QCursor(QtCore.Qt.CursorShape.WaitCursor))
def restore_cursor(self):
"""Restores the cursor set by ``set_wait_cursor``."""
super().restoreOverrideCursor()
def refresh(self, objs):
for obj in objs:
if obj.can_refresh:
obj.load(priority=True, refresh=True)
def bring_tagger_front(self):
self.window.setWindowState(self.window.windowState() & ~QtCore.Qt.WindowState.WindowMinimized | QtCore.Qt.WindowState.WindowActive)
self.window.raise_()
self.window.activateWindow()
@classmethod
def instance(cls):
return cls.__instance
def signal(self, signum, frame):
log.debug("signal %i received", signum)
# Send a notification about a received signal from the signal handler
# to Qt.
self.signalfd[0].sendall(b"a")
def sighandler(self):
self.signalnotifier.setEnabled(False)
self.quit()
self.signalnotifier.setEnabled(True)
class PicardArgumentParser(argparse.ArgumentParser):
def exit(self, status=0, message=None):
if is_windowed_app():
if message:
show_standalone_messagebox(message)
super().exit(status)
else:
super().exit(status, message)
def error(self, message):
if is_windowed_app():
if message:
show_standalone_messagebox(message)
super().exit(2)
else:
super().error(message)
def print_help(self, file=None):
if is_windowed_app() and file is None:
from io import StringIO
file = StringIO()
super().print_help(file=file)
file.seek(0)
show_standalone_messagebox(file.read())
else:
return super().print_help(file)
def is_windowed_app():
# Return True if this is a Windows windowed application without attached console
return IS_WIN and not sys.stdout
def show_standalone_messagebox(message, informative_text=None):
app = QtCore.QCoreApplication.instance()
if not app:
app = QtWidgets.QApplication(sys.argv)
msgbox = QtWidgets.QMessageBox()
msgbox.setIcon(QtWidgets.QMessageBox.Icon.Information)
msgbox.setWindowTitle(f"{PICARD_ORG_NAME} {PICARD_APP_NAME}")
msgbox.setTextFormat(QtCore.Qt.TextFormat.PlainText)
font = msgbox.font()
font.setFamily(FONT_FAMILY_MONOSPACE)
msgbox.setFont(font)
msgbox.setText(message)
if informative_text:
msgbox.setInformativeText(informative_text)
msgbox.setStandardButtons(QtWidgets.QMessageBox.StandardButton.Ok)
msgbox.setDefaultButton(QtWidgets.QMessageBox.StandardButton.Ok)
msgbox.exec()
app.quit()
def print_message_and_exit(message, informative_text=None, status=0):
if is_windowed_app():
show_standalone_messagebox(message, informative_text)
else:
print(message)
if informative_text:
print(informative_text)
sys.exit(status)
def print_help_for_commands():
if is_windowed_app():
maxwidth = 300
else:
maxwidth = 80
informative_text = []
message = """Usage: picard -e [command] [arguments ...]
or picard -e [command 1] [arguments ...] -e [command 2] [arguments ...]
List of the commands available to execute in Picard from the command-line:
"""
for name in sorted(REMOTE_COMMANDS):
remcmd = REMOTE_COMMANDS[name]
s = " - %-34s %s" % (name + " " + remcmd.help_args, remcmd.help_text)
informative_text.append(fill(s, width=maxwidth, subsequent_indent=' '*39))
informative_text.append('')
def fmt(s):
informative_text.append(fill(s, width=maxwidth))
fmt("Commands are case insensitive.")
fmt("Picard will try to load all the positional arguments before processing commands.")
fmt("If there is no instance to pass the arguments to, Picard will start and process the commands after the "
"positional arguments are loaded, as mentioned above. Otherwise they will be handled by the running "
"Picard instance")
fmt("Arguments are optional, but some commands may require one or more arguments to actually do something.")
print_message_and_exit(message, "\n".join(informative_text))
def process_picard_args():
parser = PicardArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""If one of the filenames begins with a hyphen, use -- to separate the options from the filenames.
If a new instance will not be spawned files/directories will be passed to the existing instance"""
)
# Qt default arguments. Parse them so Picard does not interpret the
# arguments as file names to load.
parser.add_argument('-style', nargs=1, help=argparse.SUPPRESS)
parser.add_argument('-stylesheet', nargs=1, help=argparse.SUPPRESS)
# Same for default X arguments
parser.add_argument('-display', nargs=1, help=argparse.SUPPRESS)
# Picard specific arguments
parser.add_argument('-a', '--audit', action='store',
default=None,
help="audit events passed as a comma-separated list, prefixes supported, "
"use all to match any (see https://docs.python.org/3/library/audit_events.html#audit-events)")
parser.add_argument('-c', '--config-file', action='store',
default=None,
help="location of the configuration file")
parser.add_argument('-d', '--debug', action='store_true',
help="enable debug-level logging")
parser.add_argument('-e', '--exec', nargs='+', action='append',
help="send command (arguments can be entered after space) to a running instance "
"(use `-e help` for a list of the available commands)",
metavar='COMMAND')
parser.add_argument('-M', '--no-player', action='store_true',
help="disable built-in media player")
parser.add_argument('-N', '--no-restore', action='store_true',
help="do not restore positions and/or sizes")
parser.add_argument('-P', '--no-plugins', action='store_true',
help="do not load any plugins")
parser.add_argument('--no-crash-dialog', action='store_true',
help="disable the crash dialog")
parser.add_argument('--debug-opts', action='store',
default=None,
help="comma-separated list of debug options to enable: %s" % DebugOpt.opt_names())
parser.add_argument('-s', '--stand-alone-instance', action='store_true',
help="force Picard to create a new, stand-alone instance")
parser.add_argument('-v', '--version', action='store_true',
help="display version information and exit")
parser.add_argument('-V', '--long-version', action='store_true',
help="display long version information and exit")
parser.add_argument('FILE_OR_URL', nargs='*',
help="the file(s), URL(s) and MBID(s) to load")
args = parser.parse_args()
args.remote_commands_help = False
args.processable = []
for path in args.FILE_OR_URL:
if not urlparse(path).netloc:
try:
path = os.path.abspath(path)
except FileNotFoundError:
# os.path.abspath raises if path is relative and cwd doesn't
# exist anymore. Just pass the path as it is and leave
# the error handling to Picard's file loading.
pass
args.processable.append(f"LOAD {path}")
if args.exec:
for e in args.exec:
args.remote_commands_help = args.remote_commands_help or 'HELP' in {x.upper().strip() for x in e}
remote_command_args = e[1:] or ['']
for arg in remote_command_args:
args.processable.append(f"{e[0]} {arg}")
return args
def main(localedir=None, autoupdate=True):
# Some libs (ie. Phonon) require those to be set
QtWidgets.QApplication.setApplicationName(PICARD_APP_NAME)
QtWidgets.QApplication.setOrganizationName(PICARD_ORG_NAME)
QtWidgets.QApplication.setDesktopFileName(PICARD_APP_NAME)
# HighDpiScaleFactorRoundingPolicy is available since Qt 5.14. This is
# required to support fractional scaling on Windows properly.
# It causes issues without scaling on Linux, see https://tickets.metabrainz.org/browse/PICARD-1948
if IS_WIN:
QtGui.QGuiApplication.setHighDpiScaleFactorRoundingPolicy(
QtCore.Qt.HighDpiScaleFactorRoundingPolicy.PassThrough)
# Enable mnemonics on all platforms, even macOS
QtGui.qt_set_sequence_auto_mnemonic(True)
signal.signal(signal.SIGINT, signal.SIG_DFL)
picard_args = process_picard_args()
if picard_args.long_version:
_ = QtCore.QCoreApplication(sys.argv)
print_message_and_exit(versions.as_string())
if picard_args.version:
print_message_and_exit(f"{PICARD_ORG_NAME} {PICARD_APP_NAME} {PICARD_FANCY_VERSION_STR}")
if picard_args.remote_commands_help:
print_help_for_commands()
# any of the flags that change Picard's workflow significantly should trigger creation of a new instance
if picard_args.stand_alone_instance:
identifier = uuid4().hex
else:
if picard_args.config_file:
identifier = blake2b(picard_args.config_file.encode('utf-8'), digest_size=16).hexdigest()
else:
identifier = 'main'
if picard_args.no_plugins:
identifier += '_NP'
if picard_args.processable:
log.info("Sending messages to main instance: %r", picard_args.processable)
try:
pipe_handler = pipe.Pipe(app_name=PICARD_APP_NAME, app_version=PICARD_FANCY_VERSION_STR,
identifier=identifier, args=picard_args.processable)
should_start = pipe_handler.is_pipe_owner
except pipe.PipeErrorNoPermission as err:
log.error(err)
pipe_handler = None
should_start = True
# pipe has sent its args to existing one, doesn't need to start
if not should_start:
log.debug("No need for spawning a new instance, exiting...")
sys.exit(0)
try:
from PyQt6.QtDBus import QDBusConnection
dbus = QDBusConnection.sessionBus()
dbus.registerService(PICARD_APP_ID)
except ImportError:
pass
tagger = Tagger(picard_args, localedir, autoupdate, pipe_handler=pipe_handler)
# Initialize Qt default translations
translator = QtCore.QTranslator()
locale = QtCore.QLocale()
translation_path = QtCore.QLibraryInfo.path(QtCore.QLibraryInfo.LibraryPath.TranslationsPath)
log.debug("Looking for Qt locale %s in %s", locale.name(), translation_path)
if translator.load(locale, 'qtbase_', directory=translation_path):
tagger.installTranslator(translator)
else:
log.debug("Qt locale %s not available", locale.name())
tagger.startTimer(1000)
exit_code = tagger.run()
if tagger.pipe_handler.unexpected_removal:
os._exit(exit_code)
sys.exit(exit_code)
| 61,174
|
Python
|
.py
| 1,393
| 33.323762
| 139
| 0.607064
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,942
|
version.py
|
metabrainz_picard/picard/version.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2019-2021 Philipp Wolfer
# Copyright (C) 2020-2021 Laurent Monin
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from collections import namedtuple
import re
class VersionError(Exception):
pass
class Version(namedtuple('VersionBase', 'major minor patch identifier revision')):
_version_re = re.compile(r"^(\d+)(?:[._](\d+)(?:[._](\d+)[._]?(?:(dev|a|alpha|b|beta|rc|final)[._]?(\d+))?)?)?$")
_identifiers = {
'dev': 0,
'alpha': 1,
'a': 1,
'beta': 2,
'b': 2,
'rc': 3,
'final': 4
}
def __new__(cls, major, minor=0, patch=0, identifier='final', revision=0):
if identifier not in cls.valid_identifiers():
raise VersionError("Should be either 'final', 'dev', 'alpha', 'beta' or 'rc'")
identifier = {'a': 'alpha', 'b': 'beta'}.get(identifier, identifier)
try:
major = int(major)
minor = int(minor)
patch = int(patch)
revision = int(revision)
except (TypeError, ValueError):
raise VersionError("major, minor, patch and revision must be integer values")
return super(Version, cls).__new__(cls, major, minor, patch, identifier, revision)
@classmethod
def from_string(cls, version_str):
match_ = cls._version_re.search(version_str)
if match_:
(major, minor, patch, identifier, revision) = match_.groups()
major = int(major)
if minor is None:
return Version(major)
minor = int(minor)
if patch is None:
return Version(major, minor)
patch = int(patch)
if identifier is None:
return Version(major, minor, patch)
revision = int(revision)
return Version(major, minor, patch, identifier, revision)
raise VersionError("String '%s' does not match regex '%s'" % (version_str,
cls._version_re.pattern))
@classmethod
def valid_identifiers(cls):
return set(cls._identifiers.keys())
def short_str(self):
if self.identifier in {'alpha', 'beta'}:
version = self._replace(identifier=self.identifier[0])
else:
version = self
if version.identifier == 'final':
if version.patch == 0:
version_str = '%d.%d' % version[:2]
else:
version_str = '%d.%d.%d' % version[:3]
elif version.identifier in {'a', 'b', 'rc'}:
version_str = '%d.%d.%d%s%d' % version
else:
version_str = '%d.%d.%d.%s%d' % version
return version_str
@property
def sortkey(self):
return self[:3] + (self._identifiers.get(self.identifier, 0), self.revision)
def __str__(self):
return '%d.%d.%d.%s%d' % self
def __lt__(self, other):
if not isinstance(other, Version):
other = Version(*other)
return self.sortkey < other.sortkey
def __le__(self, other):
if not isinstance(other, Version):
other = Version(*other)
return self.sortkey <= other.sortkey
def __gt__(self, other):
if not isinstance(other, Version):
other = Version(*other)
return self.sortkey > other.sortkey
def __ge__(self, other):
if not isinstance(other, Version):
other = Version(*other)
return self.sortkey >= other.sortkey
def __eq__(self, other):
if not isinstance(other, Version):
other = Version(*other)
return self.sortkey == other.sortkey
def __ne__(self, other):
if not isinstance(other, Version):
other = Version(*other)
return self.sortkey != other.sortkey
def __hash__(self):
return super().__hash__()
| 4,630
|
Python
|
.py
| 114
| 31.982456
| 117
| 0.59097
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,943
|
audit.py
|
metabrainz_picard/picard/audit.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2023-2024 Laurent Monin
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from collections import defaultdict
import sys
import threading
import time
def setup_audit(prefixes_string):
"""Setup audit hook according to `audit` command-line option"""
if not prefixes_string:
return
if 'all' in prefixes_string.split(','):
def event_match(event):
return ('all', )
else:
# prebuild the dict, constant
PREFIXES_DICT = make_prefixes_dict(prefixes_string)
def event_match(event):
return is_matching_a_prefix(event, PREFIXES_DICT)
start_time = time.time()
def audit(event, args):
matched = event_match(event)
if matched:
matched = '.'.join(matched)
tid = threading.get_native_id()
secs = time.time() - start_time
# we can't use log here, as it generates events
print(f'audit:{matched}:{tid}:{secs} {event} args={args}')
try:
sys.addaudithook(audit)
except AttributeError:
# sys.addaudithook() appeared in Python 3.8
pass
def list_from_prefixes_string(prefixes_string):
"""Generate a sorted list of prefixes tuples
A prefixes string is a comma-separated list of dot-separated keys
"a,b.c,d.e.f,,g" would result in following sorted list:
[('a',), ('b', 'c'), ('d', 'e', 'f'), ('g',)]
"""
yield from sorted(set(tuple(e.split('.')) for e in prefixes_string.split(',') if e))
def make_prefixes_dict(prefixes_string):
"""Build a dict with keys = length of prefix"""
d = defaultdict(list)
for prefix_tuple in list_from_prefixes_string(prefixes_string):
d[len(prefix_tuple)].append(prefix_tuple)
return dict(d)
def prefixes_candidates_for_length(length, prefixes_dict):
"""Generate prefixes that may match this length"""
for prefix_len, prefixes in prefixes_dict.items():
if length >= prefix_len:
yield from prefixes
def is_matching_a_prefix(key, prefixes_dict):
"""Matches dot-separated key against prefixes
Typical case: we want to match `os.mkdir` if prefix is `os` or `os.mkdir`
but not the reverse: if prefix is `os.mkdir`Â we don't want to match a key named `os`
It returns False, or the matched prefix
"""
key_tuple = tuple(key.split('.'))
key_tuple_len = len(key_tuple)
# only use candidates that may have a chance to match
for prefix_tuple in prefixes_candidates_for_length(key_tuple_len, prefixes_dict):
# check that all elements of the key are in prefix tuple
if all(prefix_part == key_tuple[i] for i, prefix_part in enumerate(prefix_tuple)):
return prefix_tuple
return False
| 3,494
|
Python
|
.py
| 81
| 37.518519
| 92
| 0.681484
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,944
|
utils.py
|
metabrainz_picard/picard/coverart/utils.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2013-2015, 2020-2021, 2023-2024 Laurent Monin
# Copyright (C) 2017 Sambhav Kothari
# Copyright (C) 2018 Wieland Hoffmann
# Copyright (C) 2019-2021 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from enum import IntEnum
from picard.const import MB_ATTRIBUTES
from picard.i18n import (
N_,
gettext as _,
pgettext_attributes,
)
# list of types from http://musicbrainz.org/doc/Cover_Art/Types
# order of declaration is preserved in selection box
CAA_TYPES = []
for k, v in sorted(MB_ATTRIBUTES.items(), key=lambda k_v: k_v[0]):
if k.startswith('DB:cover_art_archive.art_type/name:'):
CAA_TYPES.append({'name': v.lower(), 'title': v})
# pseudo type, used for the no type case
CAA_TYPES.append({'name': 'unknown', 'title': N_("Unknown")})
CAA_TYPES_TR = {}
for t in CAA_TYPES:
CAA_TYPES_TR[t['name']] = t['title']
def translate_caa_type(name):
if name == 'unknown':
return _(CAA_TYPES_TR[name])
else:
title = CAA_TYPES_TR.get(name, name)
return pgettext_attributes("cover_art_type", title)
# See https://id3.org/id3v2.4.0-frames, 4.14 Attached picture
class Id3ImageType(IntEnum):
OTHER = 0
FILE_ICON = 1
FILE_ICON_OTHER = 2
COVER_FRONT = 3
COVER_BACK = 4
LEAFLET_PAGE = 5
MEDIA = 6
LEAD_ARTIST = 7
ARTIST = 8
CONDUCTOR = 9
BAND = 10
COMPOSER = 11
LYRICIST = 12
RECORDING_DURATION = 13
DURING_RECORDING = 14
DURING_PERFORMANCE = 15
VIDEO_SCREEN_CAPTURE = 16
BRIGHT_COLOURED_FISH = 17
ILLUSTRATION = 18
LOGO_ARTIST = 19
LOGO_STUDIO = 20
__ID3_IMAGE_TYPE_MAP = {
'obi': Id3ImageType.OTHER,
'tray': Id3ImageType.OTHER,
'spine': Id3ImageType.OTHER,
'sticker': Id3ImageType.OTHER,
'other': Id3ImageType.OTHER,
'front': Id3ImageType.COVER_FRONT,
'back': Id3ImageType.COVER_BACK,
'booklet': Id3ImageType.LEAFLET_PAGE,
'track': Id3ImageType.MEDIA,
'medium': Id3ImageType.MEDIA,
}
__ID3_REVERSE_IMAGE_TYPE_MAP = {v: k for k, v in __ID3_IMAGE_TYPE_MAP.items()}
def image_type_from_id3_num(id3type):
return __ID3_REVERSE_IMAGE_TYPE_MAP.get(id3type, 'other')
def image_type_as_id3_num(texttype):
return __ID3_IMAGE_TYPE_MAP.get(texttype, Id3ImageType.OTHER)
def types_from_id3(id3type):
return [image_type_from_id3_num(id3type)]
TYPES_SEPARATOR = ", "
def translated_types_as_string(types, separator=TYPES_SEPARATOR):
return separator.join(translate_caa_type(t) for t in types)
| 3,252
|
Python
|
.py
| 91
| 32.274725
| 80
| 0.710233
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,945
|
__init__.py
|
metabrainz_picard/picard/coverart/__init__.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2007 Oliver Charles
# Copyright (C) 2007, 2010-2011 Lukáš Lalinský
# Copyright (C) 2007-2011, 2019-2023 Philipp Wolfer
# Copyright (C) 2011 Michael Wiencek
# Copyright (C) 2011-2012 Wieland Hoffmann
# Copyright (C) 2013-2015, 2018-2021, 2023-2024 Laurent Monin
# Copyright (C) 2016-2017 Sambhav Kothari
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from functools import partial
import traceback
from PyQt6 import QtCore
from picard import log
from picard.config import get_config
from picard.coverart.image import CoverArtImageIOError
from picard.coverart.processing import (
CoverArtImageProcessing,
run_image_filters,
)
from picard.coverart.providers import (
CoverArtProvider,
cover_art_providers,
)
from picard.extension_points.metadata import register_album_metadata_processor
from picard.i18n import N_
from picard.util import imageinfo
class CoverArt:
def __init__(self, album, metadata, release):
self._queue_new()
self.album = album
self.metadata = metadata
self.release = release # not used in this class, but used by providers
self.front_image_found = False
self.image_processing = CoverArtImageProcessing(album)
def __repr__(self):
return "%s for %r" % (self.__class__.__name__, self.album)
def retrieve(self):
"""Retrieve available cover art images for the release"""
config = get_config()
if config.setting['save_images_to_tags'] or config.setting['save_images_to_files']:
self.providers = cover_art_providers()
self.next_in_queue()
else:
log.debug("Cover art disabled by user options.")
def _set_metadata(self, coverartimage, data, image_info):
self.image_processing.run_image_processors(coverartimage, data, image_info)
if coverartimage.can_be_saved_to_metadata:
log.debug("Storing to metadata: %r", coverartimage)
self.metadata.images.append(coverartimage)
for track in self.album._new_tracks:
track.metadata.images.append(coverartimage)
# If the image already was a front image,
# there might still be some other non-CAA front
# images in the queue - ignore them.
if not self.front_image_found:
self.front_image_found = coverartimage.is_front_image()
else:
log.debug("Not storing to metadata: %r", coverartimage)
def _coverart_downloaded(self, coverartimage, data, http, error):
"""Handle finished download, save it to metadata"""
self.album._requests -= 1
if error:
self.album.error_append("Coverart error: %s" % http.errorString())
elif len(data) < 1000:
log.warning("Not enough data, skipping %s", coverartimage)
else:
self._message(
N_("Cover art of type '%(type)s' downloaded for %(albumid)s from %(host)s"),
{
'type': coverartimage.types_as_string(),
'albumid': self.album.id,
'host': coverartimage.url.host(),
},
echo=None
)
try:
image_info = imageinfo.identify(data)
filters_result = True
if coverartimage.can_be_filtered:
filters_result = run_image_filters(data, image_info, self.album, coverartimage)
if filters_result:
self._set_metadata(coverartimage, data, image_info)
except imageinfo.IdentificationError:
return
self.next_in_queue()
def next_in_queue(self):
"""Downloads next item in queue.
If there are none left, loading of album will be finalized.
"""
if self.album.id not in self.album.tagger.albums:
# album removed
return
config = get_config()
if (self.front_image_found
and config.setting['save_images_to_tags']
and not config.setting['save_images_to_files']
and config.setting['embed_only_one_front_image']):
# no need to continue
processing_result = self.image_processing.wait_for_processing()
self.album._finalize_loading(error=processing_result)
return
if self._queue_empty():
try:
# requeue from next provider
provider = next(self.providers)
ret = CoverArtProvider._STARTED
try:
instance = provider.cls(self)
if provider.enabled and instance.enabled():
log.debug("Trying cover art provider %s …", provider.name)
ret = instance.queue_images()
else:
log.debug("Skipping cover art provider %s …", provider.name)
except BaseException:
log.error(traceback.format_exc())
raise
finally:
if ret != CoverArtProvider.WAIT:
self.next_in_queue()
return
except StopIteration:
# nothing more to do
processing_result = self.image_processing.wait_for_processing()
self.album._finalize_loading(error=processing_result)
return
# We still have some items to try!
coverartimage = self._queue_get()
if not coverartimage.support_types and self.front_image_found:
# we already have one front image, no need to try other type-less
# sources
log.debug("Skipping %r, one front image is already available",
coverartimage)
self.next_in_queue()
return
# local files
if coverartimage.url and coverartimage.url.scheme() == 'file':
try:
path = coverartimage.url.toLocalFile()
with open(path, 'rb') as file:
self._set_metadata(coverartimage, file.read())
except OSError as exc:
(errnum, errmsg) = exc.args
log.error("Failed to read %r: %s (%d)", path, errmsg, errnum)
except CoverArtImageIOError:
# It doesn't make sense to store/download more images if we can't
# save them in the temporary folder, abort.
return
self.next_in_queue()
return
# on the web
self._message(
N_("Downloading cover art of type '%(type)s' for %(albumid)s from %(host)s …"),
{
'type': coverartimage.types_as_string(),
'albumid': self.album.id,
'host': coverartimage.url.host(),
},
echo=None
)
log.debug("Downloading %r", coverartimage)
self.album.tagger.webservice.download_url(
url=coverartimage.url,
handler=partial(self._coverart_downloaded, coverartimage),
priority=True,
)
self.album._requests += 1
def queue_put(self, coverartimage):
"""Add an image to queue"""
log.debug("Queuing cover art image %r", coverartimage)
self.__queue.append(coverartimage)
def _queue_get(self):
"""Get next image and remove it from queue"""
return self.__queue.pop(0)
def _queue_empty(self):
"""Returns True if the queue is empty"""
return not self.__queue
def _queue_new(self):
"""Initialize the queue"""
self.__queue = []
def _message(self, *args, **kwargs):
"""Display message to status bar"""
tagger = QtCore.QCoreApplication.instance()
tagger.window.set_statusbar_message(*args, **kwargs)
def _retrieve_coverart(album, metadata, release):
"""Gets all cover art URLs from the metadata and then attempts to
download the album art. """
coverart = CoverArt(album, metadata, release)
log.debug("New %r", coverart)
coverart.retrieve()
register_album_metadata_processor(_retrieve_coverart)
| 8,955
|
Python
|
.py
| 206
| 33.058252
| 99
| 0.610263
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,946
|
image.py
|
metabrainz_picard/picard/coverart/image.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2007 Oliver Charles
# Copyright (C) 2007, 2010-2011 Lukáš Lalinský
# Copyright (C) 2007-2011, 2014, 2018-2024 Philipp Wolfer
# Copyright (C) 2011 Michael Wiencek
# Copyright (C) 2011-2012, 2015 Wieland Hoffmann
# Copyright (C) 2013-2015, 2018-2024 Laurent Monin
# Copyright (C) 2016 Ville Skyttä
# Copyright (C) 2016-2018 Sambhav Kothari
# Copyright (C) 2017 Antonio Larrosa
# Copyright (C) 2018 Vishal Choudhary
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from hashlib import blake2b
import os
import shutil
import tempfile
from PyQt6.QtCore import (
QCoreApplication,
QMutex,
QUrl,
)
from picard import log
from picard.config import get_config
from picard.const.defaults import DEFAULT_COVER_IMAGE_FILENAME
from picard.const.sys import (
IS_MACOS,
IS_WIN,
)
from picard.coverart.utils import (
TYPES_SEPARATOR,
Id3ImageType,
image_type_as_id3_num,
translated_types_as_string,
)
from picard.metadata import Metadata
from picard.util import (
decode_filename,
encode_filename,
imageinfo,
is_absolute_path,
periodictouch,
sanitize_filename,
)
from picard.util.filenaming import (
make_save_path,
make_short_filename,
)
from picard.util.scripttofilename import script_to_filename
_datafiles = dict()
_datafile_mutex = QMutex()
class DataHash:
def __init__(self, data, prefix='picard', suffix=''):
self._filename = None
_datafile_mutex.lock()
try:
self._hash = blake2b(data).hexdigest()
if self._hash not in _datafiles:
# store tmp file path in _datafiles[self._hash] ASAP
(fd, _datafiles[self._hash]) = tempfile.mkstemp(prefix=prefix, suffix=suffix)
filepath = _datafiles[self._hash]
tagger = QCoreApplication.instance()
tagger.register_cleanup(self.delete_file)
periodictouch.register_file(filepath)
with os.fdopen(fd, 'wb') as imagefile:
imagefile.write(data)
log.debug("Saving image data %s to %r", self._hash[:16], filepath)
self._filename = _datafiles[self._hash]
finally:
_datafile_mutex.unlock()
def __eq__(self, other):
return self._hash == other._hash
def __lt__(self, other):
return self._hash < other._hash
def hash(self):
return self._hash
def delete_file(self):
if not self._hash or self._hash not in _datafiles:
return
_datafile_mutex.lock()
try:
filepath = _datafiles[self._hash]
try:
os.unlink(filepath)
periodictouch.unregister_file(filepath)
except BaseException as e:
log.debug("Failed to delete file %r: %s", filepath, e)
del _datafiles[self._hash]
except KeyError:
log.error("Hash %s not found in cache for file: %r", self._hash[:16], self._filename)
finally:
self._hash = None
self._filename = None
_datafile_mutex.unlock()
@property
def data(self):
if self._filename:
with open(self._filename, 'rb') as imagefile:
return imagefile.read()
return None
@property
def filename(self):
return self._filename
class CoverArtImageError(Exception):
pass
class CoverArtImageIOError(CoverArtImageError):
pass
class CoverArtImageIdentificationError(CoverArtImageError):
pass
class CoverArtImage:
# Indicate if types are provided by the source, ie. CAA or certain file
# formats may have types associated with cover art, but some other sources
# don't provide such information
support_types = False
# Indicates that the source supports multiple types per image.
support_multi_types = False
# `is_front` has to be explicitly set, it is used to handle CAA is_front
# indicator
is_front = None
sourceprefix = 'URL'
def __init__(self, url=None, types=None, comment='', data=None, support_types=None,
support_multi_types=None, id3_type=None):
if types is None:
self.types = []
else:
self.types = types
if url is not None:
if not isinstance(url, QUrl):
self.url = QUrl(url)
else:
self.url = url
else:
self.url = None
self.comment = comment
self.datahash = None
# thumbnail is used to link to another CoverArtImage, ie. for PDFs
self.thumbnail = None
self.external_file_coverart = None
self.can_be_saved_to_tags = True
self.can_be_saved_to_disk = True
self.can_be_saved_to_metadata = True
self.can_be_filtered = True
self.can_be_processed = True
if support_types is not None:
self.support_types = support_types
if support_multi_types is not None:
self.support_multi_types = support_multi_types
if data is not None:
self.set_tags_data(data)
try:
self.id3_type = id3_type
except ValueError:
log.warning("Invalid ID3 image type %r in %r", type, self)
self.id3_type = Id3ImageType.OTHER
@property
def source(self):
if self.url is not None:
return "%s: %s" % (self.sourceprefix, self.url.toString())
else:
return "%s" % self.sourceprefix
def is_front_image(self):
"""Indicates if image is considered as a 'front' image.
It depends on few things:
- if `is_front` was set, it is used over anything else
- if `types` was set, search for 'front' in it
- if `support_types` is False, default to True for any image
- if `support_types` is True, default to False for any image
"""
if not self.can_be_saved_to_metadata:
# ignore thumbnails
return False
if self.is_front is not None:
return self.is_front
if 'front' in self.types:
return True
return (self.support_types is False)
def imageinfo_as_string(self):
if self.datahash is None:
return ""
return "w=%d h=%d mime=%s ext=%s datalen=%d file=%s" % (self.width,
self.height,
self.mimetype,
self.extension,
self.datalength,
self.tempfile_filename)
def dimensions_as_string(self):
if self.datahash is None:
return ""
return f"{self.width}x{self.height}"
def _repr(self):
if self.url is not None:
yield "url=%r" % self.url.toString()
if self.types:
yield "types=%r" % self.types
yield 'support_types=%r' % self.support_types
yield 'support_multi_types=%r' % self.support_multi_types
if self.is_front is not None:
yield "is_front=%r" % self.is_front
if self.comment:
yield "comment=%r" % self.comment
def __repr__(self):
return "%s(%s)" % (self.__class__.__name__, ", ".join(self._repr()))
def _str(self):
if self.url is not None:
yield "from %s" % self.url.toString()
if self.types:
yield "of type %s" % ','.join(self.types)
if self.comment:
yield "and comment '%s'" % self.comment
def __str__(self):
output = self.__class__.__name__
s = tuple(self._str())
if s:
output += ' ' + ' '.join(s)
return output
def __eq__(self, other):
if self and other:
if self.support_types and other.support_types:
if self.support_multi_types and other.support_multi_types:
return (self.datahash, self.types) == (other.datahash, other.types)
else:
return (self.datahash, self.maintype) == (other.datahash, other.maintype)
else:
return self.datahash == other.datahash
return not self and not other
def __lt__(self, other):
"""Try to provide constant ordering"""
stypes = self.normalized_types()
otypes = other.normalized_types()
if stypes != otypes:
sfront = self.is_front_image()
ofront = other.is_front_image()
if sfront != ofront:
# front image first
ret = sfront
else:
# lower number of types first
# '-' == unknown type always last
ret = stypes < otypes or '-' in otypes
elif self.comment != other.comment:
# shortest comment first, alphabetical
scomment = self.comment or ''
ocomment = other.comment or ''
ret = scomment < ocomment
else:
# arbitrary order based on data, but should be constant
ret = self.datahash < other.datahash
return ret
def __hash__(self):
if self.datahash is None:
return 0
return hash(self.datahash.hash())
def set_tags_data(self, data):
"""Store image data in a file, if data already exists in such file
it will be re-used and no file write occurs
"""
if self.datahash:
self.datahash.delete_file()
self.datahash = None
try:
info = imageinfo.identify(data)
self.width, self.height = info.width, info.height
self.mimetype = info.mime
self.extension = info.extension
self.datalength = info.datalen
except imageinfo.IdentificationError as e:
raise CoverArtImageIdentificationError(e)
try:
self.datahash = DataHash(data, suffix=self.extension)
except OSError as e:
raise CoverArtImageIOError(e)
def set_external_file_data(self, data):
self.external_file_coverart = CoverArtImage(data=data, url=self.url)
@property
def maintype(self):
"""Returns one type only, even for images having more than one type set.
This is mostly used when saving cover art to tags because most formats
don't support multiple types for one image.
Images coming from CAA can have multiple types (ie. 'front, booklet').
"""
if self.is_front_image() or not self.types or 'front' in self.types:
return 'front'
# TODO: do something better than randomly using the first in the list
return self.types[0]
@property
def id3_type(self):
"""Returns the ID3 APIC image type.
If explicitly set the type is returned as is, otherwise it is derived
from `maintype`. See http://www.id3.org/id3v2.4.0-frames"""
if self._id3_type is not None:
return self._id3_type
else:
return image_type_as_id3_num(self.maintype)
@id3_type.setter
def id3_type(self, type):
"""Explicitly sets the ID3 APIC image type.
If set to None the type will be derived from `maintype`."""
if type is not None:
type = Id3ImageType(type)
self._id3_type = type
def _make_image_filename(self, filename, dirname, _metadata, win_compat, win_shorten_path):
metadata = Metadata()
metadata.copy(_metadata)
metadata['coverart_maintype'] = self.maintype
metadata['coverart_comment'] = self.comment
if self.is_front:
metadata.add_unique('coverart_types', 'front')
for cover_type in self.types:
metadata.add_unique('coverart_types', cover_type)
filename = script_to_filename(filename, metadata)
if not filename:
filename = DEFAULT_COVER_IMAGE_FILENAME
dirname = os.path.normpath(dirname)
if not is_absolute_path(filename):
filename = os.path.normpath(os.path.join(dirname, filename))
try:
basedir = os.path.commonpath((dirname, os.path.dirname(filename)))
relpath = os.path.relpath(filename, start=basedir)
except ValueError:
basedir = os.path.dirname(filename)
relpath = os.path.basename(filename)
relpath = make_short_filename(basedir, relpath, win_shorten_path=win_shorten_path)
filename = os.path.join(basedir, relpath)
filename = make_save_path(filename, win_compat=win_compat, mac_compat=IS_MACOS)
return encode_filename(filename)
def save(self, dirname, metadata, counters):
"""Saves this image.
:dirname: The name of the directory that contains the audio file
:metadata: A metadata object
:counters: A dictionary mapping filenames to the amount of how many
images with that filename were already saved in `dirname`.
"""
if self.external_file_coverart is not None:
self.external_file_coverart.save(dirname, metadata, counters)
return
if not self.can_be_saved_to_disk:
return
config = get_config()
win_compat = IS_WIN or config.setting['windows_compatibility']
win_shorten_path = win_compat and not config.setting['windows_long_paths']
if config.setting['image_type_as_filename'] and not self.is_front_image():
filename = sanitize_filename(self.maintype, win_compat=win_compat)
log.debug("Make cover filename from types: %r -> %r",
self.types, filename)
else:
filename = config.setting['cover_image_filename']
log.debug("Using default cover image filename %r", filename)
filename = self._make_image_filename(
filename, dirname, metadata, win_compat, win_shorten_path)
overwrite = config.setting['save_images_overwrite']
ext = encode_filename(self.extension)
image_filename = self._next_filename(filename, counters)
while os.path.exists(image_filename + ext) and not overwrite:
if not self._is_write_needed(image_filename + ext):
break
image_filename = self._next_filename(filename, counters)
else:
new_filename = image_filename + ext
# Even if overwrite is enabled we don't need to write the same
# image multiple times
if not self._is_write_needed(new_filename):
return
log.debug("Saving cover image to %r", new_filename)
try:
new_dirname = os.path.dirname(new_filename)
if not os.path.isdir(new_dirname):
os.makedirs(new_dirname)
shutil.copyfile(self.tempfile_filename, new_filename)
except OSError as e:
raise CoverArtImageIOError(e)
@staticmethod
def _next_filename(filename, counters):
if counters[filename]:
new_filename = "%s (%d)" % (decode_filename(filename), counters[filename])
else:
new_filename = filename
counters[filename] += 1
return encode_filename(new_filename)
def _is_write_needed(self, filename):
if (os.path.exists(filename)
and os.path.getsize(filename) == self.datalength):
log.debug("Identical file size, not saving %r", filename)
return False
return True
@property
def data(self):
"""Reads the data from the temporary file created for this image.
May raise CoverArtImageIOError
"""
try:
return self.datahash.data
except OSError as e:
raise CoverArtImageIOError(e)
@property
def tempfile_filename(self):
return self.datahash.filename
def normalized_types(self):
if self.types and self.support_types:
# ensure front type is first, if any
# the rest is sorted
types_front = ['front'] if 'front' in self.types else []
types_without_front = sorted(set(t for t in self.types if t != 'front'))
types = types_front + types_without_front
elif self.is_front_image():
types = ['front']
else:
types = ['-']
return tuple(types)
def types_as_string(self, translate=True, separator=TYPES_SEPARATOR):
types = self.normalized_types()
if translate:
return translated_types_as_string(types, separator)
else:
return separator.join(types)
class CaaCoverArtImage(CoverArtImage):
"""Image from Cover Art Archive"""
support_types = True
support_multi_types = True
sourceprefix = 'CAA'
def __init__(self, url, types=None, is_front=False, comment='', data=None):
super().__init__(url=url, types=types, comment=comment, data=data)
self.is_front = is_front
class CaaThumbnailCoverArtImage(CaaCoverArtImage):
"""Used for thumbnails of CaaCoverArtImage objects, together with thumbnail
property"""
def __init__(self, url, types=None, is_front=False, comment='', data=None):
super().__init__(url=url, types=types, comment=comment, data=data)
self.is_front = False
self.can_be_saved_to_disk = False
self.can_be_saved_to_tags = False
self.can_be_saved_to_metadata = False
self.can_be_filtered = False
self.can_be_processed = False
class TagCoverArtImage(CoverArtImage):
"""Image from file tags"""
def __init__(self, file, tag=None, types=None, is_front=None,
support_types=False, comment='', data=None,
support_multi_types=False, id3_type=None):
self.sourcefile = file
self.tag = tag
super().__init__(url=None, types=types, comment=comment, data=data, id3_type=id3_type)
self.support_types = support_types
self.support_multi_types = support_multi_types
if is_front is not None:
self.is_front = is_front
@property
def source(self):
if self.tag:
return 'Tag %s from %s' % (self.tag, self.sourcefile)
else:
return 'File %s' % (self.sourcefile)
def _repr(self):
yield '%r' % self.sourcefile
if self.tag is not None:
yield 'tag=%r' % self.tag
yield from super()._repr()
def _str(self):
yield 'from %r' % self.sourcefile
yield from super()._str()
class LocalFileCoverArtImage(CoverArtImage):
sourceprefix = 'LOCAL'
def __init__(self, filepath, types=None, comment='',
support_types=False, support_multi_types=False):
url = QUrl.fromLocalFile(filepath).toString()
super().__init__(url=url, types=types, comment=comment)
self.support_types = support_types
self.support_multi_types = support_multi_types
| 19,922
|
Python
|
.py
| 482
| 31.593361
| 97
| 0.608388
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,947
|
local.py
|
metabrainz_picard/picard/coverart/providers/local.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2015, 2018-2021, 2023-2024 Laurent Monin
# Copyright (C) 2016-2017 Sambhav Kothari
# Copyright (C) 2017 Ville Skytt√§
# Copyright (C) 2019-2021 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import os
import re
from picard.config import get_config
from picard.const.defaults import DEFAULT_LOCAL_COVER_ART_REGEX
from picard.coverart.image import LocalFileCoverArtImage
from picard.coverart.providers.provider import (
CoverArtProvider,
ProviderOptions,
)
from picard.coverart.utils import CAA_TYPES
from picard.i18n import N_
from picard.ui.forms.ui_provider_options_local import Ui_LocalOptions
class ProviderOptionsLocal(ProviderOptions):
"""
Options for Local Files cover art provider
"""
HELP_URL = '/config/options_local_files.html'
_options_ui = Ui_LocalOptions
def __init__(self, parent=None):
super().__init__(parent)
self.init_regex_checker(self.ui.local_cover_regex_edit, self.ui.local_cover_regex_error)
self.ui.local_cover_regex_default.clicked.connect(self.set_local_cover_regex_default)
def set_local_cover_regex_default(self):
self.ui.local_cover_regex_edit.setText(DEFAULT_LOCAL_COVER_ART_REGEX)
def load(self):
config = get_config()
self.ui.local_cover_regex_edit.setText(config.setting['local_cover_regex'])
def save(self):
config = get_config()
config.setting['local_cover_regex'] = self.ui.local_cover_regex_edit.text()
class CoverArtProviderLocal(CoverArtProvider):
"""Get cover art from local files"""
NAME = "Local Files"
TITLE = N_("Local Files")
OPTIONS = ProviderOptionsLocal
_types_split_re = re.compile('[^a-z0-9]', re.IGNORECASE)
_known_types = {t['name'] for t in CAA_TYPES}
_default_types = ['front']
def queue_images(self):
config = get_config()
regex = config.setting['local_cover_regex']
if regex:
_match_re = re.compile(regex, re.IGNORECASE)
dirs_done = set()
for file in self.album.iterfiles():
current_dir = os.path.dirname(file.filename)
if current_dir in dirs_done:
continue
dirs_done.add(current_dir)
for image in self.find_local_images(current_dir, _match_re):
self.queue_put(image)
return CoverArtProvider.FINISHED
def get_types(self, string):
found = {x.lower() for x in self._types_split_re.split(string) if x}
return list(found.intersection(self._known_types))
def find_local_images(self, current_dir, match_re):
for root, dirs, files in os.walk(current_dir):
for filename in files:
m = match_re.search(filename)
if not m:
continue
filepath = os.path.join(current_dir, root, filename)
if not os.path.exists(filepath):
continue
try:
type_from_filename = self.get_types(m.group(1))
except IndexError:
type_from_filename = []
yield LocalFileCoverArtImage(
filepath,
types=type_from_filename or self._default_types,
support_types=True,
support_multi_types=True
)
| 4,141
|
Python
|
.py
| 96
| 35.166667
| 96
| 0.659046
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,948
|
provider.py
|
metabrainz_picard/picard/coverart/providers/provider.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2014-2015, 2018-2019, 2021 Laurent Monin
# Copyright (C) 2015 Rahul Raturi
# Copyright (C) 2016 Ville Skytt√§
# Copyright (C) 2016 Wieland Hoffmann
# Copyright (C) 2017 Sambhav Kothari
# Copyright (C) 2019-2020 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import traceback
from picard.ui.options import OptionsPage
class ProviderOptions(OptionsPage):
""" Template class for provider's options
It works like OptionsPage for the most (options, load, save)
It will append the provider's options page as a child of the main
cover art's options page.
The property _options_ui must be set to a valid Qt Ui class
containing the layout and widgets for defined provider's options.
A specific provider class (inhereting from CoverArtProvider) has
to set the subclassed ProviderOptions as OPTIONS property.
Options will be registered at the same time as the provider.
class MyProviderOptions(ProviderOptions):
_options_ui = Ui_MyProviderOptions
....
class MyProvider(CoverArtProvider):
OPTIONS = ProviderOptionsMyProvider
....
"""
PARENT = "cover"
def __init__(self, parent=None):
super().__init__(parent=parent)
self.ui = self._options_ui()
self.ui.setupUi(self)
class CoverArtProviderMetaClass(type):
"""Provide default properties name & title for CoverArtProvider
It is recommended to use those in place of NAME and TITLE that might not be defined
"""
@property
def name(cls):
return getattr(cls, 'NAME', cls.__name__)
@property
def title(cls):
return getattr(cls, 'TITLE', cls.name)
class CoverArtProvider(metaclass=CoverArtProviderMetaClass):
"""Subclasses of this class need to reimplement at least `queue_images()`.
`__init__()` does not have to do anything.
`queue_images()` will be called if `enabled()` returns `True`.
`queue_images()` must return `FINISHED` when it finished to queue
potential cover art downloads (using `queue_put(<CoverArtImage object>).
If `queue_images()` delegates the job of queuing downloads to another
method (asynchronous) it should return `WAIT` and the other method has to
explicitly call `next_in_queue()`.
If `FINISHED` is returned, `next_in_queue()` will be automatically called
by CoverArt object.
"""
# default state, internal use
_STARTED = 0
# returned by queue_images():
# next_in_queue() will be automatically called
FINISHED = 1
# returned by queue_images():
# next_in_queue() has to be called explicitly by provider
WAIT = 2
def __init__(self, coverart):
self.coverart = coverart
self.release = coverart.release
self.metadata = coverart.metadata
self.album = coverart.album
def enabled(self):
return not self.coverart.front_image_found
def queue_images(self):
# this method has to return CoverArtProvider.FINISHED or
# CoverArtProvider.WAIT
raise NotImplementedError
def error(self, msg):
self.coverart.album.error_append(msg)
def queue_put(self, what):
self.coverart.queue_put(what)
def next_in_queue(self):
# must be called by provider if queue_images() returns WAIT
self.coverart.next_in_queue()
def match_url_relations(self, relation_types, func):
"""Execute `func` for each relation url matching type in
`relation_types`
"""
try:
if 'relations' in self.release:
for relation in self.release['relations']:
if relation['target-type'] == 'url':
if relation['type'] in relation_types:
func(relation['url']['resource'])
except AttributeError:
self.error(traceback.format_exc())
| 4,708
|
Python
|
.py
| 108
| 36.842593
| 87
| 0.681609
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,949
|
caa_release_group.py
|
metabrainz_picard/picard/coverart/providers/caa_release_group.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2014-2016, 2018-2021, 2023-2024 Laurent Monin
# Copyright (C) 2017 Sambhav Kothari
# Copyright (C) 2020 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from picard.coverart.image import (
CaaCoverArtImage,
CaaThumbnailCoverArtImage,
)
from picard.coverart.providers.caa import CoverArtProviderCaa
from picard.i18n import N_
class CaaCoverArtImageRg(CaaCoverArtImage):
pass
class CaaThumbnailCoverArtImageRg(CaaThumbnailCoverArtImage):
pass
class CoverArtProviderCaaReleaseGroup(CoverArtProviderCaa):
"""Use cover art from album release group"""
NAME = "CaaReleaseGroup"
TITLE = N_("Cover Art Archive: Release Group")
# FIXME: caa release group uses the same options than caa
OPTIONS = None
ignore_json_not_found_error = True
coverartimage_class = CaaCoverArtImageRg
coverartimage_thumbnail_class = CaaThumbnailCoverArtImageRg
def enabled(self):
return not self.coverart.front_image_found
@property
def _caa_path(self):
return "/release-group/%s/" % self.metadata['musicbrainz_releasegroupid']
| 1,849
|
Python
|
.py
| 45
| 38.111111
| 81
| 0.772753
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,950
|
caa.py
|
metabrainz_picard/picard/coverart/providers/caa.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2007 Oliver Charles
# Copyright (C) 2007, 2010-2011 Lukáš Lalinský
# Copyright (C) 2007-2011, 2015, 2018-2023 Philipp Wolfer
# Copyright (C) 2011 Michael Wiencek
# Copyright (C) 2011-2012 Wieland Hoffmann
# Copyright (C) 2013-2015, 2018-2023 Laurent Monin
# Copyright (C) 2015-2016 Rahul Raturi
# Copyright (C) 2016-2017 Sambhav Kothari
# Copyright (C) 2017 Frederik “Freso” S. Olesen
# Copyright (C) 2018, 2024 Bob Swift
# Copyright (C) 2018 Vishal Choudhary
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from collections import (
OrderedDict,
namedtuple,
)
from PyQt6.QtNetwork import (
QNetworkReply,
QNetworkRequest,
)
from picard import log
from picard.config import get_config
from picard.const import CAA_URL
from picard.const.defaults import (
DEFAULT_CAA_IMAGE_SIZE,
DEFAULT_CAA_IMAGE_TYPE_EXCLUDE,
DEFAULT_CAA_IMAGE_TYPE_INCLUDE,
)
from picard.coverart.image import (
CaaCoverArtImage,
CaaThumbnailCoverArtImage,
)
from picard.coverart.processing import run_image_metadata_filters
from picard.coverart.providers.provider import (
CoverArtProvider,
ProviderOptions,
)
from picard.i18n import (
N_,
gettext as _,
)
from picard.webservice import ratecontrol
from picard.ui.caa_types_selector import CAATypesSelectorDialog
from picard.ui.forms.ui_provider_options_caa import Ui_CaaOptions
CaaSizeItem = namedtuple('CaaSizeItem', ['thumbnail', 'label'])
CaaThumbnailListItem = namedtuple('CAAThumbnailListItem', ['url', 'width'])
_CAA_THUMBNAIL_SIZE_MAP = OrderedDict([
(250, CaaSizeItem('250', N_('250 px'))),
(500, CaaSizeItem('500', N_('500 px'))),
(1200, CaaSizeItem('1200', N_('1200 px'))),
(-1, CaaSizeItem(None, N_('Full size'))),
])
_CAA_THUMBNAIL_SIZE_ALIASES = {
'500': 'large',
'250': 'small',
}
ratecontrol.set_minimum_delay_for_url(CAA_URL, 0)
ratecontrol.set_minimum_delay_for_url("https://archive.org", 0)
def caa_url_fallback_list(desired_size, thumbnails):
"""List of thumbnail urls equal or smaller than size, in size decreasing order
It is used for find the "best" thumbnail according to:
- user choice
- thumbnail availability
If user choice isn't matching an available thumbnail size, a fallback to
smaller thumbnails is possible
This function returns the list of possible urls, ordered from the biggest
matching the user choice to the smallest one, together with its thumbnail's size.
Of course, if none are possible, the returned list may be empty.
"""
reversed_map = OrderedDict(reversed(list(_CAA_THUMBNAIL_SIZE_MAP.items())))
thumbnail_list = []
for thumbnail_width, item in reversed_map.items():
if thumbnail_width == -1 or thumbnail_width > desired_size:
continue
url = thumbnails.get(item.thumbnail, None)
if url is None:
size_alias = _CAA_THUMBNAIL_SIZE_ALIASES.get(item.thumbnail, None)
if size_alias is not None:
url = thumbnails.get(size_alias, None)
if url is not None:
thumbnail_list.append(CaaThumbnailListItem(url, thumbnail_width))
return thumbnail_list
class ProviderOptionsCaa(ProviderOptions):
"""
Options for Cover Art Archive cover art provider
"""
TITLE = N_("Cover Art Archive")
HELP_URL = "/config/options_cover_art_archive.html"
_options_ui = Ui_CaaOptions
def __init__(self, parent=None):
super().__init__(parent)
self.ui.restrict_images_types.clicked.connect(self.update_caa_types)
self.ui.select_caa_types.clicked.connect(self.select_caa_types)
def restore_defaults(self):
self.caa_image_types = DEFAULT_CAA_IMAGE_TYPE_INCLUDE
self.caa_image_types_to_omit = DEFAULT_CAA_IMAGE_TYPE_EXCLUDE
super().restore_defaults()
def load(self):
self.ui.cb_image_size.clear()
for item_id, item in _CAA_THUMBNAIL_SIZE_MAP.items():
self.ui.cb_image_size.addItem(_(item.label), userData=item_id)
config = get_config()
size = config.setting['caa_image_size']
index = self.ui.cb_image_size.findData(size)
if index < 0:
index = self.ui.cb_image_size.findData(DEFAULT_CAA_IMAGE_SIZE)
self.ui.cb_image_size.setCurrentIndex(index)
self.ui.cb_approved_only.setChecked(config.setting['caa_approved_only'])
self.ui.restrict_images_types.setChecked(
config.setting['caa_restrict_image_types'])
self.caa_image_types = config.setting['caa_image_types']
self.caa_image_types_to_omit = config.setting['caa_image_types_to_omit']
self.update_caa_types()
def save(self):
config = get_config()
size = self.ui.cb_image_size.currentData()
config.setting['caa_image_size'] = size
config.setting['caa_approved_only'] = \
self.ui.cb_approved_only.isChecked()
config.setting['caa_restrict_image_types'] = \
self.ui.restrict_images_types.isChecked()
config.setting['caa_image_types'] = self.caa_image_types
config.setting['caa_image_types_to_omit'] = self.caa_image_types_to_omit
def update_caa_types(self):
enabled = self.ui.restrict_images_types.isChecked()
self.ui.select_caa_types.setEnabled(enabled)
def select_caa_types(self):
(types, types_to_omit, ok) = CAATypesSelectorDialog.display(
types_include=self.caa_image_types,
types_exclude=self.caa_image_types_to_omit,
parent=self,
instructions_top=None,
instructions_bottom=None,
)
if ok:
self.caa_image_types = types
self.caa_image_types_to_omit = types_to_omit
class CoverArtProviderCaa(CoverArtProvider):
"""Get cover art from Cover Art Archive using release mbid"""
NAME = "Cover Art Archive"
TITLE = N_("Cover Art Archive: Release")
OPTIONS = ProviderOptionsCaa
ignore_json_not_found_error = False
coverartimage_class = CaaCoverArtImage
coverartimage_thumbnail_class = CaaThumbnailCoverArtImage
def __init__(self, coverart):
super().__init__(coverart)
config = get_config()
self.restrict_types = config.setting['caa_restrict_image_types']
if self.restrict_types:
self.included_types = {t.lower() for t in config.setting['caa_image_types']}
self.excluded_types = {t.lower() for t in config.setting['caa_image_types_to_omit']}
self.included_types_count = len(self.included_types)
@property
def _has_suitable_artwork(self):
# MB web service indicates if CAA has artwork
# https://tickets.metabrainz.org/browse/MBS-4536
if 'cover-art-archive' not in self.release:
log.debug("No Cover Art Archive information for %s", self.release['id'])
return False
caa_node = self.release['cover-art-archive']
caa_has_suitable_artwork = caa_node['artwork']
if not caa_has_suitable_artwork:
log.debug("There are no images in the Cover Art Archive for %s", self.release['id'])
return False
if self.restrict_types:
want_front = 'front' in self.included_types
want_back = 'back' in self.included_types
caa_has_front = caa_node['front']
caa_has_back = caa_node['back']
if self.included_types_count == 2 and (want_front or want_back):
# The OR cases are there to still download and process the CAA
# JSON file if front or back is enabled but not in the CAA and
# another type (that's neither front nor back) is enabled.
# For example, if both front and booklet are enabled and the
# CAA only has booklet images, the front element in the XML
# from the webservice will be false (thus front_in_caa is False
# as well) but it's still necessary to download the booklet
# images by using the fact that back is enabled but there are
# no back images in the CAA.
front_in_caa = caa_has_front or not want_front
back_in_caa = caa_has_back or not want_back
caa_has_suitable_artwork = front_in_caa or back_in_caa
elif self.included_types_count == 1 and (want_front or want_back):
front_in_caa = caa_has_front and want_front
back_in_caa = caa_has_back and want_back
caa_has_suitable_artwork = front_in_caa or back_in_caa
if not caa_has_suitable_artwork:
log.debug("There are no suitable images in the Cover Art Archive for %s", self.release['id'])
else:
log.debug("There are suitable images in the Cover Art Archive for %s", self.release['id'])
return caa_has_suitable_artwork
def enabled(self):
"""Check if CAA artwork has to be downloaded"""
if not super().enabled():
return False
if self.restrict_types and not self.included_types_count:
log.debug("User disabled all Cover Art Archive types")
return False
return self._has_suitable_artwork
@property
def _caa_path(self):
return "/release/%s/" % self.metadata['musicbrainz_albumid']
def queue_images(self):
self.album.tagger.webservice.get_url(
url=CAA_URL + self._caa_path,
handler=self._caa_json_downloaded,
priority=True,
important=False,
cacheloadcontrol=QNetworkRequest.CacheLoadControl.PreferNetwork,
)
self.album._requests += 1
# we will call next_in_queue() after json parsing
return CoverArtProvider.WAIT
def _caa_json_downloaded(self, data, http, error):
"""Parse CAA JSON file and queue CAA cover art images for download"""
self.album._requests -= 1
if error:
if not (error == QNetworkReply.NetworkError.ContentNotFoundError and self.ignore_json_not_found_error):
self.error("CAA JSON error: %s" % (http.errorString()))
else:
if self.restrict_types:
log.debug("CAA types: included: %s, excluded: %s", list(self.included_types), list(self.excluded_types))
try:
config = get_config()
for image in data['images']:
if config.setting['caa_approved_only'] and not image['approved']:
continue
is_pdf = image['image'].endswith('.pdf')
if is_pdf and not config.setting['save_images_to_files']:
log.debug("Skipping pdf cover art : %s", image['image'])
continue
# if image has no type set, we still want it to match
# pseudo type 'unknown'
if not image['types']:
image['types'] = ['unknown']
else:
image['types'] = [t.lower() for t in image['types']]
if self.restrict_types:
# accept only if image types matches according to included/excluded types
accepted = bool(set(image['types']).intersection(self.included_types).difference(self.excluded_types))
log.debug("CAA image %s: %s %s",
('accepted' if accepted else 'rejected'),
image['image'],
image['types']
)
else:
accepted = True
if accepted:
thumbnail_list = caa_url_fallback_list(config.setting['caa_image_size'], image['thumbnails'])
if not thumbnail_list or is_pdf:
url = image['image']
else:
image_data = {'width': thumbnail_list[0].width, 'height': -1}
filters_result = run_image_metadata_filters(image_data)
if not filters_result:
continue
# FIXME: try other urls in case of 404
url = thumbnail_list[0].url
coverartimage = self.coverartimage_class(
url,
types=image['types'],
is_front=image['front'],
comment=image['comment'],
)
if thumbnail_list and is_pdf:
# thumbnail will be used to "display" PDF in info
# dialog
thumbnail = self.coverartimage_thumbnail_class(
url=thumbnail_list[0].url,
types=image['types'],
is_front=image['front'],
comment=image['comment'],
)
self.queue_put(thumbnail)
coverartimage.thumbnail = thumbnail
# PDFs cannot be saved to tags (as 2014/05/29)
coverartimage.can_be_saved_to_tags = False
self.queue_put(coverartimage)
if config.setting['save_only_one_front_image'] and \
config.setting['save_images_to_files'] and \
image['front']:
break
except (AttributeError, KeyError, TypeError) as e:
self.error("CAA JSON error: %s" % e)
self.next_in_queue()
| 14,613
|
Python
|
.py
| 303
| 36.894389
| 126
| 0.607827
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,951
|
__init__.py
|
metabrainz_picard/picard/coverart/providers/__init__.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2014-2015, 2018-2021, 2023-2024 Laurent Monin
# Copyright (C) 2015 Rahul Raturi
# Copyright (C) 2016 Ville Skytt√§
# Copyright (C) 2016 Wieland Hoffmann
# Copyright (C) 2017 Sambhav Kothari
# Copyright (C) 2019-2021 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from collections import (
defaultdict,
namedtuple,
)
from picard.config import get_config
from picard.coverart.providers.caa import CoverArtProviderCaa
from picard.coverart.providers.caa_release_group import (
CoverArtProviderCaaReleaseGroup,
)
from picard.coverart.providers.local import CoverArtProviderLocal
from picard.coverart.providers.provider import ( # noqa: F401 # pylint: disable=unused-import
CoverArtProvider,
ProviderOptions,
)
from picard.coverart.providers.urlrels import CoverArtProviderUrlRelationships
from picard.extension_points.cover_art_providers import (
ext_point_cover_art_providers,
register_cover_art_provider,
)
# named tuples used by cover_art_providers()
ProviderTuple = namedtuple('ProviderTuple', 'name title enabled cls')
PInfoTuple = namedtuple('PInfoTuple', 'position enabled')
def cover_art_providers():
config = get_config()
# build a defaultdict with provider name as key, and PInfoTuple as value
order = defaultdict(lambda: PInfoTuple(position=666, enabled=False))
for position, (name, enabled) in enumerate(config.setting['ca_providers']):
order[name] = PInfoTuple(position=position, enabled=enabled)
# use previously built dict to order providers, according to current ca_providers
# (yet) unknown providers are placed at the end, disabled
for p in sorted(ext_point_cover_art_providers, key=lambda p: (order[p.name].position, p.name)):
yield ProviderTuple(name=p.name, title=p.title, enabled=order[p.name].enabled, cls=p)
__providers = [
CoverArtProviderLocal,
CoverArtProviderCaa,
CoverArtProviderUrlRelationships,
CoverArtProviderCaaReleaseGroup,
]
for provider in __providers:
register_cover_art_provider(provider)
| 2,796
|
Python
|
.py
| 64
| 41.0625
| 99
| 0.778309
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,952
|
urlrels.py
|
metabrainz_picard/picard/coverart/providers/urlrels.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2007 Oliver Charles
# Copyright (C) 2007, 2010-2011 Lukáš Lalinský
# Copyright (C) 2007-2011, 2020 Philipp Wolfer
# Copyright (C) 2011 Michael Wiencek
# Copyright (C) 2011-2012 Wieland Hoffmann
# Copyright (C) 2013-2015, 2018-2019, 2021, 2023-2024 Laurent Monin
# Copyright (C) 2017 Sambhav Kothari
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from picard import log
from picard.coverart.image import CoverArtImage
from picard.coverart.providers.provider import CoverArtProvider
from picard.i18n import N_
class CoverArtProviderUrlRelationships(CoverArtProvider):
"""Use cover art link and has_cover_art_at MusicBrainz relationships to get
cover art"""
NAME = "UrlRelationships"
TITLE = N_("Allowed Cover Art URLs")
def queue_images(self):
self.match_url_relations(('cover art link', 'has_cover_art_at'),
self._queue_from_relationship)
return CoverArtProvider.FINISHED
def _queue_from_relationship(self, url):
log.debug("Found cover art link in URL relationship")
self.queue_put(CoverArtImage(url))
| 1,854
|
Python
|
.py
| 41
| 41.780488
| 80
| 0.751387
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,953
|
filters.py
|
metabrainz_picard/picard/coverart/processing/filters.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2024 Giorgio Fontanive
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from picard import log
from picard.config import get_config
from picard.extension_points.cover_art_filters import (
register_cover_art_filter,
register_cover_art_metadata_filter,
)
def _check_threshold_size(width, height):
config = get_config()
if not config.setting['filter_cover_by_size']:
return True
# If the given width or height is -1, that dimension is not considered
min_width = config.setting['cover_minimum_width'] if width != -1 else -1
min_height = config.setting['cover_minimum_height'] if height != -1 else -1
if width < min_width or height < min_height:
log.debug(
"Discarding cover art due to size. Image size: %d x %d. Minimum: %d x %d",
width,
height,
min_width,
min_height
)
return False
return True
def size_filter(data, image_info, album, coverartimage):
return _check_threshold_size(image_info.width, image_info.height)
def size_metadata_filter(metadata):
if 'width' not in metadata or 'height' not in metadata:
return True
return _check_threshold_size(metadata['width'], metadata['height'])
def bigger_previous_image_filter(data, image_info, album, coverartimage):
config = get_config()
if config.setting['dont_replace_with_smaller_cover'] and config.setting['save_images_to_tags']:
downloaded_types = coverartimage.normalized_types()
previous_images = album.orig_metadata.images.get_types_dict()
if downloaded_types in previous_images:
previous_image = previous_images[downloaded_types]
if image_info.width < previous_image.width or image_info.height < previous_image.height:
log.debug("Discarding cover art. A bigger image with the same types is already embedded.")
return False
return True
def image_types_filter(data, image_info, album, coverartimage):
config = get_config()
if config.setting['dont_replace_cover_of_types'] and config.setting['save_images_to_tags']:
downloaded_types = set(coverartimage.normalized_types())
never_replace_types = config.setting['dont_replace_included_types']
always_replace_types = config.setting['dont_replace_excluded_types']
previous_image_types = album.orig_metadata.images.get_types_dict()
if downloaded_types.intersection(always_replace_types):
return True
for previous_image_type in previous_image_types:
type_already_embedded = downloaded_types.intersection(previous_image_type)
should_not_replace = downloaded_types.intersection(never_replace_types)
if type_already_embedded and should_not_replace:
log.debug("Discarding cover art. An image with the same type is already embedded.")
return False
return True
register_cover_art_filter(size_filter)
register_cover_art_metadata_filter(size_metadata_filter)
register_cover_art_filter(bigger_previous_image_filter)
register_cover_art_filter(image_types_filter)
| 3,891
|
Python
|
.py
| 79
| 43.278481
| 106
| 0.715715
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,954
|
processors.py
|
metabrainz_picard/picard/coverart/processing/processors.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2024 Giorgio Fontanive
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import time
from PyQt6.QtCore import Qt
from picard import log
from picard.config import get_config
from picard.const.cover_processing import ResizeModes
from picard.extension_points.cover_art_processors import (
ImageProcessor,
ProcessingTarget,
register_cover_art_processor,
)
class ResizeImage(ImageProcessor):
def save_to_file(self):
config = get_config()
return config.setting['cover_file_resize']
def save_to_tags(self):
config = get_config()
return config.setting['cover_tags_resize']
def same_processing(self):
setting = get_config().setting
both_resize = setting['cover_tags_resize'] and setting['cover_file_resize']
same_enlarge = setting['cover_tags_enlarge'] == setting['cover_file_enlarge']
same_width = setting['cover_tags_resize_target_width'] == setting['cover_file_resize_target_width']
same_height = setting['cover_tags_resize_target_height'] == setting['cover_file_resize_target_height']
same_resize_mode = setting['cover_tags_resize_mode'] == setting['cover_file_resize_mode']
return both_resize and same_enlarge and same_width and same_height and same_resize_mode
def run(self, image, target):
start_time = time.time()
config = get_config()
if target == ProcessingTarget.TAGS:
scale_up = config.setting['cover_tags_enlarge']
target_width = config.setting['cover_tags_resize_target_width']
target_height = config.setting['cover_tags_resize_target_height']
resize_mode = config.setting['cover_tags_resize_mode']
else:
scale_up = config.setting['cover_file_enlarge']
target_width = config.setting['cover_file_resize_target_width']
target_height = config.setting['cover_file_resize_target_height']
resize_mode = config.setting['cover_file_resize_mode']
width_scale_factor = target_width / image.info.width
height_scale_factor = target_height / image.info.height
if resize_mode == ResizeModes.MAINTAIN_ASPECT_RATIO:
scale_factor = min(width_scale_factor, height_scale_factor)
elif resize_mode == ResizeModes.SCALE_TO_WIDTH:
scale_factor = width_scale_factor
elif resize_mode == ResizeModes.SCALE_TO_HEIGHT:
scale_factor = height_scale_factor
else: # crop or stretch
scale_factor = max(width_scale_factor, height_scale_factor)
if scale_factor == 1 or scale_factor > 1 and not scale_up:
# no resizing needed
return
qimage = image.get_qimage()
new_width = image.info.width * scale_factor
new_height = image.info.height * scale_factor
if resize_mode == ResizeModes.STRETCH_TO_FIT:
new_width = image.info.width * width_scale_factor
new_height = image.info.height * height_scale_factor
scaled_image = qimage.scaled(int(new_width), int(new_height), Qt.AspectRatioMode.IgnoreAspectRatio)
if resize_mode == ResizeModes.CROP_TO_FIT:
cutoff_width = (scaled_image.width() - target_width) // 2
cutoff_height = (scaled_image.height() - target_height) // 2
scaled_image = scaled_image.copy(cutoff_width, cutoff_height, target_width, target_height)
log.debug(
"Resized cover art from %d x %d to %d x %d in %.2f ms",
image.info.width,
image.info.height,
scaled_image.width(),
scaled_image.height(),
1000 * (time.time() - start_time)
)
image.info.width = scaled_image.width()
image.info.height = scaled_image.height()
image.info.datalen = scaled_image.sizeInBytes()
image.set_result(scaled_image)
class ConvertImage(ImageProcessor):
_format_aliases = {
"jpeg": {"jpg", "jpeg"},
"png": {"png"},
"webp": {"webp"},
"tiff": {"tif", "tiff"},
}
def save_to_tags(self):
config = get_config()
return config.setting['cover_tags_convert_images']
def save_to_file(self):
config = get_config()
return config.setting['cover_file_convert_images']
def same_processing(self):
config = get_config()
same_format = config.setting['cover_tags_convert_to_format'] == config.setting['cover_file_convert_to_format']
return self.save_to_file() and self.save_to_tags() and same_format
def run(self, image, target):
config = get_config()
if target == ProcessingTarget.TAGS:
new_format = config.setting['cover_tags_convert_to_format'].lower()
else:
new_format = config.setting['cover_file_convert_to_format'].lower()
previous_format = image.info.format
if previous_format in self._format_aliases[new_format]:
return
image.info.extension = f".{new_format}"
image.info.mime = f"image/{new_format}"
log.debug("Changed cover art format from %s to %s", previous_format, new_format)
register_cover_art_processor(ResizeImage)
register_cover_art_processor(ConvertImage)
| 5,990
|
Python
|
.py
| 124
| 40.58871
| 118
| 0.66621
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,955
|
__init__.py
|
metabrainz_picard/picard/coverart/processing/__init__.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2024 Giorgio Fontanive
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from functools import partial
from queue import Queue
import time
from picard import log
from picard.config import get_config
from picard.const.cover_processing import COVER_PROCESSING_SLEEP
from picard.coverart.image import (
CoverArtImageError,
CoverArtImageIOError,
)
from picard.coverart.processing import ( # noqa: F401 # pylint: disable=unused-import
filters,
processors,
)
from picard.extension_points.cover_art_filters import (
ext_point_cover_art_filters,
ext_point_cover_art_metadata_filters,
)
from picard.extension_points.cover_art_processors import (
CoverArtProcessingError,
ProcessingImage,
ProcessingTarget,
get_cover_art_processors,
)
from picard.util import thread
from picard.util.imageinfo import IdentificationError
def run_image_filters(data, image_info, album, coverartimage):
for f in ext_point_cover_art_filters:
if not f(data, image_info, album, coverartimage):
return False
return True
def run_image_metadata_filters(metadata):
for f in ext_point_cover_art_metadata_filters:
if not f(metadata):
return False
return True
def handle_processing_exceptions(func):
def wrapper(self, *args, **kwargs):
try:
func(self, *args, **kwargs)
except (CoverArtImageError, CoverArtProcessingError) as e:
self.errors.put(e)
return wrapper
class CoverArtImageProcessing:
def __init__(self, album):
self.album = album
self.queues = get_cover_art_processors()
self.task_counter = thread.TaskCounter()
self.errors = Queue()
@handle_processing_exceptions
def _run_processors_queue(self, coverartimage, initial_data, start_time, image, target):
data = initial_data
try:
queue = self.queues[target]
for processor in queue:
processor.run(image, target)
time.sleep(COVER_PROCESSING_SLEEP)
data = image.get_result()
except CoverArtProcessingError as e:
raise e
finally:
if target == ProcessingTarget.TAGS:
coverartimage.set_tags_data(data)
else:
coverartimage.set_external_file_data(data)
log.debug(
"Image processing for %s cover art image %s finished in %d ms",
target.name,
coverartimage,
1000 * (time.time() - start_time)
)
@handle_processing_exceptions
def _run_image_processors(self, coverartimage, initial_data, image_info):
config = get_config()
try:
start_time = time.time()
image = ProcessingImage(initial_data, image_info)
for processor in self.queues[ProcessingTarget.BOTH]:
processor.run(image, ProcessingTarget.BOTH)
time.sleep(COVER_PROCESSING_SLEEP)
run_queue_common = partial(self._run_processors_queue, coverartimage, initial_data, start_time)
if config.setting['save_images_to_files']:
run_queue = partial(run_queue_common, image.copy(), ProcessingTarget.FILE)
thread.run_task(run_queue, task_counter=self.task_counter)
if config.setting['save_images_to_tags']:
run_queue = partial(run_queue_common, image.copy(), ProcessingTarget.TAGS)
thread.run_task(run_queue, task_counter=self.task_counter)
else:
coverartimage.set_tags_data(initial_data)
except IdentificationError as e:
raise CoverArtProcessingError(e)
except CoverArtProcessingError as e:
coverartimage.set_tags_data(initial_data)
if config.setting['save_images_to_files']:
coverartimage.set_external_file_data(initial_data)
raise e
def run_image_processors(self, coverartimage, initial_data, image_info):
if coverartimage.can_be_processed:
run_processors = partial(self._run_image_processors, coverartimage, initial_data, image_info)
thread.run_task(run_processors, task_counter=self.task_counter)
else:
set_data = partial(handle_processing_exceptions, coverartimage.set_tags_data, initial_data)
thread.run_task(set_data, task_counter=self.task_counter)
def wait_for_processing(self):
self.task_counter.wait_for_tasks()
has_io_error = False
while not self.errors.empty():
error = self.errors.get()
self.album.error_append(error)
if isinstance(error, CoverArtImageIOError):
has_io_error = True
return has_io_error
| 5,530
|
Python
|
.py
| 131
| 34.229008
| 107
| 0.674034
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,956
|
formats.py
|
metabrainz_picard/picard/extension_points/formats.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2006-2008, 2012 Lukáš Lalinský
# Copyright (C) 2008 Will
# Copyright (C) 2010, 2014, 2018-2020, 2023-2024 Philipp Wolfer
# Copyright (C) 2013 Michael Wiencek
# Copyright (C) 2013, 2017-2024 Laurent Monin
# Copyright (C) 2016-2018 Sambhav Kothari
# Copyright (C) 2017 Sophist-UK
# Copyright (C) 2017 Ville Skyttä
# Copyright (C) 2020 Gabriel Ferreira
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from picard.plugin import ExtensionPoint
ext_point_formats = ExtensionPoint(label='formats')
_formats_extensions = {}
def register_format(file_format):
ext_point_formats.register(file_format.__module__, file_format)
for ext in file_format.EXTENSIONS:
_formats_extensions[ext.lower()] = file_format
def ext_to_format(ext):
return _formats_extensions.get(ext.lower(), None)
| 1,553
|
Python
|
.py
| 36
| 41.277778
| 80
| 0.76494
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,957
|
cover_art_processors.py
|
metabrainz_picard/picard/extension_points/cover_art_processors.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2024 Giorgio Fontanive
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from copy import copy
from enum import IntEnum
from PyQt6.QtCore import QBuffer
from PyQt6.QtGui import QImage
from picard.plugin import ExtensionPoint
from picard.util import imageinfo
ext_point_cover_art_processors = ExtensionPoint(label='cover_art_processors')
class CoverArtProcessingError(Exception):
pass
class CoverArtEncodingError(CoverArtProcessingError):
pass
class ProcessingTarget(IntEnum):
TAGS = 0
FILE = 1
BOTH = 2
class ProcessingImage:
def __init__(self, image, info=None):
self.set_result(image)
if info is None and not isinstance(image, QImage):
self.info = imageinfo.identify(image)
else:
self.info = info
def copy(self):
return ProcessingImage(self._qimage.copy(), copy(self.info))
def set_result(self, image):
if isinstance(image, QImage):
self._qimage = image
else:
self._qimage = QImage.fromData(image)
def get_qimage(self):
return self._qimage
def get_result(self, image_format=None, quality=90):
if image_format is None:
image_format = self.info.format
buffer = QBuffer()
if not self._qimage.save(buffer, image_format, quality=quality):
raise CoverArtEncodingError(f"Failed to encode into {image_format}")
qbytearray = buffer.data()
return qbytearray.data()
class ImageProcessor:
def save_to_tags(self):
return False
def save_to_file(self):
return False
def same_processing(self):
return False
def run(self, image, target):
pass
def get_cover_art_processors():
queues = dict.fromkeys(list(ProcessingTarget), [])
for processor in ext_point_cover_art_processors:
if processor.same_processing():
queues[ProcessingTarget.BOTH].append(processor)
else:
if processor.save_to_tags():
queues[ProcessingTarget.TAGS].append(processor)
if processor.save_to_file():
queues[ProcessingTarget.FILE].append(processor)
return queues
def register_cover_art_processor(cover_art_processor):
instance = cover_art_processor()
ext_point_cover_art_processors.register(cover_art_processor.__module__, instance)
| 3,122
|
Python
|
.py
| 81
| 32.753086
| 85
| 0.706273
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,958
|
options_pages.py
|
metabrainz_picard/picard/extension_points/options_pages.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2006-2007 Lukáš Lalinský
# Copyright (C) 2009 Nikolai Prokoschenko
# Copyright (C) 2009, 2019-2022 Philipp Wolfer
# Copyright (C) 2013, 2015, 2018-2024 Laurent Monin
# Copyright (C) 2016-2017 Sambhav Kothari
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from picard.plugin import ExtensionPoint
ext_point_options_pages = ExtensionPoint(label='options_pages')
def register_options_page(page_class):
ext_point_options_pages.register(page_class.__module__, page_class)
| 1,232
|
Python
|
.py
| 27
| 44.185185
| 80
| 0.778613
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,959
|
cover_art_providers.py
|
metabrainz_picard/picard/extension_points/cover_art_providers.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2014-2015, 2018-2021, 2023-2024 Laurent Monin
# Copyright (C) 2015 Rahul Raturi
# Copyright (C) 2016 Ville Skytt√§
# Copyright (C) 2016 Wieland Hoffmann
# Copyright (C) 2017 Sambhav Kothari
# Copyright (C) 2019-2021 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from picard.extension_points.options_pages import register_options_page
from picard.plugin import ExtensionPoint
ext_point_cover_art_providers = ExtensionPoint(label='cover_art_providers')
def register_cover_art_provider(provider):
ext_point_cover_art_providers.register(provider.__module__, provider)
if hasattr(provider, 'OPTIONS') and provider.OPTIONS:
if not hasattr(provider.OPTIONS, 'NAME'):
provider.OPTIONS.NAME = provider.name.lower().replace(' ', '_')
if not hasattr(provider.OPTIONS, 'TITLE'):
provider.OPTIONS.TITLE = provider.title
register_options_page(provider.OPTIONS)
| 1,677
|
Python
|
.py
| 35
| 45.171429
| 80
| 0.757483
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,960
|
event_hooks.py
|
metabrainz_picard/picard/extension_points/event_hooks.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2004 Robert Kaye
# Copyright (C) 2006-2009, 2011-2013, 2017 Lukáš Lalinský
# Copyright (C) 2007-2011, 2014-2015, 2018-2024 Philipp Wolfer
# Copyright (C) 2008 Gary van der Merwe
# Copyright (C) 2008 Hendrik van Antwerpen
# Copyright (C) 2008 ojnkpjg
# Copyright (C) 2008-2009 Nikolai Prokoschenko
# Copyright (C) 2009 Carlin Mangar
# Copyright (C) 2009 David Hilton
# Copyright (C) 2011-2012 Chad Wilson
# Copyright (C) 2011-2014, 2019 Michael Wiencek
# Copyright (C) 2012 Erik Wasser
# Copyright (C) 2012 Johannes Weißl
# Copyright (C) 2012 noobie
# Copyright (C) 2012-2014, 2016-2017 Wieland Hoffmann
# Copyright (C) 2013, 2018 Calvin Walton
# Copyright (C) 2013-2014 Ionuț Ciocîrlan
# Copyright (C) 2013-2015, 2017, 2021 Sophist-UK
# Copyright (C) 2013-2015, 2017-2024 Laurent Monin
# Copyright (C) 2016 Rahul Raturi
# Copyright (C) 2016 Suhas
# Copyright (C) 2016 Ville Skyttä
# Copyright (C) 2016-2018 Sambhav Kothari
# Copyright (C) 2017-2018 Antonio Larrosa
# Copyright (C) 2018 Vishal Choudhary
# Copyright (C) 2019 Joel Lintunen
# Copyright (C) 2020 Ray Bouchard
# Copyright (C) 2020-2021 Gabriel Ferreira
# Copyright (C) 2021 Petit Minion
# Copyright (C) 2021, 2023 Bob Swift
# Copyright (C) 2022 skelly37
# Copyright (C) 2024 Suryansh Shakya
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from picard.album import album_post_removal_processors
from picard.file import (
file_post_addition_to_track_processors,
file_post_load_processors,
file_post_removal_to_track_processors,
file_post_save_processors,
)
def register_album_post_removal_processor(function, priority=0):
"""Registers an album-removed processor.
Args:
function: function to call after album removal, it will be passed the album object
priority: optional, 0 by default
Returns:
None
"""
album_post_removal_processors.register(function.__module__, function, priority)
def register_file_post_load_processor(function, priority=0):
"""Registers a file-loaded processor.
Args:
function: function to call after file has been loaded, it will be passed the file object
priority: optional, 0 by default
Returns:
None
"""
file_post_load_processors.register(function.__module__, function, priority)
def register_file_post_addition_to_track_processor(function, priority=0):
"""Registers a file-added-to-track processor.
Args:
function: function to call after file addition, it will be passed the track and file objects
priority: optional, 0 by default
Returns:
None
"""
file_post_addition_to_track_processors.register(function.__module__, function, priority)
def register_file_post_removal_from_track_processor(function, priority=0):
"""Registers a file-removed-from-track processor.
Args:
function: function to call after file removal, it will be passed the track and file objects
priority: optional, 0 by default
Returns:
None
"""
file_post_removal_to_track_processors.register(function.__module__, function, priority)
def register_file_post_save_processor(function, priority=0):
"""Registers file saved processor.
Args:
function: function to call after save, it will be passed the file object
priority: optional, 0 by default
Returns:
None
"""
file_post_save_processors.register(function.__module__, function, priority)
| 4,198
|
Python
|
.py
| 102
| 37.617647
| 100
| 0.741714
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,961
|
cover_art_filters.py
|
metabrainz_picard/picard/extension_points/cover_art_filters.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2024 Giorgio Fontanive
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from picard.plugin import ExtensionPoint
ext_point_cover_art_filters = ExtensionPoint(label='cover_art_filters')
ext_point_cover_art_metadata_filters = ExtensionPoint(label='cover_art_metadata_filters')
def register_cover_art_filter(cover_art_filter):
ext_point_cover_art_filters.register(cover_art_filter.__module__, cover_art_filter)
def register_cover_art_metadata_filter(cover_art_metadata_filter):
ext_point_cover_art_metadata_filters.register(cover_art_metadata_filter.__module__, cover_art_metadata_filter)
| 1,352
|
Python
|
.py
| 26
| 50.423077
| 114
| 0.786202
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,962
|
metadata.py
|
metabrainz_picard/picard/extension_points/metadata.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2006-2008, 2011 Lukáš Lalinský
# Copyright (C) 2009, 2015, 2018-2023 Philipp Wolfer
# Copyright (C) 2011-2014 Michael Wiencek
# Copyright (C) 2012 Chad Wilson
# Copyright (C) 2012 Johannes Weißl
# Copyright (C) 2012-2014, 2018, 2020 Wieland Hoffmann
# Copyright (C) 2013-2014, 2016, 2018-2024 Laurent Monin
# Copyright (C) 2013-2014, 2017 Sophist-UK
# Copyright (C) 2016 Rahul Raturi
# Copyright (C) 2016-2017 Sambhav Kothari
# Copyright (C) 2017-2018 Antonio Larrosa
# Copyright (C) 2018 Vishal Choudhary
# Copyright (C) 2018 Xincognito10
# Copyright (C) 2020 Gabriel Ferreira
# Copyright (C) 2020 Ray Bouchard
# Copyright (C) 2021 Petit Minion
# Copyright (C) 2022 Bob Swift
# Copyright (C) 2022 skelly37
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from picard.metadata import (
album_metadata_processors,
track_metadata_processors,
)
def register_album_metadata_processor(function, priority=0):
"""Registers new album-level metadata processor."""
album_metadata_processors.register(function.__module__, function, priority)
def register_track_metadata_processor(function, priority=0):
"""Registers new track-level metadata processor."""
track_metadata_processors.register(function.__module__, function, priority)
| 2,005
|
Python
|
.py
| 46
| 41.847826
| 80
| 0.770139
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,963
|
__init__.py
|
metabrainz_picard/picard/extension_points/__init__.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2024 Laurent Monin
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
| 819
|
Python
|
.py
| 19
| 42.105263
| 80
| 0.77375
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,964
|
script_functions.py
|
metabrainz_picard/picard/extension_points/script_functions.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2006-2009, 2012 Lukáš Lalinský
# Copyright (C) 2007 Javier Kohen
# Copyright (C) 2008-2011, 2014-2015, 2018-2021, 2023 Philipp Wolfer
# Copyright (C) 2009 Carlin Mangar
# Copyright (C) 2009 Nikolai Prokoschenko
# Copyright (C) 2011-2012 Michael Wiencek
# Copyright (C) 2012 Chad Wilson
# Copyright (C) 2012 stephen
# Copyright (C) 2012, 2014, 2017, 2021 Wieland Hoffmann
# Copyright (C) 2013-2014, 2017-2024 Laurent Monin
# Copyright (C) 2014, 2017, 2021 Sophist-UK
# Copyright (C) 2016-2017 Sambhav Kothari
# Copyright (C) 2016-2017 Ville Skyttä
# Copyright (C) 2017-2018 Antonio Larrosa
# Copyright (C) 2018 Calvin Walton
# Copyright (C) 2018 virusMac
# Copyright (C) 2020-2023 Bob Swift
# Copyright (C) 2021 Adam James
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from collections import namedtuple
from inspect import getfullargspec
try:
from markdown import markdown
except ImportError:
markdown = None
from picard.i18n import gettext as _
from picard.plugin import ExtensionPoint
ext_point_script_functions = ExtensionPoint(label='script_functions')
Bound = namedtuple('Bound', ['lower', 'upper'])
class FunctionRegistryItem:
def __init__(self, function, eval_args, argcount, documentation=None,
name=None, module=None):
self.function = function
self.eval_args = eval_args
self.argcount = argcount
self.documentation = documentation
self.name = name
self.module = module
def __repr__(self):
return '{classname}({me.function}, {me.eval_args}, {me.argcount}, {doc})'.format(
classname=self.__class__.__name__,
me=self,
doc='"""{0}"""'.format(self.documentation) if self.documentation else None
)
def _postprocess(self, data, postprocessor):
if postprocessor is not None:
data = postprocessor(data, function=self)
return data
def markdowndoc(self, postprocessor=None):
if self.documentation is not None:
ret = _(self.documentation)
else:
ret = ''
return self._postprocess(ret, postprocessor)
def htmldoc(self, postprocessor=None):
if markdown is not None:
ret = markdown(self.markdowndoc())
else:
ret = ''
return self._postprocess(ret, postprocessor)
def register_script_function(function, name=None, eval_args=True,
check_argcount=True, documentation=None):
"""Registers a script function. If ``name`` is ``None``,
``function.__name__`` will be used.
If ``eval_args`` is ``False``, the arguments will not be evaluated before being
passed to ``function``.
If ``check_argcount`` is ``False`` the number of arguments passed to the
function will not be verified."""
args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations = getfullargspec(function)
required_kwonlyargs = len(kwonlyargs)
if kwonlydefaults is not None:
required_kwonlyargs -= len(kwonlydefaults.keys())
if required_kwonlyargs:
raise TypeError("Functions with required keyword-only parameters are not supported")
args = len(args) - 1 # -1 for the parser
varargs = varargs is not None
defaults = len(defaults) if defaults else 0
argcount = Bound(args - defaults, args if not varargs else None)
if name is None:
name = function.__name__
ext_point_script_functions.register(
function.__module__,
(
name,
FunctionRegistryItem(
function,
eval_args,
argcount if argcount and check_argcount else False,
documentation=documentation,
name=name,
module=function.__module__,
)
)
)
def script_function(name=None, eval_args=True, check_argcount=True, prefix='func_', documentation=None):
"""Decorator helper to register script functions
It calls ``register_script_function()`` and share same arguments
Extra optional arguments:
``prefix``: define the prefix to be removed from defined function to name script function
By default, ``func_foo`` will create ``foo`` script function
Example:
@script_function(eval_args=False)
def func_myscriptfunc():
...
"""
def script_function_decorator(func):
fname = func.__name__
if name is None and prefix and fname.startswith(prefix):
sname = fname[len(prefix):]
else:
sname = name
register_script_function(
func,
name=sname,
eval_args=eval_args,
check_argcount=check_argcount,
documentation=documentation
)
return func
return script_function_decorator
| 5,604
|
Python
|
.py
| 137
| 34.124088
| 104
| 0.670958
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,965
|
ui_init.py
|
metabrainz_picard/picard/extension_points/ui_init.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2006-2008, 2011-2012, 2014 Lukáš Lalinský
# Copyright (C) 2007 Nikolai Prokoschenko
# Copyright (C) 2008 Gary van der Merwe
# Copyright (C) 2008 Robert Kaye
# Copyright (C) 2008 Will
# Copyright (C) 2008-2010, 2015, 2018-2023 Philipp Wolfer
# Copyright (C) 2009 Carlin Mangar
# Copyright (C) 2009 David Hilton
# Copyright (C) 2011-2012 Chad Wilson
# Copyright (C) 2011-2013, 2015-2017 Wieland Hoffmann
# Copyright (C) 2011-2014 Michael Wiencek
# Copyright (C) 2013-2014, 2017 Sophist-UK
# Copyright (C) 2013-2024 Laurent Monin
# Copyright (C) 2015 Ohm Patel
# Copyright (C) 2015 samithaj
# Copyright (C) 2016 Rahul Raturi
# Copyright (C) 2016 Simon Legner
# Copyright (C) 2016-2017 Sambhav Kothari
# Copyright (C) 2017 Antonio Larrosa
# Copyright (C) 2017 Frederik “Freso” S. Olesen
# Copyright (C) 2018 Kartik Ohri
# Copyright (C) 2018 Vishal Choudhary
# Copyright (C) 2018 virusMac
# Copyright (C) 2018, 2021-2023 Bob Swift
# Copyright (C) 2019 Timur Enikeev
# Copyright (C) 2020-2021 Gabriel Ferreira
# Copyright (C) 2021 Petit Minion
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from picard.plugin import ExtensionPoint
ext_point_ui_init = ExtensionPoint(label='ui_init')
def register_ui_init(function):
ext_point_ui_init.register(function.__module__, function)
| 2,037
|
Python
|
.py
| 49
| 40.244898
| 80
| 0.767713
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,966
|
item_actions.py
|
metabrainz_picard/picard/extension_points/item_actions.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2006-2008, 2011-2012 Lukáš Lalinský
# Copyright (C) 2007 Robert Kaye
# Copyright (C) 2008 Gary van der Merwe
# Copyright (C) 2008 Hendrik van Antwerpen
# Copyright (C) 2008-2011, 2014-2015, 2018-2024 Philipp Wolfer
# Copyright (C) 2009 Carlin Mangar
# Copyright (C) 2009 Nikolai Prokoschenko
# Copyright (C) 2011 Tim Blechmann
# Copyright (C) 2011-2012 Chad Wilson
# Copyright (C) 2011-2013 Michael Wiencek
# Copyright (C) 2012 Your Name
# Copyright (C) 2012-2013 Wieland Hoffmann
# Copyright (C) 2013-2014, 2016, 2018-2024 Laurent Monin
# Copyright (C) 2013-2014, 2017, 2020 Sophist-UK
# Copyright (C) 2016 Rahul Raturi
# Copyright (C) 2016 Simon Legner
# Copyright (C) 2016 Suhas
# Copyright (C) 2016-2017 Sambhav Kothari
# Copyright (C) 2018 Vishal Choudhary
# Copyright (C) 2020-2021 Gabriel Ferreira
# Copyright (C) 2021 Bob Swift
# Copyright (C) 2021 Louis Sautier
# Copyright (C) 2021 Petit Minion
# Copyright (C) 2023 certuna
# Copyright (C) 2024 Suryansh Shakya
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from PyQt6 import (
QtCore,
QtGui,
)
from picard.plugin import ExtensionPoint
class BaseAction(QtGui.QAction):
NAME = "Unknown"
MENU = []
def __init__(self, parent=None):
super().__init__(self.NAME, parent=parent)
self.tagger = QtCore.QCoreApplication.instance()
self.triggered.connect(self.__callback)
def __callback(self):
objs = self.tagger.window.selected_objects
self.callback(objs)
def callback(self, objs):
raise NotImplementedError
ext_point_album_actions = ExtensionPoint(label='album_actions')
ext_point_cluster_actions = ExtensionPoint(label='cluster_actions')
ext_point_clusterlist_actions = ExtensionPoint(label='clusterlist_actions')
ext_point_file_actions = ExtensionPoint(label='file_actions')
ext_point_track_actions = ExtensionPoint(label='track_actions')
def register_album_action(action):
ext_point_album_actions.register(action.__module__, action)
def register_cluster_action(action):
ext_point_cluster_actions.register(action.__module__, action)
def register_clusterlist_action(action):
ext_point_clusterlist_actions.register(action.__module__, action)
def register_file_action(action):
ext_point_file_actions.register(action.__module__, action)
def register_track_action(action):
ext_point_track_actions.register(action.__module__, action)
| 3,152
|
Python
|
.py
| 75
| 39.453333
| 80
| 0.757774
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,967
|
serializer.py
|
metabrainz_picard/picard/script/serializer.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2021, 2023 Bob Swift
# Copyright (C) 2021-2024 Philipp Wolfer
# Copyright (C) 2021-2024 Laurent Monin
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from copy import deepcopy
import datetime
from enum import (
IntEnum,
unique,
)
import os
from typing import Mapping
import uuid
import yaml
from PyQt6 import (
QtCore,
QtWidgets,
)
from picard import log
from picard.const import SCRIPT_LANGUAGE_VERSION
from picard.const.defaults import DEFAULT_SCRIPT_NAME
from picard.i18n import (
N_,
gettext as _,
)
from picard.util import make_filename_from_title
from picard.ui.util import FileDialog
@unique
class ScriptSerializerType(IntEnum):
"""Picard Script object types
"""
BASE = 0
TAGGER = 1
FILENAMING = 2
class ScriptSerializerError(Exception):
"""Base exception class for ScriptSerializer errors"""
class ScriptSerializerImportExportError(ScriptSerializerError):
def __init__(self, *args, format=None, filename=None, error_msg=None):
super().__init__(*args)
self.format = format
self.filename = filename
self.error_msg = error_msg
class ScriptSerializerImportError(ScriptSerializerImportExportError):
"""Exception raised during script import"""
class ScriptSerializerExportError(ScriptSerializerImportExportError):
"""Exception raised during script export"""
class ScriptSerializerFromFileError(ScriptSerializerError):
"""Exception raised when converting a file to a ScriptSerializer"""
class MultilineLiteral(str):
@staticmethod
def yaml_presenter(dumper, data):
if data:
data = data.rstrip() + '\n'
return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|')
yaml.add_representer(MultilineLiteral, MultilineLiteral.yaml_presenter)
class ScriptSerializer():
"""Base class for Picard script objects.
"""
# Base class developed to support future tagging script class as possible replacement for currently used tuples in config.setting["list_of_scripts"].
TYPE = ScriptSerializerType.BASE
OUTPUT_FIELDS = ('title', 'script_language_version', 'script', 'id')
# Don't automatically trigger changing the `script_last_updated` property when updating these properties.
_last_updated_ignore_list = {'last_updated', 'id'}
def __init__(self, script='', title='', id=None, last_updated=None, script_language_version=None):
"""Base class for Picard script objects
Args:
script (str): Text of the script.
title (str): Title of the script.
id (str): ID code for the script. Defaults to a system generated uuid.
last_updated (str): The UTC date and time when the script was last updated. Defaults to current date/time.
"""
self.title = title if title else DEFAULT_SCRIPT_NAME
self.script = script
if not id:
self._set_new_id()
else:
self.id = id
if last_updated is None:
self.update_last_updated()
else:
self.last_updated = last_updated
if script_language_version is None or not script_language_version:
self.script_language_version = SCRIPT_LANGUAGE_VERSION
else:
self.script_language_version = script_language_version
def _set_new_id(self):
"""Sets the ID of the script to a new system generated uuid.
"""
self.id = str(uuid.uuid4())
def __getitem__(self, setting):
"""A safe way of getting the value of the specified property setting, because
it handles missing properties by returning None rather than raising an exception.
Args:
setting (str): The setting whose value to return.
Returns:
any: The value of the specified setting, or None if the setting was not found.
"""
if hasattr(self, setting):
value = getattr(self, setting)
if isinstance(value, str):
value = value.strip()
return value
return None
@property
def script(self):
return self._script
@script.setter
def script(self, value):
self._script = MultilineLiteral(value)
@staticmethod
def make_last_updated():
"""Provide consistently formatted last updated string.
Returns:
str: Last updated string from current date and time
"""
return datetime.datetime.now(datetime.timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC')
def update_last_updated(self):
"""Update the last updated attribute to the current UTC date and time.
"""
self.last_updated = self.make_last_updated()
def update_script_setting(self, **kwargs):
"""Updates the value of the specified properties.
Args:
**kwargs: Properties to update in the form `property=value`.
"""
self.update_from_dict(kwargs)
def update_from_dict(self, settings):
"""Updates the values of the properties based on the contents of the dictionary provided.
Properties in the `settings` dictionary that are not found in the script object are ignored.
Args:
settings (dict): The settings to update.
"""
updated = False
for key, value in settings.items():
if value is not None and hasattr(self, key):
if isinstance(value, str):
value = value.strip()
setattr(self, key, value)
if key not in self._last_updated_ignore_list:
updated = True
# Don't overwrite `last_updated` with a generated value if a last_updated value has been provided.
if updated and 'last_updated' not in settings:
self.update_last_updated()
def to_dict(self):
"""Generate a dictionary containing the object's OUTPUT_FIELDS.
Returns:
dict: Dictionary of the object's OUTPUT_FIELDS
"""
items = {key: getattr(self, key) for key in self.OUTPUT_FIELDS}
items['description'] = str(items['description'])
items['script'] = str(items['script'])
return items
def export_script(self, parent=None):
"""Export the script to a file.
"""
# return _export_script_dialog(script_item=self, parent=parent)
FILE_ERROR_EXPORT = N_('Error exporting file "%(filename)s": %(error)s.')
default_script_directory = os.path.normpath(QtCore.QStandardPaths.writableLocation(QtCore.QStandardPaths.StandardLocation.DocumentsLocation))
default_script_extension = "ptsp"
script_filename = ".".join((self.filename, default_script_extension))
default_path = os.path.normpath(os.path.join(default_script_directory, script_filename))
dialog_title = _("Export Script File")
dialog_file_types = self._get_dialog_filetypes()
filename, file_type = FileDialog.getSaveFileName(
parent=parent,
caption=dialog_title,
dir=default_path,
filter=dialog_file_types,
)
if not filename:
return False
# Fix issue where Qt may set the extension twice
(name, ext) = os.path.splitext(filename)
if ext and str(name).endswith('.' + ext):
filename = name
log.debug("Exporting script file: %s", filename)
if file_type == self._file_types()['package']:
script_text = self.to_yaml()
else:
script_text = self.script + "\n"
try:
with open(filename, 'w', encoding='utf-8') as o_file:
o_file.write(script_text)
except OSError as error:
raise ScriptSerializerExportError(format=FILE_ERROR_EXPORT, filename=filename, error_msg=error.strerror)
dialog = QtWidgets.QMessageBox(
QtWidgets.QMessageBox.Icon.Information,
_("Export Script"),
_("Script successfully exported to %s") % filename,
QtWidgets.QMessageBox.StandardButton.Ok,
parent
)
dialog.exec()
return True
@classmethod
def import_script(cls, parent=None):
"""Import a script from a file.
"""
FILE_ERROR_IMPORT = N_('Error importing "%(filename)s": %(error)s')
FILE_ERROR_DECODE = N_('Error decoding "%(filename)s": %(error)s')
dialog_title = _("Import Script File")
dialog_file_types = cls._get_dialog_filetypes()
default_script_directory = os.path.normpath(QtCore.QStandardPaths.writableLocation(QtCore.QStandardPaths.StandardLocation.DocumentsLocation))
filename, file_type = FileDialog.getOpenFileName(
parent=parent,
caption=dialog_title,
dir=default_script_directory,
filter=dialog_file_types,
)
if not filename:
return None
log.debug("Importing script file: %s", filename)
try:
with open(filename, 'r', encoding='utf-8') as i_file:
file_content = i_file.read()
except OSError as error:
raise ScriptSerializerImportError(format=FILE_ERROR_IMPORT, filename=filename, error_msg=error.strerror)
if not file_content.strip():
raise ScriptSerializerImportError(format=FILE_ERROR_IMPORT, filename=filename, error_msg=N_("The file was empty"))
if file_type == cls._file_types()['package']:
try:
return cls().create_from_yaml(file_content)
except ScriptSerializerFromFileError as error:
raise ScriptSerializerImportError(format=FILE_ERROR_DECODE, filename=filename, error_msg=error)
else:
return cls(
title=_("Imported from %s") % filename,
script=file_content.strip()
)
@classmethod
def create_from_dict(cls, script_dict, create_new_id=True):
"""Creates an instance based on the contents of the dictionary provided.
Properties in the dictionary that are not found in the script object are ignored.
Args:
script_dict (dict): Dictionary containing the property settings.
create_new_id (bool, optional): Determines whether a new ID is generated. Defaults to True.
Returns:
object: An instance of the class, populated from the property settings in the dictionary provided.
"""
new_object = cls()
if not isinstance(script_dict, Mapping):
raise ScriptSerializerFromFileError(N_("Argument is not a dictionary"))
if 'title' not in script_dict or 'script' not in script_dict:
raise ScriptSerializerFromFileError(N_("Invalid script package"))
new_object.update_from_dict(script_dict)
if create_new_id or not new_object['id']:
new_object._set_new_id()
return new_object
def copy(self):
"""Create a copy of the current script object with updated title and last updated attributes.
"""
new_object = deepcopy(self)
new_object.update_script_setting(
title=_("%s (Copy)") % self.title,
script_language_version=SCRIPT_LANGUAGE_VERSION,
)
new_object._set_new_id()
return new_object
def to_yaml(self):
"""Converts the properties of the script object to a YAML formatted string. Note that only property
names listed in `OUTPUT_FIELDS` will be included in the output.
Returns:
str: The properties of the script object formatted as a YAML string.
"""
items = {key: getattr(self, key) for key in self.OUTPUT_FIELDS}
return yaml.dump(items, sort_keys=False)
@classmethod
def create_from_yaml(cls, yaml_string, create_new_id=True):
"""Creates an instance based on the contents of the YAML string provided.
Properties in the YAML string that are not found in the script object are ignored.
Args:
yaml_string (str): YAML string containing the property settings.
create_new_id (bool, optional): Determines whether a new ID is generated. Defaults to True.
Returns:
object: An instance of the class, populated from the property settings in the YAML string.
"""
new_object = cls()
yaml_dict = yaml.safe_load(yaml_string)
if not isinstance(yaml_dict, dict):
raise ScriptSerializerFromFileError(N_("File content not a dictionary"))
if 'title' not in yaml_dict or 'script' not in yaml_dict:
raise ScriptSerializerFromFileError(N_("Invalid script package"))
new_object.update_from_dict(yaml_dict)
if create_new_id or not new_object['id']:
new_object._set_new_id()
return new_object
@property
def filename(self):
return make_filename_from_title(self.title, _("Unnamed Script"))
@classmethod
def _file_types(cls):
"""Helper function to provide standard import/export file types (translated).
Returns:
dict: Diction of the standard file types
"""
return {
'all': _("All files") + " (*)",
'script': _("Picard script files") + " (*.pts *.txt)",
'package': _("Picard script package") + " (*.ptsp *.yaml)",
}
@classmethod
def _get_dialog_filetypes(cls):
"""Helper function to build file type string used in the file dialogs.
Returns:
str: File type selection string
"""
file_types = cls._file_types()
return ";;".join((
file_types['package'],
file_types['script'],
file_types['all'],
))
class TaggingScriptInfo(ScriptSerializer):
"""Picard tagging script class
"""
TYPE = ScriptSerializerType.TAGGER
OUTPUT_FIELDS = ('title', 'script_language_version', 'script', 'id')
def __init__(self, script='', title='', id=None, last_updated=None, script_language_version=None):
"""Creates a Picard tagging script object.
Args:
script (str): Text of the script.
title (str): Title of the script.
id (str): ID code for the script. Defaults to a system generated uuid.
last_updated (str): The UTC date and time when the script was last updated. Defaults to current date/time.
"""
super().__init__(script=script, title=title, id=id, last_updated=last_updated, script_language_version=script_language_version)
class FileNamingScriptInfo(ScriptSerializer):
"""Picard file naming script class
"""
TYPE = ScriptSerializerType.FILENAMING
OUTPUT_FIELDS = ('title', 'description', 'author', 'license', 'version', 'last_updated', 'script_language_version', 'script', 'id')
def __init__(
self,
script='',
title='',
id=None,
author='',
description='',
license='',
version='',
last_updated=None,
script_language_version=None,
**kwargs, # Catch additional (deprecated) arguments to avoid error in prior version config_upgrade functions.
):
"""Creates a Picard file naming script object.
Args:
script (str): Text of the script.
title (str): Title of the script.
id (str): ID code for the script. Defaults to a system generated uuid.
author (str): The author of the script. Defaults to ''.
description (str): A description of the script, typically including type of output and any required plugins or settings. Defaults to ''.
license (str): The license under which the script is being distributed. Defaults to ''.
version (str): Identifies the version of the script. Defaults to ''.
last_updated (str): The UTC date and time when the script was last updated. Defaults to current date/time.
script_language_version (str): The version of the script language supported by the script.
"""
super().__init__(script=script, title=title, id=id, last_updated=last_updated, script_language_version=script_language_version)
self.author = author
self.description = description
self.license = license
self.version = version
@property
def description(self):
return self._description
@description.setter
def description(self, value):
self._description = MultilineLiteral(value)
| 17,311
|
Python
|
.py
| 384
| 36.486979
| 153
| 0.648947
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,968
|
__init__.py
|
metabrainz_picard/picard/script/__init__.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2006-2009, 2012 Lukáš Lalinský
# Copyright (C) 2007 Javier Kohen
# Copyright (C) 2008-2011, 2014-2015, 2018-2021, 2023-2024 Philipp Wolfer
# Copyright (C) 2009 Carlin Mangar
# Copyright (C) 2009 Nikolai Prokoschenko
# Copyright (C) 2011-2012 Michael Wiencek
# Copyright (C) 2012 Chad Wilson
# Copyright (C) 2012 stephen
# Copyright (C) 2012, 2014, 2017 Wieland Hoffmann
# Copyright (C) 2013-2014, 2017-2021, 2023-2024 Laurent Monin
# Copyright (C) 2014, 2017 Sophist-UK
# Copyright (C) 2016-2017 Sambhav Kothari
# Copyright (C) 2016-2017 Ville Skyttä
# Copyright (C) 2017-2018 Antonio Larrosa
# Copyright (C) 2018 Calvin Walton
# Copyright (C) 2018 virusMac
# Copyright (C) 2020-2021, 2023 Bob Swift
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from picard import log
from picard.config import get_config
from picard.const.defaults import (
DEFAULT_FILE_NAMING_FORMAT,
DEFAULT_NAMING_PRESET_ID,
)
from picard.extension_points import script_functions
from picard.i18n import (
N_,
gettext as _,
)
# Those imports are required to actually parse the code and interpret decorators
import picard.script.functions # noqa: F401 # pylint: disable=unused-import
from picard.script.parser import ( # noqa: F401 # pylint: disable=unused-import
MultiValue,
ScriptEndOfFile,
ScriptError,
ScriptExpression,
ScriptFunction,
ScriptParseError,
ScriptParser,
ScriptRuntimeError,
ScriptSyntaxError,
ScriptText,
ScriptUnicodeError,
ScriptUnknownFunction,
ScriptVariable,
)
from picard.script.serializer import FileNamingScriptInfo
class TaggingScriptSetting:
def __init__(self, pos=0, name="", enabled=False, content=""):
self.pos = pos
self.name = name
self.enabled = enabled
self.content = content
def iter_tagging_scripts_from_config(config=None):
if config is None:
config = get_config()
yield from iter_tagging_scripts_from_tuples(config.setting['list_of_scripts'])
def iter_tagging_scripts_from_tuples(tuples):
for pos, name, enabled, content in tuples:
yield TaggingScriptSetting(pos=pos, name=name, enabled=enabled, content=content)
def save_tagging_scripts_to_config(scripts, config=None):
if config is None:
config = get_config()
config.setting['list_of_scripts'] = [(s.pos, s.name, s.enabled, s.content) for s in scripts]
def iter_active_tagging_scripts(config=None):
"""Returns an iterator over the enabled and not empty tagging scripts."""
if config is None:
config = get_config()
if not config.setting['enable_tagger_scripts']:
return
for script in iter_tagging_scripts_from_config(config=config):
if script.enabled and script.content:
yield script
class ScriptFunctionDocError(Exception):
pass
class ScriptFunctionDocUnknownFunctionError(ScriptFunctionDocError):
pass
class ScriptFunctionDocNoDocumentationError(ScriptFunctionDocError):
pass
def script_function_documentation(name, fmt, functions=None, postprocessor=None):
if functions is None:
functions = dict(script_functions.ext_point_script_functions)
if name not in functions:
raise ScriptFunctionDocUnknownFunctionError("no such function: %s (known functions: %r)" % (name, [name for name in functions]))
if fmt == 'html':
return functions[name].htmldoc(postprocessor)
elif fmt == 'markdown':
return functions[name].markdowndoc(postprocessor)
else:
raise ScriptFunctionDocNoDocumentationError("no such documentation format: %s (known formats: html, markdown)" % fmt)
def script_function_names(functions=None):
if functions is None:
functions = dict(script_functions.ext_point_script_functions)
yield from sorted(functions)
def script_function_documentation_all(fmt='markdown', pre='',
post='', postprocessor=None):
functions = dict(script_functions.ext_point_script_functions)
doc_elements = []
for name in script_function_names(functions):
doc_element = script_function_documentation(name, fmt,
functions=functions,
postprocessor=postprocessor)
if doc_element:
doc_elements.append(pre + doc_element + post)
return "\n".join(doc_elements)
def get_file_naming_script(settings):
"""Retrieve the file naming script.
Args:
settings (ConfigSection): Object containing the user settings
Returns:
str: The text of the file naming script if available, otherwise None
"""
from picard.script import get_file_naming_script_presets
scripts = settings['file_renaming_scripts']
selected_id = settings['selected_file_naming_script_id']
if selected_id:
if scripts and selected_id in scripts:
return scripts[selected_id]['script']
for item in get_file_naming_script_presets():
if item['id'] == selected_id:
return str(item['script'])
log.error("Unable to retrieve the file naming script '%s'", selected_id)
return None
def get_file_naming_script_presets():
"""Generator of preset example file naming script objects.
Yields:
FileNamingScriptInfo: the next example FileNamingScriptInfo object
"""
AUTHOR = "MusicBrainz Picard Development Team"
DESCRIPTION = _("This preset example file naming script does not require any special settings, tagging scripts or plugins.")
LICENSE = "GNU Public License version 2"
def preset_title(number, title):
return _("Preset %(number)d: %(title)s") % {
'number': number,
'title': _(title),
}
yield FileNamingScriptInfo(
id=DEFAULT_NAMING_PRESET_ID,
title=preset_title(1, N_("Default file naming script")),
script=DEFAULT_FILE_NAMING_FORMAT,
author=AUTHOR,
description=DESCRIPTION,
version="1.0",
license=LICENSE,
last_updated="2019-08-05 13:40:00 UTC",
script_language_version="1.0",
)
yield FileNamingScriptInfo(
id="Preset 2",
title=preset_title(2, N_("[album artist]/[album]/[track #]. [title]")),
script="%albumartist%/\n"
"%album%/\n"
"%tracknumber%. %title%",
author=AUTHOR,
description=DESCRIPTION,
version="1.0",
license=LICENSE,
last_updated="2021-04-12 21:30:00 UTC",
script_language_version="1.0",
)
yield FileNamingScriptInfo(
id="Preset 3",
title=preset_title(3, N_("[album artist]/[album]/[disc and track #] [artist] - [title]")),
script="$if2(%albumartist%,%artist%)/\n"
"$if(%albumartist%,%album%/,)\n"
"$if($gt(%totaldiscs%,1),%discnumber%-,)\n"
"$if($and(%albumartist%,%tracknumber%),$num(%tracknumber%,2) ,)\n"
"$if(%_multiartist%,%artist% - ,)\n"
"%title%",
author=AUTHOR,
description=DESCRIPTION,
version="1.0",
license=LICENSE,
last_updated="2021-04-12 21:30:00 UTC",
script_language_version="1.0",
)
| 7,996
|
Python
|
.py
| 193
| 35.005181
| 136
| 0.683885
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,969
|
parser.py
|
metabrainz_picard/picard/script/parser.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2006-2009, 2012 Lukáš Lalinský
# Copyright (C) 2007 Javier Kohen
# Copyright (C) 2008-2011, 2014-2015, 2018-2021 Philipp Wolfer
# Copyright (C) 2009 Carlin Mangar
# Copyright (C) 2009 Nikolai Prokoschenko
# Copyright (C) 2011-2012 Michael Wiencek
# Copyright (C) 2012 Chad Wilson
# Copyright (C) 2012 stephen
# Copyright (C) 2012, 2014, 2017 Wieland Hoffmann
# Copyright (C) 2013-2014, 2017-2021, 2023-2024 Laurent Monin
# Copyright (C) 2014, 2017 Sophist-UK
# Copyright (C) 2016-2017 Sambhav Kothari
# Copyright (C) 2016-2017 Ville Skyttä
# Copyright (C) 2017-2018 Antonio Larrosa
# Copyright (C) 2018 Calvin Walton
# Copyright (C) 2018 virusMac
# Copyright (C) 2020-2021 Bob Swift
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from collections.abc import MutableSequence
from queue import LifoQueue
from picard.extension_points import script_functions
from picard.metadata import (
MULTI_VALUED_JOINER,
Metadata,
)
class ScriptError(Exception):
pass
class ScriptParseError(ScriptError):
def __init__(self, stackitem, message):
super().__init__(
"{prefix:s}: {message:s}".format(
prefix=str(stackitem),
message=message
)
)
class ScriptEndOfFile(ScriptParseError):
def __init__(self, stackitem):
super().__init__(
stackitem,
"Unexpected end of script"
)
class ScriptSyntaxError(ScriptParseError):
pass
class ScriptUnicodeError(ScriptSyntaxError):
pass
class ScriptUnknownFunction(ScriptParseError):
def __init__(self, stackitem):
super().__init__(
stackitem,
"Unknown function '{name}'".format(name=stackitem.name)
)
class ScriptRuntimeError(ScriptError):
def __init__(self, stackitem, message='Unknown error'):
super().__init__(
"{prefix:s}: {message:s}".format(
prefix=str(stackitem),
message=message
)
)
class StackItem:
def __init__(self, line, column, name=None):
self.line = line
self.column = column
if name is None:
self.name = None
else:
self.name = '$' + name
def __str__(self):
if self.name is None:
return "{line:d}:{column:d}".format(
line=self.line,
column=self.column
)
else:
return "{line:d}:{column:d}:{name}".format(
line=self.line,
column=self.column,
name=self.name
)
class ScriptText(str):
def eval(self, state):
return self
def normalize_tagname(name):
if name.startswith('_'):
return '~' + name[1:]
return name
class ScriptVariable:
def __init__(self, name):
self.name = name
def __repr__(self):
return "<ScriptVariable %%%s%%>" % self.name
def eval(self, state):
return state.context.get(normalize_tagname(self.name), "")
class ScriptFunction:
def __init__(self, name, args, parser, column=0, line=0):
self.stackitem = StackItem(line, column, name)
try:
argnum_bound = parser.functions[name].argcount
argcount = len(args)
if argnum_bound:
too_few_args = argcount < argnum_bound.lower
if argnum_bound.upper is not None:
if argnum_bound.lower == argnum_bound.upper:
expected = "exactly %i" % argnum_bound.lower
else:
expected = "between %i and %i" % (argnum_bound.lower, argnum_bound.upper)
too_many_args = argcount > argnum_bound.upper
else:
expected = "at least %i" % argnum_bound.lower
too_many_args = False
if too_few_args or too_many_args:
raise ScriptSyntaxError(
self.stackitem,
"Wrong number of arguments for $%s: Expected %s, got %i"
% (name, expected, argcount)
)
except KeyError:
raise ScriptUnknownFunction(self.stackitem)
self.name = name
self.args = args
def __repr__(self):
return "<ScriptFunction $%s(%r)>" % (self.name, self.args)
def eval(self, parser):
try:
function_registry_item = parser.functions[self.name]
except KeyError:
raise ScriptUnknownFunction(self.stackitem)
if function_registry_item.eval_args:
args = [arg.eval(parser) for arg in self.args]
else:
args = self.args
parser._function_stack.put(self.stackitem)
# Save return value to allow removing function from the stack on successful completion
return_value = function_registry_item.function(parser, *args)
parser._function_stack.get()
return return_value
class ScriptExpression(list):
def eval(self, state):
return "".join(item.eval(state) for item in self)
def isidentif(ch):
return ch.isalnum() or ch == '_'
class ScriptParser:
r"""Tagger script parser.
Grammar:
unicodechar ::= '\u' [a-fA-F0-9]{4}
text ::= [^$%] | '\$' | '\%' | '\(' | '\)' | '\,' | unicodechar
argtext ::= [^$%(),] | '\$' | '\%' | '\(' | '\)' | '\,' | unicodechar
identifier ::= [a-zA-Z0-9_]
variable ::= '%' (identifier | ':')+ '%'
function ::= '$' (identifier)+ '(' (argument (',' argument)*)? ')'
expression ::= (variable | function | text)*
argument ::= (variable | function | argtext)*
"""
_cache = {}
def __init__(self):
self._function_stack = LifoQueue()
def __raise_eof(self):
raise ScriptEndOfFile(StackItem(line=self._y, column=self._x))
def __raise_char(self, ch):
raise ScriptSyntaxError(StackItem(line=self._y, column=self._x), "Unexpected character '%s'" % ch)
def __raise_unicode(self, ch):
raise ScriptUnicodeError(StackItem(line=self._y, column=self._x), "Invalid unicode character '\\u%s'" % ch)
def read(self):
try:
ch = self._text[self._pos]
except IndexError:
return None
else:
self._pos += 1
self._px = self._x
self._py = self._y
if ch == '\n':
self._line = self._pos
self._x = 1
self._y += 1
else:
self._x += 1
return ch
def read_multi(self, count):
text = ch = self.read()
if not ch:
self.__raise_eof()
count -= 1
while ch and count:
ch = self.read()
if not ch:
self.__raise_eof()
text += ch
count -= 1
return text
def unread(self):
self._pos -= 1
self._x = self._px
self._y = self._py
def parse_arguments(self):
results = []
while True:
result, ch = self.parse_expression(False)
results.append(result)
if ch == ')':
# Only an empty expression as first argument
# is the same as no argument given.
if len(results) == 1 and results[0] == []:
return []
return results
def parse_function(self):
start = self._pos
column = self._x - 2 # Set x position to start of function name ($)
line = self._y
while True:
ch = self.read()
if ch == '(':
name = self._text[start:self._pos-1]
if name not in self.functions:
raise ScriptUnknownFunction(StackItem(line, column, name))
return ScriptFunction(name, self.parse_arguments(), self, column, line)
elif ch is None:
self.__raise_eof()
elif not isidentif(ch):
self.__raise_char(ch)
def parse_variable(self):
begin = self._pos
while True:
ch = self.read()
if ch == '%':
return ScriptVariable(self._text[begin:self._pos-1])
elif ch is None:
self.__raise_eof()
elif not isidentif(ch) and ch != ':':
self.__raise_char(ch)
def parse_text(self, top):
text = []
while True:
ch = self.read()
if ch == "\\":
text.append(self.parse_escape_sequence())
elif ch is None:
break
elif not top and ch == '(':
self.__raise_char(ch)
elif ch in '$%' or (not top and ch in ',)'):
self.unread()
break
else:
text.append(ch)
return ScriptText("".join(text))
def parse_escape_sequence(self):
ch = self.read()
if ch == 'n':
return '\n'
elif ch == 't':
return '\t'
elif ch == 'u':
codepoint = self.read_multi(4)
try:
return chr(int(codepoint, 16))
except (TypeError, ValueError):
self.__raise_unicode(codepoint)
elif ch is None:
self.__raise_eof()
elif ch not in "$%(),\\":
self.__raise_char(ch)
else:
return ch
def parse_expression(self, top):
tokens = ScriptExpression()
while True:
ch = self.read()
if ch is None:
if top:
break
else:
self.__raise_eof()
elif not top and ch in ',)':
break
elif ch == '$':
tokens.append(self.parse_function())
elif ch == '%':
tokens.append(self.parse_variable())
else:
self.unread()
tokens.append(self.parse_text(top))
return (tokens, ch)
def load_functions(self):
self.functions = dict(script_functions.ext_point_script_functions)
def parse(self, script, functions=False):
"""Parse the script."""
self._text = script
self._pos = 0
self._px = self._x = 1
self._py = self._y = 1
self._line = 0
if not functions:
self.load_functions()
return self.parse_expression(True)[0]
def eval(self, script, context=None, file=None):
"""Parse and evaluate the script."""
self.context = context if context is not None else Metadata()
self.file = file
self.load_functions()
key = hash(script)
if key not in ScriptParser._cache:
ScriptParser._cache[key] = self.parse(script, True)
return ScriptParser._cache[key].eval(self)
class MultiValue(MutableSequence):
def __init__(self, parser, multi, separator):
self.parser = parser
if isinstance(separator, ScriptExpression):
self.separator = separator.eval(self.parser)
else:
self.separator = separator
if (self.separator == MULTI_VALUED_JOINER
and len(multi) == 1
and isinstance(multi[0], ScriptVariable)):
# Convert ScriptExpression containing only a single variable into variable
self._multi = self.parser.context.getall(normalize_tagname(multi[0].name))
else:
# Fall-back to converting to a string and splitting if haystack is an expression
# or user has overridden the separator character.
evaluated_multi = multi.eval(self.parser)
if not evaluated_multi:
self._multi = []
elif self.separator:
self._multi = evaluated_multi.split(self.separator)
else:
self._multi = [evaluated_multi]
def __len__(self):
return len(self._multi)
def __getitem__(self, key):
return self._multi[key]
def __setitem__(self, key, value):
self._multi[key] = value
def __delitem__(self, key):
del self._multi[key]
def insert(self, index, value):
return self._multi.insert(index, value)
def __repr__(self):
return "%s(%r, %r, %r)" % (self.__class__.__name__, self.parser, self._multi, self.separator)
def __str__(self):
return self.separator.join(x for x in self if x)
| 13,239
|
Python
|
.py
| 357
| 27.285714
| 115
| 0.558844
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,970
|
functions.py
|
metabrainz_picard/picard/script/functions.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2006-2009, 2012 Lukáš Lalinský
# Copyright (C) 2007 Javier Kohen
# Copyright (C) 2008-2011, 2014-2015, 2018-2023 Philipp Wolfer
# Copyright (C) 2009 Carlin Mangar
# Copyright (C) 2009 Nikolai Prokoschenko
# Copyright (C) 2011-2012 Michael Wiencek
# Copyright (C) 2012 Chad Wilson
# Copyright (C) 2012 stephen
# Copyright (C) 2012, 2014, 2017, 2021 Wieland Hoffmann
# Copyright (C) 2013-2014, 2017-2024 Laurent Monin
# Copyright (C) 2014, 2017, 2021 Sophist-UK
# Copyright (C) 2016-2017 Sambhav Kothari
# Copyright (C) 2016-2017 Ville Skyttä
# Copyright (C) 2017-2018 Antonio Larrosa
# Copyright (C) 2018 Calvin Walton
# Copyright (C) 2018 virusMac
# Copyright (C) 2020-2022 Bob Swift
# Copyright (C) 2021 Adam James
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from collections import namedtuple
import datetime
from functools import reduce
import operator
import re
import unicodedata
from picard.const.countries import RELEASE_COUNTRIES
from picard.extension_points.script_functions import script_function
from picard.i18n import (
N_,
gettext_countries,
)
from picard.metadata import MULTI_VALUED_JOINER
from picard.script.parser import (
MultiValue,
ScriptRuntimeError,
normalize_tagname,
)
from picard.util import (
pattern_as_regex,
uniqify,
)
def _compute_int(operation, *args):
return str(reduce(operation, map(int, args)))
def _compute_logic(operation, *args):
return operation(args)
@script_function(eval_args=False, documentation=N_(
"""`$if(if,then,else)`
If `if` is not empty, it returns `then`, otherwise it returns `else`."""
))
def func_if(parser, _if, _then, _else=None):
if _if.eval(parser):
return _then.eval(parser)
elif _else:
return _else.eval(parser)
return ''
@script_function(eval_args=False, documentation=N_(
"""`$if2(a1,a2,a3,…)`
Returns first non empty argument."""
))
def func_if2(parser, *args):
for arg in args:
arg = arg.eval(parser)
if arg:
return arg
return ''
@script_function(eval_args=False, documentation=N_(
"""`$noop(…)`
Does nothing (useful for comments or disabling a block of code)."""
))
def func_noop(parser, *args):
return ''
@script_function(documentation=N_(
"""`$left(text,number)`
Returns the first `number` characters from `text`."""
))
def func_left(parser, text, length):
try:
return text[:int(length)]
except ValueError:
return ''
@script_function(documentation=N_(
"""`$right(text,number)`
Returns the last `number` characters from `text`."""
))
def func_right(parser, text, length):
try:
return text[-int(length):]
except ValueError:
return ''
@script_function(documentation=N_(
"""`$lower(text)`
Returns `text` in lower case."""
))
def func_lower(parser, text):
return text.lower()
@script_function(documentation=N_(
"""`$upper(text)`
Returns `text` in upper case."""
))
def func_upper(parser, text):
return text.upper()
@script_function(documentation=N_(
"""`$pad(text,length,char)`
Pads the `text` to the `length` provided by adding as many copies of `char` as
needed to the **beginning** of the string."""
))
def func_pad(parser, text, length, char):
try:
return char * (int(length) - len(text)) + text
except ValueError:
return ''
@script_function(documentation=N_(
"""`$strip(text)`
Replaces all whitespace in `text` with a single space, and removes leading and trailing spaces.
Whitespace characters include multiple consecutive spaces, and various other unicode characters."""
))
def func_strip(parser, text):
return re.sub(r"\s+", " ", text).strip()
@script_function(documentation=N_(
"""`$replace(text,search,replace)`
Replaces occurrences of `search` in `text` with value of `replace` and returns the resulting string."""
))
def func_replace(parser, text, old, new):
return text.replace(old, new)
@script_function(eval_args=False, documentation=N_(
"""`$replacemulti(name,search,replace,separator="; ")`
Replaces occurrences of `search` with `replace` in the multi-value variable `name`.
Empty elements are automatically removed.
Example:
$replacemulti(%genre%,Idm,IDM)
"""
))
def func_replacemulti(parser, multi, search, replace, separator=MULTI_VALUED_JOINER):
if not multi or not search or replace is None or not separator:
return multi.eval(parser)
search = search.eval(parser)
replace = replace.eval(parser)
multi_value = MultiValue(parser, multi, separator)
for n, value in enumerate(multi_value):
if value == search:
multi_value[n] = replace
return str(multi_value)
@script_function(documentation=N_(
"""`$in(x,y)`
Returns true, if `x` contains `y`."""
))
def func_in(parser, text, needle):
if needle in text:
return '1'
else:
return ''
@script_function(eval_args=False, documentation=N_(
"""`$inmulti(%x%,y)`
Returns true if multi-value variable `x` contains exactly `y` as one of its values.
_Since Picard 1.0_"""
))
def func_inmulti(parser, haystack, needle, separator=MULTI_VALUED_JOINER):
"""Searches for ``needle`` in ``haystack``, supporting a list variable for
``haystack``. If a string is used instead, then a ``separator`` can be
used to split it. In both cases, it returns true if the resulting list
contains exactly ``needle`` as a member."""
needle = needle.eval(parser)
return func_in(parser, MultiValue(parser, haystack, separator), needle)
@script_function(documentation=N_(
"""`$rreplace(text,pattern,replace)`
[Regular expression](https://docs.python.org/3/library/re.html#regular-expression-syntax) replace."""
))
def func_rreplace(parser, text, old, new):
try:
return re.sub(old, new, text)
except re.error:
return text
@script_function(documentation=N_(
"""`$rsearch(text,pattern)`
[Regular expression](https://docs.python.org/3/library/re.html#regular-expression-syntax) search.
This function will return the first matching group."""
))
def func_rsearch(parser, text, pattern):
try:
match_ = re.search(pattern, text)
except re.error:
return ''
if match_:
try:
return match_.group(1)
except IndexError:
return match_.group(0)
return ''
@script_function(documentation=N_(
"""`$num(number,length)`
Returns `number` formatted to `length` digits (maximum 20)."""
))
def func_num(parser, text, length):
try:
format_ = "%%0%dd" % max(0, min(int(length), 20))
except ValueError:
return ''
try:
value = int(text)
except ValueError:
value = 0
return format_ % value
@script_function(documentation=N_(
"""`$unset(name)`
Unsets the variable `name`.
Allows for wildcards to unset certain tags (works with "performer:\\*", "comment:\\*", and "lyrics:\\*").
For example `$unset(performer:*)` would unset all performer tags."""
))
def func_unset(parser, name):
name = normalize_tagname(name)
# Allow wild-card unset for certain keys
if name in {'performer:*', 'comment:*', 'lyrics:*'}:
name = name[:-1]
for key in list(parser.context.keys()):
if key.startswith(name):
parser.context.unset(key)
return ''
parser.context.unset(name)
return ''
@script_function(documentation=N_(
"""`$delete(name)`
Unsets the variable `name` and marks the tag for deletion.
This is similar to `$unset(name)` but also marks the tag for deletion. E.g.
running `$delete(genre)` will actually remove the genre tag from a file when
saving.
_Since Picard 2.1_"""
))
def func_delete(parser, name):
parser.context.delete(normalize_tagname(name))
return ''
@script_function(documentation=N_(
"""`$set(name,value)`
Sets the variable `name` to `value`.
Note: To create a variable which can be used for the file naming string, but
which will not be written as a tag in the file, prefix the variable name
with an underscore. `%something%` will create a "something" tag;
`%_something%` will not."""
))
def func_set(parser, name, value):
if value:
parser.context[normalize_tagname(name)] = value
else:
func_unset(parser, name)
return ''
@script_function(documentation=N_(
"""`$setmulti(name,value,separator="; ")`
Sets the variable `name` to `value`, using the separator (or "; " if not passed)
to coerce the value back into a proper multi-valued tag. This can be used to
operate on multi-valued tags as a string, and then set them back as proper
multi-valued tags.
Example:
$setmulti(genre,$lower(%genre%))
_Since Picard 1.0_"""
))
def func_setmulti(parser, name, value, separator=MULTI_VALUED_JOINER):
return func_set(parser, name, value.split(separator) if value and separator else value)
@script_function(documentation=N_(
"""`$get(name)`
Returns the variable `name` (equivalent to `%name%`)."""
))
def func_get(parser, name):
"""Returns the variable ``name`` (equivalent to ``%name%``)."""
return parser.context.get(normalize_tagname(name), "")
@script_function(documentation=N_(
"""`$copy(new,old)`
Copies metadata from variable `old` to `new`.
The difference between `$set(new,%old%)` is that `$copy(new,old)` copies
multi-value variables without flattening them.
_Since Picard 0.9_"""
))
def func_copy(parser, new, old):
new = normalize_tagname(new)
old = normalize_tagname(old)
parser.context[new] = parser.context.getall(old)[:]
return ''
@script_function(documentation=N_(
"""`$copymerge(new,old[,keep_duplicates])`
Merges metadata from variable `old` into `new`, removing duplicates and
appending to the end, so retaining the original ordering. Like `$copy`, this
will also copy multi-valued variables without flattening them.
If `keep_duplicates` is set, then the duplicates will not be removed from the result.
_Since Picard 1.0_"""
))
def func_copymerge(parser, new, old, keep_duplicates=False):
new = normalize_tagname(new)
old = normalize_tagname(old)
newvals = parser.context.getall(new)
oldvals = parser.context.getall(old)
parser.context[new] = newvals + oldvals if keep_duplicates else uniqify(newvals + oldvals)
return ''
@script_function(documentation=N_(
"""`$trim(text[,char])`
Trims all leading and trailing whitespaces from `text`.
The optional second parameter `char` specifies the character to trim."""
))
def func_trim(parser, text, char=None):
if char:
return text.strip(char)
else:
return text.strip()
@script_function(documentation=N_(
"""`$add(x,y,…)`
Add `y` to `x`.
Can be used with an arbitrary number of arguments.
Example:
$add(x,y,z) = ((x + y) + z)
"""
))
def func_add(parser, x, y, *args):
try:
return _compute_int(operator.add, x, y, *args)
except ValueError:
return ''
@script_function(documentation=N_(
"""`$sub(x,y,…)`
Subtracts `y` from `x`.
Can be used with an arbitrary number of arguments.
Example:
$sub(x,y,z) = ((x - y) - z)
"""
))
def func_sub(parser, x, y, *args):
try:
return _compute_int(operator.sub, x, y, *args)
except ValueError:
return ''
@script_function(documentation=N_(
"""`$div(x,y,…)`
Divides `x` by `y`.
Can be used with an arbitrary number of arguments.
Example:
$div(x,y,z) = ((x / y) / z)
"""
))
def func_div(parser, x, y, *args):
try:
return _compute_int(operator.floordiv, x, y, *args)
except ValueError:
return ''
except ZeroDivisionError:
return ''
@script_function(documentation=N_(
"""`$mod(x,y,…)`
Returns the remainder of `x` divided by `y`.
Can be used with an arbitrary number of arguments.
Example:
$mod(x,y,z) = ((x % y) % z)
"""
))
def func_mod(parser, x, y, *args):
try:
return _compute_int(operator.mod, x, y, *args)
except (ValueError, ZeroDivisionError):
return ''
@script_function(documentation=N_(
"""`$mul(x,y,…)`
Multiplies `x` by `y`.
Can be used with an arbitrary number of arguments.
Example:
$mul(x,y,z) = ((x * y) * z)
"""
))
def func_mul(parser, x, y, *args):
try:
return _compute_int(operator.mul, x, y, *args)
except ValueError:
return ''
@script_function(documentation=N_(
"""`$or(x,y,…)`
Returns true if either `x` or `y` not empty.
Can be used with an arbitrary number of arguments.
The result is true if ANY of the arguments is not empty."""
))
def func_or(parser, x, y, *args):
if _compute_logic(any, x, y, *args):
return '1'
else:
return ''
@script_function(documentation=N_(
"""`$and(x,y,…)`
Returns true if both `x` and `y` are not empty.
Can be used with an arbitrary number of arguments.
The result is true if ALL of the arguments are not empty."""
))
def func_and(parser, x, y, *args):
if _compute_logic(all, x, y, *args):
return '1'
else:
return ''
@script_function(documentation=N_(
"""`$not(x)`
Returns true if `x` is empty."""
))
def func_not(parser, x):
if not x:
return '1'
else:
return ''
@script_function(documentation=N_(
"""`$eq(x,y)`
Returns true if `x` equals `y`."""
))
def func_eq(parser, x, y):
if x == y:
return '1'
else:
return ''
@script_function(documentation=N_(
"""`$ne(x,y)`
Returns true if `x` does not equal `y`."""
))
def func_ne(parser, x, y):
if x != y:
return '1'
else:
return ''
def _cmp(op, x, y, _type):
"""Compare x vs y using op method and specified _type
op is expected to be a method from operator module
"""
if not _type:
_type = 'auto'
_typer = None
if _type == 'auto':
_type = 'text'
for _test_type in (int, float):
try:
_type = (_test_type(x), _test_type(y))
_type = _test_type.__name__
break
except ValueError:
pass
if _type == 'text':
return '1' if op(x, y) else ""
elif _type == 'nocase':
return '1' if op(x.lower(), y.lower()) else ""
elif _type == 'float':
_typer = float
elif _type == 'int':
_typer = int
if _typer is not None:
try:
if op(_typer(x), _typer(y)):
return '1'
except ValueError:
pass
return ''
@script_function(documentation=N_(
"""`$lt(x,y[,type])`
Returns true if `x` is less than `y` using the comparison specified in `type`.
Possible values of `type` are "int" (integer), "float" (floating point), "text"
(case-sensitive text), "nocase" (case-insensitive text) and "auto" (automatically
determine the type of arguments provided), with "auto" used as the default
comparison method if `type` is not specified. The "auto" type will use the
first type that applies to both arguments in the following order of preference:
"int", "float" and "text"."""
))
def func_lt(parser, x, y, _type=None):
return _cmp(operator.lt, x, y, _type)
@script_function(documentation=N_(
"""`$lte(x,y[,type])`
Returns true if `x` is less than or equal to `y` using the comparison specified in `type`.
Possible values of `type` are "int" (integer), "float" (floating point), "text"
(case-sensitive text), "nocase" (case-insensitive text) and "auto" (automatically
determine the type of arguments provided), with "auto" used as the default
comparison method if `type` is not specified. The "auto" type will use the
first type that applies to both arguments in the following order of preference:
"int", "float" and "text"."""
))
def func_lte(parser, x, y, _type=None):
return _cmp(operator.le, x, y, _type)
@script_function(documentation=N_(
"""`$gt(x,y[,type])`
Returns true if `x` is greater than `y` using the comparison specified in `type`.
Possible values of `type` are "int" (integer), "float" (floating point), "text"
(case-sensitive text), "nocase" (case-insensitive text) and "auto" (automatically
determine the type of arguments provided), with "auto" used as the default
comparison method if `type` is not specified. The "auto" type will use the
first type that applies to both arguments in the following order of preference:
"int", "float" and "text"."""
))
def func_gt(parser, x, y, _type=None):
return _cmp(operator.gt, x, y, _type)
@script_function(documentation=N_(
"""`$gte(x,y[,type])`
Returns true if `x` is greater than or equal to `y` using the comparison specified in `type`.
Possible values of `type` are "int" (integer), "float" (floating point), "text"
(case-sensitive text), "nocase" (case-insensitive text) and "auto" (automatically
determine the type of arguments provided), with "auto" used as the default
comparison method if `type` is not specified. The "auto" type will use the
first type that applies to both arguments in the following order of preference:
"int", "float" and "text"."""
))
def func_gte(parser, x, y, _type=None):
return _cmp(operator.ge, x, y, _type)
@script_function(documentation=N_(
"""`$len(text)`
Returns the number of characters in `text`."""
))
def func_len(parser, text=""):
return str(len(text))
@script_function(eval_args=False, documentation=N_(
"""`$lenmulti(name,separator="; ")`
Returns the number of elements in the multi-value tag `name`. A literal value
representing a multi-value can be substituted for `name`, using the
`separator` (or "; " if not passed) to coerce the value into a proper
multi-valued tag.
Example:
$lenmulti(One; Two; Three) = 3
"""
))
def func_lenmulti(parser, multi, separator=MULTI_VALUED_JOINER):
return str(len(MultiValue(parser, multi, separator)))
@script_function(documentation=N_(
"""`$performer(pattern="",join=", ")`
Returns the performers where the performance type (e.g. "vocal") matches `pattern`, joined by `join`.
You can specify a regular expression in the format `/pattern/flags`. `flags` are optional. Currently
the only supported flag is "i" (ignore case). For example `$performer(/^guitars?$/i)` matches the
performance type "guitar" or "Guitars", but not e.g. "bass guitar".
_Since Picard 0.10_"""
))
def func_performer(parser, pattern="", join=", "):
values = []
try:
regex = pattern_as_regex(pattern, allow_wildcards=False)
except re.error:
return ''
for name, value in parser.context.items():
if name.startswith("performer:"):
name, performance = name.split(':', 1)
if regex.search(performance):
values.append(value)
return join.join(values)
@script_function(eval_args=False, documentation=N_(
"""`$matchedtracks()`
Returns the number of matched tracks within a release.
**Only works in File Naming scripts.**
_Since Picard 0.12_"""
))
def func_matchedtracks(parser, *args):
# only works in file naming scripts, always returns zero in tagging scripts
file = parser.file
if file and file.parent_item and hasattr(file.parent_item, 'album') and file.parent_item.album:
return str(parser.file.parent_item.album.get_num_matched_tracks())
return '0'
@script_function(documentation=N_(
"""`$is_complete()`
Returns true if every track in the album is matched to a single file.
**Only works in File Naming scripts.**"""
))
def func_is_complete(parser):
# only works in file naming scripts, always returns zero in tagging scripts
file = parser.file
if (file and file.parent_item and hasattr(file.parent_item, 'album') and file.parent_item.album
and file.parent_item.album.is_complete()):
return '1'
return ''
@script_function(documentation=N_(
"""`$firstalphachar(text,nonalpha="#")`
Returns the first character of `text`.
If `text` does not begin with an alphabetic character, then `nonalpha` is returned instead. If `nonalpha` is not
specified, the default value "#" will be used.
_Since Picard 0.12_"""
))
def func_firstalphachar(parser, text="", nonalpha="#"):
if len(text) == 0:
return nonalpha
firstchar = text[0]
if firstchar.isalpha():
return firstchar.upper()
else:
return nonalpha
@script_function(documentation=N_(
"""`$initials(text)`
Returns the first character of each word in `text`, if it is an alphabetic character.
_Since Picard 0.12_"""
))
def func_initials(parser, text=""):
return ''.join(a[:1] for a in text.split(" ") if a[:1].isalpha())
@script_function(documentation=N_(
"""`$firstwords(text,length)`
Like `$truncate()` except that it will only return the complete words from `text` which fit within `length` characters.
_Since Picard 0.12_"""
))
def func_firstwords(parser, text, length):
try:
length = int(length)
except ValueError:
length = 0
if len(text) <= length:
return text
else:
try:
if text[length] == ' ':
return text[:length]
return text[:length].rsplit(' ', 1)[0]
except IndexError:
return ''
@script_function(documentation=N_(
"""`$startswith(text,prefix)`
Returns true if `text` starts with `prefix`.
_Since Picard 1.4_"""
))
def func_startswith(parser, text, prefix):
if text.startswith(prefix):
return '1'
return ''
@script_function(documentation=N_(
"""`$endswith(text,suffix)`
Returns true if `text` ends with `suffix`.
_Since Picard 1.4_"""
))
def func_endswith(parser, text, suffix):
if text.endswith(suffix):
return '1'
return ''
@script_function(documentation=N_(
"""`$truncate(text,length)`
Truncate `text` to `length`.
_Since Picard 0.12_"""
))
def func_truncate(parser, text, length):
try:
length = int(length)
except ValueError:
length = None
return text[:length].rstrip()
@script_function(check_argcount=False, documentation=N_(
"""`$swapprefix(text,prefix1,prefix2,…)`
Moves the specified prefixes from the beginning to the end of `text`. Multiple
prefixes can be specified as separate parameters. If no prefix is specified 'A'
and 'The' are used by default.
Example:
$swapprefix(%albumartist%,A,An,The,La,Le,Les,Un,Une)
_Since Picard 1.3, previously as a plugin since Picard 0.13_"""
))
def func_swapprefix(parser, text, *prefixes):
# Inspired by the swapprefix plugin by Philipp Wolfer.
text, prefix = _delete_prefix(parser, text, *prefixes)
if prefix != '':
return text + ', ' + prefix
return text
@script_function(check_argcount=False, documentation=N_(
"""`$delprefix(text,prefix1,prefix2,…)`
Deletes the specified prefixes from the beginning of `text`. Multiple
prefixes can be specified as separate parameters. If no prefix is specified 'A'
and 'The' are used by default.
Example:
$delprefix(%albumartist%,A,An,The,La,Le,Les,Un,Une)
_Since Picard 1.3_"""
))
def func_delprefix(parser, text, *prefixes):
# Inspired by the swapprefix plugin by Philipp Wolfer.
return _delete_prefix(parser, text, *prefixes)[0]
def _delete_prefix(parser, text, *prefixes):
"""
Worker function to deletes the specified prefixes.
Returns remaining string and deleted part separately.
If no prefix is specified 'A' and 'The' used.
"""
# Inspired by the swapprefix plugin by Philipp Wolfer.
if not prefixes:
prefixes = ('A', 'The')
text = text.strip()
rx = '(' + r'\s+)|('.join(map(re.escape, prefixes)) + r'\s+)'
match_ = re.match(rx, text)
if match_:
pref = match_.group()
return text[len(pref):], pref.strip()
return text, ''
@script_function(check_argcount=False, documentation=N_(
"""`$eq_any(x,a1,a2,…)`
Returns true if `x` equals `a1` or `a2` or …
Functionally equivalent to `$or($eq(x,a1),$eq(x,a2),…)`.
Functionally equivalent to the eq2 plugin."""
))
def func_eq_any(parser, x, *args):
# Inspired by the eq2 plugin by Brian Schweitzer.
return '1' if x in args else ''
@script_function(check_argcount=False, documentation=N_(
"""`$ne_all(x,a1,a2,…)`
Returns true if `x` does not equal `a1` and `a2` and …
Functionally equivalent to `$and($ne(x,a1),$ne(x,a2),…)`.
Functionally equivalent to the ne2 plugin."""
))
def func_ne_all(parser, x, *args):
# Inspired by the ne2 plugin by Brian Schweitzer.
return '1' if x not in args else ''
@script_function(check_argcount=False, documentation=N_(
"""`$eq_all(x,a1,a2,…)`
Returns true if `x` equals `a1` and `a2` and …
Functionally equivalent to `$and($eq(x,a1),$eq(x,a2),…)`.
Example:
$if($eq_all(%albumartist%,%artist%,Justin Bieber),$set(engineer,Meat Loaf))
"""
))
def func_eq_all(parser, x, *args):
for i in args:
if x != i:
return ''
return '1'
@script_function(check_argcount=False, documentation=N_(
"""`$ne_any(x,a1,a2,…)`
Returns true if `x` does not equal `a1` or `a2` or …
Functionally equivalent to `$or($ne(x,a1),$ne(x,a2),…)`.
Example:
$if($ne_any(%albumartist%,%trackartist%,%composer%),$set(lyricist,%composer%))
"""
))
def func_ne_any(parser, x, *args):
return func_not(parser, func_eq_all(parser, x, *args))
@script_function(documentation=N_(
"""`$title(text)`
Returns `text` in title case (first character in every word capitalized).
Example:
$set(album,$title(%album%))
_Since Picard 2.1_"""
))
def func_title(parser, text):
# GPL 2.0 licensed code by Javier Kohen, Sambhav Kothari
# from https://github.com/metabrainz/picard-plugins/blob/2.0/plugins/titlecase/titlecase.py
if not text:
return text
capitalized = text[0].capitalize()
capital = False
for i in range(1, len(text)):
t = text[i]
if t in "’'" and text[i-1].isalpha():
capital = False
elif iswbound(t):
capital = True
elif capital and t.isalpha():
capital = False
t = t.capitalize()
else:
capital = False
capitalized += t
return capitalized
def iswbound(char):
# GPL 2.0 licensed code by Javier Kohen, Sambhav Kothari
# from https://github.com/metabrainz/picard-plugins/blob/2.0/plugins/titlecase/titlecase.py
""" Checks whether the given character is a word boundary """
category = unicodedata.category(char)
return 'Zs' == category or 'Sk' == category or 'P' == category[0]
@script_function(documentation=N_(
"""`$is_audio()`
Returns true, if the file processed is an audio file.
_Since Picard 2.2_"""
))
def func_is_audio(parser):
if func_is_video(parser) == "1":
return ''
else:
return '1'
@script_function(documentation=N_(
"""`$is_video()`
Returns true, if the file processed is a video file.
_Since Picard 2.2_"""
))
def func_is_video(parser):
if parser.context['~video'] and parser.context['~video'] != '0':
return '1'
else:
return ''
@script_function(documentation=N_(
"""`$find(haystack,needle)`
Finds the location of one string within another.
Returns the index of the first occurrence of `needle` in `haystack`, or "" if `needle` was not found.
_Since Picard 2.3_
Note that prior to Picard 2.3.2 `$find` returned "-1" if `needle` was not found."""
))
def func_find(parser, haystack, needle):
index = haystack.find(needle)
if index < 0:
return ''
return str(index)
@script_function(documentation=N_(
"""`$reverse(text)`
Returns `text` in reverse order."""
))
def func_reverse(parser, text):
return text[::-1]
@script_function(documentation=N_(
"""`$substr(text,start[,end])`
Returns the substring beginning with the character at the `start` index, up to
(but not including) the character at the `end` index. Indexes are
zero-based. Negative numbers will be counted back from the end of the
string. If the `start` or `end` indexes are left blank, they will default to
the start and end of the string respectively."""
))
def func_substr(parser, text, start_index, end_index=None):
try:
start = int(start_index) if start_index else None
except ValueError:
start = None
try:
end = int(end_index) if end_index else None
except ValueError:
end = None
return text[start:end]
@script_function(eval_args=False, documentation=N_(
"""`$getmulti(name,index,separator="; ")`
Gets the element at `index` from the multi-value tag `name`. A literal value
representing a multi-value can be substituted for `name`, using the
separator (or "; " if not passed) to coerce the value into a proper
multi-valued tag."""
))
def func_getmulti(parser, multi, item_index, separator=MULTI_VALUED_JOINER):
if not item_index:
return ''
try:
index = int(item_index.eval(parser))
multi_value = MultiValue(parser, multi, separator)
return str(multi_value[index])
except (ValueError, IndexError):
return ''
@script_function(eval_args=False, documentation=N_(
"""`$foreach(name,code,separator="; ")`
Iterates over each element found in the multi-value tag `name`, executing
`code`. For each loop, the element value is first stored in the tag
`_loop_value` and the count is stored in the tag `_loop_count`. This allows
the element or count value to be accessed within the `code` script. A
literal value representing a multi-value can be substituted for `name`,
using the separator (or "; " if not passed) to coerce the value into a
proper multi-valued tag."""
))
def func_foreach(parser, multi, loop_code, separator=MULTI_VALUED_JOINER):
multi_value = MultiValue(parser, multi, separator)
for loop_count, value in enumerate(multi_value, 1):
func_set(parser, '_loop_count', str(loop_count))
func_set(parser, '_loop_value', str(value))
loop_code.eval(parser)
func_unset(parser, '_loop_count')
func_unset(parser, '_loop_value')
return ''
@script_function(eval_args=False, documentation=N_(
"""`$while(condition,code)`
Standard 'while' loop. Executes `code` repeatedly until `condition` no longer
evaluates to `True`. For each loop, the count is stored in the tag
`_loop_count`. This allows the count value to be accessed within the `code`
script. The function limits the maximum number of iterations to 1000 as a
safeguard against accidentally creating an infinite loop."""
))
def func_while(parser, condition, loop_code):
if condition and loop_code:
runaway_check = 1000
loop_count = 0
while condition.eval(parser) and loop_count < runaway_check:
loop_count += 1
func_set(parser, '_loop_count', str(loop_count))
loop_code.eval(parser)
func_unset(parser, '_loop_count')
return ''
@script_function(eval_args=False, documentation=N_(
"""`$map(name,code,separator="; ")`
Iterates over each element found in the multi-value tag `name` and updates the
value of the element to the value returned by `code`, returning the updated
multi-value tag. For each loop, the element value is first stored in the tag
`_loop_value` and the count is stored in the tag `_loop_count`. This allows
the element or count value to be accessed within the `code` script.
Empty elements are automatically removed.
Example:
$map(First:A; Second:B,$upper(%_loop_count%=%_loop_value%))
Result: 1=FIRST:A; 2=SECOND:B
"""
))
def func_map(parser, multi, loop_code, separator=MULTI_VALUED_JOINER):
multi_value = MultiValue(parser, multi, separator)
for loop_count, value in enumerate(multi_value, 1):
func_set(parser, '_loop_count', str(loop_count))
func_set(parser, '_loop_value', str(value))
# Make changes in-place
multi_value[loop_count - 1] = str(loop_code.eval(parser))
func_unset(parser, '_loop_count')
func_unset(parser, '_loop_value')
return str(multi_value)
@script_function(eval_args=False, documentation=N_(
"""`$join(name,text,separator="; ")`
Joins all elements in `name`, placing `text` between each element, and returns the result as a string."""
))
def func_join(parser, multi, join_phrase, separator=MULTI_VALUED_JOINER):
join_phrase = str(join_phrase.eval(parser))
multi_value = MultiValue(parser, multi, separator)
return join_phrase.join(multi_value)
@script_function(eval_args=False, documentation=N_(
"""`$slice(name,start,end,separator="; ")`
Returns a multi-value variable containing the elements between the `start` and
`end` indexes from the multi-value tag `name`. A literal value representing
a multi-value can be substituted for `name`, using the separator (or "; " if
not passed) to coerce the value into a proper multi-valued tag. Indexes are
zero based. Negative numbers will be counted back from the end of the list.
If the `start` or `end` indexes are left blank, they will default to the
start and end of the list respectively.
The following example will create a multi-value variable with all artists
in `%artists%` except the first, which can be used to create a "feat." list.
Examples:
$setmulti(supporting_artists,$slice(%artists%,1))
$setmulti(supporting_artists,$slice(%artists%,1,-1))
"""
))
def func_slice(parser, multi, start_index, end_index=None, separator=MULTI_VALUED_JOINER):
try:
start = int(start_index.eval(parser)) if start_index else None
except ValueError:
start = None
try:
end = int(end_index.eval(parser)) if end_index else None
except ValueError:
end = None
multi_value = MultiValue(parser, multi, separator)
return multi_value.separator.join(multi_value[start:end])
@script_function(documentation=N_(
"""`$datetime(format="%Y-%m-%d %H:%M:%S")`
Returns the current date and time in the specified `format`, which is based on
the standard Python `strftime` [format codes](https://strftime.org/). If no
`format` is specified the date/time will be returned in the form
`2020-02-05 14:26:32`.
Note: Platform-specific formatting codes should be avoided to help ensure the
portability of scripts across the different platforms. These codes include:
remove zero-padding (e.g. `%-d` and `%-m` on Linux or macOS, and their
equivalent `%#d` and `%#m` on Windows); element length specifiers (e.g.
`%3Y`); and hanging '%' at the end of the format string."""
))
def func_datetime(parser, format=None):
# local_tz required for Python 3.5 which does not allow setting astimezone()
# on a naive datetime.datetime object. This provides timezone information to
# allow the use of %Z and %z in the output format.
local_tz = datetime.datetime.now(datetime.timezone.utc).astimezone().tzinfo
# Handle case where format evaluates to ''
if not format:
format = '%Y-%m-%d %H:%M:%S'
try:
return datetime.datetime.now(tz=local_tz).strftime(format)
except ValueError:
stackitem = parser._function_stack.get()
raise ScriptRuntimeError(stackitem, "Unsupported format code")
@script_function(eval_args=False, documentation=N_(
"""`$sortmulti(name,separator="; ")`
Returns a copy of the multi-value tag `name` with the elements sorted in ascending order.
Example:
$sortmulti(B; A; C)
Result: A; B; C
"""
))
def func_sortmulti(parser, multi, separator=MULTI_VALUED_JOINER):
multi_value = MultiValue(parser, multi, separator)
return multi_value.separator.join(sorted(multi_value))
@script_function(eval_args=False, documentation=N_(
"""`$reversemulti(name,separator="; ")`
Returns a copy of the multi-value tag `name` with the elements in reverse order.
This can be used in conjunction with the `$sortmulti` function to sort in
descending order.
Example:
$reversemulti($sortmulti(B; A; C))
Result: C; B; A
"""
))
def func_reversemulti(parser, multi, separator=MULTI_VALUED_JOINER):
multi_value = MultiValue(parser, multi, separator)
return multi_value.separator.join(reversed(multi_value))
@script_function(eval_args=False, documentation=N_(
"""`$unique(name,case_sensitive="",separator="; ")`
Returns a copy of the multi-value tag `name` with no duplicate elements.
By default, a case-insensitive comparison of the elements is performed.
Example 1:
$setmulti(foo,a; A; B; b; cd; Cd; cD; CD; a; A; b)
$unique(%foo%)
Result: A; CD; b
Example 2:
$setmulti(foo,a; A; B; b; a; b; A; B, cd)
$unique(%foo%,True)
Result: A; B; a; b; cd
"""
))
def func_unique(parser, multi, case_sensitive="", separator=MULTI_VALUED_JOINER):
multi_value = MultiValue(parser, multi, separator)
if not case_sensitive:
multi_value._multi = list({v.lower(): v for v in multi_value}.values())
return multi_value.separator.join(sorted(set(multi_value)))
@script_function(documentation=N_(
"""`$countryname(country_code,translate="")`
Returns the name of the country for the specified country code. If the country code is invalid an empty string will be returned.
If translate is not blank, the output will be translated into the current locale language.
"""
))
def func_countryname(parser, country_code, translate=""):
name = RELEASE_COUNTRIES.get(country_code.strip().upper(), "")
if translate:
return gettext_countries(name)
return name
DateTuple = namedtuple('DateTuple', ('year', 'month', 'day'))
def _split_date(date_to_parse, date_order="ymd"):
"""Split the specified date into parts.
Args:
date_to_parse (str): Date string to parse
date_order (str, optional): Order of date elements. Can be "ymd", "mdy" or "dmy". Defaults to "ymd".
Returns:
tuple: Tuple of the date parts as (year, month, day)
"""
parts = re.split(r'\D+', date_to_parse.strip())
parts.extend(['', '', ''])
date_order = date_order.lower()
if date_order == 'dmy':
return DateTuple(parts[2], parts[1], parts[0])
elif date_order == 'mdy':
return DateTuple(parts[2], parts[0], parts[1])
else:
return DateTuple(parts[0], parts[1], parts[2])
@script_function(documentation=N_(
"""`$year(date,date_order="ymd")`
Returns the year portion of the specified date. The default order is "ymd". This can be changed by specifying
either "dmy" or "mdy". If the date is invalid an empty string will be returned.
_Since Picard 2.7_"""
))
def func_year(parser, date_to_parse, date_order='ymd'):
return _split_date(date_to_parse, date_order).year
@script_function(documentation=N_(
"""`$month(date,date_order="ymd")`
Returns the month portion of the specified date. The default order is "ymd". This can be changed by specifying
either "dmy" or "mdy". If the date is invalid an empty string will be returned.
_Since Picard 2.7_"""
))
def func_month(parser, date_to_parse, date_order='ymd'):
return _split_date(date_to_parse, date_order).month
@script_function(documentation=N_(
"""`$day(date,date_order="ymd")`
Returns the day portion of the specified date. The default order is "ymd". This can be changed by specifying
either "dmy" or "mdy". If the date is invalid an empty string will be returned.
_Since Picard 2.7_"""
))
def func_day(parser, date_to_parse, date_order='ymd'):
return _split_date(date_to_parse, date_order).day
@script_function(documentation=N_(
"""`$dateformat(date,format="%Y-%m-%d",date_order="ymd")`
Returns the input date in the specified `format`, which is based on the standard
Python `strftime` [format codes](https://strftime.org/). If no `format` is
specified the date will be returned in the form `2020-02-05`. If the date or
format are invalid an empty string will be returned.
The default order for the input date is "ymd". This can be changed by specifying
either "dmy" or "mdy".
Note: Platform-specific formatting codes should be avoided to help ensure the
portability of scripts across the different platforms. These codes include:
remove zero-padding (e.g. `%-d` and `%-m` on Linux or macOS, and their
equivalent `%#d` and `%#m` on Windows); element length specifiers (e.g.
`%3Y`); and hanging '%' at the end of the format string.
_Since Picard 2.7_"""
))
def func_dateformat(parser, date_to_parse, date_format=None, date_order='ymd'):
# Handle case where format evaluates to ''
if not date_format:
date_format = '%Y-%m-%d'
yr, mo, da = _split_date(date_to_parse, date_order)
try:
date_object = datetime.date(int(yr), int(mo), int(da))
except ValueError:
return ''
try:
return date_object.strftime(date_format)
except ValueError:
return ''
@script_function(eval_args=False, documentation=N_(
"""`$is_multi(name)`
Returns '1' if the argument is a multi-value tag and there are more than one elements, otherwise an empty string.
Example:
$is_multi(%artists%)
Result: 1 if there is more than one artist, otherwise "".
_Since Picard 2.7_"""
))
def func_is_multi(parser, multi):
multi_value = MultiValue(parser, multi, MULTI_VALUED_JOINER)
return '' if len(multi_value) < 2 else '1'
@script_function(eval_args=True, documentation=N_(
"""`$cleanmulti(name)`
Removes all empty string elements from the multi-value variable.
Example:
$setmulti(test,one; ; two; three)
$cleanmulti(test)
Result: Sets the value of 'test' to ["one", "two", "three"].
_Since Picard 2.8_"""
))
def func_cleanmulti(parser, multi):
name = normalize_tagname(multi)
values = [str(value) for value in parser.context.getall(name) if value or value == 0]
parser.context[name] = values
return ''
def _type_args(_type, *args):
haystack = set()
# Automatically expand multi-value arguments
for item in args:
haystack = haystack.union(set(x for x in item.split(MULTI_VALUED_JOINER)))
if not _type:
_type = 'auto'
_typer = None
if _type == 'auto':
_type = 'text'
for _test_type in (int, float):
try:
_type = set(_test_type(item) for item in haystack)
_type = _test_type.__name__
break
except ValueError:
pass
_typer = None
if _type == 'int':
_typer = int
elif _type == 'float':
_typer = float
elif _type in ('text', 'nocase'):
pass
else:
# Unknown processing type
raise ValueError
if _typer is not None:
haystack = set(_typer(item) for item in haystack)
return haystack
def _extract(_func, _type, *args):
try:
haystack = _type_args(_type, *args)
except ValueError:
return ''
if _type == 'nocase':
op = operator.lt if _func == min else operator.gt
val = None
for item in haystack:
if val is None or op(item.lower(), val.lower()):
val = item
return str(val)
return str(_func(haystack))
@script_function(documentation=N_(
"""`$min(type,x,…)`
Returns the minimum value using the comparison specified in `type`.
Possible values of `type` are "int" (integer), "float" (floating point), "text"
(case-sensitive text), "nocase" (case-insensitive text) and "auto" (automatically
determine the type of arguments provided), with "auto" used as the default
comparison method if `type` is not specified. The "auto" type will use the
first type that applies to both arguments in the following order of preference:
"int", "float" and "text".
Can be used with an arbitrary number of arguments. Multi-value arguments
will be expanded automatically.
_Since Picard 2.9_"""
))
def func_min(parser, _type, x, *args):
return _extract(min, _type, x, *args)
@script_function(documentation=N_(
"""`$max(type,x,…)`
Returns the maximum value using the comparison specified in `type`.
Possible values of `type` are "int" (integer), "float" (floating point), "text"
(case-sensitive text), "nocase" (case-insensitive text) and "auto" (automatically
determine the type of arguments provided), with "auto" used as the default
comparison method if `type` is not specified. The "auto" type will use the
first type that applies to both arguments in the following order of preference:
"int", "float" and "text".
Can be used with an arbitrary number of arguments. Multi-value arguments
will be expanded automatically.
_Since Picard 2.9_"""
))
def func_max(parser, _type, x, *args):
return _extract(max, _type, x, *args)
| 45,396
|
Python
|
.py
| 1,175
| 34.235745
| 129
| 0.681832
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,971
|
recordings.py
|
metabrainz_picard/picard/acoustid/recordings.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2023-2024 Philipp Wolfer
# Copyright (C) 2024 Laurent Monin
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from collections import (
defaultdict,
deque,
namedtuple,
)
from functools import partial
from typing import (
Dict,
List,
)
from PyQt6.QtNetwork import QNetworkReply
from picard.acoustid.json_helpers import (
parse_recording,
recording_has_metadata,
)
from picard.webservice import WebService
from picard.webservice.api_helpers import MBAPIHelper
# Only do extra lookup for recordings without metadata, if they have at least
# this percentage of sources compared to the recording with most sources.
SOURCE_THRESHOLD_NO_METADATA = 0.25
# Load max. this number of recordings without metadata per AcoustID
MAX_NO_METADATA_RECORDINGS = 3
class Recording:
recording: dict
result_score: float
sources: int
def __init__(self, recording, result_score=1.0, sources=1):
self.recording = recording
self.result_score = result_score
self.sources = sources
IncompleteRecording = namedtuple('Recording', 'mbid acoustid result_score sources')
class RecordingResolver:
"""Given an AcoustID lookup result returns a list of MB recordings.
The recordings are either directly taken from the AcoustID result or, if the
results return only the MBID without metadata, loaded via the MB web service.
"""
_recording_map: Dict[str, Dict[str, Recording]]
def __init__(self, ws: WebService, doc: dict, callback: callable) -> None:
self._mbapi = MBAPIHelper(ws)
self._doc = doc
self._callback = callback
self._recording_map = defaultdict(dict)
self._recording_cache = dict()
self._missing_metadata = deque()
def resolve(self) -> None:
results = self._doc.get('results') or []
incomplete_counts = defaultdict(lambda: 0)
for result in results:
recordings = result.get('recordings') or []
result_score = get_score(result)
acoustid = result.get('id')
max_sources = max_source_count_raw_recording(recordings)
for recording in sorted(recordings, key=lambda r: r.get('sources', 1), reverse=True):
mbid = recording.get('id')
sources = recording.get('sources', 1)
if recording_has_metadata(recording):
mb_recording = parse_recording(recording)
self._recording_cache[mbid] = mb_recording
self._recording_map[acoustid][recording['id']] = Recording(
recording=mb_recording,
result_score=result_score,
sources=sources,
)
else:
if (sources / max_sources > SOURCE_THRESHOLD_NO_METADATA
and incomplete_counts[acoustid] < MAX_NO_METADATA_RECORDINGS):
self._missing_metadata.append(IncompleteRecording(
mbid=mbid,
acoustid=acoustid,
result_score=result_score,
sources=sources,
))
incomplete_counts[acoustid] += 1
self._load_recordings()
def _load_recordings(self):
if not self._missing_metadata:
self._send_results()
return
mbid = self._missing_metadata[0].mbid
if mbid in self._recording_cache:
mb_recording = self._recording_cache[mbid]
self._recording_request_finished(mbid, mb_recording, None, None)
else:
self._mbapi.get_track_by_id(
self._missing_metadata[0].mbid,
partial(self._recording_request_finished, mbid),
inc=('artists', 'release-groups', 'releases', 'media'),
)
def _recording_request_finished(self, original_mbid, mb_recording, http, error):
recording = self._missing_metadata.popleft()
if error:
if error == QNetworkReply.NetworkError.ContentNotFoundError:
# Recording does not exist, ignore and move on
self._load_recordings()
else:
self._send_results(error)
return
mbid = mb_recording.get('id')
recording_dict = self._recording_map[recording.acoustid]
if mbid:
self._recording_cache[mbid] = mb_recording
# This was a redirect, cache the old MBID as well
if original_mbid != mbid:
self._recording_cache[original_mbid] = mb_recording
if mbid not in recording_dict:
recording_dict[mbid] = Recording(
recording=mb_recording,
result_score=recording.result_score,
sources=recording.sources,
)
else:
recording_dict[mbid].sources += recording.sources
self._load_recordings()
def _send_results(self, error=None):
self._callback(list(parse_recording_map(self._recording_map)), error)
def get_score(node):
try:
return float(node.get('score', 1.0))
except (TypeError, ValueError):
return 1.0
def parse_recording_map(recording_map: Dict[str, Dict[str, Recording]]):
for acoustid, recordings in recording_map.items():
recording_list = recordings.values()
max_sources = max_source_count(recording_list)
for recording in recording_list:
parsed_recording = recording.recording
if parsed_recording is not None:
# Calculate a score based on result score and sources for this
# recording relative to other recordings in this result
score = min(recording.sources / max_sources, 1.0) * 100
parsed_recording['score'] = score * recording.result_score
parsed_recording['acoustid'] = acoustid
parsed_recording['sources'] = recording.sources
yield parsed_recording
def max_source_count(recordings: List[Recording]):
"""Given a list of recordings return the highest number of sources.
This ignores recordings without metadata.
"""
sources = {r.sources for r in recordings}
sources.add(1)
return max(sources)
def max_source_count_raw_recording(recordings: List[dict]):
"""Given a list of recordings return the highest number of sources.
This ignores recordings without metadata.
"""
sources = {r.get('sources', 1) for r in recordings}
sources.add(1)
return max(sources)
| 7,405
|
Python
|
.py
| 168
| 34.559524
| 97
| 0.636969
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,972
|
json_helpers.py
|
metabrainz_picard/picard/acoustid/json_helpers.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2017 Sambhav Kothari
# Copyright (C) 2018-2020, 2023 Philipp Wolfer
# Copyright (C) 2020 Ray Bouchard
# Copyright (C) 2020-2021 Laurent Monin
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""
The idea here is to bring the data returned by the AcoustID service into the
same format as the JSON result from the MB web service. Below methods help us
to do that conversion process.
"""
def _make_releases_node(recording):
release_list = []
for release_group in recording['releasegroups']:
for release in release_group['releases']:
release_mb = {}
release_mb['id'] = release['id']
release_mb['release-group'] = {}
release_mb['release-group']['id'] = release_group['id']
if 'type' in release_group:
release_mb['release-group']['primary-type'] = release_group['type']
if 'secondarytypes' in release_group:
release_mb['release-group']['secondary-types'] = release_group['secondarytypes']
if 'title' in release:
release_mb['title'] = release['title']
else:
release_mb['title'] = release_group['title']
if 'country' in release:
release_mb['country'] = release['country']
if 'date' in release:
release_mb['date'] = release['date']
if 'medium_count' in release:
release_mb['medium-count'] = release['medium_count']
if 'track_count' in release:
release_mb['track-count'] = release['track_count']
release_mb['media'] = []
for medium in release['mediums']:
media_mb = {}
if 'format' in medium:
media_mb['format'] = medium['format']
if 'track_count' in medium:
media_mb['track-count'] = medium['track_count']
if 'position' in medium:
media_mb['position'] = medium['position']
if 'tracks' in medium:
media_mb['track'] = medium['tracks']
for track_mb in media_mb['track']:
track_mb['number'] = track_mb['position']
release_mb['media'].append(media_mb)
# AcoustId service is returning country/date as attrib of the release, but really, according to MusicBrainz database schema definition,
# https://musicbrainz.org/doc/MusicBrainz_Database/Schema
# Its a one-to-many sub attribute in release events.
# They do return the releaseevents, but seem to be copying the first one on to the release.
# So if we have releaseevents, then use them to create multiple records, and ignore what is coming on the release
if 'releaseevents' in release:
for releaseevent in release['releaseevents']:
release_mb['country'] = releaseevent.get('country', '')
release_mb['date'] = releaseevent.get('date', '')
release_list.append(release_mb)
else:
release_list.append(release_mb)
return release_list
def _make_artist_node(artist):
artist_node = {
'name': artist['name'],
'sort-name': artist['name'],
'id': artist['id']
}
return artist_node
def _make_artist_credit_node(artists):
artist_list = []
for i, artist in enumerate(artists):
node = {
'artist': _make_artist_node(artist),
'name': artist['name']
}
if i > 0:
node['joinphrase'] = '; '
artist_list.append(node)
return artist_list
def parse_recording(recording):
if 'id' not in recording: # we have no metadata for this recording
return
recording_mb = {
'id': recording['id']
}
if 'title' in recording:
recording_mb['title'] = recording['title']
if 'artists' in recording:
recording_mb['artist-credit'] = _make_artist_credit_node(recording['artists'])
if 'releasegroups' in recording:
recording_mb['releases'] = _make_releases_node(recording)
if 'duration' in recording:
try:
recording_mb['length'] = int(recording['duration']) * 1000
except TypeError:
pass
if 'sources' in recording:
recording_mb['sources'] = recording['sources']
return recording_mb
def recording_has_metadata(recording):
return 'id' in recording and recording.get('title') is not None
| 5,309
|
Python
|
.py
| 118
| 35.635593
| 147
| 0.612672
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,973
|
manager.py
|
metabrainz_picard/picard/acoustid/manager.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2011 Lukáš Lalinský
# Copyright (C) 2017 Sambhav Kothari
# Copyright (C) 2018 Vishal Choudhary
# Copyright (C) 2018, 2020-2021, 2023-2024 Laurent Monin
# Copyright (C) 2020, 2022-2023 Philipp Wolfer
# Copyright (C) 2022 cybersphinx
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from functools import partial
from PyQt6 import QtCore
from picard import log
from picard.i18n import N_
from picard.util import load_json
from picard.ui.enums import MainAction
# Maximum difference between file duration and MB recording length.
# If the match is above this threshold the MBID will not get submitted.
# Compare also acoustid/const.py in acoustid-server sources
FINGERPRINT_MAX_ALLOWED_LENGTH_DIFF_MS = 30000
class Submission:
def __init__(self, fingerprint, duration, recordingid=None, metadata=None):
self.fingerprint = fingerprint
self.duration = duration
self.recordingid = self.orig_recordingid = recordingid
self.metadata = metadata
self.attempts = 0
def __len__(self):
# payload approximation
# the length of all submitted data, plus a small overhead to account for
# potential urlencode expansion
return int(sum((len(key) + len(value) + 2 for key, value in self.args.items())) * 1.03)
def __bool__(self):
return bool(self.fingerprint and self.duration is not None)
def __repr__(self):
return '<%s %r, %d, %r>' % (self.__class__.__name__, self.fingerprint, self.duration, self.recordingid)
@property
def puid(self):
return self.metadata.get('musicip_puid', '') if self.metadata else ''
@property
def valid_duration(self):
return self.metadata is None or abs(self.duration * 1000 - self.metadata.length) <= FINGERPRINT_MAX_ALLOWED_LENGTH_DIFF_MS
@property
def is_submitted(self):
return not self.recordingid or self.orig_recordingid == self.recordingid
@property
def args(self):
"""Returns a dictionary of arguments suitable for submission to AcoustID."""
args = {
'fingerprint': self.fingerprint,
'duration': str(self.duration),
}
metadata = self.metadata
if metadata:
puid = metadata['musicip_puid']
if puid:
args['puid'] = puid
if self.valid_duration and self.recordingid:
args['mbid'] = self.recordingid
elif metadata:
args['track'] = metadata['title']
args['artist'] = metadata['artist']
args['album'] = metadata['album']
args['albumartist'] = metadata['albumartist']
args['trackno'] = metadata['tracknumber']
args['discno'] = metadata['discnumber']
year = metadata['year'] or metadata['date'][:4]
if year and year.isdecimal():
args['year'] = year
return args
class AcoustIDManager:
# AcoustID has a post limit of around 1 MB.
MAX_PAYLOAD = 1000000
# Limit each submission to N attempts
MAX_ATTEMPTS = 5
# In case of Payload Too Large error, batch size is reduced by this factor
# and a retry occurs
BATCH_SIZE_REDUCTION_FACTOR = 0.7
def __init__(self, acoustid_api):
self.tagger = QtCore.QCoreApplication.instance()
self._submissions = {}
self._acoustid_api = acoustid_api
def add(self, file, recordingid):
if not file.acoustid_fingerprint or not file.acoustid_length:
return
metadata = file.metadata
self._submissions[file] = Submission(
file.acoustid_fingerprint, file.acoustid_length, recordingid, metadata)
self._check_unsubmitted()
def update(self, file, recordingid):
submission = self._submissions.get(file)
if submission is None:
return
submission.recordingid = recordingid
submission.metadata = file.metadata
self._check_unsubmitted()
def remove(self, file):
if file in self._submissions:
del self._submissions[file]
self._check_unsubmitted()
def is_submitted(self, file):
submission = self._submissions.get(file)
if submission:
return submission.is_submitted
return True
def _unsubmitted(self, reset=False):
for file, submission in self._submissions.items():
if not submission.is_submitted:
if reset:
submission.attempts = 0
yield (file, submission)
def _check_unsubmitted(self):
enabled = next(self._unsubmitted(), None) is not None
self.tagger.window.enable_action(MainAction.SUBMIT_ACOUSTID, enabled)
def submit(self):
self.max_batch_size = self.MAX_PAYLOAD
submissions = list(self._unsubmitted(reset=True))
if not submissions:
self._check_unsubmitted()
return
log.debug("AcoustID: submitting total of %d fingerprints…", len(submissions))
self._batch_submit(submissions)
def _batch(self, submissions):
batch = []
remaining = []
batch_size = 0
max_attempts = self.MAX_ATTEMPTS
for file, submission in submissions:
if submission.attempts < max_attempts:
batch_size += len(submission)
if batch_size < self.max_batch_size:
submission.attempts += 1
batch.append((file, submission))
continue
else:
# force appending the rest to remaining if we reach max_batch_size
max_attempts = 0
remaining.append((file, submission))
return batch, remaining
def _batch_submit(self, submissions, errors=None):
if not submissions: # All fingerprints submitted, nothing to do
if errors:
log_msg = N_("AcoustID submission finished, but not all fingerprints have been submitted")
else:
log_msg = N_("AcoustID submission finished successfully")
log.debug(log_msg)
self.tagger.window.set_statusbar_message(
log_msg, echo=None, timeout=3000)
self._check_unsubmitted()
return
batch, submissions = self._batch(submissions)
if not batch:
if self.max_batch_size == 0:
log_msg = N_("AcoustID submission failed permanently, maximum batch size reduced to zero")
else:
log_msg = N_("AcoustID submission failed permanently, probably too many retries")
log.error(log_msg)
self.tagger.window.set_statusbar_message(
log_msg, echo=None, timeout=3000)
self._check_unsubmitted()
return
log.debug("AcoustID: submitting batch of %d fingerprints (%d remaining)…",
len(batch), len(submissions))
self.tagger.window.set_statusbar_message(
N_("Submitting AcoustIDs …"),
echo=None
)
if not errors:
errors = []
self._acoustid_api.submit_acoustid_fingerprints(
[submission for file_, submission in batch],
partial(self._batch_submit_finished, submissions, batch, errors)
)
def _batch_submit_finished(self, submissions, batch, previous_errors, document, http, error):
if error:
# re-add batched items to remaining list
submissions.extend(batch)
response_code = self._acoustid_api.webservice.http_response_code(http)
if response_code == 413:
self.max_batch_size = int(self.max_batch_size * self.BATCH_SIZE_REDUCTION_FACTOR)
log.warn("AcoustID: payload too large, batch size reduced to %d", self.max_batch_size)
else:
try:
errordoc = load_json(document)
message = errordoc['error']['message']
except BaseException:
message = ""
mparms = {
'error': http.errorString(),
'message': message
}
previous_errors.append(mparms)
log_msg = N_("AcoustID submission failed with error '%(error)s': %(message)s")
log.error(log_msg, mparms)
self.tagger.window.set_statusbar_message(
log_msg, mparms, echo=None, timeout=3000)
else:
log.debug("AcoustID: %d fingerprints successfully submitted", len(batch))
for file, submission in batch:
submission.orig_recordingid = submission.recordingid
file.update()
self._check_unsubmitted()
self._batch_submit(submissions, previous_errors)
| 9,592
|
Python
|
.py
| 217
| 34.391705
| 130
| 0.626835
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,974
|
__init__.py
|
metabrainz_picard/picard/acoustid/__init__.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2011 Lukáš Lalinský
# Copyright (C) 2017-2018 Sambhav Kothari
# Copyright (C) 2018 Vishal Choudhary
# Copyright (C) 2018-2021, 2023-2024 Laurent Monin
# Copyright (C) 2018-2024 Philipp Wolfer
# Copyright (C) 2023 Bob Swift
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from collections import (
deque,
namedtuple,
)
from enum import IntEnum
from functools import partial
import json
from PyQt6 import QtCore
from picard import log
from picard.acoustid.recordings import RecordingResolver
from picard.config import get_config
from picard.const import FPCALC_NAMES
from picard.const.defaults import DEFAULT_FPCALC_THREADS
from picard.const.sys import IS_WIN
from picard.file import File
from picard.i18n import N_
from picard.util import (
find_executable,
win_prefix_longpath,
)
from picard.webservice.api_helpers import AcoustIdAPIHelper
class FpcalcExit(IntEnum):
# fpcalc returned successfully
NOERROR = 0
# fpcalc encountered errors during decoding, but could still generate a fingerprint
DECODING_ERROR = 3
def get_score(node):
try:
return float(node.get('score', 1.0))
except (TypeError, ValueError):
return 1.0
def get_fpcalc(config=None):
if not config:
config = get_config()
fpcalc_path = config.setting["acoustid_fpcalc"]
if not fpcalc_path:
fpcalc_path = find_fpcalc()
return fpcalc_path or 'fpcalc'
def find_fpcalc():
return find_executable(*FPCALC_NAMES)
AcoustIDTask = namedtuple('AcoustIDTask', ('file', 'next_func'))
class AcoustIDClient(QtCore.QObject):
def __init__(self, acoustid_api: AcoustIdAPIHelper):
super().__init__()
self.tagger = QtCore.QCoreApplication.instance()
self._queue = deque()
self._running = 0
self._acoustid_api = acoustid_api
def init(self):
pass
def done(self):
pass
def get_max_processes(self):
config = get_config()
return config.setting['fpcalc_threads'] or DEFAULT_FPCALC_THREADS
def _on_lookup_finished(self, task, document, http, error):
if error:
mparms = {
'error': http.errorString(),
'body': document,
'filename': task.file.filename,
}
log.error(
"AcoustID: Lookup network error for '%(filename)s': %(error)r, %(body)s" %
mparms)
self.tagger.window.set_statusbar_message(
N_("AcoustID lookup network error for '%(filename)s'!"),
mparms,
echo=None
)
task.next_func({}, http, error)
else:
try:
status = document['status']
if status == 'ok':
resolver = RecordingResolver(
self._acoustid_api.webservice,
document,
callback=partial(self._on_recording_resolve_finish, task, document, http))
resolver.resolve()
else:
mparms = {
'error': document['error']['message'],
'filename': task.file.filename
}
log.error(
"AcoustID: Lookup error for '%(filename)s': %(error)r" %
mparms)
self.tagger.window.set_statusbar_message(
N_("AcoustID lookup failed for '%(filename)s'!"),
mparms,
echo=None
)
task.next_func({}, http, error)
except (AttributeError, KeyError, TypeError) as e:
log.error("AcoustID: Error reading response", exc_info=True)
task.next_func({}, http, e)
def _on_recording_resolve_finish(self, task, document, http, result=None, error=None):
recording_list = result
if not recording_list:
results = document.get('results')
if results:
# Set AcoustID in tags if there was no matching recording
acoustid = results[0].get('id')
task.file.metadata['acoustid_id'] = acoustid
task.file.update()
log.debug(
"AcoustID: Found no matching recordings for '%s',"
" setting acoustid_id tag to %r",
task.file.filename, acoustid
)
else:
log.debug(
"AcoustID: Lookup successful for '%s' (recordings: %d)",
task.file.filename,
len(recording_list)
)
task.next_func({'recordings': recording_list}, http, error)
def _lookup_fingerprint(self, task, result=None, error=None):
if task.file.state == File.REMOVED:
log.debug("File %r was removed", task.file)
return
mparms = {
'filename': task.file.filename
}
if not result:
log.debug(
"AcoustID: lookup returned no result for file '%(filename)s'" %
mparms
)
self.tagger.window.set_statusbar_message(
N_("AcoustID lookup returned no result for file '%(filename)s'"),
mparms,
echo=None
)
task.file.clear_pending()
return
log.debug(
"AcoustID: looking up the fingerprint for file '%(filename)s'" %
mparms
)
self.tagger.window.set_statusbar_message(
N_("Looking up the fingerprint for file '%(filename)s' …"),
mparms,
echo=None
)
params = dict(meta='recordings releasegroups releases tracks compress sources')
if result[0] == 'fingerprint':
fp_type, fingerprint, length = result
params['fingerprint'] = fingerprint
params['duration'] = str(length)
else:
fp_type, recordingid = result
params['recordingid'] = recordingid
self._acoustid_api.query_acoustid(partial(self._on_lookup_finished, task), **params)
def _on_fpcalc_finished(self, task, exit_code, exit_status):
process = self.sender()
finished = process.property('picard_finished')
if finished:
return
process.setProperty('picard_finished', True)
result = None
try:
self._running -= 1
self._run_next_task()
# fpcalc returns the exit code 3 in case of decoding errors that
# still allowed it to calculate a result.
if exit_code in {FpcalcExit.NOERROR, FpcalcExit.DECODING_ERROR} and exit_status == QtCore.QProcess.ExitStatus.NormalExit:
if exit_code == FpcalcExit.DECODING_ERROR:
error = bytes(process.readAllStandardError()).decode()
log.warning("fpcalc non-critical decoding errors for %s: %s", task.file, error)
output = bytes(process.readAllStandardOutput()).decode()
jsondata = json.loads(output)
# Use only integer part of duration, floats are not allowed in lookup
duration = int(jsondata.get('duration'))
fingerprint = jsondata.get('fingerprint')
if fingerprint and duration:
result = 'fingerprint', fingerprint, duration
else:
log.error(
"Fingerprint calculator failed exit code = %r, exit status = %r, error = %s",
exit_code,
exit_status,
process.errorString())
except (json.decoder.JSONDecodeError, UnicodeDecodeError, ValueError):
log.error("Error reading fingerprint calculator output", exc_info=True)
finally:
if result and result[0] == 'fingerprint':
fp_type, fingerprint, length = result
# Only set the fingerprint if it was calculated without
# decoding errors. Otherwise fingerprints for broken files
# might get submitted.
if exit_code == FpcalcExit.NOERROR:
task.file.set_acoustid_fingerprint(fingerprint, length)
task.next_func(result)
def _on_fpcalc_error(self, task, error):
process = self.sender()
finished = process.property('picard_finished')
if finished:
return
process.setProperty('picard_finished', True)
try:
self._running -= 1
self._run_next_task()
log.error(
"Fingerprint calculator failed error= %s (%r) program=%r arguments=%r",
process.errorString(), error, process.program(), process.arguments()
)
finally:
task.next_func(None)
def _run_next_task(self):
try:
task = self._queue.popleft()
except IndexError:
return
if task.file.state == File.REMOVED:
log.debug("File %r was removed", task.file)
return
self._running += 1
process = QtCore.QProcess(self)
process.setProperty('picard_finished', False)
process.finished.connect(partial(self._on_fpcalc_finished, task))
process.errorOccurred.connect(partial(self._on_fpcalc_error, task))
file_path = task.file.filename
# On Windows fpcalc.exe does not handle long paths, even if system wide
# long path support is enabled. Ensure the path is properly prefixed.
if IS_WIN:
file_path = win_prefix_longpath(file_path)
process.start(self._fpcalc, ['-json', '-length', '120', file_path])
log.debug("Starting fingerprint calculator %r %r", self._fpcalc, task.file.filename)
def analyze(self, file, next_func):
fpcalc_next = partial(self._lookup_fingerprint, AcoustIDTask(file, next_func))
task = AcoustIDTask(file, fpcalc_next)
config = get_config()
fingerprint = task.file.acoustid_fingerprint
if not fingerprint and not config.setting['ignore_existing_acoustid_fingerprints']:
# use cached fingerprint from file metadata
fingerprints = task.file.metadata.getall('acoustid_fingerprint')
if fingerprints:
fingerprint = fingerprints[0]
task.file.set_acoustid_fingerprint(fingerprint)
# If the fingerprint already exists skip calling fpcalc
if fingerprint:
length = task.file.acoustid_length
fpcalc_next(result=('fingerprint', fingerprint, length))
return
# calculate the fingerprint
self._fingerprint(task)
def _fingerprint(self, task):
if task.file.state == File.REMOVED:
log.debug("File %r was removed", task.file)
return
self._queue.append(task)
self._fpcalc = get_fpcalc()
if self._running < self.get_max_processes():
self._run_next_task()
def fingerprint(self, file, next_func):
self._fingerprint(AcoustIDTask(file, next_func))
def stop_analyze(self, file):
new_queue = deque()
for task in self._queue:
if task.file != file and task.file.state != File.REMOVED:
new_queue.appendleft(task)
self._queue = new_queue
| 12,214
|
Python
|
.py
| 288
| 31.527778
| 133
| 0.596568
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,975
|
metadatabox.py
|
metabrainz_picard/picard/ui/metadatabox.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2004 Robert Kaye
# Copyright (C) 2006-2007, 2012 Lukáš Lalinský
# Copyright (C) 2011-2014 Michael Wiencek
# Copyright (C) 2012 Nikolai Prokoschenko
# Copyright (C) 2013-2014, 2017-2024 Laurent Monin
# Copyright (C) 2013-2014, 2021 Sophist-UK
# Copyright (C) 2015 Ohm Patel
# Copyright (C) 2015 Wieland Hoffmann
# Copyright (C) 2015, 2018-2023 Philipp Wolfer
# Copyright (C) 2016-2018 Sambhav Kothari
# Copyright (C) 2018 Vishal Choudhary
# Copyright (C) 2020 Felix Schwarz
# Copyright (C) 2020-2021 Gabriel Ferreira
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from collections import (
Counter,
defaultdict,
namedtuple,
)
from functools import partial
from PyQt6 import (
QtCore,
QtGui,
QtWidgets,
)
from picard.album import Album
from picard.browser.filelookup import FileLookup
from picard.cluster import Cluster
from picard.config import get_config
from picard.file import File
from picard.i18n import (
gettext as _,
ngettext,
)
from picard.metadata import MULTI_VALUED_JOINER
from picard.track import Track
from picard.util import (
IgnoreUpdatesContext,
format_time,
icontheme,
restore_method,
thread,
throttle,
)
from picard.util.preservedtags import PreservedTags
from picard.util.tags import display_tag_name
from picard.ui.colors import interface_colors
from picard.ui.edittagdialog import (
EditTagDialog,
TagEditorDelegate,
)
class TagStatus:
NONE = 0
NOCHANGE = 1
ADDED = 2
REMOVED = 4
CHANGED = ADDED | REMOVED
EMPTY = 8
NOTREMOVABLE = 16
READONLY = 32
TagCounterDisplayValue = namedtuple('TagCounterDisplayValue', ('text', 'is_grouped'))
class TagCounter(dict):
__slots__ = ('parent', 'counts', 'different')
def __init__(self, parent):
self.parent = parent
self.counts = Counter()
self.different = set()
def __getitem__(self, tag):
return super().get(tag, [""])
def add(self, tag, values):
if tag not in self.different:
if tag not in self:
self[tag] = values
elif self[tag] != values:
self.different.add(tag)
self[tag] = [""]
self.counts[tag] += 1
def display_value(self, tag):
count = self.counts[tag]
missing = self.parent.objects - count
if tag in self.different:
text = ngettext("(different across %d item)", "(different across %d items)", count) % count
is_grouped = True
else:
if tag == '~length':
msg = format_time(self.get(tag, 0))
else:
msg = MULTI_VALUED_JOINER.join(self[tag])
if count > 0 and missing > 0:
text = msg + " " + (ngettext("(missing from %d item)", "(missing from %d items)", missing) % missing)
is_grouped = True
else:
text = msg
is_grouped = False
return TagCounterDisplayValue(text, is_grouped)
class TagDiff:
__slots__ = ('tag_names', 'new', 'orig', 'status', 'objects', 'max_length_delta_ms')
def __init__(self, max_length_diff=2):
self.tag_names = []
self.new = TagCounter(self)
self.orig = TagCounter(self)
self.status = defaultdict(lambda: TagStatus.NONE)
self.objects = 0
self.max_length_delta_ms = max_length_diff * 1000
def __tag_ne(self, tag, orig, new):
if tag == '~length':
return abs(float(orig) - float(new)) > self.max_length_delta_ms
else:
return orig != new
def add(self, tag, orig_values, new_values, removable, removed=False, readonly=False, top_tags=None):
if orig_values:
self.orig.add(tag, orig_values)
if new_values:
self.new.add(tag, new_values)
if not top_tags:
top_tags = set()
if (orig_values and not new_values) or removed:
self.status[tag] |= TagStatus.REMOVED
elif new_values and not orig_values:
self.status[tag] |= TagStatus.ADDED
removable = True
elif orig_values and new_values and self.__tag_ne(tag, orig_values, new_values):
self.status[tag] |= TagStatus.CHANGED
elif not (orig_values or new_values or tag in top_tags):
self.status[tag] |= TagStatus.EMPTY
else:
self.status[tag] |= TagStatus.NOCHANGE
if not removable:
self.status[tag] |= TagStatus.NOTREMOVABLE
if readonly:
self.status[tag] |= TagStatus.READONLY
def tag_status(self, tag):
status = self.status[tag]
for s in (TagStatus.CHANGED, TagStatus.ADDED,
TagStatus.REMOVED, TagStatus.EMPTY):
if status & s == s:
return s
return TagStatus.NOCHANGE
class TableTagEditorDelegate(TagEditorDelegate):
def createEditor(self, parent, option, index):
editor = super().createEditor(parent, option, index)
if editor and isinstance(editor, QtWidgets.QPlainTextEdit):
table = self.parent()
# Set the editor to the row height, but at least 80 pixel
# to allow for proper multiline editing.
height = max(80, table.rowHeight(index.row()) - 1)
editor.setMinimumSize(QtCore.QSize(0, height))
# Resize the row so the editor fits in. Add 1 pixel, otherwise the
# frame gets hidden.
table.setRowHeight(index.row(), editor.frameSize().height() + 1)
return editor
def sizeHint(self, option, index):
# Expand the row for multiline content, but limit the maximum row height.
size_hint = super().sizeHint(option, index)
return QtCore.QSize(size_hint.width(), min(160, size_hint.height()))
def get_tag_name(self, index):
return index.data(QtCore.Qt.ItemDataRole.UserRole)
class MetadataBox(QtWidgets.QTableWidget):
COLUMN_TAG = 0
COLUMN_ORIG = 1
COLUMN_NEW = 2
# keys are tags
# values are FileLookup methods (as string)
# to use to look up for the matching tag
LOOKUP_TAGS = {
'acoustid_id': 'acoust_lookup',
'musicbrainz_albumartistid': 'artist_lookup',
'musicbrainz_albumid': 'album_lookup',
'musicbrainz_artistid': 'artist_lookup',
'musicbrainz_discid': 'discid_lookup',
'musicbrainz_recordingid': 'recording_lookup',
'musicbrainz_releasegroupid': 'release_group_lookup',
'musicbrainz_trackid': 'track_lookup',
'musicbrainz_workid': 'work_lookup',
}
def __init__(self, parent=None):
super().__init__(parent=parent)
self.tagger = QtCore.QCoreApplication.instance()
config = get_config()
self.setAccessibleName(_("metadata view"))
self.setAccessibleDescription(_("Displays original and new tags for the selected files"))
self.setColumnCount(3)
self.setHorizontalHeaderLabels((_("Tag"), _("Original Value"), _("New Value")))
self.horizontalHeader().setStretchLastSection(True)
self.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.ResizeMode.Stretch)
self.horizontalHeader().setSectionsClickable(False)
self.verticalHeader().setDefaultSectionSize(21)
self.verticalHeader().setVisible(False)
self.setHorizontalScrollMode(QtWidgets.QAbstractItemView.ScrollMode.ScrollPerPixel)
self.setSelectionMode(QtWidgets.QAbstractItemView.SelectionMode.ExtendedSelection)
self.setTabKeyNavigation(False)
self.setStyleSheet("QTableWidget {border: none;}")
self.setAttribute(QtCore.Qt.WidgetAttribute.WA_MacShowFocusRect, 1)
self.setItemDelegate(TableTagEditorDelegate(self))
self.setWordWrap(False)
self.files = set()
self.tracks = set()
self.objects = set()
self.tag_diff = None
self.selection_mutex = QtCore.QMutex()
self.selection_dirty = False
self.editing = None # the QTableWidgetItem being edited
self.clipboard = [""]
self.add_tag_action = QtGui.QAction(_("Add New Tag…"), self)
self.add_tag_action.triggered.connect(partial(self._edit_tag, ""))
self.changes_first_action = QtGui.QAction(_("Show Changes First"), self)
self.changes_first_action.setCheckable(True)
self.changes_first_action.setChecked(config.persist['show_changes_first'])
self.changes_first_action.toggled.connect(self._toggle_changes_first)
# TR: Keyboard shortcut for "Add New Tag…"
self.add_tag_shortcut = QtGui.QShortcut(QtGui.QKeySequence(_("Alt+Shift+A")), self, partial(self._edit_tag, ""))
self.add_tag_action.setShortcut(self.add_tag_shortcut.key())
# TR: Keyboard shortcut for "Edit…" (tag)
self.edit_tag_shortcut = QtGui.QShortcut(QtGui.QKeySequence(_("Alt+Shift+E")), self, partial(self._edit_selected_tag))
# TR: Keyboard shortcut for "Remove" (tag)
self.remove_tag_shortcut = QtGui.QShortcut(QtGui.QKeySequence(_("Alt+Shift+R")), self, self.remove_selected_tags)
self.preserved_tags = PreservedTags()
self._single_file_album = False
self._single_track_album = False
self.ignore_updates = IgnoreUpdatesContext(on_exit=self.update)
self.tagger.clipboard().dataChanged.connect(self._update_clipboard)
def _get_file_lookup(self):
"""Return a FileLookup object."""
config = get_config()
return FileLookup(self, config.setting['server_host'],
config.setting['server_port'],
self.tagger.browser_integration.port)
def _lookup_tag(self, tag):
lookup = self._get_file_lookup()
return getattr(lookup, self.LOOKUP_TAGS[tag])
def _open_link(self, values, tag):
lookup_func = self._lookup_tag(tag)
for v in values:
lookup_func(v)
def edit(self, index, trigger, event):
if index.column() != self.COLUMN_NEW:
return False
item = self.itemFromIndex(index)
if item.flags() & QtCore.Qt.ItemFlag.ItemIsEditable and \
trigger in {QtWidgets.QAbstractItemView.EditTrigger.DoubleClicked,
QtWidgets.QAbstractItemView.EditTrigger.EditKeyPressed,
QtWidgets.QAbstractItemView.EditTrigger.AnyKeyPressed}:
tag = self.tag_diff.tag_names[item.row()]
values = self.tag_diff.new[tag]
if len(values) > 1:
self._edit_tag(tag)
return False
else:
self.editing = item
item.setText(values[0])
return super().edit(index, trigger, event)
return False
def keyPressEvent(self, event):
if event.matches(QtGui.QKeySequence.StandardKey.Copy):
self._copy_value()
elif event.matches(QtGui.QKeySequence.StandardKey.Paste):
self._paste_value()
else:
super().keyPressEvent(event)
def _copy_value(self):
item = self.currentItem()
if item:
column = item.column()
tag = self.tag_diff.tag_names[item.row()]
value = None
if column == self.COLUMN_ORIG:
value = self.tag_diff.orig[tag]
elif column == self.COLUMN_NEW:
value = self.tag_diff.new[tag]
if tag == '~length':
value = [format_time(value or 0), ]
if value is not None:
self.tagger.clipboard().setText(MULTI_VALUED_JOINER.join(value))
self.clipboard = value
def _paste_value(self):
item = self.currentItem()
if item:
column = item.column()
tag = self.tag_diff.tag_names[item.row()]
if column == self.COLUMN_NEW and self._tag_is_editable(tag):
self._set_tag_values(tag, self.clipboard)
self.update()
def _update_clipboard(self):
clipboard = self.tagger.clipboard().text().split(MULTI_VALUED_JOINER)
if clipboard:
self.clipboard = clipboard
def closeEditor(self, editor, hint):
super().closeEditor(editor, hint)
tag = self.tag_diff.tag_names[self.editing.row()]
old = self.tag_diff.new[tag]
new = [self._get_editor_value(editor)]
if old == new:
self.editing.setText(old[0])
else:
self._set_tag_values(tag, new)
self.editing = None
self.update(drop_album_caches=tag == 'album')
@staticmethod
def _get_editor_value(editor):
if hasattr(editor, 'text'):
return editor.text()
elif hasattr(editor, 'toPlainText'):
return editor.toPlainText()
return ''
def contextMenuEvent(self, event):
menu = QtWidgets.QMenu(self)
if self.objects:
tags = list(self._selected_tags())
single_tag = len(tags) == 1
if single_tag:
selected_tag = tags[0]
editable = self._tag_is_editable(selected_tag)
edit_tag_action = QtGui.QAction(_("Edit…"), self)
edit_tag_action.triggered.connect(partial(self._edit_tag, selected_tag))
edit_tag_action.setShortcut(self.edit_tag_shortcut.key())
edit_tag_action.setEnabled(editable)
menu.addAction(edit_tag_action)
if selected_tag not in self.preserved_tags:
add_to_preserved_tags_action = QtGui.QAction(_("Add to 'Preserve Tags' List"), self)
add_to_preserved_tags_action.triggered.connect(partial(self.preserved_tags.add, selected_tag))
add_to_preserved_tags_action.setEnabled(editable)
menu.addAction(add_to_preserved_tags_action)
else:
remove_from_preserved_tags_action = QtGui.QAction(_("Remove from 'Preserve Tags' List"), self)
remove_from_preserved_tags_action.triggered.connect(partial(self.preserved_tags.discard, selected_tag))
remove_from_preserved_tags_action.setEnabled(editable)
menu.addAction(remove_from_preserved_tags_action)
removals = []
useorigs = []
item = self.currentItem()
if item:
column = item.column()
for tag in tags:
if tag in self.LOOKUP_TAGS:
if (column == self.COLUMN_ORIG or column == self.COLUMN_NEW) and single_tag and item.text():
if column == self.COLUMN_ORIG:
values = self.tag_diff.orig[tag]
else:
values = self.tag_diff.new[tag]
lookup_action = QtGui.QAction(_("Lookup in &Browser"), self)
lookup_action.triggered.connect(partial(self._open_link, values, tag))
menu.addAction(lookup_action)
if self._tag_is_removable(tag):
removals.append(partial(self._remove_tag, tag))
status = self.tag_diff.status[tag] & TagStatus.CHANGED
if status == TagStatus.CHANGED or status == TagStatus.REMOVED:
file_tracks = []
track_albums = set()
for file in self.files:
objects = [file]
if file.parent_item in self.tracks and len(self.files & set(file.parent_item.files)) == 1:
objects.append(file.parent_item)
file_tracks.append(file.parent_item)
track_albums.add(file.parent_item.album)
orig_values = list(file.orig_metadata.getall(tag)) or [""]
useorigs.append(partial(self._set_tag_values, tag, orig_values, objects))
for track in set(self.tracks)-set(file_tracks):
objects = [track]
orig_values = list(track.orig_metadata.getall(tag)) or [""]
useorigs.append(partial(self._set_tag_values, tag, orig_values, objects))
track_albums.add(track.album)
for album in track_albums:
objects = [album]
orig_values = list(album.orig_metadata.getall(tag)) or [""]
useorigs.append(partial(self._set_tag_values, tag, orig_values, objects))
remove_tag_action = QtGui.QAction(_("Remove"), self)
remove_tag_action.triggered.connect(partial(self._apply_update_funcs, removals))
remove_tag_action.setShortcut(self.remove_tag_shortcut.key())
remove_tag_action.setEnabled(bool(removals))
menu.addAction(remove_tag_action)
if useorigs:
name = ngettext("Use Original Value", "Use Original Values", len(useorigs))
use_orig_value_action = QtGui.QAction(name, self)
use_orig_value_action.triggered.connect(partial(self._apply_update_funcs, useorigs))
menu.addAction(use_orig_value_action)
menu.addSeparator()
if single_tag:
menu.addSeparator()
copy_action = QtGui.QAction(icontheme.lookup('edit-copy', icontheme.ICON_SIZE_MENU), _("&Copy"), self)
copy_action.triggered.connect(self._copy_value)
copy_action.setShortcut(QtGui.QKeySequence.StandardKey.Copy)
menu.addAction(copy_action)
paste_action = QtGui.QAction(icontheme.lookup('edit-paste', icontheme.ICON_SIZE_MENU), _("&Paste"), self)
paste_action.triggered.connect(self._paste_value)
paste_action.setShortcut(QtGui.QKeySequence.StandardKey.Paste)
paste_action.setEnabled(editable)
menu.addAction(paste_action)
if single_tag or removals or useorigs:
menu.addSeparator()
menu.addAction(self.add_tag_action)
menu.addSeparator()
menu.addAction(self.changes_first_action)
menu.exec(event.globalPos())
event.accept()
def _apply_update_funcs(self, funcs):
with self.tagger.window.ignore_selection_changes:
for f in funcs:
f()
self.tagger.window.update_selection(new_selection=False, drop_album_caches=True)
def _edit_tag(self, tag):
if self.tag_diff is not None:
EditTagDialog(self, tag).exec()
def _edit_selected_tag(self):
tags = list(self._selected_tags(filter_func=self._tag_is_editable))
if len(tags) == 1:
self._edit_tag(tags[0])
def _toggle_changes_first(self, checked):
config = get_config()
config.persist['show_changes_first'] = checked
self.update()
def _set_tag_values(self, tag, values, objects=None):
if objects is None:
objects = self.objects
with self.tagger.window.ignore_selection_changes:
if values == [""]:
values = []
if not values and self._tag_is_removable(tag):
for obj in objects:
del obj.metadata[tag]
obj.update()
elif values:
for obj in objects:
obj.metadata[tag] = values
obj.update()
def _remove_tag(self, tag):
self._set_tag_values(tag, [])
def remove_selected_tags(self):
for tag in self._selected_tags(filter_func=self._tag_is_removable):
self._remove_tag(tag)
self.tagger.window.update_selection(new_selection=False, drop_album_caches=True)
def _tag_is_removable(self, tag):
return self.tag_diff.status[tag] & TagStatus.NOTREMOVABLE == 0
def _tag_is_editable(self, tag):
return self.tag_diff.status[tag] & TagStatus.READONLY == 0
def _selected_tags(self, filter_func=None):
for tag in set(self.tag_diff.tag_names[item.row()]
for item in self.selectedItems()):
if filter_func is None or filter_func(tag):
yield tag
def _update_selection(self):
if not hasattr(self.tagger, 'window'):
# main window not yet available
# FIXME: early call strictly needed?
return
files = set()
tracks = set()
objects = set()
for obj in self.tagger.window.selected_objects:
if isinstance(obj, File):
files.add(obj)
elif isinstance(obj, Track):
tracks.add(obj)
files.update(obj.files)
elif isinstance(obj, Cluster) and obj.can_edit_tags:
objects.add(obj)
files.update(obj.files)
elif isinstance(obj, Album):
objects.add(obj)
tracks.update(obj.tracks)
for track in obj.tracks:
files.update(track.files)
objects.update(files)
objects.update(tracks)
self.selection_dirty = False
self.selection_mutex.lock()
self.files = files
self.tracks = tracks
self.objects = objects
self.selection_mutex.unlock()
@throttle(100)
def update(self, drop_album_caches=False):
new_selection = self.selection_dirty
if self.editing or (self.ignore_updates and not new_selection):
return
if new_selection:
self._update_selection()
thread.run_task(partial(self._update_tags, new_selection, drop_album_caches), self._update_items,
thread_pool=self.tagger.priority_thread_pool)
def _update_tags(self, new_selection=True, drop_album_caches=False):
self.selection_mutex.lock()
files = self.files
tracks = self.tracks
self.selection_mutex.unlock()
if not (files or tracks):
return None
if new_selection or drop_album_caches:
self._single_file_album = len({file.metadata['album'] for file in files}) == 1
self._single_track_album = len({track.metadata['album'] for track in tracks}) == 1
while not new_selection: # Just an if with multiple exit points
# If we are dealing with the same selection
# skip updates unless it we are dealing with a single file/track
if len(files) == 1:
break
if len(tracks) == 1:
break
# Or if we are dealing with a single cluster/album
if self._single_file_album:
break
if self._single_track_album:
break
return self.tag_diff
self.colors = {
TagStatus.NOCHANGE: self.palette().color(QtGui.QPalette.ColorRole.Text),
TagStatus.REMOVED: QtGui.QBrush(interface_colors.get_qcolor('tagstatus_removed')),
TagStatus.ADDED: QtGui.QBrush(interface_colors.get_qcolor('tagstatus_added')),
TagStatus.CHANGED: QtGui.QBrush(interface_colors.get_qcolor('tagstatus_changed'))
}
config = get_config()
tag_diff = TagDiff(max_length_diff=config.setting['ignore_track_duration_difference_under'])
tag_diff.objects = len(files)
clear_existing_tags = config.setting['clear_existing_tags']
top_tags = config.setting['metadatabox_top_tags']
top_tags_set = set(top_tags)
settings = config.setting.as_dict()
for file in files:
new_metadata = file.metadata
orig_metadata = file.orig_metadata
tags = set(new_metadata) | set(orig_metadata)
for tag in tags:
if tag.startswith("~"):
continue
if not file.supports_tag(tag):
continue
new_values = file.format_specific_metadata(new_metadata, tag, settings)
orig_values = file.format_specific_metadata(orig_metadata, tag, settings)
if not clear_existing_tags and not new_values:
new_values = list(orig_values or [""])
removed = tag in new_metadata.deleted_tags
tag_diff.add(tag, orig_values, new_values, True, removed, top_tags=top_tags_set)
tag_diff.add('~length', str(orig_metadata.length), str(new_metadata.length),
removable=False, readonly=True)
for track in tracks:
if track.num_linked_files == 0:
for tag, new_values in track.metadata.rawitems():
if not tag.startswith("~"):
if tag in track.orig_metadata:
orig_values = track.orig_metadata.getall(tag)
else:
orig_values = new_values
tag_diff.add(tag, orig_values, new_values, True)
length = str(track.metadata.length)
tag_diff.add('~length', length, length, removable=False, readonly=True)
tag_diff.objects += 1
all_tags = set(list(tag_diff.orig) + list(tag_diff.new))
common_tags = [tag for tag in top_tags if tag in all_tags]
tag_names = common_tags + sorted(all_tags.difference(common_tags),
key=lambda x: display_tag_name(x).lower())
if config.persist['show_changes_first']:
tags_by_status = {}
for tag in tag_names:
tags_by_status.setdefault(tag_diff.tag_status(tag), []).append(tag)
for status in (TagStatus.CHANGED, TagStatus.ADDED,
TagStatus.REMOVED, TagStatus.NOCHANGE):
tag_diff.tag_names += tags_by_status.pop(status, [])
else:
tag_diff.tag_names = [
tag for tag in tag_names if
tag_diff.status[tag] != TagStatus.EMPTY]
return tag_diff
def _update_items(self, result=None, error=None):
if self.editing:
return
if not (self.files or self.tracks):
result = None
self.tag_diff = result
if self.tag_diff is None:
self.setRowCount(0)
return
self.setRowCount(len(self.tag_diff.tag_names))
orig_flags = QtCore.Qt.ItemFlag.ItemIsSelectable | QtCore.Qt.ItemFlag.ItemIsEnabled
new_flags = orig_flags | QtCore.Qt.ItemFlag.ItemIsEditable
alignment = QtCore.Qt.AlignmentFlag.AlignLeft | QtCore.Qt.AlignmentFlag.AlignTop
for i, tag in enumerate(self.tag_diff.tag_names):
color = self.colors.get(self.tag_diff.tag_status(tag),
self.colors[TagStatus.NOCHANGE])
tag_item = self.item(i, self.COLUMN_TAG)
if not tag_item:
tag_item = QtWidgets.QTableWidgetItem()
tag_item.setFlags(orig_flags)
font = tag_item.font()
font.setBold(True)
tag_item.setFont(font)
tag_item.setTextAlignment(alignment)
self.setItem(i, self.COLUMN_TAG, tag_item)
tag_item.setText(display_tag_name(tag))
orig_item = self.item(i, self.COLUMN_ORIG)
if not orig_item:
orig_item = QtWidgets.QTableWidgetItem()
orig_item.setFlags(orig_flags)
orig_item.setTextAlignment(alignment)
self.setItem(i, self.COLUMN_ORIG, orig_item)
self._set_item_value(orig_item, self.tag_diff.orig, tag)
orig_item.setForeground(color)
new_item = self.item(i, self.COLUMN_NEW)
if not new_item:
new_item = QtWidgets.QTableWidgetItem()
new_item.setTextAlignment(alignment)
if tag == '~length':
new_item.setFlags(orig_flags)
else:
new_item.setFlags(new_flags)
self.setItem(i, self.COLUMN_NEW, new_item)
self._set_item_value(new_item, self.tag_diff.new, tag)
font = new_item.font()
strikeout = self.tag_diff.tag_status(tag) == TagStatus.REMOVED
font.setStrikeOut(strikeout)
new_item.setFont(font)
new_item.setForeground(color)
# Adjust row height to content size
self.setRowHeight(i, self.sizeHintForRow(i))
def _set_item_value(self, item, tags, tag):
display_value = tags.display_value(tag)
item.setData(QtCore.Qt.ItemDataRole.UserRole, tag)
item.setText(display_value.text)
font = item.font()
font.setItalic(display_value.is_grouped)
item.setFont(font)
@restore_method
def restore_state(self):
config = get_config()
state = config.persist['metadatabox_header_state']
header = self.horizontalHeader()
header.restoreState(state)
header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeMode.Interactive)
def save_state(self):
config = get_config()
header = self.horizontalHeader()
state = header.saveState()
config.persist['metadatabox_header_state'] = state
| 30,407
|
Python
|
.py
| 646
| 35.193498
| 126
| 0.597943
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,976
|
colors.py
|
metabrainz_picard/picard/ui/colors.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2019-2021, 2024 Laurent Monin
# Copyright (C) 2019-2022 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from collections import defaultdict
from PyQt6 import QtGui
from picard.config import get_config
from picard.i18n import (
N_,
gettext as _,
)
from picard.ui.theme import theme
class UnknownColorException(Exception):
pass
class ColorDescription:
def __init__(self, title, group):
self.title = title
self.group = group
_COLOR_DESCRIPTIONS = {
'entity_error': ColorDescription(title=N_("Errored entity"), group=N_("Entities")),
'entity_pending': ColorDescription(title=N_("Pending entity"), group=N_("Entities")),
'entity_saved': ColorDescription(title=N_("Saved entity"), group=N_("Entities")),
'first_cover_hl': ColorDescription(title=N_("First cover art"), group=N_("Others")),
'log_debug': ColorDescription(title=N_('Log view text (debug)'), group=N_("Logging")),
'log_error': ColorDescription(title=N_('Log view text (error)'), group=N_("Logging")),
'log_info': ColorDescription(title=N_('Log view text (info)'), group=N_("Logging")),
'log_warning': ColorDescription(title=N_('Log view text (warning)'), group=N_("Logging")),
'profile_hl_bg': ColorDescription(title=N_("Profile highlight background"), group=N_("Profiles")),
'profile_hl_fg': ColorDescription(title=N_("Profile highlight foreground"), group=N_("Profiles")),
'row_highlight': ColorDescription(title=N_("Row Highlight"), group=N_("Others")),
'tagstatus_added': ColorDescription(title=N_("Tag added"), group=N_("Tags")),
'tagstatus_changed': ColorDescription(title=N_("Tag changed"), group=N_("Tags")),
'tagstatus_removed': ColorDescription(title=N_("Tag removed"), group=N_("Tags")),
'syntax_hl_error': ColorDescription(title=N_("Error syntax highlight"), group=N_("Syntax Highlighting")),
'syntax_hl_escape': ColorDescription(title=N_("Escape syntax highlight"), group=N_("Syntax Highlighting")),
'syntax_hl_func': ColorDescription(title=N_("Function syntax highlight"), group=N_("Syntax Highlighting")),
'syntax_hl_noop': ColorDescription(title=N_("Noop syntax highlight"), group=N_("Syntax Highlighting")),
'syntax_hl_special': ColorDescription(title=N_("Special syntax highlight"), group=N_("Syntax Highlighting")),
'syntax_hl_unicode': ColorDescription(title=N_("Unicode syntax highlight"), group=N_("Syntax Highlighting")),
'syntax_hl_var': ColorDescription(title=N_("Variable syntax highlight"), group=N_("Syntax Highlighting")),
}
_DEFAULT_COLORS = defaultdict(dict)
class DefaultColor:
def __init__(self, value, description):
qcolor = QtGui.QColor(value)
self.value = qcolor.name()
self.description = description
def register_color(themes, name, value):
description = _COLOR_DESCRIPTIONS.get(name, "FIXME: color desc for %s" % name)
for theme_name in themes:
_DEFAULT_COLORS[theme_name][name] = DefaultColor(value, description)
_DARK = ('dark', )
_LIGHT = ('light', )
_ALL = _DARK + _LIGHT
register_color(_ALL, 'entity_error', '#C80000')
register_color(_ALL, 'entity_pending', '#808080')
register_color(_ALL, 'entity_saved', '#00AA00')
register_color(_LIGHT, 'log_debug', 'purple')
register_color(_DARK, 'log_debug', 'plum')
register_color(_ALL, 'log_error', 'red')
register_color(_LIGHT, 'log_info', 'black')
register_color(_DARK, 'log_info', 'white')
register_color(_ALL, 'log_warning', 'darkorange')
register_color(_ALL, 'tagstatus_added', 'green')
register_color(_ALL, 'tagstatus_changed', 'darkgoldenrod')
register_color(_ALL, 'tagstatus_removed', 'red')
register_color(_DARK, 'profile_hl_fg', '#FFFFFF')
register_color(_LIGHT, 'profile_hl_fg', '#000000')
register_color(_DARK, 'profile_hl_bg', '#000080')
register_color(_LIGHT, 'profile_hl_bg', '#F9F906')
register_color(_LIGHT, 'row_highlight', '#FFFFE0')
register_color(_DARK, 'row_highlight', '#90907E')
register_color(_LIGHT, 'first_cover_hl', 'darkgoldenrod')
register_color(_DARK, 'first_cover_hl', 'orange')
# syntax highlighting colors
register_color(_LIGHT, 'syntax_hl_error', 'red')
register_color(_LIGHT, 'syntax_hl_escape', 'darkRed')
register_color(_LIGHT, 'syntax_hl_func', 'blue')
register_color(_LIGHT, 'syntax_hl_noop', 'darkGray')
register_color(_LIGHT, 'syntax_hl_special', 'blue')
register_color(_LIGHT, 'syntax_hl_unicode', 'darkRed')
register_color(_LIGHT, 'syntax_hl_var', 'darkCyan')
register_color(_DARK, 'syntax_hl_error', '#F16161')
register_color(_DARK, 'syntax_hl_escape', '#4BEF1F')
register_color(_DARK, 'syntax_hl_func', '#FF57A0')
register_color(_DARK, 'syntax_hl_noop', '#04E7D5')
register_color(_DARK, 'syntax_hl_special', '#FF57A0')
register_color(_DARK, 'syntax_hl_unicode', '#4BEF1F')
register_color(_DARK, 'syntax_hl_var', '#FCBB51')
class InterfaceColors:
def __init__(self, dark_theme=None):
self._dark_theme = dark_theme
self.set_default_colors()
@property
def dark_theme(self):
if self._dark_theme is None:
return theme.is_dark_theme
else:
return self._dark_theme
@property
def default_colors(self):
if self.dark_theme:
return _DEFAULT_COLORS['dark']
else:
return _DEFAULT_COLORS['light']
@property
def _config_key(self):
if self.dark_theme:
return 'interface_colors_dark'
else:
return 'interface_colors'
def set_default_colors(self):
self._colors = dict()
for color_key in self.default_colors:
self.set_default_color(color_key)
def set_default_color(self, color_key):
color_value = self.default_colors[color_key].value
self.set_color(color_key, color_value)
def set_colors(self, colors_dict):
for color_key in self.default_colors:
if color_key in colors_dict:
color_value = colors_dict[color_key]
else:
color_value = self.default_colors[color_key].value
self.set_color(color_key, color_value)
def load_from_config(self):
config = get_config()
self.set_colors(config.setting[self._config_key])
def get_colors(self):
return self._colors
def get_color(self, color_key):
try:
return self._colors[color_key]
except KeyError:
if color_key in self.default_colors:
return self.default_colors[color_key].value
raise UnknownColorException("Unknown color key: %s" % color_key)
def get_qcolor(self, color_key):
return QtGui.QColor(self.get_color(color_key))
def get_color_description(self, color_key):
return _(self.default_colors[color_key].description)
def get_color_title(self, color_key):
return _(self.default_colors[color_key].description.title)
def get_color_group(self, color_key):
return _(self.default_colors[color_key].description.group)
def set_color(self, color_key, color_value):
if color_key in self.default_colors:
qcolor = QtGui.QColor(color_value)
if not qcolor.isValid():
qcolor = QtGui.QColor(self.default_colors[color_key].value)
self._colors[color_key] = qcolor.name()
else:
raise UnknownColorException("Unknown color key: %s" % color_key)
def save_to_config(self):
# returns True if user has to be warned about color changes
changed = False
config = get_config()
conf = config.setting[self._config_key]
for key, color in self._colors.items():
if key not in conf:
# new color key, not need to warn user
conf[key] = color
elif color != conf[key]:
# color changed
conf[key] = color
changed = True
for key in set(conf) - set(self.default_colors):
# old color key, remove
del conf[key]
config.setting[self._config_key] = conf
return changed
interface_colors = InterfaceColors()
| 8,861
|
Python
|
.py
| 188
| 41.18617
| 113
| 0.675009
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,977
|
aboutdialog.py
|
metabrainz_picard/picard/ui/aboutdialog.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2006-2014 Lukáš Lalinský
# Copyright (C) 2008, 2013, 2018-2024 Philipp Wolfer
# Copyright (C) 2011 Pavan Chander
# Copyright (C) 2011, 2013 Wieland Hoffmann
# Copyright (C) 2013 Michael Wiencek
# Copyright (C) 2013-2015, 2018, 2020-2024 Laurent Monin
# Copyright (C) 2014 Ismael Olea
# Copyright (C) 2017 Sambhav Kothari
# Copyright (C) 2021 Bob Swift
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from PyQt6 import QtCore
from picard.const import PICARD_URLS
from picard.formats import supported_extensions
from picard.i18n import gettext as _
from picard.util import versions
from picard.ui import (
PicardDialog,
SingletonDialog,
)
from picard.ui.forms.ui_aboutdialog import Ui_AboutDialog
class AboutDialog(PicardDialog, SingletonDialog):
def __init__(self, parent=None):
super().__init__(parent=parent)
self.setAttribute(QtCore.Qt.WidgetAttribute.WA_DeleteOnClose)
self.ui = Ui_AboutDialog()
self.ui.setupUi(self)
self._update_content()
def _update_content(self):
args = versions.as_dict(i18n=True)
args['third_parties_versions'] = ', '.join([
("%s %s" % (versions.version_name(name), value))
.replace(' ', ' ')
.replace('-', '‑') # non-breaking hyphen
for name, value
in versions.as_dict(i18n=True).items()
if name != 'version'])
args['formats'] = ", ".join(map(lambda x: x[1:], supported_extensions()))
args['copyright_years'] = '2004-2024'
args['authors_credits'] = ", ".join([
'Robert Kaye',
'Lukáš Lalinský',
'Laurent Monin',
'Sambhav Kothari',
'Philipp Wolfer',
])
# TR: Replace this with your name to have it appear in the "About" dialog.
args['translator_credits'] = _('translator-credits')
if args['translator_credits'] != 'translator-credits':
# TR: Replace LANG with language you are translating to.
args['translator_credits'] = _("<br/>Translated to LANG by %s") % args['translator_credits'].replace("\n", "<br/>")
else:
args['translator_credits'] = ""
args['icons_credits'] = _(
'Icons made by Sambhav Kothari <sambhavs.email@gmail.com> '
'and <a href="http://www.flaticon.com/authors/madebyoliver">Madebyoliver</a>, '
'<a href="http://www.flaticon.com/authors/pixel-buddha">Pixel Buddha</a>, '
'<a href="http://www.flaticon.com/authors/nikita-golubev">Nikita Golubev</a>, '
'<a href="http://www.flaticon.com/authors/maxim-basinski">Maxim Basinski</a>, '
'<a href="https://www.flaticon.com/authors/smashicons">Smashicons</a> '
'from <a href="https://www.flaticon.com">www.flaticon.com</a>')
def strong(s):
return '<strong>' + s + '</strong>'
def small(s):
return '<small>' + s + '</small>'
def url(url, s=None):
if s is None:
s = url
return '<a href="%s">%s</a>' % (url, s)
text_paragraphs = [
strong(_("Version %(version)s")),
small('%(third_parties_versions)s'),
strong(_("Supported formats")),
'%(formats)s',
strong(_("Please donate")),
_("Thank you for using Picard. Picard relies on the MusicBrainz database, which is operated by the "
"MetaBrainz Foundation with the help of thousands of volunteers. If you like this application please "
"consider donating to the MetaBrainz Foundation to keep the service running."),
url(PICARD_URLS['donate'], _("Donate now!")),
strong(_("Credits")),
small(_("Copyright © %(copyright_years)s %(authors_credits)s and others") + "%(translator_credits)s"),
small('%(icons_credits)s'),
strong(_("Official website")),
url(PICARD_URLS['home'])
]
self.ui.label.setOpenExternalLinks(True)
self.ui.label.setText("".join('<p align="center">' + p + "</p>" for p in text_paragraphs) % args)
| 4,914
|
Python
|
.py
| 103
| 39.815534
| 127
| 0.628733
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,978
|
infodialog.py
|
metabrainz_picard/picard/ui/infodialog.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2006 Lukáš Lalinský
# Copyright (C) 2011-2014 Michael Wiencek
# Copyright (C) 2012-2014, 2017, 2019 Wieland Hoffmann
# Copyright (C) 2013-2014, 2018-2024 Laurent Monin
# Copyright (C) 2014, 2017, 2020 Sophist-UK
# Copyright (C) 2016 Rahul Raturi
# Copyright (C) 2016-2017 Sambhav Kothari
# Copyright (C) 2017-2019 Antonio Larrosa
# Copyright (C) 2018 Vishal Choudhary
# Copyright (C) 2018-2024 Philipp Wolfer
# Copyright (C) 2024 Suryansh Shakya
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from collections import (
defaultdict,
namedtuple,
)
from html import escape
import re
import traceback
from PyQt6 import (
QtCore,
QtGui,
QtWidgets,
)
from picard import log
from picard.album import Album
from picard.config import get_config
from picard.coverart.image import CoverArtImageIOError
from picard.coverart.utils import translated_types_as_string
from picard.file import File
from picard.i18n import (
gettext as _,
ngettext,
)
from picard.track import Track
from picard.util import (
bytes2human,
format_time,
open_local_path,
)
from picard.ui import PicardDialog
from picard.ui.colors import interface_colors
from picard.ui.forms.ui_infodialog import Ui_InfoDialog
from picard.ui.util import StandardButton
class ArtworkCoverWidget(QtWidgets.QWidget):
"""A QWidget that can be added to artwork column cell of ArtworkTable."""
SIZE = 170
def __init__(self, pixmap=None, text=None, size=None, parent=None):
super().__init__(parent=parent)
layout = QtWidgets.QVBoxLayout()
if pixmap is not None:
if size is None:
size = self.SIZE
image_label = QtWidgets.QLabel()
image_label.setPixmap(pixmap.scaled(size, size,
QtCore.Qt.AspectRatioMode.KeepAspectRatio,
QtCore.Qt.TransformationMode.SmoothTransformation))
image_label.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)
layout.addWidget(image_label)
if text is not None:
text_label = QtWidgets.QLabel()
text_label.setText(text)
text_label.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)
text_label.setWordWrap(True)
layout.addWidget(text_label)
self.setLayout(layout)
class ArtworkTable(QtWidgets.QTableWidget):
H_SIZE = 200
V_SIZE = 230
NUM_ROWS = 0
NUM_COLS = 3
_columns = {}
_labels = ()
_tooltips = {}
artwork_columns = ()
def __init__(self, parent=None):
super().__init__(self.NUM_ROWS, self.NUM_COLS, parent=parent)
h_header = self.horizontalHeader()
h_header.setDefaultSectionSize(self.H_SIZE)
h_header.setStretchLastSection(True)
v_header = self.verticalHeader()
v_header.setDefaultSectionSize(self.V_SIZE)
self.setHorizontalHeaderLabels(self._labels)
for colname, index in self._columns.items():
self.horizontalHeaderItem(index).setToolTip(self._tooltips.get(colname, None))
def get_column_index(self, name):
return self._columns[name]
class ArtworkTableSimple(ArtworkTable):
TYPE_COLUMN_SIZE = 140
def __init__(self, parent=None):
super().__init__(parent=parent)
self.setColumnWidth(self.get_column_index('type'), self.TYPE_COLUMN_SIZE)
class ArtworkTableNew(ArtworkTableSimple):
_columns = {
'type': 0,
'new': 1,
'external': 2,
}
artwork_columns = ('new', 'external',)
_labels = (_("Type"), _("New Embedded"), _("New Exported"),)
_tooltips = {
'new': _("New cover art embedded into tags"),
'external': _("New cover art saved as a separate file"),
}
class ArtworkTableOriginal(ArtworkTableSimple):
NUM_COLS = 2
_columns = {
'type': 0,
'new': 1,
}
artwork_columns = ('new',)
_labels = (_("Type"), _("Existing Cover"))
_tooltips = {
'new': _("Existing cover art already embedded into tags"),
}
class ArtworkTableExisting(ArtworkTable):
NUM_COLS = 4
_columns = {
'orig': 0,
'type': 1,
'new': 2,
'external': 3,
}
artwork_columns = ('orig', 'new', 'external',)
_labels = (_("Existing Cover"), _("Type"), _("New Embedded"), _("New Exported"),)
_tooltips = {
'orig': _("Existing cover art already embedded into tags"),
'new': _("New cover art embedded into tags"),
'external': _("New cover art saved as a separate file"),
}
class ArtworkRow:
def __init__(self, orig_image=None, new_image=None, types=None):
self.orig_image = orig_image
self.new_image = new_image
self.types = types
self.new_external_image = None
if self.new_image:
self.new_external_image = self.new_image.external_file_coverart
class InfoDialog(PicardDialog):
def __init__(self, obj, parent=None):
super().__init__(parent=parent)
self.obj = obj
self.ui = Ui_InfoDialog()
self._pixmaps = {
'missing': QtGui.QPixmap(":/images/image-missing.png"),
'arrow': QtGui.QPixmap(":/images/arrow.png"),
}
self.new_images = sorted(obj.metadata.images) or []
self.orig_images = []
artworktable_class = ArtworkTableNew
self.has_new_external_images = any(image.external_file_coverart for image in self.new_images)
has_orig_images = hasattr(obj, 'orig_metadata') and obj.orig_metadata.images
if has_orig_images:
artworktable_class = ArtworkTableOriginal
has_new_different_images = obj.orig_metadata.images != obj.metadata.images
if has_new_different_images or self.has_new_external_images:
is_track = isinstance(obj, Track)
is_linked_file = isinstance(obj, File) and isinstance(obj.parent_item, Track)
is_album_with_files = isinstance(obj, Album) and obj.get_num_total_files() > 0
if is_track or is_linked_file or is_album_with_files:
self.orig_images = sorted(obj.orig_metadata.images)
artworktable_class = ArtworkTableExisting
self.ui.setupUi(self)
self.ui.buttonBox.addButton(
StandardButton(StandardButton.CLOSE), QtWidgets.QDialogButtonBox.ButtonRole.AcceptRole)
self.ui.buttonBox.accepted.connect(self.accept)
# Add the ArtworkTable to the ui
self.ui.artwork_table = artworktable_class(parent=self)
self.ui.artwork_table.setObjectName('artwork_table')
self.ui.artwork_tab.layout().addWidget(self.ui.artwork_table)
self.setTabOrder(self.ui.tabWidget, self.ui.artwork_table)
self.setTabOrder(self.ui.artwork_table, self.ui.buttonBox)
self.setWindowTitle(_("Info"))
self.artwork_table = self.ui.artwork_table
self._display_tabs()
def _display_tabs(self):
self._display_info_tab()
self._display_error_tab()
self._display_artwork_tab()
def _display_error_tab(self):
if hasattr(self.obj, 'errors') and self.obj.errors:
self._show_errors(self.obj.errors)
else:
self.tab_hide(self.ui.error_tab)
def _show_errors(self, errors):
if errors:
color = interface_colors.get_color('log_error')
text = '<br />'.join(map(
lambda s: '<font color="%s">%s</font>' % (color, text_as_html(s)), errors))
self.ui.error.setText(text + '<hr />')
def _artwork_infos(self, image):
"""Information about image, as list of strings"""
if image.comment:
yield image.comment
bytes_size_decimal = bytes2human.decimal(image.datalength)
bytes_size_binary = bytes2human.binary(image.datalength)
yield f"{bytes_size_decimal} ({bytes_size_binary})"
if image.width and image.height:
yield f"{image.width} x {image.height}"
yield image.mimetype
def _artwork_tooltip(self, message, image):
"""Format rich-text tooltip text"""
fmt = _("<strong>%(message)s</strong><br />"
"Temporary file: <em>%(tempfile)s</em><br />"
"Source: <em>%(sourcefile)s</em>")
return fmt % {
'message': message,
'tempfile': escape(image.tempfile_filename),
'sourcefile': escape(image.source),
}
def _display_artwork_image_cell(self, row_index, colname):
"""Display artwork image, depending on source (new/orig), in the proper column"""
col_index = self.artwork_table.get_column_index(colname)
pixmap = None
infos = None
source = 'orig_image'
if colname == 'new':
source = 'new_image'
elif colname == 'external':
source = 'new_external_image'
image = getattr(self.artwork_rows[row_index], source)
item = QtWidgets.QTableWidgetItem()
if image:
try:
data = None
if image.thumbnail:
try:
data = image.thumbnail.data
except CoverArtImageIOError as e:
log.warning(e)
else:
data = image.data
if data:
pixmap = QtGui.QPixmap()
pixmap.loadFromData(data)
item.setToolTip(self._artwork_tooltip(_("Double-click to open in external viewer"), image))
item.setData(QtCore.Qt.ItemDataRole.UserRole, image)
except CoverArtImageIOError:
log.error(traceback.format_exc())
pixmap = self._pixmaps['missing']
item.setToolTip(self._artwork_tooltip(_("Missing temporary file"), image))
infos = "<br />".join(escape(t) for t in self._artwork_infos(image))
img_wgt = ArtworkCoverWidget(pixmap=pixmap, text=infos)
self.artwork_table.setCellWidget(row_index, col_index, img_wgt)
self.artwork_table.setItem(row_index, col_index, item)
def _display_artwork_type_cell(self, row_index):
"""Display type cell, with arrow if this row has both new & orig images"""
artwork_row = self.artwork_rows[row_index]
if artwork_row.new_image and artwork_row.orig_image:
type_pixmap = self._pixmaps['arrow']
type_size = ArtworkCoverWidget.SIZE // 2
else:
type_pixmap = None
type_size = None
col_index = self.artwork_table.get_column_index('type')
type_item = QtWidgets.QTableWidgetItem()
type_wgt = ArtworkCoverWidget(
pixmap=type_pixmap,
size=type_size,
text=translated_types_as_string(artwork_row.types),
)
self.artwork_table.setCellWidget(row_index, col_index, type_wgt)
self.artwork_table.setItem(row_index, col_index, type_item)
def _build_artwork_rows(self):
"""Generate artwork rows, trying to match orig/new image types"""
# we work on a copy, since will pop matched images
new_images = self.new_images[:]
if self.orig_images:
for orig_image in self.orig_images:
types = orig_image.normalized_types()
# let check if we can find a new image exactly matching this type
found_new_image = None
for i, new_image in enumerate(new_images):
if new_image.normalized_types() == types:
# we found one, pop it from new_images, we don't want to match it again
found_new_image = new_images.pop(i)
break
yield ArtworkRow(orig_image=orig_image, new_image=found_new_image, types=types)
# now, remaining images that weren't matched to orig images
for new_image in new_images:
yield ArtworkRow(new_image=new_image, types=new_image.normalized_types())
def _display_artwork_rows(self):
"""Display rows of images and types in artwork tab"""
self.artwork_rows = dict(enumerate(self._build_artwork_rows()))
for row_index in self.artwork_rows:
self.artwork_table.insertRow(row_index)
self._display_artwork_type_cell(row_index)
for colname in self.artwork_table.artwork_columns:
self._display_artwork_image_cell(row_index, colname)
def _display_artwork_tab(self):
if not self.new_images and not self.orig_images:
self.tab_hide(self.ui.artwork_tab)
return
self._display_artwork_rows()
self.artwork_table.itemDoubleClicked.connect(self.show_item)
self.artwork_table.verticalHeader().resizeSections(QtWidgets.QHeaderView.ResizeMode.ResizeToContents)
if isinstance(self.artwork_table, ArtworkTableOriginal):
return
config = get_config()
for colname in self.artwork_table.artwork_columns:
tags_image_not_used = colname == 'new' and not config.setting['save_images_to_tags']
file_image_not_used = colname == 'external' and not self.has_new_external_images
if tags_image_not_used or file_image_not_used:
col_index = self.artwork_table.get_column_index(colname)
self.artwork_table.setColumnHidden(col_index, True)
def tab_hide(self, widget):
tab = self.ui.tabWidget
index = tab.indexOf(widget)
tab.removeTab(index)
def show_item(self, item):
data = item.data(QtCore.Qt.ItemDataRole.UserRole)
# Check if this function isn't triggered by cell in Type column
if not data:
return
filename = data.tempfile_filename
if filename:
open_local_path(filename)
def format_file_info(file_):
info = []
info.append((_("Filename:"), file_.filename))
if '~format' in file_.orig_metadata:
info.append((_("Format:"), file_.orig_metadata['~format']))
if '~filesize' in file_.orig_metadata:
size = file_.orig_metadata['~filesize']
try:
sizestr = "%s (%s)" % (bytes2human.decimal(size), bytes2human.binary(size))
except ValueError:
sizestr = _("unknown")
info.append((_("Size:"), sizestr))
if file_.orig_metadata.length:
info.append((_("Length:"), format_time(file_.orig_metadata.length)))
if '~bitrate' in file_.orig_metadata:
info.append((_("Bitrate:"), "%s kbps" % file_.orig_metadata['~bitrate']))
if '~sample_rate' in file_.orig_metadata:
info.append((_("Sample rate:"), "%s Hz" % file_.orig_metadata['~sample_rate']))
if '~bits_per_sample' in file_.orig_metadata:
info.append((_("Bits per sample:"), str(file_.orig_metadata['~bits_per_sample'])))
if '~channels' in file_.orig_metadata:
ch = file_.orig_metadata['~channels']
if ch == '1':
ch = _("Mono")
elif ch == '2':
ch = _("Stereo")
info.append((_("Channels:"), ch))
return '<br/>'.join(map(lambda i: '<b>%s</b> %s' %
(escape(i[0]), escape(i[1])), info))
def format_tracklist(cluster):
info = []
info.append('<b>%s</b> %s' % (_("Album:"), escape(cluster.metadata['album'])))
info.append('<b>%s</b> %s' % (_("Artist:"), escape(cluster.metadata['albumartist'])))
info.append("")
TrackListItem = namedtuple('TrackListItem', 'number, title, artist, length')
tracklists = defaultdict(list)
if isinstance(cluster, Album):
objlist = cluster.tracks
else:
objlist = cluster.iterfiles(False)
for obj_ in objlist:
m = obj_.metadata
artist = m['artist'] or m['albumartist'] or cluster.metadata['albumartist']
track = TrackListItem(m['tracknumber'], m['title'], artist,
m['~length'])
tracklists[obj_.discnumber].append(track)
def sorttracknum(track):
try:
return int(track.number)
except ValueError:
try:
# This allows to parse values like '3' but also '3/10'
m = re.search(r'^\d+', track.number)
return int(m.group(0))
except AttributeError:
return 0
ndiscs = len(tracklists)
for discnumber in sorted(tracklists):
tracklist = tracklists[discnumber]
if ndiscs > 1:
info.append('<b>%s</b>' % (_("Disc %d") % discnumber))
lines = ['%s %s - %s (%s)' % item for item in sorted(tracklist, key=sorttracknum)]
info.append('<b>%s</b><br />%s<br />' % (_("Tracklist:"),
'<br />'.join(escape(s).replace(' ', ' ') for s in lines)))
return '<br/>'.join(info)
def text_as_html(text):
return '<br />'.join(escape(str(text))
.replace('\t', ' ')
.replace(' ', ' ')
.splitlines())
class FileInfoDialog(InfoDialog):
def __init__(self, file_, parent=None):
super().__init__(file_, parent=parent)
self.setWindowTitle(_("Info") + " - " + file_.base_filename)
def _display_info_tab(self):
file_ = self.obj
text = format_file_info(file_)
self.ui.info.setText(text)
class AlbumInfoDialog(InfoDialog):
def __init__(self, album, parent=None):
super().__init__(album, parent=parent)
self.setWindowTitle(_("Album Info"))
def _display_info_tab(self):
album = self.obj
if album._tracks_loaded:
self.ui.info.setText(format_tracklist(album))
else:
self.tab_hide(self.ui.info_tab)
class TrackInfoDialog(InfoDialog):
def __init__(self, track, parent=None):
super().__init__(track, parent=parent)
self.setWindowTitle(_("Track Info"))
def _display_info_tab(self):
track = self.obj
tab = self.ui.info_tab
tabWidget = self.ui.tabWidget
tab_index = tabWidget.indexOf(tab)
if track.num_linked_files == 0:
tabWidget.setTabText(tab_index, _("&Info"))
self.tab_hide(tab)
return
tabWidget.setTabText(tab_index, _("&Info"))
text = ngettext("%i file in this track", "%i files in this track",
track.num_linked_files) % track.num_linked_files
info_files = [format_file_info(file_) for file_ in track.files]
text += '<hr />' + '<hr />'.join(info_files)
self.ui.info.setText(text)
class ClusterInfoDialog(InfoDialog):
def __init__(self, cluster, parent=None):
super().__init__(cluster, parent=parent)
self.setWindowTitle(_("Cluster Info"))
def _display_info_tab(self):
tab = self.ui.info_tab
tabWidget = self.ui.tabWidget
tab_index = tabWidget.indexOf(tab)
tabWidget.setTabText(tab_index, _("&Info"))
self.ui.info.setText(format_tracklist(self.obj))
| 19,795
|
Python
|
.py
| 451
| 34.833703
| 111
| 0.617626
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,979
|
enums.py
|
metabrainz_picard/picard/ui/enums.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2006-2008, 2011-2012, 2014 Lukáš Lalinský
# Copyright (C) 2007 Nikolai Prokoschenko
# Copyright (C) 2008 Gary van der Merwe
# Copyright (C) 2008 Robert Kaye
# Copyright (C) 2008 Will
# Copyright (C) 2008-2010, 2015, 2018-2023 Philipp Wolfer
# Copyright (C) 2009 Carlin Mangar
# Copyright (C) 2009 David Hilton
# Copyright (C) 2011-2012 Chad Wilson
# Copyright (C) 2011-2013, 2015-2017 Wieland Hoffmann
# Copyright (C) 2011-2014 Michael Wiencek
# Copyright (C) 2013-2014, 2017 Sophist-UK
# Copyright (C) 2013-2023 Laurent Monin
# Copyright (C) 2015 Ohm Patel
# Copyright (C) 2015 samithaj
# Copyright (C) 2016 Rahul Raturi
# Copyright (C) 2016 Simon Legner
# Copyright (C) 2016-2017 Sambhav Kothari
# Copyright (C) 2017 Antonio Larrosa
# Copyright (C) 2017 Frederik “Freso” S. Olesen
# Copyright (C) 2018 Kartik Ohri
# Copyright (C) 2018 Vishal Choudhary
# Copyright (C) 2018 virusMac
# Copyright (C) 2018, 2021-2023 Bob Swift
# Copyright (C) 2019 Timur Enikeev
# Copyright (C) 2020-2021 Gabriel Ferreira
# Copyright (C) 2021 Petit Minion
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from enum import (
Enum,
unique,
)
# TODO: when Python 3.11 will the lowest version supported move this to StrEnum
# see https://tsak.dev/posts/python-enum/
@unique
class MainAction(str, Enum):
ABOUT = 'about_action'
ADD_DIRECTORY = 'add_directory_action'
ADD_FILES = 'add_files_action'
ALBUM_OTHER_VERSIONS = 'album_other_versions_action'
ALBUM_SEARCH = 'album_search_action'
ANALYZE = 'analyze_action'
AUTOTAG = 'autotag_action'
BROWSER_LOOKUP = 'browser_lookup_action'
CD_LOOKUP = 'cd_lookup_action'
CHECK_UPDATE = 'check_update_action'
CLOSE_WINDOW = 'close_window_action'
CLUSTER = 'cluster_action'
CUT = 'cut_action'
DONATE = 'donate_action'
ENABLE_MOVING = 'enable_moving_action'
ENABLE_RENAMING = 'enable_renaming_action'
ENABLE_TAG_SAVING = 'enable_tag_saving_action'
EXIT = 'exit_action'
GENERATE_FINGERPRINTS = 'generate_fingerprints_action'
HELP = 'help_action'
OPEN_COLLECTION_IN_BROWSER = 'open_collection_in_browser_action'
OPEN_FOLDER = 'open_folder_action'
OPTIONS = 'options_action'
PASTE = 'paste_action'
PLAY_FILE = 'play_file_action'
PLAYER_TOOLBAR_TOGGLE = 'player_toolbar_toggle_action' # defined in MainWindow
REFRESH = 'refresh_action'
REMOVE = 'remove_action'
REPORT_BUG = 'report_bug_action'
SAVE = 'save_action'
SEARCH = 'search_action'
SEARCH_TOOLBAR_TOGGLE = 'search_toolbar_toggle_action' # defined in MainWindow
SHOW_COVER_ART = 'show_cover_art_action'
SHOW_FILE_BROWSER = 'show_file_browser_action'
SHOW_METADATA_VIEW = 'show_metadata_view_action'
SHOW_SCRIPT_EDITOR = 'show_script_editor_action'
SHOW_TOOLBAR = 'show_toolbar_action'
SIMILAR_ITEMS_SEARCH = 'similar_items_search_action'
SUBMIT_ACOUSTID = 'submit_acoustid_action'
SUBMIT_CLUSTER = 'submit_cluster_action'
SUBMIT_FILE_AS_RECORDING = 'submit_file_as_recording_action'
SUBMIT_FILE_AS_RELEASE = 'submit_file_as_release_action'
SUPPORT_FORUM = 'support_forum_action'
TAGS_FROM_FILENAMES = 'tags_from_filenames_action'
TRACK_SEARCH = 'track_search_action'
VIEW_HISTORY = 'view_history_action'
VIEW_INFO = 'view_info_action'
VIEW_LOG = 'view_log_action'
| 4,097
|
Python
|
.py
| 101
| 37.475248
| 83
| 0.733752
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,980
|
cdlookup.py
|
metabrainz_picard/picard/ui/cdlookup.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2006-2007 Lukáš Lalinský
# Copyright (C) 2009, 2018-2023 Philipp Wolfer
# Copyright (C) 2011-2013 Michael Wiencek
# Copyright (C) 2012 Chad Wilson
# Copyright (C) 2013-2014, 2018, 2020-2021, 2023-2024 Laurent Monin
# Copyright (C) 2014 Sophist-UK
# Copyright (C) 2016-2017 Sambhav Kothari
# Copyright (C) 2018 Vishal Choudhary
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from PyQt6 import (
QtCore,
QtGui,
QtWidgets,
)
from picard import log
from picard.config import get_config
from picard.i18n import gettext as _
from picard.mbjson import (
artist_credit_from_node,
label_info_from_node,
release_dates_and_countries_from_node,
)
from picard.util import (
compare_barcodes,
restore_method,
)
from picard.ui import PicardDialog
from picard.ui.forms.ui_cdlookup import Ui_CDLookupDialog
class CDLookupDialog(PicardDialog):
dialog_header_state = 'cdlookupdialog_header_state'
def __init__(self, releases, disc, parent=None):
super().__init__(parent=parent)
self.releases = releases
self.disc = disc
self.ui = Ui_CDLookupDialog()
self.ui.setupUi(self)
release_list = self.ui.release_list
release_list.setSelectionMode(QtWidgets.QAbstractItemView.SelectionMode.ExtendedSelection)
release_list.setSortingEnabled(True)
release_list.setAlternatingRowColors(True)
release_list.setHeaderLabels([_("Album"), _("Artist"), _("Date"), _("Country"),
_("Labels"), _("Catalog #s"), _("Barcode"),
_("Disambiguation")])
self.ui.submit_button.setIcon(QtGui.QIcon(":/images/cdrom.png"))
if self.releases:
def myjoin(values):
return "\n".join(values)
self.ui.results_view.setCurrentIndex(0)
selected = None
for release in self.releases:
labels, catalog_numbers = label_info_from_node(release['label-info'])
dates, countries = release_dates_and_countries_from_node(release)
barcode = release.get('barcode', '')
item = QtWidgets.QTreeWidgetItem(release_list)
if disc.mcn and compare_barcodes(barcode, disc.mcn):
selected = item
item.setText(0, release['title'])
item.setText(1, artist_credit_from_node(release['artist-credit'])[0])
item.setText(2, myjoin(dates))
item.setText(3, myjoin(countries))
item.setText(4, myjoin(labels))
item.setText(5, myjoin(catalog_numbers))
item.setText(6, barcode)
item.setText(7, release.get('disambiguation', ''))
item.setData(0, QtCore.Qt.ItemDataRole.UserRole, release['id'])
release_list.setCurrentItem(selected or release_list.topLevelItem(0))
self.ui.ok_button.setEnabled(True)
for i in range(release_list.columnCount() - 1):
release_list.resizeColumnToContents(i)
# Sort by descending date, then ascending country
release_list.sortByColumn(3, QtCore.Qt.SortOrder.AscendingOrder)
release_list.sortByColumn(2, QtCore.Qt.SortOrder.DescendingOrder)
else:
self.ui.results_view.setCurrentIndex(1)
if self.disc.submission_url:
self.ui.lookup_button.clicked.connect(self.lookup)
self.ui.submit_button.clicked.connect(self.lookup)
else:
self.ui.lookup_button.hide()
self.ui.submit_button.hide()
self.restore_header_state()
self.finished.connect(self.save_header_state)
def accept(self):
release_list = self.ui.release_list
for index in release_list.selectionModel().selectedRows():
release_id = release_list.itemFromIndex(index).data(0, QtCore.Qt.ItemDataRole.UserRole)
self.tagger.load_album(release_id, discid=self.disc.id)
super().accept()
def lookup(self):
submission_url = self.disc.submission_url
if submission_url:
lookup = self.tagger.get_file_lookup()
lookup.discid_submission(submission_url)
else:
log.error("No submission URL for disc ID %s", self.disc.id)
super().accept()
@restore_method
def restore_header_state(self):
if self.ui.release_list:
header = self.ui.release_list.header()
config = get_config()
state = config.persist[self.dialog_header_state]
if state:
header.restoreState(state)
log.debug("restore_state: %s", self.dialog_header_state)
def save_header_state(self):
if self.ui.release_list:
state = self.ui.release_list.header().saveState()
config = get_config()
config.persist[self.dialog_header_state] = state
log.debug("save_state: %s", self.dialog_header_state)
| 5,759
|
Python
|
.py
| 128
| 36.148438
| 99
| 0.650757
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,981
|
util.py
|
metabrainz_picard/picard/ui/util.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2007 Lukáš Lalinský
# Copyright (C) 2013-2015, 2018-2024 Laurent Monin
# Copyright (C) 2016-2017 Sambhav Kothari
# Copyright (C) 2017 Frederik “Freso” S. Olesen
# Copyright (C) 2017 Sophist-UK
# Copyright (C) 2018 Vishal Choudhary
# Copyright (C) 2019, 2021-2022, 2024 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from html import escape as html_escape
from PyQt6 import (
QtCore,
QtGui,
QtWidgets,
)
from picard import PICARD_DISPLAY_NAME
from picard.config import get_config
from picard.const.sys import (
IS_LINUX,
IS_MACOS,
IS_WIN,
)
from picard.i18n import (
N_,
gettext as _,
)
from picard.util import find_existing_path
from picard.ui.enums import MainAction
class StandardButton(QtWidgets.QPushButton):
OK = 0
CANCEL = 1
HELP = 2
CLOSE = 4
__types = {
OK: (N_("&Ok"), 'SP_DialogOkButton'),
CANCEL: (N_("&Cancel"), 'SP_DialogCancelButton'),
HELP: (N_("&Help"), 'SP_DialogHelpButton'),
CLOSE: (N_("Clos&e"), 'SP_DialogCloseButton'),
}
def __init__(self, btntype):
label = _(self.__types[btntype][0])
args = [label]
if not IS_WIN and not IS_MACOS:
iconname = self.__types[btntype][1]
if hasattr(QtWidgets.QStyle, iconname):
icon = QtCore.QCoreApplication.instance().style().standardIcon(getattr(QtWidgets.QStyle, iconname))
args = [icon, label]
super().__init__(*args)
def find_starting_directory():
config = get_config()
if config.setting['starting_directory']:
path = config.setting['starting_directory_path']
else:
path = config.persist['current_directory'] or QtCore.QDir.homePath()
return find_existing_path(path)
def _picardize_caption(caption):
return _("%s - %s") % (caption, PICARD_DISPLAY_NAME)
def _filedialog_caption(caption, default_caption=""):
if not caption:
caption = default_caption
return _picardize_caption(caption)
def _filedialog_options(options, default=None):
if options is None:
# returns default flags or empty enum flag
return default or QtWidgets.QFileDialog.Option(0)
else:
return options
class FileDialog(QtWidgets.QFileDialog):
"""Wrap QFileDialog & its static methods"""
def __init__(self, parent=None, caption="", directory="", filter=""):
if not caption:
caption = _("Select a file or a directory")
caption = _picardize_caption(caption)
super().__init__(parent=parent, caption=caption, directory=directory, filter=filter)
@staticmethod
def getSaveFileName(parent=None, caption="", dir="", filter="", selectedFilter="", options=None):
caption = _filedialog_caption(caption, _("Select a target file"))
options = _filedialog_options(options)
return QtWidgets.QFileDialog.getSaveFileName(
parent=parent, caption=caption, directory=dir,
filter=filter, initialFilter=selectedFilter, options=options
)
@staticmethod
def getOpenFileName(parent=None, caption="", dir="", filter="", selectedFilter="", options=None):
caption = _filedialog_caption(caption, _("Select a file"))
options = _filedialog_options(options)
return QtWidgets.QFileDialog.getOpenFileName(
parent=parent, caption=caption, directory=dir,
filter=filter, initialFilter=selectedFilter, options=options
)
@staticmethod
def getOpenFileNames(parent=None, caption="", dir="", filter="", selectedFilter="", options=None):
caption = _filedialog_caption(caption, _("Select one or more files"))
options = _filedialog_options(options)
return QtWidgets.QFileDialog.getOpenFileNames(
parent=parent, caption=caption, directory=dir,
filter=filter, initialFilter=selectedFilter, options=options
)
@staticmethod
def getExistingDirectory(parent=None, caption="", dir="", options=None):
caption = _filedialog_caption(caption, _("Select a directory"))
options = _filedialog_options(options, default=QtWidgets.QFileDialog.Option.ShowDirsOnly)
return QtWidgets.QFileDialog.getExistingDirectory(
parent=parent, caption=caption, directory=dir, options=options
)
@staticmethod
def getMultipleDirectories(parent=None, caption="", directory="", filter=""):
"""Custom file selection dialog which allows the selection
of multiple directories.
Depending on the platform, dialog may fallback on non-native.
"""
if not caption:
caption = _("Select one or more directories")
file_dialog = FileDialog(parent=parent, caption=caption, directory=directory, filter=filter)
file_dialog.setFileMode(QtWidgets.QFileDialog.FileMode.Directory)
file_dialog.setOption(QtWidgets.QFileDialog.Option.ShowDirsOnly)
# The native dialog doesn't allow selecting >1 directory
file_dialog.setOption(QtWidgets.QFileDialog.Option.DontUseNativeDialog)
for view in file_dialog.findChildren((QtWidgets.QListView, QtWidgets.QTreeView)):
if isinstance(view.model(), QtGui.QFileSystemModel):
view.setSelectionMode(QtWidgets.QAbstractItemView.SelectionMode.ExtendedSelection)
# Allow access to all mounted drives in the sidebar
root_volume = "/"
volume_paths = []
for volume in QtCore.QStorageInfo.mountedVolumes():
if volume.isValid() and volume.isReady():
path = volume.rootPath()
if volume.isRoot():
root_volume = path
else:
if not IS_LINUX or (path.startswith("/media/") or path.startswith("/mnt/")):
volume_paths.append(path)
paths = [
root_volume,
QtCore.QDir.homePath(),
QtCore.QStandardPaths.writableLocation(QtCore.QStandardPaths.StandardLocation.MusicLocation),
]
file_dialog.setSidebarUrls(QtCore.QUrl.fromLocalFile(p) for p in paths + sorted(volume_paths) if p)
dirs = ()
if file_dialog.exec() == QtWidgets.QDialog.DialogCode.Accepted:
dirs = file_dialog.selectedFiles()
return tuple(dirs)
def qlistwidget_items(qlistwidget):
"""Yield all items from a QListWidget"""
for i in range(qlistwidget.count()):
yield qlistwidget.item(i)
def changes_require_restart_warning(parent, warnings=None, notes=None):
"""Display a warning dialog about modified options requiring a restart"""
if not warnings:
return
text = '<p><ul>'
for warning in warnings:
text += '<li>' + html_escape(warning) + '</li>'
text += "</ul></p>"
if notes:
for note in notes:
text += "<p><em>" + html_escape(note) + "</em></p>"
text += "<p><strong>" + _("You have to restart Picard for the changes to take effect.") + "</strong></p>"
QtWidgets.QMessageBox.warning(
parent,
_("Changes only applied on restart"),
text
)
def menu_builder(menu, main_actions, *args):
"""Adds each argument to menu, depending on their type"""
for arg in args:
if arg == '-':
menu.addSeparator()
elif isinstance(arg, QtWidgets.QMenu):
menu.addMenu(arg)
elif isinstance(arg, MainAction) and main_actions[arg]:
menu.addAction(main_actions[arg])
elif isinstance(arg, QtWidgets.QWidgetAction):
menu.addAction(arg)
| 8,346
|
Python
|
.py
| 190
| 36.721053
| 115
| 0.66909
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,982
|
collectionmenu.py
|
metabrainz_picard/picard/ui/collectionmenu.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2013 Michael Wiencek
# Copyright (C) 2014-2015, 2018, 2020-2024 Laurent Monin
# Copyright (C) 2016-2017 Sambhav Kothari
# Copyright (C) 2018 Vishal Choudhary
# Copyright (C) 2018, 2022-2023 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from PyQt6 import (
QtCore,
QtGui,
QtWidgets,
)
from picard.collection import (
load_user_collections,
user_collections,
)
from picard.i18n import (
gettext as _,
ngettext,
sort_key,
)
class CollectionMenu(QtWidgets.QMenu):
def __init__(self, albums, title, parent=None):
super().__init__(title, parent=parent)
self.releases = set(a.id for a in albums)
self._ignore_update = False
self._ignore_hover = False
self._update_collections()
def _update_collections(self):
self._ignore_update = True
self.clear()
self.actions = []
for collection in sorted(user_collections.values(),
key=lambda c: (sort_key(c.name), c.id)):
action = QtWidgets.QWidgetAction(self)
action.setDefaultWidget(CollectionMenuItem(self, collection))
self.addAction(action)
self.actions.append(action)
self._ignore_update = False
self.addSeparator()
self.refresh_action = self.addAction(_("Refresh List"))
self.hovered.connect(self._on_hovered)
def _refresh_list(self):
self.refresh_action.setEnabled(False)
load_user_collections(self._update_collections)
def mouseReleaseEvent(self, event):
# Not using self.refresh_action.triggered because it closes the menu
if self.actionAt(event.pos()) == self.refresh_action and self.refresh_action.isEnabled():
self._refresh_list()
def _on_hovered(self, action):
if self._ignore_hover:
return
for a in self.actions:
a.defaultWidget().set_active(a == action)
def update_active_action_for_widget(self, widget):
if self._ignore_update:
return
for action in self.actions:
action_widget = action.defaultWidget()
is_active = action_widget == widget
if is_active:
self._ignore_hover = True
self.setActiveAction(action)
self._ignore_hover = False
action_widget.set_active(is_active)
class CollectionMenuItem(QtWidgets.QWidget):
def __init__(self, menu, collection, parent=None):
super().__init__(parent=parent)
self.menu = menu
self.active = False
self._setup_layout(menu, collection)
self._setup_colors()
def _setup_layout(self, menu, collection):
layout = QtWidgets.QVBoxLayout(self)
style = self.style()
layout.setContentsMargins(
style.pixelMetric(QtWidgets.QStyle.PixelMetric.PM_LayoutLeftMargin),
style.pixelMetric(QtWidgets.QStyle.PixelMetric.PM_FocusFrameVMargin),
style.pixelMetric(QtWidgets.QStyle.PixelMetric.PM_LayoutRightMargin),
style.pixelMetric(QtWidgets.QStyle.PixelMetric.PM_FocusFrameVMargin))
self.checkbox = CollectionCheckBox(menu, collection, parent=self)
layout.addWidget(self.checkbox)
def _setup_colors(self):
palette = self.palette()
self.text_color = palette.text().color()
self.highlight_color = palette.highlightedText().color()
def set_active(self, active):
self.active = active
palette = self.palette()
textcolor = self.highlight_color if active else self.text_color
palette.setColor(QtGui.QPalette.ColorRole.WindowText, textcolor)
self.checkbox.setPalette(palette)
def enterEvent(self, e):
self.menu.update_active_action_for_widget(self)
def leaveEvent(self, e):
self.set_active(False)
def paintEvent(self, e):
painter = QtWidgets.QStylePainter(self)
option = QtWidgets.QStyleOptionMenuItem()
option.initFrom(self)
option.state = QtWidgets.QStyle.StateFlag.State_None
if self.isEnabled():
option.state |= QtWidgets.QStyle.StateFlag.State_Enabled
if self.active:
option.state |= QtWidgets.QStyle.StateFlag.State_Selected
painter.drawControl(QtWidgets.QStyle.ControlElement.CE_MenuItem, option)
class CollectionCheckBox(QtWidgets.QCheckBox):
def __init__(self, menu, collection, parent=None):
self.menu = menu
self.collection = collection
super().__init__(self._label(), parent=parent)
releases = collection.releases & menu.releases
if len(releases) == len(menu.releases):
self.setCheckState(QtCore.Qt.CheckState.Checked)
elif not releases:
self.setCheckState(QtCore.Qt.CheckState.Unchecked)
else:
self.setCheckState(QtCore.Qt.CheckState.PartiallyChecked)
def nextCheckState(self):
releases = self.menu.releases
if releases & self.collection.pending_releases:
return
diff = releases - self.collection.releases
if diff:
self.collection.add_releases(diff, self._update_text)
self.setCheckState(QtCore.Qt.CheckState.Checked)
else:
self.collection.remove_releases(releases & self.collection.releases, self._update_text)
self.setCheckState(QtCore.Qt.CheckState.Unchecked)
def _update_text(self):
self.setText(self._label())
def _label(self):
c = self.collection
return ngettext("%(name)s (%(count)i release)", "%(name)s (%(count)i releases)", c.size) % {
'name': c.name,
'count': c.size,
}
| 6,476
|
Python
|
.py
| 153
| 34.424837
| 100
| 0.667408
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,983
|
pluginupdatedialog.py
|
metabrainz_picard/picard/ui/pluginupdatedialog.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2022-2023 Philipp Wolfer
# Copyright (C) 2023 Bob Swift
# Copyright (C) 2024 Laurent Monin
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from PyQt6 import QtCore
from PyQt6.QtWidgets import (
QCheckBox,
QMessageBox,
)
from picard.i18n import (
gettext as _,
ngettext,
)
UPDATE_LINES_TO_SHOW = 3
class PluginUpdatesDialog():
def __init__(self, parent, plugin_names):
self._plugin_names = sorted(plugin_names)
self.show_again = True
show_again_text = _("Perform this check again the next time you start Picard.")
self.msg = QMessageBox(parent)
self.msg.setIcon(QMessageBox.Icon.Information)
self.msg.setText(self._dialog_text)
self.msg.setWindowTitle(_("Picard Plugins Update"))
self.msg.setWindowModality(QtCore.Qt.WindowModality.ApplicationModal)
self.cb = QCheckBox(show_again_text)
self.cb.setChecked(self.show_again)
self.cb.toggled.connect(self._set_state)
self.msg.setCheckBox(self.cb)
self.msg.setStandardButtons(QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.Cancel)
self.msg.setDefaultButton(QMessageBox.StandardButton.Cancel)
def _set_state(self):
self.show_again = not self.show_again
@property
def _dialog_text(self):
file_count = len(self._plugin_names)
header = '<p>' + ngettext(
"There is an update available for one of your currently installed plugins:",
"There are updates available for your currently installed plugins:",
file_count
) + '</p>'
footer = '<p>' + ngettext(
"Do you want to update the plugin now?",
"Do you want to update the plugins now?",
file_count
) + '</p>'
extra_file_count = file_count - UPDATE_LINES_TO_SHOW
if extra_file_count > 0:
extra_plugins = '<p>' + ngettext(
"plus {extra_file_count:,d} other plugin.",
"plus {extra_file_count:,d} other plugins.",
extra_file_count).format(extra_file_count=extra_file_count) + '</p>'
else:
extra_plugins = ''
plugin_list = ''
for plugin_name in self._plugin_names[:UPDATE_LINES_TO_SHOW]:
plugin_list += f"<li>{plugin_name}</li>"
return f'{header}<ul>{plugin_list}</ul>{extra_plugins}{footer}'
def show(self):
show_plugins_page = self.msg.exec() == QMessageBox.StandardButton.Yes
return show_plugins_page, self.show_again
| 3,301
|
Python
|
.py
| 77
| 36.233766
| 103
| 0.670306
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,984
|
savewarningdialog.py
|
metabrainz_picard/picard/ui/savewarningdialog.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2022-2023 Philipp Wolfer
# Copyright (C) 2023 Bob Swift
# Copyright (C) 2024 Laurent Monin
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from PyQt6 import (
QtCore,
QtWidgets,
)
from picard.config import get_config
from picard.i18n import (
gettext as _,
ngettext,
)
class SaveWarningDialog():
def __init__(self, parent, file_count):
actions = []
config = get_config()
if not config.setting['dont_write_tags']:
actions.append(ngettext(
"overwrite existing metadata (tags) within the file",
"overwrite existing metadata (tags) within the files",
file_count))
if config.setting['rename_files']:
actions.append(ngettext(
"rename the file",
"rename the files",
file_count))
if config.setting['move_files']:
actions.append(ngettext(
"move the file to a different location",
"move the files to a different location",
file_count))
if actions:
header = ngettext(
"You are about to save {file_count:,d} file and this will:",
"You are about to save {file_count:,d} files and this will:",
file_count).format(file_count=file_count)
footer = _("<strong>This action cannot be undone.</strong> Do you want to continue?")
list_of_actions = ''
for action in actions:
list_of_actions += _('<li>{action}</li>').format(action=action)
warning_text = _('<p>{header}</p><ul>{list_of_actions}</ul><p>{footer}</p>').format(header=header, list_of_actions=list_of_actions, footer=footer)
else:
warning_text = _("There are no actions selected. No changes will be saved.")
disable_text = _("Don't show this warning again.")
self.disable = False
self.msg = QtWidgets.QMessageBox(parent)
self.msg.setIcon(QtWidgets.QMessageBox.Icon.Warning)
self.msg.setText(warning_text)
self.msg.setWindowTitle(_("File Save Warning"))
self.msg.setWindowModality(QtCore.Qt.WindowModality.ApplicationModal)
self.cb = QtWidgets.QCheckBox(disable_text)
self.cb.setChecked(False)
self.cb.toggled.connect(self._set_state)
self.msg.setCheckBox(self.cb)
self.msg.setStandardButtons(QtWidgets.QMessageBox.StandardButton.Ok | QtWidgets.QMessageBox.StandardButton.Cancel)
self.msg.setDefaultButton(QtWidgets.QMessageBox.StandardButton.Cancel)
def _set_state(self):
self.disable = not self.disable
def show(self):
return self.msg.exec() == QtWidgets.QMessageBox.StandardButton.Ok, self.disable
| 3,525
|
Python
|
.py
| 78
| 37.333333
| 158
| 0.659382
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,985
|
coverartbox.py
|
metabrainz_picard/picard/ui/coverartbox.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2006-2007, 2011 Lukáš Lalinský
# Copyright (C) 2009 Carlin Mangar
# Copyright (C) 2009, 2018-2023 Philipp Wolfer
# Copyright (C) 2011-2013 Michael Wiencek
# Copyright (C) 2012 Chad Wilson
# Copyright (C) 2012-2014 Wieland Hoffmann
# Copyright (C) 2013-2014, 2017-2024 Laurent Monin
# Copyright (C) 2014 Francois Ferrand
# Copyright (C) 2015 Sophist-UK
# Copyright (C) 2016 Ville Skyttä
# Copyright (C) 2016-2017 Sambhav Kothari
# Copyright (C) 2017 Paul Roub
# Copyright (C) 2017-2019 Antonio Larrosa
# Copyright (C) 2018 Vishal Choudhary
# Copyright (C) 2021 Louis Sautier
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from contextlib import ExitStack
from functools import partial
import os
import re
from PyQt6 import (
QtCore,
QtGui,
QtNetwork,
QtWidgets,
)
from picard import log
from picard.album import Album
from picard.cluster import Cluster
from picard.config import get_config
from picard.const import MAX_COVERS_TO_STACK
from picard.coverart.image import (
CoverArtImage,
CoverArtImageError,
CoverArtImageIOError,
)
from picard.file import File
from picard.i18n import gettext as _
from picard.item import FileListItem
from picard.track import Track
from picard.util import (
imageinfo,
normpath,
)
from picard.util.lrucache import LRUCache
from picard.ui import PicardDialog
from picard.ui.colors import interface_colors
from picard.ui.util import (
FileDialog,
StandardButton,
)
from picard.ui.widgets import ActiveLabel
THUMBNAIL_WIDTH = 128
COVERART_WIDTH = THUMBNAIL_WIDTH - 7
class CoverArtThumbnail(ActiveLabel):
image_dropped = QtCore.pyqtSignal(QtCore.QUrl, bytes)
def __init__(self, active=False, drops=False, pixmap_cache=None, parent=None):
super().__init__(active=active, parent=parent)
self.data = None
self.has_common_images = None
self.release = None
self.tagger = QtCore.QCoreApplication.instance()
window_handle = self.window().windowHandle()
if window_handle:
self.pixel_ratio = window_handle.screen().devicePixelRatio()
window_handle.screenChanged.connect(self.screen_changed)
else:
self.pixel_ratio = self.tagger.primaryScreen().devicePixelRatio()
self._pixmap_cache = pixmap_cache
self._update_default_pixmaps()
self.setPixmap(self.shadow)
self.setAlignment(QtCore.Qt.AlignmentFlag.AlignTop | QtCore.Qt.AlignmentFlag.AlignHCenter)
self.setMargin(0)
self.setAcceptDrops(drops)
self.clicked.connect(self.open_release_page)
self.related_images = []
self.current_pixmap_key = None
def screen_changed(self, screen):
pixel_ratio = screen.devicePixelRatio()
log.debug("screen changed, pixel ratio %s", pixel_ratio)
if pixel_ratio != self.pixel_ratio:
self.pixel_ratio = pixel_ratio
self._update_default_pixmaps()
if self.data:
self.set_data(self.data, force=True, has_common_images=self.has_common_images)
else:
self.setPixmap(self.shadow)
def _update_default_pixmaps(self):
w, h = self.scaled(THUMBNAIL_WIDTH, THUMBNAIL_WIDTH)
self.shadow = self._load_cached_default_pixmap(":/images/CoverArtShadow.png", w, h)
self.file_missing_pixmap = self._load_cached_default_pixmap(":/images/image-missing.png", w, h)
def _load_cached_default_pixmap(self, pixmap_path, w, h):
key = hash((pixmap_path, self.pixel_ratio))
try:
pixmap = self._pixmap_cache[key]
except KeyError:
pixmap = QtGui.QPixmap(pixmap_path)
pixmap = pixmap.scaled(w, h, QtCore.Qt.AspectRatioMode.KeepAspectRatio, QtCore.Qt.TransformationMode.SmoothTransformation)
pixmap.setDevicePixelRatio(self.pixel_ratio)
self._pixmap_cache[key] = pixmap
return pixmap
def __eq__(self, other):
if len(self.data) or len(other.data):
return self.current_pixmap_key == other.current_pixmap_key
else:
return True
def dragEnterEvent(self, event):
event.setDropAction(QtCore.Qt.DropAction.CopyAction)
event.accept()
def dropEvent(self, event):
if event.proposedAction() == QtCore.Qt.DropAction.IgnoreAction:
event.acceptProposedAction()
return
accepted = False
# Chromium includes the actual data of the dragged image in the drop event. This
# is useful for Google Images, where the url links to the page that contains the image
# so we use it if the downloaded url is not an image.
mime_data = event.mimeData()
dropped_data = bytes(mime_data.data('application/octet-stream'))
if not dropped_data:
dropped_data = bytes(mime_data.data('application/x-qt-image'))
if not dropped_data:
# Maybe we can get something useful from a dropped HTML snippet.
dropped_data = bytes(mime_data.data('text/html'))
if not accepted:
for url in mime_data.urls():
if url.scheme() in {'https', 'http', 'file'}:
accepted = True
log.debug("Dropped %s url (with %d bytes of data)",
url.toString(), len(dropped_data or ''))
self.image_dropped.emit(url, dropped_data)
if not accepted:
if mime_data.hasImage():
image_bytes = QtCore.QByteArray()
image_buffer = QtCore.QBuffer(image_bytes)
mime_data.imageData().save(image_buffer, 'JPEG')
dropped_data = bytes(image_bytes)
accepted = True
log.debug("Dropped %d bytes of Qt image data", len(dropped_data))
self.image_dropped.emit(QtCore.QUrl(''), dropped_data)
if accepted:
event.setDropAction(QtCore.Qt.DropAction.CopyAction)
event.accept()
def scaled(self, *dimensions):
return (round(self.pixel_ratio * dimension) for dimension in dimensions)
def show(self):
self.set_data(self.data, True)
def set_data(self, data, force=False, has_common_images=True):
if not force and self.data == data and self.has_common_images == has_common_images:
return
self.data = data
self.has_common_images = has_common_images
if not force and self.parent().isHidden():
return
if not self.data:
self.setPixmap(self.shadow)
self.current_pixmap_key = None
return
if len(self.data) == 1:
has_common_images = True
key = hash(tuple(sorted(self.data, key=lambda x: x.types_as_string())) + (has_common_images, self.pixel_ratio))
try:
pixmap = self._pixmap_cache[key]
except KeyError:
if len(self.data) == 1:
pixmap = QtGui.QPixmap()
try:
if pixmap.loadFromData(self.data[0].data):
pixmap = self.decorate_cover(pixmap)
else:
pixmap = self.file_missing_pixmap
except CoverArtImageIOError:
pixmap = self.file_missing_pixmap
else:
pixmap = self.render_cover_stack(self.data, has_common_images)
self._pixmap_cache[key] = pixmap
self.setPixmap(pixmap)
self.current_pixmap_key = key
def decorate_cover(self, pixmap):
offx = offy = 1
w = h = COVERART_WIDTH
cover = QtGui.QPixmap(self.shadow)
cover.setDevicePixelRatio(self.pixel_ratio)
pixmap = pixmap.scaled(*self.scaled(w, h), QtCore.Qt.AspectRatioMode.KeepAspectRatio, QtCore.Qt.TransformationMode.SmoothTransformation)
pixmap.setDevicePixelRatio(self.pixel_ratio)
painter = QtGui.QPainter(cover)
bgcolor = QtGui.QColor.fromRgb(0, 0, 0, 128)
painter.fillRect(QtCore.QRectF(offx, offy, w, h), bgcolor)
self._draw_centered(painter, pixmap, w, h, offx, offy)
painter.end()
return cover
@staticmethod
def _draw_centered(painter, pixmap, width, height, offset_x=0, offset_y=0):
pixel_ratio = pixmap.devicePixelRatio()
x = int(offset_x + (width - pixmap.width() / pixel_ratio) // 2)
y = int(offset_y + (height - pixmap.height() / pixel_ratio) // 2)
painter.drawPixmap(x, y, pixmap)
def render_cover_stack(self, data, has_common_images):
w = h = THUMBNAIL_WIDTH
displacements = 20
limited = len(data) > MAX_COVERS_TO_STACK
if limited:
data_to_paint = data[:MAX_COVERS_TO_STACK - 1]
offset = displacements * len(data_to_paint)
else:
data_to_paint = data
offset = displacements * (len(data_to_paint) - 1)
stack_width, stack_height = (w + offset, h + offset)
pixmap = QtGui.QPixmap(*self.scaled(stack_width, stack_height))
pixmap.setDevicePixelRatio(self.pixel_ratio)
bgcolor = self.palette().color(QtGui.QPalette.ColorRole.Window)
painter = QtGui.QPainter(pixmap)
painter.fillRect(QtCore.QRectF(0, 0, stack_width, stack_height), bgcolor)
cx = stack_width - w // 2
cy = h // 2
def calculate_cover_coordinates(pixmap, cx, cy):
pixel_ratio = pixmap.devicePixelRatio()
x = int(cx - pixmap.width() / pixel_ratio // 2)
y = int(cy - pixmap.height() / pixel_ratio // 2)
return x, y
if limited:
# Draw the default background three times to indicate that there are more
# covers than the ones displayed
x, y = calculate_cover_coordinates(self.shadow, cx, cy)
for i in range(3):
painter.drawPixmap(x, y, self.shadow)
x -= displacements // 3
y += displacements // 3
cx -= displacements
cy += displacements
else:
cx = stack_width - w // 2
cy = h // 2
for image in reversed(data_to_paint):
if isinstance(image, QtGui.QPixmap):
thumb = image
else:
thumb = QtGui.QPixmap()
try:
if not thumb.loadFromData(image.data):
thumb = self.file_missing_pixmap
except CoverArtImageIOError:
thumb = self.file_missing_pixmap
thumb = self.decorate_cover(thumb)
x, y = calculate_cover_coordinates(thumb, cx, cy)
painter.drawPixmap(x, y, thumb)
cx -= displacements
cy += displacements
if not has_common_images:
# Draw a highlight around the first cover to indicate that
# images are not common to all selected items
color = interface_colors.get_qcolor('first_cover_hl')
border_length = 10
for k in range(border_length):
color.setAlpha(255 - k * 255 // border_length)
painter.setPen(color)
x_offset = x + COVERART_WIDTH + k
# Horizontal line above the cover
painter.drawLine(x, y - k - 1, x_offset + 1, y - k - 1)
# Vertical line right of the cover
painter.drawLine(x_offset + 2, y - 1 - k, x_offset + 2, y + COVERART_WIDTH + 4)
# A bit of shadow
for k in range(5):
bgcolor.setAlpha(80 + k * 255 // 7)
painter.setPen(bgcolor)
painter.drawLine(x + COVERART_WIDTH + 2, y + COVERART_WIDTH + 2 + k, x + COVERART_WIDTH + border_length + 2, y + COVERART_WIDTH + 2 + k)
painter.end()
return pixmap.scaled(*self.scaled(w, h), QtCore.Qt.AspectRatioMode.KeepAspectRatio, QtCore.Qt.TransformationMode.SmoothTransformation)
def set_metadata(self, metadata):
data = None
self.related_images = []
if metadata and metadata.images:
self.related_images = metadata.images
data = [image for image in metadata.images if image.is_front_image()]
if not data:
# There's no front image, choose the first one available
data = [metadata.images[0]]
has_common_images = getattr(metadata, 'has_common_images', True)
self.set_data(data, has_common_images=has_common_images)
release = None
if metadata:
release = metadata.get('musicbrainz_albumid', None)
if release:
self.setActive(True)
text = _("View release on MusicBrainz")
else:
self.setActive(False)
text = ""
if hasattr(metadata, 'has_common_images'):
if has_common_images:
note = _('Common images on all tracks')
else:
note = _('Tracks contain different images')
if text:
text += '<br />'
text += '<i>%s</i>' % note
self.setToolTip(text)
self.release = release
def open_release_page(self):
lookup = self.tagger.get_file_lookup()
lookup.album_lookup(self.release)
def set_image_replace(obj, coverartimage):
obj.metadata.images.strip_front_images()
obj.metadata.images.append(coverartimage)
obj.metadata_images_changed.emit()
def set_image_append(obj, coverartimage):
obj.metadata.images.append(coverartimage)
obj.metadata_images_changed.emit()
def iter_file_parents(file):
parent = file.parent_item
if parent:
yield parent
if isinstance(parent, Track) and parent.album:
yield parent.album
elif isinstance(parent, Cluster) and parent.related_album:
yield parent.related_album
HTML_IMG_SRC_REGEX = re.compile(r'<img .*?src="(.*?)"', re.UNICODE)
class ImageURLDialog(PicardDialog):
def __init__(self, parent=None):
super().__init__(parent=parent)
self.setWindowTitle(_("Enter url"))
self.setWindowModality(QtCore.Qt.WindowModality.WindowModal)
self.layout = QtWidgets.QVBoxLayout(self)
self.label = QtWidgets.QLabel(_("Cover art url:"))
self.url = QtWidgets.QLineEdit(self)
self.buttonbox = QtWidgets.QDialogButtonBox(self)
accept_role = QtWidgets.QDialogButtonBox.ButtonRole.AcceptRole
self.buttonbox.addButton(StandardButton(StandardButton.OK), accept_role)
reject_role = QtWidgets.QDialogButtonBox.ButtonRole.RejectRole
self.buttonbox.addButton(StandardButton(StandardButton.CANCEL), reject_role)
self.buttonbox.accepted.connect(self.accept)
self.buttonbox.rejected.connect(self.reject)
self.layout.addWidget(self.label)
self.layout.addWidget(self.url)
self.layout.addWidget(self.buttonbox)
self.setLayout(self.layout)
@classmethod
def display(cls, parent=None):
dialog = cls(parent=parent)
result = dialog.exec()
url = QtCore.QUrl(dialog.url.text())
return (url, result == QtWidgets.QDialog.DialogCode.Accepted)
class CoverArtBox(QtWidgets.QGroupBox):
def __init__(self, parent=None):
super().__init__("", parent=parent)
self.layout = QtWidgets.QVBoxLayout()
self.layout.setSpacing(6)
self.tagger = QtCore.QCoreApplication.instance()
# Kills off any borders
self.setStyleSheet('''QGroupBox{background-color:none;border:1px;}''')
self.setFlat(True)
self.item = None
self.pixmap_cache = LRUCache(40)
self.cover_art_label = QtWidgets.QLabel('')
self.cover_art_label.setAlignment(QtCore.Qt.AlignmentFlag.AlignTop | QtCore.Qt.AlignmentFlag.AlignHCenter)
self.cover_art = CoverArtThumbnail(drops=True, pixmap_cache=self.pixmap_cache, parent=self)
self.cover_art.image_dropped.connect(self.fetch_remote_image)
spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Minimum, QtWidgets.QSizePolicy.Policy.Expanding)
self.orig_cover_art_label = QtWidgets.QLabel('')
self.orig_cover_art = CoverArtThumbnail(drops=False, pixmap_cache=self.pixmap_cache, parent=self)
self.orig_cover_art_label.setAlignment(QtCore.Qt.AlignmentFlag.AlignTop | QtCore.Qt.AlignmentFlag.AlignHCenter)
self.show_details_button = QtWidgets.QPushButton(_('Show more details'), self)
self.show_details_shortcut = QtGui.QShortcut(QtGui.QKeySequence(_("Ctrl+Shift+I")), self, self.show_cover_art_info)
self.layout.addWidget(self.cover_art_label)
self.layout.addWidget(self.cover_art)
self.layout.addWidget(self.orig_cover_art_label)
self.layout.addWidget(self.orig_cover_art)
self.layout.addWidget(self.show_details_button)
self.layout.addSpacerItem(spacerItem)
self.setLayout(self.layout)
self.orig_cover_art.setHidden(True)
self.show_details_button.setHidden(True)
self.show_details_button.clicked.connect(self.show_cover_art_info)
def show_cover_art_info(self):
self.tagger.window.view_info(default_tab=1)
def update_display(self, force=False):
if self.isHidden():
if not force:
# If the Cover art box is hidden and selection is updated
# we should not update the display of child widgets
return
else:
# Coverart box display was toggled.
# Update the pixmaps and display them
self.cover_art.show()
self.orig_cover_art.show()
# We want to show the 2 coverarts only if they are different
# and orig_cover_art data is set and not the default cd shadow
if self.orig_cover_art.data is None or self.cover_art == self.orig_cover_art:
self.show_details_button.setVisible(bool(self.item and self.item.can_view_info))
self.orig_cover_art.setVisible(False)
self.cover_art_label.setText('')
self.orig_cover_art_label.setText('')
else:
self.show_details_button.setVisible(True)
self.orig_cover_art.setVisible(True)
self.cover_art_label.setText(_('New Cover Art'))
self.orig_cover_art_label.setText(_('Original Cover Art'))
def set_item(self, item):
if not item.can_show_coverart:
self.cover_art.set_metadata(None)
self.orig_cover_art.set_metadata(None)
return
if self.item and hasattr(self.item, 'metadata_images_changed'):
self.item.metadata_images_changed.disconnect(self.update_metadata)
self.item = item
if hasattr(self.item, 'metadata_images_changed'):
self.item.metadata_images_changed.connect(self.update_metadata)
self.update_metadata()
def update_metadata(self):
if not self.item:
return
metadata = self.item.metadata
orig_metadata = None
if hasattr(self.item, 'orig_metadata'):
orig_metadata = self.item.orig_metadata
if not metadata or not metadata.images:
self.cover_art.set_metadata(orig_metadata)
else:
self.cover_art.set_metadata(metadata)
self.orig_cover_art.set_metadata(orig_metadata)
self.update_display()
def fetch_remote_image(self, url, fallback_data=None):
if self.item is None:
return
if fallback_data:
self.load_remote_image(url, fallback_data)
if url.scheme() in {'http', 'https'}:
self.tagger.webservice.download_url(
url=url,
handler=partial(self.on_remote_image_fetched, url, fallback_data=fallback_data),
priority=True,
important=True,
)
elif url.scheme() == 'file':
path = normpath(url.toLocalFile().rstrip("\0"))
if path and os.path.exists(path):
with open(path, 'rb') as f:
data = f.read()
self.load_remote_image(url, data)
def on_remote_image_fetched(self, url, data, reply, error, fallback_data=None):
if error:
log.error("Failed loading remote image from %s: %s", url, reply.errorString())
if fallback_data:
self._load_fallback_data(url, fallback_data)
return
data = bytes(data)
mime = reply.header(QtNetwork.QNetworkRequest.KnownHeaders.ContentTypeHeader)
# Some sites return a mime type with encoding like "image/jpeg; charset=UTF-8"
mime = mime.split(';')[0]
url_query = QtCore.QUrlQuery(url.query())
log.debug('Fetched remote image with MIME-Type %s from %s', mime, url.toString())
# If mime indicates only binary data we can try to guess the real mime type
if (mime in {'application/octet-stream', 'binary/data'} or mime.startswith('image/')
or imageinfo.supports_mime_type(mime)):
try:
self._try_load_remote_image(url, data)
return
except CoverArtImageError:
pass
if url_query.hasQueryItem("imgurl"):
# This may be a google images result, try to get the URL which is encoded in the query
url = QtCore.QUrl(url_query.queryItemValue("imgurl", QtCore.QUrl.ComponentFormattingOption.FullyDecoded))
log.debug('Possible Google images result, trying to fetch imgurl=%s', url.toString())
self.fetch_remote_image(url)
elif url_query.hasQueryItem("mediaurl"):
# Bing uses mediaurl
url = QtCore.QUrl(url_query.queryItemValue("mediaurl", QtCore.QUrl.ComponentFormattingOption.FullyDecoded))
log.debug('Possible Bing images result, trying to fetch imgurl=%s', url.toString())
self.fetch_remote_image(url)
else:
log.warning("Can't load remote image with MIME-Type %s", mime)
if fallback_data:
self._load_fallback_data(url, fallback_data)
def _load_fallback_data(self, url, data):
try:
log.debug("Trying to load image from dropped data")
self._try_load_remote_image(url, data)
return
except CoverArtImageError as e:
log.debug("Unable to identify dropped data format: %s", e)
# Try getting image out of HTML (e.g. for Google image search detail view)
try:
html = data.decode()
match_ = re.search(HTML_IMG_SRC_REGEX, html)
if match_:
url = QtCore.QUrl(match_.group(1))
except UnicodeDecodeError as e:
log.warning("Unable to decode dropped data format: %s", e)
else:
log.debug("Trying URL parsed from HTML: %s", url.toString())
self.fetch_remote_image(url)
def load_remote_image(self, url, data):
try:
self._try_load_remote_image(url, data)
except CoverArtImageError as e:
log.warning("Can't load image: %s", e)
return
def _try_load_remote_image(self, url, data):
coverartimage = CoverArtImage(
url=url.toString(),
types=['front'],
data=data
)
config = get_config()
if config.setting['load_image_behavior'] == 'replace':
set_image = set_image_replace
debug_info = "Replacing with dropped %r in %r"
else:
set_image = set_image_append
debug_info = "Appending dropped %r to %r"
if isinstance(self.item, Album):
album = self.item
with ExitStack() as stack:
stack.enter_context(album.suspend_metadata_images_update)
set_image(album, coverartimage)
for track in album.tracks:
stack.enter_context(track.suspend_metadata_images_update)
set_image(track, coverartimage)
for file in album.iterfiles():
set_image(file, coverartimage)
file.update(signal=False)
album.update(update_tracks=False)
elif isinstance(self.item, FileListItem):
parents = set()
filelist = self.item
with ExitStack() as stack:
stack.enter_context(filelist.suspend_metadata_images_update)
set_image(filelist, coverartimage)
for file in filelist.iterfiles():
for parent in iter_file_parents(file):
stack.enter_context(parent.suspend_metadata_images_update)
parents.add(parent)
set_image(file, coverartimage)
file.update(signal=False)
for parent in parents:
set_image(parent, coverartimage)
if isinstance(parent, Album):
parent.update(update_tracks=False)
else:
parent.update()
filelist.update()
elif isinstance(self.item, File):
file = self.item
set_image(file, coverartimage)
file.update()
else:
debug_info = "Dropping %r to %r is not handled"
log.debug(debug_info, coverartimage, self.item)
return coverartimage
def choose_local_file(self):
file_chooser = FileDialog(parent=self)
extensions = ['*' + ext for ext in imageinfo.get_supported_extensions()]
extensions.sort()
file_chooser.setNameFilters([
_("All supported image formats") + " (" + " ".join(extensions) + ")",
_("All files") + " (*)",
])
if file_chooser.exec():
file_urls = file_chooser.selectedUrls()
if file_urls:
self.fetch_remote_image(file_urls[0])
def choose_image_from_url(self):
url, ok = ImageURLDialog.display(parent=self)
if ok:
self.fetch_remote_image(url)
def set_load_image_behavior(self, behavior):
config = get_config()
config.setting['load_image_behavior'] = behavior
def keep_original_images(self):
self.item.keep_original_images()
self.cover_art.set_metadata(self.item.metadata)
self.show()
def contextMenuEvent(self, event):
menu = QtWidgets.QMenu(self)
if self.show_details_button.isVisible():
name = _("Show more details…")
show_more_details_action = QtGui.QAction(name, parent=menu)
show_more_details_action.triggered.connect(self.show_cover_art_info)
menu.addAction(show_more_details_action)
if self.orig_cover_art.isVisible():
name = _("Keep original cover art")
use_orig_value_action = QtGui.QAction(name, parent=menu)
use_orig_value_action.triggered.connect(self.keep_original_images)
menu.addAction(use_orig_value_action)
if self.item and self.item.can_show_coverart:
name = _("Choose local file…")
choose_local_file_action = QtGui.QAction(name, parent=menu)
choose_local_file_action.triggered.connect(self.choose_local_file)
menu.addAction(choose_local_file_action)
name = _("Add from url…")
choose_image_from_url_action = QtGui.QAction(name, parent=menu)
choose_image_from_url_action.triggered.connect(self.choose_image_from_url)
menu.addAction(choose_image_from_url_action)
if not menu.isEmpty():
menu.addSeparator()
load_image_behavior_group = QtGui.QActionGroup(menu)
action = QtGui.QAction(_("Replace front cover art"), parent=load_image_behavior_group)
action.setCheckable(True)
action.triggered.connect(partial(self.set_load_image_behavior, behavior='replace'))
config = get_config()
if config.setting['load_image_behavior'] == 'replace':
action.setChecked(True)
menu.addAction(action)
action = QtGui.QAction(_("Append front cover art"), parent=load_image_behavior_group)
action.setCheckable(True)
action.triggered.connect(partial(self.set_load_image_behavior, behavior='append'))
if config.setting['load_image_behavior'] == 'append':
action.setChecked(True)
menu.addAction(action)
menu.exec(event.globalPos())
event.accept()
| 29,364
|
Python
|
.py
| 629
| 36.230525
| 152
| 0.624873
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,986
|
scripteditor.py
|
metabrainz_picard/picard/ui/scripteditor.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2021-2023 Bob Swift
# Copyright (C) 2021-2023 Philipp Wolfer
# Copyright (C) 2021-2024 Laurent Monin
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from collections import namedtuple
from copy import deepcopy
from functools import partial
import os.path
import random
from PyQt6 import (
QtCore,
QtGui,
QtWidgets,
)
from PyQt6.QtGui import QPalette
from picard import log
from picard.config import (
SettingConfigSection,
get_config,
)
from picard.const import PICARD_URLS
from picard.const.defaults import (
DEFAULT_COPY_TEXT,
DEFAULT_NAMING_PRESET_ID,
DEFAULT_SCRIPT_NAME,
)
from picard.file import File
from picard.i18n import (
N_,
gettext as _,
gettext_constants,
)
from picard.metadata import Metadata
from picard.script import (
ScriptError,
ScriptParser,
get_file_naming_script,
get_file_naming_script_presets,
iter_tagging_scripts_from_tuples,
)
from picard.script.serializer import (
FileNamingScriptInfo,
ScriptSerializerImportExportError,
)
from picard.util import (
get_base_title,
icontheme,
iter_files_from_objects,
unique_numbered_title,
webbrowser2,
)
from picard.util.filenaming import WinPathTooLong
from picard.util.settingsoverride import SettingsOverride
from picard.ui import (
PicardDialog,
SingletonDialog,
)
from picard.ui.forms.ui_scripteditor import Ui_ScriptEditor
from picard.ui.forms.ui_scripteditor_details import Ui_ScriptDetails
from picard.ui.options import OptionsPage
from picard.ui.options.scripting import (
OptionsCheckError,
ScriptCheckError,
)
from picard.ui.widgets.scriptdocumentation import ScriptingDocumentationWidget
class ScriptFileError(OptionsCheckError):
pass
class ScriptEditorExamples():
"""File naming script examples.
"""
max_samples = 10 # pick up to 10 samples
def __init__(self, tagger):
"""File naming script examples.
Args:
tagger (object): The main window tagger object.
"""
self.tagger = tagger
self._sampled_example_files = []
config = get_config()
self.settings = config.setting
self.example_list = []
self.script_text = get_file_naming_script(self.settings)
def _get_samples(self, candidates):
candidates = tuple(candidates)
length = min(self.max_samples, len(candidates))
return random.sample(candidates, k=length)
def update_sample_example_files(self):
"""Get a new sample of randomly selected / loaded files to use as renaming examples.
"""
if self.tagger.window.selected_objects:
# If files/albums/tracks are selected, sample example files from them
candidates = iter_files_from_objects(self.tagger.window.selected_objects)
else:
# If files/albums/tracks are not selected, sample example files from the pool of loaded files
candidates = self.tagger.files.values()
files = self._get_samples(candidates)
self._sampled_example_files = files or list(self.default_examples())
self.update_examples()
def update_examples(self, override=None, script_text=None):
"""Update the before and after file naming examples list.
Args:
override (dict, optional): Dictionary of settings overrides to apply. Defaults to None.
script_text (str, optional): Text of the file naming script to use. Defaults to None.
"""
if override and isinstance(override, dict):
config = get_config()
self.settings = SettingsOverride(config.setting, override)
if script_text and isinstance(script_text, str):
self.script_text = script_text
if self.settings['move_files'] or self.settings['rename_files']:
if not self._sampled_example_files:
self.update_sample_example_files()
self.example_list = [self._example_to_filename(example) for example in self._sampled_example_files]
else:
err_text = _("Renaming options are disabled")
self.example_list = [[err_text, err_text]]
def _example_to_filename(self, file):
"""Produce the before and after file naming example tuple for the specified file.
Args:
file (File): File to produce example before and after names
Returns:
tuple: Example before and after names for the specified file
"""
# Operate on a copy of the file object metadata to avoid multiple changes to file metadata. See PICARD-2508.
c_metadata = Metadata()
c_metadata.copy(file.metadata)
try:
# Only apply scripts if the original file metadata has not been changed.
if self.settings['enable_tagger_scripts'] and not c_metadata.diff(file.orig_metadata):
for s in iter_tagging_scripts_from_tuples(self.settings['list_of_scripts']):
if s.enabled and s.content:
parser = ScriptParser()
parser.eval(s.content, c_metadata)
filename_before = file.filename
filename_after = file.make_filename(filename_before, c_metadata, self.settings, self.script_text)
if not self.settings['move_files']:
return os.path.basename(filename_before), os.path.basename(filename_after)
return filename_before, filename_after
except (ScriptError, TypeError, WinPathTooLong):
return "", ""
def update_example_listboxes(self, before_listbox, after_listbox):
"""Update the contents of the file naming examples before and after listboxes.
Args:
before_listbox (QListBox): The before listbox
after_listbox (QListBox): The after listbox
"""
before_listbox.clear()
after_listbox.clear()
for before, after in sorted(self.get_examples(), key=lambda x: x[1]):
before_listbox.addItem(before)
after_listbox.addItem(after)
def get_examples(self):
"""Get the list of examples.
Returns:
[list]: List of the before and after file name example tuples
"""
return self.example_list
@staticmethod
def synchronize_selected_example_lines(current_row, source, target):
"""Sets the current row in the target to match the current row in the source.
Args:
current_row (int): Currently selected row
source (QListView): Source list
target (QListView): Target list
"""
if source.currentRow() != current_row:
current_row = source.currentRow()
target.blockSignals(True)
target.setCurrentRow(current_row)
target.blockSignals(False)
@classmethod
def get_notes_text(cls):
"""Provides usage notes text suitable for display on the dialog.
Returns:
str: Notes text
"""
return _(
"If you select files from the Cluster pane or Album pane prior to opening the Options screen, "
"up to %u files will be randomly chosen from your selection as file naming examples. If you "
"have not selected any files, then some default examples will be provided.") % cls.max_samples
@classmethod
def get_tooltip_text(cls):
"""Provides tooltip text suitable for display on the dialog.
Returns:
str: Tooltip text
"""
return _("Reload up to %u items chosen at random from files selected in the main window") % cls.max_samples
@staticmethod
def default_examples():
"""Generator for default example files.
Yields:
File: the next example File object
"""
# example 1
efile = File("ticket_to_ride.mp3")
efile.state = File.NORMAL
efile.metadata.update({
'album': 'Help!',
'title': 'Ticket to Ride',
'~releasecomment': '2014 mono remaster',
'artist': 'The Beatles',
'artistsort': 'Beatles, The',
'albumartist': 'The Beatles',
'albumartistsort': 'Beatles, The',
'tracknumber': '7',
'totaltracks': '14',
'discnumber': '1',
'totaldiscs': '1',
'originaldate': '1965-08-06',
'originalyear': '1965',
'date': '2014-09-08',
'releasetype': ['album', 'soundtrack'],
'~primaryreleasetype': ['album'],
'~secondaryreleasetype': ['soundtrack'],
'releasestatus': 'official',
'releasecountry': 'US',
'barcode': '602537825745',
'catalognumber': 'PMC 1255',
'genre': 'Rock',
'isrc': 'GBAYE0900666',
'label': 'Parlophone',
'language': 'eng',
'media': '12″ Vinyl',
'script': 'Latn',
'engineer': ['Ken Scott', 'Norman Smith'],
'producer': 'George Martin',
'writer': ['John Lennon', 'Paul McCartney'],
'~bitrate': '192.0',
'~channels': '2',
'~extension': 'mp3',
'~filename': 'ticket_to_ride',
'~filesize': '3563068',
'~format': 'MPEG-1 Layer 3 - ID3v2.4',
'~length': '3:13',
'~sample_rate': '44100',
'musicbrainz_albumid': 'd7fbbb0a-1348-40ad-8eef-cd438d4cd203',
'musicbrainz_albumartistid': 'b10bbbfc-cf9e-42e0-be17-e2c3e1d2600d',
'musicbrainz_artistid': 'b10bbbfc-cf9e-42e0-be17-e2c3e1d2600d',
'musicbrainz_recordingid': 'ed052ae1-c950-47f2-8d2b-46e1b58ab76c',
'musicbrainz_trackid': '392639f5-5629-477e-b04b-93bffa703405',
'musicbrainz_releasegroupid': '0d44e1cb-c6e0-3453-8b68-4d2082f05421',
})
yield efile
# example 2
config = get_config()
efile = File("track05.flac")
efile.state = File.NORMAL
efile.metadata.update({
'album': "Coup d'État, Volume 1: Ku De Ta / Prologue",
'title': "I've Got to Learn the Mambo",
'artist': "Snowboy feat. James Hunter",
'artistsort': "Snowboy feat. Hunter, James",
'albumartist': config.setting['va_name'],
'albumartistsort': config.setting['va_name'],
'tracknumber': '5',
'totaltracks': '13',
'discnumber': '2',
'totaldiscs': '2',
'discsubtitle': "Beat Up",
'originaldate': '2005-07-04',
'originalyear': '2005',
'date': '2005-07-04',
'releasetype': ['album', 'compilation'],
'~primaryreleasetype': 'album',
'~secondaryreleasetype': 'compilation',
'releasestatus': 'official',
'releasecountry': 'AU',
'barcode': '5021456128754',
'catalognumber': 'FM001',
'label': 'Filter Music',
'media': 'CD',
'script': 'Latn',
'compilation': '1',
'~multiartist': '1',
'~bitrate': '1609.038',
'~channels': '2',
'~extension': 'flac',
'~filename': 'track05',
'~filesize': '9237672',
'~format': 'FLAC',
'~sample_rate': '44100',
'musicbrainz_albumid': '4b50c71e-0a07-46ac-82e4-cb85dc0c9bdd',
'musicbrainz_recordingid': 'b3c487cb-0e55-477d-8df3-01ec6590f099',
'musicbrainz_trackid': 'f8649a05-da39-39ba-957c-7abf8f9012be',
'musicbrainz_albumartistid': '89ad4ac3-39f7-470e-963a-56509c546377',
'musicbrainz_artistid': ['7b593455-d207-482c-8c6f-19ce22c94679', '9e082466-2390-40d1-891e-4803531f43fd'],
'musicbrainz_releasegroupid': 'fa90225d-1810-347c-ae5f-f051a760b623',
})
yield efile
def confirmation_dialog(parent, message):
"""Displays a confirmation dialog.
Args:
parent (object): Parent object / window making the call to set modality
message (str): Message to be displayed
Returns:
bool: True if accepted, otherwise False.
"""
dialog = QtWidgets.QMessageBox(
QtWidgets.QMessageBox.Icon.Warning,
_("Confirm"),
message,
QtWidgets.QMessageBox.StandardButton.Ok | QtWidgets.QMessageBox.StandardButton.Cancel,
parent
)
return dialog.exec() == QtWidgets.QMessageBox.StandardButton.Ok
def synchronize_vertical_scrollbars(widgets):
"""Synchronize position of vertical scrollbars and selections for listed widgets.
Args:
widgets (list): List of QListView widgets to synchronize
"""
# Set highlight colors for selected list items
example_style = widgets[0].palette()
highlight_bg = example_style.color(QPalette.ColorGroup.Active, QPalette.ColorRole.Highlight)
highlight_fg = example_style.color(QPalette.ColorGroup.Active, QPalette.ColorRole.HighlightedText)
stylesheet = "QListView::item:selected { color: " + highlight_fg.name() + "; background-color: " + highlight_bg.name() + "; }"
def _sync_scrollbar_vert(widget, value):
widget.blockSignals(True)
widget.verticalScrollBar().setValue(value)
widget.blockSignals(False)
widgets = set(widgets)
for widget in widgets:
for other in widgets - {widget}:
widget.verticalScrollBar().valueChanged.connect(partial(_sync_scrollbar_vert, other))
widget.setStyleSheet(stylesheet)
def populate_script_selection_combo_box(naming_scripts, selected_script_id, combo_box):
"""Populate the specified script selection combo box and identify the selected script.
Args:
naming_scripts (dict): Dictionary of available user-defined naming scripts as script dictionaries as produced by FileNamingScriptInfo().to_dict()
selected_script_id (str): ID code for the currently selected script
combo_box (QComboBox): Combo box object to populate
Returns:
int: The index of the currently selected script
"""
combo_box.blockSignals(True)
combo_box.clear()
def _add_and_check(idx, count, title, item):
combo_box.addItem(title, item)
if item['id'] == selected_script_id:
idx = count
return idx
idx = 0
count = -1
for count, (id, naming_script) in enumerate(sorted(naming_scripts.items(), key=lambda item: item[1]['title'])):
idx = _add_and_check(idx, count, naming_script['title'], naming_script)
combo_box.setCurrentIndex(idx)
combo_box.blockSignals(False)
return idx
class NotEmptyValidator(QtGui.QValidator):
def validate(self, text: str, pos):
if bool(text.strip()):
state = QtGui.QValidator.State.Acceptable
else:
state = QtGui.QValidator.State.Intermediate # so that field can be made empty temporarily
return state, text, pos
class ScriptEditorDialog(PicardDialog, SingletonDialog):
"""File Naming Script Editor Page
"""
TITLE = N_("File naming script editor")
STYLESHEET_ERROR = OptionsPage.STYLESHEET_ERROR
help_url = PICARD_URLS['doc_naming_script_edit']
signal_save = QtCore.pyqtSignal()
signal_update = QtCore.pyqtSignal()
signal_selection_changed = QtCore.pyqtSignal()
signal_index_changed = QtCore.pyqtSignal()
default_script_directory = os.path.normpath(QtCore.QStandardPaths.writableLocation(QtCore.QStandardPaths.StandardLocation.DocumentsLocation))
default_script_filename = "picard_naming_script.ptsp"
Profile = namedtuple('Profile', ['id', 'title', 'script_id'])
@classmethod
def show_instance(cls, *args, **kwargs):
if cls._instance:
# Accommodate condition where OptionsPage closing may have destroyed the
# ScriptEditorDialog instance without resetting the cls._instance property
cls._instance.show()
if not cls._instance.isVisible():
cls._instance = None
instance = super().show_instance(*args, **kwargs)
# Manually set examples in case of re-using an existing instance of the dialog
instance.examples = kwargs['examples']
instance.update_examples()
# Reset formatting lost when changing parent.
instance.ui.label.setWordWrap(False)
return instance
def __init__(self, parent=None, examples=None):
"""Stand-alone file naming script editor.
Args:
parent (QMainWindow or OptionsPage, optional): Parent object. Defaults to None.
examples (ScriptEditorExamples, required): Object containing examples to display. Defaults to None.
"""
super().__init__(parent=parent)
self.examples = examples
self.setWindowTitle(_(self.TITLE))
self.loading = True
self.ui = Ui_ScriptEditor()
self.ui.setupUi(self)
self.make_menu()
self.ui.label.setWordWrap(False)
self.installEventFilter(self)
# Dialog buttons
self.reset_button = QtWidgets.QPushButton(_("Reset"))
self.reset_button.setToolTip(self.reset_action.toolTip())
self.reset_button.clicked.connect(self.reload_from_config)
self.ui.buttonbox.addButton(self.reset_button, QtWidgets.QDialogButtonBox.ButtonRole.ActionRole)
self.save_button = self.ui.buttonbox.addButton(_("Make It So!"), QtWidgets.QDialogButtonBox.ButtonRole.AcceptRole)
self.save_button.setToolTip(self.save_action.toolTip())
self.ui.buttonbox.accepted.connect(self.make_it_so)
self.close_button = self.ui.buttonbox.addButton(QtWidgets.QDialogButtonBox.StandardButton.Cancel)
self.close_button.setToolTip(self.close_action.toolTip())
self.ui.buttonbox.rejected.connect(self.close)
self.ui.buttonbox.addButton(QtWidgets.QDialogButtonBox.StandardButton.Help)
self.ui.buttonbox.helpRequested.connect(self.show_help)
# Add links to edit script metadata
self.ui.script_title.installEventFilter(self)
self.ui.script_title.setContextMenuPolicy(QtCore.Qt.ContextMenuPolicy.ActionsContextMenu)
self.ui.script_title.addAction(self.details_action)
self.ui.file_naming_format.setEnabled(True)
# Add scripting documentation to parent frame.
doc_widget = ScriptingDocumentationWidget(include_link=False, parent=self)
self.ui.documentation_frame_layout.addWidget(doc_widget)
self.ui.file_naming_format.textChanged.connect(self.check_formats)
self.ui.script_title.textChanged.connect(self.update_script_title)
self.ui.script_title.setValidator(NotEmptyValidator(self.ui.script_title))
self._sampled_example_files = []
self.ui.example_filename_after.itemSelectionChanged.connect(self.match_before_to_after)
self.ui.example_filename_before.itemSelectionChanged.connect(self.match_after_to_before)
self.ui.preset_naming_scripts.currentIndexChanged.connect(partial(self.select_script, update_last_selected=True))
synchronize_vertical_scrollbars((self.ui.example_filename_before, self.ui.example_filename_after))
self.toggle_documentation() # Force update to display
self.examples_current_row = -1
self.selected_script_index = 0
self.current_item_dict = None
self.original_script_id = ''
self.original_script_title = ''
self.last_selected_id = ''
self.load()
self.loading = False
def setParent(self, parent):
"""Custom setParent() method to check that parent is different to avoid display problems.
Args:
parent (object): Parent to set for the instance
"""
if self.parent() != parent:
flags = self.windowFlags() | QtCore.Qt.WindowType.Window
super().setParent(parent, flags)
# Set appropriate state of script selector in parent
save_enabled = self.save_button.isEnabled()
self.set_selector_states(save_enabled=save_enabled)
def make_menu(self):
"""Build the menu bar.
"""
config = get_config()
main_menu = QtWidgets.QMenuBar()
# File menu settings
file_menu = main_menu.addMenu(_("&File"))
file_menu.setToolTipsVisible(True)
self.import_action = QtGui.QAction(_("&Import a script file"), self)
self.import_action.setToolTip(_("Import a file as a new script"))
self.import_action.setIcon(icontheme.lookup('document-open'))
self.import_action.triggered.connect(self.import_script)
file_menu.addAction(self.import_action)
self.export_action = QtGui.QAction(_("&Export a script file"), self)
self.export_action.setToolTip(_("Export the script to a file"))
self.export_action.setIcon(icontheme.lookup('document-save'))
self.export_action.triggered.connect(self.export_script)
file_menu.addAction(self.export_action)
self.reset_action = QtGui.QAction(_("&Reset all scripts"), self)
self.reset_action.setToolTip(_("Reset all scripts to the saved values"))
self.reset_action.setIcon(icontheme.lookup('view-refresh'))
self.reset_action.triggered.connect(self.reload_from_config)
file_menu.addAction(self.reset_action)
self.save_action = QtGui.QAction(_("&Save and exit"), self)
self.save_action.setToolTip(_("Save changes to the script settings and exit"))
self.save_action.setIcon(icontheme.lookup('document-save'))
self.save_action.triggered.connect(self.make_it_so)
file_menu.addAction(self.save_action)
self.close_action = QtGui.QAction(_("E&xit without saving"), self)
self.close_action.setToolTip(_("Close the script editor without saving changes"))
self.close_action.triggered.connect(self.close)
file_menu.addAction(self.close_action)
# Script menu settings
script_menu = main_menu.addMenu(_("&Script"))
script_menu.setToolTipsVisible(True)
self.details_action = QtGui.QAction(_("View/Edit Script &Metadata"), self)
self.details_action.setToolTip(_("Display the details for the script"))
self.details_action.triggered.connect(self.view_script_details)
self.details_action.setShortcut(QtGui.QKeySequence(_("Ctrl+M")))
script_menu.addAction(self.details_action)
self.add_action = QtWidgets.QMenu(_("Add a &new script"))
self.add_action.setIcon(icontheme.lookup('add-item'))
self.make_script_template_selector_menu()
script_menu.addMenu(self.add_action)
self.copy_action = QtGui.QAction(_("&Copy the current script"), self)
self.copy_action.setToolTip(_("Save a copy of the script as a new script"))
self.copy_action.setIcon(icontheme.lookup('edit-copy'))
self.copy_action.triggered.connect(self.copy_script)
script_menu.addAction(self.copy_action)
self.delete_action = QtGui.QAction(_("&Delete the current script"), self)
self.delete_action.setToolTip(_("Delete the script"))
self.delete_action.setIcon(icontheme.lookup('list-remove'))
self.delete_action.triggered.connect(self.delete_script)
script_menu.addAction(self.delete_action)
# Display menu settings
display_menu = main_menu.addMenu(_("&View"))
display_menu.setToolTipsVisible(True)
self.examples_action = QtGui.QAction(_("&Reload random example files"), self)
self.examples_action.setToolTip(self.examples.get_tooltip_text())
self.examples_action.setIcon(icontheme.lookup('view-refresh'))
self.examples_action.triggered.connect(self.update_example_files)
display_menu.addAction(self.examples_action)
display_menu.addAction(self.ui.file_naming_format.wordwrap_action)
display_menu.addAction(self.ui.file_naming_format.show_tooltips_action)
self.docs_action = QtGui.QAction(_("&Show documentation"), self)
self.docs_action.setToolTip(_("View the scripting documentation in a sidebar"))
self.docs_action.triggered.connect(self.toggle_documentation)
self.docs_action.setShortcut(QtGui.QKeySequence(_("Ctrl+H")))
self.docs_action.setCheckable(True)
self.docs_action.setChecked(config.persist["script_editor_show_documentation"])
display_menu.addAction(self.docs_action)
# Help menu settings
help_menu = main_menu.addMenu(_("&Help"))
help_menu.setToolTipsVisible(True)
self.help_action = QtGui.QAction(_("&Help…"), self)
self.help_action.setShortcut(QtGui.QKeySequence.StandardKey.HelpContents)
self.help_action.triggered.connect(self.show_help)
help_menu.addAction(self.help_action)
self.scripting_docs_action = QtGui.QAction(_("&Scripting documentation…"), self)
self.scripting_docs_action.setToolTip(_("Open the scripting documentation in your browser"))
self.scripting_docs_action.triggered.connect(self.docs_browser)
help_menu.addAction(self.scripting_docs_action)
self.ui.layout_for_menubar.addWidget(main_menu)
def make_script_template_selector_menu(self):
"""Update the sub-menu of available file naming script templates.
"""
self.add_action.clear()
def _add_menu_item(title, script):
script_action = QtGui.QAction(title, self.add_action)
script_action.triggered.connect(partial(self.new_script, script))
self.add_action.addAction(script_action)
# Add blank script template
_add_menu_item(_("Empty / blank script"), f"$noop( {_('New Script')} )")
# Add preset script templates
for script_item in get_file_naming_script_presets():
_add_menu_item(script_item['title'], script_item['script'])
def is_options_ui(self):
return self.parent().__class__.__name__ == 'RenamingOptionsPage'
def is_main_ui(self):
return self.parent().__class__.__name__ == 'MainWindow'
def load(self, reload=False):
"""Load initial configuration.
"""
config = get_config()
self.naming_scripts = config.setting['file_renaming_scripts']
self.selected_script_id = config.setting['selected_file_naming_script_id']
if not self.selected_script_id or self.selected_script_id not in self.naming_scripts:
self.selected_script_id = DEFAULT_NAMING_PRESET_ID
self.last_selected_id = self.selected_script_id
if not reload:
self.examples.settings = config.setting
self.original_script_id = self.selected_script_id
self.original_script_title = self.all_scripts()[self.original_script_id]['title']
if self.is_options_ui():
selector = self.parent().ui.naming_script_selector
idx = selector.currentIndex()
sel_id = selector.itemData(idx)['id']
if sel_id in self.all_scripts():
self.selected_script_id = sel_id
self.selected_script_index = 0
self.populate_script_selector()
if not self.loading:
self.select_script()
def all_scripts(self, scripts=None):
"""Get dictionary of all current scripts.
Returns:
dict: All current scripts
"""
return deepcopy(scripts if scripts is not None else self.naming_scripts)
def reload_from_config(self):
"""Reload the scripts and selected script from the configuration.
"""
if self.unsaved_changes_in_profile_confirmation():
self.load(reload=True)
def docs_browser(self):
"""Open the scriping documentation in a browser.
"""
webbrowser2.open('doc_scripting')
def eventFilter(self, object, event):
"""Process selected events.
"""
evtype = event.type()
if evtype in {QtCore.QEvent.Type.WindowActivate, QtCore.QEvent.Type.FocusIn}:
self.update_examples()
elif object == self.ui.script_title and evtype == QtCore.QEvent.Type.MouseButtonDblClick:
self.details_action.trigger()
return True
return False
def closeEvent(self, event):
"""Custom close event handler to check for unsaved changes.
"""
if self.unsaved_changes_in_profile_confirmation():
self.reset_script_in_settings()
self.set_selector_states(save_enabled=True)
event.ignore()
super().closeEvent(event)
else:
event.ignore()
def unsaved_changes_in_profile_confirmation(self):
"""Confirm reset of selected script in profile if it points to an unsaved script.
Returns:
bool: False if user chooses to cancel, otherwise True.
"""
all_naming_scripts = self.all_scripts()
profiles_with_scripts = self.scripts_in_profiles()
for script_id in self.unsaved_scripts():
profile = self.is_used_in_profile(script_id=script_id, profiles=profiles_with_scripts)
if not profile:
continue
old_script_title = all_naming_scripts[script_id]['title']
new_script_title = self.original_script_title
if confirmation_dialog(
self,
_(
'At least one unsaved script has been attached to an option profile.\n\n'
' Profile: {profile_title}\n'
' Script: {old_script_title}\n\n'
'Continuing without saving will reset the selected script in the profile to:\n\n'
' {new_script_title}\n\n'
'Are you sure that you want to continue?'
).format(
profile_title=profile.title,
old_script_title=old_script_title,
new_script_title=new_script_title,
)
):
self.reset_script_in_profiles()
break
else:
return False
return True
def reset_script_in_settings(self):
"""Reset the currently selected script if it was not saved and is no longer available.
"""
config = get_config()
unsaved = set(self.unsaved_scripts())
if config.setting['selected_file_naming_script_id'] in unsaved:
config.setting['selected_file_naming_script_id'] = self.original_script_id
self.naming_scripts = config.setting['file_renaming_scripts']
all_scripts = self.all_scripts()
if self.selected_script_id not in all_scripts:
if self.last_selected_id in all_scripts:
self.selected_script_id = self.last_selected_id
if self.selected_script_id not in all_scripts:
self.selected_script_id = next(iter(all_scripts))
script_text = all_scripts[self.selected_script_id]['script']
self.update_examples(script_text=script_text)
self.signal_selection_changed.emit()
def reset_script_in_profiles(self):
"""Reset the selected script in profiles if it was not saved and is no longer available.
"""
config = get_config()
profiles_with_scripts = self.scripts_in_profiles()
profiles_settings = config.profiles[SettingConfigSection.SETTINGS_KEY]
for script_id in self.unsaved_scripts():
profile = self.is_used_in_profile(script_id=script_id, profiles=profiles_with_scripts)
if profile:
profiles_settings[profile.id]['selected_file_naming_script_id'] = self.original_script_id
def unsaved_scripts(self):
"""Generate ID codes of scripts that have not been saved.
Yields:
str: ID code for the unsaved script
"""
config = get_config()
cfg_naming_scripts = config.setting['file_renaming_scripts']
all_naming_scripts = self.all_scripts(scripts=cfg_naming_scripts)
for script_id in self.naming_scripts.keys():
if script_id not in all_naming_scripts:
yield script_id
def scripts_in_profiles(self):
"""Get list of script IDs saved to option profiles.
Returns:
list: List of Profile named tuples
"""
profiles_list = []
config = get_config()
profiles = config.profiles[SettingConfigSection.PROFILES_KEY]
profile_settings = config.profiles[SettingConfigSection.SETTINGS_KEY]
for profile in profiles:
settings = profile_settings[profile['id']]
if 'selected_file_naming_script_id' in settings:
profiles_list.append(
self.Profile(
profile['id'],
profile['title'],
settings['selected_file_naming_script_id']
)
)
return profiles_list
def update_script_text(self):
"""Updates the combo box item with changes to the current script.
"""
selected, script_item = self.get_selected_index_and_item()
script_item['script'] = self.get_script()
self.update_combo_box_item(selected, script_item)
def check_duplicate_script_title(self, new_title=None):
"""Checks the script title to see if it is a duplicate of an existing script title.
If no title is provided, then it will be extracted from the item data for the
currently selected script.
Args:
new_title (string, optional): New title to check. Defaults to None.
Returns:
bool: True if the title is unique, otherwise False.
"""
selected, script_item = self.get_selected_index_and_item()
title = script_item['title'] if new_title is None else new_title
for i in range(self.ui.preset_naming_scripts.count()):
if i == selected:
continue
if title == self.ui.preset_naming_scripts.itemData(i)['title']:
return False
return True
def update_script_title(self):
"""Update the script selection combo box after updating the script title.
"""
selected, script_item = self.get_selected_index_and_item()
title = str(self.ui.script_title.text()).strip()
if title:
if self.check_duplicate_script_title(new_title=title):
script_item['title'] = title
self.update_combo_box_item(selected, script_item)
self.save_script()
self.signal_selection_changed.emit()
else:
self.display_error(OptionsCheckError(_("Error"), _("There is already a script with that title.")))
self.ui.script_title.setFocus()
else:
self.display_error(OptionsCheckError(_("Error"), _("The script title must not be empty.")))
self.ui.script_title.setText(script_item['title'])
self.ui.script_title.setFocus()
def populate_script_selector(self):
"""Populate the script selection combo box.
"""
idx = populate_script_selection_combo_box(self.naming_scripts, self.selected_script_id, self.ui.preset_naming_scripts)
self.set_selected_script_index(idx)
def toggle_documentation(self):
"""Toggle the display of the scripting documentation sidebar.
"""
checked = self.docs_action.isChecked()
config = get_config()
config.persist['script_editor_show_documentation'] = checked
self.ui.documentation_frame.setVisible(checked)
def view_script_details(self):
"""View and edit the metadata associated with the script.
"""
self.current_item_dict = self.get_selected_item()
details_page = ScriptDetailsEditor(self.current_item_dict, parent=self)
details_page.signal_save.connect(self.update_from_details)
details_page.show()
details_page.raise_()
details_page.activateWindow()
def update_from_details(self):
"""Update the script selection combo box and script list after updates from the script details dialog.
"""
selected, script_item = self.get_selected_index_and_item()
new_title = self.current_item_dict['title']
old_title = script_item['title']
if not self.check_duplicate_script_title(new_title=new_title):
self.current_item_dict['title'] = old_title
self.update_combo_box_item(selected, self.current_item_dict)
self.ui.script_title.setText(new_title)
self.save_script()
def _set_combobox_index(self, idx):
"""Sets the index of the script selector combo box.
Args:
idx (int): New index position
"""
widget = self.ui.preset_naming_scripts
widget.blockSignals(True)
widget.setCurrentIndex(idx)
widget.blockSignals(False)
self.selected_script_index = idx
self.signal_index_changed.emit()
def _insert_item(self, script_item):
"""Insert a new item into the script selection combo box and update the script list in the settings.
Args:
script_item (dict): File naming script to insert as produced by FileNamingScriptInfo().to_dict()
"""
self.selected_script_id = script_item['id']
self.naming_scripts[self.selected_script_id] = script_item
idx = populate_script_selection_combo_box(
self.naming_scripts,
self.selected_script_id,
self.ui.preset_naming_scripts
)
self._set_combobox_index(idx)
self.naming_scripts = self.get_scripts_dict()
self.select_script(update_last_selected=False)
self.save_script()
def new_script_name(self, base_title=None):
"""Get new unique script name.
"""
default_title = base_title if base_title is not None else gettext_constants(DEFAULT_SCRIPT_NAME)
existing_titles = set(script['title'] for script in self.naming_scripts.values())
return unique_numbered_title(default_title, existing_titles)
def new_script(self, script):
"""Add a new script to the script selection combo box and script list.
"""
script_item = FileNamingScriptInfo(script=script)
script_item.title = self.new_script_name()
self._insert_item(script_item.to_dict())
def copy_script(self):
"""Add a copy of the script as a new editable script to the script selection combo box.
"""
selected, script_item = self.get_selected_index_and_item()
new_item = FileNamingScriptInfo.create_from_dict(script_dict=script_item).copy()
base_title = "%s %s" % (get_base_title(script_item['title']), gettext_constants(DEFAULT_COPY_TEXT))
new_item.title = self.new_script_name(base_title)
self._insert_item(new_item.to_dict())
def make_it_so(self):
"""Save the scripts and settings to configuration and exit.
"""
script_item = self.get_selected_item()
self.selected_script_id = script_item['id']
self.naming_scripts = self.get_scripts_dict()
config = get_config()
config.setting['file_renaming_scripts'] = self.naming_scripts
config.setting['selected_file_naming_script_id'] = script_item['id']
self.close()
def get_scripts_dict(self):
"""Get dictionary of scripts from the combo box items suitable for saving to the configuration settings.
Returns:
dict: Dictionary of scripts
"""
naming_scripts = {}
for idx in range(self.ui.preset_naming_scripts.count()):
script_item = self.ui.preset_naming_scripts.itemData(idx)
naming_scripts[script_item['id']] = script_item
return naming_scripts
def get_script_item(self, idx):
return self.ui.preset_naming_scripts.itemData(idx)
def get_selected_index_and_item(self):
idx = self.ui.preset_naming_scripts.currentIndex()
return idx, self.get_script_item(idx)
def get_selected_item(self):
"""Get the specified item from the script selection combo box.
Returns:
dict: File naming script dictionary as produced by FileNamingScriptInfo().to_dict()
"""
return self.get_script_item(self.ui.preset_naming_scripts.currentIndex())
def set_selected_script_id(self, id):
"""Select the script with the specified ID.
Args:
id (str): ID of the script to select
"""
idx = 0
for i in range(self.ui.preset_naming_scripts.count()):
script_item = self.get_script_item(i)
if script_item['id'] == id:
idx = i
break
self.set_selected_script_index(idx)
def set_selected_script_index(self, idx):
"""Select the script at the specified combo box index.
Args:
idx (int): Index of the script to select
"""
self._set_combobox_index(idx)
self.select_script()
def select_script(self, update_last_selected=True):
"""Load the current script from the combo box into the editor.
"""
self.selected_script_index, script_item = self.get_selected_index_and_item()
self.ui.script_title.setText(script_item['title'])
self.ui.file_naming_format.setPlainText(str(script_item['script']).strip())
self.selected_script_id = script_item['id']
if update_last_selected:
self.last_selected_id = self.selected_script_id
if not self.loading:
self.save_script()
self.signal_save.emit()
self.set_button_states()
self.update_examples()
if not self.loading:
self.signal_selection_changed.emit()
def update_combo_box_item(self, idx, script_item):
"""Update the title and item data for the specified script selection combo box item.
Args:
idx (int): Index of the item to update
script_item (dict): Updated file naming script information as produced by FileNamingScriptInfo().to_dict()
"""
self.ui.preset_naming_scripts.setItemData(idx, script_item)
title = script_item['title']
self.ui.preset_naming_scripts.setItemText(idx, title)
self.naming_scripts = self.get_scripts_dict()
if not self.loading:
self.signal_save.emit()
def set_selector_states(self, save_enabled=True):
"""Set the script selector enabled states based on the save_enabled state of the currently selected
item in the script selection combo box.
Args:
save_enabled (bool, optional): Allow selection of different script item. Defaults to True.
"""
self.ui.preset_naming_scripts.setEnabled(save_enabled)
if self.is_options_ui():
self.parent().ui.naming_script_selector.setEnabled(save_enabled)
elif self.is_main_ui():
self.parent().script_quick_selector_menu.setEnabled(save_enabled)
def set_button_states(self, save_enabled=True):
"""Set the button states based on the readonly and deletable attributes of the currently selected
item in the script selection combo box.
Args:
save_enabled (bool, optional): Allow updates to be saved to this item. Defaults to True.
"""
selected = self.ui.preset_naming_scripts.currentIndex()
if selected < 0:
return
# Script selectors
self.set_selector_states(save_enabled=save_enabled)
# Buttons
self.save_action.setEnabled(save_enabled)
self.save_button.setEnabled(save_enabled)
# Menu items
self.add_action.setEnabled(save_enabled)
self.copy_action.setEnabled(save_enabled)
self.delete_action.setEnabled(save_enabled and self.ui.preset_naming_scripts.count() > 1)
self.import_action.setEnabled(save_enabled)
self.export_action.setEnabled(save_enabled)
def match_after_to_before(self):
"""Sets the selected item in the 'after' list to the corresponding item in the 'before' list.
"""
self.examples.synchronize_selected_example_lines(
self.examples_current_row,
self.ui.example_filename_before,
self.ui.example_filename_after
)
def match_before_to_after(self):
"""Sets the selected item in the 'before' list to the corresponding item in the 'after' list.
"""
self.examples.synchronize_selected_example_lines(
self.examples_current_row,
self.ui.example_filename_after,
self.ui.example_filename_before
)
def delete_script(self):
"""Removes the currently selected script from the script selection combo box and script list.
"""
profile = self.is_used_in_profile()
if profile is not None:
QtWidgets.QMessageBox(
QtWidgets.QMessageBox.Icon.Warning,
_("Error Deleting Script"),
_(
"The script could not be deleted because it is used in one of the user profiles."
"\n\n"
"Profile: %s"
) % profile.title,
QtWidgets.QMessageBox.StandardButton.Ok,
self
).exec()
return
if confirmation_dialog(self, _("Are you sure that you want to delete the script?")):
widget = self.ui.preset_naming_scripts
idx = widget.currentIndex()
widget.blockSignals(True)
widget.removeItem(idx)
widget.blockSignals(False)
if idx >= widget.count():
idx = widget.count() - 1
self._set_combobox_index(idx)
self.selected_script_index = idx
self.naming_scripts = self.get_scripts_dict()
self.select_script(update_last_selected=False)
def is_used_in_profile(self, script_id=None, profiles=None):
"""Check if the script is included in any profile settings.
Args:
script_id (str, optional): ID of the script to check or ID of current script if not specified.
profiles (list, optional): List of Profile named tuples.
Returns:
Profile: Named tuple of profile script information if the script is used in a profile otherwise None
"""
if script_id is None:
script_id = self.selected_script_id
if profiles is None:
profiles = self.scripts_in_profiles()
for profile in profiles:
if profile.script_id == script_id:
return profile
return None
def save_script(self):
"""Saves changes to the current script to the script list and combo box item.
"""
title = str(self.ui.script_title.text()).strip()
if title:
selected, script_item = self.get_selected_index_and_item()
if self.check_duplicate_script_title(new_title=title):
script_item['title'] = title
script_item['script'] = self.get_script()
self.update_combo_box_item(selected, script_item)
else:
self.display_error(OptionsCheckError(_("Error"), _("The script title must not be empty.")))
def get_script(self):
"""Provides the text of the file naming script currently loaded into the editor.
Returns:
str: File naming script
"""
return str(self.ui.file_naming_format.toPlainText()).strip()
def update_example_files(self):
"""Update the before and after file naming examples list.
"""
self.examples.update_sample_example_files()
self.display_examples()
def update_examples(self, script_text=None):
"""Update the before and after file naming examples using the current file naming script in the editor.
"""
if script_text is None:
script_text = self.get_script()
self.examples.update_examples(script_text=script_text)
self.display_examples()
def display_examples(self):
"""Update the display of the before and after file naming examples.
"""
self.examples_current_row = -1
self.examples.update_example_listboxes(self.ui.example_filename_before, self.ui.example_filename_after)
if not self.loading:
self.signal_update.emit()
def output_file_error(self, fmt, filename, msg):
"""Log file error and display error message dialog.
Args:
fmt (str): Format for the error type being displayed
filename (str): Name of the file being imported or exported
msg (str): Error message to display
"""
log.error(fmt, filename, msg)
error_message = _(fmt) % (filename, _(msg))
self.display_error(ScriptFileError(_("File Error"), error_message))
def import_script(self):
"""Import from an external text file to a new script. Import can be either a plain text script or
a naming script package.
"""
try:
script_item = FileNamingScriptInfo().import_script(self)
except ScriptSerializerImportExportError as error:
self.output_file_error(error.format, error.filename, error.error_msg)
return
if script_item:
title = script_item.title.strip()
for id in self.naming_scripts:
existing_script = self.naming_scripts[id]
if title != existing_script['title']:
continue
box = QtWidgets.QMessageBox()
box.setIcon(QtWidgets.QMessageBox.Icon.Question)
box.setWindowTitle(_("Confirm"))
box.setText(
_(
"A script named \"{script_name}\" already exists.\n"
"\n"
"Do you want to overwrite it, add as a copy or cancel?"
).format(script_name=title,))
box.setStandardButtons(QtWidgets.QMessageBox.StandardButton.Yes | QtWidgets.QMessageBox.StandardButton.No | QtWidgets.QMessageBox.StandardButton.Cancel)
buttonY = box.button(QtWidgets.QMessageBox.StandardButton.Yes)
buttonY.setText(_("Overwrite"))
buttonN = box.button(QtWidgets.QMessageBox.StandardButton.No)
buttonN.setText(_("Copy"))
box.setDefaultButton(QtWidgets.QMessageBox.StandardButton.Cancel)
box.exec()
if box.clickedButton() == buttonY:
# Overwrite pressed
script_item.id = id
elif box.clickedButton() == buttonN:
# Copy pressed
titles = [self.naming_scripts[id]['title'] for id in self.naming_scripts]
script_item.title = unique_numbered_title(title, titles)
else:
return
self._insert_item(script_item.to_dict())
def export_script(self):
"""Export the current script to an external file. Export can be either as a plain text
script or a naming script package.
"""
selected = self.get_selected_item()
script_item = FileNamingScriptInfo.create_from_dict(script_dict=selected, create_new_id=False)
script_item.title = get_base_title(script_item.title)
try:
script_item.export_script(parent=self)
except ScriptSerializerImportExportError as error:
self.output_file_error(error.format, error.filename, error.error_msg)
def check_formats(self):
"""Checks for valid file naming script and settings, and updates the examples.
"""
self.test()
self.update_examples()
def check_format(self):
"""Parse the file naming script and check for errors.
"""
config = get_config()
parser = ScriptParser()
script_text = self.get_script()
try:
parser.eval(script_text)
except Exception as e:
raise ScriptCheckError("", str(e))
if config.setting['rename_files']:
if not self.get_script():
raise ScriptCheckError("", _("The file naming format must not be empty."))
def display_error(self, error):
"""Display an error message for the specified error.
Args:
error (Exception): The exception to display.
"""
# Ignore scripting errors, those are handled inline
if not isinstance(error, ScriptCheckError):
dialog = QtWidgets.QMessageBox(
QtWidgets.QMessageBox.Icon.Warning, error.title,
error.info, QtWidgets.QMessageBox.StandardButton.Ok, self
)
dialog.exec()
def test(self):
"""Parse the script and display any errors.
"""
self.ui.renaming_error.setStyleSheet("")
self.ui.renaming_error.setText("")
save_enabled = True
try:
self.check_format()
# Update script in combobox item if no errors.
self.update_script_text()
except ScriptCheckError as e:
self.ui.renaming_error.setStyleSheet(self.STYLESHEET_ERROR)
self.ui.renaming_error.setText(e.info)
save_enabled = False
self.set_button_states(save_enabled=save_enabled)
class ScriptDetailsEditor(PicardDialog):
"""View / edit the metadata details for a script.
"""
NAME = 'scriptdetails'
TITLE = N_("Script Details")
signal_save = QtCore.pyqtSignal()
def __init__(self, script_item, parent=None):
"""Script metadata viewer / editor.
Args:
script_item (dict): The script whose metadata is displayed
parent (optional): The parent object, passed to PicardDialog
"""
super().__init__(parent=parent)
self.script_item = script_item
self.ui = Ui_ScriptDetails()
self.ui.setupUi(self)
self.ui.buttonBox.accepted.connect(self.save_changes)
self.ui.buttonBox.rejected.connect(self.close_window)
self.ui.last_updated_now.clicked.connect(self.set_last_updated)
self.ui.script_title.setText(self.script_item['title'])
self.ui.script_author.setText(self.script_item['author'])
self.ui.script_version.setText(self.script_item['version'])
self.ui.script_last_updated.setText(self.script_item['last_updated'])
self.ui.script_license.setText(self.script_item['license'])
self.ui.script_description.setPlainText(self.script_item['description'])
self.ui.buttonBox.setFocus()
self.setModal(True)
self.setWindowTitle(_(self.TITLE))
self.skip_change_check = False
def has_changed(self):
"""Check if the current script metadata has pending edits that have not been saved.
Returns:
bool: True if there are unsaved changes, otherwise false.
"""
return self.script_item['title'] != self.ui.script_title.text().strip() or \
self.script_item['author'] != self.ui.script_author.text().strip() or \
self.script_item['version'] != self.ui.script_version.text().strip() or \
self.script_item['license'] != self.ui.script_license.text().strip() or \
self.script_item['description'] != self.ui.script_description.toPlainText().strip()
def change_check(self):
"""Confirm whether the unsaved changes should be lost.
Returns:
bool: True if changes can be lost, otherwise False.
"""
return confirmation_dialog(
self,
_(
"There are unsaved changes to the current metadata."
"\n\n"
"Do you want to continue and lose these changes?"
),
)
def set_last_updated(self):
"""Set the last updated value to the current timestamp.
"""
self.ui.script_last_updated.setText(FileNamingScriptInfo.make_last_updated())
self.ui.script_last_updated.setModified(True)
def save_changes(self):
"""Update the script object with any changes to the metadata.
"""
title = self.ui.script_title.text().strip()
if not title:
QtWidgets.QMessageBox(
QtWidgets.QMessageBox.Icon.Critical,
_("Error"),
_("The script title must not be empty."),
QtWidgets.QMessageBox.StandardButton.Ok,
self
).exec()
return
if self.has_changed():
last_updated = self.ui.script_last_updated
if not last_updated.isModified() or not last_updated.text().strip():
self.set_last_updated()
self.script_item['title'] = self.ui.script_title.text().strip()
self.script_item['author'] = self.ui.script_author.text().strip()
self.script_item['version'] = self.ui.script_version.text().strip()
self.script_item['license'] = self.ui.script_license.text().strip()
self.script_item['description'] = self.ui.script_description.toPlainText().strip()
self.script_item['last_updated'] = self.ui.script_last_updated.text().strip()
self.signal_save.emit()
self.skip_change_check = True
self.close_window()
def close_window(self):
"""Close the script metadata editor window.
"""
self.close()
def closeEvent(self, event):
"""Custom close event handler to check for unsaved changes.
"""
if (self.skip_change_check
or not self.has_changed()
or (self.has_changed() and self.change_check())):
event.accept()
else:
event.ignore()
| 58,936
|
Python
|
.py
| 1,242
| 37.47504
| 168
| 0.637926
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,987
|
tagsfromfilenames.py
|
metabrainz_picard/picard/ui/tagsfromfilenames.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2006-2007 Lukáš Lalinský
# Copyright (C) 2009, 2014, 2019-2022 Philipp Wolfer
# Copyright (C) 2012-2013 Michael Wiencek
# Copyright (C) 2014, 2017 Sophist-UK
# Copyright (C) 2016-2017 Sambhav Kothari
# Copyright (C) 2017 Ville Skyttä
# Copyright (C) 2018 Vishal Choudhary
# Copyright (C) 2018, 2020-2024 Laurent Monin
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from collections import OrderedDict
import os.path
import re
from PyQt6 import QtWidgets
from picard.config import get_config
from picard.i18n import gettext as _
from picard.script.parser import normalize_tagname
from picard.util.tags import display_tag_name
from picard.ui import PicardDialog
from picard.ui.forms.ui_tagsfromfilenames import Ui_TagsFromFileNamesDialog
from picard.ui.util import StandardButton
class TagMatchExpression:
_numeric_tags = ('tracknumber', 'totaltracks', 'discnumber', 'totaldiscs')
def __init__(self, expression, replace_underscores=False):
self.replace_underscores = replace_underscores
self._tag_re = re.compile(r"(%\w+%)")
self._parse(expression)
def _parse(self, expression):
self._group_map = OrderedDict()
format_re = ['(?:^|/)']
for i, part in enumerate(self._tag_re.split(expression)):
if part.startswith('%') and part.endswith('%'):
name = part[1:-1]
group = '%s_%i' % (name, i)
tag = normalize_tagname(name)
self._group_map[group] = tag
if tag in self._numeric_tags:
format_re.append(r'(?P<' + group + r'>\d+)')
elif tag == 'date':
format_re.append(r'(?P<' + group + r'>\d+(?:-\d+(?:-\d+)?)?)')
else:
format_re.append(r'(?P<' + group + r'>[^/]*?)')
else:
format_re.append(re.escape(part))
# Optional extension
format_re.append(r'(?:\.\w+)?$')
self._format_re = re.compile("".join(format_re))
@property
def matched_tags(self):
# Return unique values, but preserve order
return list(OrderedDict.fromkeys(self._group_map.values()))
def match_file(self, filename):
match_ = self._format_re.search(filename.replace('\\', '/'))
if match_:
result = {}
for group, tag in self._group_map.items():
value = match_.group(group).strip()
if tag in self._numeric_tags:
value = value.lstrip("0")
if self.replace_underscores:
value = value.replace('_', ' ')
all_values = result.get(tag, [])
all_values.append(value)
result[tag] = all_values
return result
else:
return {}
class TagsFromFileNamesDialog(PicardDialog):
help_url = 'doc_tags_from_filenames'
def __init__(self, files, parent=None):
super().__init__(parent=parent)
self.ui = Ui_TagsFromFileNamesDialog()
self.ui.setupUi(self)
items = [
"%artist%/%album%/%title%",
"%artist%/%album%/%tracknumber% %title%",
"%artist%/%album%/%tracknumber% - %title%",
"%artist%/%album% - %tracknumber% - %title%",
"%artist% - %album%/%title%",
"%artist% - %album%/%tracknumber% %title%",
"%artist% - %album%/%tracknumber% - %title%",
]
config = get_config()
tff_format = config.persist['tags_from_filenames_format']
if tff_format not in items:
selected_index = 0
if tff_format:
items.insert(0, tff_format)
else:
selected_index = items.index(tff_format)
self.ui.format.addItems(items)
self.ui.format.setCurrentIndex(selected_index)
self.ui.buttonbox.addButton(StandardButton(StandardButton.HELP), QtWidgets.QDialogButtonBox.ButtonRole.HelpRole)
self.ui.buttonbox.addButton(StandardButton(StandardButton.OK), QtWidgets.QDialogButtonBox.ButtonRole.AcceptRole)
self.ui.buttonbox.addButton(StandardButton(StandardButton.CANCEL), QtWidgets.QDialogButtonBox.ButtonRole.RejectRole)
self.ui.buttonbox.accepted.connect(self.accept)
self.ui.buttonbox.rejected.connect(self.reject)
self.ui.buttonbox.helpRequested.connect(self.show_help)
self.ui.preview.clicked.connect(self.preview)
self.ui.files.setHeaderLabels([_("File Name")])
self.files = files
self.items = []
for file in files:
item = QtWidgets.QTreeWidgetItem(self.ui.files)
item.setText(0, os.path.basename(file.filename))
self.items.append(item)
def preview(self):
expression = TagMatchExpression(self.ui.format.currentText(), self.ui.replace_underscores.isChecked())
columns = expression.matched_tags
headers = [_("File Name")] + list(map(display_tag_name, columns))
self.ui.files.setColumnCount(len(headers))
self.ui.files.setHeaderLabels(headers)
for item, file in zip(self.items, self.files):
matches = expression.match_file(file.filename)
for i, column in enumerate(columns):
values = matches.get(column, [])
item.setText(i + 1, '; '.join(values))
self.ui.files.header().resizeSections(QtWidgets.QHeaderView.ResizeMode.ResizeToContents)
self.ui.files.header().setStretchLastSection(True)
def accept(self):
expression = TagMatchExpression(self.ui.format.currentText(), self.ui.replace_underscores.isChecked())
for file in self.files:
metadata = expression.match_file(file.filename)
file.metadata.update(metadata)
file.update()
config = get_config()
config.persist['tags_from_filenames_format'] = self.ui.format.currentText()
super().accept()
| 6,693
|
Python
|
.py
| 144
| 37.75
| 124
| 0.636642
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,988
|
statusindicator.py
|
metabrainz_picard/picard/ui/statusindicator.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2019-2023 Philipp Wolfer
# Copyright (C) 2020 Julius Michaelis
# Copyright (C) 2020-2021, 2023-2024 Laurent Monin
# Copyright (C) 2021 Gabriel Ferreira
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from picard import log
from picard.const.sys import (
IS_HAIKU,
IS_MACOS,
IS_WIN,
)
DesktopStatusIndicator = None
class ProgressStatus:
def __init__(self, files=0, albums=0, pending_files=0, pending_requests=0, progress=0):
self.files = files
self.albums = albums
self.pending_files = pending_files
self.pending_requests = pending_requests
self.progress = progress
class AbstractProgressStatusIndicator:
def __init__(self):
self._max_pending = 0
self._last_pending = 0
def update(self, progress_status):
if not self.is_available:
return
total_pending = progress_status.pending_files + progress_status.pending_requests
if total_pending == self._last_pending:
return # No changes, avoid update
previous_done = self._max_pending - self._last_pending
self._max_pending = max(self._max_pending, previous_done + total_pending)
self._last_pending = total_pending
if total_pending == 0 or self._max_pending <= 1: # No need to show progress for single item
self._max_pending = 0
self.hide_progress()
return
self.set_progress(progress_status.progress)
@property
def is_available(self):
return True
def hide_progress(self):
raise NotImplementedError
def set_progress(self, progress):
raise NotImplementedError
# FIXME: QtWinExtras got removed in Qt6
# See: https://www.qt.io/blog/qt-extras-modules-in-qt-6
# https://bugreports.qt.io/browse/QTBUG-89564
# https://bugreports.qt.io/browse/QTBUG-94008
# if IS_WIN:
# from PyQt6.QtWinExtras import QWinTaskbarButton
# class WindowsTaskbarStatusIndicator(AbstractProgressStatusIndicator):
# def __init__(self, window):
# super().__init__()
# taskbar_button = QWinTaskbarButton(window)
# taskbar_button.setWindow(window)
# self._progress = taskbar_button.progress()
# @property
# def is_available(self):
# return bool(self._progress)
# def hide_progress(self):
# self._progress.hide()
# def set_progress(self, progress):
# self._progress.setValue(int(progress * 100))
# self._progress.show()
# DesktopStatusIndicator = WindowsTaskbarStatusIndicator
if not (IS_WIN or IS_MACOS or IS_HAIKU):
QDBusConnection = None
try:
from PyQt6.QtCore import (
QObject,
pyqtSlot,
)
from PyQt6.QtDBus import (
QDBusAbstractAdaptor,
QDBusConnection,
QDBusMessage,
)
except ImportError as err:
log.warning('Failed importing PyQt6.QtDBus: %r', err)
else:
from picard import PICARD_DESKTOP_NAME
DBUS_INTERFACE = 'com.canonical.Unity.LauncherEntry'
class UnityLauncherEntryService(QObject):
def __init__(self, bus, app_id):
QObject.__init__(self)
self._bus = bus
self._app_uri = 'application://' + app_id
self._path = '/com/canonical/unity/launcherentry/1'
self._progress = 0
self._visible = False
self._dbus_adaptor = UnityLauncherEntryAdaptor(self)
self._available = bus.registerObject(self._path, self)
@property
def current_progress(self):
return {
'progress': self._progress,
'progress-visible': self._visible,
}
@property
def is_available(self):
return self._available
def update(self, progress, visible=True):
self._progress = progress
self._visible = visible
# Automatic forwarding of Qt signals does not work in this case
# since Qt cannot handle the complex "a{sv}" type.
# Create the signal message manually.
message = QDBusMessage.createSignal(self._path, DBUS_INTERFACE, 'Update')
message.setArguments([self._app_uri, self.current_progress])
self._bus.send(message)
def query(self):
return [self._app_uri, self.current_progress]
class UnityLauncherEntryAdaptor(QDBusAbstractAdaptor):
""" This provides the DBus adaptor to the outside world
The supported interface is:
<interface name="com.canonical.Unity.LauncherEntry">
<signal name="Update">
<arg direction="out" type="s" name="app_uri"/>
<arg direction="out" type="a{sv}" name="properties"/>
</signal>
<method name="Query">
<arg direction="out" type="s" name="app_uri"/>
<arg direction="out" type="a{sv}" name="properties"/>
</method>
</interface>
"""
def __init__(self, parent):
super().__init__(parent)
@pyqtSlot(name="Query", result=list)
def query(self):
return self.parent().query()
class UnityLauncherEntryStatusIndicator(AbstractProgressStatusIndicator):
def __init__(self, window):
super().__init__()
bus = QDBusConnection.sessionBus()
self._service = UnityLauncherEntryService(bus, PICARD_DESKTOP_NAME)
@property
def is_available(self):
return self._service.is_available
def hide_progress(self):
self._service.update(0, False)
def set_progress(self, progress):
self._service.update(progress)
DesktopStatusIndicator = UnityLauncherEntryStatusIndicator
| 6,890
|
Python
|
.py
| 161
| 33.459627
| 100
| 0.61215
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,989
|
playertoolbar.py
|
metabrainz_picard/picard/ui/playertoolbar.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2019 Timur Enikeev
# Copyright (C) 2019-2023 Philipp Wolfer
# Copyright (C) 2019-2024 Laurent Monin
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from collections import deque
import locale
import os
from PyQt6 import (
QtCore,
QtGui,
QtWidgets,
)
from picard import log
from picard.config import get_config
from picard.const.sys import IS_MACOS
from picard.i18n import (
N_,
gettext as _,
)
from picard.util import (
format_time,
icontheme,
iter_files_from_objects,
)
from picard.ui.widgets import (
ClickableSlider,
ElidedLabel,
SliderPopover,
)
try:
from PyQt6 import QtMultimedia
except ImportError as e:
qt_multimedia_available = False
qt_multimedia_errmsg = e.msg
else:
qt_multimedia_available = True
qt_multimedia_errmsg = None
def get_logarithmic_volume(player_value):
"""Return logarithmic scale volume to set slider position"""
return QtMultimedia.QAudio.convertVolume(
player_value,
QtMultimedia.QAudio.VolumeScale.LinearVolumeScale,
QtMultimedia.QAudio.VolumeScale.LogarithmicVolumeScale)
def get_linear_volume(slider_value):
"""Return linear scale volume from slider position"""
return QtMultimedia.QAudio.convertVolume(
slider_value,
QtMultimedia.QAudio.VolumeScale.LogarithmicVolumeScale,
QtMultimedia.QAudio.VolumeScale.LinearVolumeScale)
def get_text_width(font, text):
metrics = QtGui.QFontMetrics(font)
size = metrics.size(QtCore.Qt.TextFlag.TextSingleLine, text)
return size.width()
class Player(QtCore.QObject):
error = QtCore.pyqtSignal(object, str)
def __init__(self, parent):
super().__init__(parent)
self._player = None
self._toolbar = None
self._selected_objects = []
self._media_queue = deque()
self.is_playing = False
self.is_stopped = False
self.is_paused = False
if qt_multimedia_available:
log.debug("Internal player: QtMultimedia available, initializing QMediaPlayer")
player = QtMultimedia.QMediaPlayer(parent)
if player.isAvailable():
output = QtMultimedia.QAudioOutput()
player.setAudioOutput(output)
self.state_changed = player.playbackStateChanged
self._logarithmic_volume = get_logarithmic_volume(output.volume())
log.debug("Internal player: available, QMediaPlayer set up")
self._player = player
self._audio_output = output
self._player.playbackStateChanged.connect(self._on_playback_state_changed)
self._player.errorOccurred.connect(self._on_error)
else:
log.warning("Internal player: unavailable")
else:
log.warning("Internal player: unavailable, %s", qt_multimedia_errmsg)
@property
def available(self):
return self._player is not None
@property
def toolbar(self):
return self._toolbar
def volume(self):
return int(self._logarithmic_volume * 100)
def playback_rate(self):
return self._player.playbackRate()
def create_toolbar(self):
self._toolbar = PlayerToolbar(self, parent=self.parent())
return self._toolbar
def set_objects(self, objects):
self._selected_objects = objects
self._toolbar.play_action.setEnabled(bool(objects))
def play(self):
"""Play selected tracks with an internal player"""
self._media_queue = deque(
QtCore.QUrl.fromLocalFile(file.filename)
for file in iter_files_from_objects(self._selected_objects)
)
self._play_next()
def _play_next(self):
try:
next_track = self._media_queue.popleft()
self._player.setSource(next_track)
self._player.play()
except IndexError:
self._player.stop()
def _on_playback_state_changed(self, state):
self.is_stopped = state == QtMultimedia.QMediaPlayer.PlaybackState.StoppedState
self.is_playing = state == QtMultimedia.QMediaPlayer.PlaybackState.PlayingState
self.is_paused = state == QtMultimedia.QMediaPlayer.PlaybackState.PausedState
if self.is_stopped:
self._play_next()
def pause(self, is_paused):
"""Toggle pause of an internal player"""
if is_paused:
self._player.pause()
else:
self._player.play()
def set_volume(self, logarithmic_volume):
"""Convert to linear scale and set the volume
The value must be given in logarithmic scale as a value between 0 and 100.
"""
self._logarithmic_volume = logarithmic_volume / 100.
linear_volume = get_linear_volume(self._logarithmic_volume)
log.debug('Internal player: Set volume %f -> linear %f', logarithmic_volume, linear_volume)
self._audio_output.setVolume(linear_volume)
def set_position(self, position):
self._player.setPosition(position)
def set_playback_rate(self, playback_rate):
player = self._player
player.setPlaybackRate(playback_rate)
if not IS_MACOS:
# Playback rate changes do not affect the current media playback on
# Linux and does work unreliable on Windows.
# Force playback restart to have the rate change applied immediately.
player_state = player.playbackState()
if player_state != QtMultimedia.QMediaPlayer.PlaybackState.StoppedState:
position = player.position()
player.stop()
player.setPosition(position)
if player_state == QtMultimedia.QMediaPlayer.PlaybackState.PlayingState:
player.play()
elif player_state == QtMultimedia.QMediaPlayer.PlaybackState.PausedState:
player.pause()
def _on_error(self, error):
if error == QtMultimedia.QMediaPlayer.Error.FormatError:
msg = _("Internal player: The format of a media resource isn't (fully) supported")
elif error == QtMultimedia.QMediaPlayer.Error.AccessDeniedError:
msg = _("Internal player: There are not the appropriate permissions to play a media resource")
else:
msg = _("Internal player: %(error)s, %(message)s") % {
'error': error,
'message': self._player.errorString(),
}
self.error.emit(error, msg)
class PlayerToolbar(QtWidgets.QToolBar):
def __init__(self, player, parent=None):
super().__init__(_("Player"), parent=parent)
self.setObjectName('player_toolbar')
self.setAllowedAreas(QtCore.Qt.ToolBarArea.TopToolBarArea
| QtCore.Qt.ToolBarArea.BottomToolBarArea
| QtCore.Qt.ToolBarArea.NoToolBarArea)
self.player = player
self.player.state_changed.connect(self.playback_state_changed)
self.play_action = QtGui.QAction(icontheme.lookup('play'), _("Play"), self)
play_tip = _("Play selected files")
self.play_action.setToolTip(play_tip)
self.play_action.setStatusTip(play_tip)
self.play_action.setEnabled(False)
self.play_action.triggered.connect(self.play)
self.pause_action = QtGui.QAction(icontheme.lookup('pause'), _("Pause"), self)
pause_tip = _("Pause or resume current playback")
self.pause_action.setToolTip(pause_tip)
self.pause_action.setStatusTip(pause_tip)
self.pause_action.setCheckable(True)
self.pause_action.setChecked(False)
self.pause_action.setEnabled(False)
self.pause_action.toggled.connect(self.pause)
self._add_toolbar_action(self.play_action)
self._add_toolbar_action(self.pause_action)
self.progress_widget = PlaybackProgressSlider(self.player, parent=self)
self.addWidget(self.progress_widget)
config = get_config()
volume = config.persist['mediaplayer_volume']
self.player.set_volume(volume)
self.volume_button = VolumeControlButton(volume, parent=self)
self.volume_button.volume_changed.connect(self.player.set_volume)
self.volume_button.setToolButtonStyle(self.toolButtonStyle())
self.addWidget(self.volume_button)
playback_rate = config.persist['mediaplayer_playback_rate']
self.player.set_playback_rate(playback_rate)
self.playback_rate_button = PlaybackRateButton(playback_rate, parent=self)
self.playback_rate_button.playback_rate_changed.connect(self.player.set_playback_rate)
self.playback_rate_button.setToolButtonStyle(self.toolButtonStyle())
self.addWidget(self.playback_rate_button)
def playback_state_changed(self, state):
self.pause_action.setEnabled(self.player.is_playing or self.player.is_paused)
def _add_toolbar_action(self, action):
self.addAction(action)
widget = self.widgetForAction(action)
widget.setFocusPolicy(QtCore.Qt.FocusPolicy.TabFocus)
widget.setAttribute(QtCore.Qt.WidgetAttribute.WA_MacShowFocusRect)
def pause(self, checked):
if self.player.is_playing or self.player.is_paused:
self.player.pause(checked)
def play(self):
self.player.play()
self.pause_action.setChecked(False)
def setToolButtonStyle(self, style):
super().setToolButtonStyle(style)
self.playback_rate_button.setToolButtonStyle(style)
self.volume_button.setToolButtonStyle(style)
def showEvent(self, event):
super().showEvent(event)
self._update_popover_position()
def _update_popover_position(self):
popover_position = self._get_popover_position()
self.playback_rate_button.popover_position = popover_position
self.volume_button.popover_position = popover_position
def _get_popover_position(self):
if self.isFloating():
return 'bottom'
pos = self.mapToParent(QtCore.QPoint(0, 0))
half_main_window_height = self.parent().height() / 2
if pos.y() <= half_main_window_height:
return 'bottom'
else:
return 'top'
class PlaybackProgressSlider(QtWidgets.QWidget):
def __init__(self, player, parent=None):
super().__init__(parent=parent)
self.player = player
self._position_update = False
tool_font = QtWidgets.QApplication.font('QToolButton')
self.progress_slider = ClickableSlider(parent=self)
self.progress_slider.setOrientation(QtCore.Qt.Orientation.Horizontal)
self.progress_slider.setEnabled(False)
self.progress_slider.setMinimumWidth(30)
self.progress_slider.setSingleStep(1000)
self.progress_slider.setPageStep(3000)
self.progress_slider.valueChanged.connect(self.on_value_changed)
self.media_name_label = ElidedLabel(self)
self.media_name_label.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)
self.media_name_label.setFont(tool_font)
slider_container = QtWidgets.QWidget(parent=self)
hbox = QtWidgets.QHBoxLayout(slider_container)
hbox.setContentsMargins(0, 0, 0, 0)
self.position_label = QtWidgets.QLabel("0:00", self)
self.duration_label = QtWidgets.QLabel(format_time(0), self)
min_duration_width = get_text_width(self.position_label.font(), "8:88")
self.position_label.setMinimumWidth(min_duration_width)
self.duration_label.setMinimumWidth(min_duration_width)
self.position_label.setFont(tool_font)
self.duration_label.setFont(tool_font)
hbox.addWidget(self.position_label)
hbox.addWidget(self.progress_slider)
hbox.addWidget(self.duration_label)
vbox = QtWidgets.QVBoxLayout(self)
vbox.setSpacing(0)
vbox.addWidget(slider_container)
vbox.addWidget(self.media_name_label)
self.player._player.durationChanged.connect(self.on_duration_changed)
self.player._player.positionChanged.connect(self.on_position_changed)
self.player._player.sourceChanged.connect(self.on_media_changed)
def on_duration_changed(self, duration):
self.progress_slider.setMaximum(duration)
self.duration_label.setText(format_time(duration))
def on_position_changed(self, position):
self._position_update = True
self.progress_slider.setValue(position)
self._position_update = False
self.position_label.setText(format_time(position, display_zero=True))
def on_media_changed(self, media):
if media.isEmpty():
self.progress_slider.setEnabled(False)
else:
url = media.toString()
self.media_name_label.setText(os.path.basename(url))
self.progress_slider.setEnabled(True)
def on_value_changed(self, value):
if not self._position_update: # Avoid circular events
self.player.set_position(value)
class PlaybackRateButton(QtWidgets.QToolButton):
playback_rate_changed = QtCore.pyqtSignal(float)
multiplier = 10.0
def __init__(self, playback_rate, parent=None):
super().__init__(parent=parent)
self.popover_position = 'bottom'
self.rate_fmt = N_("%1.1f ×")
button_margin = self.style().pixelMetric(QtWidgets.QStyle.PixelMetric.PM_ButtonMargin)
min_width = get_text_width(self.font(), _(self.rate_fmt) % 8.8)
self.setMinimumWidth(min_width + (2 * button_margin) + 2)
self.set_playback_rate(playback_rate)
self.clicked.connect(self.show_popover)
tooltip = _("Change playback speed")
self.setToolTip(tooltip)
self.setStatusTip(tooltip)
def show_popover(self):
slider_value = self.playback_rate * self.multiplier
popover = SliderPopover(
self, self.popover_position, _("Playback speed"), slider_value)
# In 0.1 steps from 0.5 to 1.5
popover.slider.setMinimum(5)
popover.slider.setMaximum(15)
popover.slider.setSingleStep(1)
popover.slider.setPageStep(1)
popover.slider.setTickInterval(1)
popover.slider.setTickPosition(QtWidgets.QSlider.TickPosition.TicksBelow)
popover.value_changed.connect(self.on_slider_value_changed)
popover.show()
def on_slider_value_changed(self, value):
playback_rate = value / self.multiplier
self.set_playback_rate(playback_rate)
self.playback_rate_changed.emit(self.playback_rate)
def set_playback_rate(self, playback_rate):
self.playback_rate = playback_rate
label = locale.format_string(_(self.rate_fmt), playback_rate)
self.setText(label)
def wheelEvent(self, event):
delta = event.angleDelta().y()
# Incrementing repeatedly in 0.1 steps would cause floating point
# rounding issues. Do the calculation in whole numbers to prevent this.
new_rate = int(self.playback_rate * 10)
if delta > 0:
new_rate += 1
elif delta < 0:
new_rate -= 1
new_rate = min(max(new_rate, 5), 15) / 10.0
if new_rate != self.playback_rate:
self.set_playback_rate(new_rate)
self.playback_rate_changed.emit(new_rate)
class VolumeControlButton(QtWidgets.QToolButton):
volume_changed = QtCore.pyqtSignal(int)
def __init__(self, volume, parent=None):
super().__init__(parent=parent)
self.popover_position = 'bottom'
self.step = 3
self.volume_fmt = N_("%d%%")
self.set_volume(volume)
button_margin = self.style().pixelMetric(QtWidgets.QStyle.PixelMetric.PM_ButtonMargin)
min_width = get_text_width(self.font(), _(self.volume_fmt) % 888)
self.setMinimumWidth(min_width + (2 * button_margin) + 2)
self.clicked.connect(self.show_popover)
tooltip = _("Change audio volume")
self.setToolTip(tooltip)
self.setStatusTip(tooltip)
def show_popover(self):
popover = SliderPopover(
self, self.popover_position, _("Audio volume"), self.volume)
popover.slider.setMinimum(0)
popover.slider.setMaximum(100)
popover.slider.setPageStep(self.step)
popover.value_changed.connect(self.on_slider_value_changed)
popover.show()
def on_slider_value_changed(self, value):
self.set_volume(value)
self.volume_changed.emit(self.volume)
def set_volume(self, volume):
self.volume = volume
label = _(self.volume_fmt) % volume
self.setText(label)
self.update_icon()
def update_icon(self):
if self.volume == 0:
icon = 'speaker-0'
elif self.volume <= 33:
icon = 'speaker-33'
elif self.volume <= 66:
icon = 'speaker-66'
else:
icon = 'speaker-100'
icon = icontheme.lookup(icon)
self.setIcon(icon)
def wheelEvent(self, event):
delta = event.angleDelta().y()
volume = self.volume
if delta > 0:
volume += self.step
elif delta < 0:
volume -= self.step
volume = min(max(volume, 0), 100)
if volume != self.volume:
self.set_volume(volume)
self.volume_changed.emit(volume)
| 18,125
|
Python
|
.py
| 406
| 36.17734
| 106
| 0.669349
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,990
|
tablebaseddialog.py
|
metabrainz_picard/picard/ui/tablebaseddialog.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2016 Rahul Raturi
# Copyright (C) 2018, 2021-2024 Laurent Monin
# Copyright (C) 2019, 2021-2022 Philipp Wolfer
# Copyright (C) 2020 Ray Bouchard
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""
This can be used for basic dialogs that mostly contain a table as its core feature
"""
from abc import abstractmethod
from collections import OrderedDict
from PyQt6 import (
QtCore,
QtGui,
QtWidgets,
)
from PyQt6.QtCore import pyqtSignal
from picard import log
from picard.config import get_config
from picard.i18n import sort_key
from picard.util import (
restore_method,
throttle,
)
from picard.ui import PicardDialog
from picard.ui.colors import interface_colors
class ResultTable(QtWidgets.QTableWidget):
def __init__(self, parent=None, parent_dialog=None):
super().__init__(parent=parent)
self.parent_dialog = parent_dialog
self.setSelectionMode(QtWidgets.QAbstractItemView.SelectionMode.ExtendedSelection)
self.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectionBehavior.SelectRows)
self.setEditTriggers(QtWidgets.QAbstractItemView.EditTrigger.NoEditTriggers)
self.horizontalHeader().setStretchLastSection(True)
self.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.ResizeMode.Stretch)
self.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.ResizeMode.Interactive)
self.horizontalScrollBar().valueChanged.connect(self.emit_scrolled)
self.verticalScrollBar().valueChanged.connect(self.emit_scrolled)
self.setHorizontalScrollMode(QtWidgets.QAbstractItemView.ScrollMode.ScrollPerPixel)
def prepare(self, headers):
self.clear()
self.setColumnCount(len(headers))
self.setHorizontalHeaderLabels(headers)
self.setRowCount(0)
self.setSortingEnabled(False)
@throttle(1000) # only emit scrolled signal once per second
def emit_scrolled(self, value):
if self.parent_dialog:
self.parent_dialog.scrolled.emit()
@throttle(1000) # only emit resized signal once per second
def emit_resized(self):
if self.parent_dialog:
self.parent_dialog.resized.emit()
def resizeEvent(self, event):
self.emit_resized()
super().resizeEvent(event)
class SortableTableWidgetItem(QtWidgets.QTableWidgetItem):
def __init__(self, sort_key):
super().__init__()
self.sort_key = sort_key
def __lt__(self, other):
return self.sort_key < other.sort_key
class TableBasedDialog(PicardDialog):
defaultsize = QtCore.QSize(720, 360)
scrolled = pyqtSignal()
resized = pyqtSignal()
def __init__(self, parent):
super().__init__(parent=parent)
self.setupUi()
self.columns = None # self.columns has to be an ordered dict, with column name as keys, and matching label as values
self.sorting_enabled = True
self.create_table()
self.finished.connect(self.save_state)
@property
def columns(self):
return self.__columns
@columns.setter
def columns(self, list_of_tuples):
if not list_of_tuples:
list_of_tuples = []
self.__columns = OrderedDict(list_of_tuples)
self.__colkeys = list(self.columns.keys())
@property
def table_headers(self):
return list(self.columns.values())
def colpos(self, colname):
return self.__colkeys.index(colname)
@abstractmethod
def get_value_for_row_id(self, row, value):
pass
def set_table_item(self, row, colname, obj, key, sortkey=None):
value = obj.get(key, "")
self.set_table_item_val(row, colname, value, sortkey)
def set_table_item_val(self, row, colname, value, sortkey=None):
# QVariant remembers the original type of the data
# matching comparison operator will be used when sorting
# get() will return a string, force conversion if asked to
if sortkey is None:
sortkey = sort_key(value, numeric=True)
item = SortableTableWidgetItem(sortkey)
item.setData(QtCore.Qt.ItemDataRole.DisplayRole, value)
pos = self.colpos(colname)
if pos == 0:
id = self.get_value_for_row_id(row, value)
item.setData(QtCore.Qt.ItemDataRole.UserRole, id)
self.table.setItem(row, pos, item)
@abstractmethod
def setupUi(self):
pass
def add_widget_to_center_layout(self, widget):
"""Update center widget with new child. If child widget exists,
schedule it for deletion."""
widget_item = self.center_layout.takeAt(0)
if widget_item:
current_widget = widget_item.widget()
current_widget.hide()
self.center_layout.removeWidget(current_widget)
if current_widget != self.table:
current_widget.deleteLater()
self.center_layout.addWidget(widget)
widget.show()
def create_table_obj(self):
return ResultTable(parent_dialog=self)
def create_table(self):
self.table = self.create_table_obj()
self.table.verticalHeader().setDefaultSectionSize(100)
self.table.setSortingEnabled(False)
self.table.cellDoubleClicked.connect(self.accept)
self.table.hide()
def enable_accept_button():
self.accept_button.setEnabled(True)
self.table.itemSelectionChanged.connect(enable_accept_button)
def highlight_row(self, row):
model = self.table.model()
highlight_color = interface_colors.get_qcolor('row_highlight')
highlight_brush = QtGui.QBrush(highlight_color)
for column in range(0, model.columnCount()):
index = model.index(row, column)
model.setData(index, highlight_brush, QtCore.Qt.ItemDataRole.BackgroundRole)
def prepare_table(self):
self.table.prepare(self.table_headers)
self.restore_table_header_state()
def show_table(self, sort_column=None, sort_order=QtCore.Qt.SortOrder.DescendingOrder):
self.add_widget_to_center_layout(self.table)
self.table.horizontalHeader().setSortIndicatorShown(self.sorting_enabled)
self.table.setSortingEnabled(self.sorting_enabled)
if self.sorting_enabled and sort_column:
self.table.sortItems(self.colpos(sort_column), sort_order)
self.table.resizeColumnsToContents()
self.table.resizeRowsToContents()
self.table.setAlternatingRowColors(True)
def accept(self):
if self.table:
selected_rows_user_values = []
for idx in self.table.selectionModel().selectedRows():
row = self.table.itemFromIndex(idx).data(QtCore.Qt.ItemDataRole.UserRole)
selected_rows_user_values .append(row)
self.accept_event(selected_rows_user_values)
super().accept()
@restore_method
def restore_table_header_state(self):
header = self.table.horizontalHeader()
config = get_config()
state = config.persist[self.dialog_header_state]
if state:
header.restoreState(state)
header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeMode.Interactive)
log.debug("restore_state: %s", self.dialog_header_state)
def save_state(self):
if self.table:
self.save_table_header_state()
def save_table_header_state(self):
state = self.table.horizontalHeader().saveState()
config = get_config()
config.persist[self.dialog_header_state] = state
log.debug("save_state: %s", self.dialog_header_state)
| 8,391
|
Python
|
.py
| 192
| 36.505208
| 125
| 0.695599
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,991
|
logview.py
|
metabrainz_picard/picard/ui/logview.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2007 Lukáš Lalinský
# Copyright (C) 2008-2009, 2019-2023 Philipp Wolfer
# Copyright (C) 2012-2013 Michael Wiencek
# Copyright (C) 2013-2014, 2018-2024 Laurent Monin
# Copyright (C) 2014 Sophist-UK
# Copyright (C) 2016, 2018 Sambhav Kothari
# Copyright (C) 2018 Wieland Hoffmann
# Copyright (C) 2021 Gabriel Ferreira
# Copyright (C) 2022 Kamil
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from functools import partial
import logging
import os
import re
from PyQt6 import (
QtCore,
QtGui,
QtWidgets,
)
from picard import log
from picard.config import get_config
from picard.debug_opts import DebugOpt
from picard.i18n import gettext as _
from picard.util import (
reconnect,
wildcards_to_regex_pattern,
)
from picard.ui import (
FONT_FAMILY_MONOSPACE,
PicardDialog,
)
from picard.ui.colors import interface_colors
from picard.ui.util import FileDialog
class LogViewDialog(PicardDialog):
defaultsize = QtCore.QSize(570, 400)
def __init__(self, title, parent=None):
super().__init__(parent=parent)
self.setWindowFlags(QtCore.Qt.WindowType.Window)
self.setWindowTitle(title)
self.doc = QtGui.QTextDocument()
self.textCursor = QtGui.QTextCursor(self.doc)
self.browser = QtWidgets.QTextBrowser()
self.browser.setDocument(self.doc)
self.vbox = QtWidgets.QVBoxLayout()
self.setLayout(self.vbox)
self.vbox.addWidget(self.browser)
class LogViewCommon(LogViewDialog):
def __init__(self, log_tail, title, parent=None):
super().__init__(title, parent=parent)
self.displaying = False
self.log_tail = log_tail
self._init_doc()
def _init_doc(self):
self.prev = -1
self.doc.clear()
self.textCursor.movePosition(QtGui.QTextCursor.MoveOperation.Start)
def closeEvent(self, event):
self.save_geometry()
event.ignore()
self.hide()
def hideEvent(self, event):
reconnect(self.log_tail.updated, None)
super().hideEvent(event)
def showEvent(self, event):
self.display()
reconnect(self.log_tail.updated, self._updated)
super().showEvent(event)
def _updated(self):
if self.displaying:
return
self.display()
def display(self, clear=False):
self.displaying = True
if clear:
self._init_doc()
for logitem in self.log_tail.contents(self.prev):
self._add_entry(logitem)
self.prev = logitem.pos
self.displaying = False
def _add_entry(self, logitem):
self.textCursor.movePosition(QtGui.QTextCursor.MoveOperation.End)
self.textCursor.insertText(logitem.message)
self.textCursor.insertBlock()
sb = self.browser.verticalScrollBar()
sb.setValue(sb.maximum())
def clear(self):
self.log_tail.clear()
self.display(clear=True)
class Highlighter(QtGui.QSyntaxHighlighter):
def __init__(self, string, parent):
super().__init__(parent)
self.fmt = QtGui.QTextCharFormat()
self.fmt.setBackground(QtCore.Qt.GlobalColor.lightGray)
self.reg = re.compile(wildcards_to_regex_pattern(string), re.IGNORECASE)
def highlightBlock(self, text):
for match in self.reg.finditer(text):
index = match.start()
length = match.end() - match.start()
self.setFormat(index, length, self.fmt)
class VerbosityMenu(QtWidgets.QMenu):
verbosity_changed = QtCore.pyqtSignal(int)
def __init__(self, parent=None):
super().__init__(parent=parent)
self.action_group = QtGui.QActionGroup(self)
self.actions = {}
for level, feat in log.levels_features.items():
action = QtGui.QAction(_(feat.name), self)
action.setCheckable(True)
action.triggered.connect(partial(self.verbosity_changed.emit, level))
self.action_group.addAction(action)
self.addAction(action)
self.actions[level] = action
def set_verbosity(self, level):
self.actions[level].setChecked(True)
class DebugOptsMenu(QtWidgets.QMenu):
def __init__(self, parent=None):
super().__init__(parent=parent)
self.actions = {}
for debug_opt in DebugOpt:
action = QtGui.QAction(_(debug_opt.title), self, checkable=True, checked=debug_opt.enabled)
action.setToolTip(_(debug_opt.description))
action.triggered.connect(partial(self.debug_opt_changed, debug_opt))
self.addAction(action)
self.actions[debug_opt] = action
def debug_opt_changed(self, debug_opt, checked):
debug_opt.enabled = checked
class LogView(LogViewCommon):
def __init__(self, parent=None):
super().__init__(log.main_tail, _("Log"), parent=parent)
self.verbosity = log.get_effective_level()
self._setup_formats()
self.hl_text = ''
self.hl = None
self.hbox = QtWidgets.QHBoxLayout()
self.vbox.addLayout(self.hbox)
self.verbosity_menu_button = QtWidgets.QPushButton()
self.verbosity_menu_button.setAccessibleName(_("Verbosity"))
self.hbox.addWidget(self.verbosity_menu_button)
self.verbosity_menu = VerbosityMenu()
self.verbosity_menu.verbosity_changed.connect(self._verbosity_changed)
self.verbosity_menu_button.setMenu(self.verbosity_menu)
self.debug_opts_menu_button = QtWidgets.QPushButton(_("Debug Options"))
self.debug_opts_menu_button.setAccessibleName(_("Debug Options"))
self.hbox.addWidget(self.debug_opts_menu_button)
self.debug_opts_menu = DebugOptsMenu()
self.debug_opts_menu_button.setMenu(self.debug_opts_menu)
self._set_verbosity(self.verbosity)
# highlight input
self.highlight_text = QtWidgets.QLineEdit()
self.highlight_text.setPlaceholderText(_("String to highlight"))
self.highlight_text.textEdited.connect(self._highlight_text_edited)
self.hbox.addWidget(self.highlight_text)
# highlight button
self.highlight_button = QtWidgets.QPushButton(_("Highlight"))
self.hbox.addWidget(self.highlight_button)
self.highlight_button.setDefault(True)
self.highlight_button.setEnabled(False)
self.highlight_button.clicked.connect(self._highlight_do)
self.highlight_text.returnPressed.connect(self.highlight_button.click)
# clear highlight button
self.clear_highlight_button = QtWidgets.QPushButton(_("Clear Highlight"))
self.hbox.addWidget(self.clear_highlight_button)
self.clear_highlight_button.setEnabled(False)
self.clear_highlight_button.clicked.connect(self._clear_highlight_do)
# clear log
self.clear_log_button = QtWidgets.QPushButton(_("Clear Log"))
self.hbox.addWidget(self.clear_log_button)
self.clear_log_button.clicked.connect(self._clear_log_do)
# save as
self.save_log_as_button = QtWidgets.QPushButton(_("Save As…"))
self.hbox.addWidget(self.save_log_as_button)
self.save_log_as_button.clicked.connect(self._save_log_as_do)
self._prev_logitem_level = logging.NOTSET
def _clear_highlight_do(self):
self.highlight_text.setText('')
self.highlight_button.setEnabled(False)
self._highlight_do()
def _highlight_text_edited(self, text):
if text and self.hl_text != text:
self.highlight_button.setEnabled(True)
else:
self.highlight_button.setEnabled(False)
if not text:
self.clear_highlight_button.setEnabled(bool(self.hl))
def _highlight_do(self):
new_hl_text = self.highlight_text.text()
if new_hl_text != self.hl_text:
self.hl_text = new_hl_text
if self.hl is not None:
self.hl.setDocument(None)
self.hl = None
if self.hl_text:
self.hl = Highlighter(self.hl_text, self.doc)
self.clear_highlight_button.setEnabled(bool(self.hl))
def _setup_formats(self):
interface_colors.load_from_config()
self.formats = {}
for level, feat in log.levels_features.items():
text_fmt = QtGui.QTextCharFormat()
text_fmt.setFontFamilies([FONT_FAMILY_MONOSPACE])
text_fmt.setForeground(interface_colors.get_qcolor(feat.color_key))
self.formats[level] = text_fmt
def _format(self, level):
return self.formats[level]
def _save_log_as_do(self):
path, ok = FileDialog.getSaveFileName(
parent=self,
caption=_("Save Log View to File"),
options=QtWidgets.QFileDialog.Option.DontConfirmOverwrite,
)
if ok and path:
if os.path.isfile(path):
reply = QtWidgets.QMessageBox.question(
self,
_("Save Log View to File"),
_("File already exists, do you really want to save to this file?"),
QtWidgets.QMessageBox.StandardButton.Yes | QtWidgets.QMessageBox.StandardButton.No
)
if reply != QtWidgets.QMessageBox.StandardButton.Yes:
return
writer = QtGui.QTextDocumentWriter(path)
writer.setFormat(b'plaintext')
success = writer.write(self.doc)
if not success:
QtWidgets.QMessageBox.critical(
self,
_("Failed to save Log View to file"),
_("Something prevented data to be written to '%s'") % writer.fileName()
)
def show(self):
self.highlight_text.setFocus(QtCore.Qt.FocusReason.OtherFocusReason)
super().show()
def display(self, clear=False):
if clear:
self._prev_logitem_level = logging.NOTSET
super().display(clear=clear)
def _clear_log_do(self):
reply = QtWidgets.QMessageBox.question(
self,
_("Clear Log"),
_("Are you sure you want to clear the log?"),
QtWidgets.QMessageBox.StandardButton.Yes | QtWidgets.QMessageBox.StandardButton.No
)
if reply != QtWidgets.QMessageBox.StandardButton.Yes:
return
self.log_tail.clear()
self.display(clear=True)
def is_shown(self, logitem):
return logitem.level >= self.verbosity
def _add_entry(self, logitem):
if not self.is_shown(logitem):
return
if self._prev_logitem_level != logitem.level:
self.textCursor.setBlockCharFormat(self._format(logitem.level))
self._prev_logitem_level = logitem.level
super()._add_entry(logitem)
def _set_verbosity(self, level):
self.verbosity = level
self.verbosity_menu.set_verbosity(self.verbosity)
self._update_verbosity_label()
def _verbosity_changed(self, level):
if level != self.verbosity:
config = get_config()
config.setting['log_verbosity'] = level
self.verbosity = level
self._update_verbosity_label()
tagger = QtCore.QCoreApplication.instance()
tagger.set_log_level(level)
self.display(clear=True)
def _update_verbosity_label(self):
feat = log.levels_features.get(self.verbosity)
label = _(feat.name) if feat else _("Verbosity")
self.verbosity_menu_button.setText(label)
self.debug_opts_menu_button.setEnabled(self.verbosity == logging.DEBUG)
class HistoryView(LogViewCommon):
def __init__(self, parent=None):
super().__init__(log.history_tail, _("Activity History"), parent=parent)
| 12,564
|
Python
|
.py
| 294
| 34.139456
| 103
| 0.654423
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,992
|
__init__.py
|
metabrainz_picard/picard/ui/__init__.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2006-2008 Lukáš Lalinský
# Copyright (C) 2014 Sophist-UK
# Copyright (C) 2014, 2018, 2020-2024 Laurent Monin
# Copyright (C) 2016-2018 Sambhav Kothari
# Copyright (C) 2018 Vishal Choudhary
# Copyright (C) 2019-2023 Philipp Wolfer
# Copyright (C) 2021 Bob Swift
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import uuid
from PyQt6 import (
QtCore,
QtGui,
QtWidgets,
)
from picard import log
from picard.config import (
Option,
get_config,
)
from picard.const import DOCS_BASE_URL
from picard.const.sys import (
IS_HAIKU,
IS_MACOS,
IS_WIN,
)
from picard.util import (
restore_method,
webbrowser2,
)
if IS_MACOS:
FONT_FAMILY_MONOSPACE = 'Menlo'
elif IS_WIN:
FONT_FAMILY_MONOSPACE = 'Consolas'
elif IS_HAIKU:
FONT_FAMILY_MONOSPACE = 'Noto Sans Mono'
else:
FONT_FAMILY_MONOSPACE = 'Monospace'
class PreserveGeometry:
defaultsize = None
def __init__(self, *args, **kwargs):
Option.add_if_missing('persist', self.opt_name(), QtCore.QByteArray())
Option.add_if_missing('persist', self.splitters_name(), {})
if getattr(self, 'finished', None):
self.finished.connect(self.save_geometry)
def opt_name(self):
return 'geometry_' + self.__class__.__name__
def splitters_name(self):
return 'splitters_' + self.__class__.__name__
def _get_lineage(self, widget):
"""Try to develop a unique lineage / ancestry to identify the specified widget.
Args:
widget (QtWidget): Widget to process.
Returns:
generator: full ancestry for the specified widget.
"""
parent = widget.parent()
if parent:
yield from self._get_lineage(parent)
yield widget.objectName() if widget.objectName() else widget.__class__.__name__
def _get_name(self, widget):
"""Return the name of the widget.
Args:
widget (QtWidget): Widget to process.
Returns:
str: The name of the widget or the lineage if there is no name assigned.
"""
name = widget.objectName()
if not name:
name = '.'.join(self._get_lineage(widget))
log.debug("Splitter does not have objectName(): %s", name)
return name
@property
def _get_splitters(self):
try:
return {
self._get_name(splitter): splitter
for splitter in self.findChildren(QtWidgets.QSplitter)
}
except AttributeError:
return {}
@restore_method
def restore_geometry(self):
config = get_config()
geometry = config.persist[self.opt_name()]
if not geometry.isNull():
self.restoreGeometry(geometry)
elif self.defaultsize:
self.resize(self.defaultsize)
splitters = config.persist[self.splitters_name()]
seen = set()
for name, splitter in self._get_splitters.items():
if name in splitters:
splitter.restoreState(splitters[name])
seen.add(name)
# remove unused saved states that don't match any existing splitter names
for name in set(splitters) - seen:
del config.persist[self.splitters_name()][name]
def save_geometry(self):
config = get_config()
config.persist[self.opt_name()] = self.saveGeometry()
config.persist[self.splitters_name()] = {
name: bytearray(splitter.saveState())
for name, splitter in self._get_splitters.items()
}
class SingletonDialog:
_instance = None
@classmethod
def get_instance(cls, *args, **kwargs):
if not cls._instance:
cls._instance = cls(*args, **kwargs)
cls._instance.destroyed.connect(cls._on_dialog_destroyed)
return cls._instance
@classmethod
def show_instance(cls, *args, **kwargs):
instance = cls.get_instance(*args, **kwargs)
# Get the current parent
if hasattr(instance, 'parent'):
if callable(instance.parent):
parent = instance.parent()
else:
parent = instance.parent
else:
parent = None
# Update parent if changed
if 'parent' in kwargs and parent != kwargs['parent']:
instance.setParent(kwargs['parent'])
instance.show()
instance.raise_()
instance.activateWindow()
return instance
@classmethod
def _on_dialog_destroyed(cls):
cls._instance = None
class PicardDialog(QtWidgets.QDialog, PreserveGeometry):
help_url = None
flags = QtCore.Qt.WindowType.WindowSystemMenuHint | QtCore.Qt.WindowType.WindowTitleHint | QtCore.Qt.WindowType.WindowCloseButtonHint
ready_for_display = QtCore.pyqtSignal()
def __init__(self, parent=None):
super().__init__(parent=parent, f=self.flags)
self.tagger = QtCore.QCoreApplication.instance()
self.__shown = False
self.ready_for_display.connect(self.restore_geometry)
def keyPressEvent(self, event):
if event.matches(QtGui.QKeySequence.StandardKey.Close):
self.close()
elif event.matches(QtGui.QKeySequence.StandardKey.HelpContents) and self.help_url:
self.show_help()
else:
super().keyPressEvent(event)
def showEvent(self, event):
if not self.__shown:
self.ready_for_display.emit()
self.__shown = True
return super().showEvent(event)
def show_help(self):
if self.help_url:
url = self.help_url
if url.startswith('/'):
url = DOCS_BASE_URL + url
webbrowser2.open(url)
# With py3, QObjects are no longer hashable unless they have
# an explicit __hash__ implemented.
# See: http://python.6.x6.nabble.com/QTreeWidgetItem-is-not-hashable-in-Py3-td5212216.html
class HashableItem:
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.__id = uuid.uuid4()
self.__hash = hash(self.__id)
def __eq__(self, other):
return self.__id == other.__id
def __hash__(self):
return self.__hash
class HashableTreeWidgetItem(HashableItem, QtWidgets.QTreeWidgetItem):
pass
class HashableListWidgetItem(HashableItem, QtWidgets.QListWidgetItem):
pass
| 7,144
|
Python
|
.py
| 193
| 29.803109
| 137
| 0.646352
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,993
|
newuserdialog.py
|
metabrainz_picard/picard/ui/newuserdialog.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2022-2023 Philipp Wolfer
# Copyright (C) 2023 Bob Swift
# Copyright (C) 2024 Laurent Monin
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from PyQt6 import (
QtCore,
QtWidgets,
)
from picard.const import PICARD_URLS
from picard.i18n import gettext as _
class NewUserDialog():
def __init__(self, parent):
dialog_text = _(
"<p>"
"<strong>Changes made by Picard are not reversible.</strong>"
"</p><p>"
"Picard is a very flexible music tagging tool which can rename your files and overwrite the tags. "
"We <strong>strongly recommend</strong> that you:"
"</p><ul>"
"<li>read the <a href='{documentation_url}'>User Guide</a> (also available from the Help menu)</li>"
"<li>test with copies of your music and work in small batches</li>"
"</ul><p>"
"Picard is open source software written by volunteers. It is provided as-is and with no warranty."
"</p>"
).format(documentation_url=PICARD_URLS['documentation_server'])
self.show_again = True
show_again_text = _("Show this message again the next time you start Picard.")
self.msg = QtWidgets.QMessageBox(parent)
self.msg.setIcon(QtWidgets.QMessageBox.Icon.Warning)
self.msg.setText(dialog_text)
self.msg.setWindowTitle(_("New User Warning"))
self.msg.setWindowModality(QtCore.Qt.WindowModality.ApplicationModal)
self.cb = QtWidgets.QCheckBox(show_again_text)
self.cb.setChecked(self.show_again)
self.cb.toggled.connect(self._set_state)
self.msg.setCheckBox(self.cb)
self.msg.setStandardButtons(QtWidgets.QMessageBox.StandardButton.Ok)
def _set_state(self):
self.show_again = not self.show_again
def show(self):
self.msg.exec()
return self.show_again
| 2,646
|
Python
|
.py
| 59
| 38.745763
| 112
| 0.688423
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,994
|
edittagdialog.py
|
metabrainz_picard/picard/ui/edittagdialog.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2011-2014 Michael Wiencek
# Copyright (C) 2014 Sophist-UK
# Copyright (C) 2016-2017 Sambhav Kothari
# Copyright (C) 2017 Wieland Hoffmann
# Copyright (C) 2017-2018, 2020-2024 Laurent Monin
# Copyright (C) 2018 Vishal Choudhary
# Copyright (C) 2019-2022 Philipp Wolfer
# Copyright (C) 2023 certuna
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from PyQt6 import (
QtCore,
QtGui,
QtWidgets,
)
from picard.const import (
RELEASE_FORMATS,
RELEASE_PRIMARY_GROUPS,
RELEASE_SECONDARY_GROUPS,
RELEASE_STATUS,
)
from picard.const.countries import RELEASE_COUNTRIES
from picard.i18n import gettext as _
from picard.util.tags import TAG_NAMES
from picard.ui import PicardDialog
from picard.ui.forms.ui_edittagdialog import Ui_EditTagDialog
AUTOCOMPLETE_RELEASE_TYPES = [s.lower() for s
in sorted(RELEASE_PRIMARY_GROUPS) + sorted(RELEASE_SECONDARY_GROUPS)]
AUTOCOMPLETE_RELEASE_STATUS = sorted(s.lower() for s in RELEASE_STATUS)
AUTOCOMPLETE_RELEASE_COUNTRIES = sorted(RELEASE_COUNTRIES, key=str.casefold)
AUTOCOMPLETE_RELEASE_FORMATS = sorted(RELEASE_FORMATS, key=str.casefold)
MULTILINE_TAGS = {'comment', 'lyrics', 'syncedlyrics'}
class TagEditorDelegate(QtWidgets.QItemDelegate):
def createEditor(self, parent, option, index):
if not index.isValid():
return None
tag = self.get_tag_name(index)
if tag.partition(':')[0] in MULTILINE_TAGS:
editor = QtWidgets.QPlainTextEdit(parent)
editor.setFrameStyle(editor.style().styleHint(QtWidgets.QStyle.StyleHint.SH_ItemView_DrawDelegateFrame, None, editor))
editor.setMinimumSize(QtCore.QSize(0, 80))
else:
editor = super().createEditor(parent, option, index)
completer = None
if tag in {'date', 'originaldate', 'releasedate'}:
editor.setPlaceholderText(_("YYYY-MM-DD"))
elif tag == 'originalyear':
editor.setPlaceholderText(_("YYYY"))
elif tag == 'releasetype':
completer = QtWidgets.QCompleter(AUTOCOMPLETE_RELEASE_TYPES, editor)
elif tag == 'releasestatus':
completer = QtWidgets.QCompleter(AUTOCOMPLETE_RELEASE_STATUS, editor)
completer.setModelSorting(QtWidgets.QCompleter.ModelSorting.CaseInsensitivelySortedModel)
elif tag == 'releasecountry':
completer = QtWidgets.QCompleter(AUTOCOMPLETE_RELEASE_COUNTRIES, editor)
completer.setModelSorting(QtWidgets.QCompleter.ModelSorting.CaseInsensitivelySortedModel)
elif tag == 'media':
completer = QtWidgets.QCompleter(AUTOCOMPLETE_RELEASE_FORMATS, editor)
completer.setModelSorting(QtWidgets.QCompleter.ModelSorting.CaseInsensitivelySortedModel)
if editor and completer:
completer.setCompletionMode(QtWidgets.QCompleter.CompletionMode.UnfilteredPopupCompletion)
completer.setCaseSensitivity(QtCore.Qt.CaseSensitivity.CaseInsensitive)
editor.setCompleter(completer)
return editor
def get_tag_name(self, index):
return self.parent().tag
class EditTagDialog(PicardDialog):
def __init__(self, metadata_box, tag):
super().__init__(parent=metadata_box)
self.ui = Ui_EditTagDialog()
self.ui.setupUi(self)
self.value_list = self.ui.value_list
self.tagger = QtCore.QCoreApplication.instance()
self.metadata_box = metadata_box
self.tag = tag
self.modified_tags = {}
self.is_grouped = False
self.default_tags = sorted(
set(list(TAG_NAMES.keys()) + self.metadata_box.tag_diff.tag_names))
if len(self.metadata_box.files) == 1:
current_file = list(self.metadata_box.files)[0]
self.default_tags = list(filter(current_file.supports_tag, self.default_tags))
tag_names = self.ui.tag_names
tag_names.addItem("")
visible_tags = [tn for tn in self.default_tags if not tn.startswith("~")]
tag_names.addItems(visible_tags)
self.completer = QtWidgets.QCompleter(visible_tags, tag_names)
self.completer.setCompletionMode(QtWidgets.QCompleter.CompletionMode.PopupCompletion)
tag_names.setCompleter(self.completer)
self.value_list.model().rowsInserted.connect(self.on_rows_inserted)
self.value_list.model().rowsRemoved.connect(self.on_rows_removed)
self.value_list.setItemDelegate(TagEditorDelegate(self))
self.tag_changed(tag)
self.value_selection_changed()
def keyPressEvent(self, event):
if event.modifiers() == QtCore.Qt.KeyboardModifier.NoModifier and event.key() in {QtCore.Qt.Key.Key_Enter, QtCore.Qt.Key.Key_Return}:
self.add_or_edit_value()
event.accept()
elif event.matches(QtGui.QKeySequence.StandardKey.Delete):
self.remove_value()
elif event.key() == QtCore.Qt.Key.Key_Insert:
self.add_value()
else:
super().keyPressEvent(event)
def tag_selected(self, index):
self.add_or_edit_value()
def edit_value(self):
item = self.value_list.currentItem()
if item:
# Do not initialize editing if editor is already active. Avoids flickering of the edit field
# when already in edit mode. `isPersistentEditorOpen` is only supported in Qt 5.10 and later.
if hasattr(self.value_list, 'isPersistentEditorOpen') and self.value_list.isPersistentEditorOpen(item):
return
self.value_list.editItem(item)
def add_value(self):
item = QtWidgets.QListWidgetItem()
item.setFlags(QtCore.Qt.ItemFlag.ItemIsSelectable | QtCore.Qt.ItemFlag.ItemIsEnabled | QtCore.Qt.ItemFlag.ItemIsEditable)
self.value_list.addItem(item)
self.value_list.setCurrentItem(item)
self.value_list.editItem(item)
def add_or_edit_value(self):
last_item = self.value_list.item(self.value_list.count() - 1)
# Edit the last item, if it is empty, or add a new empty item
if last_item and not last_item.text():
self.value_list.setCurrentItem(last_item)
self.edit_value()
else:
self.add_value()
def _group(self, is_grouped):
self.is_grouped = is_grouped
self.ui.add_value.setEnabled(not is_grouped)
def remove_value(self):
value_list = self.value_list
row = value_list.currentRow()
if row == 0 and self.is_grouped:
self._group(False)
value_list.takeItem(row)
def on_rows_inserted(self, parent, first, last):
for row in range(first, last + 1):
item = self.value_list.item(row)
self._modified_tag().insert(row, item.text())
def on_rows_removed(self, parent, first, last):
for row in range(first, last + 1):
del self._modified_tag()[row]
def move_row_up(self):
row = self.value_list.currentRow()
if row > 0:
self._move_row(row, -1)
def move_row_down(self):
row = self.value_list.currentRow()
if row + 1 < self.value_list.count():
self._move_row(row, 1)
def _move_row(self, row, direction):
value_list = self.value_list
item = value_list.takeItem(row)
new_row = row + direction
value_list.insertItem(new_row, item)
value_list.setCurrentRow(new_row)
def disable_all(self):
self.value_list.clear()
self.value_list.setEnabled(False)
self.ui.add_value.setEnabled(False)
def enable_all(self):
self.value_list.setEnabled(True)
self.ui.add_value.setEnabled(True)
def tag_changed(self, tag):
tag_names = self.ui.tag_names
tag_names.editTextChanged.disconnect(self.tag_changed)
line_edit = tag_names.lineEdit()
cursor_pos = line_edit.cursorPosition()
flags = QtCore.Qt.MatchFlag.MatchFixedString | QtCore.Qt.MatchFlag.MatchCaseSensitive
# if the previous tag was new and has no value, remove it from the QComboBox.
# e.g. typing "XYZ" should not leave "X" or "XY" in the QComboBox.
if self.tag and self.tag not in self.default_tags and self._modified_tag() == [""]:
tag_names.removeItem(tag_names.findText(self.tag, flags))
row = tag_names.findText(tag, flags)
self.tag = tag
if row <= 0:
if tag:
# add custom tags to the QComboBox immediately
tag_names.addItem(tag)
tag_names.model().sort(0)
row = tag_names.findText(tag, flags)
else:
# the QLineEdit is empty, disable everything
self.disable_all()
tag_names.setCurrentIndex(0)
tag_names.editTextChanged.connect(self.tag_changed)
return
self.enable_all()
tag_names.setCurrentIndex(row)
line_edit.setCursorPosition(cursor_pos)
self.value_list.clear()
values = self.modified_tags.get(self.tag, None)
if values is None:
new_tags = self.metadata_box.tag_diff.new
display_value = new_tags.display_value(self.tag)
if display_value.is_grouped:
# grouped values have a special text, which isn't a valid tag value
values = [display_value.text]
self._group(True)
else:
# normal tag values
values = new_tags[self.tag]
self._group(False)
self.value_list.model().rowsInserted.disconnect(self.on_rows_inserted)
self._add_value_items(values)
self.value_list.model().rowsInserted.connect(self.on_rows_inserted)
self.value_list.setCurrentItem(self.value_list.item(0), QtCore.QItemSelectionModel.SelectionFlag.SelectCurrent)
tag_names.editTextChanged.connect(self.tag_changed)
def _set_item_style(self, item):
font = item.font()
font.setItalic(self.is_grouped)
item.setFont(font)
def _add_value_items(self, values):
values = [v for v in values if v] or [""]
for value in values:
item = QtWidgets.QListWidgetItem(value)
item.setFlags(QtCore.Qt.ItemFlag.ItemIsSelectable | QtCore.Qt.ItemFlag.ItemIsEnabled | QtCore.Qt.ItemFlag.ItemIsEditable | QtCore.Qt.ItemFlag.ItemIsDragEnabled)
self._set_item_style(item)
self.value_list.addItem(item)
def value_edited(self, item):
row = self.value_list.row(item)
value = item.text()
if row == 0 and self.is_grouped:
self.modified_tags[self.tag] = [value]
self._group(False)
self._set_item_style(item)
else:
self._modified_tag()[row] = value
# add tags to the completer model once they get values
cm = self.completer.model()
if self.tag not in cm.stringList():
cm.insertRows(0, 1)
cm.setData(cm.index(0, 0), self.tag)
cm.sort(0)
def value_selection_changed(self):
selection = len(self.value_list.selectedItems()) > 0
self.ui.edit_value.setEnabled(selection)
self.ui.remove_value.setEnabled(selection)
self.ui.move_value_up.setEnabled(selection)
self.ui.move_value_down.setEnabled(selection)
def _modified_tag(self):
return self.modified_tags.setdefault(self.tag,
list(self.metadata_box.tag_diff.new[self.tag]) or [""])
def accept(self):
with self.tagger.window.ignore_selection_changes:
for tag, values in self.modified_tags.items():
self.modified_tags[tag] = [v for v in values if v]
modified_tags = self.modified_tags.items()
for obj in self.metadata_box.objects:
for tag, values in modified_tags:
obj.metadata[tag] = list(values)
obj.update()
super().accept()
| 12,810
|
Python
|
.py
| 271
| 38.0369
| 172
| 0.654452
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,995
|
caa_types_selector.py
|
metabrainz_picard/picard/ui/caa_types_selector.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2007 Oliver Charles
# Copyright (C) 2007, 2010-2011 Lukáš Lalinský
# Copyright (C) 2007-2011, 2015, 2018-2023 Philipp Wolfer
# Copyright (C) 2011 Michael Wiencek
# Copyright (C) 2011-2012 Wieland Hoffmann
# Copyright (C) 2013-2015, 2018-2023 Laurent Monin
# Copyright (C) 2015-2016 Rahul Raturi
# Copyright (C) 2016-2017 Sambhav Kothari
# Copyright (C) 2017 Frederik “Freso” S. Olesen
# Copyright (C) 2018, 2024 Bob Swift
# Copyright (C) 2018 Vishal Choudhary
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from functools import partial
from PyQt6 import (
QtCore,
QtGui,
QtWidgets,
)
from picard.const.defaults import (
DEFAULT_CAA_IMAGE_TYPE_EXCLUDE,
DEFAULT_CAA_IMAGE_TYPE_INCLUDE,
)
from picard.coverart.utils import (
CAA_TYPES,
translate_caa_type,
)
from picard.i18n import (
N_,
gettext as _,
)
from picard.ui import PicardDialog
from picard.ui.util import (
StandardButton,
qlistwidget_items,
)
class ArrowButton(QtWidgets.QPushButton):
"""Standard arrow button for CAA image type selection dialog.
Keyword Arguments:
label {string} -- Label to display on the button
command {command} -- Command to execute when the button is clicked (default: {None})
parent {[type]} -- Parent of the QPushButton object being created (default: {None})
"""
def __init__(self, icon_name, command=None, parent=None):
icon = QtGui.QIcon(":/images/16x16/" + icon_name + '.png')
super().__init__(icon, "", parent=parent)
if command is not None:
self.clicked.connect(command)
class ArrowsColumn(QtWidgets.QWidget):
"""Standard arrow buttons column for CAA image type selection dialog.
Keyword Arguments:
selection_list {ListBox} -- ListBox of selected items associated with this arrow column
ignore_list {ListBox} -- ListBox of unselected items associated with this arrow column
callback {command} -- Command to execute after items are moved between lists (default: {None})
reverse {bool} -- Determines whether the arrow directions should be reversed (default: {False})
parent {[type]} -- Parent of the QWidget object being created (default: {None})
"""
def __init__(self, selection_list, ignore_list, callback=None, reverse=False, parent=None):
super().__init__(parent=parent)
self.selection_list = selection_list
self.ignore_list = ignore_list
self.callback = callback
spacer_item = QtWidgets.QSpacerItem(20, 20, QtWidgets.QSizePolicy.Policy.Minimum, QtWidgets.QSizePolicy.Policy.Expanding)
arrows_layout = QtWidgets.QVBoxLayout()
arrows_layout.addItem(QtWidgets.QSpacerItem(spacer_item))
self.button_add = ArrowButton('go-next' if reverse else 'go-previous', self.move_from_ignore)
arrows_layout.addWidget(self.button_add)
self.button_add_all = ArrowButton('move-all-right' if reverse else 'move-all-left', self.move_all_from_ignore)
arrows_layout.addWidget(self.button_add_all)
self.button_remove = ArrowButton('go-previous' if reverse else 'go-next', self.move_to_ignore)
arrows_layout.addWidget(self.button_remove)
self.button_remove_all = ArrowButton('move-all-left' if reverse else 'move-all-right', self.move_all_to_ignore)
arrows_layout.addWidget(self.button_remove_all)
arrows_layout.addItem(QtWidgets.QSpacerItem(spacer_item))
self.setLayout(arrows_layout)
def move_from_ignore(self):
self.ignore_list.move_selected_items(self.selection_list, callback=self.callback)
def move_all_from_ignore(self):
self.ignore_list.move_all_items(self.selection_list, callback=self.callback)
def move_to_ignore(self):
self.selection_list.move_selected_items(self.ignore_list, callback=self.callback)
def move_all_to_ignore(self):
self.selection_list.move_all_items(self.ignore_list, callback=self.callback)
class ListBox(QtWidgets.QListWidget):
"""Standard list box for CAA image type selection dialog.
Keyword Arguments:
parent {[type]} -- Parent of the QListWidget object being created (default: {None})
"""
LISTBOX_WIDTH = 100
LISTBOX_HEIGHT = 250
def __init__(self, parent=None):
super().__init__(parent=parent)
self.setMinimumSize(QtCore.QSize(self.LISTBOX_WIDTH, self.LISTBOX_HEIGHT))
self.setSizePolicy(QtWidgets.QSizePolicy.Policy.MinimumExpanding, QtWidgets.QSizePolicy.Policy.Expanding)
self.setSortingEnabled(True)
self.setSelectionMode(QtWidgets.QAbstractItemView.SelectionMode.ExtendedSelection)
def move_item(self, item, target_list):
"""Move the specified item to another listbox."""
self.takeItem(self.row(item))
target_list.addItem(item)
def move_selected_items(self, target_list, callback=None):
"""Move the selected item to another listbox."""
for item in self.selectedItems():
self.move_item(item, target_list)
if callback:
callback()
def move_all_items(self, target_list, callback=None):
"""Move all items to another listbox."""
while self.count():
self.move_item(self.item(0), target_list)
if callback:
callback()
def all_items_data(self, role=QtCore.Qt.ItemDataRole.UserRole):
for item in qlistwidget_items(self):
yield item.data(role)
class CAATypesSelectorDialog(PicardDialog):
"""Display dialog box to select the CAA image types to include and exclude from download and use.
Keyword Arguments:
types_include {[string]} -- List of CAA image types to include (default: {None})
types_exclude {[string]} -- List of CAA image types to exclude (default: {None})
parent {[type]} -- Parent of the QDialog object being created (default: {None})
instructions_top {string} -- Replacement for the default instruction text to display above the list boxes (default: {None})
instructions_bottom {string} -- Replacement for the instruction text to display between the list boxes and the button bar (default: {None})
"""
help_url = 'doc_cover_art_types'
def __init__(
self,
types_include=None,
types_exclude=None,
parent=None,
instructions_top=None,
instructions_bottom=None,
):
super().__init__(parent=parent)
types_include = set(types_include or ())
types_exclude = set(types_exclude or ())
self._default_include = DEFAULT_CAA_IMAGE_TYPE_INCLUDE
self._default_exclude = DEFAULT_CAA_IMAGE_TYPE_EXCLUDE
self._known_types = {t['name']: translate_caa_type(t['name']) for t in CAA_TYPES}
self.setWindowTitle(_("Cover art types"))
self.setWindowModality(QtCore.Qt.WindowModality.WindowModal)
self.layout = QtWidgets.QVBoxLayout(self)
self.layout.setSizeConstraint(QtWidgets.QLayout.SizeConstraint.SetFixedSize)
# Create list boxes for dialog
self.list_include = ListBox()
self.list_exclude = ListBox()
self.list_ignore = ListBox()
# Populate list boxes from current settings
self.fill_lists(types_include, types_exclude)
# Set triggers when the lists receive the current focus
self.list_include.clicked.connect(partial(self._on_list_clicked, (self.list_ignore, self.list_exclude)))
self.list_exclude.clicked.connect(partial(self._on_list_clicked, (self.list_ignore, self.list_include)))
self.list_ignore.clicked.connect(partial(self._on_list_clicked, (self.list_include, self.list_exclude)))
# Add instructions to the dialog box
instructions = QtWidgets.QLabel()
if instructions_top is None:
instructions_top = N_("Please select the contents of the image type 'Include' and 'Exclude' lists.")
instructions.setText(_(instructions_top))
instructions.setWordWrap(True)
instructions.setSizePolicy(QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Expanding)
self.layout.addWidget(instructions)
self.arrows_include = ArrowsColumn(
self.list_include,
self.list_ignore,
callback=self.set_buttons_enabled_state,
)
self.arrows_exclude = ArrowsColumn(
self.list_exclude,
self.list_ignore,
callback=self.set_buttons_enabled_state,
reverse=True
)
lists_layout = QtWidgets.QHBoxLayout()
include_list_layout = QtWidgets.QVBoxLayout()
include_list_layout.addWidget(QtWidgets.QLabel(_("Include types list")))
include_list_layout.addWidget(self.list_include)
lists_layout.addLayout(include_list_layout)
lists_layout.addWidget(self.arrows_include)
ignore_list_layout = QtWidgets.QVBoxLayout()
ignore_list_layout.addWidget(QtWidgets.QLabel(""))
ignore_list_layout.addWidget(self.list_ignore)
lists_layout.addLayout(ignore_list_layout)
lists_layout.addWidget(self.arrows_exclude)
exclude_list_layout = QtWidgets.QVBoxLayout()
exclude_list_layout.addWidget(QtWidgets.QLabel(_("Exclude types list")))
exclude_list_layout.addWidget(self.list_exclude)
lists_layout.addLayout(exclude_list_layout)
self.layout.addLayout(lists_layout)
# Add usage explanation to the dialog box
instructions = QtWidgets.QLabel()
if instructions_bottom is None:
instructions_bottom = N_(
"CAA images with an image type found in the 'Include' list will be downloaded and used "
"UNLESS they also have an image type found in the 'Exclude' list. Images with types "
"found in the 'Exclude' list will NEVER be used. Image types not appearing in the 'Include' "
"or 'Exclude' lists will not be considered when determining whether or not to download and "
"use a CAA image.\n"
)
instructions.setText(_(instructions_bottom))
instructions.setWordWrap(True)
instructions.setSizePolicy(QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Expanding)
self.layout.addWidget(instructions)
self.buttonbox = QtWidgets.QDialogButtonBox(self)
self.buttonbox.setOrientation(QtCore.Qt.Orientation.Horizontal)
self.buttonbox.addButton(
StandardButton(StandardButton.OK), QtWidgets.QDialogButtonBox.ButtonRole.AcceptRole)
self.buttonbox.addButton(StandardButton(StandardButton.CANCEL),
QtWidgets.QDialogButtonBox.ButtonRole.RejectRole)
self.buttonbox.addButton(
StandardButton(StandardButton.HELP), QtWidgets.QDialogButtonBox.ButtonRole.HelpRole)
extrabuttons = [
(N_("I&nclude all"), self.move_all_to_include_list),
(N_("E&xclude all"), self.move_all_to_exclude_list),
(N_("C&lear all"), self.move_all_to_ignore_list),
(N_("Restore &Defaults"), self.reset_to_defaults),
]
for label, callback in extrabuttons:
button = QtWidgets.QPushButton(_(label))
self.buttonbox.addButton(button, QtWidgets.QDialogButtonBox.ButtonRole.ActionRole)
button.clicked.connect(callback)
self.layout.addWidget(self.buttonbox)
self.buttonbox.accepted.connect(self.accept)
self.buttonbox.rejected.connect(self.reject)
self.buttonbox.helpRequested.connect(self.show_help)
self.set_buttons_enabled_state()
def move_all_to_include_list(self):
self.list_ignore.move_all_items(self.list_include)
self.list_exclude.move_all_items(self.list_include)
self.set_buttons_enabled_state()
def move_all_to_exclude_list(self):
self.list_ignore.move_all_items(self.list_exclude)
self.list_include.move_all_items(self.list_exclude)
self.set_buttons_enabled_state()
def move_all_to_ignore_list(self):
self.list_include.move_all_items(self.list_ignore)
self.list_exclude.move_all_items(self.list_ignore)
self.set_buttons_enabled_state()
def fill_lists(self, includes, excludes):
"""Fill dialog listboxes.
First clears the contents of the three listboxes, and then populates the listboxes
from the dictionary of standard CAA types, using the provided 'includes' and
'excludes' lists to determine the appropriate list for each type.
Arguments:
includes -- set of standard image types to place in the "Include" listbox
excludes -- set of standard image types to place in the "Exclude" listbox
"""
self.list_include.clear()
self.list_exclude.clear()
self.list_ignore.clear()
for name, title in self._known_types.items():
item = QtWidgets.QListWidgetItem(title)
item.setData(QtCore.Qt.ItemDataRole.UserRole, name)
if name in includes:
self.list_include.addItem(item)
elif name in excludes:
self.list_exclude.addItem(item)
else:
self.list_ignore.addItem(item)
@property
def included(self):
return tuple(self.list_include.all_items_data()) or ('front', )
@property
def excluded(self):
return tuple(self.list_exclude.all_items_data())
def _on_list_clicked(self, lists, index):
for temp_list in lists:
temp_list.clearSelection()
self.set_buttons_enabled_state()
def reset_to_defaults(self):
self.fill_lists(self._default_include, self._default_exclude)
self.set_buttons_enabled_state()
def set_buttons_enabled_state(self):
has_items_include = self.list_include.count()
has_items_exclude = self.list_exclude.count()
has_items_ignore = self.list_ignore.count()
has_selected_include = bool(self.list_include.selectedItems())
has_selected_exclude = bool(self.list_exclude.selectedItems())
has_selected_ignore = bool(self.list_ignore.selectedItems())
# "Include" list buttons
self.arrows_include.button_add.setEnabled(has_items_ignore and has_selected_ignore)
self.arrows_include.button_add_all.setEnabled(has_items_ignore)
self.arrows_include.button_remove.setEnabled(has_items_include and has_selected_include)
self.arrows_include.button_remove_all.setEnabled(has_items_include)
# "Exclude" list buttons
self.arrows_exclude.button_add.setEnabled(has_items_ignore and has_selected_ignore)
self.arrows_exclude.button_add_all.setEnabled(has_items_ignore)
self.arrows_exclude.button_remove.setEnabled(has_items_exclude and has_selected_exclude)
self.arrows_exclude.button_remove_all.setEnabled(has_items_exclude)
@classmethod
def display(
cls,
types_include=None,
types_exclude=None,
parent=None,
instructions_top=None,
instructions_bottom=None,
):
dialog = cls(
types_include=types_include,
types_exclude=types_exclude,
parent=parent,
instructions_top=instructions_top,
instructions_bottom=instructions_bottom,
)
result = dialog.exec()
return (dialog.included, dialog.excluded, result == QtWidgets.QDialog.DialogCode.Accepted)
| 16,295
|
Python
|
.py
| 322
| 42.406832
| 147
| 0.689182
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,996
|
filebrowser.py
|
metabrainz_picard/picard/ui/filebrowser.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2006-2008 Lukáš Lalinský
# Copyright (C) 2008 Hendrik van Antwerpen
# Copyright (C) 2008-2009, 2019-2022, 2024 Philipp Wolfer
# Copyright (C) 2011 Andrew Barnert
# Copyright (C) 2012-2013 Michael Wiencek
# Copyright (C) 2013 Wieland Hoffmann
# Copyright (C) 2013, 2017 Sophist-UK
# Copyright (C) 2013, 2018-2024 Laurent Monin
# Copyright (C) 2015 Jeroen Kromwijk
# Copyright (C) 2016-2017 Sambhav Kothari
# Copyright (C) 2018 Vishal Choudhary
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import os
from PyQt6 import (
QtCore,
QtGui,
QtWidgets,
)
from picard.config import get_config
from picard.const.sys import IS_MACOS
from picard.formats import supported_formats
from picard.i18n import gettext as _
from picard.util import find_existing_path
from picard.util.macos import (
extend_root_volume_path,
strip_root_volume_path,
)
class FileBrowser(QtWidgets.QTreeView):
def __init__(self, parent=None):
super().__init__(parent=parent)
self.tagger = QtCore.QCoreApplication.instance()
self.setSelectionMode(QtWidgets.QAbstractItemView.SelectionMode.ExtendedSelection)
self.setDragEnabled(True)
self.load_selected_files_action = QtGui.QAction(_("&Load selected files"), self)
self.load_selected_files_action.triggered.connect(self.load_selected_files)
self.addAction(self.load_selected_files_action)
self.move_files_here_action = QtGui.QAction(_("&Move tagged files here"), self)
self.move_files_here_action.triggered.connect(self.move_files_here)
self.addAction(self.move_files_here_action)
self.toggle_hidden_action = QtGui.QAction(_("Show &hidden files"), self)
self.toggle_hidden_action.setCheckable(True)
config = get_config()
self.toggle_hidden_action.setChecked(config.persist['show_hidden_files'])
self.toggle_hidden_action.toggled.connect(self.show_hidden)
self.addAction(self.toggle_hidden_action)
self.set_as_starting_directory_action = QtGui.QAction(_("&Set as starting directory"), self)
self.set_as_starting_directory_action.triggered.connect(self.set_as_starting_directory)
self.addAction(self.set_as_starting_directory_action)
self.doubleClicked.connect(self.load_file_for_item)
self.focused = False
def showEvent(self, event):
if not self.model():
self._set_model()
def contextMenuEvent(self, event):
menu = QtWidgets.QMenu(self)
menu.addAction(self.load_selected_files_action)
menu.addSeparator()
menu.addAction(self.move_files_here_action)
menu.addAction(self.toggle_hidden_action)
menu.addAction(self.set_as_starting_directory_action)
menu.exec(event.globalPos())
event.accept()
def _set_model(self):
model = QtGui.QFileSystemModel()
self.setModel(model)
model.layoutChanged.connect(self._layout_changed)
model.setRootPath("")
self._set_model_filter()
filters = []
for exts, name in supported_formats():
filters.extend("*" + e for e in exts)
model.setNameFilters(filters)
# Hide unsupported files completely
model.setNameFilterDisables(False)
model.sort(0, QtCore.Qt.SortOrder.AscendingOrder)
if IS_MACOS:
self.setRootIndex(model.index("/Volumes"))
header = self.header()
header.hideSection(1)
header.hideSection(2)
header.hideSection(3)
header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeMode.ResizeToContents)
header.setStretchLastSection(False)
header.setVisible(False)
def _set_model_filter(self):
config = get_config()
model_filter = QtCore.QDir.Filter.AllDirs | QtCore.QDir.Filter.Files | QtCore.QDir.Filter.Drives | QtCore.QDir.Filter.NoDotAndDotDot
if config.persist['show_hidden_files']:
model_filter |= QtCore.QDir.Filter.Hidden
self.model().setFilter(model_filter)
def _layout_changed(self):
def scroll():
# XXX The currentIndex seems to change while QFileSystemModel is
# populating itself (so setCurrentIndex in __init__ won't last).
# The time it takes to load varies and there are no signals to find
# out when it's done. As a workaround, keep restoring the state as
# long as the layout is updating, and the user hasn't focused yet.
if not self.focused:
self._restore_state()
self.scrollTo(self.currentIndex())
QtCore.QTimer.singleShot(0, scroll)
def scrollTo(self, index, scrolltype=QtWidgets.QAbstractItemView.ScrollHint.EnsureVisible):
# QTreeView.scrollTo resets the horizontal scroll position to 0.
# Reimplemented to instead scroll to horizontal parent position or keep previous position.
config = get_config()
if index and config.setting['filebrowser_horizontal_autoscroll']:
level = -1
parent = index.parent()
root = self.rootIndex()
while parent.isValid() and parent != root:
parent = parent.parent()
level += 1
pos_x = max(self.indentation() * level, 0)
else:
pos_x = self.horizontalScrollBar().value()
super().scrollTo(index, scrolltype)
self.horizontalScrollBar().setValue(pos_x)
def mousePressEvent(self, event):
super().mousePressEvent(event)
index = self.indexAt(event.pos())
if index.isValid():
self.selectionModel().setCurrentIndex(index, QtCore.QItemSelectionModel.SelectionFlag.NoUpdate)
def focusInEvent(self, event):
self.focused = True
super().focusInEvent(event)
def show_hidden(self, state):
config = get_config()
config.persist['show_hidden_files'] = state
self._set_model_filter()
def save_state(self):
indexes = self.selectedIndexes()
if indexes:
path = self.model().filePath(indexes[0])
config = get_config()
config.persist['current_browser_path'] = os.path.normpath(path)
def restore_state(self):
pass
def _restore_state(self):
config = get_config()
if config.setting['starting_directory']:
path = config.setting['starting_directory_path']
scrolltype = QtWidgets.QAbstractItemView.ScrollHint.PositionAtTop
else:
path = config.persist['current_browser_path']
scrolltype = QtWidgets.QAbstractItemView.ScrollHint.PositionAtCenter
if path:
if IS_MACOS:
path = extend_root_volume_path(path)
index = self.model().index(find_existing_path(path))
self.setCurrentIndex(index)
self.expand(index)
self.scrollTo(index, scrolltype)
def _get_destination_from_path(self, path):
destination = os.path.normpath(path)
if not os.path.isdir(destination):
destination = os.path.dirname(destination)
if IS_MACOS:
destination = strip_root_volume_path(destination)
return destination
def load_file_for_item(self, index):
model = self.model()
if not model.isDir(index):
self.tagger.add_paths([
model.filePath(index)
])
def load_selected_files(self):
indexes = self.selectedIndexes()
if not indexes:
return
paths = set(self.model().filePath(index) for index in indexes)
self.tagger.add_paths(paths)
def move_files_here(self):
indexes = self.selectedIndexes()
if not indexes:
return
config = get_config()
path = self.model().filePath(indexes[0])
config.setting['move_files_to'] = self._get_destination_from_path(path)
def set_as_starting_directory(self):
indexes = self.selectedIndexes()
if indexes:
config = get_config()
path = self.model().filePath(indexes[0])
config.setting['starting_directory_path'] = self._get_destination_from_path(path)
| 8,959
|
Python
|
.py
| 201
| 36.512438
| 140
| 0.671859
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,997
|
theme.py
|
metabrainz_picard/picard/ui/theme.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2019-2022 Philipp Wolfer
# Copyright (C) 2020-2021 Gabriel Ferreira
# Copyright (C) 2021-2024 Laurent Monin
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from enum import Enum
from PyQt6 import (
QtCore,
QtGui,
QtWidgets,
)
from picard import log
from picard.config import get_config
from picard.const.sys import (
IS_HAIKU,
IS_MACOS,
IS_WIN,
)
OS_SUPPORTS_THEMES = True
if IS_MACOS:
try:
import AppKit
except ImportError:
AppKit = None
OS_SUPPORTS_THEMES = bool(AppKit) and hasattr(AppKit.NSAppearance, '_darkAquaAppearance')
elif IS_HAIKU:
OS_SUPPORTS_THEMES = False
# Those are values stored in config file:
class UiTheme(Enum):
DEFAULT = 'default'
DARK = 'dark'
LIGHT = 'light'
SYSTEM = 'system'
def __str__(self):
return self.value
@classmethod
def _missing_(cls, value):
return cls.DEFAULT
AVAILABLE_UI_THEMES = [UiTheme.DEFAULT]
if IS_WIN or IS_MACOS:
AVAILABLE_UI_THEMES.extend([UiTheme.LIGHT, UiTheme.DARK])
elif not IS_HAIKU:
AVAILABLE_UI_THEMES.extend([UiTheme.SYSTEM])
class MacOverrideStyle(QtWidgets.QProxyStyle):
"""Override the default style to fix some platform specific issues"""
def styleHint(self, hint, option, widget, returnData):
# This is disabled on macOS, but prevents collapsing tree view items easily with
# left arrow key. Enable this consistently on all platforms.
# See https://tickets.metabrainz.org/browse/PICARD-2417
# and https://bugreports.qt.io/browse/QTBUG-100305
if hint == QtWidgets.QStyle.StyleHint.SH_ItemView_ArrowKeysNavigateIntoChildren:
return True
return super().styleHint(hint, option, widget, returnData)
class BaseTheme:
def __init__(self):
self._dark_theme = False
self._loaded_config_theme = UiTheme.DEFAULT
def setup(self, app):
config = get_config()
self._loaded_config_theme = UiTheme(config.setting['ui_theme'])
# Use the new fusion style from PyQt6 for a modern and consistent look
# across all OSes.
if not IS_MACOS and not IS_HAIKU and self._loaded_config_theme != UiTheme.SYSTEM:
app.setStyle('Fusion')
elif IS_MACOS:
app.setStyle(MacOverrideStyle(app.style()))
app.setStyleSheet(
'QGroupBox::title { /* PICARD-1206, Qt bug workaround */ }'
)
palette = QtGui.QPalette(app.palette())
base_color = palette.color(QtGui.QPalette.ColorGroup.Active, QtGui.QPalette.ColorRole.Base)
self._dark_theme = base_color.lightness() < 128
self.update_palette(palette, self.is_dark_theme, self.accent_color)
app.setPalette(palette)
@property
def is_dark_theme(self):
if self._loaded_config_theme == UiTheme.DARK:
return True
elif self._loaded_config_theme == UiTheme.LIGHT:
return False
else:
return self._dark_theme
@property
def accent_color(self): # pylint: disable=no-self-use
return None
# pylint: disable=no-self-use
def update_palette(self, palette, dark_theme, accent_color):
if accent_color:
accent_text_color = QtCore.Qt.GlobalColor.white if accent_color.lightness() < 160 else QtCore.Qt.GlobalColor.black
palette.setColor(QtGui.QPalette.ColorGroup.Active, QtGui.QPalette.ColorRole.Highlight, accent_color)
palette.setColor(QtGui.QPalette.ColorGroup.Active, QtGui.QPalette.ColorRole.HighlightedText, accent_text_color)
link_color = QtGui.QColor()
link_color.setHsl(accent_color.hue(), accent_color.saturation(), 160, accent_color.alpha())
palette.setColor(QtGui.QPalette.ColorRole.Link, link_color)
if IS_WIN:
import winreg
class WindowsTheme(BaseTheme):
def setup(self, app):
app.setStyle('Fusion')
super().setup(app)
@property
def is_dark_theme(self):
if self._loaded_config_theme != UiTheme.DEFAULT:
return self._loaded_config_theme == UiTheme.DARK
dark_theme = False
try:
with winreg.OpenKey(winreg.HKEY_CURRENT_USER,
r"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize") as key:
dark_theme = winreg.QueryValueEx(key, "AppsUseLightTheme")[0] == 0
except OSError:
log.warning("Failed reading AppsUseLightTheme from registry")
return dark_theme
@property
def accent_color(self):
accent_color = None
try:
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\DWM") as key:
accent_color_dword = winreg.QueryValueEx(key, "ColorizationColor")[0]
accent_color_hex = '#{:06x}'.format(accent_color_dword & 0xffffff)
accent_color = QtGui.QColor(accent_color_hex)
except OSError:
log.warning("Failed reading ColorizationColor from registry")
return accent_color
def update_palette(self, palette, dark_theme, accent_color):
# Adapt to Windows 10 color scheme (dark / light theme and accent color)
super().update_palette(palette, dark_theme, accent_color)
if dark_theme:
palette.setColor(QtGui.QPalette.ColorRole.Window, QtGui.QColor(51, 51, 51))
palette.setColor(QtGui.QPalette.ColorRole.WindowText, QtCore.Qt.GlobalColor.white)
palette.setColor(QtGui.QPalette.ColorRole.Base, QtGui.QColor(31, 31, 31))
palette.setColor(QtGui.QPalette.ColorRole.AlternateBase, QtGui.QColor(51, 51, 51))
palette.setColor(QtGui.QPalette.ColorRole.ToolTipBase, QtGui.QColor(51, 51, 51))
palette.setColor(QtGui.QPalette.ColorRole.ToolTipText, QtCore.Qt.GlobalColor.white)
palette.setColor(QtGui.QPalette.ColorRole.Text, QtCore.Qt.GlobalColor.white)
palette.setColor(QtGui.QPalette.ColorRole.Button, QtGui.QColor(51, 51, 51))
palette.setColor(QtGui.QPalette.ColorRole.ButtonText, QtCore.Qt.GlobalColor.white)
palette.setColor(QtGui.QPalette.ColorRole.BrightText, QtCore.Qt.GlobalColor.red)
palette.setColor(QtGui.QPalette.ColorGroup.Disabled, QtGui.QPalette.ColorRole.Text, QtCore.Qt.GlobalColor.darkGray)
palette.setColor(QtGui.QPalette.ColorGroup.Disabled, QtGui.QPalette.ColorRole.Light, QtGui.QColor(0, 0, 0, 0))
palette.setColor(QtGui.QPalette.ColorGroup.Disabled, QtGui.QPalette.ColorRole.ButtonText, QtCore.Qt.GlobalColor.darkGray)
palette.setColor(QtGui.QPalette.ColorGroup.Disabled, QtGui.QPalette.ColorRole.Base, QtGui.QColor(60, 60, 60))
palette.setColor(QtGui.QPalette.ColorGroup.Inactive, QtGui.QPalette.ColorRole.Highlight, QtGui.QColor(51, 51, 51))
palette.setColor(QtGui.QPalette.ColorGroup.Inactive, QtGui.QPalette.ColorRole.HighlightedText, QtCore.Qt.GlobalColor.white)
theme = WindowsTheme()
elif IS_MACOS:
dark_appearance = False
if OS_SUPPORTS_THEMES and AppKit:
# Default procedure to identify the current appearance (theme)
appearance = AppKit.NSAppearance.currentAppearance()
try:
basic_appearance = appearance.bestMatchFromAppearancesWithNames_([
AppKit.NSAppearanceNameAqua,
AppKit.NSAppearanceNameDarkAqua
])
dark_appearance = basic_appearance == AppKit.NSAppearanceNameDarkAqua
except AttributeError:
pass
class MacTheme(BaseTheme):
def setup(self, app):
super().setup(app)
if self._loaded_config_theme != UiTheme.DEFAULT:
dark_theme = self._loaded_config_theme == UiTheme.DARK
else:
dark_theme = dark_appearance
# MacOS uses a NSAppearance object to change the current application appearance
# We call this even if UiTheme is the default, preventing MacOS from switching on-the-fly
if OS_SUPPORTS_THEMES and AppKit:
try:
if dark_theme:
appearance = AppKit.NSAppearance._darkAquaAppearance()
else:
appearance = AppKit.NSAppearance._aquaAppearance()
AppKit.NSApplication.sharedApplication().setAppearance_(appearance)
except AttributeError:
pass
@property
def is_dark_theme(self):
if not OS_SUPPORTS_THEMES:
# Fall back to generic dark color palette detection
return super().is_dark_theme
elif self._loaded_config_theme == UiTheme.DEFAULT:
return dark_appearance
else:
return self._loaded_config_theme == UiTheme.DARK
# pylint: disable=no-self-use
def update_palette(self, palette, dark_theme, accent_color):
pass # No palette changes, theme is fully handled by Qt
theme = MacTheme()
else:
theme = BaseTheme()
def setup(app):
theme.setup(app)
| 10,069
|
Python
|
.py
| 208
| 38.8125
| 139
| 0.663237
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,998
|
passworddialog.py
|
metabrainz_picard/picard/ui/passworddialog.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2008, 2021 Philipp Wolfer
# Copyright (C) 2009 Carlin Mangar
# Copyright (C) 2012, 2014 Lukáš Lalinský
# Copyright (C) 2012-2013 Michael Wiencek
# Copyright (C) 2013-2014, 2018, 2020-2021, 2023-2024 Laurent Monin
# Copyright (C) 2014 Sophist-UK
# Copyright (C) 2016-2017 Sambhav Kothari
# Copyright (C) 2018 Vishal Choudhary
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from picard.config import get_config
from picard.i18n import gettext as _
from picard.ui import PicardDialog
from picard.ui.forms.ui_passworddialog import Ui_PasswordDialog
class PasswordDialog(PicardDialog):
def __init__(self, authenticator, reply, parent=None):
super().__init__(parent=parent)
self._authenticator = authenticator
self.ui = Ui_PasswordDialog()
self.ui.setupUi(self)
self.ui.info_text.setText(
_("The server %s requires you to login. Please enter your username and password.") %
reply.url().host())
self.ui.username.setText(reply.url().userName())
self.ui.password.setText(reply.url().password())
self.ui.buttonbox.accepted.connect(self.set_new_password)
def set_new_password(self):
self._authenticator.setUser(self.ui.username.text())
self._authenticator.setPassword(self.ui.password.text())
self.accept()
class ProxyDialog(PicardDialog):
def __init__(self, authenticator, proxy, parent=None):
super().__init__(parent=parent)
self._authenticator = authenticator
self._proxy = proxy
self.ui = Ui_PasswordDialog()
self.ui.setupUi(self)
config = get_config()
self.ui.info_text.setText(_("The proxy %s requires you to login. Please enter your username and password.")
% config.setting['proxy_server_host'])
self.ui.username.setText(config.setting['proxy_username'])
self.ui.password.setText(config.setting['proxy_password'])
self.ui.buttonbox.accepted.connect(self.set_proxy_password)
def set_proxy_password(self):
config = get_config()
config.setting['proxy_username'] = self.ui.username.text()
config.setting['proxy_password'] = self.ui.password.text()
self._authenticator.setUser(self.ui.username.text())
self._authenticator.setPassword(self.ui.password.text())
self.accept()
| 3,122
|
Python
|
.py
| 66
| 41.69697
| 115
| 0.707429
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|
10,999
|
infostatus.py
|
metabrainz_picard/picard/ui/infostatus.py
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2013, 2018, 2020-2024 Laurent Monin
# Copyright (C) 2016-2017 Sambhav Kothari
# Copyright (C) 2019, 2021-2022 Philipp Wolfer
# Copyright (C) 2021 Gabriel Ferreira
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import time
from PyQt6 import (
QtCore,
QtGui,
QtWidgets,
)
from picard.i18n import gettext as _
from picard.util import icontheme
from picard.util.time import get_timestamp
from picard.ui.forms.ui_infostatus import Ui_InfoStatus
class InfoStatus(QtWidgets.QWidget, Ui_InfoStatus):
def __init__(self, parent=None):
QtWidgets.QWidget.__init__(self, parent=parent)
Ui_InfoStatus.__init__(self)
self.setupUi(self)
self._size = QtCore.QSize(16, 16)
self._create_icons()
self._init_labels()
self.reset_counters()
def _init_labels(self):
size = self._size
self.label1.setPixmap(self.icon_eta.pixmap(size))
self.label1.hide()
self.label2.setPixmap(self.icon_file.pixmap(size))
self.label3.setPixmap(self.icon_cd.pixmap(size))
self.label4.setPixmap(self.icon_file_pending.pixmap(size))
self.label5.setPixmap(self.icon_download.pixmap(size, QtGui.QIcon.Mode.Disabled))
self._init_tooltips()
def _create_icons(self):
self.icon_eta = QtGui.QIcon(":/images/22x22/hourglass.png")
self.icon_cd = icontheme.lookup('media-optical')
self.icon_file = QtGui.QIcon(":/images/file.png")
self.icon_file_pending = QtGui.QIcon(":/images/file-pending.png")
self.icon_download = QtGui.QIcon(":/images/16x16/action-go-down-16.png")
def _init_tooltips(self):
t1 = _("Estimated Time")
t2 = _("Files")
t3 = _("Albums")
t4 = _("Pending files")
t5 = _("Pending requests")
self.val1.setToolTip(t1)
self.label1.setToolTip(t1)
self.val2.setToolTip(t2)
self.label2.setToolTip(t2)
self.val3.setToolTip(t3)
self.label3.setToolTip(t3)
self.val4.setToolTip(t4)
self.label4.setToolTip(t4)
self.val5.setToolTip(t5)
self.label5.setToolTip(t5)
def update(self, progress_status):
self.set_files(progress_status.files)
self.set_albums(progress_status.albums)
self.set_pending_files(progress_status.pending_files)
self.set_pending_requests(progress_status.pending_requests)
# estimate eta
total_pending = progress_status.pending_files + progress_status.pending_requests
last_pending = self._last_pending_files + self._last_pending_requests
# Reset the counters if we had no pending progress before and receive new pending items.
# This resets the starting timestamp and starts a new round of measurement.
if total_pending > 0 and last_pending == 0:
self.reset_counters()
previous_done_files = max(0, self._max_pending_files - self._last_pending_files)
previous_done_requests = max(0, self._max_pending_requests - self._last_pending_requests)
self._max_pending_files = max(self._max_pending_files, previous_done_files + progress_status.pending_files)
self._max_pending_requests = max(self._max_pending_requests, previous_done_requests + progress_status.pending_requests)
self._last_pending_files = progress_status.pending_files
self._last_pending_requests = progress_status.pending_requests
if total_pending == 0 or (self._max_pending_files + self._max_pending_requests <= 1):
self.reset_counters()
self.hide_eta()
return
if total_pending != last_pending:
current_time = time.time()
# time since we started processing this batch
diff_time = max(0.1, current_time - self._prev_time) # denominator can't be 0
previous_done_files = max(1, previous_done_files) # denominator can't be 0
# we estimate based on the time per file * number of pending files + 1 second per additional request
file_eta_seconds = (diff_time / previous_done_files) * progress_status.pending_files + progress_status.pending_requests
# we assume additional network requests based on the ratio of requests/files * pending files
# to estimate an upper bound (e.g. fetch cover, lookup, scan)
network_eta_seconds = progress_status.pending_requests + (previous_done_requests / previous_done_files) * progress_status.pending_files
# general eta (biased towards whatever takes longer)
eta_seconds = max(network_eta_seconds, file_eta_seconds)
# estimate progress
self._last_progress = diff_time / (diff_time + eta_seconds)
self.set_eta(eta_seconds)
def reset_counters(self):
self._last_progress = 0
self._max_pending_requests = 0
self._last_pending_requests = 0
self._max_pending_files = 0
self._last_pending_files = 0
self._prev_time = time.time()
def get_progress(self):
return self._last_progress
def set_eta(self, eta_seconds):
if eta_seconds > 0:
self.val1.setText(get_timestamp(eta_seconds))
self.val1.show()
self.label1.show()
else:
self.hide_eta()
def hide_eta(self):
self.val1.hide()
self.label1.hide()
def set_files(self, num):
self.val2.setText(str(num))
def set_albums(self, num):
self.val3.setText(str(num))
def set_pending_files(self, num):
self.val4.setText(str(num))
def set_pending_requests(self, num):
if num <= 0:
enabled = QtGui.QIcon.Mode.Disabled
else:
enabled = QtGui.QIcon.Mode.Normal
self.label5.setPixmap(self.icon_download.pixmap(self._size, enabled))
self.val5.setText(str(num))
| 6,637
|
Python
|
.py
| 141
| 39.319149
| 147
| 0.669245
|
metabrainz/picard
| 3,687
| 383
| 10
|
GPL-2.0
|
9/5/2024, 5:11:02 PM (Europe/Amsterdam)
|