Commit 52778805 authored by fred's avatar fred

trivial: apply black

parent 8a495254
from django.contrib import admin
from .models import Emission, Episode, Category, Colour, Schedule, \
SoundFile, NewsItem, NewsCategory, Nonstop, Focus, Format
from .models import (
Emission,
Episode,
Category,
Colour,
Schedule,
SoundFile,
NewsItem,
NewsCategory,
Nonstop,
Focus,
Format,
)
class EmissionAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',)}
admin.site.register(Emission, EmissionAdmin)
class EpisodeAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',)}
admin.site.register(Episode, EpisodeAdmin)
class CategoryAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',)}
admin.site.register(Category, CategoryAdmin)
class ColourAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',)}
admin.site.register(Colour, ColourAdmin)
class ScheduleAdmin(admin.ModelAdmin):
pass
admin.site.register(Schedule, ScheduleAdmin)
class NewsCategoryAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',)}
admin.site.register(NewsCategory, NewsCategoryAdmin)
class NewsItemAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',)}
admin.site.register(NewsItem, NewsItemAdmin)
class SoundFileAdmin(admin.ModelAdmin):
pass
admin.site.register(SoundFile, SoundFileAdmin)
class NonstopAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',)}
admin.site.register(Nonstop, NonstopAdmin)
class FocusAdmin(admin.ModelAdmin):
pass
admin.site.register(Focus, FocusAdmin)
class FormatAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',)}
admin.site.register(Format, FormatAdmin)
......@@ -18,8 +18,7 @@ from django.template.loader import render_to_string
from taggit.forms import TagWidget
from .models import (Emission, Episode, Diffusion, Schedule, SoundFile,
NewsItem, Absence, PlaylistElement)
from .models import Emission, Episode, Diffusion, Schedule, SoundFile, NewsItem, Absence, PlaylistElement
from .utils import get_duration
from .widgets import DateTimeWidget, DateWidget
......@@ -31,8 +30,15 @@ def slugify(s):
class DayAndHourWidget(forms.MultiWidget):
def __init__(self, attrs=None):
WEEKDAYS = [_('Monday'), _('Tuesday'), _('Wednesday'), _('Thursday'),
_('Friday'), _('Saturday'), _('Sunday')]
WEEKDAYS = [
_('Monday'),
_('Tuesday'),
_('Wednesday'),
_('Thursday'),
_('Friday'),
_('Saturday'),
_('Sunday'),
]
widgets = (
forms.Select(attrs=attrs, choices=([(weekday, WEEKDAYS[weekday]) for weekday in range(7)])),
forms.Select(attrs=attrs, choices=([(hour, hour) for hour in range(24)])),
......@@ -50,11 +56,11 @@ class DayAndHourWidget(forms.MultiWidget):
# datetime value to store that; we pick 2007 as reference year as
# it had its January 1st on a Monday.
data_list = [
widget.value_from_datadict(data, files, name + '_%s' % i)
for i, widget in enumerate(self.widgets)]
widget.value_from_datadict(data, files, name + '_%s' % i) for i, widget in enumerate(self.widgets)
]
if data_list:
return datetime.datetime(2007, 1, int(data_list[0])+1, int(data_list[1]), int(data_list[2]))
return datetime.datetime(2007, 1, int(data_list[0]) + 1, int(data_list[1]), int(data_list[2]))
return None
......@@ -63,19 +69,23 @@ class JqueryFileUploadFileInput(forms.FileInput):
def get_context(self, name, value, attrs):
context = super(JqueryFileUploadFileInput, self).get_context(name, value, attrs)
context['widget'].update({
'upload_url': self.url,
'files': self.files,
'STATIC_URL': settings.STATIC_URL}
context['widget'].update(
{'upload_url': self.url, 'files': self.files, 'STATIC_URL': settings.STATIC_URL}
)
return context
def render(self, name, value, attrs=None):
output = render_to_string('emissions/upload.html', {'widget': {
'upload_url': self.url,
'files': self.files,
'name': name,
'STATIC_URL': settings.STATIC_URL}})
output = render_to_string(
'emissions/upload.html',
{
'widget': {
'upload_url': self.url,
'files': self.files,
'name': name,
'STATIC_URL': settings.STATIC_URL,
}
},
)
return mark_safe(output)
......@@ -86,8 +96,7 @@ class JqueryFileUploadInput(forms.MultiWidget):
def __init__(self, attrs=None, choices=[], max_filename_length=None):
self.max_filename_length = max_filename_length
widget_list = (forms.HiddenInput(attrs=attrs),
JqueryFileUploadFileInput(attrs=attrs))
widget_list = (forms.HiddenInput(attrs=attrs), JqueryFileUploadFileInput(attrs=attrs))
super(JqueryFileUploadInput, self).__init__(widget_list, attrs)
def decompress(self, value):
......@@ -110,11 +119,11 @@ class JqueryFileUploadInput(forms.MultiWidget):
yield storage.open(os.path.join(path, name))
def value_from_datadict(self, data, files, name):
'''
If some file was submitted, that's the value,
If a regular hidden_id is present, use it to find uploaded files,
otherwise return an empty list
'''
"""
If some file was submitted, that's the value,
If a regular hidden_id is present, use it to find uploaded files,
otherwise return an empty list
"""
upload_id, file_input = super(JqueryFileUploadInput, self).value_from_datadict(data, files, name)
if file_input:
pass
......@@ -154,8 +163,7 @@ class EpisodeForm(forms.ModelForm):
class Meta:
model = Episode
exclude = ('slug', 'has_focus', 'got_focus', 'effective_start', 'effective_end')
widgets = {'emission': forms.HiddenInput(),
'tags': TagWidget()}
widgets = {'emission': forms.HiddenInput(), 'tags': TagWidget()}
def save(self, commit=True):
if not self.instance.slug:
......@@ -175,21 +183,18 @@ class EpisodeForm(forms.ModelForm):
class EpisodeNewForm(EpisodeForm):
first_diffusion = forms.DateTimeField(label=_('First Diffusion'),
widget=DateTimeWidget)
second_diffusion = forms.DateTimeField(label=_('Second Diffusion'),
widget=DateTimeWidget)
third_diffusion = forms.DateTimeField(label=_('Third Diffusion'),
widget=DateTimeWidget)
fourth_diffusion = forms.DateTimeField(label=_('Fourth Diffusion'),
widget=DateTimeWidget)
first_diffusion = forms.DateTimeField(label=_('First Diffusion'), widget=DateTimeWidget)
second_diffusion = forms.DateTimeField(label=_('Second Diffusion'), widget=DateTimeWidget)
third_diffusion = forms.DateTimeField(label=_('Third Diffusion'), widget=DateTimeWidget)
fourth_diffusion = forms.DateTimeField(label=_('Fourth Diffusion'), widget=DateTimeWidget)
def get_diffusion_fields(self, emission):
if emission:
schedules = list(Schedule.objects.filter(emission=emission).order_by('datetime'))
if len(schedules) > 1 and (
schedules[0].weeks == schedules[1].weeks and
schedules[0].datetime.date() == schedules[1].datetime.date()):
schedules[0].weeks == schedules[1].weeks
and schedules[0].datetime.date() == schedules[1].datetime.date()
):
# special case for daily program with same-day rerun
schedules = 2
else:
......@@ -228,8 +233,8 @@ class ScheduleForm(forms.ModelForm):
model = Schedule
exclude = ()
widgets = {
'emission': forms.HiddenInput(),
'datetime': DayAndHourWidget(),
'emission': forms.HiddenInput(),
'datetime': DayAndHourWidget(),
}
......@@ -238,8 +243,8 @@ class SoundFileForm(forms.ModelForm):
model = SoundFile
exclude = ('has_focus', 'got_focus', 'duration')
widgets = {
'episode': forms.HiddenInput(),
'file': JqueryFileUploadInput(),
'episode': forms.HiddenInput(),
'file': JqueryFileUploadInput(),
}
def clean(self):
......@@ -255,7 +260,7 @@ class SoundFileEditForm(forms.ModelForm):
model = SoundFile
exclude = ('has_focus', 'got_focus', 'file', 'duration')
widgets = {
'episode': forms.HiddenInput(),
'episode': forms.HiddenInput(),
}
def __init__(self, *args, **kwargs):
......@@ -285,8 +290,8 @@ class DiffusionForm(forms.ModelForm):
model = Diffusion
exclude = ()
widgets = {
'episode': forms.HiddenInput(),
'datetime': DateTimeWidget(),
'episode': forms.HiddenInput(),
'datetime': DateTimeWidget(),
}
def __init__(self, *args, **kwargs):
......@@ -306,11 +311,12 @@ class NewsItemForm(forms.ModelForm):
class Meta:
model = NewsItem
exclude = ('slug', 'has_focus', 'got_focus')
widgets = {'tags': TagWidget(),
'date': DateWidget(),
'expiration_date': DateWidget(),
'event_date': DateWidget(),
}
widgets = {
'tags': TagWidget(),
'date': DateWidget(),
'expiration_date': DateWidget(),
'event_date': DateWidget(),
}
def __init__(self, *args, **kwargs):
super(NewsItemForm, self).__init__(*args, **kwargs)
......@@ -357,7 +363,7 @@ class AbsenceForm(forms.ModelForm):
model = Absence
exclude = ()
widgets = {
'emission': forms.HiddenInput(),
'emission': forms.HiddenInput(),
}
def __init__(self, *args, **kwargs):
......@@ -365,7 +371,7 @@ class AbsenceForm(forms.ModelForm):
emission = kwargs.get('initial', {}).get('emission')
user = kwargs.get('initial', {}).get('user')
self.fields['datetime'].widget.emission = emission
if (user and user.has_perm('emissions.delete_diffusion')):
if user and user.has_perm('emissions.delete_diffusion'):
date = emission.get_next_planned_date()
self.fields['datetime'].initial = date
self.fields['datetime'].widget = DateTimeWidget()
......@@ -375,8 +381,8 @@ class AbsenceForm(forms.ModelForm):
def save(self, commit=True):
t = super(AbsenceForm, self).save(commit=commit)
for i, schedule in enumerate(
Schedule.objects.filter(emission=self.instance.emission,
rerun=True).order_by('datetime')):
Schedule.objects.filter(emission=self.instance.emission, rerun=True).order_by('datetime')
):
rerun_date = schedule.get_next_planned_date(self.instance.datetime)
rerun_absence = Absence()
rerun_absence.emission = self.instance.emission
......@@ -390,6 +396,6 @@ class PlaylistElementForm(forms.ModelForm):
model = PlaylistElement
exclude = ('title', 'notes', 'order')
widgets = {
'episode': forms.HiddenInput(),
'sound': JqueryFileUploadInput(),
'episode': forms.HiddenInput(),
'sound': JqueryFileUploadInput(),
}
This diff is collapsed.
......@@ -7,15 +7,11 @@ from ...models import Emission
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('--emission',
dest='emission_slug',
metavar='SLUG',
default=None)
parser.add_argument('--emission', dest='emission_slug', metavar='SLUG', default=None)
def handle(self, emission_slug, verbosity, **options):
self.verbose = (verbosity > 1)
self.verbose = verbosity > 1
emissions = Emission.objects.all()
if emission_slug:
emissions = emissions.filter(slug=emission_slug)
......
......@@ -13,11 +13,13 @@ from ...models import SoundFile
def get_bitrate(filename):
p = subprocess.Popen(['mediainfo', '--Inform=Audio;%BitRate%', filename],
close_fds=True,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
p = subprocess.Popen(
['mediainfo', '--Inform=Audio;%BitRate%', filename],
close_fds=True,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
stdout, stderr = p.communicate()
try:
return int(stdout) / 1000
......@@ -26,46 +28,45 @@ def get_bitrate(filename):
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
'--force',
action='store_true',
dest='force',
default=False,
help='Create files even if they exist')
parser.add_argument('--reset-metadata',
help='Create files even if they exist',
)
parser.add_argument(
'--reset-metadata',
action='store_true',
dest='reset_metadata',
default=False,
help='Reset metadata on all files')
parser.add_argument('--emission',
help='Reset metadata on all files',
)
parser.add_argument(
'--emission',
dest='emission',
metavar='EMISSION',
default=None,
help='Process files belonging to emission only')
parser.add_argument('--episode',
help='Process files belonging to emission only',
)
parser.add_argument(
'--episode',
dest='episode',
metavar='EPISODE',
default=None,
help='Process files belonging to episode only')
parser.add_argument('--formats',
dest='formats',
default='ogg,mp3',
help='File formats')
parser.add_argument('--copy',
action='store_true',
dest='copy',
default=False,
help='Copy initial file')
parser.add_argument('--link',
action='store_true',
dest='link',
default=False,
help='Link initial file')
help='Process files belonging to episode only',
)
parser.add_argument('--formats', dest='formats', default='ogg,mp3', help='File formats')
parser.add_argument(
'--copy', action='store_true', dest='copy', default=False, help='Copy initial file'
)
parser.add_argument(
'--link', action='store_true', dest='link', default=False, help='Link initial file'
)
def handle(self, force, reset_metadata, copy, link, emission, episode, verbosity, formats, **kwargs):
self.verbose = (verbosity > 1)
self.verbose = verbosity > 1
self.copy = copy
self.link = link
......@@ -93,7 +94,7 @@ class Command(BaseCommand):
created = self.create(soundfile, format)
if created or reset_metadata:
self.set_metadata(soundfile, format)
if (force or not soundfile.duration):
if force or not soundfile.duration:
soundfile.compute_duration()
if soundfile.duration:
soundfile.save()
......@@ -153,16 +154,14 @@ class Command(BaseCommand):
audio.delete() # strip all existing metadata
if soundfile.fragment is True and soundfile.title:
audio['title'] = '%s - %s' % (
soundfile.episode.title,
soundfile.title)
audio['title'] = '%s - %s' % (soundfile.episode.title, soundfile.title)
else:
audio['title'] = soundfile.episode.title
audio['album'] = soundfile.episode.emission.title
audio['artist'] = 'Radio Panik'
if soundfile.episode.image or soundfile.episode.emission.image:
image = (soundfile.episode.image or soundfile.episode.emission.image)
image = soundfile.episode.image or soundfile.episode.emission.image
image.file.open()
if os.path.splitext(image.path)[1].lower() in ('.jpeg', '.jpg'):
mimetype = 'image/jpeg'
......@@ -178,9 +177,11 @@ class Command(BaseCommand):
elif format == 'mp3':
audio.save()
audio = mutagen.mp3.MP3(file_path)
audio.tags.add(mutagen.id3.APIC(
encoding=3, description='image',
type=3, mime=mimetype, data=image.read()))
audio.tags.add(
mutagen.id3.APIC(
encoding=3, description='image', type=3, mime=mimetype, data=image.read()
)
)
image.close()
audio.save()
......@@ -10,26 +10,31 @@ from ...models import SoundFile
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('--force',
parser.add_argument(
'--force',
action='store_true',
dest='force',
default=False,
help='Create files even if they exist')
parser.add_argument('--emission',
help='Create files even if they exist',
)
parser.add_argument(
'--emission',
dest='emission',
metavar='EMISSION',
default=None,
help='Process files belonging to emission only')
parser.add_argument('--episode',
help='Process files belonging to emission only',
)
parser.add_argument(
'--episode',
dest='episode',
metavar='EPISODE',
default=None,
help='Process files belonging to episode only')
help='Process files belonging to episode only',
)
def handle(self, force, emission, episode, verbosity, **kwargs):
self.verbose = (verbosity > 1)
self.verbose = verbosity > 1
for soundfile in SoundFile.objects.select_related().exclude(podcastable=False):
if emission and soundfile.episode.emission.slug != emission:
......@@ -53,14 +58,32 @@ class Command(BaseCommand):
sound_filename = soundfile.get_format_path('mp3')
if not os.path.exists(sound_filename):
return
cmd = ['sox', sound_filename, '-t', 'raw', '-c', '1', '-r', '4000',
'-e' 'unsigned-integer', '-b', '8', '-']
cmd = [
'sox',
sound_filename,
'-t',
'raw',
'-c',
'1',
'-r',
'4000',
'-e' 'unsigned-integer',
'-b',
'8',
'-',
]
wave_array = subprocess.check_output(cmd)
for filename, n_samples in (('waveform.json', 200), ('waveform-500.json', 500)):
# reduce to $n_samples$ samples of max positive value
if six.PY3:
wave_reduced = [int(max(x)) for x in np.array_split(np.array([max(0, x-128) for x in wave_array]), n_samples)]
wave_reduced = [
int(max(x))
for x in np.array_split(np.array([max(0, x - 128) for x in wave_array]), n_samples)
]
else:
wave_reduced = [max(x) for x in np.array_split(np.array([max(0, ord(x)-128) for x in wave_array]), n_samples)]
wave_reduced = [
max(x)
for x in np.array_split(np.array([max(0, ord(x) - 128) for x in wave_array]), n_samples)
]
file_path = soundfile.get_format_path(filename)
json.dump(wave_reduced, open(file_path, 'w'))
......@@ -18,8 +18,7 @@ from ...models import Emission, Episode, Diffusion, SoundFile
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('filename', metavar='FILENAME', type=str,
help='name of file to import')
parser.add_argument('filename', metavar='FILENAME', type=str, help='name of file to import')
def adjust_slug(self, title):
slug = slugify(title.replace("'", " ").replace("’", " "))
......@@ -32,7 +31,7 @@ class Command(BaseCommand):
return slug.strip('-')
def handle(self, filename, verbosity, **options):
self.verbose = (verbosity > 1)
self.verbose = verbosity > 1
values = json.load(open(filename)).get('episodes').values()
for i, episode_data in enumerate(values):
if not episode_data.get('title'):
......@@ -42,30 +41,33 @@ class Command(BaseCommand):
if not episode_data.get('text') and not episode_data.get('sound'):
continue
if self.verbose:
print('[%5d/%5d] %s' % (i+1, len(values), episode_data['title']))
print('[%5d/%5d] %s' % (i + 1, len(values), episode_data['title']))
emission_slug = self.adjust_slug(episode_data['emission'])
emission, created = Emission.objects.get_or_create(
slug=emission_slug,
defaults={'title': episode_data['emission']})
slug=emission_slug, defaults={'title': episode_data['emission']}
)
if created:
emission.archived = True
emission.save()
episode, created = Episode.objects.get_or_create(
slug=episode_data['path'].split('/')[-1],
emission=emission)
slug=episode_data['path'].split('/')[-1], emission=emission
)
episode.title = episode_data['title']
episode.text = episode_data['text']
episode.creation_timestamp = isodate.parse_datetime(
episode_data['pub_date'].replace(' ', 'T', 1).replace(' ', ''))
episode_data['pub_date'].replace(' ', 'T', 1).replace(' ', '')