File size: 4,886 Bytes
a7d7463 | 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 | """Web Updater - Update knowledge from web sources"""
import re
import time
import hashlib
from pathlib import Path
from typing import Optional, List, Dict
from dataclasses import dataclass
from datetime import datetime
import requests
from bs4 import BeautifulSoup
@dataclass
class WebSource:
"""Web source configuration"""
name: str
url: str
selector: str = "article"
update_interval: int = 3600
class WebUpdater:
"""Update knowledge from web sources"""
DEFAULT_SOURCES = [
WebSource(
name="python_docs",
url="https://docs.python.org/3/",
selector="main",
),
WebSource(
name="javascript_docs",
url="https://developer.mozilla.org/en-US/docs/Web/JavaScript",
selector="article",
),
]
def __init__(self, cache_dir: Optional[str] = None):
if cache_dir:
self.cache_dir = Path(cache_dir)
else:
self.cache_dir = Path.home() / ".burme_coder" / "cache"
self.cache_dir.mkdir(parents=True, exist_ok=True)
self.last_fetch: Dict[str, datetime] = {}
def fetch_content(self, source: WebSource) -> Optional[str]:
"""Fetch content from a web source"""
cache_file = self.cache_dir / f"{source.name}.html"
if self._is_cache_valid(cache_file):
return cache_file.read_text(encoding="utf-8")
try:
response = requests.get(
source.url, timeout=30, headers={"User-Agent": "Burme-Coder/1.0"}
)
response.raise_for_status()
soup = BeautifulSoup(response.text, "lxml")
content_tag = soup.select_one(source.selector)
if content_tag:
text = self._clean_text(content_tag.get_text())
cache_file.write_text(text, encoding="utf-8")
self.last_fetch[source.name] = datetime.now()
return text
except requests.RequestException as e:
print(f"Error fetching {source.name}: {e}")
return None
def _is_cache_valid(self, cache_file: Path, max_age: int = 3600) -> bool:
"""Check if cache file is still valid"""
if not cache_file.exists():
return False
mtime = datetime.fromtimestamp(cache_file.stat().st_mtime)
age = (datetime.now() - mtime).total_seconds()
return age < max_age
def _clean_text(self, text: str) -> str:
"""Clean and format text content"""
text = re.sub(r"\n{3,}", "\n\n", text)
text = re.sub(r" {2,}", " ", text)
return text.strip()
def fetch_all(self) -> Dict[str, str]:
"""Fetch content from all configured sources"""
results = {}
for source in self.DEFAULT_SOURCES:
content = self.fetch_content(source)
if content:
results[source.name] = content
return results
def update_markdown_files(
self, output_dir: Path, force: bool = False
) -> List[str]:
"""Update markdown files from web sources"""
output_dir.mkdir(parents=True, exist_ok=True)
updated_files = []
for source in self.DEFAULT_SOURCES:
content = self.fetch_content(source)
if content:
md_file = output_dir / f"{source.name}.md"
if md_file.exists() and not force:
if self._content_changed(md_file, content):
md_file.write_text(content, encoding="utf-8")
updated_files.append(md_file.name)
else:
md_file.write_text(content, encoding="utf-8")
updated_files.append(md_file.name)
return updated_files
def _content_changed(self, file: Path, new_content: str) -> bool:
"""Check if content has changed"""
old_content = file.read_text(encoding="utf-8")
old_hash = hashlib.md5(old_content.encode()).hexdigest()
new_hash = hashlib.md5(new_content.encode()).hexdigest()
return old_hash != new_hash
def scrape_url(self, url: str, selectors: List[str]) -> Optional[str]:
"""Scrape specific content from a URL"""
try:
response = requests.get(url, timeout=30)
response.raise_for_status()
soup = BeautifulSoup(response.text, "lxml")
for selector in selectors:
element = soup.select_one(selector)
if element:
return self._clean_text(element.get_text())
except requests.RequestException as e:
print(f"Error scraping {url}: {e}")
return None
def get_last_fetch_time(self, source_name: str) -> Optional[datetime]:
"""Get the last fetch time for a source"""
return self.last_fetch.get(source_name)
|