istiak101 commited on
Commit
c86dda3
·
verified ·
1 Parent(s): 2bfc6e4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +129 -115
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
- load_dotenv()
18
-
19
- # huggingface_token = st.secrets["huggingface"]["token"]
20
-
21
- # Set the environment variable using os
22
- huggingface_token = os.getenv("HUGGINGFACE_TOKEN")
23
-
24
- # Run the huggingface-cli login command from the Python script using subprocess
25
- subprocess.run(["huggingface-cli", "login", "--token", huggingface_token])
26
- # Load the pre-trained Llama3 model (or your fine-tuned model)
27
- # model_name = "meta-llama/Meta-Llama-3-8B-Instruct" # Replace with your fine-tuned model path or model name from Hugging Face
28
- # tokenizer = AutoTokenizer.from_pretrained(model_name)
29
- # model = AutoModelForCausalLM.from_pretrained(model_name)
30
-
31
- tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-3.2-1B")
32
- model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.2-1B")
33
- # Load your dataset (this is just an example, replace with your actual dataset)
34
- dataset = load_dataset('qiaojin/PubMedQA', 'pqa_artificial') # Replace with the Hugging Face dataset name
35
-
36
- # Dataset preprocessing (assuming the dataset is a Q&A dataset with columns 'question', 'answer', 'context')
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
- # Embed the context (documents)
40
- embedding_model_name = "sentence-transformers/all-MiniLM-L6-v2"
41
- embedder = SentenceTransformer(embedding_model_name)
42
-
43
- # Create embeddings for the context
44
- document_embeddings = embedder.encode(df['context'].tolist(), convert_to_tensor=True)
45
-
46
- # Create FAISS index
47
- faiss_index = FAISS.from_embeddings(document_embeddings)
48
-
49
- # Create the retrieval chain with LangChain
50
- qa_chain = RetrievalQA.from_chain_type(
51
- llm=model,
52
- retriever=faiss_index.as_retriever(),
53
- return_source_documents=True
54
- )
55
-
56
- # Return the loaded resources
57
- return model, tokenizer, dataset, faiss_index, qa_chain
58
-
59
- # Load resources only once and cache them
60
- if "model" not in st.session_state:
61
- with st.spinner("Loading the model and dataset... Please wait!"):
62
- model, tokenizer, dataset, faiss_index, qa_chain = load_resources()
63
-
64
- # Store the loaded resources in session state
65
- st.session_state.model = model
66
- st.session_state.tokenizer = tokenizer
67
- st.session_state.dataset = dataset
68
- st.session_state.faiss_index = faiss_index
69
- st.session_state.qa_chain = qa_chain
70
-
71
- # Initialize Streamlit session state for memory
72
- if "conversation_history" not in st.session_state:
73
- st.session_state.conversation_history = []
74
-
75
- # Streamlit UI Setup
76
- st.title("Llama3-based Chatbot with RAG and Contextual Memory")
77
- st.write("Ask a question, and I will provide two possible answers for you to choose from.")
78
-
79
- # User input for the query
80
- user_query = st.text_input("Your Query:", "")
81
-
82
- if user_query:
83
- with st.spinner("Getting two possible answers..."):
84
- # Retrieve context using FAISS (document retrieval)
85
- result = st.session_state.qa_chain.run(user_query)
86
-
87
- # Show two possible responses (you can adjust this to get two different answers)
88
- possible_answers = [
89
- result['result'], # First possible answer from model
90
- result['result'] # Duplicate for simplicity - in real cases, generate two variations (use different methods or prompt variations)
91
- ]
92
-
93
- # Save the current user query and model responses to the conversation history
94
- st.session_state.conversation_history.append({"question": user_query, "answers": possible_answers})
95
-
96
- # Show two responses for the user to choose from
97
- st.write("Possible Answers:")
98
- answer_1 = st.button("Answer 1: " + possible_answers[0], key="answer_1")
99
- answer_2 = st.button("Answer 2: " + possible_answers[1], key="answer_2")
100
-
101
- if answer_1:
102
- st.write(f"You selected Answer 1: {possible_answers[0]}")
103
- # Continue the conversation with the selected answer
104
- st.session_state.conversation_history.append({"question": "Answer 1 selected", "answers": [possible_answers[0]]})
105
-
106
- if answer_2:
107
- st.write(f"You selected Answer 2: {possible_answers[1]}")
108
- # Continue the conversation with the selected answer
109
- st.session_state.conversation_history.append({"question": "Answer 2 selected", "answers": [possible_answers[1]]})
110
-
111
- # Show the conversation history (for debug purposes, can be removed in production)
112
- st.write("Conversation History:")
113
- for conversation in st.session_state.conversation_history:
114
- st.write(f"Question: {conversation['question']}")
115
- st.write(f"Answers: {conversation['answers']}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.")