burme-coder-max / src /knowledge /web_updater.py
amkyawdev's picture
Upload folder using huggingface_hub
a7d7463 verified
"""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)