import os
import json
import time
from typing import List
import faiss
import pypdf
import random
import itertools
import text_utils
import pandas as pd
import altair as alt
import streamlit as st
from io import StringIO
from llama_index import Document
from langchain.llms import Anthropic
from langchain.chains import RetrievalQA
from langchain.vectorstores import FAISS
from llama_index import LangchainEmbedding
from langchain.chat_models import ChatOpenAI
from langchain.retrievers import SVMRetriever
from langchain.chains import QAGenerationChain
from langchain.retrievers import TFIDFRetriever
from langchain.evaluation.qa import QAEvalChain
from langchain.embeddings import HuggingFaceEmbeddings
from langchain.embeddings.openai import OpenAIEmbeddings
from gpt_index import LLMPredictor, ServiceContext, GPTFaissIndex
from langchain.text_splitter import RecursiveCharacterTextSplitter, CharacterTextSplitter
from text_utils import GRADE_DOCS_PROMPT, GRADE_ANSWER_PROMPT, GRADE_DOCS_PROMPT_FAST, GRADE_ANSWER_PROMPT_FAST, GRADE_ANSWER_PROMPT_BIAS_CHECK, GRADE_ANSWER_PROMPT_OPENAI

# Keep dataframe in memory to accumulate experimental results
if "existing_df" not in st.session_state:
    summary = pd.DataFrame(columns=['chunk_chars',
                                    'overlap',
                                    'split',
                                    'model',
                                    'retriever',
                                    'embedding',
                                    'num_neighbors',
                                    'Latency',
                                    'Retrieval score',
                                    'Answer score'])
    st.session_state.existing_df = summary
else:
    summary = st.session_state.existing_df


@st.cache_data
def load_docs(files: List) -> str:
    """
    Load docs from files
    @param files: list of files to load
    @return: string of all docs concatenated
    """

    st.info("`Reading doc ...`")
    all_text = ""
    for file_path in files:
        file_extension = os.path.splitext(file_path.name)[1]
        if file_extension == ".pdf":
            pdf_reader = pypdf.PdfReader(file_path)
            file_content = ""
            for page in pdf_reader.pages:
                file_content += page.extract_text()
            file_content = text_utils.clean_pdf_text(file_content)
            all_text += file_content
        elif file_extension == ".txt":
            stringio = StringIO(file_path.getvalue().decode("utf-8"))
            file_content = stringio.read()
            all_text += file_content
        else:
            st.warning('Please provide txt or pdf.', icon="⚠️")
    return all_text


@st.cache_data
def generate_eval(text: str, num_questions: int, chunk: int):
    """
    Generate eval set
    @param text: text to generate eval set from
    @param num_questions: number of questions to generate
    @param chunk: chunk size to draw question from in the doc
    @return: eval set as JSON list
    """
    st.info("`Generating eval set ...`")
    n = len(text)
    starting_indices = [random.randint(0, n - chunk) for _ in range(num_questions)]
    sub_sequences = [text[i:i + chunk] for i in starting_indices]
    chain = QAGenerationChain.from_llm(ChatOpenAI(temperature=0))
    eval_set = []
    for i, b in enumerate(sub_sequences):
        try:
            qa = chain.run(b)
            eval_set.append(qa)
        except:
            st.warning('Error generating question %s.' % str(i + 1), icon="⚠️")
    eval_set_full = list(itertools.chain.from_iterable(eval_set))
    return eval_set_full


@st.cache_resource
def split_texts(text, chunk_size: int, overlap, split_method: str):
    """
    Split text into chunks
    @param text: text to split
    @param chunk_size:
    @param overlap:
    @param split_method:
    @return: list of str splits
    """
    st.info("`Splitting doc ...`")
    if split_method == "RecursiveTextSplitter":
        text_splitter = RecursiveCharacterTextSplitter(chunk_size=chunk_size,
                                                       chunk_overlap=overlap)
    elif split_method == "CharacterTextSplitter":
        text_splitter = CharacterTextSplitter(separator=" ",
                                              chunk_size=chunk_size,
                                              chunk_overlap=overlap)
    else:
        st.warning("`Split method not recognized. Using RecursiveCharacterTextSplitter`", icon="⚠️")
        text_splitter = RecursiveCharacterTextSplitter(chunk_size=chunk_size,
                                                       chunk_overlap=overlap)

    split_text = text_splitter.split_text(text)
    return split_text


@st.cache_resource
def make_llm(model_version: str):
    """
    Make LLM from model version
    @param model_version: model_version
    @return: LLN
    """
    if (model_version == "gpt-3.5-turbo") or (model_version == "gpt-4"):
        chosen_model = ChatOpenAI(model_name=model_version, temperature=0)
    elif model_version == "anthropic":
        chosen_model = Anthropic(temperature=0)
    else:
        st.warning("`Model version not recognized. Using gpt-3.5-turbo`", icon="⚠️")
        chosen_model = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0)
    return chosen_model


