Spaces:
Sleeping
Sleeping
Download storage.py from Ramasani/WebScrapper-AI: direct link, hf CLI and curl.
- Browser
- Download file 13.1 kB
-
https://huggingface.co/spaces/Ramasani/WebScrapper-AI/resolve/main/storage.py
- Command line
-
hf download hf://spaces/Ramasani/WebScrapper-AI/storage.py
-
curl -L -o storage.py https://huggingface.co/spaces/Ramasani/WebScrapper-AI/resolve/main/storage.py
13.1 kB
| import sqlite3 | |
| import threading | |
| from contextlib import contextmanager | |
| from pathlib import Path | |
| from typing import Optional, List, Dict, Any | |
| import json | |
| from datetime import datetime | |
| from config import config | |
| class Database: | |
| _instance = None | |
| _lock = threading.Lock() | |
| def __new__(cls): | |
| if cls._instance is None: | |
| with cls._lock: | |
| if cls._instance is None: | |
| cls._instance = super().__new__(cls) | |
| cls._instance._initialized = False | |
| return cls._instance | |
| def __init__(self): | |
| if self._initialized: | |
| return | |
| self.db_path = config.db_path | |
| self._init_db() | |
| self._migrate_db() | |
| self._initialized = True | |
| def _get_connection(self) -> sqlite3.Connection: | |
| conn = sqlite3.connect(self.db_path, check_same_thread=False) | |
| conn.row_factory = sqlite3.Row | |
| conn.execute("PRAGMA journal_mode=WAL") | |
| conn.execute("PRAGMA synchronous=NORMAL") | |
| conn.execute("PRAGMA cache_size=-32768") | |
| return conn | |
| def get_conn(self): | |
| conn = self._get_connection() | |
| try: | |
| yield conn | |
| conn.commit() | |
| except Exception: | |
| conn.rollback() | |
| raise | |
| finally: | |
| conn.close() | |
| def _init_db(self): | |
| Path(self.db_path).parent.mkdir(parents=True, exist_ok=True) | |
| with self.get_conn() as conn: | |
| conn.executescript(""" | |
| CREATE TABLE IF NOT EXISTS scraped_pages ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| url TEXT NOT NULL UNIQUE, | |
| html TEXT, | |
| status_code INTEGER, | |
| title TEXT, | |
| text_length INTEGER, | |
| content_hash TEXT, | |
| scraped_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, | |
| error TEXT, | |
| clean_text TEXT, | |
| markdown TEXT, | |
| metadata TEXT, | |
| links TEXT, | |
| images TEXT, | |
| headings TEXT | |
| ); | |
| CREATE INDEX IF NOT EXISTS idx_pages_url ON scraped_pages(url); | |
| CREATE INDEX IF NOT EXISTS idx_pages_scraped_at ON scraped_pages(scraped_at); | |
| CREATE TABLE IF NOT EXISTS page_features ( | |
| page_id INTEGER PRIMARY KEY, | |
| tag_div INTEGER DEFAULT 0, | |
| tag_p INTEGER DEFAULT 0, | |
| tag_h1 INTEGER DEFAULT 0, | |
| tag_h2 INTEGER DEFAULT 0, | |
| tag_h3 INTEGER DEFAULT 0, | |
| tag_a INTEGER DEFAULT 0, | |
| tag_img INTEGER DEFAULT 0, | |
| tag_script INTEGER DEFAULT 0, | |
| tag_style INTEGER DEFAULT 0, | |
| link_count INTEGER DEFAULT 0, | |
| text_length INTEGER DEFAULT 0, | |
| html_length INTEGER DEFAULT 0, | |
| dom_depth_avg REAL DEFAULT 0.0, | |
| dom_depth_max INTEGER DEFAULT 0, | |
| readability_score REAL DEFAULT 0.0, | |
| link_density REAL DEFAULT 0.0, | |
| form_count INTEGER DEFAULT 0, | |
| input_count INTEGER DEFAULT 0, | |
| FOREIGN KEY (page_id) REFERENCES scraped_pages(id) ON DELETE CASCADE | |
| ); | |
| CREATE TABLE IF NOT EXISTS ml_predictions ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| page_id INTEGER NOT NULL, | |
| category TEXT, | |
| relevance_score REAL, | |
| is_spam INTEGER DEFAULT 0, | |
| confidence REAL, | |
| model_version TEXT, | |
| predicted_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, | |
| FOREIGN KEY (page_id) REFERENCES scraped_pages(id) ON DELETE CASCADE | |
| ); | |
| CREATE INDEX IF NOT EXISTS idx_predictions_page ON ml_predictions(page_id); | |
| CREATE INDEX IF NOT EXISTS idx_predictions_category ON ml_predictions(category); | |
| CREATE TABLE IF NOT EXISTS scrape_jobs ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| job_id TEXT NOT NULL UNIQUE, | |
| urls TEXT NOT NULL, | |
| status TEXT DEFAULT 'pending', | |
| completed INTEGER DEFAULT 0, | |
| total INTEGER DEFAULT 0, | |
| created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, | |
| completed_at TIMESTAMP | |
| ); | |
| CREATE INDEX IF NOT EXISTS idx_jobs_status ON scrape_jobs(status); | |
| """) | |
| def _migrate_db(self): | |
| needed_columns = [ | |
| "clean_text TEXT", | |
| "markdown TEXT", | |
| "metadata TEXT", | |
| "links TEXT", | |
| "images TEXT", | |
| "headings TEXT", | |
| ] | |
| with self.get_conn() as conn: | |
| existing_columns = { | |
| row["name"] | |
| for row in conn.execute("PRAGMA table_info(scraped_pages)") | |
| } | |
| for column_def in needed_columns: | |
| column_name = column_def.split(" ")[0] | |
| if column_name not in existing_columns: | |
| conn.execute(f"ALTER TABLE scraped_pages ADD COLUMN {column_def}") | |
| def save_page(self, url: str, html: str, status_code: int, title: str = None, error: str = None, | |
| clean_text: str = None, markdown: str = None, metadata: Dict[str, Any] = None, | |
| links: List[str] = None, images: List[Dict[str, str]] = None, headings: List[Dict[str, Any]] = None) -> int: | |
| import hashlib | |
| content_hash = hashlib.sha256((html or "").encode()).hexdigest()[:16] if html else None | |
| text_length = len(clean_text) if clean_text else 0 | |
| with self.get_conn() as conn: | |
| conn.execute(""" | |
| INSERT OR REPLACE INTO scraped_pages (url, html, status_code, title, text_length, content_hash, error, | |
| clean_text, markdown, metadata, links, images, headings) | |
| VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) | |
| """, (url, html, status_code, title, text_length, content_hash, error, | |
| clean_text, markdown, | |
| json.dumps(metadata) if metadata else None, | |
| json.dumps(links) if links else None, | |
| json.dumps(images) if images else None, | |
| json.dumps(headings) if headings else None)) | |
| row = conn.execute("SELECT id FROM scraped_pages WHERE url = ?", (url,)).fetchone() | |
| return row["id"] if row else 0 | |
| def get_page(self, page_id: int) -> Optional[Dict[str, Any]]: | |
| with self.get_conn() as conn: | |
| row = conn.execute("SELECT * FROM scraped_pages WHERE id = ?", (page_id,)).fetchone() | |
| if not row: | |
| return None | |
| result = dict(row) | |
| for key in ["metadata", "links", "images", "headings"]: | |
| if result.get(key) and isinstance(result[key], str): | |
| result[key] = json.loads(result[key]) | |
| return result | |
| def get_page_by_url(self, url: str) -> Optional[Dict[str, Any]]: | |
| with self.get_conn() as conn: | |
| row = conn.execute("SELECT * FROM scraped_pages WHERE url = ?", (url,)).fetchone() | |
| if not row: | |
| return None | |
| result = dict(row) | |
| for key in ["metadata", "links", "images", "headings"]: | |
| if result.get(key) and isinstance(result[key], str): | |
| result[key] = json.loads(result[key]) | |
| return result | |
| def get_pages(self, limit: int = 100, offset: int = 0, status: str = None) -> List[Dict[str, Any]]: | |
| with self.get_conn() as conn: | |
| query = "SELECT * FROM scraped_pages" | |
| params = [] | |
| if status == "error": | |
| query += " WHERE error IS NOT NULL" | |
| elif status == "success": | |
| query += " WHERE error IS NULL" | |
| query += " ORDER BY scraped_at DESC LIMIT ? OFFSET ?" | |
| params.extend([limit, offset]) | |
| rows = conn.execute(query, params).fetchall() | |
| results = [] | |
| for row in rows: | |
| result = dict(row) | |
| for key in ["metadata", "links", "images", "headings"]: | |
| if result.get(key) and isinstance(result[key], str): | |
| result[key] = json.loads(result[key]) | |
| results.append(result) | |
| return results | |
| def save_features(self, page_id: int, features: Dict[str, Any]): | |
| with self.get_conn() as conn: | |
| cols = ", ".join(features.keys()) | |
| placeholders = ", ".join(["?" for _ in features]) | |
| updates = ", ".join([f"{k} = ?" for k in features.keys()]) | |
| values = list(features.values()) | |
| conn.execute(f""" | |
| INSERT INTO page_features (page_id, {cols}) | |
| VALUES (?, {placeholders}) | |
| ON CONFLICT(page_id) DO UPDATE SET {updates} | |
| """, [page_id] + values + values) | |
| def get_features(self, page_id: int) -> Optional[Dict[str, Any]]: | |
| with self.get_conn() as conn: | |
| row = conn.execute("SELECT * FROM page_features WHERE page_id = ?", (page_id,)).fetchone() | |
| return dict(row) if row else None | |
| def save_prediction(self, page_id: int, category: str, relevance_score: float, | |
| is_spam: int, confidence: float, model_version: str): | |
| with self.get_conn() as conn: | |
| conn.execute(""" | |
| INSERT INTO ml_predictions (page_id, category, relevance_score, is_spam, confidence, model_version) | |
| VALUES (?, ?, ?, ?, ?, ?) | |
| """, (page_id, category, relevance_score, is_spam, confidence, model_version)) | |
| def get_prediction(self, page_id: int) -> Optional[Dict[str, Any]]: | |
| with self.get_conn() as conn: | |
| row = conn.execute( | |
| "SELECT * FROM ml_predictions WHERE page_id = ? ORDER BY predicted_at DESC LIMIT 1", | |
| (page_id,) | |
| ).fetchone() | |
| return dict(row) if row else None | |
| def get_training_data(self) -> List[Dict[str, Any]]: | |
| with self.get_conn() as conn: | |
| query = """ | |
| SELECT pf.*, p.category, p.relevance_score, p.is_spam | |
| FROM page_features pf | |
| JOIN ml_predictions p ON pf.page_id = p.page_id | |
| WHERE p.predicted_at = ( | |
| SELECT MAX(predicted_at) FROM ml_predictions WHERE page_id = pf.page_id | |
| ) | |
| """ | |
| rows = conn.execute(query).fetchall() | |
| return [dict(row) for row in rows] | |
| def create_job(self, job_id: str, urls: List[str]) -> int: | |
| urls_json = json.dumps(urls) | |
| with self.get_conn() as conn: | |
| cursor = conn.execute( | |
| "INSERT INTO scrape_jobs (job_id, urls, total) VALUES (?, ?, ?)", | |
| (job_id, urls_json, len(urls)) | |
| ) | |
| return cursor.lastrowid | |
| def update_job_progress(self, job_id: str, completed: int, status: str = None): | |
| with self.get_conn() as conn: | |
| if status == "completed": | |
| conn.execute( | |
| "UPDATE scrape_jobs SET completed = ?, status = ?, completed_at = CURRENT_TIMESTAMP WHERE job_id = ?", | |
| (completed, status, job_id) | |
| ) | |
| else: | |
| conn.execute( | |
| "UPDATE scrape_jobs SET completed = ?, status = ? WHERE job_id = ?", | |
| (completed, status or "running", job_id) | |
| ) | |
| def get_job(self, job_id: str) -> Optional[Dict[str, Any]]: | |
| with self.get_conn() as conn: | |
| row = conn.execute("SELECT * FROM scrape_jobs WHERE job_id = ?", (job_id,)).fetchone() | |
| if row: | |
| result = dict(row) | |
| result["urls"] = json.loads(result["urls"]) | |
| return result | |
| return None | |
| def get_stats(self) -> Dict[str, Any]: | |
| with self.get_conn() as conn: | |
| total = conn.execute("SELECT COUNT(*) FROM scraped_pages").fetchone()[0] | |
| errors = conn.execute("SELECT COUNT(*) FROM scraped_pages WHERE error IS NOT NULL").fetchone()[0] | |
| predictions = conn.execute("SELECT COUNT(*) FROM ml_predictions").fetchone()[0] | |
| db_size = Path(self.db_path).stat().st_size if Path(self.db_path).exists() else 0 | |
| return { | |
| "total_pages": total, | |
| "error_pages": errors, | |
| "success_pages": total - errors, | |
| "total_predictions": predictions, | |
| "database_size_bytes": db_size, | |
| "database_size_mb": round(db_size / (1024 * 1024), 2) | |
| } | |
| def vacuum(self): | |
| with self.get_conn() as conn: | |
| conn.execute("VACUUM") | |
| db = Database() |