





import math
import os

import cva
import numpy as np

_SCREAMING_SNAKE_CASE   						=		2_5_5.0


def 				SCREAMING_SNAKE_CASE__    (     __a ,			__a ):
	snake_case_		:      Optional[Any]           =						np.mean((original - contrast) ** 2 )
	if mse == 0:
		return 1_00

	return 20 * math.logaa(PIXEL_MAX / math.sqrt(__a ) )


def 				SCREAMING_SNAKE_CASE__    (     ):
	snake_case_		:      Any           =						os.path.dirname(os.path.realpath(__a ) )
	# Loading images (original image and compressed image)
	snake_case_		:      int           =						cva.imread(os.path.join(__a ,			'image_data/original_image.png' ) )
	snake_case_		:      Tuple           =						cva.imread(os.path.join(__a ,			'image_data/compressed_image.png' ) ,			1 )

	snake_case_		:      Dict           =						cva.imread(os.path.join(__a ,			'image_data/PSNR-example-base.png' ) )
	snake_case_		:      Optional[Any]           =						cva.imread(
	    os.path.join(__a ,			'image_data/PSNR-example-comp-10.jpg' ) ,			1 )

	# Value expected: 29.73dB
	print('-- First Test --' )
	print(f"""PSNR value is {peak_signal_to_noise_ratio(__a ,			__a )} dB""" )

	# # Value expected: 31.53dB (Wikipedia Example)
	print('\n-- Second Test --' )
	print(f"""PSNR value is {peak_signal_to_noise_ratio(__a ,			__a )} dB""" )


if __name__ == "__main__":
						main()



import os
import tempfile
from pathlib import Path
from unittest import TestCase

import pyarrow as pa
import pytest

from datasets.arrow_dataset import Dataset
from datasets.arrow_reader import ArrowReader, BaseReader, FileInstructions, ReadInstruction, make_file_instructions
from datasets.info import DatasetInfo
from datasets.splits import NamedSplit, Split, SplitDict, SplitInfo

from .utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases


class 			UpperCamelCase_				(  A     ):




      '''simple docstring'''







      def lowercase__		( self					,					_UpperCAmelCase					,					_UpperCAmelCase=False):
            lowerCAmelCase_			,		lowerCAmelCase_			,		lowerCAmelCase_						=      (
                filename_skip_take['''filename'''],
                filename_skip_take['''skip'''] if '''skip''' in filename_skip_take else None,
                filename_skip_take['''take'''] if '''take''' in filename_skip_take else None,
            )
            open(os.path.join(_UpperCAmelCase)					,					'''wb''').close()
            lowerCAmelCase_						=      pa.Table.from_pydict({'''filename''': [Path(_UpperCAmelCase).name] * 100})
            if take == -1:
                  lowerCAmelCase_						=      len(_UpperCAmelCase) - skip
            if skip is not None and take is not None:
                  lowerCAmelCase_						=      pa_table.slice(_UpperCAmelCase					,					_UpperCAmelCase)
            return pa_table


