Maia Pelletier commited on
Commit ·
8338e22
1
Parent(s): 2f50a55
make hyperlink text webpage title, not URL text
Browse files- ingestion.py +29 -23
ingestion.py
CHANGED
|
@@ -3,13 +3,11 @@ Document ingestion module for processing PDFs and URLs.
|
|
| 3 |
"""
|
| 4 |
import os
|
| 5 |
from typing import List, Dict
|
| 6 |
-
from pathlib import Path
|
| 7 |
import requests
|
| 8 |
from bs4 import BeautifulSoup
|
| 9 |
from pypdf import PdfReader
|
| 10 |
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
| 11 |
from sentence_transformers import SentenceTransformer
|
| 12 |
-
import numpy as np
|
| 13 |
import faiss
|
| 14 |
import pickle
|
| 15 |
|
|
@@ -77,15 +75,15 @@ class DocumentIngestion:
|
|
| 77 |
except Exception as e:
|
| 78 |
raise Exception(f"Error reading PDF {file_path}: {str(e)}")
|
| 79 |
|
| 80 |
-
def read_url(self, url: str)
|
| 81 |
"""
|
| 82 |
-
Extract text from a URL.
|
| 83 |
-
|
| 84 |
Args:
|
| 85 |
url: URL to fetch and extract text from
|
| 86 |
-
|
| 87 |
Returns:
|
| 88 |
-
|
| 89 |
"""
|
| 90 |
try:
|
| 91 |
headers = {
|
|
@@ -93,22 +91,27 @@ class DocumentIngestion:
|
|
| 93 |
}
|
| 94 |
response = requests.get(url, headers=headers, timeout=10)
|
| 95 |
response.raise_for_status()
|
| 96 |
-
|
| 97 |
soup = BeautifulSoup(response.content, 'html.parser')
|
| 98 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
# Remove script and style elements
|
| 100 |
for script in soup(["script", "style"]):
|
| 101 |
script.decompose()
|
| 102 |
-
|
| 103 |
# Get text
|
| 104 |
text = soup.get_text()
|
| 105 |
-
|
| 106 |
# Clean up whitespace
|
| 107 |
lines = (line.strip() for line in text.splitlines())
|
| 108 |
chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
|
| 109 |
text = ' '.join(chunk for chunk in chunks if chunk)
|
| 110 |
-
|
| 111 |
-
return text
|
| 112 |
except Exception as e:
|
| 113 |
raise Exception(f"Error reading URL {url}: {str(e)}")
|
| 114 |
|
|
@@ -148,17 +151,20 @@ class DocumentIngestion:
|
|
| 148 |
if urls:
|
| 149 |
for url in urls:
|
| 150 |
try:
|
| 151 |
-
text = self.read_url(url)
|
| 152 |
chunks = self.text_splitter.split_text(text)
|
| 153 |
-
# Use
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
|
|
|
|
|
|
|
|
|
| 162 |
for i, chunk in enumerate(chunks):
|
| 163 |
all_texts.append(chunk)
|
| 164 |
all_metadata.append({
|
|
|
|
| 3 |
"""
|
| 4 |
import os
|
| 5 |
from typing import List, Dict
|
|
|
|
| 6 |
import requests
|
| 7 |
from bs4 import BeautifulSoup
|
| 8 |
from pypdf import PdfReader
|
| 9 |
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
| 10 |
from sentence_transformers import SentenceTransformer
|
|
|
|
| 11 |
import faiss
|
| 12 |
import pickle
|
| 13 |
|
|
|
|
| 75 |
except Exception as e:
|
| 76 |
raise Exception(f"Error reading PDF {file_path}: {str(e)}")
|
| 77 |
|
| 78 |
+
def read_url(self, url: str):
|
| 79 |
"""
|
| 80 |
+
Extract text and page title from a URL.
|
| 81 |
+
|
| 82 |
Args:
|
| 83 |
url: URL to fetch and extract text from
|
| 84 |
+
|
| 85 |
Returns:
|
| 86 |
+
Tuple of (text content, page title or None)
|
| 87 |
"""
|
| 88 |
try:
|
| 89 |
headers = {
|
|
|
|
| 91 |
}
|
| 92 |
response = requests.get(url, headers=headers, timeout=10)
|
| 93 |
response.raise_for_status()
|
| 94 |
+
|
| 95 |
soup = BeautifulSoup(response.content, 'html.parser')
|
| 96 |
+
|
| 97 |
+
# Extract page title before stripping elements
|
| 98 |
+
page_title = None
|
| 99 |
+
if soup.title and soup.title.string:
|
| 100 |
+
page_title = soup.title.string.strip()
|
| 101 |
+
|
| 102 |
# Remove script and style elements
|
| 103 |
for script in soup(["script", "style"]):
|
| 104 |
script.decompose()
|
| 105 |
+
|
| 106 |
# Get text
|
| 107 |
text = soup.get_text()
|
| 108 |
+
|
| 109 |
# Clean up whitespace
|
| 110 |
lines = (line.strip() for line in text.splitlines())
|
| 111 |
chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
|
| 112 |
text = ' '.join(chunk for chunk in chunks if chunk)
|
| 113 |
+
|
| 114 |
+
return text, page_title
|
| 115 |
except Exception as e:
|
| 116 |
raise Exception(f"Error reading URL {url}: {str(e)}")
|
| 117 |
|
|
|
|
| 151 |
if urls:
|
| 152 |
for url in urls:
|
| 153 |
try:
|
| 154 |
+
text, page_title = self.read_url(url)
|
| 155 |
chunks = self.text_splitter.split_text(text)
|
| 156 |
+
# Use the page's <title> tag if available, otherwise fall back to domain + path
|
| 157 |
+
if page_title:
|
| 158 |
+
document_title = page_title
|
| 159 |
+
else:
|
| 160 |
+
try:
|
| 161 |
+
from urllib.parse import urlparse
|
| 162 |
+
parsed = urlparse(url)
|
| 163 |
+
document_title = parsed.netloc or url
|
| 164 |
+
if parsed.path and parsed.path != "/":
|
| 165 |
+
document_title += " " + parsed.path.strip("/")[:50]
|
| 166 |
+
except Exception:
|
| 167 |
+
document_title = url
|
| 168 |
for i, chunk in enumerate(chunks):
|
| 169 |
all_texts.append(chunk)
|
| 170 |
all_metadata.append({
|