




'''simple docstring'''


import datasets
import faiss
import numpy as np
import streamlit as st
import torch
from elasticsearch import Elasticsearch
from elia_utils import (
    embed_questions_for_retrieval,
    make_qa_sas_model,
    qa_sas_generate,
    query_es_index,
    query_qa_dense_index,
)

import transformers
from transformers import AutoModel, AutoModelForSeqaSeqLM, AutoTokenizer


_snake_case   :   Union[str, Any]     							=	'bart'
_snake_case   :   Any     							=	True
@st.cache(allow_output_mutation=UpperCamelCase   )
def 	snake_case_					():





							'''simple docstring'''


							if LOAD_DENSE_INDEX:
														_a			  =       AutoTokenizer.from_pretrained('''yjernite/retribert-base-uncased'''   )
														_a			  =       AutoModel.from_pretrained('''yjernite/retribert-base-uncased'''   ).to('''cuda:0'''   )
														_a			  =       qar_model.eval()
							else:
														_a  ,							_a			  =       (None, None)
							if MODEL_TYPE == "bart":
														_a			  =       AutoTokenizer.from_pretrained('''yjernite/bart_eli5'''   )
														_a			  =       AutoModelForSeqaSeqLM.from_pretrained('''yjernite/bart_eli5'''   ).to('''cuda:0'''   )
														_a			  =       torch.load('''seq2seq_models/eli5_bart_model_blm_2.pth'''   )
														sas_model.load_state_dict(save_dict['''model''']   )
														_a			  =       sas_model.eval()
							else:
														_a  ,							_a			  =       make_qa_sas_model(
														    model_name='''t5-small'''				,		from_file='''seq2seq_models/eli5_t5_model_1024_4.pth'''				,		device='''cuda:0'''   )
							return (qar_tokenizer, qar_model, sas_tokenizer, sas_model)
@st.cache(allow_output_mutation=UpperCamelCase   )
def 	snake_case_					():





							'''simple docstring'''


							if LOAD_DENSE_INDEX:
														_a			  =       faiss.StandardGpuResources()
														_a			  =       datasets.load_dataset(path='''wiki_snippets'''				,		name='''wiki40b_en_100_0'''   )['''train''']
														_a			  =       np.memmap(
														    '''wiki40b_passages_reps_32_l-8_h-768_b-512-512.dat'''				,		dtype='''float32'''				,		mode='''r'''				,		shape=(wikiaab_passages.num_rows, 128)				,		)
														_a			  =       faiss.IndexFlatIP(128   )
														_a			  =       faiss.index_cpu_to_gpu(UpperCamelCase				,		1				,		UpperCamelCase   )
														wikiaab_gpu_index_flat.add(UpperCamelCase   )  # TODO fix for larger GPU
							else:
														_a  ,							_a			  =       (None, None)
							_a			  =       Elasticsearch([{'''host''': '''localhost''', '''port''': '''9200'''}]   )
							return (wikiaab_passages, wikiaab_gpu_index_flat, es_client)
@st.cache(allow_output_mutation=UpperCamelCase   )
def 	snake_case_					():





							'''simple docstring'''


							_a			  =       datasets.load_dataset('''eli5'''				,		name='''LFQA_reddit'''   )
							_a			  =       elia['''train_eli5''']
							_a			  =       np.memmap(
							    '''eli5_questions_reps.dat'''				,		dtype='''float32'''				,		mode='''r'''				,		shape=(elia_train.num_rows, 128)   )
							_a			  =       faiss.IndexFlatIP(128   )
							eli5_train_q_index.add(UpperCamelCase   )
							return (elia_train, eli5_train_q_index)


_snake_case							,       _snake_case							,       _snake_case   :   Optional[Any]     							=	load_indexes()
_snake_case							,       _snake_case							,       _snake_case							,       _snake_case   :   Union[str, Any]     							=	load_models()
_snake_case							,       _snake_case   :   Tuple     							=	load_train_data()
def 	snake_case_					(UpperCamelCase :						List[Any]				,		UpperCamelCase :						Tuple=10   ):





							'''simple docstring'''


							_a			  =       embed_questions_for_retrieval([question]				,		UpperCamelCase				,		UpperCamelCase   )
							_a  ,							_a			  =       eli5_train_q_index.search(UpperCamelCase				,		UpperCamelCase   )
							_a			  =       [elia_train[int(UpperCamelCase   )] for i in I[0]]
							return nn_examples
