NLPGenius commited on
Commit
068d763
·
verified ·
1 Parent(s): d2249a5

Upload 3 files

Browse files
Files changed (3) hide show
  1. Dockerfile +16 -0
  2. flask_app.py +135 -0
  3. requirements.txt +23 -0
Dockerfile ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Read the doc: https://huggingface.co/docs/hub/spaces-sdks-docker
2
+ # you will also find guides on how best to write your Dockerfile
3
+
4
+ FROM python:3.9
5
+
6
+ RUN useradd -m -u 1000 user
7
+ USER user
8
+ ENV PATH="/home/user/.local/bin:$PATH"
9
+
10
+ WORKDIR /app
11
+
12
+ COPY --chown=user ./requirements.txt requirements.txt
13
+ RUN pip install --no-cache-dir --upgrade -r requirements.txt
14
+
15
+ COPY --chown=user . /app
16
+ CMD ["gunicorn", "-b", "0.0.0.0:7860", "flask_app:app"]
flask_app.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import AutoTokenizer, AutoModelForCausalLM
2
+ from langchain_core.output_parsers import BaseOutputParser
3
+ from langchain.prompts import PromptTemplate
4
+ from langchain_core.runnables import RunnablePassthrough, RunnableMap
5
+ 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
14
+ from transformers import pipeline
15
+ llm_chain = transformers.pipeline(
16
+ model=model, tokenizer=tokenizer,
17
+ return_full_text=True, # langchain expects the full text
18
+ task='text-generation',
19
+ # we pass model parameters here too
20
+ temperature=0.3, # 'randomness' of outputs, 0.0 is the min and 1.0 the max
21
+ do_sample=True,
22
+ max_length=2000, # mex number of tokens to generate in the output
23
+ truncation=True,
24
+ repetition_penalty=1.1 # without this output begins repeating
25
+ )
26
+
27
+ from langchain.llms import HuggingFacePipeline
28
+
29
+ llm = HuggingFacePipeline(pipeline=llm_chain)
30
+
31
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
32
+ from langchain.embeddings import HuggingFaceEmbeddings
33
+ from langchain.vectorstores import FAISS
34
+
35
+ # Define the chunking and embedding strategy
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):
57
+ def parse(self, text: str) -> str:
58
+ # Extract everything after "Answer:"
59
+ if "Answer:" in text:
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:
79
+ {question}
80
+
81
+ Answer:
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
100
+
101
+ # Initialize Flask app
102
+ app = Flask(__name__)
103
+ CORS(app, supports_credentials=True, allow_headers=["Content-Type"])
104
+
105
+ # Mock chatbot function (replace with your actual pipeline)
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)}"
113
+
114
+ # Route for chatbot responses
115
+ @app.route('/', methods=['GET','POST'])
116
+ def chat():
117
+
118
+ # Try to get JSON data
119
+ if request.content_type == 'application/json':
120
+ data = request.get_json(silent=True)
121
+ user_query = data.get("query", "").strip() if data else ""
122
+ else:
123
+ # Fallback to form-data
124
+ user_query = request.form.get("query", "").strip()
125
+
126
+ if not user_query:
127
+ return jsonify({"error": "Please provide a valid query."}), 400
128
+
129
+ # Get chatbot response
130
+ bot_reply = chatbot_response(user_query)
131
+ return jsonify({"response": bot_reply})
132
+
133
+ # Run the Flask app
134
+ if __name__ == '__main__':
135
+ app.run()
requirements.txt ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ jupyter
2
+ transformers
3
+ git+https://github.com/huggingface/transformers.git
4
+ numpy
5
+ torch
6
+ aiohttp
7
+ torchvision
8
+ torchaudio
9
+ langchain
10
+ unstructured
11
+ langchain-community
12
+ faiss-cpu
13
+ docx2txt
14
+ sentence-transformers
15
+ xformers
16
+ accelerate
17
+ einops
18
+ scikit-learn
19
+ datasets
20
+ peft
21
+ flask
22
+ flask-cors
23
+ gunicorn