singhankur01 commited on
Commit
d90ea5d
·
verified ·
1 Parent(s): 40a7274

Update utils/DocsLoader.py

Browse files
Files changed (1) hide show
  1. utils/DocsLoader.py +58 -47
utils/DocsLoader.py CHANGED
@@ -19,55 +19,66 @@ nltk.download("punkt_tab", download_dir=NLTK_PATH, quiet=True)
19
 
20
  MODEL_DIR = os.path.join("/tmp", "e5-large-v2")
21
 
 
 
 
22
  def load_and_chunk(url: str) -> list[Document]:
23
  print(url)
24
- resp = requests.get(url)
25
- if resp.status_code != 200:
26
- raise HTTPException(400, "Could not download document")
27
-
28
- content_type = resp.headers.get("Content-Type", "").lower()
29
- url_lower = url.lower()
30
-
31
- if "application/pdf" in content_type or ".pdf" in url_lower:
32
- with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp:
33
- tmp.write(resp.content)
34
- tmp_path = tmp.name
35
- try:
36
- loader = PyMuPDFLoader(tmp_path)
37
- docs = loader.load_and_split()
38
- finally:
39
- os.remove(tmp_path)
40
-
41
- elif (
42
- "application/vnd.openxmlformats-officedocument.wordprocessingml.document" in content_type
43
- or ".docx" in url_lower
44
- ):
45
- with tempfile.NamedTemporaryFile(delete=False, suffix=".docx") as tmp:
46
- tmp.write(resp.content)
47
- tmp_path = tmp.name
48
- try:
49
- loader = Docx2txtLoader(tmp_path)
50
- docs = loader.load_and_split()
51
- finally:
52
- os.remove(tmp_path)
53
-
54
- elif "text/plain" in content_type or ".txt" in url_lower:
55
- text = resp.content.decode("utf-8", errors="ignore")
56
- docs = [Document(page_content=text)]
57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  else:
59
- raise HTTPException(400, f"Unsupported document type: {content_type}")
60
- # # --- Step 1: Sentence split ---
61
- # sentence_docs = []
62
- # for doc in docs:
63
- # sentences = nltk.sent_tokenize(doc.page_content)
64
- # for sent in sentences:
65
- # if sent.strip():
66
- # sentence_docs.append(Document(page_content=sent, metadata=doc.metadata))
67
- full_text = "\n".join([doc.page_content for doc in docs])
68
 
69
- # splitter = RecursiveCharacterTextSplitter(chunk_size=800, chunk_overlap=150)
70
- splitter = SentenceTransformersTokenTextSplitter(model_name = MODEL_DIR,tokens_per_chunk=512, chunk_overlap=80)
71
- # return splitter.split_documents(docs)
72
- # return splitter.split_documents([Document(page_content=full_text)])
73
- return splitter.create_documents([full_text])
 
19
 
20
  MODEL_DIR = os.path.join("/tmp", "e5-large-v2")
21
 
22
+ chunk_dict= {}
23
+
24
+
25
  def load_and_chunk(url: str) -> list[Document]:
26
  print(url)
27
+ if(url not in chunk_dict):
28
+ print("processing new url")
29
+ resp = requests.get(url)
30
+ if resp.status_code != 200:
31
+ raise HTTPException(400, "Could not download document")
32
+
33
+ content_type = resp.headers.get("Content-Type", "").lower()
34
+ url_lower = url.lower()
35
+
36
+ if "application/pdf" in content_type or ".pdf" in url_lower:
37
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp:
38
+ tmp.write(resp.content)
39
+ tmp_path = tmp.name
40
+ try:
41
+ loader = PyMuPDFLoader(tmp_path)
42
+ docs = loader.load_and_split()
43
+ finally:
44
+ os.remove(tmp_path)
45
+
46
+ elif (
47
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document" in content_type
48
+ or ".docx" in url_lower
49
+ ):
50
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".docx") as tmp:
51
+ tmp.write(resp.content)
52
+ tmp_path = tmp.name
53
+ try:
54
+ loader = Docx2txtLoader(tmp_path)
55
+ docs = loader.load_and_split()
56
+ finally:
57
+ os.remove(tmp_path)
 
 
58
 
59
+ elif "text/plain" in content_type or ".txt" in url_lower:
60
+ text = resp.content.decode("utf-8", errors="ignore")
61
+ docs = [Document(page_content=text)]
62
+
63
+ else:
64
+ raise HTTPException(400, f"Unsupported document type: {content_type}")
65
+ # # --- Step 1: Sentence split ---
66
+ # sentence_docs = []
67
+ # for doc in docs:
68
+ # sentences = nltk.sent_tokenize(doc.page_content)
69
+ # for sent in sentences:
70
+ # if sent.strip():
71
+ # sentence_docs.append(Document(page_content=sent, metadata=doc.metadata))
72
+ full_text = "\n".join([doc.page_content for doc in docs])
73
+
74
+ # splitter = RecursiveCharacterTextSplitter(chunk_size=800, chunk_overlap=150)
75
+ splitter = SentenceTransformersTokenTextSplitter(model_name = MODEL_DIR,tokens_per_chunk=512, chunk_overlap=90)
76
+ # return splitter.split_documents(docs)
77
+ # return splitter.split_documents([Document(page_content=full_text)])
78
+ chunk_dict[url] = splitter.create_documents([full_text])
79
+ # return splitter.create_documents([full_text])
80
+ return chunk_dict[url]
81
  else:
82
+ print("stored chunk")
83
+ return chunk_dict[url]
 
 
 
 
 
 
 
84