def 	snake_case_					(UpperCamelCase :						Tuple				,		UpperCamelCase :						Union[str, Any]="wiki40b"				,		UpperCamelCase :						str="dense"				,		UpperCamelCase :						Union[str, Any]=10   ):





							'''simple docstring'''


							if source == "none":
														_a  ,							_a			  =       (''' <P> '''.join(['''''' for _ in range(11   )]   ).strip(), [])
							else:
														if method == "dense":
																					_a  ,							_a			  =       query_qa_dense_index(
																					    UpperCamelCase				,		UpperCamelCase				,		UpperCamelCase				,		UpperCamelCase				,		UpperCamelCase				,		UpperCamelCase   )
														else:
																					_a  ,							_a			  =       query_es_index(
																					    UpperCamelCase				,		UpperCamelCase				,		index_name='''english_wiki40b_snippets_100w'''				,		n_results=UpperCamelCase				,		)
							_a			  =       [
							    (res['''article_title'''], res['''section_title'''].strip(), res['''score'''], res['''passage_text''']) for res in hit_lst
							]
							_a			  =       '''question: {} context: {}'''.format(UpperCamelCase				,		UpperCamelCase   )
							return question_doc, support_list
@st.cache(
    hash_funcs={
        torch.Tensor: (lambda UpperCamelCase   : None),
        transformers.models.bart.tokenization_bart.BartTokenizer: (lambda UpperCamelCase   : None),
    }   )
def 	snake_case_					(UpperCamelCase :						Optional[int]				,		UpperCamelCase :						Any				,		UpperCamelCase :						List[Any]				,		UpperCamelCase :						Union[str, Any]=64				,		UpperCamelCase :						Tuple=256				,		UpperCamelCase :						Any=False				,		UpperCamelCase :						str=2				,		UpperCamelCase :						Union[str, Any]=0.95				,		UpperCamelCase :						Union[str, Any]=0.8   ):





							'''simple docstring'''


							with torch.no_grad():
														_a			  =       qa_sas_generate(
														    UpperCamelCase				,		UpperCamelCase				,		UpperCamelCase				,		num_answers=1				,		num_beams=UpperCamelCase				,		min_len=UpperCamelCase				,		max_len=UpperCamelCase				,		do_sample=UpperCamelCase				,		temp=UpperCamelCase				,		top_p=UpperCamelCase				,		top_k=UpperCamelCase				,		max_input_length=1024				,		device='''cuda:0'''				,		)[0]
							return (answer, support_list)


st.title('Long Form Question Answering with ELI5')

# Start sidebar
_snake_case   :   Dict     							=	'<img src=\'https://huggingface.co/front/assets/huggingface_logo.svg\'>'
_snake_case   :   List[Any]     							=	'\n<html>\n  <head>\n    <style>\n      .img-container {\n        padding-left: 90px;\n        padding-right: 90px;\n        padding-top: 50px;\n        padding-bottom: 50px;\n        background-color: #f0f3f9;\n      }\n    </style>\n  </head>\n  <body>\n    <span class="img-container"> <!-- Inline parent element -->\n      %s\n    </span>\n  </body>\n</html>\n' % (
    header_html,
)
st.sidebar.markdown(
    header_full,
    unsafe_allow_html=True,
)

# Long Form QA with ELI5 and Wikipedia
_snake_case   :   int     							=	'\nThis demo presents a model trained to [provide long-form answers to open-domain questions](https://yjernite.github.io/lfqa.html).\nFirst, a document retriever fetches a set of relevant Wikipedia passages given the question from the [Wiki40b](https://research.google/pubs/pub49029/) dataset,\na pre-processed fixed snapshot of Wikipedia.\n'
st.sidebar.markdown(description, unsafe_allow_html=True)

_snake_case   :   Any     							=	[
    'Answer the question',
    'View the retrieved document only',
    'View the most similar ELI5 question and answer',
    'Show me everything, please!',
]
_snake_case   :   List[str]     							=	st.sidebar.checkbox('Demo options')
if demo_options:
				_snake_case   :   Union[str, Any]     							=	st.sidebar.selectbox(
				    '',
				    action_list,
				    index=3,
				)
				_snake_case   :   Union[str, Any]     							=	action_list.index(action_st)
				_snake_case   :   int     							=	st.sidebar.selectbox(
				    '',
				    ['Show full text of passages', 'Show passage section titles'],
				    index=0,
				)
				_snake_case   :   str     							=	show_type == 'Show full text of passages'
else:
				_snake_case   :   List[str]     							=	3
				_snake_case   :   Dict     							=	True

_snake_case   :   Tuple     							=	st.sidebar.checkbox('Retrieval options')
if retrieval_options:
				_snake_case   :   Dict     							=	'\n    ### Information retriever options\n\n    The **sparse** retriever uses ElasticSearch, while the **dense** retriever uses max-inner-product search between a question and passage embedding\n    trained using the [ELI5](https://arxiv.org/abs/1907.09190) questions-answer pairs.\n    The answer is then generated by sequence to sequence model which takes the question and retrieved document as input.\n    '
				st.sidebar.markdown(retriever_info)
				_snake_case   :   Optional[int]     							=	st.sidebar.selectbox('Which Wikipedia format should the model use?', ['wiki40b', 'none'])
				_snake_case   :   int     							=	st.sidebar.selectbox('Which Wikipedia indexer should the model use?', ['dense', 'sparse', 'mixed'])
