NLPGenius commited on
Commit
e0cae50
·
verified ·
1 Parent(s): 87b905c

Update flask_app.py

Browse files
Files changed (1) hide show
  1. flask_app.py +66 -28
flask_app.py CHANGED
@@ -6,8 +6,10 @@ from langchain.schema import Generation
6
  import torch
7
 
8
  # Load your tokenizer and model
9
- tokenizer = AutoTokenizer.from_pretrained("NLPGenius/KPDastak-llama3-1b")
10
- model = AutoModelForCausalLM.from_pretrained("NLPGenius/KPDastak-llama3-1b", torch_dtype=torch.bfloat16, device_map="auto",)
 
 
11
 
12
 
13
  import transformers
@@ -36,21 +38,53 @@ from langchain.vectorstores import FAISS
36
  text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
37
  embedding_model = HuggingFaceEmbeddings() # Adjust if you have a specific embedding model
38
 
39
- from langchain_core.output_parsers import StrOutputParser
 
 
 
 
 
 
40
  from langchain_core.runnables import RunnablePassthrough
41
- from langchain_community.document_loaders import Docx2txtLoader
42
 
43
- # Set up the vector store for FAISS
44
- def create_faiss_index(pdf_path):
45
- loader = Docx2txtLoader(pdf_path)
46
- data = loader.load()
47
-
48
- texts = text_splitter.split_documents(data)
49
-
50
  vector_store = FAISS.from_documents(texts, embedding_model)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  retriever = vector_store.as_retriever()
 
52
  return retriever
53
 
 
 
 
 
 
54
 
55
  # Define a custom output parser to extract only the answer
56
  class AnswerOutputParser(BaseOutputParser):
@@ -60,19 +94,21 @@ class AnswerOutputParser(BaseOutputParser):
60
  return text.split("Answer:")[-1].strip()
61
  return "I don't know."
62
 
63
- # Define the RAG pipeline
64
- def create_rag_pipeline(pdf_path):
65
- retriever = create_faiss_index(pdf_path)
66
-
67
- # Define the prompt template
68
  prompt = PromptTemplate(
69
  input_variables=["context", "question"],
70
  template="""\
71
  You are a helpful assistant. Answer the query accurately by focusing solely on the most relevant parts of the provided context.
 
72
  1. Identify and use only the sections of the context directly related to the query, ignoring unrelated or extraneous information.
73
  2. If the query cannot be explicitly answered using the relevant parts of the context, respond with: "The answer is not found in the context provided."
74
-
75
- Context:
 
 
 
76
  {context}
77
 
78
  Query:
@@ -82,18 +118,20 @@ def create_rag_pipeline(pdf_path):
82
  """
83
  )
84
 
85
- # Define the sequence
86
  rag_chain = (
87
- RunnableMap({"context": retriever, "question": RunnablePassthrough()}) # Map inputs
88
- | prompt # Use the prompt template
89
- | llm # Apply the LLM
90
- | AnswerOutputParser() # Extract answer from output
91
- )
 
 
92
  return rag_chain
93
 
94
- # Usage example
95
- pdf_path = "Dastak_FullContext.docx"
96
- rag_pipeline = create_rag_pipeline(pdf_path)
97
 
98
  from flask import Flask, request, jsonify
99
  from flask_cors import CORS
@@ -106,7 +144,7 @@ CORS(app, supports_credentials=True, allow_headers=["Content-Type"])
106
  def chatbot_response(query):
107
  try:
108
  # Call your actual RAG pipeline here
109
- response = rag_pipeline.invoke(query) # Replace with your actual RAG pipeline call
110
  return response
111
  except Exception as e:
112
  return f"Error: {str(e)}"
 
6
  import torch
7
 
8
  # Load your tokenizer and model
9
+ tokenizer = AutoTokenizer.from_pretrained("NLPGenius/GovGPT-llama3")
10
+ model = AutoModelForCausalLM.from_pretrained("NLPGenius/GovGPT-llama3",
11
+ torch_dtype=torch.bfloat16,
12
+ device_map="auto",)
13
 
