





import argparse
import collections
import json
import os
import re
import string
import sys

import numpy as np


_UpperCAmelCase             =							re.compile(R'\b(a|an|the)\b', re.UNICODE)

_UpperCAmelCase             =							None






def 	_SCREAMING_SNAKE_CASE		(      )      ->   Any:
 __lowerCAmelCase					:	int      =       argparse.ArgumentParser("""Official evaluation script for SQuAD version 2.0."""   )
 parser.add_argument("""data_file"""   ,   metavar="""data.json"""   ,   help="""Input data JSON file."""   )
 parser.add_argument("""pred_file"""   ,   metavar="""pred.json"""   ,   help="""Model predictions."""   )
 parser.add_argument(
     """--out-file"""   ,   """-o"""   ,   metavar="""eval.json"""   ,   help="""Write accuracy metrics to file (default is stdout)."""   )
 parser.add_argument(
     """--na-prob-file"""   ,   """-n"""   ,   metavar="""na_prob.json"""   ,   help="""Model estimates of probability of no answer."""   )
 parser.add_argument(
     """--na-prob-thresh"""   ,   """-t"""   ,   type=__UpperCamelCase   ,   default=1.0   ,   help="""Predict \"\" if no-answer probability exceeds this (default = 1.0)."""   ,   )
 parser.add_argument(
     """--out-image-dir"""   ,   """-p"""   ,   metavar="""out_images"""   ,   default=__UpperCamelCase   ,   help="""Save precision-recall curves to directory."""   )
 parser.add_argument("""--verbose"""   ,   """-v"""   ,   action="""store_true"""   )
 if len(sys.argv   ) == 1:
  parser.print_help()
  sys.exit(1   )
 return parser.parse_args()






def 	_SCREAMING_SNAKE_CASE		(      SCREAMING_SNAKE_CASE		:str   )      ->   List[Any]:
 __lowerCAmelCase					:	str      =       {}
 for article in dataset:
  for p in article["paragraphs"]:
   for qa in p["qas"]:
    __lowerCAmelCase					:	str      =       bool(qa["""answers"""]["""text"""]   )
 return qid_to_has_ans






def 	_SCREAMING_SNAKE_CASE		(      SCREAMING_SNAKE_CASE		:Any   )      ->   Optional[int]:


 def remove_articles(SCREAMING_SNAKE_CASE		:str   ):
  return ARTICLES_REGEX.sub(""" """   ,   __UpperCamelCase   )

 def white_space_fix(SCREAMING_SNAKE_CASE		:str   ):
  return " ".join(text.split()   )

 def remove_punc(SCREAMING_SNAKE_CASE		:Tuple   ):
  __lowerCAmelCase					:	Optional[int]      =       set(string.punctuation   )
  return "".join(ch for ch in text if ch not in exclude   )

 def lower(SCREAMING_SNAKE_CASE		:str   ):
  return text.lower()

 return white_space_fix(remove_articles(remove_punc(lower(__UpperCamelCase   )   )   )   )






def 	_SCREAMING_SNAKE_CASE		(      SCREAMING_SNAKE_CASE		:Tuple   )      ->   Union[str, Any]:


 if not s:
  return []
 return normalize_answer(__UpperCamelCase   ).split()






def 	_SCREAMING_SNAKE_CASE		(      SCREAMING_SNAKE_CASE		:Tuple   ,   SCREAMING_SNAKE_CASE		:int   )      ->   str:
 return int(normalize_answer(__UpperCamelCase   ) == normalize_answer(__UpperCamelCase   )   )