else:
				_snake_case   :   Optional[int]     							=	'wiki40b'
				_snake_case   :   Union[str, Any]     							=	'dense'

_snake_case   :   List[str]     							=	'beam'
_snake_case   :   Optional[int]     							=	2
_snake_case   :   Dict     							=	64
_snake_case   :   Union[str, Any]     							=	256
_snake_case   :   Union[str, Any]     							=	None
_snake_case   :   Union[str, Any]     							=	None
_snake_case   :   List[Any]     							=	st.sidebar.checkbox('Generation options')
if generate_options:
				_snake_case   :   Tuple     							=	'\n    ### Answer generation options\n\n    The sequence-to-sequence model was initialized with [BART](https://huggingface.co/facebook/bart-large)\n    weights and fine-tuned on the ELI5 QA pairs and retrieved documents. You can use the model for greedy decoding with\n    **beam** search, or **sample** from the decoder\'s output probabilities.\n    '
				st.sidebar.markdown(generate_info)
				_snake_case   :   List[str]     							=	st.sidebar.selectbox('Would you like to use beam search or sample an answer?', ['beam', 'sampled'])
				_snake_case   :   Dict     							=	st.sidebar.slider(
				    'Minimum generation length', min_value=8, max_value=256, value=64, step=8, format=None, key=None
				)
				_snake_case   :   List[str]     							=	st.sidebar.slider(
				    'Maximum generation length', min_value=64, max_value=512, value=256, step=16, format=None, key=None
				)
				if sampled == "beam":
								_snake_case   :   Optional[Any]     							=	st.sidebar.slider('Beam size', min_value=1, max_value=8, value=2, step=None, format=None, key=None)
				else:
								_snake_case   :   Optional[Any]     							=	st.sidebar.slider(
								    'Nucleus sampling p', min_value=0.1, max_value=1.0, value=0.95, step=0.01, format=None, key=None
								)
								_snake_case   :   Dict     							=	st.sidebar.slider(
								    'Temperature', min_value=0.1, max_value=1.0, value=0.7, step=0.01, format=None, key=None
								)
								_snake_case   :   str     							=	None

# start main text
_snake_case   :   Dict     							=	[
    '<MY QUESTION>',
    'How do people make chocolate?',
    'Why do we get a fever when we are sick?',
    'How can different animals perceive different colors?',
    'What is natural language processing?',
    'What\'s the best way to treat a sunburn?',
    'What exactly are vitamins ?',
    'How does nuclear energy provide electricity?',
    'What\'s the difference between viruses and bacteria?',
    'Why are flutes classified as woodwinds when most of them are made out of metal ?',
    'Why do people like drinking coffee even though it tastes so bad?',
    'What happens when wine ages? How does it make the wine taste better?',
    'If an animal is an herbivore, where does it get the protein that it needs to survive if it only eats grass?',
    'How can we set a date to the beginning or end of an artistic period? Doesn\'t the change happen gradually?',
    'How does New Zealand have so many large bird predators?',
]
_snake_case   :   Any     							=	st.selectbox(
    'What would you like to ask? ---- select <MY QUESTION> to enter a new query',
    questions_list,
    index=1,
)
if question_s == "<MY QUESTION>":
				_snake_case   :   Optional[int]     							=	st.text_input('Enter your question here:', '')
else:
				_snake_case   :   Any     							=	question_s

