Spaces:
Sleeping
Sleeping
Download app.py from jonmfc/Headline_Analyzer: direct link, hf CLI and curl.
- Browser
- Download file 7.93 kB
-
https://huggingface.co/spaces/jonmfc/Headline_Analyzer/resolve/main/app.py
- Command line
-
hf download hf://spaces/jonmfc/Headline_Analyzer/app.py
-
curl -L -o app.py https://huggingface.co/spaces/jonmfc/Headline_Analyzer/resolve/main/app.py
7.93 kB
| 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() | |