remove extrenal librarian from tags.
[wolnelektury.git] / scripts / irename.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
4 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
5 #
6 from django.core.management import setup_environ
7 from wolnelektury import settings
8 import sys
9 from os.path import abspath, join, dirname, splitext
10 import os
11
12 # Add apps and lib directories to PYTHONPATH
13 sys.path.insert(0, abspath(join(dirname(__file__), 'apps')))
14 sys.path.insert(0, abspath(join(dirname(__file__), 'lib')))
15
16 setup_environ(settings)
17
18 from catalogue.models import Book
19 from mutagen import easyid3
20 from slughifi import slughifi
21
22 chosen_book_slugs = set()
23
24 for file_name in os.listdir('mp3'):
25     base_name, ext = splitext(file_name)
26     if ext != '.mp3':
27         continue
28
29     audio = easyid3.EasyID3(join('mp3', file_name))
30     title = audio['title'][0]
31     artist = title.split(',', 1)[0].strip()
32     artist_slug = slughifi(artist)
33     title_part = slughifi(title.rsplit(',', 1)[1].strip())
34
35     print "--------------------"
36     print "File: %s" % file_name
37     print "Title: %s" % title
38     print
39     print "Matching books:"
40
41     matching_books = [book for book in Book.tagged.with_all(artist_slug) if book.slug not in chosen_book_slugs]
42     matching_books = [book for book in matching_books if title_part in book.slug]
43
44     if len(matching_books) > 1:
45         for i, book in enumerate(matching_books):
46             print "%d: %s (%s)" % (i, book.title, ', '.join(tag.slug for tag in book.tags))
47         print
48         i = int(input("Choose which book is read in this file:"))
49     elif len(matching_books) == 1:
50         i = 0
51     else:
52         print "Skipping %s: No matching book found" % file_name
53         continue
54
55     print "You chose %d (%s)" % (i, matching_books[i].slug)
56
57     chosen_book_slugs.add(matching_books[i].slug)
58     os.rename(join('mp3', file_name), join('new_mp3', matching_books[i].slug + '.mp3'))
59     os.rename(join('oggvorbis', base_name + '.ogg'), join('new_ogg', matching_books[i].slug + '.ogg'))
60