if st.button('Show me!'):
				if action in [0, 1, 3]:
								if index_type == "mixed":
												_snake_case							,       _snake_case   :   List[str]     							=	make_support(question, source=wiki_source, method='dense', n_results=10)
												_snake_case							,       _snake_case   :   Union[str, Any]     							=	make_support(question, source=wiki_source, method='sparse', n_results=10)
												_snake_case   :   Dict     							=	[]
												for res_d, res_s in zip(support_list_dense, support_list_sparse):
																if tuple(res_d) not in support_list:
																				support_list += [tuple(res_d)]
																if tuple(res_s) not in support_list:
																				support_list += [tuple(res_s)]
												_snake_case   :   List[Any]     							=	support_list[:10]
												_snake_case   :   Union[str, Any]     							=	'<P> ' + ' <P> '.join([res[-1] for res in support_list])
								else:
												_snake_case							,       _snake_case   :   Any     							=	make_support(question, source=wiki_source, method=index_type, n_results=10)
				if action in [0, 3]:
								_snake_case							,       _snake_case   :   Optional[Any]     							=	answer_question(
								    question_doc,
								    sas_model,
								    sas_tokenizer,
								    min_len=min_len,
								    max_len=int(max_len),
								    sampling=(sampled == 'sampled'),
								    n_beams=n_beams,
								    top_p=top_p,
								    temp=temp,
								)
								st.markdown('### The model generated answer is:')
								st.write(answer)
				if action in [0, 1, 3] and wiki_source != "none":
								st.markdown('--- \n ### The model is drawing information from the following Wikipedia passages:')
								for i, res in enumerate(support_list):
												_snake_case   :   List[str]     							=	'https://en.wikipedia.org/wiki/{}'.format(res[0].replace(' ', '_'))
												_snake_case   :   str     							=	res[1].strip()
												if sec_titles == "":
																_snake_case   :   Dict     							=	'[{}]({})'.format(res[0], wiki_url)
												else:
																_snake_case   :   Optional[Any]     							=	sec_titles.split(' & ')
																_snake_case   :   Any     							=	' & '.join(
																    ['[{}]({}#{})'.format(sec.strip(), wiki_url, sec.strip().replace(' ', '_')) for sec in sec_list]
																)
												st.markdown(
												    '{0:02d} - **Article**: {1:<18} <br>  _Section_: {2}'.format(i + 1, res[0], sections),
												    unsafe_allow_html=True,
												)
												if show_passages:
																st.write(
																    '> <span style="font-family:arial; font-size:10pt;">' + res[-1] + '</span>', unsafe_allow_html=True
																)
				if action in [2, 3]:
								_snake_case   :   List[Any]     							=	find_nearest_training(question)
								_snake_case   :   int     							=	nn_train_list[0]
								st.markdown(
								    '--- \n ### The most similar question in the ELI5 training set was: \n\n {}'.format(train_exple['title'])
								)
								_snake_case   :   List[Any]     							=	[
								    '{}. {}'.format(i + 1, '  \n'.join([line.strip() for line in ans.split('\n') if line.strip() != '']))
								    for i, (ans, sc) in enumerate(zip(train_exple['answers']['text'], train_exple['answers']['score']))
								    if i == 0 or sc > 2
								]
								st.markdown('##### Its answers were: \n\n {}'.format('\n'.join(answers_st)))


_snake_case   :   Dict     							=	'\n---\n\n**Disclaimer**\n\n*The intent of this app is to provide some (hopefully entertaining) insights into the behavior of a current LFQA system.\nEvaluating biases of such a model and ensuring factual generations are still very much open research problems.\nTherefore, until some significant progress is achieved, we caution against using the generated answers for practical purposes.*\n'

st.sidebar.markdown(disclaimer, unsafe_allow_html=True)







'''simple docstring'''


import copy
import os
import tempfile
from unittest import TestCase
from unittest.mock import patch

import numpy as np
import pyarrow as pa
import pyarrow.parquet as pq
import pytest

from datasets.arrow_writer import ArrowWriter, OptimizedTypedSequence, ParquetWriter, TypedSequence
from datasets.features import ArrayaD, ClassLabel, Features, Image, Value
from datasets.features.features import ArrayaDExtensionType, cast_to_python_objects
from datasets.keyhash import DuplicatedKeysError, InvalidKeyError

from .utils import require_pil

