#!/usr/bin/env python3 """ AGGRESSIVE KNOWLEDGE BASE ACQUISITION Multi-Source Scraping for Quantum Training Aurora - ETL Systems Specialist """ import requests import json import time import re from bs4 import BeautifulSoup from pathlib import Path from urllib.parse import urljoin, urlparse import concurrent.futures from tqdm import tqdm import xml.etree.ElementTree as ET from datetime import datetime import pandas as pd import xml.etree.ElementTree as ET class KnowledgeBaseScraper: def __init__(self): self.session = requests.Session() self.session.headers.update({ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language': 'en-US,en;q=0.5', 'Accept-Encoding': 'gzip, deflate', 'DNT': '1', 'Connection': 'keep-alive', 'Upgrade-Insecure-Requests': '1', }) self.output_dir = Path("/data/adaptai/corpus-data/knowledge-base") self.output_dir.mkdir(exist_ok=True, parents=True) # Target knowledge sources self.sources = { 'technical': [ 'https://arxiv.org/list/cs.AI/recent', # AI papers 'https://arxiv.org/list/cs.LG/recent', # Machine Learning 'https://arxiv.org/list/cs.CL/recent', # Computation & Language 'https://paperswithcode.com/', 'https://huggingface.co/papers', ], 'scientific': [ 'https://www.nature.com/subjects/artificial-intelligence', 'https://www.science.org/topic/artificial-intelligence', 'https://www.ncbi.nlm.nih.gov/pmc/', ], 'educational': [ 'https://www.khanacademy.org/', 'https://ocw.mit.edu/', 'https://www.coursera.org/', 'https://developers.google.com/machine-learning', ], 'financial': [ 'https://www.sec.gov/edgar/searchedgar/companysearch.html', 'https://www.federalreserve.gov/releases/', 'https://www.imf.org/en/Publications', ], 'programming': [ 'https://docs.python.org/3/', 'https://developer.mozilla.org/en-US/docs/Web', 'https://docs.docker.com/', 'https://kubernetes.io/docs/', ] } # Optional SEC filters from environment (comma-separated) import os self.sec_ciks = {c.strip().lower() for c in (os.getenv('SEC_CIK') or '').split(',') if c.strip()} self.sec_form_types = {t.strip().upper() for t in (os.getenv('SEC_FORM_TYPES') or '').split(',') if t.strip()} def scrape_arxiv(self, url): """Scrape arXiv papers""" try: response = self.session.get(url, timeout=30) soup = BeautifulSoup(response.text, 'html.parser') papers = [] for item in soup.find_all('div', class_='meta'): title_elem = item.find('div', class_='list-title') authors_elem = item.find('div', class_='list-authors') abstract_elem = item.find('p', class_='mathjax') if title_elem and abstract_elem: title = title_elem.text.replace('Title:', '').strip() authors = authors_elem.text.replace('Authors:', '').strip() if authors_elem else "" abstract = abstract_elem.text.strip() papers.append({ 'title': title, 'authors': authors, 'abstract': abstract, 'source': 'arxiv', 'url': url, 'timestamp': datetime.now().isoformat() }) return papers except Exception as e: print(f"Error scraping arXiv {url}: {e}") return [] def scrape_academic_site(self, url): """Scrape academic and research sites""" try: response = self.session.get(url, timeout=30) soup = BeautifulSoup(response.text, 'html.parser') # Remove scripts, styles, nav elements for element in soup(['script', 'style', 'nav', 'footer', 'header']): element.decompose() # Get main content text = soup.get_text() lines = (line.strip() for line in text.splitlines()) chunks = (phrase.strip() for line in lines for phrase in line.split(" ")) text = ' '.join(chunk for chunk in chunks if chunk) return { 'content': text, 'title': soup.title.text if soup.title else "", 'url': url, 'source': 'academic', 'timestamp': datetime.now().isoformat() } except Exception as e: print(f"Error scraping academic site {url}: {e}") return None def scrape_documentation(self, url): """Scrape technical documentation""" try: response = self.session.get(url, timeout=30) soup = BeautifulSoup(response.text, 'html.parser') # Focus on main content areas content_selectors = [ 'main', 'article', '.content', '#content', '.documentation', '.docs', 'section' ] content = "" for selector in content_selectors: elements = soup.select(selector) for element in elements: text = element.get_text() lines = (line.strip() for line in text.splitlines()) chunks = (phrase.strip() for line in lines for phrase in line.split(" ")) content += ' '.join(chunk for chunk in chunks if chunk) + "\n\n" if not content: content = soup.get_text() return { 'content': content, 'title': soup.title.text if soup.title else "", 'url': url, 'source': 'documentation', 'timestamp': datetime.now().isoformat() } except Exception as e: print(f"Error scraping documentation {url}: {e}") return None def scrape_financial_data(self, url): """Scrape financial reports and data with basic SEC EDGAR support. - If URL is SEC EDGAR, fetch the Atom feed of recent filings and parse entries. - Otherwise, fall back to academic-style scraping. """ try: if 'sec.gov' in url: # Use the EDGAR recent filings Atom feed for reliability feed_url = 'https://www.sec.gov/cgi-bin/browse-edgar?action=getcurrent&owner=include&count=40&output=atom' headers = { 'User-Agent': self.session.headers.get('User-Agent', 'Mozilla/5.0'), 'Accept': 'application/atom+xml,application/xml;q=0.9,*/*;q=0.8' } resp = self.session.get(feed_url, headers=headers, timeout=30) resp.raise_for_status() root = ET.fromstring(resp.text) ns = {'atom': 'http://www.w3.org/2005/Atom'} items = [] for entry in root.findall('atom:entry', ns): title = (entry.findtext('atom:title', default='', namespaces=ns) or '').strip() summary = (entry.findtext('atom:summary', default='', namespaces=ns) or '').strip() link_el = entry.find('atom:link', ns) link = link_el.get('href') if link_el is not None else '' updated = (entry.findtext('atom:updated', default='', namespaces=ns) or '').strip() item = { 'title': title, 'content': summary, 'category': 'sec_edgar', 'url': link, 'source': 'edgar_atom', 'timestamp': updated or datetime.now().isoformat() } # Basic filtering by CIK and form type if configured # Title format often contains: "8-K - COMPANY NAME (CIK 0000320193)" title_upper = title.upper() title_lower = title.lower() if self.sec_form_types: if not any(ft in title_upper.split() for ft in self.sec_form_types): continue if self.sec_ciks: if not any(f"cik {c}" in title_lower for c in self.sec_ciks): continue items.append(item) return items else: return self.scrape_academic_site(url) except Exception as e: print(f"Error scraping financial data {url}: {e}") return None def scrape_source_type(self, urls, scrape_func): """Scrape multiple URLs of same type""" results = [] with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor: futures = {executor.submit(scrape_func, url): url for url in urls} for future in tqdm(concurrent.futures.as_completed(futures), total=len(futures), desc="Scraping sources"): result = future.result() if result: if isinstance(result, list): results.extend(result) else: results.append(result) return results def scrape_all_sources(self): """Scrape all knowledge sources""" all_data = {} print("šŸš€ AGGRESSIVE KNOWLEDGE BASE SCRAPING INITIATED") print("=" * 60) # Scrape technical sources (arXiv) print("\nšŸ“š Scraping technical papers...") tech_data = [] for arxiv_url in self.sources['technical']: if 'arxiv' in arxiv_url: tech_data.extend(self.scrape_arxiv(arxiv_url)) all_data['technical'] = tech_data # Scrape academic sources print("\nšŸŽ“ Scraping academic resources...") academic_data = self.scrape_source_type( self.sources['scientific'] + self.sources['educational'], self.scrape_academic_site ) all_data['academic'] = academic_data # Scrape documentation print("\nšŸ’» Scraping technical documentation...") docs_data = self.scrape_source_type( self.sources['programming'], self.scrape_documentation ) all_data['documentation'] = docs_data # Scrape financial data print("\nšŸ’° Scraping financial data...") financial_data = self.scrape_source_type( self.sources['financial'], self.scrape_financial_data ) all_data['financial'] = financial_data return all_data def save_results(self, data): """Save scraped data to organized structure""" timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") for category, items in data.items(): if items: category_dir = self.output_dir / category category_dir.mkdir(exist_ok=True) # Save as JSON output_file = category_dir / f"{category}_{timestamp}.json" with open(output_file, 'w', encoding='utf-8') as f: json.dump(items, f, indent=2, ensure_ascii=False) print(f"šŸ’¾ Saved {len(items)} {category} items to {output_file}") # Save summary summary = { 'total_items': sum(len(items) for items in data.values()), 'categories': {cat: len(items) for cat, items in data.items()}, 'timestamp': timestamp, 'sources_scraped': self.sources } summary_file = self.output_dir / f"scraping_summary_{timestamp}.json" with open(summary_file, 'w', encoding='utf-8') as f: json.dump(summary, f, indent=2) print(f"\nšŸ“Š SCRAPING SUMMARY:") print(f" Total items: {summary['total_items']}") for category, count in summary['categories'].items(): print(f" {category}: {count} items") def main(): scraper = KnowledgeBaseScraper() # Start aggressive scraping scraped_data = scraper.scrape_all_sources() # Save results scraper.save_results(scraped_data) print("\nāœ… KNOWLEDGE BASE ACQUISITION COMPLETE") print("=" * 60) print("Next: Process with quantum preprocessing pipeline") if __name__ == "__main__": main()