File size: 13,273 Bytes
42bba47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/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()