Exemple #1
0
def download(request, filename_hash, id, slug, extension):
    closedcaptions = get_object_or_404(
        ClosedCaptions,
        id=id,
        event__slug__iexact=slug,
    )
    if extension not in FILE_EXTENSIONS.values():
        raise http.Http404('Unrecognized extension')
    if closedcaptions.filename_hash != filename_hash:
        raise http.Http404('Unrecognized hash')

    for key, ext in FILE_EXTENSIONS.items():
        if ext == extension:
            output_writer = SUPPORTED_WRITERS[key]
    content = closedcaptions.file.read()
    if not (closedcaptions.file.name.lower().endswith('.ttml')
            or closedcaptions.file.name.lower().endswith('.dfxp')):
        content = content.decode('utf-8')

    reader = pycaption.detect_format(content)
    assert reader
    converter = pycaption.CaptionConverter()
    converter.read(content, reader())
    response = http.HttpResponse()
    response['Content-Type'] = CONTENT_TYPES.get(extension, 'text/plain')
    response.write(converter.write(output_writer()))
    return response
Exemple #2
0
 def select_subtitles_file(self, fn):
   if not os.path.isfile(fn):
     def f():
       dialog = Gtk.MessageDialog(self.win, 0, Gtk.MessageType.ERROR, Gtk.ButtonsType.CLOSE, "File Not Found")
       dialog.format_secondary_text("Could not find subtitles file: %s" % fn)
       dialog.run()
       dialog.destroy()
     GLib.idle_add(f)
     return
   fn = os.path.abspath(fn)
   ext = fn.split('.')[-1]
   display_name = os.path.basename(fn)
   if ext=='vtt':
     with open(fn) as f:
       self.subtitles = f.read()
   else:
     with open(fn,'rb') as f:
       caps = f.read()
       try: caps = caps.decode()
       except UnicodeDecodeError: caps = caps.decode('latin-1')
     if caps.startswith('\ufeff'): # BOM
       caps = caps[1:]
     converter = pycaption.CaptionConverter()
     converter.read(caps, pycaption.detect_format(caps)())
     self.subtitles = converter.write(pycaption.WebVTTWriter())
   pos = len(self.subtitle_store)
   self.subtitle_store.append([display_name, pos-2, self.subtitles])
   self.subtitle_combo.set_active(pos)
Exemple #3
0
    def gen_thumbnail(self):
        container = self.fn.lower().split(".")[-1]
        thumbnail_fn = None
        subtitle_ids = []
        if container in ('aac', 'mp3', 'wav'):
            cmd = ['ffmpeg', '-i', self.fn, '-f', 'ffmetadata', '-']
        else:
            thumbnail_fn = tempfile.mkstemp(suffix='.jpg',
                                            prefix='gnomecast_thumbnail_')[1]
            os.remove(thumbnail_fn)
            cmd = [
                'ffmpeg', '-y', '-i', self.fn, '-f', 'mjpeg', '-vframes', '1',
                '-ss', '27', '-vf', 'scale=600:-1', thumbnail_fn
            ]
        self.ffmpeg_desc = output = subprocess.check_output(
            cmd, stderr=subprocess.STDOUT)
        for line in output.decode().split('\n'):
            line = line.strip()
            if line.startswith('Duration:'):
                self.duration = parse_ffmpeg_time(line.split()[1].strip(','))
            if line.startswith('Stream') and 'Subtitle' in line:
                id = line.split()[1].strip('#').replace(':', '.')
                id = id[:id.index('(')]
                subtitle_ids.append(id)
        print('subtitle_ids', subtitle_ids)

        def f():
            if thumbnail_fn:
                self.thumbnail_image.set_from_file(thumbnail_fn)
                os.remove(thumbnail_fn)
                self.win.resize(1, 1)
            self.update_status()

        GLib.idle_add(f)
        new_subtitles = []
        for subtitle_id in subtitle_ids:
            srt_fn = tempfile.mkstemp(suffix='.srt',
                                      prefix='gnomecast_subtitles_')[1]
            output = subprocess.check_output([
                'ffmpeg', '-y', '-i', self.fn, '-vn', '-an',
                '-codec:s:%s' % subtitle_id, 'srt', srt_fn
            ],
                                             stderr=subprocess.STDOUT)
            with open(srt_fn) as f:
                caps = f.read()
            print('caps', caps)
            converter = pycaption.CaptionConverter()
            converter.read(caps, pycaption.detect_format(caps)())
            subtitles = converter.write(pycaption.WebVTTWriter())
            new_subtitles.append((subtitle_id, subtitles))
            os.remove(srt_fn)

        def f():
            pos = len(self.subtitle_store)
            for id, subs in new_subtitles:
                self.subtitle_store.append([id, pos - 2, subs])
                pos += 1

        GLib.idle_add(f)
Exemple #4
0
def convert_file(input_captions, output_writer):
    reader = pycaption.detect_format(input_captions)

    if not reader:
        raise RuntimeError('Unrecognized format')

    converter = pycaption.CaptionConverter()
    converter.read(input_captions, reader())
    return converter.write(output_writer)