class 			UpperCamelCase_				(  A     ):




      '''simple docstring'''







      def lowercase__		( self):
            lowerCAmelCase_						=      '''my_name'''
            lowerCAmelCase_						=      SplitInfo(name='''train'''					,					num_examples=100)
            lowerCAmelCase_						=      SplitInfo(name='''test'''					,					num_examples=100)
            lowerCAmelCase_						=      [train_info, test_info]
            lowerCAmelCase_						=      SplitDict()
            split_dict.add(_UpperCAmelCase)
            split_dict.add(_UpperCAmelCase)
            lowerCAmelCase_						=      DatasetInfo(splits=_UpperCAmelCase)

            with tempfile.TemporaryDirectory() as tmp_dir:
                  lowerCAmelCase_						=      ReaderTest(_UpperCAmelCase					,					_UpperCAmelCase)

                  lowerCAmelCase_						=      '''test[:33%]'''
                  lowerCAmelCase_						=      Dataset(**reader.read(_UpperCAmelCase					,					_UpperCAmelCase					,					_UpperCAmelCase))
                  self.assertEqual(dset['''filename'''][0]					,					f'{name}-test')
                  self.assertEqual(dset.num_rows					,					33)
                  self.assertEqual(dset.num_columns					,					1)

                  lowerCAmelCase_						=      ['''train''', '''test[:33%]''']
                  lowerCAmelCase_						=      [Split.TRAIN, ReadInstruction.from_spec('''test[:33%]''')]
                  for instructions in [instructionsa, instructionsa]:
                        lowerCAmelCase_						=      [reader.read(_UpperCAmelCase					,					_UpperCAmelCase					,					_UpperCAmelCase) for instr in instructions]
                        lowerCAmelCase_			,		lowerCAmelCase_						=      (Dataset(**_UpperCAmelCase) for dataset_kwargs in datasets_kwargs)
                        self.assertEqual(train_dset['''filename'''][0]					,					f'{name}-train')
                        self.assertEqual(train_dset.num_rows					,					100)
                        self.assertEqual(train_dset.num_columns					,					1)
                        self.assertIsInstance(train_dset.split					,					_UpperCAmelCase)
                        self.assertEqual(str(train_dset.split)					,					'''train''')
                        self.assertEqual(test_dset['''filename'''][0]					,					f'{name}-test')
                        self.assertEqual(test_dset.num_rows					,					33)
                        self.assertEqual(test_dset.num_columns					,					1)
                        self.assertIsInstance(test_dset.split					,					_UpperCAmelCase)
                        self.assertEqual(str(test_dset.split)					,					'''test[:33%]''')
                        del train_dset, test_dset







      def lowercase__		( self):
            lowerCAmelCase_						=      '''my_name'''
            lowerCAmelCase_						=      SplitInfo(name='''train'''					,					num_examples=1_000					,					shard_lengths=[100] * 10)
            lowerCAmelCase_						=      [train_info]
            lowerCAmelCase_						=      SplitDict()
            split_dict.add(_UpperCAmelCase)
            lowerCAmelCase_						=      DatasetInfo(splits=_UpperCAmelCase)

            with tempfile.TemporaryDirectory() as tmp_dir:
                  lowerCAmelCase_						=      ReaderTest(_UpperCAmelCase					,					_UpperCAmelCase)

                  lowerCAmelCase_						=      '''train[:33%]'''
                  lowerCAmelCase_						=      Dataset(**reader.read(_UpperCAmelCase					,					_UpperCAmelCase					,					_UpperCAmelCase))
                  self.assertEqual(dset['''filename'''][0]					,					f'{name}-train-00000-of-00010')
                  self.assertEqual(dset['''filename'''][-1]					,					f'{name}-train-00003-of-00010')
                  self.assertEqual(dset.num_rows					,					330)
                  self.assertEqual(dset.num_columns					,					1)







      def lowercase__		( self):
            lowerCAmelCase_						=      SplitInfo(name='''train'''					,					num_examples=100)
            lowerCAmelCase_						=      SplitInfo(name='''test'''					,					num_examples=100)
            lowerCAmelCase_						=      SplitDict()
            split_dict.add(_UpperCAmelCase)
            split_dict.add(_UpperCAmelCase)
            lowerCAmelCase_						=      DatasetInfo(splits=_UpperCAmelCase)

            with tempfile.TemporaryDirectory() as tmp_dir:
                  lowerCAmelCase_						=      ReaderTest(_UpperCAmelCase					,					_UpperCAmelCase)

                  lowerCAmelCase_						=      [
                      {'''filename''': os.path.join(_UpperCAmelCase					,					'''train''')},
                      {'''filename''': os.path.join(_UpperCAmelCase					,					'''test'''), '''skip''': 10, '''take''': 10},
                  ]
                  lowerCAmelCase_						=      Dataset(**reader.read_files(_UpperCAmelCase					,					original_instructions='''train+test[10:20]'''))
                  self.assertEqual(dset.num_rows					,					110)
                  self.assertEqual(dset.num_columns					,					1)
                  del dset
@pytest.mark.parametrize('''in_memory'''		,					[False, True]						)
def lowerCamelCase_       (			A			:      List[Any]		,					A			:      Union[str, Any]		,					A			:      Optional[int]						):




      """simple docstring"""
      lowerCAmelCase_						=      arrow_file
      with assert_arrow_memory_increases() if in_memory else assert_arrow_memory_doesnt_increase():
            lowerCAmelCase_						=      ArrowReader.read_table(A		,					in_memory=A						)
      assert table.shape == dataset.data.shape
      assert set(table.column_names						) == set(dataset.data.column_names						)
      assert dict(table.to_pydict()						) == dict(dataset.data.to_pydict()						)  # to_pydict returns OrderedDict
