ak0601 commited on
Commit
9923cde
·
verified ·
1 Parent(s): bd88854

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -86
app.py CHANGED
@@ -1,119 +1,95 @@
1
- from pypdf import PdfReader
2
- from langchain.document_loaders import PyPDFLoader
3
- from langchain.document_loaders import TextLoader
4
- from langchain.document_loaders import Docx2txtLoader
5
- from langchain.text_splitter import CharacterTextSplitter
6
- from langchain_text_splitters import RecursiveCharacterTextSplitter
 
 
 
 
 
 
 
7
  from langchain.embeddings import HuggingFaceEmbeddings
8
- from langchain.vectorstores import Chroma
9
- from huggingface_hub import notebook_login
10
- import torch
11
- from langchain_google_genai import ChatGoogleGenerativeAI
12
- from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
13
- from langchain_core.messages import HumanMessage, SystemMessage
14
- from langchain.chains import create_history_aware_retriever, create_retrieval_chain
15
- from langchain.chains.combine_documents import create_stuff_documents_chain
16
- from dotenv import load_dotenv, dotenv_values
17
- from langchain.schema.document import Document
18
  import os
19
- import streamlit as st
20
- HUGGINGFACEHUB_API_TOKEN = os.getenv("HUGGINGFACEHUB_API_TOKEN")
21
- os.environ['HUGGINGFACEHUB_API_TOKEN'] = HUGGINGFACEHUB_API_TOKEN
22
- GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
23
- os.environ["GOOGLE_API_KEY"] = GOOGLE_API_KEY
24
 
 
 
25
 
26
  if not GOOGLE_API_KEY:
27
  raise ValueError("Gemini API key not found. Please set it in the .env file.")
28
 
29
- st.set_page_config(page_title="English Tutor Chatbot", layout="centered")
30
- st.title("English Turtor Bot")
 
 
 
31
 
32
- # Initialize OpenAI LLM
33
  llm = ChatGoogleGenerativeAI(
34
  model="gemini-1.5-pro-latest",
35
- temperature=0.2, # Slightly higher for varied responses
36
  max_tokens=None,
37
  timeout=None,
38
  max_retries=2,
39
  )
40
 
41
-
42
- embeddings = HuggingFaceEmbeddings(model_name='sentence-transformers/all-mpnet-base-v2')
43
 
44
  def load_preprocessed_vectorstore():
45
  try:
46
- reader = PdfReader("sound.pdf")
47
- num_pages = len(reader.pages)
48
-
49
- document = []
50
- dict1 = {}
51
- indx = 0
52
- for i in range(34,456):
53
- page = reader.pages[i]
54
- document.append(Document(page_content=page.extract_text()))
55
- text_splitter = RecursiveCharacterTextSplitter(
56
  separators=["\n\n", "\n", ". ", " ", ""],
57
  chunk_size=3000,
58
- chunk_overlap=1000)
59
-
60
- document_chunks = text_splitter.split_documents(document)
 
61
 
62
- vector_store =Chroma.from_documents(document_chunks,embedding=embeddings, persist_directory='./data')
 
 
 
 
63
  return vector_store
64
  except Exception as e:
65
  st.error(f"Error creating vector store: {e}")
66
  return None
67
 
68
  def get_context_retriever_chain(vector_store):
69
- """Creates a history-aware retriever chain."""
70
  retriever = vector_store.as_retriever()
71
 
72
- # Define the prompt for the retriever chain
73
  prompt = ChatPromptTemplate.from_messages([
74
  MessagesPlaceholder(variable_name="chat_history"),
75
  ("human", "{input}"),
76
- ("system", """Given the chat history and the latest user question, which might reference context in the chat history,
77
- formulate a standalone question that can be understood without the chat history.
78
- If the question is directly addressed within the provided document, provide a relevant answer.
79
- If the question is not explicitly addressed in the document, return the following message:
80
- 'This question is beyond the scope of the available information. Please contact the mentor for further assistance.'
81
- Do NOT answer the question directly, just reformulate it if needed and otherwise return it as is.
82
- Also if the questions is about any irrelevent topic like politics, war, homosexuality, transgender etc just reply the following message:
83
- 'Please reframe your question'""")
84
  ])
85
 
86
  retriever_chain = create_history_aware_retriever(llm, retriever, prompt)
87
  return retriever_chain
88
 
89
  def get_conversational_chain(retriever_chain):