def test_captions():
	srt_caps = '''1
	00:00:09,209 --> 00:00:12,312
	This is an example SRT file,which, while extremely short,is still a valid SRT file.


	2
	00:00:19,209 --> 00:00:22,312
	This is an example SRT file,which, while extremely short,is still a valid SRT file.
	'''
	converter = pycaption.CaptionConverter()
	converter.read(srt_caps,pycaption.SRTReader())
	print(converter.write(pycaption.WebVTTWriter()))
Exemple #6
0
 def select_subtitles_file(self, fn):
     ext = fn.split('.')[-1]
     display_name = os.path.basename(fn)
     if ext == 'vtt':
         with open(fn) as f:
             self.subtitles = f.read()
     else:
         with open(fn) as f:
             caps = f.read()
         if caps.startswith('\ufeff'):  # BOM
             caps = caps[1:]
         converter = pycaption.CaptionConverter()
         converter.read(caps, pycaption.detect_format(caps)())
         self.subtitles = converter.write(pycaption.WebVTTWriter())
     pos = len(self.subtitle_store)
     self.subtitle_store.append([display_name, pos - 2, self.subtitles])
     self.subtitle_combo.set_active(pos)
Exemple #7
0
 def update_subtitles(self):
   subtitle_ids = []
   cmd = ['ffprobe', '-i', self.fn]
   output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
   for line in output.decode().split('\n'):
     line = line.strip()
     if line.startswith('Stream') and 'Subtitle' in line:
       id = line.split()[1].strip('#').replace(':','.')
       id = id[:id.index('(')]
       subtitle_ids.append(id)
   print('subtitle_ids', subtitle_ids)
   new_subtitles = []
   for subtitle_id in subtitle_ids:
     srt_fn = tempfile.mkstemp(suffix='.srt', prefix='gnomecast_subtitles_')[1]
     output = subprocess.check_output(['ffmpeg', '-y', '-i', self.fn, '-vn', '-an', '-codec:s:%s' % subtitle_id, 'srt', srt_fn], stderr=subprocess.STDOUT)
     with open(srt_fn) as f:
       caps = f.read()
     #print('caps', caps)
     converter = pycaption.CaptionConverter()
     converter.read(caps, pycaption.detect_format(caps)())
     subtitles = converter.write(pycaption.WebVTTWriter())
     new_subtitles.append((subtitle_id, subtitles))
     os.remove(srt_fn)
   def f():
     self.subtitle_store.clear()
     self.subtitle_store.append(["No subtitles.", -1, None])
     self.subtitle_store.append(["Add subtitle file...", -2, None])
     self.subtitle_combo.set_active(0)
     pos = len(self.subtitle_store)
     for id, subs in new_subtitles:
       self.subtitle_store.append([id, pos-2, subs])
       pos += 1
   GLib.idle_add(f)
   ext = self.fn.split('.')[-1]
   sexts = ['vtt', 'srt']
   for sext in sexts:
     if os.path.isfile(self.fn[:-len(ext)] + sext):
       self.select_subtitles_file(self.fn[:-len(ext)] + sext) 
       break
def event_closed_captions_submit(request, event_id, id):
    event = get_object_or_404(Event, id=event_id)
    closedcaptions = get_object_or_404(ClosedCaptions, event=event, id=id)

    # XXX This might change. Instead of using the same tag as the one
    # being used, we might use a custom one just for the transcription
    # service.
    submission, = VidlySubmission.objects.filter(
        event=event, tag=event.template_environment['tag'])

    if request.method == 'POST':
        form = forms.SubmitClosedCaptionsForm(request.POST)
        if form.is_valid():
            file_format = form.cleaned_data['file_format']
            base_url = get_base_url(request)
            public_url = base_url + reverse('closedcaptions:download',
                                            args=(
                                                closedcaptions.filename_hash,
                                                closedcaptions.id,
                                                event.slug,
                                                file_format,
                                            ))

            # Send it in
            vidly.update_media_closed_captions(
                submission.tag,
                submission.url,
                public_url,
                hd=submission.hd,
                notify_url=None  # XXX improve this some day
            )
            if not closedcaptions.submission_info:
                closedcaptions.submission_info = {}
            if not closedcaptions.submission_info.get('submissions'):
                closedcaptions.submission_info['submissions'] = []
            closedcaptions.submission_info['submissions'].append({
                'tag':
                submission.tag,
                'url':
                submission.url,
                'public_url':
                public_url,
                'hd':
                submission.hd,
                'date':
                timezone.now().isoformat(),
            })
            closedcaptions.save()
            messages.success(
                request,
                '{} submitted for Vid.ly transcoding'.format(public_url))
            return redirect('manage:event_closed_captions', event.id)
    else:
        form = forms.SubmitClosedCaptionsForm()

    content = closedcaptions.file.read()
    reader = pycaption.detect_format(content)
    converter = pycaption.CaptionConverter()
    converter.read(content, reader())
    last_caption = converter.write(LastTimestampWriter()) / 1000000

    context = {
        'form': form,
        'event': closedcaptions.event,
        'closedcaptions': closedcaptions,
        'last_caption': last_caption,
        'submission': submission,
    }
    return render(request, 'manage/event_closed_captions_submit.html', context)