





import os
from datetime import datetime as dt

from github import Github


_lowerCamelCase			       =      [
    'good first issue',
    'feature request',
    'wip',
]




def    __UpperCAmelCase(      ):
       _lowerCamelCase							:     List[Any]	=		Github(os.environ['''GITHUB_TOKEN''']      )
       _lowerCamelCase							:     Optional[int]	=		g.get_repo('''huggingface/accelerate'''      )
       _lowerCamelCase							:     int	=		repo.get_issues(state='''open'''      )

       for issue in open_issues:
              _lowerCamelCase							:     List[str]	=		sorted([comment for comment in issue.get_comments()] ,    key=lambda lowercase_      : i.created_at ,    reverse=lowerCamelCase_      )
              _lowerCamelCase							:     List[str]	=		comments[0] if len(lowerCamelCase_      ) > 0 else None
              _lowerCamelCase							:     Any	=		dt.utcnow()
              _lowerCamelCase							:     str	=		(current_time - issue.updated_at).days
              _lowerCamelCase							:     Optional[Any]	=		(current_time - issue.created_at).days
              if (
                  last_comment is not None
                  and last_comment.user.login == "github-actions[bot]"
                  and days_since_updated > 7
                  and days_since_creation >= 30
                  and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels()      )
              ):
                     # Close issue since it has been 7 days of inactivity since bot mention.
                     issue.edit(state='''closed'''      )
              elif (
                  days_since_updated > 23
                  and days_since_creation >= 30
                  and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels()      )
              ):
                     # Add stale comment
                     issue.create_comment(
                         '''This issue has been automatically marked as stale because it has not had '''
                         '''recent activity. If you think this still needs to be addressed '''
                         '''please comment on this thread.\n\nPlease note that issues that do not follow the '''
                         '''[contributing guidelines](https://github.com/huggingface/accelerate/blob/main/CONTRIBUTING.md) '''
                         '''are likely to be ignored.'''      )


if __name__ == "__main__":
       main()








import time
from dataclasses import dataclass
from multiprocessing import Pool
from unittest import TestCase
from unittest.mock import patch

import multiprocess
import numpy as np
import pytest

from datasets.utils.py_utils import (
    NestedDataStructure,
    asdict,
    iflatmap_unordered,
    map_nested,
    temp_seed,
    temporary_assignment,
    zip_dict,
)

from .utils import require_tf, require_torch




def    __UpperCAmelCase(      lowercase_      ):  # picklable for multiprocessing
       return x.sum()




def    __UpperCAmelCase(      lowercase_      ):  # picklable for multiprocessing
       return i + 1







@dataclass
class 			__A       :




      """simple docstring"""







      UpperCAmelCase__						=      42
      UpperCAmelCase__						=      42