@st.cache_resource
def make_retriever(splits, retriever_type, embedding_type, num_neighbors, _llm):
    """
    Make document retriever
    @param splits: list of str splits
    @param retriever_type: retriever type
    @param embedding_type: embedding type
    @param num_neighbors: number of neighbors for retrieval
    @param _llm: model
    @return: retriever
    """
    st.info("`Making retriever ...`")
    # Set embeddings
    if embedding_type == "OpenAI":
        embedding = OpenAIEmbeddings()
    elif embedding_type == "HuggingFace":
        embedding = HuggingFaceEmbeddings()
    else:
        st.warning("`Embedding type not recognized. Using OpenAI`", icon="⚠️")
        embedding = OpenAIEmbeddings()

    # Select retriever
    if retriever_type == "similarity-search":
        try:
            vector_store = FAISS.from_texts(splits, embedding)
        except ValueError:
            st.warning("`Error using OpenAI embeddings (disallowed TikToken token in the text). Using HuggingFace.`",
                       icon="⚠️")
            vector_store = FAISS.from_texts(splits, HuggingFaceEmbeddings())
        retriever_obj = vector_store.as_retriever(k=num_neighbors)
    elif retriever_type == "SVM":
        retriever_obj = SVMRetriever.from_texts(splits, embedding)
    elif retriever_type == "TF-IDF":
        retriever_obj = TFIDFRetriever.from_texts(splits)
    elif retriever_type == "Llama-Index":
        documents = [Document(t, LangchainEmbedding(embedding)) for t in splits]
        llm_predictor = LLMPredictor(llm)
        context = ServiceContext.from_defaults(chunk_size_limit=512, llm_predictor=llm_predictor)
        d = 1536
        faiss_index = faiss.IndexFlatL2(d)
        retriever_obj = GPTFaissIndex.from_documents(documents, faiss_index=faiss_index, service_context=context)
    else:
        st.warning("`Retriever type not recognized. Using SVM`", icon="⚠️")
        retriever_obj = SVMRetriever.from_texts(splits, embedding)
    return retriever_obj


def make_chain(llm, retriever, retriever_type: str) -> RetrievalQA:
    """
    Make chain
    @param llm: model
    @param retriever: retriever
    @param retriever_type: retriever type
    @return: chain (or return retriever for Llama-Index)
    """
    st.info("`Making chain ...`")
    if retriever_type == "Llama-Index":
        qa = retriever
    else:
        qa = RetrievalQA.from_chain_type(llm,
                                         chain_type="stuff",
                                         retriever=retriever,
                                         input_key="question")
    return qa


def grade_model_answer(predicted_dataset: List, predictions: List, grade_answer_prompt: str) -> List:
    """
    Grades the distilled answer based on ground truth and model predictions.
    @param predicted_dataset: A list of dictionaries containing ground truth questions and answers.
    @param predictions: A list of dictionaries containing model predictions for the questions.
    @param grade_answer_prompt: The prompt level for the grading. Either "Fast" or "Full".
    @return: A list of scores for the distilled answers.
    """
    # Grade the distilled answer
    st.info("`Grading model answer ...`")
    # Set the grading prompt based on the grade_answer_prompt parameter
    if grade_answer_prompt == "Fast":
        prompt = GRADE_ANSWER_PROMPT_FAST
    elif grade_answer_prompt == "Descriptive w/ bias check":
        prompt = GRADE_ANSWER_PROMPT_BIAS_CHECK
    elif grade_answer_prompt == "OpenAI grading prompt":
        prompt = GRADE_ANSWER_PROMPT_OPENAI
    else:
        prompt = GRADE_ANSWER_PROMPT

    # Create an evaluation chain
    eval_chain = QAEvalChain.from_llm(
        llm=ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0),
        prompt=prompt
    )

    # Evaluate the predictions and ground truth using the evaluation chain
    graded_outputs = eval_chain.evaluate(
        predicted_dataset,
        predictions,
        question_key="question",
        prediction_key="result"
    )

    return graded_outputs


def grade_model_retrieval(gt_dataset: List, predictions: List, grade_docs_prompt: str):
    """
    Grades the relevance of retrieved documents based on ground truth and model predictions.
    @param gt_dataset: list of dictionaries containing ground truth questions and answers.
    @param predictions: list of dictionaries containing model predictions for the questions
    @param grade_docs_prompt: prompt level for the grading. Either "Fast" or "Full"
    @return: list of scores for the retrieved documents.
    """
    # Grade the docs retrieval
    st.info("`Grading relevance of retrieved docs ...`")

    # Set the grading prompt based on the grade_docs_prompt parameter
    prompt = GRADE_DOCS_PROMPT_FAST if grade_docs_prompt == "Fast" else GRADE_DOCS_PROMPT

    # Create an evaluation chain
    eval_chain = QAEvalChain.from_llm(
        llm=ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0),
        prompt=prompt
    )

    # Evaluate the predictions and ground truth using the evaluation chain
    graded_outputs = eval_chain.evaluate(
        gt_dataset,
        predictions,
        question_key="question",
        prediction_key="result"
    )
    return graded_outputs


def run_evaluation(chain, retriever, eval_set, grade_prompt, retriever_type, num_neighbors):
    """
    Runs evaluation on a model's performance on a given evaluation dataset.
    @param chain: Model chain used for answering questions
    @param retriever:  Document retriever used for retrieving relevant documents
    @param eval_set: List of dictionaries containing questions and corresponding ground truth answers
    @param grade_prompt: String prompt used for grading model's performance
    @param retriever_type: String specifying the type of retriever used
    @param num_neighbors: Number of neighbors to retrieve using the retriever
    @return: A tuple of four items:
    - answers_grade: A dictionary containing scores for the model's answers.
    - retrieval_grade: A dictionary containing scores for the model's document retrieval.
    - latencies_list: A list of latencies in seconds for each question answered.
    - predictions_list: A list of dictionaries containing the model's predicted answers and relevant documents for each question.
    """
    st.info("`Running evaluation ...`")
    predictions_list = []
    retrieved_docs = []
    gt_dataset = []
    latencies_list = []

    for data in eval_set:

        # Get answer and log latency
        start_time = time.time()
        if retriever_type != "Llama-Index":
            predictions_list.append(chain(data))
        elif retriever_type == "Llama-Index":
            answer = chain.query(data["question"], similarity_top_k=num_neighbors, response_mode="tree_summarize",
                                 use_async=True)
            predictions_list.append({"question": data["question"], "answer": data["answer"], "result": answer.response})
        gt_dataset.append(data)
        end_time = time.time()
        elapsed_time = end_time - start_time
        latencies_list.append(elapsed_time)

        # Retrieve docs
        retrieved_doc_text = ""
        if retriever_type == "Llama-Index":
            for i, doc in enumerate(answer.source_nodes):
                retrieved_doc_text += "Doc %s: " % str(i + 1) + doc.node.text + " "

        else:
            docs = retriever.get_relevant_documents(data["question"])
            for i, doc in enumerate(docs):
                retrieved_doc_text += "Doc %s: " % str(i + 1) + doc.page_content + " "

        retrieved = {"question": data["question"], "answer": data["answer"], "result": retrieved_doc_text}
        retrieved_docs.append(retrieved)

    # Grade
    answers_grade = grade_model_answer(gt_dataset, predictions_list, grade_prompt)
    retrieval_grade = grade_model_retrieval(gt_dataset, retrieved_docs, grade_prompt)
    return answers_grade, retrieval_grade, latencies_list, predictions_list


# Auth
st.sidebar.image("img/diagnostic.jpg")

with st.sidebar.form("user_input"):
    num_eval_questions = st.select_slider("`Number of eval questions`",
                                          options=[1, 5, 10, 15, 20], value=5)

    chunk_chars = st.select_slider("`Choose chunk size for splitting`",
                                   options=[500, 750, 1000, 1500, 2000], value=1000)

    overlap = st.select_slider("`Choose overlap for splitting`",
                               options=[0, 50, 100, 150, 200], value=100)

    split_method = st.radio("`Split method`",
                            ("RecursiveTextSplitter",
                             "CharacterTextSplitter"),
                            index=0)

    model = st.radio("`Choose model`",
                     ("gpt-3.5-turbo",
                      "gpt-4",
                      "anthropic"),
                     index=0)

    retriever_type = st.radio("`Choose retriever`",
                              ("TF-IDF",
                               "SVM",
                               "Llama-Index",
                               "similarity-search"),
                              index=3)

    num_neighbors = st.select_slider("`Choose # chunks to retrieve`",
                                     options=[3, 4, 5, 6, 7, 8])

    embeddings = st.radio("`Choose embeddings`",
                          ("HuggingFace",
                           "OpenAI"),
                          index=1)

    grade_prompt = st.radio("`Grading style prompt`",
                            ("Fast",
                             "Descriptive",
                             "Descriptive w/ bias check",
                             "OpenAI grading prompt"),
                            index=0)

    submitted = st.form_submit_button("Submit evaluation")

# App
st.header("`Auto-evaluator`")
st.info(
    "`I am an evaluation tool for question-answering. Given documents, I will auto-generate a question-answer eval "
    "set and evaluate using the selected chain settings. Experiments with different configurations are logged. "
    "Optionally, provide your own eval set (as a JSON, see docs/karpathy-pod-eval.json for an example).`")

with st.form(key='file_inputs'):
    uploaded_file = st.file_uploader("`Please upload a file to evaluate (.txt or .pdf):` ",
                                     type=['pdf', 'txt'],
                                     accept_multiple_files=True)

    uploaded_eval_set = st.file_uploader("`[Optional] Please upload eval set (.json):` ",
                                         type=['json'],
                                         accept_multiple_files=False)

    submitted = st.form_submit_button("Submit files")

if uploaded_file:

    # Load docs
    text = load_docs(uploaded_file)
    # Generate num_eval_questions questions, each from context of 3k chars randomly selected
    if not uploaded_eval_set:
        eval_set = generate_eval(text, num_eval_questions, 3000)
    else:
        eval_set = json.loads(uploaded_eval_set.read())
    # Split text
    splits = split_texts(text, chunk_chars, overlap, split_method)
    # Make LLM
    llm = make_llm(model)
    # Make vector DB
    retriever = make_retriever(splits, retriever_type, embeddings, num_neighbors, llm)
    # Make chain
    qa_chain = make_chain(llm, retriever, retriever_type)
    # Grade model
    graded_answers, graded_retrieval, latency, predictions = run_evaluation(qa_chain, retriever, eval_set, grade_prompt,
                                                                      retriever_type, num_neighbors)

    # Assemble outputs
    d = pd.DataFrame(predictions)
    d['answer score'] = [g['text'] for g in graded_answers]
    d['docs score'] = [g['text'] for g in graded_retrieval]
    d['latency'] = latency

    # Summary statistics
    mean_latency = d['latency'].mean()
    correct_answer_count = len([text for text in d['answer score'] if "INCORRECT" not in text])
    correct_docs_count = len([text for text in d['docs score'] if "Context is relevant: True" in text])
    percentage_answer = (correct_answer_count / len(graded_answers)) * 100
    percentage_docs = (correct_docs_count / len(graded_retrieval)) * 100

    st.subheader("`Run Results`")
    st.info(
        "`I will grade the chain based on: 1/ the relevance of the retrived documents relative to the question and 2/ "
        "the summarized answer relative to the ground truth answer. You can see (and change) to prompts used for "
        "grading in text_utils`")
    st.dataframe(data=d, use_container_width=True)

    # Accumulate results
    st.subheader("`Aggregate Results`")
    st.info(
        "`Retrieval and answer scores are percentage of retrived documents deemed relevant by the LLM grader ("
        "relative to the question) and percentage of summarized answers deemed relevant (relative to ground truth "
        "answer), respectively. The size of point correponds to the latency (in seconds) of retrieval + answer "
        "summarization (larger circle = slower).`")
    new_row = pd.DataFrame({'chunk_chars': [chunk_chars],
                            'overlap': [overlap],
                            'split': [split_method],
                            'model': [model],
                            'retriever': [retriever_type],
                            'embedding': [embeddings],
                            'num_neighbors': [num_neighbors],
                            'Latency': [mean_latency],
                            'Retrieval score': [percentage_docs],
                            'Answer score': [percentage_answer]})
    summary = pd.concat([summary, new_row], ignore_index=True)
    st.dataframe(data=summary, use_container_width=True)
    st.session_state.existing_df = summary

    # Dataframe for visualization
    show = summary.reset_index().copy()
    show.columns = ['expt number', 'chunk_chars', 'overlap',
                    'split', 'model', 'retriever', 'embedding', 'num_neighbors', 'Latency', 'Retrieval score',
                    'Answer score']
    show['expt number'] = show['expt number'].apply(lambda x: "Expt #: " + str(x + 1))
    c = alt.Chart(show).mark_circle().encode(x='Retrieval score',
                                             y='Answer score',
                                             size=alt.Size('Latency'),
                                             color='expt number',
                                             tooltip=['expt number', 'Retrieval score', 'Latency', 'Answer score'])
    st.altair_chart(c, use_container_width=True, theme="streamlit")

langchain.text_splitter.CharacterTextSplitter langchain.retrievers.SVMRetriever.from_texts langchain.embeddings.HuggingFaceEmbeddings langchain.chains.RetrievalQA.from_chain_type langchain.text_splitter.RecursiveCharacterTextSplitter langchain.chat_models.ChatOpenAI langchain.vectorstores.FAISS.from_texts langchain.retrievers.TFIDFRetriever.from_texts langchain.llms.Anthropic langchain.embeddings.openai.OpenAIEmbeddings
[((13312, 13350), 'streamlit.sidebar.image', 'st.sidebar.image', (['"""img/diagnostic.jpg"""'], {}), "('img/diagnostic.jpg')\n", (13328, 13350), True, 'import streamlit as st\n'), ((15130, 15159), 'streamlit.header', 'st.header', (['"""`Auto-evaluator`"""'], {}), "('`Auto-evaluator`')\n", (15139, 15159), True, 'import streamlit as st\n'), ((15160, 15496), 'streamlit.info', 'st.info', (['"""`I am an evaluation tool for question-answering. Given documents, I will auto-generate a question-answer eval set and evaluate using the selected chain settings. Experiments with different configurations are logged. Optionally, provide your own eval set (as a JSON, see docs/karpathy-pod-eval.json for an example).`"""'], {}), "(\n    '`I am an evaluation tool for question-answering. Given documents, I will auto-generate a question-answer eval set and evaluate using the selected chain settings. Experiments with different configurations are logged. Optionally, provide your own eval set (as a JSON, see docs/karpathy-pod-eval.json for an example).`'\n    )\n", (15167, 15496), True, 'import streamlit as st\n'), ((1209, 1372), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['chunk_chars', 'overlap', 'split', 'model', 'retriever', 'embedding',\n    'num_neighbors', 'Latency', 'Retrieval score', 'Answer score']"}), "(columns=['chunk_chars', 'overlap', 'split', 'model',\n    'retriever', 'embedding', 'num_neighbors', 'Latency', 'Retrieval score',\n    'Answer score'])\n", (1221, 1372), True, 'import pandas as pd\n'), ((1964, 1992), 'streamlit.info', 'st.info', (['"""`Reading doc ...`"""'], {}), "('`Reading doc ...`')\n", (1971, 1992), True, 'import streamlit as st\n'), ((3028, 3064), 'streamlit.info', 'st.info', (['"""`Generating eval set ...`"""'], {}), "('`Generating eval set ...`')\n", (3035, 3064), True, 'import streamlit as st\n'), ((3888, 3918), 'streamlit.info', 'st.info', (['"""`Splitting doc ...`"""'], {}), "('`Splitting doc ...`')\n", (3895, 3918), True, 'import streamlit as st\n'), ((5679, 5712), 'streamlit.info', 'st.info', (['"""`Making retriever ...`"""'], {}), "('`Making retriever ...`')\n", (5686, 5712), True, 'import streamlit as st\n'), ((7560, 7589), 'streamlit.info', 'st.info', (['"""`Making chain ...`"""'], {}), "('`Making chain ...`')\n", (7567, 7589), True, 'import streamlit as st\n'), ((8486, 8523), 'streamlit.info', 'st.info', (['"""`Grading model answer ...`"""'], {}), "('`Grading model answer ...`')\n", (8493, 8523), True, 'import streamlit as st\n'), ((9923, 9975), 'streamlit.info', 'st.info', (['"""`Grading relevance of retrieved docs ...`"""'], {}), "('`Grading relevance of retrieved docs ...`')\n", (9930, 9975), True, 'import streamlit as st\n'), ((11634, 11669), 'streamlit.info', 'st.info', (['"""`Running evaluation ...`"""'], {}), "('`Running evaluation ...`')\n", (11641, 11669), True, 'import streamlit as st\n'), ((13357, 13386), 'streamlit.sidebar.form', 'st.sidebar.form', (['"""user_input"""'], {}), "('user_input')\n", (13372, 13386), True, 'import streamlit as st\n'), ((13413, 13500), 'streamlit.select_slider', 'st.select_slider', (['"""`Number of eval questions`"""'], {'options': '[1, 5, 10, 15, 20]', 'value': '(5)'}), "('`Number of eval questions`', options=[1, 5, 10, 15, 20],\n    value=5)\n", (13429, 13500), True, 'import streamlit as st\n'), ((13558, 13666), 'streamlit.select_slider', 'st.select_slider', (['"""`Choose chunk size for splitting`"""'], {'options': '[500, 750, 1000, 1500, 2000]', 'value': '(1000)'}), "('`Choose chunk size for splitting`', options=[500, 750, \n    1000, 1500, 2000], value=1000)\n", (13574, 13666), True, 'import streamlit as st\n'), ((13712, 13809), 'streamlit.select_slider', 'st.select_slider', (['"""`Choose overlap for splitting`"""'], {'options': '[0, 50, 100, 150, 200]', 'value': '(100)'}), "('`Choose overlap for splitting`', options=[0, 50, 100, 150,\n    200], value=100)\n", (13728, 13809), True, 'import streamlit as st\n'), ((13857, 13948), 'streamlit.radio', 'st.radio', (['"""`Split method`"""', "('RecursiveTextSplitter', 'CharacterTextSplitter')"], {'index': '(0)'}), "('`Split method`', ('RecursiveTextSplitter',\n    'CharacterTextSplitter'), index=0)\n", (13865, 13948), True, 'import streamlit as st\n'), ((14043, 14119), 'streamlit.radio', 'st.radio', (['"""`Choose model`"""', "('gpt-3.5-turbo', 'gpt-4', 'anthropic')"], {'index': '(0)'}), "('`Choose model`', ('gpt-3.5-turbo', 'gpt-4', 'anthropic'), index=0)\n", (14051, 14119), True, 'import streamlit as st\n'), ((14228, 14326), 'streamlit.radio', 'st.radio', (['"""`Choose retriever`"""', "('TF-IDF', 'SVM', 'Llama-Index', 'similarity-search')"], {'index': '(3)'}), "('`Choose retriever`', ('TF-IDF', 'SVM', 'Llama-Index',\n    'similarity-search'), index=3)\n", (14236, 14326), True, 'import streamlit as st\n'), ((14497, 14574), 'streamlit.select_slider', 'st.select_slider', (['"""`Choose # chunks to retrieve`"""'], {'options': '[3, 4, 5, 6, 7, 8]'}), "('`Choose # chunks to retrieve`', options=[3, 4, 5, 6, 7, 8])\n", (14513, 14574), True, 'import streamlit as st\n'), ((14630, 14697), 'streamlit.radio', 'st.radio', (['"""`Choose embeddings`"""', "('HuggingFace', 'OpenAI')"], {'index': '(1)'}), "('`Choose embeddings`', ('HuggingFace', 'OpenAI'), index=1)\n", (14638, 14697), True, 'import streamlit as st\n'), ((14797, 14923), 'streamlit.radio', 'st.radio', (['"""`Grading style prompt`"""', "('Fast', 'Descriptive', 'Descriptive w/ bias check', 'OpenAI grading prompt')"], {'index': '(0)'}), "('`Grading style prompt`', ('Fast', 'Descriptive',\n    'Descriptive w/ bias check', 'OpenAI grading prompt'), index=0)\n", (14805, 14923), True, 'import streamlit as st\n'), ((15080, 15122), 'streamlit.form_submit_button', 'st.form_submit_button', (['"""Submit evaluation"""'], {}), "('Submit evaluation')\n", (15101, 15122), True, 'import streamlit as st\n'), ((15512, 15538), 'streamlit.form', 'st.form', ([], {'key': '"""file_inputs"""'}), "(key='file_inputs')\n", (15519, 15538), True, 'import streamlit as st\n'), ((15560, 15684), 'streamlit.file_uploader', 'st.file_uploader', (['"""`Please upload a file to evaluate (.txt or .pdf):` """'], {'type': "['pdf', 'txt']", 'accept_multiple_files': '(True)'}), "('`Please upload a file to evaluate (.txt or .pdf):` ',\n    type=['pdf', 'txt'], accept_multiple_files=True)\n", (15576, 15684), True, 'import streamlit as st\n'), ((15780, 15894), 'streamlit.file_uploader', 'st.file_uploader', (['"""`[Optional] Please upload eval set (.json):` """'], {'type': "['json']", 'accept_multiple_files': '(False)'}), "('`[Optional] Please upload eval set (.json):` ', type=[\n    'json'], accept_multiple_files=False)\n", (15796, 15894), True, 'import streamlit as st\n'), ((15989, 16026), 'streamlit.form_submit_button', 'st.form_submit_button', (['"""Submit files"""'], {}), "('Submit files')\n", (16010, 16026), True, 'import streamlit as st\n'), ((16933, 16958), 'pandas.DataFrame', 'pd.DataFrame', (['predictions'], {}), '(predictions)\n', (16945, 16958), True, 'import pandas as pd\n'), ((17524, 17553), 'streamlit.subheader', 'st.subheader', (['"""`Run Results`"""'], {}), "('`Run Results`')\n", (17536, 17553), True, 'import streamlit as st\n'), ((17558, 17814), 'streamlit.info', 'st.info', (['"""`I will grade the chain based on: 1/ the relevance of the retrived documents relative to the question and 2/ the summarized answer relative to the ground truth answer. You can see (and change) to prompts used for grading in text_utils`"""'], {}), "(\n    '`I will grade the chain based on: 1/ the relevance of the retrived documents relative to the question and 2/ the summarized answer relative to the ground truth answer. You can see (and change) to prompts used for grading in text_utils`'\n    )\n", (17565, 17814), True, 'import streamlit as st\n'), ((17840, 17886), 'streamlit.dataframe', 'st.dataframe', ([], {'data': 'd', 'use_container_width': '(True)'}), '(data=d, use_container_width=True)\n', (17852, 17886), True, 'import streamlit as st\n'), ((17917, 17952), 'streamlit.subheader', 'st.subheader', (['"""`Aggregate Results`"""'], {}), "('`Aggregate Results`')\n", (17929, 17952), True, 'import streamlit as st\n'), ((17957, 18326), 'streamlit.info', 'st.info', (['"""`Retrieval and answer scores are percentage of retrived documents deemed relevant by the LLM grader (relative to the question) and percentage of summarized answers deemed relevant (relative to ground truth answer), respectively. The size of point correponds to the latency (in seconds) of retrieval + answer summarization (larger circle = slower).`"""'], {}), "(\n    '`Retrieval and answer scores are percentage of retrived documents deemed relevant by the LLM grader (relative to the question) and percentage of summarized answers deemed relevant (relative to ground truth answer), respectively. The size of point correponds to the latency (in seconds) of retrieval + answer summarization (larger circle = slower).`'\n    )\n", (17964, 18326), True, 'import streamlit as st\n'), ((18373, 18693), 'pandas.DataFrame', 'pd.DataFrame', (["{'chunk_chars': [chunk_chars], 'overlap': [overlap], 'split': [split_method\n    ], 'model': [model], 'retriever': [retriever_type], 'embedding': [\n    embeddings], 'num_neighbors': [num_neighbors], 'Latency': [mean_latency\n    ], 'Retrieval score': [percentage_docs], 'Answer score': [\n    percentage_answer]}"], {}), "({'chunk_chars': [chunk_chars], 'overlap': [overlap], 'split':\n    [split_method], 'model': [model], 'retriever': [retriever_type],\n    'embedding': [embeddings], 'num_neighbors': [num_neighbors], 'Latency':\n    [mean_latency], 'Retrieval score': [percentage_docs], 'Answer score': [\n    percentage_answer]})\n", (18385, 18693), True, 'import pandas as pd\n'), ((18943, 18991), 'pandas.concat', 'pd.concat', (['[summary, new_row]'], {'ignore_index': '(True)'}), '([summary, new_row], ignore_index=True)\n', (18952, 18991), True, 'import pandas as pd\n'), ((18996, 19048), 'streamlit.dataframe', 'st.dataframe', ([], {'data': 'summary', 'use_container_width': '(True)'}), '(data=summary, use_container_width=True)\n', (19008, 19048), True, 'import streamlit as st\n'), ((19848, 19911), 'streamlit.altair_chart', 'st.altair_chart', (['c'], {'use_container_width': '(True)', 'theme': '"""streamlit"""'}), "(c, use_container_width=True, theme='streamlit')\n", (19863, 19911), True, 'import streamlit as st\n'), ((3107, 3135), 'random.randint', 'random.randint', (['(0)', '(n - chunk)'], {}), '(0, n - chunk)\n', (3121, 3135), False, 'import random\n'), ((3272, 3297), 'langchain.chat_models.ChatOpenAI', 'ChatOpenAI', ([], {'temperature': '(0)'}), '(temperature=0)\n', (3282, 3297), False, 'from langchain.chat_models import ChatOpenAI\n'), ((3555, 3594), 'itertools.chain.from_iterable', 'itertools.chain.from_iterable', (['eval_set'], {}), '(eval_set)\n', (3584, 3594), False, 'import itertools\n'), ((3991, 4067), 'langchain.text_splitter.RecursiveCharacterTextSplitter', 'RecursiveCharacterTextSplitter', ([], {'chunk_size': 'chunk_size', 'chunk_overlap': 'overlap'}), '(chunk_size=chunk_size, chunk_overlap=overlap)\n', (4021, 4067), False, 'from langchain.text_splitter import RecursiveCharacterTextSplitter, CharacterTextSplitter\n'), ((4966, 5017), 'langchain.chat_models.ChatOpenAI', 'ChatOpenAI', ([], {'model_name': 'model_version', 'temperature': '(0)'}), '(model_name=model_version, temperature=0)\n', (4976, 5017), False, 'from langchain.chat_models import ChatOpenAI\n'), ((5789, 5807), 'langchain.embeddings.openai.OpenAIEmbeddings', 'OpenAIEmbeddings', ([], {}), '()\n', (5805, 5807), False, 'from langchain.embeddings.openai import OpenAIEmbeddings\n'), ((7676, 7775), 'langchain.chains.RetrievalQA.from_chain_type', 'RetrievalQA.from_chain_type', (['llm'], {'chain_type': '"""stuff"""', 'retriever': 'retriever', 'input_key': '"""question"""'}), "(llm, chain_type='stuff', retriever=retriever,\n    input_key='question')\n", (7703, 7775), False, 'from langchain.chains import RetrievalQA\n'), ((11850, 11861), 'time.time', 'time.time', ([], {}), '()\n', (11859, 11861), False, 'import time\n'), ((12337, 12348), 'time.time', 'time.time', ([], {}), '()\n', (12346, 12348), False, 'import time\n'), ((2064, 2096), 'os.path.splitext', 'os.path.splitext', (['file_path.name'], {}), '(file_path.name)\n', (2080, 2096), False, 'import os\n'), ((2162, 2188), 'pypdf.PdfReader', 'pypdf.PdfReader', (['file_path'], {}), '(file_path)\n', (2177, 2188), False, 'import pypdf\n'), ((2340, 2379), 'text_utils.clean_pdf_text', 'text_utils.clean_pdf_text', (['file_content'], {}), '(file_content)\n', (2365, 2379), False, 'import text_utils\n'), ((4197, 4284), 'langchain.text_splitter.CharacterTextSplitter', 'CharacterTextSplitter', ([], {'separator': '""" """', 'chunk_size': 'chunk_size', 'chunk_overlap': 'overlap'}), "(separator=' ', chunk_size=chunk_size, chunk_overlap=\n    overlap)\n", (4218, 4284), False, 'from langchain.text_splitter import RecursiveCharacterTextSplitter, CharacterTextSplitter\n'), ((4390, 4491), 'streamlit.warning', 'st.warning', (['"""`Split method not recognized. Using RecursiveCharacterTextSplitter`"""'], {'icon': '"""⚠️"""'}), "(\n    '`Split method not recognized. Using RecursiveCharacterTextSplitter`',\n    icon='⚠️')\n", (4400, 4491), True, 'import streamlit as st\n'), ((4507, 4583), 'langchain.text_splitter.RecursiveCharacterTextSplitter', 'RecursiveCharacterTextSplitter', ([], {'chunk_size': 'chunk_size', 'chunk_overlap': 'overlap'}), '(chunk_size=chunk_size, chunk_overlap=overlap)\n', (4537, 4583), False, 'from langchain.text_splitter import RecursiveCharacterTextSplitter, CharacterTextSplitter\n'), ((5080, 5104), 'langchain.llms.Anthropic', 'Anthropic', ([], {'temperature': '(0)'}), '(temperature=0)\n', (5089, 5104), False, 'from langchain.llms import Anthropic\n'), ((5123, 5199), 'streamlit.warning', 'st.warning', (['"""`Model version not recognized. Using gpt-3.5-turbo`"""'], {'icon': '"""⚠️"""'}), "('`Model version not recognized. Using gpt-3.5-turbo`', icon='⚠️')\n", (5133, 5199), True, 'import streamlit as st\n'), ((5223, 5276), 'langchain.chat_models.ChatOpenAI', 'ChatOpenAI', ([], {'model_name': '"""gpt-3.5-turbo"""', 'temperature': '(0)'}), "(model_name='gpt-3.5-turbo', temperature=0)\n", (5233, 5276), False, 'from langchain.chat_models import ChatOpenAI\n'), ((5870, 5893), 'langchain.embeddings.HuggingFaceEmbeddings', 'HuggingFaceEmbeddings', ([], {}), '()\n', (5891, 5893), False, 'from langchain.embeddings import HuggingFaceEmbeddings\n'), ((5912, 5982), 'streamlit.warning', 'st.warning', (['"""`Embedding type not recognized. Using OpenAI`"""'], {'icon': '"""⚠️"""'}), "('`Embedding type not recognized. Using OpenAI`', icon='⚠️')\n", (5922, 5982), True, 'import streamlit as st\n'), ((6003, 6021), 'langchain.embeddings.openai.OpenAIEmbeddings', 'OpenAIEmbeddings', ([], {}), '()\n', (6019, 6021), False, 'from langchain.embeddings.openai import OpenAIEmbeddings\n'), ((6132, 6167), 'langchain.vectorstores.FAISS.from_texts', 'FAISS.from_texts', (['splits', 'embedding'], {}), '(splits, embedding)\n', (6148, 6167), False, 'from langchain.vectorstores import FAISS\n'), ((6549, 6591), 'langchain.retrievers.SVMRetriever.from_texts', 'SVMRetriever.from_texts', (['splits', 'embedding'], {}), '(splits, embedding)\n', (6572, 6591), False, 'from langchain.retrievers import SVMRetriever\n'), ((9018, 9071), 'langchain.chat_models.ChatOpenAI', 'ChatOpenAI', ([], {'model_name': '"""gpt-3.5-turbo"""', 'temperature': '(0)'}), "(model_name='gpt-3.5-turbo', temperature=0)\n", (9028, 9071), False, 'from langchain.chat_models import ChatOpenAI\n'), ((10222, 10275), 'langchain.chat_models.ChatOpenAI', 'ChatOpenAI', ([], {'model_name': '"""gpt-3.5-turbo"""', 'temperature': '(0)'}), "(model_name='gpt-3.5-turbo', temperature=0)\n", (10232, 10275), False, 'from langchain.chat_models import ChatOpenAI\n'), ((19641, 19660), 'altair.Size', 'alt.Size', (['"""Latency"""'], {}), "('Latency')\n", (19649, 19660), True, 'import altair as alt\n'), ((2632, 2683), 'streamlit.warning', 'st.warning', (['"""Please provide txt or pdf."""'], {'icon': '"""⚠️"""'}), "('Please provide txt or pdf.', icon='⚠️')\n", (2642, 2683), True, 'import streamlit as st\n'), ((6207, 6333), 'streamlit.warning', 'st.warning', (['"""`Error using OpenAI embeddings (disallowed TikToken token in the text). Using HuggingFace.`"""'], {'icon': '"""⚠️"""'}), "(\n    '`Error using OpenAI embeddings (disallowed TikToken token in the text). Using HuggingFace.`'\n    , icon='⚠️')\n", (6217, 6333), True, 'import streamlit as st\n'), ((6653, 6686), 'langchain.retrievers.TFIDFRetriever.from_texts', 'TFIDFRetriever.from_texts', (['splits'], {}), '(splits)\n', (6678, 6686), False, 'from langchain.retrievers import TFIDFRetriever\n'), ((6399, 6422), 'langchain.embeddings.HuggingFaceEmbeddings', 'HuggingFaceEmbeddings', ([], {}), '()\n', (6420, 6422), False, 'from langchain.embeddings import HuggingFaceEmbeddings\n'), ((6834, 6851), 'gpt_index.LLMPredictor', 'LLMPredictor', (['llm'], {}), '(llm)\n', (6846, 6851), False, 'from gpt_index import LLMPredictor, ServiceContext, GPTFaissIndex\n'), ((6870, 6949), 'gpt_index.ServiceContext.from_defaults', 'ServiceContext.from_defaults', ([], {'chunk_size_limit': '(512)', 'llm_predictor': 'llm_predictor'}), '(chunk_size_limit=512, llm_predictor=llm_predictor)\n', (6898, 6949), False, 'from gpt_index import LLMPredictor, ServiceContext, GPTFaissIndex\n'), ((6989, 7009), 'faiss.IndexFlatL2', 'faiss.IndexFlatL2', (['d'], {}), '(d)\n', (7006, 7009), False, 'import faiss\n'), ((7034, 7127), 'gpt_index.GPTFaissIndex.from_documents', 'GPTFaissIndex.from_documents', (['documents'], {'faiss_index': 'faiss_index', 'service_context': 'context'}), '(documents, faiss_index=faiss_index,\n    service_context=context)\n', (7062, 7127), False, 'from gpt_index import LLMPredictor, ServiceContext, GPTFaissIndex\n'), ((7142, 7209), 'streamlit.warning', 'st.warning', (['"""`Retriever type not recognized. Using SVM`"""'], {'icon': '"""⚠️"""'}), "('`Retriever type not recognized. Using SVM`', icon='⚠️')\n", (7152, 7209), True, 'import streamlit as st\n'), ((7234, 7276), 'langchain.retrievers.SVMRetriever.from_texts', 'SVMRetriever.from_texts', (['splits', 'embedding'], {}), '(splits, embedding)\n', (7257, 7276), False, 'from langchain.retrievers import SVMRetriever\n'), ((19470, 19485), 'altair.Chart', 'alt.Chart', (['show'], {}), '(show)\n', (19479, 19485), True, 'import altair as alt\n'), ((6762, 6791), 'llama_index.LangchainEmbedding', 'LangchainEmbedding', (['embedding'], {}), '(embedding)\n', (6780, 6791), False, 'from llama_index import LangchainEmbedding\n')]