def 	_SCREAMING_SNAKE_CASE		(      SCREAMING_SNAKE_CASE		:Tuple   ,   SCREAMING_SNAKE_CASE		:Optional[int]   )      ->   Optional[Any]:
 __lowerCAmelCase					:	str      =       get_tokens(__UpperCamelCase   )
 __lowerCAmelCase					:	List[Any]      =       get_tokens(__UpperCamelCase   )
 __lowerCAmelCase					:	Union[str, Any]      =       collections.Counter(__UpperCamelCase   ) & collections.Counter(__UpperCamelCase   )
 __lowerCAmelCase					:	int      =       sum(common.values()   )
 if len(__UpperCamelCase   ) == 0 or len(__UpperCamelCase   ) == 0:
  # If either is no-answer, then F1 is 1 if they agree, 0 otherwise
  return int(gold_toks == pred_toks   )
 if num_same == 0:
  return 0
 __lowerCAmelCase					:	Optional[int]      =       1.0 * num_same / len(__UpperCamelCase   )
 __lowerCAmelCase					:	Dict      =       1.0 * num_same / len(__UpperCamelCase   )
 __lowerCAmelCase					:	Any      =       (2 * precision * recall) / (precision + recall)
 return fa






def 	_SCREAMING_SNAKE_CASE		(      SCREAMING_SNAKE_CASE		:Any   ,   SCREAMING_SNAKE_CASE		:Union[str, Any]   )      ->   Optional[Any]:
 __lowerCAmelCase					:	Tuple      =       {}
 __lowerCAmelCase					:	List[str]      =       {}
 for article in dataset:
  for p in article["paragraphs"]:
   for qa in p["qas"]:
    __lowerCAmelCase					:	List[str]      =       qa["""id"""]
    __lowerCAmelCase					:	int      =       [t for t in qa["""answers"""]["""text"""] if normalize_answer(__UpperCamelCase   )]
    if not gold_answers:
     # For unanswerable questions, only correct answer is empty string
     __lowerCAmelCase					:	Dict      =       [""""""]
    if qid not in preds:
     print(F'''Missing prediction for {qid}'''   )
     continue
    __lowerCAmelCase					:	Any      =       preds[qid]
    # Take max over all gold answers
    __lowerCAmelCase					:	str      =       max(compute_exact(__UpperCamelCase   ,   __UpperCamelCase   ) for a in gold_answers   )
    __lowerCAmelCase					:	Optional[int]      =       max(compute_fa(__UpperCamelCase   ,   __UpperCamelCase   ) for a in gold_answers   )
 return exact_scores, fa_scores






def 	_SCREAMING_SNAKE_CASE		(      SCREAMING_SNAKE_CASE		:List[Any]   ,   SCREAMING_SNAKE_CASE		:Optional[Any]   ,   SCREAMING_SNAKE_CASE		:Union[str, Any]   ,   SCREAMING_SNAKE_CASE		:int   )      ->   int:
 __lowerCAmelCase					:	Optional[Any]      =       {}
 for qid, s in scores.items():
  __lowerCAmelCase					:	List[str]      =       na_probs[qid] > na_prob_thresh
  if pred_na:
   __lowerCAmelCase					:	Optional[int]      =       float(not qid_to_has_ans[qid]   )
  else:
   __lowerCAmelCase					:	List[Any]      =       s
 return new_scores






def 	_SCREAMING_SNAKE_CASE		(      SCREAMING_SNAKE_CASE		:Tuple   ,   SCREAMING_SNAKE_CASE		:Optional[int]   ,   SCREAMING_SNAKE_CASE		:Dict=None   )      ->   Dict:


 if not qid_list:
  __lowerCAmelCase					:	Dict      =       len(__UpperCamelCase   )
  return collections.OrderedDict(
      [
          ("""exact""", 100.0 * sum(exact_scores.values()   ) / total),
          ("""f1""", 100.0 * sum(fa_scores.values()   ) / total),
          ("""total""", total),
      ]   )
 else:
  __lowerCAmelCase					:	Union[str, Any]      =       len(__UpperCamelCase   )
  return collections.OrderedDict(
      [
          ("""exact""", 100.0 * sum(exact_scores[k] for k in qid_list   ) / total),
          ("""f1""", 100.0 * sum(fa_scores[k] for k in qid_list   ) / total),
          ("""total""", total),
      ]   )






def 	_SCREAMING_SNAKE_CASE		(      SCREAMING_SNAKE_CASE		:str   ,   SCREAMING_SNAKE_CASE		:Optional[Any]   ,   SCREAMING_SNAKE_CASE		:Any   )      ->   List[Any]:


 for k in new_eval:
  __lowerCAmelCase					:	Tuple      =       new_eval[k]






