def clean_and_validate(self, cleaned_data):
        file = cleaned_data.get('file')

        if file:
            # check extension of the data file
            _, fname, ext = split_filename(file.name)
            if not ext.lower() in [".nii.gz", ".nii", ".img"]:
                self._errors["file"] = self.error_class(
                    ["Doesn't have proper extension"]
                )
                del cleaned_data["file"]
                return cleaned_data

            # prepare file to loading into memory
            file.open()
            fileobj = file.file
            if file.name.lower().endswith(".gz"):
                fileobj = GzipFile(filename=file.name, mode='rb',
                                   fileobj=fileobj)

            file_map = {'image': nb.FileHolder(file.name, fileobj)}
            try:
                tmp_dir = tempfile.mkdtemp()
                if ext.lower() == ".img":
                    hdr_file = cleaned_data.get('hdr_file')
                    if hdr_file:
                        # check extension of the hdr file
                        _, _, hdr_ext = split_filename(hdr_file.name)
                        if not hdr_ext.lower() in [".hdr"]:
                            self._errors["hdr_file"] = self.error_class(
                                ["Doesn't have proper extension"])
                            del cleaned_data["hdr_file"]
                            return cleaned_data
                        else:
                            hdr_file.open()
                            file_map["header"] = nb.FileHolder(hdr_file.name,
                                                               hdr_file.file)
                    else:
                        self._errors["hdr_file"] = self.error_class(
                            [".img file requires .hdr file"]
                        )
                        del cleaned_data["hdr_file"]
                        return cleaned_data

                # check if it is really nifti
                try:
                    print file_map
                    if "header" in file_map:
                        nii = nb.Nifti1Pair.from_file_map(file_map)
                    else:
                        nii = nb.Nifti1Image.from_file_map(file_map)
                except Exception as e:
                    raise

                # detect AFNI 4D files and prepare 3D slices
                if nii is not None and detect_4D(nii):
                    self.afni_subbricks = split_4D_to_3D(nii, tmp_dir=tmp_dir)
                else:
                    squeezable_dimensions = len(
                        filter(lambda a: a not in [0, 1], nii.shape)
                    )

                    if squeezable_dimensions != 3:
                        self._errors["file"] = self.error_class(
                            ["4D files are not supported.\n "
                             "If it's multiple maps in one "
                             "file please split them and "
                             "upload separately"])
                        del cleaned_data["file"]
                        return cleaned_data

                    # convert to nii.gz if needed
                    if (ext.lower() != ".nii.gz"
                            or squeezable_dimensions < len(nii.shape)):
                        # convert pseudo 4D to 3D
                        if squeezable_dimensions < len(nii.shape):
                            new_data = np.squeeze(nii.get_data())
                            nii = nb.Nifti1Image(new_data, nii.get_affine(),
                                                 nii.get_header())

                        # Papaya does not handle float64, but by converting
                        # files we loose precision
                        # if nii.get_data_dtype() == np.float64:
                        # ii.set_data_dtype(np.float32)
                        new_name = fname + ".nii.gz"
                        nii_tmp = os.path.join(tmp_dir, new_name)
                        nb.save(nii, nii_tmp)

                        print "updating file in cleaned_data"

                        cleaned_data['file'] = memory_uploadfile(
                            nii_tmp, new_name, cleaned_data['file']
                        )
            finally:
                try:
                    if self.afni_subbricks:
                        # keep temp dir for AFNI slicing
                        self.afni_tmp = tmp_dir
                    else:
                        print "removing %s"%tmp_dir
                        shutil.rmtree(tmp_dir)
                except __HOLE__ as exc:
                    if exc.errno != 2:  # code 2 - no such file or directory
                        raise  # re-raise exception
        elif not getattr(self, 'partial', False):
            # Skip validation error if this is a partial update from the API
            raise ValidationError("Couldn't read uploaded file")

        return cleaned_data
dataset/ETHPy150Open NeuroVault/NeuroVault/neurovault/apps/statmaps/forms.py/ImageValidationMixin.clean_and_validate