MoviePy в Django: не удалось прочитать продолжительность файла

Я пытаюсь передать видеоданные, извлеченные из ModelsForm, в метод moviepy, однако функция VideoFileClip() не может прочитать продолжительность файла.

Я проверил данные, которые ввожу, и это правильное имя. В настоящее время проблема может заключаться в том, что я передаю ее в виде строки. Однако без этого он возвращает ошибку: объект «Разделитель» не имеет атрибута «заканчивается».

Пожалуйста, смотрите ошибку и мой код ниже. Спасибо за вашу помощь!

Код Models.py

Сообщение об ошибке

OSError at /highlights/
MoviePy error: failed to read the duration of file <highlights.splitter.Splitter object at 0x000001A82CE553D0>.
Here are the file infos returned by ffmpeg:

ffmpeg version 4.1 Copyright (c) 2000-2018 the FFmpeg developers
  built with gcc 8.2.1 (GCC) 20181017
  configuration: --enable-gpl --enable-version3 --enable-sdl2 --enable-fontconfig --enable-gnutls --enable-iconv --enable-libass --enable-libbluray --enable-libfreetype --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-libopus --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libtheora --enable-libtwolame --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libzimg --enable-lzma --enable-zlib --enable-gmp --enable-libvidstab --enable-libvorbis --enable-libvo-amrwbenc --enable-libmysofa --enable-libspeex --enable-libxvid --enable-libaom --enable-libmfx --enable-amf --enable-ffnvcodec --enable-cuvid --enable-d3d11va --enable-nvenc --enable-nvdec --enable-dxva2 --enable-avisynth
  libavutil      56. 22.100 / 56. 22.100
  libavcodec     58. 35.100 / 58. 35.100
  libavformat    58. 20.100 / 58. 20.100
  libavdevice    58.  5.100 / 58.  5.100
  libavfilter     7. 40.101 /  7. 40.101
  libswscale      5.  3.100 /  5.  3.100
  libswresample   3.  3.100 /  3.  3.100
  libpostproc    55.  3.100 / 55.  3.100
<highlights.splitter.Splitter object at 0x000001A82CE553D0>: Invalid argument
Request Method: POST
Request URL:    http://127.0.0.1:8000/highlights/
Django Version: 3.0.1
Exception Type: OSError
Exception Value:    
MoviePy error: failed to read the duration of file <highlights.splitter.Splitter object at 0x000001A82CE553D0>.
Here are the file infos returned by ffmpeg:

ffmpeg version 4.1 Copyright (c) 2000-2018 the FFmpeg developers
  built with gcc 8.2.1 (GCC) 20181017
  configuration: --enable-gpl --enable-version3 --enable-sdl2 --enable-fontconfig --enable-gnutls --enable-iconv --enable-libass --enable-libbluray --enable-libfreetype --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-libopus --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libtheora --enable-libtwolame --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libzimg --enable-lzma --enable-zlib --enable-gmp --enable-libvidstab --enable-libvorbis --enable-libvo-amrwbenc --enable-libmysofa --enable-libspeex --enable-libxvid --enable-libaom --enable-libmfx --enable-amf --enable-ffnvcodec --enable-cuvid --enable-d3d11va --enable-nvenc --enable-nvdec --enable-dxva2 --enable-avisynth
  libavutil      56. 22.100 / 56. 22.100
  libavcodec     58. 35.100 / 58. 35.100
  libavformat    58. 20.100 / 58. 20.100
  libavdevice    58.  5.100 / 58.  5.100
  libavfilter     7. 40.101 /  7. 40.101
  libswscale      5.  3.100 /  5.  3.100
  libswresample   3.  3.100 /  3.  3.100
  libpostproc    55.  3.100 / 55.  3.100
<highlights.splitter.Splitter object at 0x000001A82CE553D0>: Invalid argument
Exception Location: C:\Program Files\Python38\lib\site-packages\moviepy\video\io\ffmpeg_reader.py in ffmpeg_parse_infos, line 289
Python Executable:  C:\Program Files\Python38\python.exe
Python Version: 3.8.0
Python Path:    
['C:\\Users\\User\\Documents\\Codes\\highlightreel',
 'C:\\Program Files\\Python38\\python38.zip',
 'C:\\Program Files\\Python38\\DLLs',
 'C:\\Program Files\\Python38\\lib',
 'C:\\Program Files\\Python38',
 'C:\\Program Files\\Python38\\lib\\site-packages',
 'C:\\Program Files\\Python38\\lib\\site-packages\\IPython\\extensions']
