giveaccesstoall commited on
Commit
be8bda0
·
verified ·
1 Parent(s): bd31022

Upload 6 files

Browse files
Files changed (7) hide show
  1. .gitattributes +1 -0
  2. Dockerfile +11 -0
  3. app.py +56 -0
  4. chunks.pkl +3 -0
  5. index.faiss +3 -0
  6. process_pdf.py +53 -0
  7. requirements.txt +6 -0
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ index.faiss filter=lfs diff=lfs merge=lfs -text
Dockerfile ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.10
2
+
3
+ # Copy files
4
+ COPY . /app
5
+ WORKDIR /app
6
+
7
+ # Install dependencies
8
+ RUN pip install --no-cache-dir --upgrade -r requirements.txt
9
+
10
+ # Run FastAPI app on port 7860 (required by Hugging Face Spaces)
11
+ CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
app.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI
2
+ from fastapi.middleware.cors import CORSMiddleware
3
+ from pydantic import BaseModel
4
+ from sentence_transformers import SentenceTransformer
5
+ from transformers import pipeline
6
+ import faiss
7
+ import pickle
8
+
9
+ app = FastAPI(title="RAG Chatbot API")
10
+
11
+ # === Enable CORS (optional but recommended for browser-based Razor apps) ===
12
+ app.add_middleware(
13
+ CORSMiddleware,
14
+ allow_origins=["*"], # Replace with your domain in production
15
+ allow_methods=["*"],
16
+ allow_headers=["*"],
17
+ )
18
+
19
+ # === Load once at startup ===
20
+ chunks_path = "chunks.pkl"
21
+ index_path = "index.faiss"
22
+
23
+ with open(chunks_path, "rb") as f:
24
+ chunks = pickle.load(f)
25
+
26
+ index = faiss.read_index(index_path)
27
+ embedder = SentenceTransformer("all-MiniLM-L6-v2")
28
+ generator = pipeline("text2text-generation", model="google/flan-t5-base")
29
+
30
+ # === Retrieval and Generation ===
31
+ def retrieve(query, top_k=3):
32
+ query_embedding = embedder.encode([query], convert_to_numpy=True)
33
+ distances, indices = index.search(query_embedding, top_k)
34
+ return [chunks[i] for i in indices[0]]
35
+
36
+ def generate_answer(context, query):
37
+ prompt = f"Answer the question based on the context and give meaningfull ending.\n\nContext:\n{context}\n\nQuestion: {query}"
38
+ response = generator(prompt, max_new_tokens=150)[0]["generated_text"]
39
+ return response.strip()
40
+
41
+
42
+ # === API Endpoint ===
43
+ class QueryRequest(BaseModel):
44
+ query: str # Must match Razor payload field
45
+
46
+ @app.post("/query")
47
+ def ask_question(request: QueryRequest):
48
+ print(f"✅ Received query: {request.query}") # Debug log
49
+ retrieved = retrieve(request.query)
50
+ context = "\n".join(retrieved)
51
+ answer = generate_answer(context, request.query)
52
+ return {
53
+ "UserQuery": request.query,
54
+ "RetrievedContext": context,
55
+ "answer": answer
56
+ }
chunks.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e74eedc4f1b55a30bc3c2b7f72410d1d4e5bcd41b2f0022077293648bcb140c1
3
+ size 91858
index.faiss ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4f0ded40a06ffe7b66332c82aa95fb01029c724161d60b2fd09f5ddd7b2b142f
3
+ size 305709
process_pdf.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # process_pdf.py
2
+
3
+ import fitz # PyMuPDF
4
+ from sentence_transformers import SentenceTransformer
5
+ import faiss
6
+ import numpy as np
7
+ import pickle
8
+
9
+ # === Step 1: Extract text from PDF ===
10
+ def extract_text_from_pdf(pdf_path):
11
+ doc = fitz.open(pdf_path)
12
+ full_text = ""
13
+ for page in doc:
14
+ full_text += page.get_text()
15
+ return full_text
16
+
17
+ # === Step 2: Chunk text ===
18
+ def chunk_text(text, chunk_size=500):
19
+ paragraphs = text.split("\n")
20
+ chunks = []
21
+ current_chunk = ""
22
+ for para in paragraphs:
23
+ if len(current_chunk) + len(para) < chunk_size:
24
+ current_chunk += para + " "
25
+ else:
26
+ chunks.append(current_chunk.strip())
27
+ current_chunk = para + " "
28
+ if current_chunk:
29
+ chunks.append(current_chunk.strip())
30
+ return chunks
31
+
32
+ # === Step 3: Embed and save ===
33
+ def build_and_save_index(chunks, embedder, index_path="index.faiss", chunks_path="chunks.pkl"):
34
+ embeddings = embedder.encode(chunks, convert_to_numpy=True)
35
+ dimension = embeddings.shape[1]
36
+ index = faiss.IndexFlatL2(dimension)
37
+ index.add(embeddings)
38
+
39
+ faiss.write_index(index, index_path)
40
+ with open(chunks_path, "wb") as f:
41
+ pickle.dump(chunks, f)
42
+
43
+ print(f"✅ Saved FAISS index to {index_path}")
44
+ print(f"✅ Saved chunks to {chunks_path}")
45
+
46
+ # === Run Once ===
47
+ if __name__ == "__main__":
48
+ pdf_path = "input.pdf" # Replace with your actual PDF
49
+ raw_text = extract_text_from_pdf(pdf_path)
50
+ chunks = chunk_text(raw_text)
51
+
52
+ embedder = SentenceTransformer("all-MiniLM-L6-v2")
53
+ build_and_save_index(chunks, embedder)
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ fastapi
2
+ uvicorn
3
+ sentence-transformers
4
+ transformers
5
+ faiss-cpu
6
+ pickle5