Spaces:
Sleeping
Sleeping
Commit ·
3ac4be5
1
Parent(s): 87090eb
Add checkpoint resume + batch upsert to handle quota limits
Browse files- src/vector_store.py +51 -12
src/vector_store.py
CHANGED
|
@@ -42,28 +42,65 @@ def get_or_create_collection(client):
|
|
| 42 |
return client.get_collection(COLLECTION_NAME)
|
| 43 |
|
| 44 |
|
|
|
|
|
|
|
|
|
|
| 45 |
def add_chunks(chunks: list[dict]):
|
| 46 |
-
"""Embed và lưu chunks vào Qdrant + build BM25 index."""
|
| 47 |
client = get_client()
|
| 48 |
get_or_create_collection(client)
|
| 49 |
|
| 50 |
texts = [c["text"] for c in chunks]
|
| 51 |
metadatas = [c["metadata"] for c in chunks]
|
| 52 |
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
batch_texts = texts[i:i + BATCH_SIZE]
|
| 57 |
-
|
| 58 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
time.sleep(BATCH_SIZE * 1.5)
|
| 60 |
|
| 61 |
-
#
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
# Build BM25 index
|
| 69 |
print("Building BM25 index...")
|
|
@@ -72,6 +109,8 @@ def add_chunks(chunks: list[dict]):
|
|
| 72 |
with open(BM25_PATH, "wb") as f:
|
| 73 |
pickle.dump({"bm25": bm25, "texts": texts, "metadatas": metadatas}, f)
|
| 74 |
|
|
|
|
|
|
|
| 75 |
print(f"Đã lưu {len(chunks)} chunks vào Qdrant + BM25")
|
| 76 |
|
| 77 |
|
|
|
|
| 42 |
return client.get_collection(COLLECTION_NAME)
|
| 43 |
|
| 44 |
|
| 45 |
+
CHECKPOINT_PATH = "embed_checkpoint.pkl"
|
| 46 |
+
|
| 47 |
+
|
| 48 |
def add_chunks(chunks: list[dict]):
|
| 49 |
+
"""Embed và lưu chunks vào Qdrant + build BM25 index. Có checkpoint để resume khi lỗi quota."""
|
| 50 |
client = get_client()
|
| 51 |
get_or_create_collection(client)
|
| 52 |
|
| 53 |
texts = [c["text"] for c in chunks]
|
| 54 |
metadatas = [c["metadata"] for c in chunks]
|
| 55 |
|
| 56 |
+
# Load checkpoint nếu có
|
| 57 |
+
done_batches: dict[int, list] = {}
|
| 58 |
+
if Path(CHECKPOINT_PATH).exists():
|
| 59 |
+
with open(CHECKPOINT_PATH, "rb") as f:
|
| 60 |
+
done_batches = pickle.load(f)
|
| 61 |
+
print(f"Resume từ checkpoint: đã xong {len(done_batches)} batches (~{len(done_batches) * BATCH_SIZE} chunks)")
|
| 62 |
+
|
| 63 |
+
pending = [i for i in range(0, len(chunks), BATCH_SIZE) if i not in done_batches]
|
| 64 |
+
print(f"Embedding {len(chunks)} chunks... ({len(pending)} batches còn lại)")
|
| 65 |
+
|
| 66 |
+
for i in tqdm(pending):
|
| 67 |
batch_texts = texts[i:i + BATCH_SIZE]
|
| 68 |
+
|
| 69 |
+
for attempt in range(3):
|
| 70 |
+
try:
|
| 71 |
+
embeddings = embed_texts(batch_texts)
|
| 72 |
+
break
|
| 73 |
+
except Exception as e:
|
| 74 |
+
if "429" in str(e) or "RESOURCE_EXHAUSTED" in str(e):
|
| 75 |
+
wait = 60 * (attempt + 1)
|
| 76 |
+
print(f"\n[Quota] Lỗi rate limit, đợi {wait}s rồi thử lại (lần {attempt + 1}/3)...")
|
| 77 |
+
time.sleep(wait)
|
| 78 |
+
if attempt == 2:
|
| 79 |
+
print("[Quota] Hết quota ngày hôm nay. Chạy lại vào ngày mai, sẽ resume từ checkpoint.")
|
| 80 |
+
raise
|
| 81 |
+
else:
|
| 82 |
+
raise
|
| 83 |
+
|
| 84 |
+
done_batches[i] = embeddings
|
| 85 |
+
with open(CHECKPOINT_PATH, "wb") as f:
|
| 86 |
+
pickle.dump(done_batches, f)
|
| 87 |
+
|
| 88 |
time.sleep(BATCH_SIZE * 1.5)
|
| 89 |
|
| 90 |
+
# Ghép tất cả embeddings theo thứ tự
|
| 91 |
+
all_embeddings = []
|
| 92 |
+
for i in range(0, len(chunks), BATCH_SIZE):
|
| 93 |
+
all_embeddings.extend(done_batches[i])
|
| 94 |
+
|
| 95 |
+
# Lưu vào Qdrant theo batch để tránh timeout
|
| 96 |
+
UPSERT_BATCH = 200
|
| 97 |
+
print(f"Upserting {len(all_embeddings)} points vào Qdrant...")
|
| 98 |
+
for i in tqdm(range(0, len(all_embeddings), UPSERT_BATCH)):
|
| 99 |
+
batch_points = [
|
| 100 |
+
PointStruct(id=i + j, vector=all_embeddings[i + j], payload={"text": texts[i + j], **metadatas[i + j]})
|
| 101 |
+
for j in range(min(UPSERT_BATCH, len(all_embeddings) - i))
|
| 102 |
+
]
|
| 103 |
+
client.upsert(collection_name=COLLECTION_NAME, points=batch_points)
|
| 104 |
|
| 105 |
# Build BM25 index
|
| 106 |
print("Building BM25 index...")
|
|
|
|
| 109 |
with open(BM25_PATH, "wb") as f:
|
| 110 |
pickle.dump({"bm25": bm25, "texts": texts, "metadatas": metadatas}, f)
|
| 111 |
|
| 112 |
+
# Xóa checkpoint sau khi hoàn thành
|
| 113 |
+
Path(CHECKPOINT_PATH).unlink(missing_ok=True)
|
| 114 |
print(f"Đã lưu {len(chunks)} chunks vào Qdrant + BM25")
|
| 115 |
|
| 116 |
|