-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy patharticle_fetcher.py
More file actions
324 lines (262 loc) · 10.1 KB
/
Copy patharticle_fetcher.py
File metadata and controls
324 lines (262 loc) · 10.1 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
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
#!/usr/bin/env python3
# /// script
# dependencies = [
# "newspaper4k",
# "lxml_html_clean",
# "httpx",
# ]
# ///
"""
Article Fetcher
Author: Claude Code
Prompt:
write a python script that fetches article content from the @sources.csv file and complies to the following:
1) Use PEP-723 script header
2) Use newspaper4k library except for reddit links
3) For reddit links, use httpx to get the url suffixed with /.json. In the retreived content, the title and selftext fields should be retreived in the response.data[0].data.children[0].data object.
4) Check for which articles have already been retreived.
5) Fetch only the items that are not already retreived.
6) Save the fetched content into markdown files in a folder named "source_content"
7) Save fetch results into a csv in that folder that details if content was retreived from each link successfully and what the length in words and characters were of the retreeived content
"""
import csv
import os
import re
from pathlib import Path
from newspaper import Article
from typing import List, Dict
import httpx
def sanitize_filename(title: str) -> str:
"""Convert title to a safe filename."""
# Remove or replace invalid filename characters
safe_title = re.sub(r'[<>:"/\\|?*]', '', title)
# Replace spaces with underscores
safe_title = safe_title.replace(' ', '_')
# Limit length to avoid filesystem issues
safe_title = safe_title[:100]
return safe_title
def fetch_reddit_article(url: str) -> Dict[str, any]:
"""
Fetch article content from Reddit using JSON API.
Returns dict with success status, content, and metadata.
"""
result = {
'success': False,
'title': '',
'text': '',
'authors': [],
'publish_date': None,
'error': None
}
try:
# Add .json suffix to Reddit URL
json_url = url.rstrip('/') + '.json'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Accept': 'application/json',
'Accept-Language': 'en-US,en;q=0.9',
'Accept-Encoding': 'gzip, deflate, br',
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1',
'Sec-Fetch-Dest': 'document',
'Sec-Fetch-Mode': 'navigate',
'Sec-Fetch-Site': 'none',
'Cache-Control': 'max-age=0',
}
# Fetch with httpx
with httpx.Client(timeout=30.0) as client:
response = client.get(json_url, follow_redirects=True, headers=headers)
response.raise_for_status()
data = response.json()
# Navigate to the post data
post_data = data[0]['data']['children'][0]['data']
result['success'] = True
result['title'] = post_data.get('title', '')
result['text'] = post_data.get('selftext', '')
result['authors'] = [post_data.get('author', 'unknown')]
result['publish_date'] = None # Could extract from 'created_utc' if needed
except Exception as e:
result['error'] = str(e)
return result
def fetch_article(url: str) -> Dict[str, any]:
"""
Fetch article content from URL using newspaper4k (or httpx for Reddit).
Returns dict with success status, content, and metadata.
"""
# Check if this is a Reddit link
if 'reddit.com' in url:
return fetch_reddit_article(url)
result = {
'success': False,
'title': '',
'text': '',
'authors': [],
'publish_date': None,
'error': None
}
try:
article = Article(url)
article.download()
article.parse()
result['success'] = True
result['title'] = article.title
result['text'] = article.text
result['authors'] = article.authors
result['publish_date'] = article.publish_date
except Exception as e:
result['error'] = str(e)
return result
def save_to_markdown(title: str, content: str, url: str, output_dir: Path,
authors: List[str] = None, publish_date: str = None) -> str:
"""
Save article content to a markdown file.
Returns the filename used.
"""
filename = f"{sanitize_filename(title)}.md"
filepath = output_dir / filename
# Build markdown content with metadata
md_content = f"# {title}\n\n"
md_content += f"**Source:** {url}\n\n"
if authors:
md_content += f"**Authors:** {', '.join(authors)}\n\n"
if publish_date:
md_content += f"**Published:** {publish_date}\n\n"
md_content += "---\n\n"
md_content += content
with open(filepath, 'w', encoding='utf-8') as f:
f.write(md_content)
return filename
def get_already_fetched_urls(results_csv: Path) -> set:
"""
Read the results CSV and return a set of URLs that were successfully fetched.
"""
already_fetched = set()
if not results_csv.exists():
return already_fetched
try:
with open(results_csv, 'r', encoding='utf-8') as f:
reader = csv.DictReader(f)
for row in reader:
# Only consider successfully fetched articles
if row.get('success', '').lower() == 'true':
already_fetched.add(row['url'])
except Exception as e:
print(f"Warning: Could not read existing results CSV: {e}")
return already_fetched
def main():
"""Main execution function."""
# Setup paths
script_dir = Path(__file__).parent
sources_csv = script_dir / "sources.csv"
output_dir = script_dir / "source_content"
results_csv = output_dir / "fetch_results.csv"
# Create output directory
output_dir.mkdir(exist_ok=True)
# Check for already fetched articles
already_fetched = get_already_fetched_urls(results_csv)
if already_fetched:
print(f"Found {len(already_fetched)} already fetched articles. They will be skipped.\n")
# Prepare results storage
results = []
# Load existing results if they exist
if results_csv.exists():
try:
with open(results_csv, 'r', encoding='utf-8') as f:
reader = csv.DictReader(f)
results = list(reader)
# Convert string 'True'/'False' to boolean for consistency
for r in results:
r['success'] = r['success'].lower() == 'true'
except Exception as e:
print(f"Warning: Could not load existing results: {e}")
results = []
# Read sources CSV
print("Reading sources.csv...")
with open(sources_csv, 'r', encoding='utf-8') as f:
reader = csv.DictReader(f)
sources = list(reader)
# Filter out already fetched sources
sources_to_fetch = [s for s in sources if s['source'] not in already_fetched]
print(f"Found {len(sources)} total articles.")
print(f"Already fetched: {len(already_fetched)}")
print(f"To fetch: {len(sources_to_fetch)}\n")
# Fetch each article (only the ones not already fetched)
for idx, row in enumerate(sources_to_fetch, 1):
title = row['title']
url = row['source']
print(f"[{idx}/{len(sources_to_fetch)}] Fetching: {title}")
print(f" URL: {url}")
# Fetch article
article_data = fetch_article(url)
if article_data['success']:
# Get content stats
text = article_data['text']
word_count = len(text.split())
char_count = len(text)
# Save to markdown
try:
filename = save_to_markdown(
article_data['title'] or title,
text,
url,
output_dir,
article_data['authors'],
article_data['publish_date']
)
results.append({
'title': title,
'url': url,
'success': True,
'filename': filename,
'word_count': word_count,
'char_count': char_count,
'error': ''
})
print(f" ✓ Success: {word_count} words, {char_count} characters")
print(f" Saved to: {filename}\n")
except Exception as e:
results.append({
'title': title,
'url': url,
'success': False,
'filename': '',
'word_count': 0,
'char_count': 0,
'error': f"Save error: {str(e)}"
})
print(f" ✗ Failed to save: {str(e)}\n")
else:
results.append({
'title': title,
'url': url,
'success': False,
'filename': '',
'word_count': 0,
'char_count': 0,
'error': article_data['error']
})
print(f" ✗ Failed: {article_data['error']}\n")
# Save results to CSV
print(f"Saving results to {results_csv}...")
with open(results_csv, 'w', encoding='utf-8', newline='') as f:
fieldnames = ['title', 'url', 'success', 'filename', 'word_count', 'char_count', 'error']
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(results)
# Print summary
newly_fetched = len([r for r in results if r['url'] not in already_fetched])
total_successful = sum(1 for r in results if r['success'])
total_failed = sum(1 for r in results if not r['success'])
print(f"\n{'='*60}")
print(f"Summary:")
print(f" Total articles in sources.csv: {len(sources)}")
print(f" Already fetched (skipped): {len(already_fetched)}")
print(f" Newly attempted: {len(sources_to_fetch)}")
print(f" Newly fetched successfully: {sum(1 for r in results if r['success'] and r['url'] not in already_fetched)}")
print(f" Total in results CSV: {len(results)}")
print(f" - Successful: {total_successful}")
print(f" - Failed: {total_failed}")
print(f" Results saved to: {results_csv}")
print(f"{'='*60}")
if __name__ == "__main__":
main()