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")