






"""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


lowercase_				     =     'bart'
lowercase_				     =     True



@st.cache(allow_output_mutation=__UpperCamelCase )
def 					lowerCAmelCase				(    ):




  """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 					lowerCAmelCase				(    ):




  """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, 1_2_8)		,       )
    __A									= faiss.IndexFlatIP(1_2_8 )
    __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 					lowerCAmelCase				(    ):




  """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, 1_2_8) )
  __A									= faiss.IndexFlatIP(1_2_8 )
  eli5_train_q_index.add(__UpperCamelCase )
  return (elia_train, eli5_train_q_index)


lowercase_     ,		lowercase_     ,		lowercase_				     =     load_indexes()
lowercase_     ,		lowercase_     ,		lowercase_     ,		lowercase_				     =     load_models()
lowercase_     ,		lowercase_				     =     load_train_data()



def 					lowerCAmelCase				(    __UpperCamelCase		,       __UpperCamelCase=1_0 ):




  """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 					lowerCAmelCase				(    __UpperCamelCase		,       __UpperCamelCase="wiki40b"		,       __UpperCamelCase="dense"		,       __UpperCamelCase=1_0 ):




  """simple docstring"""







  if source == "none":
    __A			,    __A									= (''' <P> '''.join(['''''' for _ in range(1_1 )] ).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 					lowerCAmelCase				(    __UpperCamelCase		,       __UpperCamelCase		,       __UpperCamelCase		,       __UpperCamelCase=6_4		,       __UpperCamelCase=2_5_6		,       __UpperCamelCase=False		,       __UpperCamelCase=2		,       __UpperCamelCase=0.95		,       __UpperCamelCase=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=1_0_2_4		,       device='''cuda:0'''		,       )[0]
  return (answer, support_list)


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

# Start sidebar
lowercase_				     =     '<img src=\'https://huggingface.co/front/assets/huggingface_logo.svg\'>'
lowercase_				     =     '\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
lowercase_				     =     '\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)

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

lowercase_				     =     st.sidebar.checkbox('Retrieval options')
if retrieval_options:
       lowercase_				     =     '\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)
       lowercase_				     =     st.sidebar.selectbox('Which Wikipedia format should the model use?', ['wiki40b', 'none'])
       lowercase_				     =     st.sidebar.selectbox('Which Wikipedia indexer should the model use?', ['dense', 'sparse', 'mixed'])
else:
       lowercase_				     =     'wiki40b'
       lowercase_				     =     'dense'

lowercase_				     =     'beam'
lowercase_				     =     2
lowercase_				     =     64
lowercase_				     =     256
lowercase_				     =     None
lowercase_				     =     None
lowercase_				     =     st.sidebar.checkbox('Generation options')
if generate_options:
       lowercase_				     =     '\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)
       lowercase_				     =     st.sidebar.selectbox('Would you like to use beam search or sample an answer?', ['beam', 'sampled'])
       lowercase_				     =     st.sidebar.slider(
           'Minimum generation length', min_value=8, max_value=256, value=64, step=8, format=None, key=None
       )
       lowercase_				     =     st.sidebar.slider(
           'Maximum generation length', min_value=64, max_value=512, value=256, step=16, format=None, key=None
       )
       if sampled == "beam":
              lowercase_				     =     st.sidebar.slider('Beam size', min_value=1, max_value=8, value=2, step=None, format=None, key=None)
       else:
              lowercase_				     =     st.sidebar.slider(
                  'Nucleus sampling p', min_value=0.1, max_value=1.0, value=0.95, step=0.01, format=None, key=None
              )
              lowercase_				     =     st.sidebar.slider(
                  'Temperature', min_value=0.1, max_value=1.0, value=0.7, step=0.01, format=None, key=None
              )
              lowercase_				     =     None

# start main text
lowercase_				     =     [
    '<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?',
]
lowercase_				     =     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>":
       lowercase_				     =     st.text_input('Enter your question here:', '')
else:
       lowercase_				     =     question_s

if st.button('Show me!'):
       if action in [0, 1, 3]:
              if index_type == "mixed":
                     lowercase_     ,		lowercase_				     =     make_support(question, source=wiki_source, method='dense', n_results=10)
                     lowercase_     ,		lowercase_				     =     make_support(question, source=wiki_source, method='sparse', n_results=10)
                     lowercase_				     =     []
                     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)]
                     lowercase_				     =     support_list[:10]
                     lowercase_				     =     '<P> ' + ' <P> '.join([res[-1] for res in support_list])
              else:
                     lowercase_     ,		lowercase_				     =     make_support(question, source=wiki_source, method=index_type, n_results=10)
       if action in [0, 3]:
              lowercase_     ,		lowercase_				     =     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):
                     lowercase_				     =     'https://en.wikipedia.org/wiki/{}'.format(res[0].replace(' ', '_'))
                     lowercase_				     =     res[1].strip()
                     if sec_titles == "":
                            lowercase_				     =     '[{}]({})'.format(res[0], wiki_url)
                     else:
                            lowercase_				     =     sec_titles.split(' & ')
                            lowercase_				     =     ' & '.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]:
              lowercase_				     =     find_nearest_training(question)
              lowercase_				     =     nn_train_list[0]
              st.markdown(
                  '--- \n ### The most similar question in the ELI5 training set was: \n\n {}'.format(train_exple['title'])
              )
              lowercase_				     =     [
                  '{}. {}'.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)))


lowercase_				     =     '\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 importlib
import inspect
import json
import os
import re
import shutil
import sys
from pathlib import Path
from typing import Dict, Optional, Union
from urllib import request

from huggingface_hub import HfFolder, cached_download, hf_hub_download, model_info
from packaging import version

from .. import __version__
from . import DIFFUSERS_DYNAMIC_MODULE_NAME, HF_MODULES_CACHE, logging


lowercase_				     =     (
    'https://raw.githubusercontent.com/huggingface/diffusers/{revision}/examples/community/{pipeline}.py'
)


lowercase_				     =     logging.get_logger(__name__)  # pylint: disable=invalid-name



def 					lowerCAmelCase				(    ):




  """simple docstring"""







  __A									= '''https://pypi.org/pypi/diffusers/json'''
  __A									= json.loads(request.urlopen(__UpperCamelCase ).read() )['''releases'''].keys()
  return sorted(__UpperCamelCase		,       key=lambda __UpperCamelCase : version.Version(__UpperCamelCase ) )



def 					lowerCAmelCase				(    ):




  """simple docstring"""







  if HF_MODULES_CACHE in sys.path:
    return

  sys.path.append(__UpperCamelCase )
  os.makedirs(__UpperCamelCase		,       exist_ok=__UpperCamelCase )
  __A									= Path(__UpperCamelCase ) / '''__init__.py'''
  if not init_path.exists():
    init_path.touch()



def 					lowerCAmelCase				(    __UpperCamelCase ):




  """simple docstring"""







  init_hf_modules()
  __A									= Path(__UpperCamelCase ) / name
  # If the parent module does not exist yet, recursively create it.
  if not dynamic_module_path.parent.exists():
    create_dynamic_module(dynamic_module_path.parent )
  os.makedirs(__UpperCamelCase		,       exist_ok=__UpperCamelCase )
  __A									= dynamic_module_path / '''__init__.py'''
  if not init_path.exists():
    init_path.touch()



def 					lowerCAmelCase				(    __UpperCamelCase ):




  """simple docstring"""







  with open(__UpperCamelCase		,       '''r'''		,       encoding='''utf-8''' ) as f:
    __A									= f.read()

  # Imports of the form `import .xxx`
  __A									= re.findall('''^\s*import\s+\.(\S+)\s*$'''		,       __UpperCamelCase		,       flags=re.MULTILINE )
  # Imports of the form `from .xxx import yyy`
  relative_imports += re.findall('''^\s*from\s+\.(\S+)\s+import'''		,       __UpperCamelCase		,       flags=re.MULTILINE )
  # Unique-ify
  return list(set(__UpperCamelCase ) )



def 					lowerCAmelCase				(    __UpperCamelCase ):




  """simple docstring"""







  __A									= False
  __A									= [module_file]
  __A									= []

  # Let's recurse through all relative imports
  while not no_change:
    __A									= []
    for f in files_to_check:
      new_imports.extend(get_relative_imports(__UpperCamelCase ) )

    __A									= Path(__UpperCamelCase ).parent
    __A									= [str(module_path / m ) for m in new_imports]
    __A									= [f for f in new_import_files if f not in all_relative_imports]
    __A									= [f'{f}.py' for f in new_import_files]

    __A									= len(__UpperCamelCase ) == 0
    all_relative_imports.extend(__UpperCamelCase )

  return all_relative_imports



def 					lowerCAmelCase				(    __UpperCamelCase ):




  """simple docstring"""







  with open(__UpperCamelCase		,       '''r'''		,       encoding='''utf-8''' ) as f:
    __A									= f.read()

  # Imports of the form `import xxx`
  __A									= re.findall('''^\s*import\s+(\S+)\s*$'''		,       __UpperCamelCase		,       flags=re.MULTILINE )
  # Imports of the form `from xxx import yyy`
  imports += re.findall('''^\s*from\s+(\S+)\s+import'''		,       __UpperCamelCase		,       flags=re.MULTILINE )
  # Only keep the top-level module
  __A									= [imp.split('''.''' )[0] for imp in imports if not imp.startswith('''.''' )]

  # Unique-ify and test we got them all
  __A									= list(set(__UpperCamelCase ) )
  __A									= []
  for imp in imports:
    try:
      importlib.import_module(__UpperCamelCase )
    except ImportError:
      missing_packages.append(__UpperCamelCase )

  if len(__UpperCamelCase ) > 0:
    raise ImportError(
        '''This modeling file requires the following packages that were not found in your environment: '''
        f'{", ".join(__UpperCamelCase )}. Run `pip install {" ".join(__UpperCamelCase )}`' )

  return get_relative_imports(__UpperCamelCase )



def 					lowerCAmelCase				(    __UpperCamelCase		,       __UpperCamelCase ):




  """simple docstring"""







  __A									= module_path.replace(os.path.sep		,       '''.''' )
  __A									= importlib.import_module(__UpperCamelCase )

  if class_name is None:
    return find_pipeline_class(__UpperCamelCase )
  return getattr(__UpperCamelCase		,       __UpperCamelCase )



def 					lowerCAmelCase				(    __UpperCamelCase ):




  """simple docstring"""







  from ..pipelines import DiffusionPipeline

  __A									= dict(inspect.getmembers(__UpperCamelCase		,       inspect.isclass ) )

  __A									= None
  for cls_name, cls in cls_members.items():
    if (
        cls_name != DiffusionPipeline.__name__
        and issubclass(cls		,       __UpperCamelCase )
        and cls.__module__.split('''.''' )[0] != "diffusers"
    ):
      if pipeline_class is not None:
        raise ValueError(
            f'Multiple classes that inherit from {DiffusionPipeline.__name__} have been found:'
            f' {pipeline_class.__name__}, and {cls_name}. Please make sure to define only one in'
            f' {loaded_module}.' )
      __A									= cls

  return pipeline_class



def 					lowerCAmelCase				(    __UpperCamelCase		,       __UpperCamelCase		,       __UpperCamelCase = None		,       __UpperCamelCase = False		,       __UpperCamelCase = False		,       __UpperCamelCase = None		,       __UpperCamelCase = None		,       __UpperCamelCase = None		,       __UpperCamelCase = False		,       ):




  """simple docstring"""







  __A									= str(__UpperCamelCase )

  __A									= os.path.join(__UpperCamelCase		,       __UpperCamelCase )

  if os.path.isfile(__UpperCamelCase ):
    __A									= module_file_or_url
    __A									= '''local'''
  elif pretrained_model_name_or_path.count('''/''' ) == 0:
    __A									= get_diffusers_versions()
    # cut ".dev0"
    __A									= '''v''' + '''.'''.join(__version__.split('''.''' )[:3] )

    # retrieve github version that matches
    if revision is None:
      __A									= latest_version if latest_version[1:] in available_versions else '''main'''
      logger.info(f'Defaulting to latest_version: {revision}.' )
    elif revision in available_versions:
      __A									= f'v{revision}'
    elif revision == "main":
      __A									= revision
    else:
      raise ValueError(
          f'`custom_revision`: {revision} does not exist. Please make sure to choose one of'
          f' {", ".join(available_versions + ["main"] )}.' )

    # community pipeline on GitHub
    __A									= COMMUNITY_PIPELINES_URL.format(revision=__UpperCamelCase		,       pipeline=__UpperCamelCase )
    try:
      __A									= cached_download(
          __UpperCamelCase		,       cache_dir=__UpperCamelCase		,       force_download=__UpperCamelCase		,       proxies=__UpperCamelCase		,       resume_download=__UpperCamelCase		,       local_files_only=__UpperCamelCase		,       use_auth_token=__UpperCamelCase		,       )
      __A									= '''git'''
      __A									= pretrained_model_name_or_path + '''.py'''
    except EnvironmentError:
      logger.error(f'Could not locate the {module_file} inside {pretrained_model_name_or_path}.' )
      raise
  else:
    try:
      # Load from URL or cache if already cached
      __A									= hf_hub_download(
          __UpperCamelCase		,       __UpperCamelCase		,       cache_dir=__UpperCamelCase		,       force_download=__UpperCamelCase		,       proxies=__UpperCamelCase		,       resume_download=__UpperCamelCase		,       local_files_only=__UpperCamelCase		,       use_auth_token=__UpperCamelCase		,       )
      __A									= os.path.join('''local'''		,       '''--'''.join(pretrained_model_name_or_path.split('''/''' ) ) )
    except EnvironmentError:
      logger.error(f'Could not locate the {module_file} inside {pretrained_model_name_or_path}.' )
      raise

    # Check we have all the requirements in our environment
  __A									= check_imports(__UpperCamelCase )

  # Now we move the module inside our cached dynamic modules.
  __A									= DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule
  create_dynamic_module(__UpperCamelCase )
  __A									= Path(__UpperCamelCase ) / full_submodule
  if submodule == "local" or submodule == "git":
    # We always copy local files (we could hash the file to see if there was a change, and give them the name of
    # that hash, to only copy when there is a modification but it seems overkill for now).
    # The only reason we do the copy is to avoid putting too many folders in sys.path.
    shutil.copy(__UpperCamelCase		,       submodule_path / module_file )
    for module_needed in modules_needed:
      __A									= f'{module_needed}.py'
      shutil.copy(os.path.join(__UpperCamelCase		,       __UpperCamelCase )		,       submodule_path / module_needed )
  else:
    # Get the commit hash
    # TODO: we will get this info in the etag soon, so retrieve it from there and not here.
    if isinstance(__UpperCamelCase		,       __UpperCamelCase ):
      __A									= use_auth_token
    elif use_auth_token is True:
      __A									= HfFolder.get_token()
    else:
      __A									= None

    __A									= model_info(__UpperCamelCase		,       revision=__UpperCamelCase		,       token=__UpperCamelCase ).sha

    # The module file will end up being placed in a subfolder with the git hash of the repo. This way we get the
    # benefit of versioning.
    __A									= submodule_path / commit_hash
    __A									= full_submodule + os.path.sep + commit_hash
    create_dynamic_module(__UpperCamelCase )

    if not (submodule_path / module_file).exists():
      shutil.copy(__UpperCamelCase		,       submodule_path / module_file )
    # Make sure we also have every file with relative
    for module_needed in modules_needed:
      if not (submodule_path / module_needed).exists():
        get_cached_module_file(
            __UpperCamelCase		,       f'{module_needed}.py'		,       cache_dir=__UpperCamelCase		,       force_download=__UpperCamelCase		,       resume_download=__UpperCamelCase		,       proxies=__UpperCamelCase		,       use_auth_token=__UpperCamelCase		,       revision=__UpperCamelCase		,       local_files_only=__UpperCamelCase		,       )
  return os.path.join(__UpperCamelCase		,       __UpperCamelCase )





def 					lowerCAmelCase				(    __UpperCamelCase		,       __UpperCamelCase		,       __UpperCamelCase = None		,       __UpperCamelCase = None		,       __UpperCamelCase = False		,       __UpperCamelCase = False		,       __UpperCamelCase = None		,       __UpperCamelCase = None		,       __UpperCamelCase = None		,       __UpperCamelCase = False		,       **__UpperCamelCase		,       ):




  """simple docstring"""







  __A									= get_cached_module_file(
      __UpperCamelCase		,       __UpperCamelCase		,       cache_dir=__UpperCamelCase		,       force_download=__UpperCamelCase		,       resume_download=__UpperCamelCase		,       proxies=__UpperCamelCase		,       use_auth_token=__UpperCamelCase		,       revision=__UpperCamelCase		,       local_files_only=__UpperCamelCase		,       )
  return get_class_in_module(__UpperCamelCase		,       final_module.replace('''.py'''		,       '''''' ) )