14
 
15
  import transformers
 
38
  text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
39
  embedding_model = HuggingFaceEmbeddings() # Adjust if you have a specific embedding model
40
 
41
+ import os
42
+ from langchain_community.document_loaders import PyPDFLoader
43
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
44
+ from langchain.vectorstores import FAISS
45
+ from langchain.embeddings import HuggingFaceEmbeddings
46
+ from langchain.prompts import PromptTemplate
47
+ from langchain.chains import LLMChain
48
  from langchain_core.runnables import RunnablePassthrough
49
+ from langchain_core.output_parsers import StrOutputParser
50
 
51
+ # Function to create FAISS index
52
+ def create_faiss_index(docs):
53
+ texts = text_splitter.split_documents(docs)
 
 
 
 
54
  vector_store = FAISS.from_documents(texts, embedding_model)
55
+ return vector_store
56
+
57
+ # Function to fetch and process PDF files
58
+ def fetch_and_process_pdfs(folder_path):
59
+ pdf_files = [
60
+ os.path.join(folder_path, file) for file in os.listdir(folder_path) if file.endswith(".pdf")
61
+ ]
62
+
63
+ all_documents = []
64
+ for pdf_file in pdf_files:
65
+ loader = PyPDFLoader(pdf_file)
66
+ documents = loader.load()
67
+ all_documents.extend(documents)
68
+ #print(all_documents)
69
+ return all_documents
70
+
71
+
72
+ # Function to create RAG pipeline
73
+ def create_rag_pipeline(folder_path):
74
+ # Fetch and process PDF files
75
+ documents = fetch_and_process_pdfs(folder_path)
76
+
77
+ # Create vector store
78
+ vector_store = create_faiss_index(documents)
79
  retriever = vector_store.as_retriever()
80
+
81
  return retriever
82
 
83
+ # Usage example
84
+ folder_path = "/kaggle/input/pdf-files/Rules folder - Copy"
85
+ retriever = create_rag_pipeline(folder_path)
86
+
87
+
88
 
89
  # Define a custom output parser to extract only the answer
90
  class AnswerOutputParser(BaseOutputParser):
 
94
  return text.split("Answer:")[-1].strip()
95
  return "I don't know."
96
 
97
+ # Function to perform model inference
98
+ def model_inference(retriever, question):
99
+ # Define prompt template
 
 
100
  prompt = PromptTemplate(
101
  input_variables=["context", "question"],
102
  template="""\
103
  You are a helpful assistant. Answer the query accurately by focusing solely on the most relevant parts of the provided context.
104
+
105
  1. Identify and use only the sections of the context directly related to the query, ignoring unrelated or extraneous information.
106
  2. If the query cannot be explicitly answered using the relevant parts of the context, respond with: "The answer is not found in the context provided."
107
+ 3. If you are unsure or do not know the answer, respond with: "I don't know."
108
+ 4. Do not add information, interpretations, or assumptions beyond what is explicitly stated in the context.
109
+ 5. Ensure the response is concise, avoids redundancy, and directly addresses the query.
110
+
111
+ Context:
112
  {context}
113
 
114
  Query:
 
118
  """
119
  )
120
 
121
+
122
  rag_chain = (
123
+ {"context": retriever, "question": RunnablePassthrough()}
124
+ | prompt
125
+ | llm
126
+ | AnswerOutputParser()
127
+ )
128
+ response = rag_chain.invoke(question)
129
+ print("Bot response: ",response)
130
  return rag_chain
131
 
132
+ #response = model_inference(retriever, "Why was a new agriculture policy needed in Khyber Pakhtunkhwa?")
133
+
134
+
135
 
136
  from flask import Flask, request, jsonify
137
  from flask_cors import CORS
 
144
  def chatbot_response(query):
145
  try:
146
  # Call your actual RAG pipeline here
147
+ response = model_inference(retriever, query)
148
  return response
149
  except Exception as e:
150
  return f"Error: {str(e)}"