import requests
from bs4 import BeautifulSoup
from urllib.parse import urlparse, urljoin, urlunparse
from collections import deque
import time # For politeness
import os # For saving temp docs
import hashlib # For chunk IDs
# Import your existing modules for chunking, embedding, redis
# --- Configuration ---
MAIN_WEBSITE_URL = "https://example.com"
BLACKLIST_URLS = {"https://example.com/private", "https://example.com/login"} # Use a set
ALLOWED_DOMAINS = {urlparse(MAIN_WEBSITE_URL).netloc} # Crawl only within this domain
# --- URL Utility Functions ---
def normalize_url(url):
"""Removes fragment, sorts query params, handles trailing slash"""
try:
parsed = urlparse(url)
# Remove fragment
parsed = parsed._replace(fragment="")
# Optional: remove/sort query params if they don't change content
# parsed = parsed._replace(query="")
# Optional: remove trailing slash if path is not root
if parsed.path.endswith('/') and len(parsed.path) > 1:
parsed = parsed._replace(path=parsed.path[:-1])
# Lowercase domain and scheme
parsed = parsed._replace(netloc=parsed.netloc.lower(), scheme=parsed.scheme.lower())
return urlunparse(parsed)
except:
return None # Handle invalid URLs
def is_allowed(url):
"""Checks if url is within allowed domains and not blacklisted"""
normalized = normalize_url(url)
if not normalized: return False
try:
domain = urlparse(normalized).netloc
if domain not in ALLOWED_DOMAINS:
return False
if normalized in BLACKLIST_URLS:
return False
# Optional: Check for specific disallowed path patterns
# if '/archive/' in urlparse(normalized).path: return False
return True
except:
return False # Handle parsing errors
def is_document_url(url):
"""Checks if the URL points to a document based on extension"""
if not url: return False
# Add more extensions as needed
doc_extensions = ['.pdf', '.docx', '.pptx', '.xlsx', '.odt', '.ods', '.odp']
return any(url.lower().endswith(ext) for ext in doc_extensions)
# --- Existing pipeline integration placeholders ---
def your_chunking_function(text, source_url):
# Call your existing text chunking logic
# Should return a list of text chunks
pass
def your_document_loader_function(file_content_binary, filename, source_url):
# Use your existing PDF/DOCX loader
# Should return a list of text chunks
pass
def your_embedding_function(text_chunk):
# Call your existing OpenAI embedding logic
pass
def your_redis_save_function(chunk_text, embedding, metadata):
# Call your existing Redis saving logic
# metadata should include source, type, etc.
pass
# --- Content Extraction (Simplified Example) ---
def extract_main_text_from_html(html_content):
"""Extracts text, removing scripts/styles and optionally other tags"""
try:
soup = BeautifulSoup(html_content, 'html.parser')
# Remove script and style elements
for script_or_style in soup(['script', 'style', 'nav', 'footer', 'aside', 'header']):
script_or_style.decompose()
# Get text - could be refined
text = soup.get_text(separator='\n', strip=True)
# --- Alternative: Use a readability library ---
# from readability import Document
# doc = Document(html_content)
# text = doc.summary() # Or doc.plain_text()
return text
except Exception as e:
print(f"Error extracting text: {e}")
return None
# --- Crawler Logic ---
def crawl_website(start_url, blacklist):
urls_to_visit = deque([normalize_url(start_url)])
visited_urls = set()
download_queue = deque() # To store document URLs found
while urls_to_visit:
current_url = urls_to_visit.popleft()
if not current_url or current_url in visited_urls or not is_allowed(current_url):
continue
print(f"Visiting: {current_url}")
visited_urls.add(current_url) # Mark as visited early
try:
response = requests.get(current_url, timeout=15)
response.raise_for_status() # Raise an HTTPError for bad responses (4xx or 5xx)
content_type = response.headers.get('Content-Type', '')
# --- Handle HTML pages ---
if 'text/html' in content_type:
html_content = response.text
soup = BeautifulSoup(html_content, 'html.parser')
# 1. Extract and Process Text Content
main_text = extract_main_text_from_html(html_content)
if main_text:
print(f"Extracted text from {current_url} ({len(main_text)} chars)")
# Process text: Chunk -> Embed -> Save to Redis
chunks = your_chunking_function(main_text, current_url)
for i, chunk_text in enumerate(chunks):
embedding = your_embedding_function(chunk_text)
metadata = {
'source': current_url,
'type': 'webpage',
'chunk_index': i,
'title': soup.title.string if soup.title else current_url, # Use page title if available
# Add a unique ID for the chunk
'chunk_id': hashlib.sha256(f"{current_url}-{i}-{chunk_text[:50]}".encode()).hexdigest()
}
your_redis_save_function(chunk_text, embedding, metadata)
print(f"Saved chunk {i} from {current_url}")
# 2. Discover Links (Web pages and Documents)
for link in soup.find_all('a', href=True):
href = link.get('href')
absolute_url = urljoin(current_url, href)
normalized = normalize_url(absolute_url)
if normalized and is_allowed(normalized):
if is_document_url(normalized):
if normalized not in download_queue and normalized not in visited_urls: # Prevent re-downloading
print(f"Found document link: {normalized}")
download_queue.append(normalized)
elif normalized not in visited_urls and normalized not in urls_to_visit:
urls_to_visit.append(normalized)
print(f"Found page link: {normalized}")
# --- Handle other content types if necessary (optional) ---
# Could check for XML, JSON APIs if they contain relevant info
except requests.exceptions.RequestException as e:
print(f"Error fetching {current_url}: {e}")
except Exception as e:
print(f"An unexpected error occurred processing {current_url}: {e}")
# Be polite - wait a bit between requests
time.sleep(1) # Adjust as needed, check robots.txt if available
# --- Process Download Queue after crawling ---
print("\n--- Starting Document Downloads ---")
while download_queue:
doc_url = download_queue.popleft()
if doc_url in visited_urls: # Check again in case it was added multiple times
continue
visited_urls.add(doc_url) # Mark document URL as visited
print(f"Downloading document: {doc_url}")
try:
response = requests.get(doc_url, stream=True, timeout=30) # Increased timeout for docs
response.raise_for_status()
# Download to a temporary file or process directly from content
# For simplicity, reading content into memory here. For very large files, save to temp.
file_content_binary = response.content
filename = os.path.basename(urlparse(doc_url).path) or 'downloaded_doc'
print(f"Downloaded {filename} ({len(file_content_binary)} bytes)")
# Process document: Load -> Chunk -> Embed -> Save to Redis
chunks = your_document_loader_function(file_content_binary, filename, doc_url) # Use your existing loader
for i, chunk_text in enumerate(chunks):
embedding = your_embedding_function(chunk_text)
metadata = {
'source': doc_url,
'type': 'document',
'filename': filename,
'chunk_index': i,
'chunk_id': hashlib.sha256(f"{doc_url}-{i}-{chunk_text[:50]}".encode()).hexdigest()
}
# Optional: add page number if your document loader provides it
your_redis_save_function(chunk_text, embedding, metadata)
print(f"Saved chunk {i} from {filename}")
except requests.exceptions.RequestException as e:
print(f"Error downloading {doc_url}: {e}")
except Exception as e:
print(f"An unexpected error occurred processing document {doc_url}: {e}")
time.sleep(1) # Be polite
print("\n--- Crawling and Document Processing Finished ---")
# --- How to run it ---
if __name__ == "__main__":
# Make sure your Redis connection, chunking, embedding functions are initialized
# For example:
# redis_client = your_redis_connection_setup()
# embedding_model = your_openai_embedding_setup()
# etc.
crawl_website(MAIN_WEBSITE_URL, BLACKLIST_URLS)