Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
127 lines (98 loc) · 4.26 KB
/
Copy pathmain.py
File metadata and controls
127 lines (98 loc) · 4.26 KB
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
import requests
import xml.etree.ElementTree as ET
import xml.dom.minidom
from datetime import datetime
from email import utils
from transformers import pipeline
def fetch_top_stories():
print("Fetching hacker news frontpage...")
response = requests.get("https://hacker-news.firebaseio.com/v0/topstories.json")
top_stories_ids = response.json()
top_stories = []
for story_id in top_stories_ids[:30]: # Fetch details of top 30 stories for example
print("Fetching story:", story_id)
story_response = requests.get(
f"https://hacker-news.firebaseio.com/v0/item/{story_id}.json"
)
story_data = story_response.json()
top_stories.append(story_data)
return top_stories
def analyze_sentiment(text):
sentiment_task = pipeline(
"sentiment-analysis",
model="cardiffnlp/twitter-roberta-base-sentiment-latest",
tokenizer="cardiffnlp/twitter-roberta-base-sentiment-latest",
)
# Truncate or pad the text to fit the model's expected input size
max_length = 512
if len(text) > max_length:
text = text[:max_length]
sentiment_result = sentiment_task(text)
print(f'Sentiment analysis for "{text}": {sentiment_result}')
for sentiment in sentiment_result:
if sentiment["label"] == "negative":
return sentiment["score"]
return 0
def filter_positive_stories(stories):
positive_stories = []
negative_stories = []
for story in stories:
id = story.get("id", "")
title = story.get("title", "")
text = story.get("text", "")
print(f"Analyzing story: {id} ({title})")
# Check sentiment of title and text (if available)
title_sentiment = analyze_sentiment(title)
text_sentiment = analyze_sentiment(text) if text else 0
# Consider a story positive if either title or text is positive
if title_sentiment <= 0.3 and text_sentiment <= 0.3:
print(f"Result: {id} is positive. ({title})")
positive_stories.append(story)
else:
print(f"Result: {id} is negative. ({title})")
negative_stories.append(story)
return {"positive": positive_stories, "negative": negative_stories}
def format_rfc2822(timestamp):
"""Converts Unix timestamp to an RFC 2822 formatted string"""
dt = datetime.fromtimestamp(timestamp)
return utils.format_datetime(dt)
def create_rss_feed(positive_stories):
"""Creates an RSS feed from the list of positive stories"""
rss = ET.Element("rss", version="2.0")
channel = ET.SubElement(rss, "channel")
ET.SubElement(channel, "title").text = "Positive HackerNews"
ET.SubElement(channel, "description").text = "The Positive Hacker News RSS Feed"
ET.SubElement(channel, "language").text = "en"
ET.SubElement(channel, "link").text = (
"https://garritfra.github.io/positive_hackernews/feed.xml"
)
ET.SubElement(channel, "lastBuildDate").text = utils.format_datetime(datetime.now())
for story in positive_stories:
item = ET.SubElement(channel, "item")
ET.SubElement(item, "title").text = story.get("title", "No Title")
ET.SubElement(item, "link").text = story.get(
"url", f"https://news.ycombinator.com/item?id={story.get('id')}"
)
ET.SubElement(item, "description").text = story.get("text", "No Text")
ET.SubElement(item, "guid").text = str(story.get("id", "No ID"))
ET.SubElement(item, "comments").text = (
f"https://news.ycombinator.com/item?id={str(story.get('id', 'No ID'))}"
)
ET.SubElement(item, "pubDate").text = format_rfc2822(story.get("time", 0))
# Convert to a string
rough_string = ET.tostring(rss, encoding="unicode")
# Pretty Print
reparsed = xml.dom.minidom.parseString(rough_string)
return reparsed.toprettyxml(indent=" ")
def write_to_file(string, filename):
with open(filename, "w", encoding="utf-8") as file:
file.write(string)
def main():
top_stories = fetch_top_stories()
analyzed_stories = filter_positive_stories(top_stories)
rss_feed = create_rss_feed(analyzed_stories["positive"])
filename = "feed.xml"
write_to_file(rss_feed, filename)
print(f"RSS feed written to file: {filename}")
if __name__ == "__main__":
main()