class 			__A       (      lowerCamelCase__  ):




      """simple docstring"""







      def 				__snake_case			(		self):



             """simple docstring"""





             _lowerCamelCase							:     Tuple	=		{}
             _lowerCamelCase							:     Dict	=		[]
             _lowerCamelCase							:     Optional[Any]	=		1
             _lowerCamelCase							:     Optional[int]	=		[1, 2]
             _lowerCamelCase							:     str	=		{'''a''': 1, '''b''': 2}
             _lowerCamelCase							:     Dict	=		{'''a''': [1, 2], '''b''': [3, 4]}
             _lowerCamelCase							:     Any	=		{'''a''': {'''1''': 1}, '''b''': 2}
             _lowerCamelCase							:     Optional[Any]	=		{'''a''': 1, '''b''': 2, '''c''': 3, '''d''': 4}
             _lowerCamelCase							:     str	=		{}
             _lowerCamelCase							:     int	=		[]
             _lowerCamelCase							:     str	=		2
             _lowerCamelCase							:     int	=		[2, 3]
             _lowerCamelCase							:     str	=		{'''a''': 2, '''b''': 3}
             _lowerCamelCase							:     Tuple	=		{'''a''': [2, 3], '''b''': [4, 5]}
             _lowerCamelCase							:     List[str]	=		{'''a''': {'''1''': 2}, '''b''': 3}
             _lowerCamelCase							:     str	=		{'''a''': 2, '''b''': 3, '''c''': 4, '''d''': 5}
             self.assertEqual(map_nested(a__      ,							a__)      ,							a__)
             self.assertEqual(map_nested(a__      ,							a__)      ,							a__)
             self.assertEqual(map_nested(a__      ,							a__)      ,							a__)
             self.assertEqual(map_nested(a__      ,							a__)      ,							a__)
             self.assertEqual(map_nested(a__      ,							a__)      ,							a__)
             self.assertEqual(map_nested(a__      ,							a__)      ,							a__)
             self.assertEqual(map_nested(a__      ,							a__)      ,							a__)
             self.assertEqual(map_nested(a__      ,							a__)      ,							a__)

             _lowerCamelCase							:     Dict	=		2
             self.assertEqual(map_nested(a__      ,							a__      ,							num_proc=a__)      ,							a__)
             self.assertEqual(map_nested(a__      ,							a__      ,							num_proc=a__)      ,							a__)
             self.assertEqual(map_nested(a__      ,							a__      ,							num_proc=a__)      ,							a__)
             self.assertEqual(map_nested(a__      ,							a__      ,							num_proc=a__)      ,							a__)
             self.assertEqual(map_nested(a__      ,							a__      ,							num_proc=a__)      ,							a__)
             self.assertEqual(map_nested(a__      ,							a__      ,							num_proc=a__)      ,							a__)
             self.assertEqual(map_nested(a__      ,							a__      ,							num_proc=a__)      ,							a__)
             self.assertEqual(map_nested(a__      ,							a__      ,							num_proc=a__)      ,							a__)

             _lowerCamelCase							:     Any	=		{'''a''': np.eye(2), '''b''': np.zeros(3), '''c''': np.ones(2)}
             _lowerCamelCase							:     Optional[int]	=		{'''a''': 2, '''b''': 0, '''c''': 2}
             _lowerCamelCase							:     Optional[int]	=		{
                 '''a''': np.eye(2).astype(a__),
                 '''b''': np.zeros(3).astype(a__),
                 '''c''': np.ones(2).astype(a__),
             }
             self.assertEqual(map_nested(a__      ,							a__      ,							map_numpy=a__)      ,							a__)
             self.assertEqual(
                 {k: v.tolist() for k, v in map_nested(a__      ,							a__      ,							map_numpy=a__).items()}      ,							{k: v.tolist() for k, v in expected_map_nested_sna_int.items()}      ,							)
             self.assertEqual(map_nested(a__      ,							a__      ,							map_numpy=a__      ,							num_proc=a__)      ,							a__)
             self.assertEqual(
                 {k: v.tolist() for k, v in map_nested(a__      ,							a__      ,							map_numpy=a__      ,							num_proc=a__).items()}      ,							{k: v.tolist() for k, v in expected_map_nested_sna_int.items()}      ,							)
             with self.assertRaises(a__):  # can't pickle a local lambda
                    map_nested(lambda a__: x + 1      ,							a__      ,							num_proc=a__)


      def 				__snake_case			(		self):



             """simple docstring"""





             _lowerCamelCase							:     Dict	=		{'''a''': 1, '''b''': 2}
             _lowerCamelCase							:     Optional[int]	=		{'''a''': 3, '''b''': 4}
             _lowerCamelCase							:     int	=		{'''a''': 5, '''b''': 6}
             _lowerCamelCase							:     Optional[int]	=		sorted([('''a''', (1, 3, 5)), ('''b''', (2, 4, 6))])
             self.assertEqual(sorted(zip_dict(a__      ,							a__      ,							a__))      ,							a__)



      def 				__snake_case			(		self):



             """simple docstring"""





             class 			__A       :




                   """simple docstring"""







                   UpperCAmelCase__						=      """bar"""
             _lowerCamelCase							:     Any	=		Foo()
             self.assertEqual(foo.my_attr      ,							'''bar''')
             with temporary_assignment(a__      ,							'''my_attr'''      ,							'''BAR'''):
                    self.assertEqual(foo.my_attr      ,							'''BAR''')
             self.assertEqual(foo.my_attr      ,							'''bar''')