90
- """Creates a conversational chain using the retriever chain."""
91
  prompt = ChatPromptTemplate.from_messages([
92
- ("system", """I am an advanced English tutor designed to help users improve their English language skills through interactive lessons, personalized feedback, and quizzes. Your goal is to enhance their vocabulary, grammar, reading comprehension, and speaking ability. You should adapt to their skill level and learning preferences."
93
-
94
- User Interaction Guidelines:
95
-
96
- Learning Mode: Begin by asking the user their current proficiency level (Beginner, Intermediate, Advanced) and their learning goals (e.g., improve vocabulary, master grammar, prepare for an exam, etc.).
97
- Interactive Lessons: Provide engaging lessons tailored to their level. Use examples, simple explanations, and interactive questions. For example:
98
- Beginner: "What's the plural form of 'apple'?"
99
- Advanced: "Explain the difference between 'affect' and 'effect' with examples."
100
- Quizzes: Offer quizzes after lessons to reinforce learning. Use multiple-choice, fill-in-the-blank, or open-ended questions. Adjust the difficulty based on user performance. Provide immediate feedback, explaining why an answer is correct or incorrect.
101
- Speaking Practice: If requested, simulate conversations and provide constructive feedback on grammar, vocabulary, and pronunciation.
102
- Example Response:
103
-
104
- Learning Mode Prompt: "Hello! I'm here to help you improve your English. Could you tell me about your current level and goals? For instance, do you want to focus on grammar, expand your vocabulary, or practice speaking?"
105
- Interactive Lesson Prompt: "Let's practice forming questions. Convert this statement into a question: 'She is reading a book.'"
106
- Quiz Prompt: "Choose the correct option: 'The cat ____ on the mat.'
107
- A) sit
108
- B) sits
109
- C) sitting
110
- D) siting"
111
- (Correct answer: B - 'sits')
112
- Adaptability Features:
113
-
114
- Respond dynamically to user input, simplifying explanations or increasing complexity as needed.
115
- Encourage and motivate users by celebrating their progress.
116
- Offer follow-up suggestions after quizzes, e.g., "You did well on vocabulary! Shall we try a grammar-focused session next?
117
  """
118
  "\n\n"
119
  "{context}"),
@@ -127,19 +103,19 @@ Offer follow-up suggestions after quizzes, e.g., "You did well on vocabulary! Sh
127
  def get_response(user_query):
128
  retriever_chain = get_context_retriever_chain(st.session_state.vector_store)
129
  conversation_rag_chain = get_conversational_chain(retriever_chain)
130
-
131
  formatted_chat_history = []
132
  for message in st.session_state.chat_history:
133
  if isinstance(message, HumanMessage):
134
  formatted_chat_history.append({"author": "user", "content": message.content})
135
  elif isinstance(message, SystemMessage):
136
  formatted_chat_history.append({"author": "assistant", "content": message.content})
137
-
138
  response = conversation_rag_chain.invoke({
139
  "chat_history": formatted_chat_history,
140
  "input": user_query
141
  })
142
-
143
  return response['answer']
144
 
145
  # Load the preprocessed vector store from the local directory
@@ -148,7 +124,7 @@ st.session_state.vector_store = load_preprocessed_vectorstore()
148
  # Initialize chat history if not present
149
  if "chat_history" not in st.session_state:
150
  st.session_state.chat_history = [
151
- {"author": "assistant", "content": "Hello, I am an English Tutor. How can I help you?"}
152
  ]
153
 
154
  # Main app logic
@@ -167,7 +143,7 @@ else:
167
 
168
  # Add user input box below the chat
169
  with st.container():
170
- with st.form(key="chat_form"):
171
  user_query = st.text_input("Type your message here...", key="user_input")
172
  submit_button = st.form_submit_button("Send")
173
 
@@ -178,7 +154,4 @@ else:
178
  st.session_state.chat_history.append({"author": "assistant", "content": response})
179
 
180
  # Rerun the app to refresh the chat display
181
- st.rerun()
182
-
183
-
184
- """"""
 
1
+ import os
2
+ import streamlit as st
3
+ import google.generativeai as genai
4
+ from langchain_google_genai import GoogleGenerativeAIEmbeddings
5
+ from langchain_google_genai import ChatGoogleGenerativeAI
6
+ from langchain_community.document_loaders import PyPDFLoader
7
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
8
+ from langchain_community.vectorstores import Chroma
9
+ from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
10
+ from langchain_core.messages import HumanMessage, SystemMessage
11
+ from langchain.chains import create_history_aware_retriever, create_retrieval_chain
12
+ from langchain.chains.combine_documents import create_stuff_documents_chain
13
+ from dotenv import load_dotenv
14
  from langchain.embeddings import HuggingFaceEmbeddings
15
+
16
+ from sentence_transformers import SentenceTransformer
17
+
18
+ import pysqlite3
19
+ import sys
20
+ sys.modules['sqlite3'] = pysqlite3
21
+
 
 
 
22
  import os
23
+ os.environ["TRANSFORMERS_OFFLINE"] = "1"
 
 
 
 
24
 
25
+ # Retrieve Google API key
26
+ GOOGLE_API_KEY = "AIzaSyAytkzRS0Xp0pCyo6WqKJ4m1o330bF-gPk"
27
 
28
  if not GOOGLE_API_KEY:
29
  raise ValueError("Gemini API key not found. Please set it in the .env file.")
30
 
31
+ os.environ["GOOGLE_API_KEY"] = GOOGLE_API_KEY
32
+
33
+ # Streamlit app configuration
34
+ st.set_page_config(page_title="English Chatbot", layout="centered")
35
+ st.title("English Tutor Bot")
36
 
37
+ # Initialize Google Generative AI LLM
38
  llm = ChatGoogleGenerativeAI(
39
  model="gemini-1.5-pro-latest",
40
+ temperature=0.2,
41
  max_tokens=None,
42
  timeout=None,
43
  max_retries=2,
44
  )
45
 
46
+ # Initialize embeddings using HuggingFace
47
+ embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2")
48
 
49
  def load_preprocessed_vectorstore():
50
  try:
51
+ loader = PyPDFLoader("sound.pdf")
52
+ documents = loader.load()
53
+
54
+ text_splitter = RecursiveCharacterTextSplitter(
 
 
 
 
 
 
55
  separators=["\n\n", "\n", ". ", " ", ""],
56
  chunk_size=3000,
57
+ chunk_overlap=1000
58
+ )
59
+
60
+ document_chunks = text_splitter.split_documents(documents)
61
 
62
+ vector_store = Chroma.from_documents(
63
+ embedding=embeddings,
64
+ documents=document_chunks,
65
+ persist_directory="./data32"
66
+ )
67
  return vector_store
68
  except Exception as e:
69
  st.error(f"Error creating vector store: {e}")
70
  return None
71
 
72
  def get_context_retriever_chain(vector_store):
 
73
  retriever = vector_store.as_retriever()
74
 
 
75
  prompt = ChatPromptTemplate.from_messages([
76
  MessagesPlaceholder(variable_name="chat_history"),
77
  ("human", "{input}"),
78
+ ("system", """Given the chat history and the latest user question, which might reference context in the chat history, Answer the question
79
+ by taking reference from the document.
80
+ If the question is directly addressed within the provided document, provide a relevant answer.
81
+ If the question is not explicitly addressed in the document, return the following message:
82
+ 'This question is beyond the scope of the available information. Please contact your mentor for further assistance.'
83
+ Do NOT answer the question directly, just reformulate it if needed and otherwise return it as is.""")
 
 
84
  ])
85
 
86
  retriever_chain = create_history_aware_retriever(llm, retriever, prompt)
87
  return retriever_chain
88
 
89
  def get_conversational_chain(retriever_chain):
 
90
  prompt = ChatPromptTemplate.from_messages([
91
+ ("system", """Hello! I'm your English Tutor, I am here to help you with learning english and can also take quiz to test your skills.
92
+ Note: I will only provide information that is available within our database to ensure accuracy. Let's get started!
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
  """
94
  "\n\n"
95
  "{context}"),
 
103
  def get_response(user_query):
104
  retriever_chain = get_context_retriever_chain(st.session_state.vector_store)
105
  conversation_rag_chain = get_conversational_chain(retriever_chain)
106
+
107
  formatted_chat_history = []
108
  for message in st.session_state.chat_history:
109
  if isinstance(message, HumanMessage):
110
  formatted_chat_history.append({"author": "user", "content": message.content})
111
  elif isinstance(message, SystemMessage):
112
  formatted_chat_history.append({"author": "assistant", "content": message.content})
113
+
114
  response = conversation_rag_chain.invoke({
115
  "chat_history": formatted_chat_history,
116
  "input": user_query
117
  })
118
+
119
  return response['answer']
120
 
121
  # Load the preprocessed vector store from the local directory
 
124
  # Initialize chat history if not present
125
  if "chat_history" not in st.session_state:
126
  st.session_state.chat_history = [
127
+ {"author": "assistant", "content": "Hello, I am Precollege. How can I help you?"}
128
  ]
129
 
130
  # Main app logic
 
143
 
144
  # Add user input box below the chat
145
  with st.container():
146
+ with st.form(key="chat_form", clear_on_submit=True):
147
  user_query = st.text_input("Type your message here...", key="user_input")
148
  submit_button = st.form_submit_button("Send")
149
 
 
154
  st.session_state.chat_history.append({"author": "assistant", "content": response})
155
 
156
  # Rerun the app to refresh the chat display
157
+ st.rerun()