def 	_SCREAMING_SNAKE_CASE		(      SCREAMING_SNAKE_CASE		:str   ,   SCREAMING_SNAKE_CASE		:str   ,   SCREAMING_SNAKE_CASE		:Optional[Any]   ,   SCREAMING_SNAKE_CASE		:Any   )      ->   Optional[int]:
 plt.step(__UpperCamelCase   ,   __UpperCamelCase   ,   color="""b"""   ,   alpha=0.2   ,   where="""post"""   )
 plt.fill_between(__UpperCamelCase   ,   __UpperCamelCase   ,   step="""post"""   ,   alpha=0.2   ,   color="""b"""   )
 plt.xlabel("""Recall"""   )
 plt.ylabel("""Precision"""   )
 plt.xlim([0.0, 1.05]   )
 plt.ylim([0.0, 1.05]   )
 plt.title(__UpperCamelCase   )
 plt.savefig(__UpperCamelCase   )
 plt.clf()






def 	_SCREAMING_SNAKE_CASE		(      SCREAMING_SNAKE_CASE		:Optional[Any]   ,   SCREAMING_SNAKE_CASE		:Tuple   ,   SCREAMING_SNAKE_CASE		:Optional[int]   ,   SCREAMING_SNAKE_CASE		:Optional[int]   ,   SCREAMING_SNAKE_CASE		:List[str]=None   ,   SCREAMING_SNAKE_CASE		:Any=None   )      ->   Any:
 __lowerCAmelCase					:	Optional[int]      =       sorted(__UpperCamelCase   ,   key=lambda SCREAMING_SNAKE_CASE   : na_probs[k]   )
 __lowerCAmelCase					:	Optional[Any]      =       0.0
 __lowerCAmelCase					:	Tuple      =       1.0
 __lowerCAmelCase					:	List[str]      =       0.0
 __lowerCAmelCase					:	Optional[int]      =       [1.0]
 __lowerCAmelCase					:	List[Any]      =       [0.0]
 __lowerCAmelCase					:	Dict      =       0.0
 for i, qid in enumerate(__UpperCamelCase   ):
  if qid_to_has_ans[qid]:
   true_pos += scores[qid]
  __lowerCAmelCase					:	List[str]      =       true_pos / float(i + 1   )
  __lowerCAmelCase					:	List[str]      =       true_pos / float(__UpperCamelCase   )
  if i == len(__UpperCamelCase   ) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]:
   # i.e., if we can put a threshold after this point
   avg_prec += cur_p * (cur_r - recalls[-1])
   precisions.append(__UpperCamelCase   )
   recalls.append(__UpperCamelCase   )
 if out_image:
  plot_pr_curve(__UpperCamelCase   ,   __UpperCamelCase   ,   __UpperCamelCase   ,   __UpperCamelCase   )
 return {"ap": 100.0 * avg_prec}






def 	_SCREAMING_SNAKE_CASE		(      SCREAMING_SNAKE_CASE		:List[str]   ,   SCREAMING_SNAKE_CASE		:Dict   ,   SCREAMING_SNAKE_CASE		:Tuple   ,   SCREAMING_SNAKE_CASE		:List[str]   ,   SCREAMING_SNAKE_CASE		:Tuple   ,   SCREAMING_SNAKE_CASE		:Union[str, Any]   )      ->   str:


 if out_image_dir and not os.path.exists(__UpperCamelCase   ):
  os.makedirs(__UpperCamelCase   )
 __lowerCAmelCase					:	Any      =       sum(1 for v in qid_to_has_ans.values() if v   )
 if num_true_pos == 0:
  return
 __lowerCAmelCase					:	Tuple      =       make_precision_recall_eval(
     __UpperCamelCase   ,   __UpperCamelCase   ,   __UpperCamelCase   ,   __UpperCamelCase   ,   out_image=os.path.join(__UpperCamelCase   ,   """pr_exact.png"""   )   ,   title="""Precision-Recall curve for Exact Match score"""   ,   )
 __lowerCAmelCase					:	List[Any]      =       make_precision_recall_eval(
     __UpperCamelCase   ,   __UpperCamelCase   ,   __UpperCamelCase   ,   __UpperCamelCase   ,   out_image=os.path.join(__UpperCamelCase   ,   """pr_f1.png"""   )   ,   title="""Precision-Recall curve for F1 score"""   ,   )
 __lowerCAmelCase					:	str      =       {k: float(__UpperCamelCase   ) for k, v in qid_to_has_ans.items()}
 __lowerCAmelCase					:	Any      =       make_precision_recall_eval(
     __UpperCamelCase   ,   __UpperCamelCase   ,   __UpperCamelCase   ,   __UpperCamelCase   ,   out_image=os.path.join(__UpperCamelCase   ,   """pr_oracle.png"""   )   ,   title="""Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)"""   ,   )
 merge_eval(__UpperCamelCase   ,   __UpperCamelCase   ,   """pr_exact"""   )
 merge_eval(__UpperCamelCase   ,   __UpperCamelCase   ,   """pr_f1"""   )
 merge_eval(__UpperCamelCase   ,   __UpperCamelCase   ,   """pr_oracle"""   )






