Spaces:
No application file

File size: 3,469 Bytes
602fb89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import re
import torch
import pandas as pd
import spacy
import textstat
import numpy as np
from sklearn.preprocessing import StandardScaler
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
from textblob import TextBlob
from transformers import RobertaTokenizerFast
from typing import Any, List, Tuple
from collections import Counter

# Initialize assets
analyzer  = SentimentIntensityAnalyzer()
nlp       = spacy.load("en_core_web_sm")
tokenizer = RobertaTokenizerFast.from_pretrained("roberta-base")

def prepare_data(path: str) -> Tuple[List[Any], List[int]]:
    df = pd.read_csv(path)

    url_col = 'url' if 'url' in df.columns else 'URL'
    col     = 'headline' if 'headline' in df.columns else 'Headline'

    # Fox News = 1, NBC = 0 (matches notebook label assignment)
    y = df[url_col].apply(lambda x: 1 if 'foxnews' in str(x).lower() else 0).tolist()

    raw_headlines = df[col].fillna("").astype(str).tolist()

    extra_features_list = []
    for text in raw_headlines:
        # Step 1: partial clean (matches notebook process_data)
        cleaned = re.sub(r'[^a-zA-Z0-9\s!?.]', '', str(text))

        # Sentiment on partially-cleaned (not yet lowered) text
        vader = analyzer.polarity_scores(cleaned)['compound']
        blob  = TextBlob(cleaned)
        pol   = blob.sentiment.polarity
        sub   = blob.sentiment.subjectivity

        # Step 2: lowercase for readability + POS (matches notebook)
        cleaned_lower = cleaned.lower()

        flesch_grade = textstat.flesch_kincaid_grade(cleaned_lower)
        dale_chall   = textstat.dale_chall_readability_score(cleaned_lower)

        doc        = nlp(cleaned_lower)
        pos_counts = Counter([token.pos_ for token in doc])
        total      = max(len(doc), 1)

        adj_ratio   = pos_counts['ADJ']  / total
        noun_ratio  = pos_counts['NOUN'] / total
        verb_ratio  = pos_counts['VERB'] / total
        propn_ratio = pos_counts['PROPN'] / total

        extra_features_list.append([
            vader, pol, sub,
            flesch_grade, dale_chall,
            adj_ratio, noun_ratio, verb_ratio, propn_ratio
        ])

        extra_features_array = np.array(extra_features_list)

    # Apply StandardScaler transformation using hardcoded train statistics
    # MEANS and SCALES from your training data
    MEANS = np.array([-0.1334619224845996, 0.03029492746171712, 0.2651717153521648, 
             9.980616597099122, 13.645249615780298, 0.0889533621243282, 
             0.3505696658815537, 0.1632638895974067, 0.1800343226802681])
    
    SCALES = np.array([0.44220484926020476, 0.24816946974516618, 0.30067967610801016, 
              3.4913473626034275, 2.6611917566411334, 0.08265346734243517, 
              0.14167055766862657, 0.08353813921243011, 0.15736948474872678])
    
    # Standardize features
    scaler = StandardScaler()
    scaler.mean_ = MEANS
    scaler.scale_ = SCALES
    extra_features_scaled = scaler.transform(extra_features_array)

    # Tokenize raw headlines
    encoded = tokenizer(
        raw_headlines,
        padding='max_length',
        truncation=True,
        max_length=64,
        return_tensors='pt'
    )

    X = []
    for i in range(len(df)):
        X.append({
            'input_ids':      encoded['input_ids'][i],
            'attention_mask': encoded['attention_mask'][i],
            'extra':          torch.tensor(extra_features_scaled[i], dtype=torch.float)
        })

    return X, y