Spaces:
Sleeping
Sleeping
Update utils/DocsLoader.py
Browse files- utils/DocsLoader.py +23 -15
utils/DocsLoader.py
CHANGED
|
@@ -72,8 +72,29 @@ os.makedirs(CACHE_DIR, exist_ok=True)
|
|
| 72 |
def load_and_chunk(url: str) -> list[Document]:
|
| 73 |
print(f"[Loader] URL: {url}")
|
| 74 |
|
| 75 |
-
#
|
| 76 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
cache_file = os.path.join(CACHE_DIR, f"{content_hash}.pkl")
|
| 78 |
|
| 79 |
# Return cached version if exists
|
|
@@ -82,17 +103,6 @@ def load_and_chunk(url: str) -> list[Document]:
|
|
| 82 |
with open(cache_file, "rb") as f:
|
| 83 |
return pickle.load(f)
|
| 84 |
|
| 85 |
-
# Download content
|
| 86 |
-
head = requests.head(url)
|
| 87 |
-
file_size = int(head.headers.get("Content-Length", 0))
|
| 88 |
-
USE_STREAM = file_size > 30 * 1024 * 1024 # > 30MB
|
| 89 |
-
|
| 90 |
-
resp = requests.get(url, stream=USE_STREAM)
|
| 91 |
-
if resp.status_code != 200:
|
| 92 |
-
raise HTTPException(400, "Could not download document")
|
| 93 |
-
|
| 94 |
-
content = resp.content
|
| 95 |
-
|
| 96 |
# Determine content type
|
| 97 |
content_type = resp.headers.get("Content-Type", "").lower()
|
| 98 |
url_lower = url.lower()
|
|
@@ -135,5 +145,3 @@ def load_and_chunk(url: str) -> list[Document]:
|
|
| 135 |
print(f"💾 Chunks cached to {cache_file}")
|
| 136 |
|
| 137 |
return chunks
|
| 138 |
-
|
| 139 |
-
|
|
|
|
| 72 |
def load_and_chunk(url: str) -> list[Document]:
|
| 73 |
print(f"[Loader] URL: {url}")
|
| 74 |
|
| 75 |
+
# Try to get content length
|
| 76 |
+
try:
|
| 77 |
+
head = requests.head(url)
|
| 78 |
+
file_size = int(head.headers.get("Content-Length", 0))
|
| 79 |
+
except:
|
| 80 |
+
file_size = 0
|
| 81 |
+
|
| 82 |
+
USE_STREAM = file_size > 30 * 1024 * 1024 # >30MB
|
| 83 |
+
|
| 84 |
+
# Download content (streamed if large)
|
| 85 |
+
content = b""
|
| 86 |
+
hasher = hashlib.md5()
|
| 87 |
+
|
| 88 |
+
with requests.get(url, stream=USE_STREAM) as resp:
|
| 89 |
+
if resp.status_code != 200:
|
| 90 |
+
raise HTTPException(400, "Could not download document")
|
| 91 |
+
|
| 92 |
+
for chunk in resp.iter_content(chunk_size=8192):
|
| 93 |
+
hasher.update(chunk)
|
| 94 |
+
content += chunk
|
| 95 |
+
|
| 96 |
+
# Cache key based on content hash
|
| 97 |
+
content_hash = hasher.hexdigest()
|
| 98 |
cache_file = os.path.join(CACHE_DIR, f"{content_hash}.pkl")
|
| 99 |
|
| 100 |
# Return cached version if exists
|
|
|
|
| 103 |
with open(cache_file, "rb") as f:
|
| 104 |
return pickle.load(f)
|
| 105 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
# Determine content type
|
| 107 |
content_type = resp.headers.get("Content-Type", "").lower()
|
| 108 |
url_lower = url.lower()
|
|
|
|
| 145 |
print(f"💾 Chunks cached to {cache_file}")
|
| 146 |
|
| 147 |
return chunks
|
|
|
|
|
|