def 	_SCREAMING_SNAKE_CASE		(      SCREAMING_SNAKE_CASE		:Any   ,   SCREAMING_SNAKE_CASE		:int   ,   SCREAMING_SNAKE_CASE		:Any   ,   SCREAMING_SNAKE_CASE		:Optional[Any]   )      ->   int:


 if not qid_list:
  return
 __lowerCAmelCase					:	Optional[Any]      =       [na_probs[k] for k in qid_list]
 __lowerCAmelCase					:	Union[str, Any]      =       np.ones_like(__UpperCamelCase   ) / float(len(__UpperCamelCase   )   )
 plt.hist(__UpperCamelCase   ,   weights=__UpperCamelCase   ,   bins=20   ,   range=(0.0, 1.0)   )
 plt.xlabel("""Model probability of no-answer"""   )
 plt.ylabel("""Proportion of dataset"""   )
 plt.title(F'''Histogram of no-answer probability: {name}'''   )
 plt.savefig(os.path.join(__UpperCamelCase   ,   F'''na_prob_hist_{name}.png'''   )   )
 plt.clf()






def 	_SCREAMING_SNAKE_CASE		(      SCREAMING_SNAKE_CASE		:Union[str, Any]   ,   SCREAMING_SNAKE_CASE		:Dict   ,   SCREAMING_SNAKE_CASE		:List[str]   ,   SCREAMING_SNAKE_CASE		:Dict   )      ->   Union[str, Any]:
 __lowerCAmelCase					:	Any      =       sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k]   )
 __lowerCAmelCase					:	Any      =       num_no_ans
 __lowerCAmelCase					:	List[Any]      =       cur_score
 __lowerCAmelCase					:	Union[str, Any]      =       0.0
 __lowerCAmelCase					:	str      =       sorted(__UpperCamelCase   ,   key=lambda SCREAMING_SNAKE_CASE   : na_probs[k]   )
 for i, qid in enumerate(__UpperCamelCase   ):
  if qid not in scores:
   continue
  if qid_to_has_ans[qid]:
   __lowerCAmelCase					:	str      =       scores[qid]
  else:
   if preds[qid]:
    __lowerCAmelCase					:	Dict      =       -1
   else:
    __lowerCAmelCase					:	Optional[Any]      =       0
  cur_score += diff
  if cur_score > best_score:
   __lowerCAmelCase					:	Optional[Any]      =       cur_score
   __lowerCAmelCase					:	Any      =       na_probs[qid]
 return 100.0 * best_score / len(__UpperCamelCase   ), best_thresh






