Spaces:
Runtime error
Runtime error
Add application file
Browse files- README.md +105 -11
- dockerfile +15 -0
- models/roberta_metadata_classifier.py +28 -0
- requirements.txt +13 -0
- src/__pycache__/dataset.cpython-312.pyc +0 -0
- src/__pycache__/evaluate.cpython-312.pyc +0 -0
- src/__pycache__/manipulation_detect.cpython-312.pyc +0 -0
- src/__pycache__/model.cpython-312.pyc +0 -0
- src/__pycache__/train_model.cpython-312.pyc +0 -0
- src/anomaly.py +9 -0
- src/app.py +68 -0
- src/data_preprocessing.py +50 -0
- src/dataset.py +37 -0
- src/evaluate.py +54 -0
- src/main.py +30 -0
- src/manipulation_detect.py +40 -0
- src/model.py +16 -0
- src/train_model.py +96 -0
- src/utils.py +19 -0
README.md
CHANGED
|
@@ -1,14 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
|
|
|
| 12 |
---
|
| 13 |
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# π§ Community Rating System for Social Posts
|
| 2 |
+
|
| 3 |
+
A machine learning-powered system that evaluates **community comments or notes** on public posts for **credibility, helpfulness, and factual consistency**, while actively resisting manipulation like spam voting or coordinated misinformation.
|
| 4 |
+
|
| 5 |
---
|
| 6 |
+
|
| 7 |
+
## π Project Overview
|
| 8 |
+
|
| 9 |
+
This project builds a full-stack pipeline that:
|
| 10 |
+
|
| 11 |
+
- Processes public comments (e.g., Reddit, StackOverflow)
|
| 12 |
+
- Extracts features like sentiment, toxicity, readability, and named entities
|
| 13 |
+
- Scores notes/comments for **credibility** and **helpfulness**
|
| 14 |
+
- Detects manipulation attempts (e.g., bot voting, duplicate spam)
|
| 15 |
+
- Provides a web interface to interactively test the system
|
| 16 |
+
|
| 17 |
---
|
| 18 |
|
| 19 |
+
## π Features
|
| 20 |
+
|
| 21 |
+
- β
Transformer-based helpfulness scoring (e.g., RoBERTa)
|
| 22 |
+
- β
Anomaly detection using Isolation Forest
|
| 23 |
+
- β
Sentiment and toxicity classification
|
| 24 |
+
- β
Interactive UI with Gradio or Streamlit
|
| 25 |
+
- β
REST API using FastAPI
|
| 26 |
+
- β
Dockerized and deployable on Hugging Face Spaces or Render
|
| 27 |
+
|
| 28 |
+
---
|
| 29 |
+
|
| 30 |
+
## ποΈ Project Structure
|
| 31 |
+
|
| 32 |
+
```plaintext
|
| 33 |
+
.
|
| 34 |
+
βββ data/
|
| 35 |
+
β βββ sample_comments.csv # Input dataset
|
| 36 |
+
βββ models/ # Saved model checkpoints
|
| 37 |
+
βββ src/
|
| 38 |
+
β βββ app.py # Web interface
|
| 39 |
+
β βββ anomaly.py # Anomaly detection logic
|
| 40 |
+
β βββ data_preprocessing.py # Cleaning, tokenization, features
|
| 41 |
+
β βββ dataset.py # PyTorch dataset logic
|
| 42 |
+
β βββ evaluate.py # Evaluation metrics
|
| 43 |
+
β βββ main.py # Entry script
|
| 44 |
+
β βββ manipulation_detect.py # Bot/spam detection
|
| 45 |
+
β βββ model.py # Helpfulness scoring model
|
| 46 |
+
β βββ train_model.py # Training loop
|
| 47 |
+
β βββ utils.py # Helper functions
|
| 48 |
+
βββ requirements.txt # Dependencies
|
| 49 |
+
βββ dockerfile # Container setup
|
| 50 |
+
βββ README.md
|
| 51 |
+
|
| 52 |
+
## π¦ Setup Instructions
|
| 53 |
+
π§ 1. Install Dependencies
|
| 54 |
+
- git clone https://github.com/yourusername/community-rating-system.git
|
| 55 |
+
- cd community-rating-system
|
| 56 |
+
- python -m venv env
|
| 57 |
+
- source env/bin/activate # or .\env\Scripts\activate on Windows
|
| 58 |
+
- pip install -r requirements.txt
|
| 59 |
+
|
| 60 |
+
## π§ͺ 2. Train the Helpfulness Model
|
| 61 |
+
- python src/train_model.py
|
| 62 |
+
|
| 63 |
+
## 𧬠3. Run Anomaly Detection
|
| 64 |
+
- python src/manipulation_detect.py
|
| 65 |
+
|
| 66 |
+
## π 4. Launch Web Interface
|
| 67 |
+
- python src/app.py
|
| 68 |
+
or
|
| 69 |
+
- uvicorn src.main:app --reload
|
| 70 |
+
|
| 71 |
+
## π Manipulation Resistance
|
| 72 |
+
- This project uses:
|
| 73 |
+
- Isolation Forest to detect abnormal user behavior (e.g., sudden karma spikes)
|
| 74 |
+
- Text similarity analysis to flag near-duplicate spam
|
| 75 |
+
- (Optional) Adversarial training to improve robustness against vote brigading
|
| 76 |
+
|
| 77 |
+
## π§ ML Model Architecture
|
| 78 |
+
- Backbone: RoBERTa-base or BERT-base
|
| 79 |
+
- Input: comment_text, along with metadata like upvotes, length, time, etc.
|
| 80 |
+
- Output: A scalar score (0.0β1.0) representing helpfulness or credibility
|
| 81 |
+
|
| 82 |
+
Additional Features:
|
| 83 |
+
β
Sentiment polarity
|
| 84 |
+
|
| 85 |
+
β
Toxicity score (via Detoxify)
|
| 86 |
+
|
| 87 |
+
β
Readability score (FleschβKincaid, Gunning Fog Index)
|
| 88 |
+
|
| 89 |
+
β
Named Entity Types (political, scientific, health-related)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
## π§ͺ Evaluation
|
| 93 |
+
Key metrics used for evaluating the scoring model and resistance components:
|
| 94 |
+
|
| 95 |
+
π ROC-AUC
|
| 96 |
+
|
| 97 |
+
π― Precision@K
|
| 98 |
+
|
| 99 |
+
π§© Agreement with majority vote labels
|
| 100 |
+
|
| 101 |
+
π Confusion Matrix on manipulated vs. organic comment behavior
|
| 102 |
+
|
| 103 |
+
## π¦ Docker Deployment
|
| 104 |
+
- To build and run the container locally:
|
| 105 |
+
- docker build -t community-rating-system .
|
| 106 |
+
- docker run -p 7860:7860 community-rating-system
|
| 107 |
+
|
| 108 |
+
|
dockerfile
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.10-slim
|
| 2 |
+
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
|
| 5 |
+
COPY requirements.txt .
|
| 6 |
+
|
| 7 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 8 |
+
|
| 9 |
+
COPY ./src ./src
|
| 10 |
+
COPY ./data ./data
|
| 11 |
+
COPY ./models ./models
|
| 12 |
+
|
| 13 |
+
EXPOSE 7860
|
| 14 |
+
|
| 15 |
+
CMD ["python", "src/app.py"]
|
models/roberta_metadata_classifier.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
from transformers import RobertaModel
|
| 4 |
+
|
| 5 |
+
class RobertaWithMetadata(nn.Module):
|
| 6 |
+
def __init__(self, model_name='roberta-base', metadata_dim=3, dropout=0.3):
|
| 7 |
+
super(RobertaWithMetadata, self).__init__()
|
| 8 |
+
self.roberta = RobertaModel.from_pretrained(model_name)
|
| 9 |
+
self.dropout = nn.Dropout(dropout)
|
| 10 |
+
|
| 11 |
+
hidden_size = self.roberta.config.hidden_size # usually 768
|
| 12 |
+
self.metadata_dim = metadata_dim
|
| 13 |
+
|
| 14 |
+
# Final classifier takes RoBERTa CLS output + metadata
|
| 15 |
+
self.classifier = nn.Sequential(
|
| 16 |
+
nn.Linear(hidden_size + metadata_dim, 256),
|
| 17 |
+
nn.ReLU(),
|
| 18 |
+
nn.Dropout(dropout),
|
| 19 |
+
nn.Linear(256, 1) # single score output (e.g., helpfulness)
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
def forward(self, input_ids, attention_mask, metadata):
|
| 23 |
+
roberta_out = self.roberta(input_ids=input_ids, attention_mask=attention_mask)
|
| 24 |
+
cls_output = roberta_out.pooler_output # [CLS] token representation
|
| 25 |
+
|
| 26 |
+
combined = torch.cat((cls_output, metadata), dim=1)
|
| 27 |
+
out = self.classifier(self.dropout(combined))
|
| 28 |
+
return out.squeeze(1) # final regression output
|
requirements.txt
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch
|
| 2 |
+
transformers
|
| 3 |
+
datasets
|
| 4 |
+
scikit-learn
|
| 5 |
+
pyod
|
| 6 |
+
gradio
|
| 7 |
+
pandas
|
| 8 |
+
numpy
|
| 9 |
+
detoxify
|
| 10 |
+
textstat
|
| 11 |
+
fastapi
|
| 12 |
+
uvicorn
|
| 13 |
+
joblib
|
src/__pycache__/dataset.cpython-312.pyc
ADDED
|
Binary file (2.05 kB). View file
|
|
|
src/__pycache__/evaluate.cpython-312.pyc
ADDED
|
Binary file (3.39 kB). View file
|
|
|
src/__pycache__/manipulation_detect.cpython-312.pyc
ADDED
|
Binary file (2.39 kB). View file
|
|
|
src/__pycache__/model.cpython-312.pyc
ADDED
|
Binary file (1.66 kB). View file
|
|
|
src/__pycache__/train_model.cpython-312.pyc
ADDED
|
Binary file (5.82 kB). View file
|
|
|
src/anomaly.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import joblib
|
| 2 |
+
import numpy as np
|
| 3 |
+
|
| 4 |
+
def load_anomaly_model(path='models/anomaly_detector.pkl'):
|
| 5 |
+
return joblib.load(path)
|
| 6 |
+
|
| 7 |
+
def is_anomalous(features, model):
|
| 8 |
+
score = model.decision_function([features])[0]
|
| 9 |
+
return model.predict([features])[0] == -1, score
|
src/app.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
+
from transformers import RobertaTokenizer
|
| 4 |
+
from src.model import CommentClassifier
|
| 5 |
+
from src.utils import preprocess_comment, extract_metadata_features
|
| 6 |
+
from src.anomaly import load_anomaly_model
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
# Load tokenizer and model
|
| 10 |
+
tokenizer = RobertaTokenizer.from_pretrained("roberta-base")
|
| 11 |
+
model = CommentClassifier()
|
| 12 |
+
model.load_state_dict(torch.load("models/best_model.pt", map_location=torch.device("cpu")))
|
| 13 |
+
model.eval()
|
| 14 |
+
|
| 15 |
+
# Load Isolation Forest model
|
| 16 |
+
anomaly_model = load_anomaly_model()
|
| 17 |
+
|
| 18 |
+
def predict_comment(text):
|
| 19 |
+
if not text.strip():
|
| 20 |
+
return "Enter a valid comment!", 0, 0, 0, 0
|
| 21 |
+
|
| 22 |
+
# Preprocess
|
| 23 |
+
input_text = preprocess_comment(text)
|
| 24 |
+
meta_features = extract_metadata_features(text)
|
| 25 |
+
meta_tensor = torch.tensor(meta_features, dtype=torch.float).unsqueeze(0)
|
| 26 |
+
|
| 27 |
+
# Tokenize
|
| 28 |
+
inputs = tokenizer(
|
| 29 |
+
input_text, padding="max_length", truncation=True, max_length=128, return_tensors="pt"
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
with torch.no_grad():
|
| 33 |
+
outputs = model(
|
| 34 |
+
input_ids=inputs["input_ids"],
|
| 35 |
+
attention_mask=inputs["attention_mask"],
|
| 36 |
+
meta_features=meta_tensor
|
| 37 |
+
)
|
| 38 |
+
probs = torch.softmax(outputs, dim=1).squeeze().numpy()
|
| 39 |
+
|
| 40 |
+
labels = ["Negative", "Neutral", "Positive"]
|
| 41 |
+
prediction = labels[probs.argmax()]
|
| 42 |
+
sentiment_score = round(probs[2], 2)
|
| 43 |
+
|
| 44 |
+
# Fake/toxic/helpfulness scores (simple heuristics)
|
| 45 |
+
toxicity = float(meta_features[0]) # e.g., from Detoxify or rule-based
|
| 46 |
+
helpfulness = float(meta_features[2])
|
| 47 |
+
anomaly_score = anomaly_model.decision_function([meta_features])[0]
|
| 48 |
+
|
| 49 |
+
return prediction, sentiment_score, round(toxicity, 2), round(helpfulness, 2), round(anomaly_score, 2)
|
| 50 |
+
|
| 51 |
+
# Gradio UI
|
| 52 |
+
iface = gr.Interface(
|
| 53 |
+
fn=predict_comment,
|
| 54 |
+
inputs=gr.Textbox(lines=4, label="Enter a Comment"),
|
| 55 |
+
outputs=[
|
| 56 |
+
gr.Textbox(label="Predicted Sentiment"),
|
| 57 |
+
gr.Number(label="Sentiment Score (0-1)"),
|
| 58 |
+
gr.Number(label="Toxicity Score"),
|
| 59 |
+
gr.Number(label="Helpfulness Score"),
|
| 60 |
+
gr.Number(label="Anomaly Score")
|
| 61 |
+
],
|
| 62 |
+
title="π§ Comment Quality Analyzer",
|
| 63 |
+
description="Paste any social media comment and get its sentiment, toxicity, helpfulness, and anomaly scores using a RoBERTa-based ML model.",
|
| 64 |
+
allow_flagging="never",
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
if __name__ == "__main__":
|
| 68 |
+
iface.launch()
|
src/data_preprocessing.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import numpy as np
|
| 3 |
+
import re
|
| 4 |
+
from sklearn.ensemble import IsolationForest
|
| 5 |
+
from detoxify import Detoxify
|
| 6 |
+
import textstat
|
| 7 |
+
|
| 8 |
+
# Clean text
|
| 9 |
+
def clean_text(text):
|
| 10 |
+
text = str(text).lower()
|
| 11 |
+
text = re.sub(r"http\S+|www\S+|https\S+", '', text)
|
| 12 |
+
text = re.sub(r'\@\w+|\#','', text)
|
| 13 |
+
text = re.sub(r'[^\w\s]', '', text)
|
| 14 |
+
return text
|
| 15 |
+
|
| 16 |
+
# Load and preprocess
|
| 17 |
+
def load_data(filepath):
|
| 18 |
+
df = pd.read_csv(filepath)
|
| 19 |
+
df.dropna(subset=["text", "helpfulness_score"], inplace=True)
|
| 20 |
+
return df
|
| 21 |
+
|
| 22 |
+
def preprocess_text(df):
|
| 23 |
+
df['text'] = df['text'].apply(clean_text)
|
| 24 |
+
|
| 25 |
+
# Toxicity score
|
| 26 |
+
print("Computing toxicity scores...")
|
| 27 |
+
toxicity_results = Detoxify('original').predict(df['text'].tolist())
|
| 28 |
+
df['toxicity_score'] = toxicity_results['toxicity']
|
| 29 |
+
|
| 30 |
+
# Readability score (lower is harder to read)
|
| 31 |
+
print("Computing readability scores...")
|
| 32 |
+
df['readability_score'] = df['text'].apply(lambda x: textstat.flesch_reading_ease(x))
|
| 33 |
+
|
| 34 |
+
# Anomaly Detection
|
| 35 |
+
print("Running anomaly detection...")
|
| 36 |
+
meta_features = df[["toxicity_score", "readability_score"]].fillna(0)
|
| 37 |
+
clf = IsolationForest(contamination=0.05, random_state=42)
|
| 38 |
+
df['is_anomalous'] = clf.fit_predict(meta_features)
|
| 39 |
+
df['is_anomalous'] = df['is_anomalous'].apply(lambda x: 1 if x == -1 else 0)
|
| 40 |
+
|
| 41 |
+
return df
|
| 42 |
+
|
| 43 |
+
# For custom evaluation later
|
| 44 |
+
def compute_custom_metrics(y_true, y_pred):
|
| 45 |
+
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
|
| 46 |
+
return {
|
| 47 |
+
"MAE": mean_absolute_error(y_true, y_pred),
|
| 48 |
+
"MSE": mean_squared_error(y_true, y_pred),
|
| 49 |
+
"R2": r2_score(y_true, y_pred)
|
| 50 |
+
}
|
src/dataset.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# dataset.py
|
| 2 |
+
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import torch
|
| 5 |
+
from torch.utils.data import Dataset
|
| 6 |
+
from transformers import RobertaTokenizer
|
| 7 |
+
|
| 8 |
+
class CommentDataset(Dataset):
|
| 9 |
+
def __init__(self, data, tokenizer, max_len=128):
|
| 10 |
+
self.data = data
|
| 11 |
+
self.tokenizer = tokenizer
|
| 12 |
+
self.max_len = max_len
|
| 13 |
+
|
| 14 |
+
def __len__(self):
|
| 15 |
+
return len(self.data)
|
| 16 |
+
|
| 17 |
+
def __getitem__(self, idx):
|
| 18 |
+
comment = self.data.iloc[idx]['comment']
|
| 19 |
+
label = self.data.iloc[idx]['label']
|
| 20 |
+
encoding = self.tokenizer(
|
| 21 |
+
comment,
|
| 22 |
+
padding='max_length',
|
| 23 |
+
truncation=True,
|
| 24 |
+
max_length=self.max_len,
|
| 25 |
+
return_tensors='pt'
|
| 26 |
+
)
|
| 27 |
+
return {
|
| 28 |
+
'input_ids': encoding['input_ids'].squeeze(),
|
| 29 |
+
'attention_mask': encoding['attention_mask'].squeeze(),
|
| 30 |
+
'label': torch.tensor(label, dtype=torch.long)
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
def load_data(path):
|
| 34 |
+
df = pd.read_csv(path)
|
| 35 |
+
tokenizer = RobertaTokenizer.from_pretrained('roberta-base')
|
| 36 |
+
dataset = CommentDataset(df, tokenizer)
|
| 37 |
+
return dataset
|
src/evaluate.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
from sklearn.metrics import roc_auc_score, precision_score
|
| 3 |
+
import torch
|
| 4 |
+
from train_model import HelpfulnessModel, tokenizer
|
| 5 |
+
import numpy as np
|
| 6 |
+
from torch.utils.data import DataLoader
|
| 7 |
+
|
| 8 |
+
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
| 9 |
+
MODEL_PATH = "../models/helpfulness_model.pt"
|
| 10 |
+
|
| 11 |
+
def evaluate():
|
| 12 |
+
df = pd.read_csv("../data/sample_comments.csv")
|
| 13 |
+
|
| 14 |
+
df['helpfulness'] = (df['score'] - df['score'].min()) / (df['score'].max() - df['score'].min() + 1e-8)
|
| 15 |
+
|
| 16 |
+
meta_cols = ['token_len', 'toxicity', 'readability', 'political_mentions',
|
| 17 |
+
'health_mentions', 'science_mentions', 'engagement', 'time_since_posted']
|
| 18 |
+
X_meta = df[meta_cols].fillna(0).values
|
| 19 |
+
|
| 20 |
+
texts = df['clean_text'].tolist()
|
| 21 |
+
targets = df['helpfulness'].values
|
| 22 |
+
|
| 23 |
+
dataset = CommentDataset(texts, X_meta, targets)
|
| 24 |
+
dataloader = DataLoader(dataset, batch_size=16)
|
| 25 |
+
|
| 26 |
+
model = HelpfulnessModel("roberta-base", X_meta.shape[1])
|
| 27 |
+
model.load_state_dict(torch.load(MODEL_PATH, map_location=DEVICE))
|
| 28 |
+
model.to(DEVICE)
|
| 29 |
+
model.eval()
|
| 30 |
+
|
| 31 |
+
preds = []
|
| 32 |
+
actuals = []
|
| 33 |
+
|
| 34 |
+
with torch.no_grad():
|
| 35 |
+
for input_ids, attention_mask, meta_features, targets in dataloader:
|
| 36 |
+
input_ids = input_ids.to(DEVICE)
|
| 37 |
+
attention_mask = attention_mask.to(DEVICE)
|
| 38 |
+
meta_features = meta_features.to(DEVICE)
|
| 39 |
+
|
| 40 |
+
outputs = model(input_ids, attention_mask, meta_features)
|
| 41 |
+
preds.extend(outputs.cpu().numpy())
|
| 42 |
+
actuals.extend(targets.numpy())
|
| 43 |
+
|
| 44 |
+
auc = roc_auc_score(actuals, preds)
|
| 45 |
+
k = 100
|
| 46 |
+
df_eval = pd.DataFrame({'pred': preds, 'actual': actuals})
|
| 47 |
+
df_eval_sorted = df_eval.sort_values('pred', ascending=False).head(k)
|
| 48 |
+
precision_at_k = (df_eval_sorted['actual'] > 0.5).mean()
|
| 49 |
+
|
| 50 |
+
print(f"AUC: {auc:.4f}")
|
| 51 |
+
print(f"Precision@{k}: {precision_at_k:.4f}")
|
| 52 |
+
|
| 53 |
+
if __name__ == "__main__":
|
| 54 |
+
evaluate()
|
src/main.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import os
|
| 3 |
+
|
| 4 |
+
from train_model import train
|
| 5 |
+
from evaluate import evaluate
|
| 6 |
+
import app
|
| 7 |
+
|
| 8 |
+
def main():
|
| 9 |
+
parser = argparse.ArgumentParser(description="Community Comment Rating System")
|
| 10 |
+
|
| 11 |
+
parser.add_argument("--mode", type=str, required=True,
|
| 12 |
+
choices=["train", "evaluate", "app"],
|
| 13 |
+
help="Mode to run: train / evaluate / app")
|
| 14 |
+
|
| 15 |
+
args = parser.parse_args()
|
| 16 |
+
|
| 17 |
+
if args.mode == "train":
|
| 18 |
+
print("π Starting Training...")
|
| 19 |
+
train()
|
| 20 |
+
|
| 21 |
+
elif args.mode == "evaluate":
|
| 22 |
+
print("π Starting Evaluation...")
|
| 23 |
+
evaluate()
|
| 24 |
+
|
| 25 |
+
elif args.mode == "app":
|
| 26 |
+
print("π Launching Gradio App...")
|
| 27 |
+
app.iface.launch()
|
| 28 |
+
|
| 29 |
+
if __name__ == "__main__":
|
| 30 |
+
main()
|
src/manipulation_detect.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from torch.utils.data import Dataset
|
| 3 |
+
from transformers import RobertaTokenizer
|
| 4 |
+
|
| 5 |
+
class CommentDataset(Dataset):
|
| 6 |
+
def __init__(self, dataframe, max_len=128):
|
| 7 |
+
self.texts = dataframe["text"].tolist()
|
| 8 |
+
self.labels = dataframe["helpfulness_score"].tolist()
|
| 9 |
+
self.toxicity = dataframe["toxicity_score"].tolist()
|
| 10 |
+
self.readability = dataframe["readability_score"].tolist()
|
| 11 |
+
self.anomaly = dataframe["is_anomalous"].tolist()
|
| 12 |
+
|
| 13 |
+
self.tokenizer = RobertaTokenizer.from_pretrained("roberta-base")
|
| 14 |
+
self.max_len = max_len
|
| 15 |
+
|
| 16 |
+
def __len__(self):
|
| 17 |
+
return len(self.texts)
|
| 18 |
+
|
| 19 |
+
def __getitem__(self, idx):
|
| 20 |
+
encoded = self.tokenizer(
|
| 21 |
+
self.texts[idx],
|
| 22 |
+
padding='max_length',
|
| 23 |
+
truncation=True,
|
| 24 |
+
max_length=self.max_len,
|
| 25 |
+
return_tensors="pt"
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
# Metadata features: concatenate scalar values
|
| 29 |
+
metadata = torch.tensor([
|
| 30 |
+
self.toxicity[idx],
|
| 31 |
+
self.readability[idx],
|
| 32 |
+
self.anomaly[idx]
|
| 33 |
+
], dtype=torch.float)
|
| 34 |
+
|
| 35 |
+
return {
|
| 36 |
+
"input_ids": encoded["input_ids"].squeeze(0),
|
| 37 |
+
"attention_mask": encoded["attention_mask"].squeeze(0),
|
| 38 |
+
"metadata": metadata,
|
| 39 |
+
"label": torch.tensor(self.labels[idx], dtype=torch.float)
|
| 40 |
+
}
|
src/model.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch.nn as nn
|
| 2 |
+
from transformers import RobertaModel
|
| 3 |
+
|
| 4 |
+
class CommentClassifier(nn.Module):
|
| 5 |
+
def __init__(self, dropout=0.3):
|
| 6 |
+
super(CommentClassifier, self).__init__()
|
| 7 |
+
self.roberta = RobertaModel.from_pretrained("roberta-base")
|
| 8 |
+
self.dropout = nn.Dropout(dropout)
|
| 9 |
+
self.classifier = nn.Linear(self.roberta.config.hidden_size + 3, 1) # +3 for metadata features
|
| 10 |
+
|
| 11 |
+
def forward(self, input_ids, attention_mask, metadata_features):
|
| 12 |
+
outputs = self.roberta(input_ids=input_ids, attention_mask=attention_mask)
|
| 13 |
+
pooled_output = outputs.pooler_output
|
| 14 |
+
combined = torch.cat((pooled_output, metadata_features), dim=1)
|
| 15 |
+
x = self.dropout(combined)
|
| 16 |
+
return self.classifier(x)
|
src/train_model.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from torch import nn
|
| 3 |
+
from torch.utils.data import DataLoader
|
| 4 |
+
from transformers import RobertaModel, get_scheduler
|
| 5 |
+
from torch.optim import AdamW
|
| 6 |
+
from tqdm import tqdm
|
| 7 |
+
import os
|
| 8 |
+
|
| 9 |
+
from dataset import CommentDataset, load_data
|
| 10 |
+
from model import CommentRatingModel
|
| 11 |
+
|
| 12 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 13 |
+
|
| 14 |
+
class RoBERTaWithMetadata(nn.Module):
|
| 15 |
+
def __init__(self, dropout=0.3):
|
| 16 |
+
super().__init__()
|
| 17 |
+
self.roberta = RobertaModel.from_pretrained("roberta-base")
|
| 18 |
+
self.dropout = nn.Dropout(dropout)
|
| 19 |
+
self.metadata_fc = nn.Linear(3, 64)
|
| 20 |
+
self.classifier = nn.Sequential(
|
| 21 |
+
nn.Linear(self.roberta.config.hidden_size + 64, 128),
|
| 22 |
+
nn.ReLU(),
|
| 23 |
+
nn.Dropout(0.2),
|
| 24 |
+
nn.Linear(128, 1) # Regression output
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
def forward(self, input_ids, attention_mask, metadata):
|
| 28 |
+
roberta_out = self.roberta(input_ids=input_ids, attention_mask=attention_mask).pooler_output
|
| 29 |
+
meta_out = torch.relu(self.metadata_fc(metadata))
|
| 30 |
+
combined = torch.cat([roberta_out, meta_out], dim=1)
|
| 31 |
+
return self.classifier(combined)
|
| 32 |
+
|
| 33 |
+
def train(model, train_loader, val_loader, epochs=5, lr=2e-5, checkpoint_path="models/best_model.pt"):
|
| 34 |
+
criterion = nn.MSELoss()
|
| 35 |
+
optimizer = AdamW(model.parameters(), lr=lr)
|
| 36 |
+
num_training_steps = epochs * len(train_loader)
|
| 37 |
+
scheduler = get_scheduler("linear", optimizer=optimizer, num_warmup_steps=0, num_training_steps=num_training_steps)
|
| 38 |
+
|
| 39 |
+
best_loss = float("inf")
|
| 40 |
+
|
| 41 |
+
for epoch in range(epochs):
|
| 42 |
+
model.train()
|
| 43 |
+
total_loss = 0
|
| 44 |
+
for batch in train_loader:
|
| 45 |
+
optimizer.zero_grad()
|
| 46 |
+
input_ids = batch["input_ids"].to(device)
|
| 47 |
+
attention_mask = batch["attention_mask"].to(device)
|
| 48 |
+
metadata = batch["metadata"].to(device)
|
| 49 |
+
labels = batch["label"].to(device).unsqueeze(1)
|
| 50 |
+
|
| 51 |
+
outputs = model(input_ids, attention_mask, metadata)
|
| 52 |
+
loss = criterion(outputs, labels)
|
| 53 |
+
loss.backward()
|
| 54 |
+
optimizer.step()
|
| 55 |
+
scheduler.step()
|
| 56 |
+
|
| 57 |
+
total_loss += loss.item()
|
| 58 |
+
|
| 59 |
+
avg_train_loss = total_loss / len(train_loader)
|
| 60 |
+
|
| 61 |
+
# Validation
|
| 62 |
+
model.eval()
|
| 63 |
+
val_loss = 0
|
| 64 |
+
with torch.no_grad():
|
| 65 |
+
for batch in val_loader:
|
| 66 |
+
input_ids = batch["input_ids"].to(device)
|
| 67 |
+
attention_mask = batch["attention_mask"].to(device)
|
| 68 |
+
metadata = batch["metadata"].to(device)
|
| 69 |
+
labels = batch["label"].to(device).unsqueeze(1)
|
| 70 |
+
|
| 71 |
+
outputs = model(input_ids, attention_mask, metadata)
|
| 72 |
+
loss = criterion(outputs, labels)
|
| 73 |
+
val_loss += loss.item()
|
| 74 |
+
avg_val_loss = val_loss / len(val_loader)
|
| 75 |
+
|
| 76 |
+
print(f"Epoch {epoch+1}: Train Loss = {avg_train_loss:.4f} | Val Loss = {avg_val_loss:.4f}")
|
| 77 |
+
|
| 78 |
+
if avg_val_loss < best_loss:
|
| 79 |
+
best_loss = avg_val_loss
|
| 80 |
+
torch.save(model.state_dict(), checkpoint_path)
|
| 81 |
+
print("β
Saved best model")
|
| 82 |
+
|
| 83 |
+
if __name__ == "__main__":
|
| 84 |
+
df = pd.read_csv("data/final_dataset.csv")
|
| 85 |
+
train_df = df.sample(frac=0.8, random_state=42)
|
| 86 |
+
val_df = df.drop(train_df.index)
|
| 87 |
+
|
| 88 |
+
train_dataset = CommentDataset(train_df)
|
| 89 |
+
val_dataset = CommentDataset(val_df)
|
| 90 |
+
|
| 91 |
+
train_loader = DataLoader(train_dataset, batch_size=16, shuffle=True)
|
| 92 |
+
val_loader = DataLoader(val_dataset, batch_size=16)
|
| 93 |
+
|
| 94 |
+
model = RoBERTaWithMetadata().to(device)
|
| 95 |
+
os.makedirs("models", exist_ok=True)
|
| 96 |
+
train(model, train_loader, val_loader)
|
src/utils.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import re
|
| 3 |
+
import string
|
| 4 |
+
from detoxify import Detoxify
|
| 5 |
+
|
| 6 |
+
detox_model = Detoxify('original')
|
| 7 |
+
|
| 8 |
+
def preprocess_comment(text):
|
| 9 |
+
text = re.sub(r"http\S+", "", text)
|
| 10 |
+
text = text.lower()
|
| 11 |
+
text = text.translate(str.maketrans("", "", string.punctuation))
|
| 12 |
+
return text.strip()
|
| 13 |
+
|
| 14 |
+
def extract_metadata_features(text):
|
| 15 |
+
toxicity = detox_model.predict(text)["toxicity"]
|
| 16 |
+
word_count = len(text.split())
|
| 17 |
+
readability = min(1.0, word_count / 50) # Normalize to [0,1]
|
| 18 |
+
engagement = min(1.0, sum(1 for w in text.split() if len(w) > 6) / word_count) if word_count else 0
|
| 19 |
+
return np.array([toxicity, readability, engagement], dtype=np.float32)
|