Exemple #1
0
    def __call__(self, video: FieldFile):
        # Get the MIME type string of this video.
        videoContentType = magic.from_buffer(video.read(), mime=True)
        # Point the cursor to the beginning of the file.
        video.seek(0)

        if videoContentType not in self.allowedContentTypes:
            raise ValidationError(
                'The file type %(contentType)s is not supported.',
                params={'contentType': videoContentType})
Exemple #2
0
def calculate_file_hash(file: FieldFile) -> str:
    # Together the MemoryFileUploadHandler and TemporaryFileUploadHandler
    # provide Django’s default file upload behavior of reading small files
    # into memory and large ones onto disk.
    # If a file is large file will be an instance of TemporaryUploadedFile,
    # TemporaryUploadedFile.temporary_file_path() returns the full path to the temporary uploaded file.
    # If a file is small file will be an instance of InMemoryUploadedFile.
    file_hash = sha256()
    # Returns True if the uploaded file is big enough to require reading in multiple chunks.
    # By default this will be any file larger than 2.5 megabytes, but that’s configurable;
    if not file.multiple_chunks():
        file_hash.update(file.read())
    else:
        for chunk in file.chunks():
            file_hash.update(chunk)

    return file_hash.hexdigest()
Exemple #3
0
def setup_work_dir(file: FieldFile) -> Tuple[TemporaryDirectory, Path]:
    """Create a temporary directory as working directory and make the source file locally available."""
    temp_dir = TemporaryDirectory()

    try:
        source_file_path = Path(file.path)
    except (AttributeError, NotImplementedError):
        source_file_path = Path(temp_dir.name) / Path(file.name).name

        with source_file_path.open('wb') as fp:
            if file.multiple_chunks():
                for chunk in file.chunks():
                    fp.write(chunk)
            else:
                fp.write(file.read())

    return temp_dir, source_file_path
Exemple #4
0
def get_preview(file: FieldFile) -> bytes:
    """
    Retrieves frame from the middle of video as preview image
    """

    temp_filename = os.path.join(tempfile.gettempdir(), str(uuid.uuid4()))
    with open(temp_filename, "wb") as _file:
        file.seek(0)
        _file.write(file.read())

    capture = cv2.VideoCapture(temp_filename)
    frame_count = int(capture.get(cv2.CAP_PROP_FRAME_COUNT))
    capture.set(cv2.CAP_PROP_POS_FRAMES, round(frame_count / 2))

    capture.grab()
    retval, img = capture.retrieve(0)

    image_bytes = cv2.imencode("temp/preview.jpg", img)[1].tobytes()

    capture.release()

    os.remove(temp_filename)

    return image_bytes
 def _get_dict_reader(self, field_file: FieldFile):
     as_str = field_file.read().decode('utf-8')
     dict_reader = DictReader(StringIO(as_str),
                              delimiter=',',
                              quotechar='"')
     return dict_reader
Exemple #6
0
def read_in_chunks(file: FieldFile, chunk_size=65536):
    while True:
        data = file.read(chunk_size)
        if not data:
            break
        yield data