def 	_SCREAMING_SNAKE_CASE		(      SCREAMING_SNAKE_CASE		:List[Any]   ,   SCREAMING_SNAKE_CASE		:Optional[Any]   ,   SCREAMING_SNAKE_CASE		:Tuple   ,   SCREAMING_SNAKE_CASE		:int   ,   SCREAMING_SNAKE_CASE		:int   ,   SCREAMING_SNAKE_CASE		:Union[str, Any]   )      ->   str:
 __lowerCAmelCase ,					__lowerCAmelCase					:	str      =       find_best_thresh(__UpperCamelCase   ,   __UpperCamelCase   ,   __UpperCamelCase   ,   __UpperCamelCase   )
 __lowerCAmelCase ,					__lowerCAmelCase					:	str      =       find_best_thresh(__UpperCamelCase   ,   __UpperCamelCase   ,   __UpperCamelCase   ,   __UpperCamelCase   )
 __lowerCAmelCase					:	Optional[Any]      =       best_exact
 __lowerCAmelCase					:	Dict      =       exact_thresh
 __lowerCAmelCase					:	Any      =       best_fa
 __lowerCAmelCase					:	Optional[Any]      =       fa_thresh






def 	_SCREAMING_SNAKE_CASE		(      )      ->   Any:


 with open(OPTS.data_file   ) as f:
  __lowerCAmelCase					:	Optional[int]      =       json.load(__UpperCamelCase   )
  __lowerCAmelCase					:	Optional[int]      =       dataset_json["""data"""]
 with open(OPTS.pred_file   ) as f:
  __lowerCAmelCase					:	Tuple      =       json.load(__UpperCamelCase   )
 if OPTS.na_prob_file:
  with open(OPTS.na_prob_file   ) as f:
   __lowerCAmelCase					:	str      =       json.load(__UpperCamelCase   )
 else:
  __lowerCAmelCase					:	Tuple      =       {k: 0.0 for k in preds}
 __lowerCAmelCase					:	Dict      =       make_qid_to_has_ans(__UpperCamelCase   )  # maps qid to True/False
 __lowerCAmelCase					:	Tuple      =       [k for k, v in qid_to_has_ans.items() if v]
 __lowerCAmelCase					:	int      =       [k for k, v in qid_to_has_ans.items() if not v]
 __lowerCAmelCase ,					__lowerCAmelCase					:	Optional[int]      =       get_raw_scores(__UpperCamelCase   ,   __UpperCamelCase   )
 __lowerCAmelCase					:	List[Any]      =       apply_no_ans_threshold(__UpperCamelCase   ,   __UpperCamelCase   ,   __UpperCamelCase   ,   OPTS.na_prob_thresh   )
 __lowerCAmelCase					:	Dict      =       apply_no_ans_threshold(__UpperCamelCase   ,   __UpperCamelCase   ,   __UpperCamelCase   ,   OPTS.na_prob_thresh   )
 __lowerCAmelCase					:	Optional[int]      =       make_eval_dict(__UpperCamelCase   ,   __UpperCamelCase   )
 if has_ans_qids:
  __lowerCAmelCase					:	List[str]      =       make_eval_dict(__UpperCamelCase   ,   __UpperCamelCase   ,   qid_list=__UpperCamelCase   )
  merge_eval(__UpperCamelCase   ,   __UpperCamelCase   ,   """HasAns"""   )
 if no_ans_qids:
  __lowerCAmelCase					:	Union[str, Any]      =       make_eval_dict(__UpperCamelCase   ,   __UpperCamelCase   ,   qid_list=__UpperCamelCase   )
  merge_eval(__UpperCamelCase   ,   __UpperCamelCase   ,   """NoAns"""   )
 if OPTS.na_prob_file:
  find_all_best_thresh(__UpperCamelCase   ,   __UpperCamelCase   ,   __UpperCamelCase   ,   __UpperCamelCase   ,   __UpperCamelCase   ,   __UpperCamelCase   )
 if OPTS.na_prob_file and OPTS.out_image_dir:
  run_precision_recall_analysis(__UpperCamelCase   ,   __UpperCamelCase   ,   __UpperCamelCase   ,   __UpperCamelCase   ,   __UpperCamelCase   ,   OPTS.out_image_dir   )
  histogram_na_prob(__UpperCamelCase   ,   __UpperCamelCase   ,   OPTS.out_image_dir   ,   """hasAns"""   )
  histogram_na_prob(__UpperCamelCase   ,   __UpperCamelCase   ,   OPTS.out_image_dir   ,   """noAns"""   )
 if OPTS.out_file:
  with open(OPTS.out_file   ,   """w"""   ) as f:
   json.dump(__UpperCamelCase   ,   __UpperCamelCase   )
 else:
  print(json.dumps(__UpperCamelCase   ,   indent=2   )   )