class     A					(	_a					):







							def      __lowerCAmelCase    (						self :						List[Any]      )    ->							List[Any]:


														"""simple docstring"""


														_a			  =       pa.array(TypedSequence([1, 2, 3]      )      )
														self.assertEqual(arr.type							,    pa.intaa()      )







							def      __lowerCAmelCase    (						self :						List[str]      )    ->							str:


														"""simple docstring"""


														with self.assertRaises(lowerCAmelCase_      ):
																					_a			  =       pa.array(TypedSequence([1, 2, 3]      )							,    type=pa.intaa()      )







							def      __lowerCAmelCase    (						self :						Dict      )    ->							Dict:


														"""simple docstring"""


														with self.assertRaises(lowerCAmelCase_      ):
																					_a			  =       pa.array(TypedSequence([1, 2, 3]							,    try_type=Value('''bool'''      )							,    type=Value('''int64'''      )      )      )







							def      __lowerCAmelCase    (						self :						List[str]      )    ->							Optional[Any]:


														"""simple docstring"""


														_a			  =       pa.array(TypedSequence([1, 2, 3]							,    type=Value('''int32'''      )      )      )
														self.assertEqual(arr.type							,    pa.intaa()      )







							def      __lowerCAmelCase    (						self :						Any      )    ->							List[Any]:


														"""simple docstring"""


														with self.assertRaises((TypeError, pa.lib.ArrowInvalid)      ):
																					_a			  =       pa.array(TypedSequence(['''foo''', '''bar''']							,    type=Value('''int64'''      )      )      )







							def      __lowerCAmelCase    (						self :						Tuple      )    ->							List[Any]:


														"""simple docstring"""


														_a			  =       pa.array(TypedSequence([1, 2, 3]							,    try_type=Value('''int32'''      )      )      )
														self.assertEqual(arr.type							,    pa.intaa()      )







							def      __lowerCAmelCase    (						self :						Any      )    ->							Tuple:


														"""simple docstring"""


														_a			  =       pa.array(TypedSequence(['''foo''', '''bar''']							,    try_type=Value('''int64'''      )      )      )
														self.assertEqual(arr.type							,    pa.string()      )







							def      __lowerCAmelCase    (						self :						List[Any]      )    ->							str:


														"""simple docstring"""


														_a			  =       pa.array(TypedSequence([[[1, 2, 3]]]							,    type=ArrayaD((1, 3)							,    '''int64'''      )      )      )
														self.assertEqual(arr.type							,    ArrayaDExtensionType((1, 3)							,    '''int64'''      )      )







							def      __lowerCAmelCase    (						self :						Optional[Any]      )    ->							Optional[int]:


														"""simple docstring"""


														with self.assertRaises((TypeError, pa.lib.ArrowInvalid)      ):
																					_a			  =       pa.array(TypedSequence(['''foo''', '''bar''']							,    type=ArrayaD((1, 3)							,    '''int64'''      )      )      )







							def      __lowerCAmelCase    (						self :						Tuple      )    ->							Tuple:


														"""simple docstring"""


														_a			  =       pa.array(TypedSequence([[[1, 2, 3]]]							,    try_type=ArrayaD((1, 3)							,    '''int64'''      )      )      )
														self.assertEqual(arr.type							,    ArrayaDExtensionType((1, 3)							,    '''int64'''      )      )







							def      __lowerCAmelCase    (						self :						List[str]      )    ->							Any:


														"""simple docstring"""


														_a			  =       pa.array(TypedSequence(['''foo''', '''bar''']							,    try_type=ArrayaD((1, 3)							,    '''int64'''      )      )      )
														self.assertEqual(arr.type							,    pa.string()      )







							@require_pil
							def      __lowerCAmelCase    (						self :						Tuple      )    ->							List[Any]:


														"""simple docstring"""


														import PIL.Image

														_a			  =       PIL.Image.fromarray(np.arange(10							,    dtype=np.uinta      ).reshape(2							,    5      )      )
														with patch(
														    '''datasets.arrow_writer.cast_to_python_objects'''							,    side_effect=lowerCAmelCase_      ) as mock_cast_to_python_objects:
																					_a			  =       pa.array(TypedSequence([{'''path''': None, '''bytes''': B'''image_bytes'''}, pil_image]							,    type=Image()      )      )
																					_a  ,							_a			  =       mock_cast_to_python_objects.call_args_list[-1]
																					self.assertIn('''optimize_list_casting'''							,    lowerCAmelCase_      )
																					self.assertFalse(kwargs['''optimize_list_casting''']      )



def 	snake_case_					(UpperCamelCase :						Union[str, Any]				,		UpperCamelCase :						int   ):





							'''simple docstring'''


							_a			  =       pa.BufferReader(UpperCamelCase   ) if isinstance(UpperCamelCase				,		pa.Buffer   ) else pa.memory_map(UpperCamelCase   )
							_a			  =       pa.ipc.open_stream(UpperCamelCase   )
							_a			  =       f.read_all()
							assert len(pa_table.to_batches()   ) == expected_num_chunks
							assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]}
							del pa_table
@pytest.mark.parametrize('''writer_batch_size'''				,		[None, 1, 10]   )
@pytest.mark.parametrize(
    '''fields'''				,		[None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}]   )
def 	snake_case_					(UpperCamelCase :						Dict				,		UpperCamelCase :						str   ):





							'''simple docstring'''


							_a			  =       pa.BufferOutputStream()
							_a			  =       pa.schema(UpperCamelCase   ) if fields else None
							with ArrowWriter(stream=UpperCamelCase				,		schema=UpperCamelCase				,		writer_batch_size=UpperCamelCase   ) as writer:
														writer.write({'''col_1''': '''foo''', '''col_2''': 1}   )
														writer.write({'''col_1''': '''bar''', '''col_2''': 2}   )
														_a  ,							_a			  =       writer.finalize()
							assert num_examples == 2
							assert num_bytes > 0
							if not fields:
														_a			  =       {'''col_1''': pa.string(), '''col_2''': pa.intaa()}
							assert writer._schema == pa.schema(UpperCamelCase				,		metadata=writer._schema.metadata   )
							_check_output(output.getvalue()				,		expected_num_chunks=num_examples if writer_batch_size == 1 else 1   )
