Spaces:
Sleeping
Sleeping
File size: 8,408 Bytes
c3b894b 82f3341 | 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 | import os
import json
import pickle
import logging
from typing import Dict, Any, List, Optional, Tuple
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.feature_extraction import DictVectorizer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report, accuracy_score
import joblib
from config import config
from storage import db
logger = logging.getLogger(__name__)
MODEL_VERSION = "1.0.0"
FEATURE_COLUMNS = [
"tag_div", "tag_p", "tag_h1", "tag_h2", "tag_h3",
"tag_a", "tag_img", "tag_script", "tag_style",
"link_count", "text_length", "html_length",
"dom_depth_avg", "dom_depth_max", "readability_score",
"link_density", "form_count", "input_count"
]
CATEGORIES = [
"news", "blog", "product", "documentation", "forum",
"social", "landing", "ecommerce", "article", "other"
]
class ContentClassifier:
def __init__(self):
self.model: Optional[Pipeline] = None
self.vectorizer: Optional[DictVectorizer] = None
self.scaler: Optional[StandardScaler] = None
self._is_trained = False
def extract_features(self, html: str, title: str = None) -> Dict[str, float]:
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, "lxml") if html else BeautifulSoup("", "lxml")
for tag in soup(["script", "style", "meta", "link", "noscript"]):
tag.decompose()
text = soup.get_text(separator=" ", strip=True)
text_length = len(text)
html_length = len(html) if html else 0
tags = soup.find_all()
tag_counts = {}
for tag in tags:
tag_counts[tag.name] = tag_counts.get(tag.name, 0) + 1
links = soup.find_all("a", href=True)
link_count = len(links)
link_density = link_count / max(text_length / 100, 1) if text_length > 0 else 0
forms = soup.find_all("form")
form_count = len(forms)
inputs = soup.find_all("input")
input_count = len(inputs)
depths = []
def calc_depth(node, depth=0):
children = [c for c in node.children if hasattr(c, 'name') and c.name]
if not children:
depths.append(depth)
else:
for child in children:
calc_depth(child, depth + 1)
if soup.html:
calc_depth(soup.html)
dom_depth_avg = np.mean(depths) if depths else 0
dom_depth_max = max(depths) if depths else 0
sentences = text.count('.') + text.count('!') + text.count('?')
words = len(text.split())
readability = words / max(sentences, 1) if sentences > 0 else words
features = {
"tag_div": tag_counts.get("div", 0),
"tag_p": tag_counts.get("p", 0),
"tag_h1": tag_counts.get("h1", 0),
"tag_h2": tag_counts.get("h2", 0),
"tag_h3": tag_counts.get("h3", 0),
"tag_a": tag_counts.get("a", 0),
"tag_img": tag_counts.get("img", 0),
"tag_script": tag_counts.get("script", 0),
"tag_style": tag_counts.get("style", 0),
"link_count": link_count,
"text_length": text_length,
"html_length": html_length,
"dom_depth_avg": float(dom_depth_avg),
"dom_depth_max": dom_depth_max,
"readability_score": float(readability),
"link_density": float(link_density),
"form_count": form_count,
"input_count": input_count,
}
return features
def build_model(self) -> Pipeline:
return Pipeline([
("vectorizer", DictVectorizer(sparse=False)),
("scaler", StandardScaler()),
("classifier", RandomForestClassifier(
n_estimators=100,
max_depth=15,
min_samples_split=5,
min_samples_leaf=2,
random_state=42,
n_jobs=-1,
class_weight="balanced"
))
])
def train(self, X: List[Dict], y: List[str]) -> Dict[str, Any]:
if len(X) < 10:
logger.warning("Not enough training data, need at least 10 samples")
return {"error": "Insufficient training data"}
self.model = self.build_model()
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y
)
self.model.fit(X_train, y_train)
y_pred = self.model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
report = classification_report(y_test, y_pred, output_dict=True)
self._is_trained = True
self.save()
logger.info(f"Model trained with accuracy: {accuracy:.4f}")
return {
"accuracy": accuracy,
"report": report,
"samples": len(X),
"categories": list(set(y))
}
def predict(self, features: Dict[str, float]) -> Dict[str, Any]:
if not self._is_trained or self.model is None:
return self._default_prediction()
try:
X = [features]
category = self.model.predict(X)[0]
probabilities = self.model.predict_proba(X)[0]
classes = self.model.classes_
confidence = float(max(probabilities))
prob_dict = {cls: float(prob) for cls, prob in zip(classes, probabilities)}
is_spam = 1 if category in ["spam", "advertisement"] else 0
relevance = 1.0 - prob_dict.get("other", 0.0)
return {
"category": category,
"relevance_score": relevance,
"is_spam": is_spam,
"confidence": confidence,
"probabilities": prob_dict,
"model_version": MODEL_VERSION
}
except Exception as e:
logger.error(f"Prediction error: {e}")
return self._default_prediction()
def _default_prediction(self) -> Dict[str, Any]:
return {
"category": "other",
"relevance_score": 0.5,
"is_spam": 0,
"confidence": 0.0,
"probabilities": {},
"model_version": MODEL_VERSION
}
def save(self):
if self.model:
joblib.dump(self.model, config.model_path)
logger.info(f"Model saved to {config.model_path}")
def load(self) -> bool:
if os.path.exists(config.model_path):
try:
self.model = joblib.load(config.model_path)
self._is_trained = True
logger.info(f"Model loaded from {config.model_path}")
return True
except Exception as e:
logger.error(f"Failed to load model: {e}")
return False
def should_retrain(self) -> bool:
training_data = db.get_training_data()
return len(training_data) >= config.model_retrain_threshold
def retrain_from_db(self) -> Dict[str, Any]:
training_data = db.get_training_data()
if not training_data:
return {"error": "No training data available"}
X = []
y = []
for row in training_data:
features = {col: row.get(col, 0) for col in FEATURE_COLUMNS}
X.append(features)
y.append(row.get("category", "other"))
return self.train(X, y)
classifier = ContentClassifier()
def classify_content(html: str, title: str = None) -> Dict[str, Any]:
features = classifier.extract_features(html, title)
prediction = classifier.predict(features)
return {
"features": features,
"prediction": prediction
}
def initialize_model():
classifier.load()
if not classifier._is_trained:
X_dummy = [{col: 0.0 for col in FEATURE_COLUMNS} for _ in range(50)]
y_dummy = ["other"] * 20 + ["news"] * 10 + ["blog"] * 10 + ["product"] * 10
classifier.train(X_dummy, y_dummy)
logger.info("Default model created") |