lloydakresi commited on
Commit
8001a18
·
1 Parent(s): 2c69fef

finished with ingestion and embedding

Browse files
Files changed (2) hide show
  1. app/embeddings.py +12 -0
  2. app/ingestion.py +53 -0
app/embeddings.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import chromadb
2
+ from ingestion import extract
3
+ def embeddings(file_path):
4
+ client = chromadb.Client()
5
+ v_db = client.get_or_create_collection(name="emb_db")
6
+ chunks, _, _ = extract(file_path)
7
+ v_db.add(
8
+ ids = chunks["ids"],
9
+ documents=chunks["text"],
10
+ metadatas=chunks["metadata"]
11
+ )
12
+ return v_db
app/ingestion.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ import fitz
3
+ import re
4
+ from langchain_text_splitters import RecursiveCharacterTextSplitter
5
+
6
+
7
+
8
+ def extract(file_path):
9
+ filename = Path(file_path).name
10
+ splitter = RecursiveCharacterTextSplitter(
11
+ chunk_size=500,
12
+ chunk_overlap=75,
13
+ separators=["\n\n", "\n", ". ", " "]
14
+ )
15
+ p = {}
16
+ p["ids"], p["text"], p["metadata"] = [], [], []
17
+ #skipping the first 24 pages
18
+ skips = 0
19
+ with fitz.open(file_path) as doc:
20
+ for page in doc:
21
+
22
+ text = page.get_text("text")
23
+ text = re.sub(r"[ \t]+", " ", text)
24
+ text = re.sub(r"\n{3,}", "\n\n", text)
25
+ text = re.sub(r"(?m)^\d+\s*$", "", text)
26
+ text = re.sub(r"-\n", "", text)
27
+ num = page.number + 1
28
+
29
+ split_text = splitter.split_text(text)
30
+
31
+ if num >= 25:
32
+ for i, t in enumerate(split_text):
33
+ id = f"{filename}_{num}_{i}"
34
+ p["ids"].append(id)
35
+ p["text"].append(t)
36
+ p["metadata"].append(
37
+ {"page_number":num}
38
+ )
39
+
40
+ else:
41
+ skips+=1
42
+ return p, skips, num
43
+
44
+ p, skips, num = extract("../corpus/d2l-en.pdf")
45
+ print(f"Total number of pages:{num}")
46
+ print(f"Pages skipped:{skips}")
47
+ print(f"Total number of chunks: {len(p["ids"])}")
48
+ total_char = 0
49
+ for x in p["text"]:
50
+ total_char += len(x)
51
+
52
+ average_chunk_len = total_char/len(p["ids"])
53
+ print(f"Average chunk length: {average_chunk_len}")