Spaces:
Sleeping
Sleeping
Upload DocsLoader.py
Browse files- utils/DocsLoader.py +50 -0
utils/DocsLoader.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import tempfile
|
| 3 |
+
import requests
|
| 4 |
+
|
| 5 |
+
from fastapi import HTTPException
|
| 6 |
+
from langchain_community.document_loaders import PyPDFLoader, Docx2txtLoader
|
| 7 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 8 |
+
from langchain.schema import Document
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def load_and_chunk(url: str) -> list[Document]:
|
| 12 |
+
resp = requests.get(url)
|
| 13 |
+
if resp.status_code != 200:
|
| 14 |
+
raise HTTPException(400, "Could not download document")
|
| 15 |
+
|
| 16 |
+
content_type = resp.headers.get("Content-Type", "").lower()
|
| 17 |
+
url_lower = url.lower()
|
| 18 |
+
|
| 19 |
+
if "application/pdf" in content_type or ".pdf" in url_lower:
|
| 20 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp:
|
| 21 |
+
tmp.write(resp.content)
|
| 22 |
+
tmp_path = tmp.name
|
| 23 |
+
try:
|
| 24 |
+
loader = PyPDFLoader(tmp_path)
|
| 25 |
+
docs = loader.load_and_split()
|
| 26 |
+
finally:
|
| 27 |
+
os.remove(tmp_path)
|
| 28 |
+
|
| 29 |
+
elif (
|
| 30 |
+
"application/vnd.openxmlformats-officedocument.wordprocessingml.document" in content_type
|
| 31 |
+
or ".docx" in url_lower
|
| 32 |
+
):
|
| 33 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".docx") as tmp:
|
| 34 |
+
tmp.write(resp.content)
|
| 35 |
+
tmp_path = tmp.name
|
| 36 |
+
try:
|
| 37 |
+
loader = Docx2txtLoader(tmp_path)
|
| 38 |
+
docs = loader.load_and_split()
|
| 39 |
+
finally:
|
| 40 |
+
os.remove(tmp_path)
|
| 41 |
+
|
| 42 |
+
elif "text/plain" in content_type or ".txt" in url_lower:
|
| 43 |
+
text = resp.content.decode("utf-8", errors="ignore")
|
| 44 |
+
docs = [Document(page_content=text)]
|
| 45 |
+
|
| 46 |
+
else:
|
| 47 |
+
raise HTTPException(400, f"Unsupported document type: {content_type}")
|
| 48 |
+
|
| 49 |
+
splitter = RecursiveCharacterTextSplitter(chunk_size=400, chunk_overlap=80)
|
| 50 |
+
return splitter.split_documents(docs)
|