Spaces:
No application file
No application file
Download lora_roberta_preprocess.py from desai7/ML_Project: direct link, hf CLI and curl.
- Browser
- Download file 3.47 kB
-
https://huggingface.co/spaces/desai7/ML_Project/resolve/main/lora_roberta_preprocess.py
- Command line
-
hf download hf://spaces/desai7/ML_Project/lora_roberta_preprocess.py
-
curl -L -o lora_roberta_preprocess.py https://huggingface.co/spaces/desai7/ML_Project/resolve/main/lora_roberta_preprocess.py
3.47 kB
| 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 | |