# Alikhan Makhamadaliev, CSC3400, Assignment 2: Youtube Comment Classification

import os
import pandas as pd
import matplotlib.pyplot as plt

from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import StratifiedKFold, cross_validate, cross_val_predict
from sklearn.metrics import roc_curve, roc_auc_score
from sklearn.naive_bayes import MultinomialNB
from sklearn.svm import LinearSVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier

# print every column of the results table
pd.set_option("display.max_columns", None)
pd.set_option("display.width", 200)

# the folder this script lives in, so the file paths work with PyCharm.
BASE_DIR = os.path.dirname(os.path.abspath(__file__))

# folder
DATA_DIR = os.path.join(BASE_DIR, "icpc17")


def read_comments(path):
    """Return the non-empty lines of a text file (one comment per line.)"""
    with open(path, encoding="utf-8", errors="replace") as f:
        return [line.strip() for line in f if line.strip()]


rows = []
for video_id in sorted(os.listdir(DATA_DIR)):
    folder = os.path.join(DATA_DIR, video_id)
    if not os.path.isdir(folder):
        # skips ReadME.txt
        continue
    for fname in os.listdir(folder):
        # a few folders misspell the names
        if fname.startswith("con"):
            # content concern
            label = 1
        elif fname.startswith("other"):
            # misc
            label = 0
        else:
            # skip "all comments.txt" and the summary files
            continue
        for text in read_comments(os.path.join(folder, fname)):
            rows.append({"video": video_id, "comment": text, "label": label})

df = pd.DataFrame(rows)
X = df["comment"]
y = df["label"]
print(df.shape)
print(y.value_counts())
print(df.groupby("video")["label"].agg(["sum", "count"]))


def make_pipeline(clf):
    """TF-IDF + classifier, so the vocabulary is re-learned inside every fold."""
    return Pipeline([

        # dropping words that appear only in 1 comment (like original study)
        # no stop word removal per the study finding that removing stop words hurt SVM
        ("tfidf", TfidfVectorizer(lowercase=True, sublinear_tf=True, min_df=2)),
        ("clf", clf),
    ])


# Stratified keeps the 30/70 split in every fold; random_state makes it repeatable
cv = StratifiedKFold(n_splits=10, shuffle=True, random_state=42)
scoring = ["accuracy", "precision", "recall", "f1"]


def evaluate(models):
    """Run 10-fold CV on each model and return a table of mean and SD per metric."""
    rows = []
    for name, model in models.items():
        scores = cross_validate(model, X, y, cv=cv, scoring=scoring)
        row = {"Classifier": name}
        for m in scoring:
            row[m.capitalize()] = scores[f"test_{m}"].mean()
            row[m.capitalize() + "_SD"] = scores[f"test_{m}"].std()
        rows.append(row)
    return pd.DataFrame(rows).set_index("Classifier")


models = {
    "Naive Bayes": make_pipeline(MultinomialNB()),
    "SVM": make_pipeline(LinearSVC(random_state=42)),
    "Decision Tree": make_pipeline(DecisionTreeClassifier(random_state=42)),
    "Random Forest": make_pipeline(RandomForestClassifier(n_estimators=200, random_state=42, n_jobs=-1)),
}

results = evaluate(models)
# report table: each cell is "mean +/- SD" across the 10-folds
summary = pd.DataFrame(index=results.index)
for m in ["Accuracy", "Precision", "Recall", "F1"]:
    summary[m] = [f"{mean:.3f} ± {sd:.3f}" for mean, sd in zip(results[m], results[m + "_SD"])]
print(summary)
results.round(3).to_csv(os.path.join(BASE_DIR, "results.csv"))

aucs = {}
plt.figure(figsize=(6, 6))
for name, model in models.items():
    # LinearSVC has no predict_proba, so I will use its decision_function scores instead
    method = "decision_function" if name == "SVM" else "predict_proba"
    scores = cross_val_predict(model, X, y, cv=cv, method=method)
    if method == "predict_proba":
    # probability of class 1 (content concern)
        scores = scores[:, 1]
    auc = roc_auc_score(y, scores)
    aucs[name] = auc

    fpr, tpr, _ = roc_curve(y, scores)
    plt.plot(fpr, tpr, label=f"{name} (AUC = {auc:.3f})")
    print(f"{name} AUC: {auc:.3f}")


# finished report table, with AUC as the last column
summary["AUC"] = [f"{aucs[name]:.3f}" for name in summary.index]
print(summary)
#"utf-8-sig" encoding makes the +/- sign display correctly when previewing csv
summary.to_csv(os.path.join(BASE_DIR, "report_table.csv"), encoding ="utf-8-sig")


plt.plot([0, 1], [0, 1], linestyle="--", color="gray", label="Random guess")
plt.xlabel("False positive rate")
plt.ylabel("True positive rate")
plt.title("ROC curves, 10-fold CV")
plt.legend(loc="lower right")
plt.tight_layout()
plt.savefig(os.path.join(BASE_DIR, "roc_curves.png"), dpi=200)
plt.show()

