Spaces:
Sleeping
Sleeping
File size: 7,931 Bytes
0090940 dd08c63 0090940 dd08c63 0090940 dd08c63 0090940 dd08c63 0090940 81c0f8f 0090940 dd08c63 0090940 dd08c63 0090940 dd08c63 81c0f8f 7f22404 9cde465 81c0f8f 0090940 dd08c63 0090940 dd08c63 0090940 dd08c63 0090940 dd08c63 0090940 dd08c63 0090940 dd08c63 2e3fd66 0090940 dd08c63 0090940 dd08c63 0090940 2e3fd66 dd08c63 2e3fd66 dd08c63 2e3fd66 dd08c63 2e3fd66 dd08c63 2e3fd66 0090940 dd08c63 2e3fd66 dd08c63 0090940 dd08c63 2e3fd66 dd08c63 0090940 dd08c63 0090940 dd08c63 0090940 2e3fd66 0090940 dd08c63 0090940 2e3fd66 dd08c63 2e3fd66 dd08c63 0090940 dd08c63 0090940 dd08c63 0090940 81c0f8f 0090940 81c0f8f 0090940 81c0f8f 0090940 dd08c63 0090940 2e3fd66 | 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 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 | import gradio as gr
import torch
import torch.nn as nn
from transformers import DistilBertTokenizer, DistilBertModel
import os
# Define the model architecture
class HeadlineScoreModel(nn.Module):
def __init__(self, n_regression_outputs, n_categories):
super(HeadlineScoreModel, self).__init__()
self.bert = DistilBertModel.from_pretrained('distilbert-base-uncased')
self.drop = nn.Dropout(p=0.3)
self.regression_head = nn.Linear(self.bert.config.hidden_size, n_regression_outputs)
self.classification_heads = nn.ModuleList([
nn.Linear(self.bert.config.hidden_size, 1) for _ in range(n_categories)
])
def forward(self, input_ids, attention_mask):
outputs = self.bert(input_ids=input_ids, attention_mask=attention_mask)
pooled_output = outputs.last_hidden_state[:, 0, :] # First token ([CLS])
output = self.drop(pooled_output)
regression_output = self.regression_head(output)
classification_outputs = [torch.sigmoid(head(output)) for head in self.classification_heads]
classification_output = torch.cat(classification_outputs, dim=1) # Shape: (batch_size, n_categories)
return regression_output, classification_output
# Information section displayed on the interface
INFORMATION_SECTION = """
## News Headlines Analyzer
Analyze news headlines for sentiment, intensity, urgency, controversy, and categories (Health, Environment, Technology, Finance, Politics).
### Key Features
- Uses a fine-tuned DistilBERT model
- Multi-task learning: regression and classification
- Edge case weighting and optimized real-time headline analysis
### Quick Pros/Cons Comparison
**Pros:**
- No hallucinations: Returns clear numerical metrics.
- Model can be finetuned to match your own thought process in training process.
- Low computational demand: Optimized with DistilBERT.
- Open-source: Fully customizable and transparent.
**Cons:**
- Tailored for headline analysis only.
- Due to the minimal headlines, it can sometimes miss analyze longer and more unique headlines.
- The model was trained specifically for news headlines and on news headlines, it is not intended for general sentiment analysis.
## Development Process
#### Data Collection and Cleaning:
Collected and cleaned over a million news headlines, ensuring proper formatting. Funneled said headlines into advances LLMs with prompts to build dataset for training, while minimizing hallucinations.
#### Custom Weighting System:
Implemented a weighting system to emphasize edge cases, such as extreme sentiment or urgency values, to enhance model performance.
#### Fine-Tuning DistilBERT:
Fine-tuned a DistilBERT model for regression and multi-label classification over 50 epochs on GPUs using Google Colab. The 16th epoch was selected as the final model, offering the best balance between training loss and validation performance.
#### Training Pipeline:
Built a GPU-accelerated training pipeline using CUDA on Google Colab, featuring sample weighting, checkpointing, and stratified data splits for reliable and scalable results.
## Contact Information
If you’d like to request the full script, discuss this work, or explore other opportunities, feel free to reach out:
### 📧 Email: [mitelmanjonathan@gmail.com](mailto:mitelmanjonathan@gmail.com)
### 🔗 LinkedIn: [linkedin.com/in/jonathan-mitelman/](https://www.linkedin.com/in/jonathan-mitelman/)
"""
def predict_headline(model, tokenizer, category_names, headline, device, max_len=183):
"""
Preprocesses and predicts the results for the given headline.
"""
model.eval()
encoding = tokenizer.encode_plus(
headline,
add_special_tokens=True,
max_length=max_len,
return_token_type_ids=False,
padding='max_length',
truncation=True,
return_attention_mask=True,
return_tensors='pt',
)
input_ids = encoding['input_ids'].to(device)
attention_mask = encoding['attention_mask'].to(device)
with torch.no_grad():
regression_output, classification_output = model(input_ids=input_ids, attention_mask=attention_mask)
regression_output = regression_output.cpu().numpy()[0]
classification_output = classification_output.cpu().numpy()[0]
# Prepare results
regression_results = {
"Sentiment": max(0, regression_output[0]), # Ensure non-negative sentiment
"Intensity": min(max(0, regression_output[1]), 10), # Clamp between 0 and 10
"Urgency": regression_output[2],
"Controversy": regression_output[3]
}
classification_results = {
category: classification_output[idx] >= 0.5
for idx, category in enumerate(category_names)
}
return regression_results, classification_results
def analyze_headline(headline):
"""
Formats and returns the analysis results for the given headline.
"""
try:
regression_results, classification_results = predict_headline(
model=model,
tokenizer=tokenizer,
category_names=category_names,
headline=headline,
device=device
)
# Format output string
sentiment = regression_results["Sentiment"]
intensity = regression_results["Intensity"]
urgency = regression_results["Urgency"]
controversy = regression_results["Controversy"]
categories = ", ".join([cat for cat, val in classification_results.items() if val]) or "None"
output = (
"Analysis Results:\n\n"
f"Metrics:\n"
f"- Sentiment: {sentiment:.2f}/10\n"
f"- Intensity: {intensity:.2f}/10\n"
f"- Urgency: {urgency:.2f}/10\n"
f"- Controversy: {controversy:.2f}/10\n\n"
f"📑 Categories: {categories}"
)
return output
except Exception as e:
return f"Error analyzing headline: {str(e)}"
def load_model():
"""
Loads the model, tokenizer, and category names.
"""
model_path = os.path.join("model", "distilbert_news_classifier_epoch16.pth")
# Determine device
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Using device: {device}")
# Ensure model directory exists
os.makedirs("model", exist_ok=True)
# Check for the model file
if not os.path.exists(model_path):
raise FileNotFoundError(
f"Model file not found at {model_path}. Please ensure the .pth file exists."
)
# Load model
model = HeadlineScoreModel(n_regression_outputs=4, n_categories=5)
model.load_state_dict(torch.load(model_path, map_location=device))
model.to(device)
model.eval()
# Load tokenizer
tokenizer = DistilBertTokenizer.from_pretrained("distilbert-base-uncased")
# Define categories
category_names = ["Health", "Environment", "Technology", "Finance", "Politics"]
return model, tokenizer, category_names, device
# Load model and tokenizer
try:
model, tokenizer, category_names, device = load_model()
except Exception as e:
print(f"Error loading model: {str(e)}")
# Define Gradio Interface
iface = gr.Interface(
fn=analyze_headline,
inputs=gr.Textbox(lines=2, placeholder="Enter a news headline here..."),
outputs="text",
title="News Headline Analyzer",
description=(
"An easier way to analyze headlines"
),
css="""
.gradio-container .container > .interface > .description {
font-size: 18px;
line-height: 1.5;
}
""",
article=INFORMATION_SECTION,
examples=[
["Massive magnitude 7 earthquake strikes off California coast"],
["Tech company launches revolutionary AI product"],
["Pig Kidney Transplant Gives Hope to US Woman Who Donated Own to Her Mother"]
]
)
# Launch the Gradio interface
if __name__ == "__main__":
iface.launch()
|