if __name__ == "__main__":
      _UpperCAmelCase             =							parse_args()
      if OPTS.out_image_dir:
            import matplotlib

            matplotlib.use('Agg')
            import matplotlib.pyplot as plt
      main()






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


_UpperCAmelCase             =							'bart'
_UpperCAmelCase             =							True






@st.cache(allow_output_mutation=SCREAMING_SNAKE_CASE   )
def 	_SCREAMING_SNAKE_CASE		(      )      ->   List[Any]:
 if LOAD_DENSE_INDEX:
  __lowerCAmelCase					:	Dict      =       AutoTokenizer.from_pretrained("""yjernite/retribert-base-uncased"""   )
  __lowerCAmelCase					:	str      =       AutoModel.from_pretrained("""yjernite/retribert-base-uncased"""   ).to("""cuda:0"""   )
  __lowerCAmelCase					:	Tuple      =       qar_model.eval()
 else:
  __lowerCAmelCase ,					__lowerCAmelCase					:	str      =       (None, None)
 if MODEL_TYPE == "bart":
  __lowerCAmelCase					:	Optional[Any]      =       AutoTokenizer.from_pretrained("""yjernite/bart_eli5"""   )
  __lowerCAmelCase					:	str      =       AutoModelForSeqaSeqLM.from_pretrained("""yjernite/bart_eli5"""   ).to("""cuda:0"""   )
  __lowerCAmelCase					:	str      =       torch.load("""seq2seq_models/eli5_bart_model_blm_2.pth"""   )
  sas_model.load_state_dict(save_dict["""model"""]   )
  __lowerCAmelCase					:	List[str]      =       sas_model.eval()
 else:
  __lowerCAmelCase ,					__lowerCAmelCase					:	Optional[int]      =       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=SCREAMING_SNAKE_CASE   )
def 	_SCREAMING_SNAKE_CASE		(      )      ->   Tuple:
 if LOAD_DENSE_INDEX:
  __lowerCAmelCase					:	List[str]      =       faiss.StandardGpuResources()
  __lowerCAmelCase					:	Optional[int]      =       datasets.load_dataset(path="""wiki_snippets"""   ,   name="""wiki40b_en_100_0"""   )["""train"""]
  __lowerCAmelCase					:	Optional[int]      =       np.memmap(
      """wiki40b_passages_reps_32_l-8_h-768_b-512-512.dat"""   ,   dtype="""float32"""   ,   mode="""r"""   ,   shape=(wikiaab_passages.num_rows, 128)   ,   )
  __lowerCAmelCase					:	int      =       faiss.IndexFlatIP(128   )
  __lowerCAmelCase					:	Optional[int]      =       faiss.index_cpu_to_gpu(SCREAMING_SNAKE_CASE   ,   1   ,   SCREAMING_SNAKE_CASE   )
  wikiaab_gpu_index_flat.add(SCREAMING_SNAKE_CASE   )  # TODO fix for larger GPU
 else:
  __lowerCAmelCase ,					__lowerCAmelCase					:	Dict      =       (None, None)
 __lowerCAmelCase					:	List[Any]      =       Elasticsearch([{"""host""": """localhost""", """port""": """9200"""}]   )
 return (wikiaab_passages, wikiaab_gpu_index_flat, es_client)






@st.cache(allow_output_mutation=SCREAMING_SNAKE_CASE   )
def 	_SCREAMING_SNAKE_CASE		(      )      ->   Optional[Any]:
 __lowerCAmelCase					:	Tuple      =       datasets.load_dataset("""eli5"""   ,   name="""LFQA_reddit"""   )
 __lowerCAmelCase					:	int      =       elia["""train_eli5"""]
 __lowerCAmelCase					:	int      =       np.memmap(
     """eli5_questions_reps.dat"""   ,   dtype="""float32"""   ,   mode="""r"""   ,   shape=(elia_train.num_rows, 128)   )
 __lowerCAmelCase					:	List[Any]      =       faiss.IndexFlatIP(128   )
 eli5_train_q_index.add(SCREAMING_SNAKE_CASE   )
 return (elia_train, eli5_train_q_index)