def 	snake_case_					():





							'''simple docstring'''


							_a			  =       pa.BufferOutputStream()
							_a			  =       Features({'''labels''': ClassLabel(names=['''neg''', '''pos''']   )}   )
							with ArrowWriter(stream=UpperCamelCase				,		features=UpperCamelCase   ) as writer:
														writer.write({'''labels''': 0}   )
														writer.write({'''labels''': 1}   )
														_a  ,							_a			  =       writer.finalize()
							assert num_examples == 2
							assert num_bytes > 0
							assert writer._schema == features.arrow_schema
							assert writer._schema.metadata == features.arrow_schema.metadata
							_a			  =       pa.BufferReader(output.getvalue()   )
							_a			  =       pa.ipc.open_stream(UpperCamelCase   )
							_a			  =       f.read_all()
							_a			  =       pa_table.schema
							assert pa_table.num_rows == 2
							assert schema == features.arrow_schema
							assert schema.metadata == features.arrow_schema.metadata
							assert features == Features.from_arrow_schema(UpperCamelCase   )
@pytest.mark.parametrize('''writer_batch_size'''				,		[None, 1, 10]   )
def 	snake_case_					(UpperCamelCase :						Any   ):





							'''simple docstring'''


							_a			  =       pa.BufferOutputStream()
							with ArrowWriter(
							    stream=UpperCamelCase				,		writer_batch_size=UpperCamelCase				,		hash_salt='''split_name'''				,		check_duplicates=UpperCamelCase				,		) as writer:
														with pytest.raises(UpperCamelCase   ):
																					writer.write({'''col_1''': '''foo''', '''col_2''': 1}				,		key=[1, 2]   )
																					_a  ,							_a			  =       writer.finalize()
@pytest.mark.parametrize('''writer_batch_size'''				,		[None, 2, 10]   )
def 	snake_case_					(UpperCamelCase :						Any   ):





							'''simple docstring'''


							_a			  =       pa.BufferOutputStream()
							with ArrowWriter(
							    stream=UpperCamelCase				,		writer_batch_size=UpperCamelCase				,		hash_salt='''split_name'''				,		check_duplicates=UpperCamelCase				,		) as writer:
														with pytest.raises(UpperCamelCase   ):
																					writer.write({'''col_1''': '''foo''', '''col_2''': 1}				,		key=10   )
																					writer.write({'''col_1''': '''bar''', '''col_2''': 2}				,		key=10   )
																					_a  ,							_a			  =       writer.finalize()
@pytest.mark.parametrize('''writer_batch_size'''				,		[None, 2, 10]   )
def 	snake_case_					(UpperCamelCase :						int   ):





							'''simple docstring'''


							_a			  =       pa.BufferOutputStream()
							with ArrowWriter(
							    stream=UpperCamelCase				,		writer_batch_size=UpperCamelCase				,		hash_salt='''split_name'''				,		check_duplicates=UpperCamelCase				,		) as writer:
														writer.write({'''col_1''': '''foo''', '''col_2''': 1}				,		key=1   )
														writer.write({'''col_1''': '''bar''', '''col_2''': 2}				,		key=2   )
														_a  ,							_a			  =       writer.finalize()
							assert num_examples == 2
							assert num_bytes > 0
							_check_output(output.getvalue()				,		expected_num_chunks=num_examples if writer_batch_size == 1 else 1   )
@pytest.mark.parametrize('''writer_batch_size'''				,		[None, 1, 10]   )
@pytest.mark.parametrize(
    '''fields'''				,		[None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}]   )
def 	snake_case_					(UpperCamelCase :						Dict				,		UpperCamelCase :						List[str]   ):





							'''simple docstring'''


							_a			  =       pa.BufferOutputStream()
							_a			  =       pa.schema(UpperCamelCase   ) if fields else None
							with ArrowWriter(stream=UpperCamelCase				,		schema=UpperCamelCase				,		writer_batch_size=UpperCamelCase   ) as writer:
														writer.write_batch({'''col_1''': ['''foo''', '''bar'''], '''col_2''': [1, 2]}   )
														writer.write_batch({'''col_1''': [], '''col_2''': []}   )
														_a  ,							_a			  =       writer.finalize()
							assert num_examples == 2
							assert num_bytes > 0
							if not fields:
														_a			  =       {'''col_1''': pa.string(), '''col_2''': pa.intaa()}
							assert writer._schema == pa.schema(UpperCamelCase				,		metadata=writer._schema.metadata   )
							_check_output(output.getvalue()				,		expected_num_chunks=num_examples if writer_batch_size == 1 else 1   )
