Spaces:
Running
Running
Upload 6 files
Browse files- app/core/embedding_engine.py +233 -160
- app/core/llm_engine.py +41 -19
- app/core/pdf_processor.py +52 -120
- app/core/rag_service.py +55 -58
- app/core/text_splitter.py +22 -0
app/core/embedding_engine.py
CHANGED
|
@@ -1,160 +1,233 @@
|
|
| 1 |
-
# # embedding_engine.py
|
| 2 |
-
|
| 3 |
-
# import uuid
|
| 4 |
-
# from qdrant_client import QdrantClient, models
|
| 5 |
-
# from qdrant_client.http.models import Distance, VectorParams
|
| 6 |
-
# from
|
| 7 |
-
# from
|
| 8 |
-
#
|
| 9 |
-
|
| 10 |
-
#
|
| 11 |
-
#
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
#
|
| 15 |
-
#
|
| 16 |
-
|
| 17 |
-
#
|
| 18 |
-
|
| 19 |
-
#
|
| 20 |
-
#
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
#
|
| 24 |
-
#
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
#
|
| 28 |
-
#
|
| 29 |
-
#
|
| 30 |
-
#
|
| 31 |
-
#
|
| 32 |
-
#
|
| 33 |
-
|
| 34 |
-
#
|
| 35 |
-
#
|
| 36 |
-
#
|
| 37 |
-
|
| 38 |
-
#
|
| 39 |
-
#
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
#
|
| 43 |
-
# )
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
#
|
| 47 |
-
|
| 48 |
-
#
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
#
|
| 52 |
-
#
|
| 53 |
-
|
| 54 |
-
#
|
| 55 |
-
#
|
| 56 |
-
#
|
| 57 |
-
#
|
| 58 |
-
#
|
| 59 |
-
#
|
| 60 |
-
# )
|
| 61 |
-
# for i in range(len(vectors))
|
| 62 |
-
# ]
|
| 63 |
-
|
| 64 |
-
#
|
| 65 |
-
|
| 66 |
-
# for i in range(0, len(points), BATCH_SIZE):
|
| 67 |
-
# batch = points[i:i + BATCH_SIZE]
|
| 68 |
-
|
| 69 |
-
#
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
#
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# # embedding_engine.py
|
| 2 |
+
|
| 3 |
+
# import uuid, time
|
| 4 |
+
# from qdrant_client import QdrantClient, models
|
| 5 |
+
# from qdrant_client.http.models import Distance, VectorParams
|
| 6 |
+
# from qdrant_client.http.exceptions import UnexpectedResponse
|
| 7 |
+
# from sentence_transformers import SentenceTransformer
|
| 8 |
+
# from app.core.config import QDRANT_URL, QDRANT_API_KEY
|
| 9 |
+
|
| 10 |
+
# MODEL_PATH = "app/core/models/bge-base-en-v1.5"
|
| 11 |
+
# embedder = SentenceTransformer(MODEL_PATH)
|
| 12 |
+
|
| 13 |
+
# qdrant = QdrantClient(
|
| 14 |
+
# url=QDRANT_URL,
|
| 15 |
+
# api_key=QDRANT_API_KEY,
|
| 16 |
+
# check_compatibility=False
|
| 17 |
+
# )
|
| 18 |
+
|
| 19 |
+
# COLLECTION_NAME = "smartnotes"
|
| 20 |
+
# BATCH_SIZE = 10
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
# def ensure_collection():
|
| 24 |
+
# collections = qdrant.get_collections().collections
|
| 25 |
+
# if COLLECTION_NAME not in [c.name for c in collections]:
|
| 26 |
+
# qdrant.create_collection(
|
| 27 |
+
# collection_name=COLLECTION_NAME,
|
| 28 |
+
# vectors_config=VectorParams(
|
| 29 |
+
# size=768,
|
| 30 |
+
# distance=Distance.COSINE
|
| 31 |
+
# ),
|
| 32 |
+
# )
|
| 33 |
+
|
| 34 |
+
# # β
Add this part
|
| 35 |
+
# qdrant.create_payload_index(
|
| 36 |
+
# collection_name=COLLECTION_NAME,
|
| 37 |
+
# field_name="doc_id",
|
| 38 |
+
# field_schema="keyword"
|
| 39 |
+
# )
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
# def embed_and_store(text_chunks, doc_id):
|
| 43 |
+
# print(f"π Embedding and storing {len(text_chunks)} chunks...")
|
| 44 |
+
# ensure_collection()
|
| 45 |
+
|
| 46 |
+
# print(f"πΉ Embedding {len(text_chunks)} chunks...")
|
| 47 |
+
|
| 48 |
+
# vectors = embed_documents(text_chunks)
|
| 49 |
+
|
| 50 |
+
# points = [
|
| 51 |
+
# models.PointStruct(
|
| 52 |
+
# id=str(uuid.uuid4()),
|
| 53 |
+
# vector=vectors[i],
|
| 54 |
+
# payload={
|
| 55 |
+
# "doc_id": doc_id,
|
| 56 |
+
# "text": text_chunks[i],
|
| 57 |
+
# "chunk_id": i,
|
| 58 |
+
# "length": len(text_chunks[i])
|
| 59 |
+
# },
|
| 60 |
+
# )
|
| 61 |
+
# for i in range(len(vectors))
|
| 62 |
+
# ]
|
| 63 |
+
|
| 64 |
+
# print("πΉ Uploading to Qdrant in batches...")
|
| 65 |
+
|
| 66 |
+
# for i in range(0, len(points), BATCH_SIZE):
|
| 67 |
+
# batch = points[i:i + BATCH_SIZE]
|
| 68 |
+
|
| 69 |
+
# success = False
|
| 70 |
+
# retries = 3
|
| 71 |
+
|
| 72 |
+
# while not success and retries > 0:
|
| 73 |
+
# try:
|
| 74 |
+
# qdrant.upsert(
|
| 75 |
+
# collection_name=COLLECTION_NAME,
|
| 76 |
+
# points=batch
|
| 77 |
+
# )
|
| 78 |
+
# success = True
|
| 79 |
+
# print(f" β Uploaded batch {i // BATCH_SIZE + 1}")
|
| 80 |
+
|
| 81 |
+
# except Exception as e:
|
| 82 |
+
# print("β Qdrant error:", e)
|
| 83 |
+
# retries -= 1
|
| 84 |
+
# time.sleep(1.5) # π₯ increase wait
|
| 85 |
+
|
| 86 |
+
# if not success:
|
| 87 |
+
# print("β οΈ Skipping batch after retries")
|
| 88 |
+
|
| 89 |
+
# time.sleep(0.4) # π₯ throttle
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
# def embed_documents(texts):
|
| 94 |
+
# vectors= []
|
| 95 |
+
|
| 96 |
+
# for i in range(0, len(texts), 32):
|
| 97 |
+
# batch = texts[i:i+32]
|
| 98 |
+
# batch_vectors = embedder.encode(batch, show_progress_bar=False)
|
| 99 |
+
# vectors.extend(batch_vectors.tolist())
|
| 100 |
+
|
| 101 |
+
# return vectors
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
# def embed_query(text):
|
| 105 |
+
# return embedder.encode(
|
| 106 |
+
# f"query: {text}",
|
| 107 |
+
# normalize_embeddings=True
|
| 108 |
+
# )
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
# embedding_engine.py
|
| 129 |
+
import uuid, time
|
| 130 |
+
from qdrant_client import QdrantClient, models
|
| 131 |
+
from qdrant_client.http.models import Distance, VectorParams
|
| 132 |
+
from sentence_transformers import SentenceTransformer
|
| 133 |
+
from app.core.config import QDRANT_URL, QDRANT_API_KEY
|
| 134 |
+
|
| 135 |
+
MODEL_PATH = "app/core/models/bge-base-en-v1.5"
|
| 136 |
+
embedder = SentenceTransformer(MODEL_PATH)
|
| 137 |
+
|
| 138 |
+
qdrant = QdrantClient(
|
| 139 |
+
url=QDRANT_URL,
|
| 140 |
+
api_key=QDRANT_API_KEY,
|
| 141 |
+
check_compatibility=False
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
COLLECTION_NAME = "smartnotes"
|
| 145 |
+
BATCH_SIZE = 5 # β
reduced for free tier
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def ensure_collection():
|
| 149 |
+
collections = qdrant.get_collections().collections
|
| 150 |
+
if COLLECTION_NAME not in [c.name for c in collections]:
|
| 151 |
+
qdrant.create_collection(
|
| 152 |
+
collection_name=COLLECTION_NAME,
|
| 153 |
+
vectors_config=VectorParams(size=768, distance=Distance.COSINE),
|
| 154 |
+
)
|
| 155 |
+
qdrant.create_payload_index(
|
| 156 |
+
collection_name=COLLECTION_NAME,
|
| 157 |
+
field_name="doc_id",
|
| 158 |
+
field_schema="keyword"
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def embed_and_store(text_chunks, doc_id):
|
| 163 |
+
print(f"π Final chunks being embedded: {len(text_chunks)}")
|
| 164 |
+
ensure_collection()
|
| 165 |
+
|
| 166 |
+
vectors = embed_documents(text_chunks) # β
now uses correct doc prefix
|
| 167 |
+
|
| 168 |
+
points = [
|
| 169 |
+
models.PointStruct(
|
| 170 |
+
id=str(uuid.uuid4()),
|
| 171 |
+
vector=vectors[i],
|
| 172 |
+
payload={
|
| 173 |
+
"doc_id": doc_id,
|
| 174 |
+
"text": text_chunks[i],
|
| 175 |
+
"chunk_id": i,
|
| 176 |
+
"length": len(text_chunks[i])
|
| 177 |
+
},
|
| 178 |
+
)
|
| 179 |
+
for i in range(len(vectors))
|
| 180 |
+
]
|
| 181 |
+
|
| 182 |
+
failed_batches = []
|
| 183 |
+
|
| 184 |
+
for i in range(0, len(points), BATCH_SIZE):
|
| 185 |
+
batch = points[i:i + BATCH_SIZE]
|
| 186 |
+
batch_num = i // BATCH_SIZE + 1
|
| 187 |
+
success = False
|
| 188 |
+
|
| 189 |
+
for attempt in range(4): # β
4 attempts with exponential backoff
|
| 190 |
+
try:
|
| 191 |
+
qdrant.upsert(collection_name=COLLECTION_NAME, points=batch)
|
| 192 |
+
success = True
|
| 193 |
+
print(f" β Batch {batch_num} uploaded")
|
| 194 |
+
break
|
| 195 |
+
except Exception as e:
|
| 196 |
+
wait = 2 ** attempt # 1s, 2s, 4s, 8s
|
| 197 |
+
print(f" β οΈ Batch {batch_num} attempt {attempt+1} failed: {e} | retrying in {wait}s")
|
| 198 |
+
time.sleep(wait)
|
| 199 |
+
|
| 200 |
+
if not success:
|
| 201 |
+
failed_batches.append(batch_num)
|
| 202 |
+
print(f" β Batch {batch_num} permanently failed")
|
| 203 |
+
|
| 204 |
+
time.sleep(0.6) # β
throttle between successful batches
|
| 205 |
+
|
| 206 |
+
if failed_batches:
|
| 207 |
+
# β
raise so the caller (routes.py) knows something went wrong
|
| 208 |
+
raise RuntimeError(f"Failed to upload batches: {failed_batches}")
|
| 209 |
+
|
| 210 |
+
print(f"β
All batches uploaded for doc_id={doc_id}")
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def embed_documents(texts):
|
| 214 |
+
"""Embed document chunks with correct BGE prefix and normalization."""
|
| 215 |
+
prefixed = [f"Represent this sentence: {t}" for t in texts] # β
correct BGE doc prefix
|
| 216 |
+
vectors = []
|
| 217 |
+
for i in range(0, len(prefixed), 32):
|
| 218 |
+
batch = prefixed[i:i + 32]
|
| 219 |
+
batch_vectors = embedder.encode(
|
| 220 |
+
batch, normalize_embeddings=True, show_progress_bar=False)
|
| 221 |
+
|
| 222 |
+
vectors.extend(batch_vectors.tolist())
|
| 223 |
+
return vectors
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def embed_query(text):
|
| 227 |
+
"""Embed a search query β BGE uses 'query:' prefix for retrieval."""
|
| 228 |
+
return embedder.encode(
|
| 229 |
+
f"query: {text}",
|
| 230 |
+
normalize_embeddings=True
|
| 231 |
+
).tolist() # β
always return list, not numpy array
|
| 232 |
+
|
| 233 |
+
|
app/core/llm_engine.py
CHANGED
|
@@ -1,19 +1,41 @@
|
|
| 1 |
-
# llm_engine.py
|
| 2 |
-
|
| 3 |
-
import google.generativeai as genai
|
| 4 |
-
from app.core.config import GEMINI_API_KEY
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# # llm_engine.py
|
| 2 |
+
|
| 3 |
+
import google.generativeai as genai
|
| 4 |
+
from app.core.config import GEMINI_API_KEY
|
| 5 |
+
from langchain_google_genai import ChatGoogleGenerativeAI
|
| 6 |
+
|
| 7 |
+
# β
Configure Gemini client
|
| 8 |
+
genai.configure(api_key=GEMINI_API_KEY)
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
llm = ChatGoogleGenerativeAI(
|
| 12 |
+
model="gemini-2.5-flash",
|
| 13 |
+
google_api_key=GEMINI_API_KEY,
|
| 14 |
+
temperature=0.2,
|
| 15 |
+
max_output_tokens=800,
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
# # β
Separate LLM for evaluator β needs near-deterministic JSON output
|
| 20 |
+
# eval_llm = ChatGoogleGenerativeAI(
|
| 21 |
+
# model="gemini-2.5-flash",
|
| 22 |
+
# google_api_key=GEMINI_API_KEY,
|
| 23 |
+
# temperature=0.0, # β
deterministic β evaluator must return valid JSON
|
| 24 |
+
# max_output_tokens=200, # β
evaluator only returns a small JSON blob
|
| 25 |
+
# thinking_level="none" # to disable chain-of-thought
|
| 26 |
+
# )
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
eval_llm = ChatGoogleGenerativeAI(
|
| 30 |
+
model="gemini-2.0-flash", # no thinking, faster
|
| 31 |
+
google_api_key=GEMINI_API_KEY,
|
| 32 |
+
temperature=0.0,
|
| 33 |
+
max_output_tokens=200,
|
| 34 |
+
# model_kwargs={
|
| 35 |
+
# "generation_config": {
|
| 36 |
+
# "thinking_config": {
|
| 37 |
+
# "thinking_budget": 0 # β
0 = disabled, bypasses langchain validation entirely
|
| 38 |
+
# }
|
| 39 |
+
# }
|
| 40 |
+
# }
|
| 41 |
+
)
|
app/core/pdf_processor.py
CHANGED
|
@@ -1,120 +1,52 @@
|
|
| 1 |
-
#
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
#
|
| 9 |
-
#
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
#
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
#
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
# pdf_preprocessor.py
|
| 70 |
-
|
| 71 |
-
import os
|
| 72 |
-
from pypdf import PdfReader
|
| 73 |
-
from pdf2image import convert_from_path
|
| 74 |
-
import pytesseract
|
| 75 |
-
|
| 76 |
-
# Optional: Set Tesseract path manually on Windows
|
| 77 |
-
# pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"
|
| 78 |
-
|
| 79 |
-
def extract_text_from_pdf(file_path: str) -> str:
|
| 80 |
-
"""
|
| 81 |
-
Extract text from both text-based and image-based PDFs.
|
| 82 |
-
Falls back to OCR using pytesseract if no embedded text is found.
|
| 83 |
-
"""
|
| 84 |
-
text_output = []
|
| 85 |
-
reader = PdfReader(file_path)
|
| 86 |
-
total_pages = len(reader.pages)
|
| 87 |
-
|
| 88 |
-
print(f"π Processing PDF: {file_path} ({total_pages} pages)")
|
| 89 |
-
|
| 90 |
-
for page_num, page in enumerate(reader.pages, start=1):
|
| 91 |
-
try:
|
| 92 |
-
# Try normal text extraction
|
| 93 |
-
extracted_text = page.extract_text()
|
| 94 |
-
if extracted_text and extracted_text.strip():
|
| 95 |
-
text_output.append(extracted_text)
|
| 96 |
-
print(f"β
Page {page_num}: Extracted embedded text.")
|
| 97 |
-
else:
|
| 98 |
-
# Run OCR if no text found
|
| 99 |
-
print(f"π Page {page_num}: No text found, running OCR...")
|
| 100 |
-
images = convert_from_path(
|
| 101 |
-
file_path, first_page=page_num, last_page=page_num
|
| 102 |
-
)
|
| 103 |
-
ocr_text = ""
|
| 104 |
-
for img in images:
|
| 105 |
-
ocr_text += pytesseract.image_to_string(img, lang="eng", config="--psm 6")
|
| 106 |
-
if ocr_text.strip():
|
| 107 |
-
text_output.append(ocr_text)
|
| 108 |
-
print(f"π§ Page {page_num}: OCR extraction complete.")
|
| 109 |
-
else:
|
| 110 |
-
print(f"β οΈ Page {page_num}: OCR found no readable text.")
|
| 111 |
-
except Exception as e:
|
| 112 |
-
print(f"β Error processing page {page_num}: {e}")
|
| 113 |
-
|
| 114 |
-
full_text = "\n".join(text_output)
|
| 115 |
-
if not full_text.strip():
|
| 116 |
-
print("β οΈ Warning: No text extracted from this PDF at all.")
|
| 117 |
-
else:
|
| 118 |
-
print(f"β
Done! Extracted {len(full_text.split())} words total.")
|
| 119 |
-
|
| 120 |
-
return full_text
|
|
|
|
| 1 |
+
# pdf_preprocessor.py
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
from pypdf import PdfReader
|
| 5 |
+
from pdf2image import convert_from_path
|
| 6 |
+
import pytesseract
|
| 7 |
+
|
| 8 |
+
# Optional: Set Tesseract path manually on Windows
|
| 9 |
+
# pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"
|
| 10 |
+
|
| 11 |
+
def extract_text_from_pdf(file_path: str) -> str:
|
| 12 |
+
"""
|
| 13 |
+
Extract text from both text-based and image-based PDFs.
|
| 14 |
+
Falls back to OCR using pytesseract if no embedded text is found.
|
| 15 |
+
"""
|
| 16 |
+
text_output = []
|
| 17 |
+
reader = PdfReader(file_path)
|
| 18 |
+
total_pages = len(reader.pages)
|
| 19 |
+
|
| 20 |
+
print(f"π Processing PDF: {file_path} ({total_pages} pages)")
|
| 21 |
+
|
| 22 |
+
for page_num, page in enumerate(reader.pages, start=1):
|
| 23 |
+
try:
|
| 24 |
+
# Try normal text extraction
|
| 25 |
+
extracted_text = page.extract_text()
|
| 26 |
+
if extracted_text and extracted_text.strip():
|
| 27 |
+
text_output.append(extracted_text)
|
| 28 |
+
print(f"β
Page {page_num}: Extracted embedded text.")
|
| 29 |
+
else:
|
| 30 |
+
# Run OCR if no text found
|
| 31 |
+
print(f"π Page {page_num}: No text found, running OCR...")
|
| 32 |
+
images = convert_from_path(
|
| 33 |
+
file_path, first_page=page_num, last_page=page_num
|
| 34 |
+
)
|
| 35 |
+
ocr_text = ""
|
| 36 |
+
for img in images:
|
| 37 |
+
ocr_text += pytesseract.image_to_string(img, lang="eng", config="--psm 6")
|
| 38 |
+
if ocr_text.strip():
|
| 39 |
+
text_output.append(ocr_text)
|
| 40 |
+
print(f"π§ Page {page_num}: OCR extraction complete.")
|
| 41 |
+
else:
|
| 42 |
+
print(f"β οΈ Page {page_num}: OCR found no readable text.")
|
| 43 |
+
except Exception as e:
|
| 44 |
+
print(f"β Error processing page {page_num}: {e}")
|
| 45 |
+
|
| 46 |
+
full_text = "\n\n".join(text_output)
|
| 47 |
+
if not full_text.strip():
|
| 48 |
+
print("β οΈ Warning: No text extracted from this PDF at all.")
|
| 49 |
+
else:
|
| 50 |
+
print(f"β
Done! Extracted {len(full_text.split())} words total.")
|
| 51 |
+
|
| 52 |
+
return full_text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
app/core/rag_service.py
CHANGED
|
@@ -1,55 +1,34 @@
|
|
| 1 |
-
# app/core/rag_service.py
|
| 2 |
-
|
| 3 |
-
from app.core.embedding_engine import embedder, COLLECTION_NAME
|
| 4 |
-
from qdrant_client.http.models import Filter, FieldCondition, MatchValue
|
| 5 |
-
from qdrant_client import QdrantClient
|
| 6 |
-
from app.core.config import QDRANT_URL, QDRANT_API_KEY
|
| 7 |
-
|
| 8 |
-
qdrant_client = QdrantClient(
|
| 9 |
-
url=QDRANT_URL,
|
| 10 |
-
api_key=QDRANT_API_KEY,
|
| 11 |
-
check_compatibility=False
|
| 12 |
-
)
|
| 13 |
-
|
| 14 |
|
| 15 |
-
#
|
| 16 |
-
#
|
| 17 |
-
|
| 18 |
-
#
|
| 19 |
-
# collection_name=COLLECTION_NAME,
|
| 20 |
-
# query=question_vector,
|
| 21 |
-
# query_filter=Filter(
|
| 22 |
-
# must=[FieldCondition(key="doc_id", match=MatchValue(value=doc_id))]
|
| 23 |
-
# ),
|
| 24 |
-
# limit=5,
|
| 25 |
-
# ).points
|
| 26 |
-
|
| 27 |
-
# # context = "\n".join([hit.payload["text"] for hit in hits])
|
| 28 |
-
|
| 29 |
-
# contexts = []
|
| 30 |
-
# sources = []
|
| 31 |
-
|
| 32 |
-
# for hit in hits:
|
| 33 |
-
# text = hit.payload.get("text", "")
|
| 34 |
-
# contexts.append(text)
|
| 35 |
-
|
| 36 |
-
# sources.append({
|
| 37 |
-
# "text": text[:300], # limit for UI
|
| 38 |
-
# # add page if you have it later
|
| 39 |
-
# })
|
| 40 |
-
|
| 41 |
-
# context = "\n".join(contexts)
|
| 42 |
-
|
| 43 |
-
# return context, sources
|
| 44 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
|
| 46 |
# def get_rag_context(query, doc_id, top_k=3):
|
|
|
|
|
|
|
| 47 |
# query_vector = embedder.encode(query).tolist()
|
| 48 |
|
|
|
|
| 49 |
# results = qdrant_client.query_points(
|
| 50 |
-
# collection_name=
|
| 51 |
# query=query_vector,
|
| 52 |
-
# limit=top_k
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
# )
|
| 54 |
|
| 55 |
# points = results.points
|
|
@@ -65,23 +44,38 @@ qdrant_client = QdrantClient(
|
|
| 65 |
|
| 66 |
|
| 67 |
|
| 68 |
-
def get_rag_context(query, doc_id, top_k=3):
|
| 69 |
-
|
| 70 |
-
# β
Embed query
|
| 71 |
-
query_vector = embedder.encode(query).tolist()
|
| 72 |
|
| 73 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
results = qdrant_client.query_points(
|
| 75 |
-
collection_name=
|
| 76 |
query=query_vector,
|
| 77 |
limit=top_k,
|
|
|
|
| 78 |
query_filter=Filter(
|
| 79 |
-
must=[
|
| 80 |
-
FieldCondition(
|
| 81 |
-
key="doc_id",
|
| 82 |
-
match=MatchValue(value=doc_id)
|
| 83 |
-
)
|
| 84 |
-
]
|
| 85 |
)
|
| 86 |
)
|
| 87 |
|
|
@@ -90,9 +84,12 @@ def get_rag_context(query, doc_id, top_k=3):
|
|
| 90 |
if not points:
|
| 91 |
return "", [], []
|
| 92 |
|
| 93 |
-
context = "\n".join([p.payload["text"] for p in points])
|
| 94 |
-
sources = [p.payload.get("
|
| 95 |
scores = [p.score for p in points]
|
| 96 |
|
| 97 |
return context, sources, scores
|
| 98 |
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# # app/core/rag_service.py
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
+
# from app.core.embedding_engine import embedder, COLLECTION_NAME
|
| 4 |
+
# from qdrant_client.http.models import Filter, FieldCondition, MatchValue
|
| 5 |
+
# from qdrant_client import QdrantClient
|
| 6 |
+
# from app.core.config import QDRANT_URL, QDRANT_API_KEY
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
+
# qdrant_client = QdrantClient(
|
| 9 |
+
# url=QDRANT_URL,
|
| 10 |
+
# api_key=QDRANT_API_KEY,
|
| 11 |
+
# check_compatibility=False
|
| 12 |
+
# )
|
| 13 |
|
| 14 |
# def get_rag_context(query, doc_id, top_k=3):
|
| 15 |
+
|
| 16 |
+
# # β
Embed query
|
| 17 |
# query_vector = embedder.encode(query).tolist()
|
| 18 |
|
| 19 |
+
# # β
Query SINGLE collection + filter by doc_id
|
| 20 |
# results = qdrant_client.query_points(
|
| 21 |
+
# collection_name="smartnotes", # π₯ FIXED
|
| 22 |
# query=query_vector,
|
| 23 |
+
# limit=top_k,
|
| 24 |
+
# query_filter=Filter(
|
| 25 |
+
# must=[
|
| 26 |
+
# FieldCondition(
|
| 27 |
+
# key="doc_id",
|
| 28 |
+
# match=MatchValue(value=doc_id)
|
| 29 |
+
# )
|
| 30 |
+
# ]
|
| 31 |
+
# )
|
| 32 |
# )
|
| 33 |
|
| 34 |
# points = results.points
|
|
|
|
| 44 |
|
| 45 |
|
| 46 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
# app/core/rag_service.py
|
| 57 |
+
from app.core.embedding_engine import embed_query, COLLECTION_NAME # β
use the correct function
|
| 58 |
+
from qdrant_client.http.models import Filter, FieldCondition, MatchValue
|
| 59 |
+
from qdrant_client import QdrantClient
|
| 60 |
+
from app.core.config import QDRANT_URL, QDRANT_API_KEY
|
| 61 |
+
|
| 62 |
+
qdrant_client = QdrantClient(
|
| 63 |
+
url=QDRANT_URL,
|
| 64 |
+
api_key=QDRANT_API_KEY,
|
| 65 |
+
check_compatibility=False
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def get_rag_context(query, doc_id, top_k=5): # β
top_k=5 for better recall
|
| 70 |
+
query_vector = embed_query(query) # β
uses "query: " prefix + returns list
|
| 71 |
+
|
| 72 |
results = qdrant_client.query_points(
|
| 73 |
+
collection_name=COLLECTION_NAME,
|
| 74 |
query=query_vector,
|
| 75 |
limit=top_k,
|
| 76 |
+
score_threshold=0.35, # β
filter truly irrelevant results early
|
| 77 |
query_filter=Filter(
|
| 78 |
+
must=[FieldCondition(key="doc_id", match=MatchValue(value=doc_id))]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
)
|
| 80 |
)
|
| 81 |
|
|
|
|
| 84 |
if not points:
|
| 85 |
return "", [], []
|
| 86 |
|
| 87 |
+
context = "\n\n---\n\n".join([p.payload["text"] for p in points]) # β
clearer separator
|
| 88 |
+
sources = [p.payload.get("chunk_id", i) for i, p in enumerate(points)]
|
| 89 |
scores = [p.score for p in points]
|
| 90 |
|
| 91 |
return context, sources, scores
|
| 92 |
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
|
app/core/text_splitter.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# text_splitter.py
|
| 2 |
+
|
| 3 |
+
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
| 4 |
+
|
| 5 |
+
splitter = RecursiveCharacterTextSplitter(
|
| 6 |
+
chunk_size=500,
|
| 7 |
+
chunk_overlap=150,
|
| 8 |
+
separators=["\n\n", "\n", ".", " ", ""]
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
def split_text(text):
|
| 12 |
+
|
| 13 |
+
chunks = splitter.split_text(text)
|
| 14 |
+
|
| 15 |
+
# π₯ CLEANING STEP (VERY IMPORTANT)
|
| 16 |
+
cleaned_chunks = []
|
| 17 |
+
for chunk in chunks:
|
| 18 |
+
chunk = chunk.strip()
|
| 19 |
+
if len(chunk) > 50: # β remove tiny garbage chunks
|
| 20 |
+
cleaned_chunks.append(chunk)
|
| 21 |
+
|
| 22 |
+
return cleaned_chunks
|