@pytest.mark.parametrize(
    '''iterable_length, num_proc, expected_num_proc''' ,    [
        (1, None, 1),
        (1, 1, 1),
        (2, None, 1),
        (2, 1, 1),
        (2, 2, 1),
        (2, 3, 1),
        (3, 2, 1),
        (16, 16, 16),
        (16, 17, 16),
        (17, 16, 16),
    ] ,    )
def    __UpperCAmelCase(      lowercase_ ,    lowercase_ ,    lowercase_      ):
       with patch('''datasets.utils.py_utils._single_map_nested'''      ) as mock_single_map_nested, patch(
           '''datasets.parallel.parallel.Pool'''      ) as mock_multiprocessing_pool:
              _lowerCamelCase							:     Union[str, Any]	=		{F"""{i}""": i for i in range(lowercase_      )}
              _lowerCamelCase							:     List[str]	=		map_nested(lambda lowercase_      : x + 10 ,    lowercase_ ,    num_proc=lowercase_ ,    parallel_min_length=16      )
              if expected_num_proc == 1:
                     assert mock_single_map_nested.called
                     assert not mock_multiprocessing_pool.called
              else:
                     assert not mock_single_map_nested.called
                     assert mock_multiprocessing_pool.called
                     assert mock_multiprocessing_pool.call_args[0][0] == expected_num_proc







class 			__A       (      lowerCamelCase__  ):




      """simple docstring"""







      @require_tf
      def 				__snake_case			(		self):



             """simple docstring"""





             import tensorflow as tf
             from tensorflow.keras import layers

             _lowerCamelCase							:     int	=		layers.Dense(2)

             def gen_random_output():
                    _lowerCamelCase							:     Union[str, Any]	=		tf.random.uniform((1, 3))
                    return model(a__).numpy()

             with temp_seed(42      ,							set_tensorflow=a__):
                    _lowerCamelCase							:     List[str]	=		gen_random_output()
             with temp_seed(42      ,							set_tensorflow=a__):
                    _lowerCamelCase							:     Any	=		gen_random_output()
             _lowerCamelCase							:     str	=		gen_random_output()

             np.testing.assert_equal(a__      ,							a__)
             self.assertGreater(np.abs(outa - outa).sum()      ,							0)


      @require_torch
      def 				__snake_case			(		self):



             """simple docstring"""





             import torch

             def gen_random_output():
                    _lowerCamelCase							:     Union[str, Any]	=		torch.nn.Linear(3      ,							2)
                    _lowerCamelCase							:     Dict	=		torch.rand(1      ,							3)
                    return model(a__).detach().numpy()

             with temp_seed(42      ,							set_pytorch=a__):
                    _lowerCamelCase							:     Any	=		gen_random_output()
             with temp_seed(42      ,							set_pytorch=a__):
                    _lowerCamelCase							:     Optional[int]	=		gen_random_output()
             _lowerCamelCase							:     Union[str, Any]	=		gen_random_output()

             np.testing.assert_equal(a__      ,							a__)
             self.assertGreater(np.abs(outa - outa).sum()      ,							0)



      def 				__snake_case			(		self):



             """simple docstring"""





             def gen_random_output():
                    return np.random.rand(1      ,							3)

             with temp_seed(42):
                    _lowerCamelCase							:     Union[str, Any]	=		gen_random_output()
             with temp_seed(42):
                    _lowerCamelCase							:     List[str]	=		gen_random_output()
             _lowerCamelCase							:     str	=		gen_random_output()

             np.testing.assert_equal(a__      ,							a__)
             self.assertGreater(np.abs(outa - outa).sum()      ,							0)




@pytest.mark.parametrize('''input_data''' ,    [{}]      )
def    __UpperCAmelCase(      lowercase_      ):
       _lowerCamelCase							:     List[Any]	=		NestedDataStructure(lowercase_      ).data
       assert output_data == input_data




