Spaces:
Sleeping
Sleeping
File size: 13,126 Bytes
c3b894b a6de989 c3b894b a6de989 c3b894b a6de989 4c4ff07 c3b894b a6de989 4c4ff07 c3b894b c4098fc a6de989 c4098fc c3b894b a6de989 c3b894b a6de989 c3b894b a6de989 c3b894b 4c4ff07 c3b894b 4c4ff07 c3b894b | 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 | 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
@contextmanager
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() |