@pytest.mark.parametrize('''in_memory'''		,					[False, True]						)
def lowerCamelCase_       (			A			:      List[str]		,					A			:      List[str]		,					A			:      Dict						):




      """simple docstring"""
      lowerCAmelCase_						=      arrow_file
      lowerCAmelCase_						=      ArrowReader(''''''		,					A						)
      with assert_arrow_memory_increases() if in_memory else assert_arrow_memory_doesnt_increase():
            lowerCAmelCase_						=      reader.read_files([{'''filename''': filename}]		,					in_memory=A						)
      assert dataset_kwargs.keys() == {"arrow_table", "info", "split"}
      lowerCAmelCase_						=      dataset_kwargs['''arrow_table''']
      assert table.shape == dataset.data.shape
      assert set(table.column_names						) == set(dataset.data.column_names						)
      assert dict(table.to_pydict()						) == dict(dataset.data.to_pydict()						)  # to_pydict returns OrderedDict
def lowerCamelCase_       (			):




      """simple docstring"""
      assert ReadInstruction('''train'''		,					to=10		,					unit='''abs'''						).to_spec() == "train[:10]"
      assert ReadInstruction('''train'''		,					from_=-80		,					to=10		,					unit='''%'''						).to_spec() == "train[-80%:10%]"

      lowerCAmelCase_						=      '''train+test'''
      assert ReadInstruction.from_spec(A						).to_spec() == spec_train_test

      lowerCAmelCase_						=      '''train[2:10]'''
      assert ReadInstruction.from_spec(A						).to_spec() == spec_train_abs

      lowerCAmelCase_						=      '''train[15%:-20%]'''
      assert ReadInstruction.from_spec(A						).to_spec() == spec_train_pct

      lowerCAmelCase_						=      '''train[:10%](closest)'''
      assert ReadInstruction.from_spec(A						).to_spec() == "train[:10%]"

      lowerCAmelCase_						=      '''train[:10%](pct1_dropremainder)'''
      assert ReadInstruction.from_spec(A						).to_spec() == spec_train_pct_rounding

      lowerCAmelCase_						=      '''train[:10%](pct1_dropremainder)+test[-10%:](pct1_dropremainder)'''
      assert ReadInstruction.from_spec(A						).to_spec() == spec_train_test_pct_rounding
def lowerCamelCase_       (			):




      """simple docstring"""
      lowerCAmelCase_						=      '''dummy'''
      lowerCAmelCase_						=      [SplitInfo(name='''train'''		,					num_examples=1_00						)]
      lowerCAmelCase_						=      '''train[:33%]'''
      lowerCAmelCase_						=      '''arrow'''
      lowerCAmelCase_						=      '''prefix'''

      lowerCAmelCase_						=      make_file_instructions(A		,					A		,					A		,					A		,					A						)
      assert isinstance(A		,					A						)
      assert file_instructions.num_examples == 33
      assert file_instructions.file_instructions == [
          {"filename": os.path.join(A		,					F'{name}-train.arrow'						), "skip": 0, "take": 33}
      ]

      lowerCAmelCase_						=      [SplitInfo(name='''train'''		,					num_examples=1_00		,					shard_lengths=[10] * 10						)]
      lowerCAmelCase_						=      make_file_instructions(A		,					A		,					A		,					A		,					A						)
      assert isinstance(A		,					A						)
      assert file_instructions.num_examples == 33
      assert file_instructions.file_instructions == [
          {"filename": os.path.join(A		,					F'{name}-train-00000-of-00010.arrow'						), "skip": 0, "take": -1},
          {"filename": os.path.join(A		,					F'{name}-train-00001-of-00010.arrow'						), "skip": 0, "take": -1},
          {"filename": os.path.join(A		,					F'{name}-train-00002-of-00010.arrow'						), "skip": 0, "take": -1},
          {"filename": os.path.join(A		,					F'{name}-train-00003-of-00010.arrow'						), "skip": 0, "take": 3},
      ]




@pytest.mark.parametrize('''name, expected_exception'''		,					[(None, TypeError), ('''''', ValueError)]						)
def lowerCamelCase_       (			A			:      Any		,					A			:      int						):




      """simple docstring"""
      lowerCAmelCase_						=      [SplitInfo(name='''train'''		,					num_examples=1_00						)]
      lowerCAmelCase_						=      '''train'''
      lowerCAmelCase_						=      '''arrow'''
      lowerCAmelCase_						=      '''prefix_path'''
      with pytest.raises(A						):
            lowerCAmelCase_						=      make_file_instructions(A		,					A		,					A		,					A		,					A						)



