



'''simple docstring'''



from typing import SupportsIndex

import numpy as np
from scipy.ndimage import convolve







def _lowercase   (  __A							,__A							,__A       ):



 '''simple docstring'''



 __UpperCamelCase				      =  np.stack((horizontal_flow, vertical_flow)							,2       )

 # Create a grid of all pixel coordinates and subtract the flow to get the
 # target pixels coordinates
 __UpperCamelCase				      =  np.stack(
     np.meshgrid(np.arange(0							,image.shape[1]       )							,np.arange(0							,image.shape[0]       )       )							,2       )
 __UpperCamelCase				      =  np.round(grid - flow       ).astype(np.intaa       )

 # Find the locations outside of the original image
 __UpperCamelCase				      =  (grid < 0) | (grid >= np.array([image.shape[1], image.shape[0]]       ))
 __UpperCamelCase				      =  0

 __UpperCamelCase				      =  image[grid[:, :, 1], grid[:, :, 0]]

 # Set pixels at invalid locations to 0
 __UpperCamelCase				      =  0

 return warped







def _lowercase   (  __A							,__A							,__A							,__A = None							,):



 '''simple docstring'''



 if alpha is None:
  __UpperCamelCase				      =  0.1

 # Initialize flow
 __UpperCamelCase				      =  np.zeros_like(__A       )
 __UpperCamelCase				      =  np.zeros_like(__A       )

 # Prepare kernels for the calculation of the derivatives and the average velocity
 __UpperCamelCase				      =  np.array([[-1, 1], [-1, 1]]       ) * 0.25
 __UpperCamelCase				      =  np.array([[-1, -1], [1, 1]]       ) * 0.25
 __UpperCamelCase				      =  np.array([[1, 1], [1, 1]]       ) * 0.25
 __UpperCamelCase				      =  np.array(
     [[1 / 12, 1 / 6, 1 / 12], [1 / 6, 0, 1 / 6], [1 / 12, 1 / 6, 1 / 12]]       )

 # Iteratively refine the flow
 for _ in range(__A       ):
  __UpperCamelCase				      =  warp(__A							,__A							,__A       )
  __UpperCamelCase				      =  convolve(__A							,__A       ) + convolve(__A							,__A       )
  __UpperCamelCase				      =  convolve(__A							,__A       ) + convolve(__A							,__A       )
  __UpperCamelCase				      =  convolve(__A							,__A       ) + convolve(__A							,-kernel_t       )

  __UpperCamelCase				      =  convolve(__A							,__A       )
  __UpperCamelCase				      =  convolve(__A							,__A       )

  # This updates the flow as proposed in the paper (Step 12)
  __UpperCamelCase				      =  (
      derivative_x * avg_horizontal_velocity
      + derivative_y * avg_vertical_velocity
      + derivative_t
  )
  __UpperCamelCase				      =  update / (alpha**2 + derivative_x**2 + derivative_y**2)

  __UpperCamelCase				      =  avg_horizontal_velocity - derivative_x * update
  __UpperCamelCase				      =  avg_vertical_velocity - derivative_y * update

 return horizontal_flow, vertical_flow


if __name__ == "__main__":
 import doctest

 doctest.testmod()










'''simple docstring'''



import textwrap

import pyarrow as pa
import pytest

from datasets import Features, Image
from datasets.packaged_modules.text.text import Text

from ..utils import require_pil







@pytest.fixture
def _lowercase   (  __A       ):



 '''simple docstring'''



 __UpperCamelCase				      =  tmp_path / """text.txt"""
 __UpperCamelCase				      =  textwrap.dedent(
     """\
        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
        Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
        Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
        Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

        Second paragraph:
        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
        Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
        Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
        Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
        """       )
 with open(__A							,"""w"""							,encoding="""utf-8"""       ) as f:
  f.write(__A       )
 return str(__A       )







@pytest.fixture
def _lowercase   (  __A							,__A       ):



 '''simple docstring'''



 __UpperCamelCase				      =  tmp_path / """text_with_image.txt"""
 with open(__A							,"""w"""							,encoding="""utf-8"""       ) as f:
  f.write(__A       )
 return str(__A       )







@pytest.mark.parametrize("""keep_linebreaks"""							,[True, False]       )
def _lowercase   (  __A							,__A       ):



 '''simple docstring'''



 with open(__A							,encoding="""utf-8"""       ) as f:
  __UpperCamelCase				      =  f.read().splitlines(keepends=__A       )
 __UpperCamelCase				      =  Text(keep_linebreaks=__A							,encoding="""utf-8"""       )
 __UpperCamelCase				      =  text._generate_tables([[text_file]]       )
 __UpperCamelCase				      =  pa.concat_tables([table for _, table in generator]       ).to_pydict()["""text"""]
 assert generated_content == expected_content







@require_pil
def _lowercase   (  __A       ):



 '''simple docstring'''



 with open(__A							,encoding="""utf-8"""       ) as f:
  __UpperCamelCase				      =  f.read().splitlines()[0]
 __UpperCamelCase				      =  Text(encoding="""utf-8"""							,features=Features({"""image""": Image()}       )       )
 __UpperCamelCase				      =  text._generate_tables([[text_file_with_image]]       )
 __UpperCamelCase				      =  pa.concat_tables([table for _, table in generator]       )
 assert pa_table.schema.field("""image"""       ).type == Image()()
 __UpperCamelCase				      =  pa_table.to_pydict()["""image"""]
 assert generated_content == [{"path": image_file, "bytes": None}]







@pytest.mark.parametrize("""sample_by"""							,["""line""", """paragraph""", """document"""]       )
def _lowercase   (  __A							,__A       ):



 '''simple docstring'''



 with open(__A							,encoding="""utf-8"""       ) as f:
  __UpperCamelCase				      =  f.read()
 if sample_by == "line":
  __UpperCamelCase				      =  expected_content.splitlines()
 elif sample_by == "paragraph":
  __UpperCamelCase				      =  expected_content.split("""\n\n"""       )
 elif sample_by == "document":
  __UpperCamelCase				      =  [expected_content]
 __UpperCamelCase				      =  Text(sample_by=__A							,encoding="""utf-8"""							,chunksize=100       )
 __UpperCamelCase				      =  text._generate_tables([[text_file]]       )
 __UpperCamelCase				      =  pa.concat_tables([table for _, table in generator]       ).to_pydict()["""text"""]
 assert generated_content == expected_content