@pytest.mark.parametrize(
    '''data, expected_output''' ,    [
        ({}, []),
        ([], []),
        ('''foo''', ['''foo''']),
        (['''foo''', '''bar'''], ['''foo''', '''bar''']),
        ([['''foo''', '''bar''']], ['''foo''', '''bar''']),
        ([[['''foo'''], ['''bar''']]], ['''foo''', '''bar''']),
        ([[['''foo'''], '''bar''']], ['''foo''', '''bar''']),
        ({'''a''': 1, '''b''': 2}, [1, 2]),
        ({'''a''': [1, 2], '''b''': [3, 4]}, [1, 2, 3, 4]),
        ({'''a''': [[1, 2]], '''b''': [[3, 4]]}, [1, 2, 3, 4]),
        ({'''a''': [[1, 2]], '''b''': [3, 4]}, [1, 2, 3, 4]),
        ({'''a''': [[[1], [2]]], '''b''': [[[3], [4]]]}, [1, 2, 3, 4]),
        ({'''a''': [[[1], [2]]], '''b''': [[3, 4]]}, [1, 2, 3, 4]),
        ({'''a''': [[[1], [2]]], '''b''': [3, 4]}, [1, 2, 3, 4]),
        ({'''a''': [[[1], [2]]], '''b''': [3, [4]]}, [1, 2, 3, 4]),
        ({'''a''': {'''1''': 1}, '''b''': 2}, [1, 2]),
        ({'''a''': {'''1''': [1]}, '''b''': 2}, [1, 2]),
        ({'''a''': {'''1''': [1]}, '''b''': [2]}, [1, 2]),
    ] ,    )
def    __UpperCAmelCase(      lowercase_ ,    lowercase_      ):
       _lowerCamelCase							:     int	=		NestedDataStructure(lowercase_      ).flatten()
       assert output == expected_output




def    __UpperCAmelCase(      ):
       _lowerCamelCase							:     Any	=		A(x=1 ,    y='''foobar'''      )
       _lowerCamelCase							:     Union[str, Any]	=		{'''x''': 1, '''y''': '''foobar'''}
       assert asdict(lowercase_      ) == expected_output

       _lowerCamelCase							:     Optional[int]	=		{'''a''': {'''b''': A(x=10 ,    y='''foo'''      )}, '''c''': [A(x=20 ,    y='''bar'''      )]}
       _lowerCamelCase							:     Union[str, Any]	=		{'''a''': {'''b''': {'''x''': 10, '''y''': '''foo'''}}, '''c''': [{'''x''': 20, '''y''': '''bar'''}]}
       assert asdict(lowercase_      ) == expected_output

       with pytest.raises(lowercase_      ):
              asdict([1, A(x=10 ,    y='''foo'''      )]      )




def    __UpperCAmelCase(      lowercase_      ):
       return text.split()




def    __UpperCAmelCase(      lowercase_      ):
       yield (time.time(), content)
       time.sleep(2      )
       yield (time.time(), content)




def    __UpperCAmelCase(      ):
       with Pool(2      ) as pool:
              _lowerCamelCase							:     Tuple	=		list(iflatmap_unordered(lowercase_ ,    _split_text ,    kwargs_iterable=[{'''text''': '''hello there'''}] * 10      )      )
              assert out.count('''hello'''      ) == 10
              assert out.count('''there'''      ) == 10
              assert len(lowercase_      ) == 20

       # check multiprocess from pathos (uses dill for pickling)
       with multiprocess.Pool(2      ) as pool:
              _lowerCamelCase							:     Dict	=		list(iflatmap_unordered(lowercase_ ,    _split_text ,    kwargs_iterable=[{'''text''': '''hello there'''}] * 10      )      )
              assert out.count('''hello'''      ) == 10
              assert out.count('''there'''      ) == 10
              assert len(lowercase_      ) == 20

       # check that we get items as fast as possible
       with Pool(2      ) as pool:
              _lowerCamelCase							:     str	=		[]
              for yield_time, content in iflatmap_unordered(
                  lowercase_ ,    _aseconds_generator_of_aitems_with_timing ,    kwargs_iterable=[{'''content''': '''a'''}, {'''content''': '''b'''}]      ):
                     assert yield_time < time.time() + 0.1, "we should each item directly after it was yielded"
                     out.append(lowercase_      )
              assert out.count('''a'''      ) == 2
              assert out.count('''b'''      ) == 2
              assert len(lowercase_      ) == 4