@pytest.mark.parametrize('''writer_batch_size'''				,		[None, 1, 10]   )
@pytest.mark.parametrize(
    '''fields'''				,		[None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}]   )
def 	snake_case_					(UpperCamelCase :						Any				,		UpperCamelCase :						Any   ):





							'''simple docstring'''


							_a			  =       pa.BufferOutputStream()
							_a			  =       pa.schema(UpperCamelCase   ) if fields else None
							with ArrowWriter(stream=UpperCamelCase				,		schema=UpperCamelCase				,		writer_batch_size=UpperCamelCase   ) as writer:
														writer.write_table(pa.Table.from_pydict({'''col_1''': ['''foo''', '''bar'''], '''col_2''': [1, 2]}   )   )
														_a  ,							_a			  =       writer.finalize()
							assert num_examples == 2
							assert num_bytes > 0
							if not fields:
														_a			  =       {'''col_1''': pa.string(), '''col_2''': pa.intaa()}
							assert writer._schema == pa.schema(UpperCamelCase				,		metadata=writer._schema.metadata   )
							_check_output(output.getvalue()				,		expected_num_chunks=num_examples if writer_batch_size == 1 else 1   )
@pytest.mark.parametrize('''writer_batch_size'''				,		[None, 1, 10]   )
@pytest.mark.parametrize(
    '''fields'''				,		[None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}]   )
def 	snake_case_					(UpperCamelCase :						int				,		UpperCamelCase :						Optional[int]   ):





							'''simple docstring'''


							_a			  =       pa.BufferOutputStream()
							_a			  =       pa.schema(UpperCamelCase   ) if fields else None
							with ArrowWriter(stream=UpperCamelCase				,		schema=UpperCamelCase				,		writer_batch_size=UpperCamelCase   ) as writer:
														writer.write_row(pa.Table.from_pydict({'''col_1''': ['''foo'''], '''col_2''': [1]}   )   )
														writer.write_row(pa.Table.from_pydict({'''col_1''': ['''bar'''], '''col_2''': [2]}   )   )
														_a  ,							_a			  =       writer.finalize()
							assert num_examples == 2
							assert num_bytes > 0
							if not fields:
														_a			  =       {'''col_1''': pa.string(), '''col_2''': pa.intaa()}
							assert writer._schema == pa.schema(UpperCamelCase				,		metadata=writer._schema.metadata   )
							_check_output(output.getvalue()				,		expected_num_chunks=num_examples if writer_batch_size == 1 else 1   )
def 	snake_case_					():





							'''simple docstring'''


							with tempfile.TemporaryDirectory() as tmp_dir:
														_a			  =       {'''col_1''': pa.string(), '''col_2''': pa.intaa()}
														_a			  =       os.path.join(UpperCamelCase				,		'''test.arrow'''   )
														with ArrowWriter(path=UpperCamelCase				,		schema=pa.schema(UpperCamelCase   )   ) as writer:
																					writer.write_batch({'''col_1''': ['''foo''', '''bar'''], '''col_2''': [1, 2]}   )
																					_a  ,							_a			  =       writer.finalize()
														assert num_examples == 2
														assert num_bytes > 0
														assert writer._schema == pa.schema(UpperCamelCase				,		metadata=writer._schema.metadata   )
														_check_output(UpperCamelCase				,		1   )
def 	snake_case_					(UpperCamelCase :						List[str]   ):





							'''simple docstring'''


							if pa.types.is_list(UpperCamelCase   ):
														return get_base_dtype(arr_type.value_type   )
							else:
														return arr_type
def 	snake_case_					(UpperCamelCase :						Optional[int]				,		UpperCamelCase :						Any   ):





							'''simple docstring'''


							if isinstance(lst[0]				,		UpperCamelCase   ):
														change_first_primitive_element_in_list(lst[0]				,		UpperCamelCase   )
							else:
														_a			  =       value
@pytest.mark.parametrize('''optimized_int_type, expected_dtype'''				,		[(None, pa.intaa()), (Value('''int32'''   ), pa.intaa())]   )
@pytest.mark.parametrize('''sequence'''				,		[[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]]   )
def 	snake_case_					(UpperCamelCase :						int				,		UpperCamelCase :						Tuple				,		UpperCamelCase :						Optional[int]   ):





							'''simple docstring'''


							_a			  =       pa.array(TypedSequence(UpperCamelCase				,		optimized_int_type=UpperCamelCase   )   )
							assert get_base_dtype(arr.type   ) == expected_dtype
@pytest.mark.parametrize(
    '''col, expected_dtype'''				,		[
        ('''attention_mask''', pa.inta()),
        ('''special_tokens_mask''', pa.inta()),
        ('''token_type_ids''', pa.inta()),
        ('''input_ids''', pa.intaa()),
        ('''other''', pa.intaa()),
    ]				,		)
