File size: 14,188 Bytes
5b14aa2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 | """URL processor for handling web pages and file downloads."""
import os
import re
import tempfile
from typing import Dict, Any, Optional
from urllib.parse import urlparse
from .base import BaseProcessor
from ..result import ConversionResult
from ..exceptions import ConversionError, NetworkError
class URLProcessor(BaseProcessor):
"""Processor for URLs and web pages."""
def can_process(self, file_path: str) -> bool:
"""Check if this processor can handle the given file.
Args:
file_path: Path to the file to check (or URL)
Returns:
True if this processor can handle the file
"""
# Check if it looks like a URL
return self._is_url(file_path)
def process(self, file_path: str) -> ConversionResult:
"""Process the URL and return a conversion result.
Args:
file_path: URL to process
Returns:
ConversionResult containing the processed content
Raises:
NetworkError: If network operations fail
ConversionError: If processing fails
"""
try:
import requests
# First, check if this URL points to a file
file_info = self._detect_file_from_url(file_path)
if file_info:
# This is a file URL, download and process it
return self._process_file_url(file_path, file_info)
else:
# This is a web page, process it as HTML
return self._process_web_page(file_path)
except ImportError:
raise ConversionError("requests and beautifulsoup4 are required for URL processing. Install them with: pip install requests beautifulsoup4")
except requests.RequestException as e:
raise NetworkError(f"Failed to fetch URL {file_path}: {str(e)}")
except Exception as e:
if isinstance(e, (NetworkError, ConversionError)):
raise
raise ConversionError(f"Failed to process URL {file_path}: {str(e)}")
def _detect_file_from_url(self, url: str) -> Optional[Dict[str, Any]]:
"""Detect if a URL points to a file and return file information.
Args:
url: URL to check
Returns:
File info dict if it's a file URL, None otherwise
"""
try:
import requests
# Check URL path for file extensions
parsed_url = urlparse(url)
path = parsed_url.path.lower()
# Common file extensions
file_extensions = {
'.pdf': 'pdf',
'.doc': 'doc',
'.docx': 'docx',
'.txt': 'txt',
'.md': 'markdown',
'.html': 'html',
'.htm': 'html',
'.xlsx': 'xlsx',
'.xls': 'xls',
'.csv': 'csv',
'.ppt': 'ppt',
'.pptx': 'pptx',
'.jpg': 'image',
'.jpeg': 'image',
'.png': 'image',
'.gif': 'image',
'.bmp': 'image',
'.tiff': 'image',
'.tif': 'image',
'.webp': 'image'
}
# Check for file extension in URL path
for ext, file_type in file_extensions.items():
if path.endswith(ext):
return {
'file_type': file_type,
'extension': ext,
'filename': os.path.basename(path) or f"downloaded_file{ext}"
}
# If no extension in URL, check content-type header
try:
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}
# Make a HEAD request to check content-type
response = requests.head(url, headers=headers, timeout=10, allow_redirects=True)
if response.status_code == 200:
content_type = response.headers.get('content-type', '').lower()
# Check for file content types
if 'application/pdf' in content_type:
return {'file_type': 'pdf', 'extension': '.pdf', 'filename': 'downloaded_file.pdf'}
elif 'application/msword' in content_type or 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' in content_type:
ext = '.docx' if 'openxmlformats' in content_type else '.doc'
return {'file_type': 'doc' if ext == '.doc' else 'docx', 'extension': ext, 'filename': f'downloaded_file{ext}'}
elif 'application/vnd.ms-excel' in content_type or 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' in content_type:
ext = '.xlsx' if 'openxmlformats' in content_type else '.xls'
return {'file_type': 'xlsx' if ext == '.xlsx' else 'xls', 'extension': ext, 'filename': f'downloaded_file{ext}'}
elif 'application/vnd.ms-powerpoint' in content_type or 'application/vnd.openxmlformats-officedocument.presentationml.presentation' in content_type:
ext = '.pptx' if 'openxmlformats' in content_type else '.ppt'
return {'file_type': 'pptx' if ext == '.pptx' else 'ppt', 'extension': ext, 'filename': f'downloaded_file{ext}'}
elif 'text/plain' in content_type:
return {'file_type': 'txt', 'extension': '.txt', 'filename': 'downloaded_file.txt'}
elif 'text/markdown' in content_type:
return {'file_type': 'markdown', 'extension': '.md', 'filename': 'downloaded_file.md'}
elif 'text/html' in content_type:
# HTML could be a web page or a file, check if it's likely a file
if 'attachment' in response.headers.get('content-disposition', '').lower():
return {'file_type': 'html', 'extension': '.html', 'filename': 'downloaded_file.html'}
# If it's HTML but not an attachment, treat as web page
return None
elif any(img_type in content_type for img_type in ['image/jpeg', 'image/png', 'image/gif', 'image/bmp', 'image/tiff', 'image/webp']):
# Determine extension from content type
ext_map = {
'image/jpeg': '.jpg',
'image/png': '.png',
'image/gif': '.gif',
'image/bmp': '.bmp',
'image/tiff': '.tiff',
'image/webp': '.webp'
}
ext = ext_map.get(content_type, '.jpg')
return {'file_type': 'image', 'extension': ext, 'filename': f'downloaded_file{ext}'}
except requests.RequestException:
# If HEAD request fails, assume it's a web page
pass
except Exception:
pass
return None
def _process_file_url(self, url: str, file_info: Dict[str, Any]) -> ConversionResult:
"""Download and process a file from URL.
Args:
url: URL to download from
file_info: Information about the file
Returns:
ConversionResult containing the processed content
"""
try:
import requests
from ..extractor import DocumentExtractor
# Download the file
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}
response = requests.get(url, headers=headers, timeout=60, stream=True)
response.raise_for_status()
# Create a temporary file
with tempfile.NamedTemporaryFile(delete=False, suffix=file_info['extension']) as temp_file:
# Write the downloaded content and track size
content_length = 0
for chunk in response.iter_content(chunk_size=8192):
if chunk: # Filter out keep-alive chunks
temp_file.write(chunk)
content_length += len(chunk)
temp_file_path = temp_file.name
try:
# Process the downloaded file using the appropriate processor
extractor = DocumentExtractor()
result = extractor.extract(temp_file_path)
# Add URL metadata to the result
result.metadata.update({
"source_url": url,
"downloaded_filename": file_info['filename'],
"content_type": response.headers.get('content-type', ''),
"content_length": content_length
})
return result
finally:
# Clean up the temporary file
try:
os.unlink(temp_file_path)
except OSError:
pass
except Exception as e:
raise ConversionError(f"Failed to download and process file from URL {url}: {str(e)}")
def _process_web_page(self, url: str) -> ConversionResult:
"""Process a web page URL.
Args:
url: URL to process
Returns:
ConversionResult containing the processed content
"""
try:
from bs4 import BeautifulSoup
import requests
# Fetch the web page
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}
response = requests.get(url, headers=headers, timeout=30)
response.raise_for_status()
# Parse the HTML
soup = BeautifulSoup(response.content, 'html.parser')
# Remove script and style elements
for script in soup(["script", "style"]):
script.decompose()
# Extract text content
content_parts = []
# Get title
title = soup.find('title')
if title:
content_parts.append(f"# {title.get_text().strip()}\n")
# Get main content
main_content = self._extract_main_content(soup)
if main_content:
content_parts.append(main_content)
else:
# Fallback to body text
body = soup.find('body')
if body:
content_parts.append(body.get_text())
content = '\n'.join(content_parts)
# Clean up the content
content = self._clean_content(content)
metadata = {
"url": url,
"status_code": response.status_code,
"content_type": response.headers.get('content-type', ''),
"content_length": len(response.content),
"processor": self.__class__.__name__
}
return ConversionResult(content, metadata)
except Exception as e:
raise ConversionError(f"Failed to process web page {url}: {str(e)}")
def _is_url(self, text: str) -> bool:
"""Check if the text looks like a URL.
Args:
text: Text to check
Returns:
True if text looks like a URL
"""
try:
result = urlparse(text)
return all([result.scheme, result.netloc])
except Exception:
return False
def _extract_main_content(self, soup) -> str:
"""Extract main content from the HTML.
Args:
soup: BeautifulSoup object
Returns:
Extracted main content
"""
# Try to find main content areas
main_selectors = [
'main',
'[role="main"]',
'.main-content',
'.content',
'#content',
'article',
'.post-content',
'.entry-content'
]
for selector in main_selectors:
element = soup.select_one(selector)
if element:
return element.get_text()
# If no main content found, return empty string
return ""
def _clean_content(self, content: str) -> str:
"""Clean up the extracted web content.
Args:
content: Raw web text content
Returns:
Cleaned text content
"""
# Remove excessive whitespace and normalize
lines = content.split('\n')
cleaned_lines = []
for line in lines:
# Remove excessive whitespace
line = ' '.join(line.split())
if line.strip():
cleaned_lines.append(line)
# Join lines and add proper spacing
content = '\n'.join(cleaned_lines)
# Add spacing around headers
content = content.replace('# ', '\n# ')
content = content.replace('## ', '\n## ')
return content.strip() |