Server time:    Wed, 1 Apr 2020 20:04:23 +0000

Отслеживание

Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/highlights/

Django Version: 3.0.1
Python Version: 3.8.0
Installed Applications:
['highlights.apps.HighlightsConfig',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback (most recent call last):
  File "C:\Program Files\Python38\lib\site-packages\moviepy\video\io\ffmpeg_reader.py", line 285, in ffmpeg_parse_infos
    line = [l for l in lines if keyword in l][index]

During handling of the above exception (list index out of range), another exception occurred:
  File "C:\Program Files\Python38\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Program Files\Python38\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Program Files\Python38\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\User\Documents\Codes\highlightreel\highlights\views.py", line 17, in video_form_upload
    Splitter(val)
  File "C:\Users\User\Documents\Codes\highlightreel\highlights\splitter.py", line 18, in __init__
    clip = mp.VideoFileClip(str(file))
  File "C:\Program Files\Python38\lib\site-packages\moviepy\video\io\VideoFileClip.py", line 88, in __init__
    self.reader = FFMPEG_VideoReader(filename, pix_fmt=pix_fmt,
  File "C:\Program Files\Python38\lib\site-packages\moviepy\video\io\ffmpeg_reader.py", line 35, in __init__
    infos = ffmpeg_parse_infos(filename, print_infos, check_duration,
  File "C:\Program Files\Python38\lib\site-packages\moviepy\video\io\ffmpeg_reader.py", line 289, in ffmpeg_parse_infos
    raise IOError(("MoviePy error: failed to read the duration of file %s.\n"

Exception Type: OSError at /highlights/
Exception Value: MoviePy error: failed to read the duration of file <highlights.splitter.Splitter object at 0x000001A82CE553D0>.
Here are the file infos returned by ffmpeg:

ffmpeg version 4.1 Copyright (c) 2000-2018 the FFmpeg developers
  built with gcc 8.2.1 (GCC) 20181017
  configuration: --enable-gpl --enable-version3 --enable-sdl2 --enable-fontconfig --enable-gnutls --enable-iconv --enable-libass --enable-libbluray --enable-libfreetype --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-libopus --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libtheora --enable-libtwolame --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libzimg --enable-lzma --enable-zlib --enable-gmp --enable-libvidstab --enable-libvorbis --enable-libvo-amrwbenc --enable-libmysofa --enable-libspeex --enable-libxvid --enable-libaom --enable-libmfx --enable-amf --enable-ffnvcodec --enable-cuvid --enable-d3d11va --enable-nvenc --enable-nvdec --enable-dxva2 --enable-avisynth
  libavutil      56. 22.100 / 56. 22.100
  libavcodec     58. 35.100 / 58. 35.100
  libavformat    58. 20.100 / 58. 20.100
  libavdevice    58.  5.100 / 58.  5.100
  libavfilter     7. 40.101 /  7. 40.101
  libswscale      5.  3.100 /  5.  3.100
  libswresample   3.  3.100 /  3.  3.100
  libpostproc    55.  3.100 / 55.  3.100
<highlights.splitter.Splitter object at 0x000001A82CE553D0>: Invalid argument

ОБНОВЛЕНИЕ

Код

Ошибка

AttributeError at /highlights/
'Splitter' object has no attribute 'endswith'
Request Method: POST
Request URL:    http://127.0.0.1:8000/highlights/
Django Version: 3.0.1
Exception Type: AttributeError
Exception Value:    
'Splitter' object has no attribute 'endswith'
Exception Location: C:\Program Files\Python38\lib\site-packages\moviepy\video\io\ffmpeg_reader.py in ffmpeg_parse_infos, line 244
Python Executable:  C:\Program Files\Python38\python.exe
Python Version: 3.8.0
Python Path:    
['C:\\Users\\User\\Documents\\Codes\\highlightreel',
 'C:\\Program Files\\Python38\\python38.zip',
 'C:\\Program Files\\Python38\\DLLs',
 'C:\\Program Files\\Python38\\lib',
 'C:\\Program Files\\Python38',
 'C:\\Program Files\\Python38\\lib\\site-packages',
 'C:\\Program Files\\Python38\\lib\\site-packages\\IPython\\extensions']
Server time:    Thu, 2 Apr 2020 00:57:52 +0000

Отслеживание

Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/highlights/

Django Version: 3.0.1
Python Version: 3.8.0
Installed Applications:
['highlights.apps.HighlightsConfig',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback (most recent call last):
  File "C:\Program Files\Python38\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Program Files\Python38\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Program Files\Python38\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\User\Documents\Codes\highlightreel\highlights\views.py", line 16, in video_form_upload
    splitter = Splitter(instance.video.path)
  File "C:\Users\User\Documents\Codes\highlightreel\highlights\splitter.py", line 20, in __init__
    clip = mp.VideoFileClip(file)
  File "C:\Program Files\Python38\lib\site-packages\moviepy\video\io\VideoFileClip.py", line 88, in __init__
    self.reader = FFMPEG_VideoReader(filename, pix_fmt=pix_fmt,
  File "C:\Program Files\Python38\lib\site-packages\moviepy\video\io\ffmpeg_reader.py", line 35, in __init__
    infos = ffmpeg_parse_infos(filename, print_infos, check_duration,
  File "C:\Program Files\Python38\lib\site-packages\moviepy\video\io\ffmpeg_reader.py", line 244, in ffmpeg_parse_infos
    is_GIF = filename.endswith('.gif')

Exception Type: AttributeError at /highlights/
Exception Value: 'Splitter' object has no attribute 'endswith'

person Silreth    schedule 01.04.2020    source источник
comment
Я проверил исходный код пакетов, которые вы используете, и передача имени файла кажется правильным способом вызова VideoFileClip   -  person Grand Phuba    schedule 01.04.2020


Ответы (1)


Кажется, вы передаете только имя файла загруженного видео, когда вы должны передать весь путь к файлу.

Попробуйте что-нибудь из следующего, но что бы это ни было, проблема, похоже, в том, что библиотеки не могут загрузить правильный файл. Сначала убедитесь, что видео загружаются в вашу медиа-папку. Если вы можете это проверить, то вы знаете, что теперь дело только за его загрузкой.

Вариант 1 - изменить представление

В представлении video_form_upload попробуйте следующее

def video_form_upload(request):
    if request.method == 'POST':
        form = VideoForm(request.POST, request.FILES)
        if form.is_valid():
             instance = form.save()  # get the saved model
             splitter = Splitter(instance.video.path)  # get the video file from the saved model
             return redirect(`highlights`)
    ...

Вариант 2 - Сменить разветвитель

В вашем классе Splitter, строка 18, попробуйте изменить ее с

clip = mp.VideoFileClip(str(file))

to

clip = mp.VideoFileClip(file.path)
person Grand Phuba    schedule 01.04.2020
comment
Это имело бы смысл! Хотя похоже, что путь не существует: AttributeError at /highlights/ Объект «Разделитель» не имеет атрибута «путь». Есть ли лучший способ работать с загруженным видео? - person Silreth; 02.04.2020
comment
Пробовал вариант один, и он проходит правильно, но возвращается к ошибке продолжительности. Я проверил, что видео нормально загружается в правильное место, кажется, оно изо всех сил пытается загрузить его: / Есть ли другие идеи, случайно? - person Silreth; 02.04.2020
comment
Удалось ли вам подтвердить, что вы передаете абсолютный путь к файлу? - person Grand Phuba; 02.04.2020
comment
на самом деле я вывел то, что он передает и через что он отправляет: ‹highlights.splitter.Splitter object at 0x000002313C68A490›, а не путь - person Silreth; 02.04.2020
comment
Можете ли вы отправить скриншот вашего текущего кода с операторами печати/журнала и выводом - person Grand Phuba; 02.04.2020