Last active
November 25, 2024 06:20
-
-
Save davidair/5ac005c86a8a04ac46b724a3c0fe9324 to your computer and use it in GitHub Desktop.
Analyze news article sentiment using ollama
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# The MIT License | |
# | |
# Copyright 2024 David Airapetyan | |
# | |
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: | |
# | |
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. | |
# | |
# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. | |
from bs4 import BeautifulSoup | |
import ollama | |
import requests | |
import xml.etree.ElementTree as ET | |
# Define Ollama model and session | |
MODEL_NAME = "llama3.2" | |
def extract_with_custom_rules(raw_html): | |
soup = BeautifulSoup(raw_html, "html.parser") | |
# Get text within <p> tags | |
paragraphs = [p.get_text() for p in soup.find_all("p")] | |
# Optionally, get 'title' attribute from the first image, if present | |
image_title = "" | |
image = soup.find("img", title=True) | |
if image: | |
image_title = image["title"] | |
# Combine both | |
combined_text = " ".join(paragraphs) + (f" {image_title}" if image_title else "") | |
return combined_text if combined_text else soup.get_text() | |
def fetch_rss_feed(url): | |
"""Fetch the RSS feed from the given URL and return the XML payload.""" | |
headers = { | |
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Safari/537.36' | |
} | |
try: | |
print(f"Fetching the RSS feed from {url}...") | |
response = requests.get(url, headers=headers) | |
response.raise_for_status() # Raises an error for bad status codes | |
return response.text | |
except requests.RequestException as e: | |
raise RuntimeError(f"Failed to fetch RSS feed: {e}") | |
def parse_rss_feed(xml_payload): | |
"""Parse the RSS XML payload and return a list of dictionaries with 'title' and 'description' keys.""" | |
print(f"Parsing results...") | |
root = ET.fromstring(xml_payload) | |
items = [] | |
for item in root.findall('./channel/item'): | |
title = item.find('title').text if item.find('title') is not None else "No title" | |
description_raw = item.find('description').text if item.find('description') is not None else "No description" | |
description = extract_with_custom_rules(description_raw) | |
items.append({"title": title, "description": description}) | |
return items | |
def analyze_sentiment(news_item): | |
# Start a chat session with Ollama | |
client = ollama.Client() | |
prompt = f"Analyze the sentiment of this news item:\n\nTitle: {news_item['title']}\nDescription: {news_item['description']}\n\nIs it positive, neutral, or negative?" | |
# Send the prompt to the model and retrieve the response | |
response = client.generate(MODEL_NAME, prompt) | |
return response["response"] | |
# CBS. More news at https://github.com/plenaryapp/awesome-rss-feeds. | |
url = "https://www.cbc.ca/webfeed/rss/rss-topstories" | |
try: | |
xml_payload = fetch_rss_feed(url) | |
articles = parse_rss_feed(xml_payload) | |
for article in articles: | |
sentiment = analyze_sentiment(article) | |
print(f"Title: {article['title']}") | |
print(f"Description: {article['description']}") | |
print(f"Sentiment: {sentiment}") | |
print() | |
except RuntimeError as e: | |
print(e) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment