Update app.py
Browse files
app.py
CHANGED
|
@@ -1,115 +1,129 @@
|
|
| 1 |
-
import streamlit as st
|
| 2 |
-
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 3 |
-
from sentence_transformers import SentenceTransformer
|
| 4 |
-
from langchain.chains import RetrievalQA
|
| 5 |
-
from langchain_community.vectorstores import FAISS
|
| 6 |
-
from datasets import load_dataset
|
| 7 |
-
import numpy as np
|
| 8 |
-
import torch
|
| 9 |
-
import pandas as pd
|
| 10 |
-
import os
|
| 11 |
-
import subprocess
|
| 12 |
-
from dotenv import load_dotenv
|
| 13 |
-
|
| 14 |
-
# Function to load model, tokenizer, and dataset only once
|
| 15 |
-
@st.cache_resource # This decorator caches the loading process
|
| 16 |
-
def load_resources():
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
#
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
# Dataset preprocessing
|
| 37 |
-
df = pd.DataFrame(dataset['train']) # Replace 'train' with your dataset split
|
| 38 |
-
df = df.sample(10000) # Sample a subset of the dataset for faster processing
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
# Create
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
#
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
st.
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
#
|
| 104 |
-
st.session_state.conversation_history.append({"question":
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
st.write(
|
| 108 |
-
|
| 109 |
-
st.
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 3 |
+
from sentence_transformers import SentenceTransformer
|
| 4 |
+
from langchain.chains import RetrievalQA
|
| 5 |
+
from langchain_community.vectorstores import FAISS
|
| 6 |
+
from datasets import load_dataset
|
| 7 |
+
import numpy as np
|
| 8 |
+
import torch
|
| 9 |
+
import pandas as pd
|
| 10 |
+
import os
|
| 11 |
+
import subprocess
|
| 12 |
+
from dotenv import load_dotenv
|
| 13 |
+
|
| 14 |
+
# Function to load model, tokenizer, and dataset only once
|
| 15 |
+
@st.cache_resource # This decorator caches the loading process
|
| 16 |
+
def load_resources():
|
| 17 |
+
print("Loading resources...")
|
| 18 |
+
|
| 19 |
+
load_dotenv()
|
| 20 |
+
huggingface_token = os.getenv("HUGGINGFACE_TOKEN")
|
| 21 |
+
print(f"Hugging Face Token: {huggingface_token}")
|
| 22 |
+
|
| 23 |
+
# Run the huggingface-cli login command from the Python script using subprocess
|
| 24 |
+
subprocess.run(["huggingface-cli", "login", "--token", huggingface_token])
|
| 25 |
+
print("Logged into Hugging Face.")
|
| 26 |
+
|
| 27 |
+
# Load the pre-trained Llama3 model (or your fine-tuned model)
|
| 28 |
+
tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-3.2-1B")
|
| 29 |
+
model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.2-1B")
|
| 30 |
+
print("Model and tokenizer loaded.")
|
| 31 |
+
|
| 32 |
+
# Load dataset
|
| 33 |
+
dataset = load_dataset('qiaojin/PubMedQA', 'pqa_artificial')
|
| 34 |
+
print("Dataset loaded.")
|
| 35 |
+
|
| 36 |
+
# Dataset preprocessing
|
| 37 |
+
df = pd.DataFrame(dataset['train']) # Replace 'train' with your dataset split
|
| 38 |
+
df = df.sample(10000) # Sample a subset of the dataset for faster processing
|
| 39 |
+
print(f"Sampled dataset: {df.shape[0]} rows.")
|
| 40 |
+
|
| 41 |
+
# Embed the context (documents)
|
| 42 |
+
embedding_model_name = "sentence-transformers/all-MiniLM-L6-v2"
|
| 43 |
+
embedder = SentenceTransformer(embedding_model_name)
|
| 44 |
+
|
| 45 |
+
# Create embeddings for the context
|
| 46 |
+
document_embeddings = embedder.encode(df['context'].tolist(), convert_to_tensor=True)
|
| 47 |
+
print("Document embeddings created.")
|
| 48 |
+
|
| 49 |
+
# Create FAISS index
|
| 50 |
+
faiss_index = FAISS.from_embeddings(document_embeddings)
|
| 51 |
+
print("FAISS index created.")
|
| 52 |
+
|
| 53 |
+
# Create the retrieval chain with LangChain
|
| 54 |
+
qa_chain = RetrievalQA.from_chain_type(
|
| 55 |
+
llm=model,
|
| 56 |
+
retriever=faiss_index.as_retriever(),
|
| 57 |
+
return_source_documents=True
|
| 58 |
+
)
|
| 59 |
+
print("Retrieval chain created.")
|
| 60 |
+
|
| 61 |
+
# Return the loaded resources
|
| 62 |
+
return model, tokenizer, dataset, faiss_index, qa_chain
|
| 63 |
+
|
| 64 |
+
# Load resources only once and cache them
|
| 65 |
+
if "model" not in st.session_state:
|
| 66 |
+
with st.spinner("Loading the model and dataset... Please wait!"):
|
| 67 |
+
print("Starting resource loading...")
|
| 68 |
+
model, tokenizer, dataset, faiss_index, qa_chain = load_resources()
|
| 69 |
+
print("Resources loaded.")
|
| 70 |
+
|
| 71 |
+
# Store the loaded resources in session state
|
| 72 |
+
st.session_state.model = model
|
| 73 |
+
st.session_state.tokenizer = tokenizer
|
| 74 |
+
st.session_state.dataset = dataset
|
| 75 |
+
st.session_state.faiss_index = faiss_index
|
| 76 |
+
st.session_state.qa_chain = qa_chain
|
| 77 |
+
|
| 78 |
+
# Initialize Streamlit session state for memory
|
| 79 |
+
if "conversation_history" not in st.session_state:
|
| 80 |
+
st.session_state.conversation_history = []
|
| 81 |
+
|
| 82 |
+
# Streamlit UI Setup
|
| 83 |
+
st.title("Llama3-based Chatbot with RAG and Contextual Memory")
|
| 84 |
+
st.write("Ask a question, and I will provide two possible answers for you to choose from.")
|
| 85 |
+
|
| 86 |
+
# User input for the query
|
| 87 |
+
user_query = st.text_input("Your Query:", "")
|
| 88 |
+
|
| 89 |
+
if user_query:
|
| 90 |
+
print(f"User query received: {user_query}")
|
| 91 |
+
with st.spinner("Getting two possible answers..."):
|
| 92 |
+
try:
|
| 93 |
+
# Retrieve context using FAISS (document retrieval)
|
| 94 |
+
result = st.session_state.qa_chain.run(user_query)
|
| 95 |
+
print("Context retrieved using FAISS.")
|
| 96 |
+
|
| 97 |
+
# Show two possible responses (you can adjust this to get two different answers)
|
| 98 |
+
possible_answers = [
|
| 99 |
+
result['result'], # First possible answer from model
|
| 100 |
+
result['result'] # Duplicate for simplicity - in real cases, generate two variations (use different methods or prompt variations)
|
| 101 |
+
]
|
| 102 |
+
|
| 103 |
+
# Save the current user query and model responses to the conversation history
|
| 104 |
+
st.session_state.conversation_history.append({"question": user_query, "answers": possible_answers})
|
| 105 |
+
|
| 106 |
+
# Show two responses for the user to choose from
|
| 107 |
+
st.write("Possible Answers:")
|
| 108 |
+
answer_1 = st.button("Answer 1: " + possible_answers[0], key="answer_1")
|
| 109 |
+
answer_2 = st.button("Answer 2: " + possible_answers[1], key="answer_2")
|
| 110 |
+
|
| 111 |
+
if answer_1:
|
| 112 |
+
st.write(f"You selected Answer 1: {possible_answers[0]}")
|
| 113 |
+
# Continue the conversation with the selected answer
|
| 114 |
+
st.session_state.conversation_history.append({"question": "Answer 1 selected", "answers": [possible_answers[0]]})
|
| 115 |
+
|
| 116 |
+
if answer_2:
|
| 117 |
+
st.write(f"You selected Answer 2: {possible_answers[1]}")
|
| 118 |
+
# Continue the conversation with the selected answer
|
| 119 |
+
st.session_state.conversation_history.append({"question": "Answer 2 selected", "answers": [possible_answers[1]]})
|
| 120 |
+
|
| 121 |
+
# Show the conversation history (for debug purposes, can be removed in production)
|
| 122 |
+
st.write("Conversation History:")
|
| 123 |
+
for conversation in st.session_state.conversation_history:
|
| 124 |
+
st.write(f"Question: {conversation['question']}")
|
| 125 |
+
st.write(f"Answers: {conversation['answers']}")
|
| 126 |
+
|
| 127 |
+
except Exception as e:
|
| 128 |
+
print(f"Error while retrieving answer: {e}")
|
| 129 |
+
st.error("An error occurred while processing your query. Please try again.")
|