@pytest.mark.parametrize('''sequence'''				,		[[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]]   )
def 	snake_case_					(UpperCamelCase :						List[Any]				,		UpperCamelCase :						str				,		UpperCamelCase :						List[Any]   ):





							'''simple docstring'''


							_a			  =       pa.array(OptimizedTypedSequence(UpperCamelCase				,		col=UpperCamelCase   )   )
							assert get_base_dtype(arr.type   ) == expected_dtype

							# not in range
							if col != "other":
														# avoids errors due to in-place modifications
														_a			  =       copy.deepcopy(UpperCamelCase   )
														_a			  =       np.iinfo(expected_dtype.to_pandas_dtype()   ).max + 1
														change_first_primitive_element_in_list(UpperCamelCase				,		UpperCamelCase   )
														_a			  =       pa.array(OptimizedTypedSequence(UpperCamelCase				,		col=UpperCamelCase   )   )
														assert get_base_dtype(arr.type   ) == pa.intaa()
@pytest.mark.parametrize('''raise_exception'''				,		[False, True]   )
def 	snake_case_					(UpperCamelCase :						Optional[Any]				,		UpperCamelCase :						Optional[Any]   ):





							'''simple docstring'''


							_a			  =       str(tmp_path / '''dataset-train.arrow'''   )
							try:
														with ArrowWriter(path=UpperCamelCase   ) as writer:
																					if raise_exception:
																												raise pa.lib.ArrowInvalid()
																					else:
																												writer.stream.close()
							except pa.lib.ArrowInvalid:
														pass
							finally:
														assert writer.stream.closed
def 	snake_case_					(UpperCamelCase :						List[Any]   ):





							'''simple docstring'''


							_a			  =       '''mock://dataset-train.arrow'''
							with ArrowWriter(path=UpperCamelCase				,		storage_options=mockfs.storage_options   ) as writer:
														assert isinstance(writer._fs				,		type(UpperCamelCase   )   )
														assert writer._fs.storage_options == mockfs.storage_options
														writer.write({'''col_1''': '''foo''', '''col_2''': 1}   )
														writer.write({'''col_1''': '''bar''', '''col_2''': 2}   )
														_a  ,							_a			  =       writer.finalize()
							assert num_examples == 2
							assert num_bytes > 0
							assert mockfs.exists(UpperCamelCase   )
def 	snake_case_					():





							'''simple docstring'''


							_a			  =       pa.BufferOutputStream()
							with ParquetWriter(stream=UpperCamelCase   ) as writer:
														writer.write({'''col_1''': '''foo''', '''col_2''': 1}   )
														writer.write({'''col_1''': '''bar''', '''col_2''': 2}   )
														_a  ,							_a			  =       writer.finalize()
							assert num_examples == 2
							assert num_bytes > 0
							_a			  =       pa.BufferReader(output.getvalue()   )
							_a			  =       pq.read_table(UpperCamelCase   )
							assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]}
@require_pil
@pytest.mark.parametrize('''embed_local_files'''				,		[False, True]   )
def 	snake_case_					(UpperCamelCase :						List[Any]				,		UpperCamelCase :						List[Any]   ):





							'''simple docstring'''


							import PIL.Image

							_a			  =       str(tmp_path / '''test_image_rgb.jpg'''   )
							PIL.Image.fromarray(np.zeros((5, 5)				,		dtype=np.uinta   )   ).save(UpperCamelCase				,		format='''png'''   )
							_a			  =       pa.BufferOutputStream()
							with ParquetWriter(
							    stream=UpperCamelCase				,		features=Features({'''image''': Image()}   )				,		embed_local_files=UpperCamelCase   ) as writer:
														writer.write({'''image''': image_path}   )
														writer.finalize()
							_a			  =       pa.BufferReader(output.getvalue()   )
							_a			  =       pq.read_table(UpperCamelCase   )
							_a			  =       pa_table.to_pydict()
							if embed_local_files:
														assert isinstance(out['''image'''][0]['''path''']				,		UpperCamelCase   )
														with open(UpperCamelCase				,		'''rb'''   ) as f:
																					assert out["image"][0]["bytes"] == f.read()
							else:
														assert out["image"][0]["path"] == image_path
														assert out["image"][0]["bytes"] is None

def 	snake_case_					():





							'''simple docstring'''


							_a			  =       pa.schema([pa.field('''col_1'''				,		pa.string()				,		nullable=UpperCamelCase   )]   )
							_a			  =       pa.BufferOutputStream()
							with ArrowWriter(stream=UpperCamelCase   ) as writer:
														writer._build_writer(inferred_schema=UpperCamelCase   )
														assert writer._schema == pa.schema([pa.field('''col_1'''				,		pa.string()   )]   )