_UpperCAmelCase       ,     _UpperCAmelCase       ,     _UpperCAmelCase             =							load_indexes()
_UpperCAmelCase       ,     _UpperCAmelCase       ,     _UpperCAmelCase       ,     _UpperCAmelCase             =							load_models()
_UpperCAmelCase       ,     _UpperCAmelCase             =							load_train_data()






def 	_SCREAMING_SNAKE_CASE		(      SCREAMING_SNAKE_CASE		:List[Any]   ,   SCREAMING_SNAKE_CASE		:List[str]=10   )      ->   List[str]:
 __lowerCAmelCase					:	Optional[Any]      =       embed_questions_for_retrieval([question]   ,   SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   )
 __lowerCAmelCase ,					__lowerCAmelCase					:	Dict      =       eli5_train_q_index.search(SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   )
 __lowerCAmelCase					:	str      =       [elia_train[int(SCREAMING_SNAKE_CASE   )] for i in I[0]]
 return nn_examples






def 	_SCREAMING_SNAKE_CASE		(      SCREAMING_SNAKE_CASE		:int   ,   SCREAMING_SNAKE_CASE		:Dict="wiki40b"   ,   SCREAMING_SNAKE_CASE		:List[Any]="dense"   ,   SCREAMING_SNAKE_CASE		:List[str]=10   )      ->   str:
 if source == "none":
  __lowerCAmelCase ,					__lowerCAmelCase					:	Any      =       (""" <P> """.join(["""""" for _ in range(11   )]   ).strip(), [])
 else:
  if method == "dense":
   __lowerCAmelCase ,					__lowerCAmelCase					:	Union[str, Any]      =       query_qa_dense_index(
       SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   )
  else:
   __lowerCAmelCase ,					__lowerCAmelCase					:	Optional[Any]      =       query_es_index(
       SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   ,   index_name="""english_wiki40b_snippets_100w"""   ,   n_results=SCREAMING_SNAKE_CASE   ,   )
 __lowerCAmelCase					:	Union[str, Any]      =       [
     (res["""article_title"""], res["""section_title"""].strip(), res["""score"""], res["""passage_text"""]) for res in hit_lst
 ]
 __lowerCAmelCase					:	str      =       """question: {} context: {}""".format(SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   )
 return question_doc, support_list






@st.cache(
    hash_funcs={
        torch.Tensor: (lambda SCREAMING_SNAKE_CASE   : None),
        transformers.models.bart.tokenization_bart.BartTokenizer: (lambda SCREAMING_SNAKE_CASE   : None),
    }   )
def 	_SCREAMING_SNAKE_CASE		(      SCREAMING_SNAKE_CASE		:Optional[int]   ,   SCREAMING_SNAKE_CASE		:int   ,   SCREAMING_SNAKE_CASE		:Dict   ,   SCREAMING_SNAKE_CASE		:int=64   ,   SCREAMING_SNAKE_CASE		:int=256   ,   SCREAMING_SNAKE_CASE		:Tuple=False   ,   SCREAMING_SNAKE_CASE		:Union[str, Any]=2   ,   SCREAMING_SNAKE_CASE		:int=0.95   ,   SCREAMING_SNAKE_CASE		:Any=0.8   )      ->   str:
 with torch.no_grad():
  __lowerCAmelCase					:	Any      =       qa_sas_generate(
      SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   ,   num_answers=1   ,   num_beams=SCREAMING_SNAKE_CASE   ,   min_len=SCREAMING_SNAKE_CASE   ,   max_len=SCREAMING_SNAKE_CASE   ,   do_sample=SCREAMING_SNAKE_CASE   ,   temp=SCREAMING_SNAKE_CASE   ,   top_p=SCREAMING_SNAKE_CASE   ,   top_k=SCREAMING_SNAKE_CASE   ,   max_input_length=1_024   ,   device="""cuda:0"""   ,   )[0]
 return (answer, support_list)


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

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

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

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

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

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

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


_UpperCAmelCase             =							'\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)