Debian Codegraph @

recipes/economist_world_ahead.recipe

raw
1 #!/usr/bin/env python
2
3 import json
4 import time
5 from datetime import datetime, timedelta
6 from urllib.parse import quote, urlencode
7 from uuid import uuid4
8
9 from html5_parser import parse
10 from lxml import etree
11 from mechanize import Request
12
13 from calibre import browser
14 from calibre.ptempfile import PersistentTemporaryFile
15 from calibre.web.feeds.news import BasicNewsRecipe
16
17
18 def safe_dict(data, *names):
19 ans = data
20 for x in names:
21 ans = ans.get(x) or {}
22 return ans
23
24
25 def process_web_list(li_node):
26 li_html = ''
27 for li in li_node['items']:
28 if li.get('textHtml'):
29 li_html += f'<li>{li["textHtml"]}</li>'
30 elif li.get('textJson'):
31 li_html += f'<li>{parse_textjson(li["textJson"])}</li>'
32 else:
33 li_html += f'<li>{li.get("text", "")}</li>'
34 return '<ul>' + li_html + '</ul>'
35
36
37 def process_info_box(bx):
38 info = ''
39 for x in safe_dict(bx, 'components'):
40 info += f'<blockquote>{process_web_node(x)}</blockquote>'
41 return info
42
43
44 def parse_txt(ty):
45 typ = ty.get('type', '')
46 children = ty.get('children', [])
47 href = '#'
48 attributes = ty.get('attributes') or ()
49 for a in attributes:
50 if a.get('name') == 'href':
51 href = a.get('value', href)
52 break
53
54 tag_map = {
55 'text': lambda: [ty.get('value', '')],
56 'scaps': lambda: [
57 f'<span style="text-transform: uppercase; font-size: 0.85em; letter-spacing: 0.05em;">{"".join(parse_txt(c))}</span>' for c in children
58 ],
59 'bold': lambda: [f'<b>{"".join(parse_txt(c))}</b>' for c in children],
60 'drop_caps': lambda: [f'<b>{"".join(parse_txt(c))}</b>' for c in children],
61 'italic': lambda: [f'<i>{"".join(parse_txt(c))}</i>' for c in children],
62 'linebreak': lambda: ['<br>'],
63 'external_link': lambda: [f'<a href="{href}">{"".join(parse_txt(c))}</a>' for c in children],
64 'internal_link': lambda: [f'<a href="{href}">{"".join(parse_txt(c))}</a>' for c in children],
65 'ufinish': lambda: [text for c in children for text in parse_txt(c)],
66 'subscript': lambda: [f'<sub>{"".join(parse_txt(c))}</sub>' for c in children],
67 'superscript': lambda: [f'<sup>{"".join(parse_txt(c))}</sup>' for c in children],
68 }
69
70 if typ in tag_map:
71 yield from tag_map[typ]()
72 else:
73 print('** ', typ)
74
75
76 def parse_textjson(nt):
77 return ''.join(''.join(parse_txt(n)) for n in nt)
78
79
80 def process_web_node(node):
81 ntype = node.get('type', '')
82 if ntype == 'CROSSHEAD':
83 if node.get('textHtml'):
84 return f'<h4>{node.get("textHtml")}</h4>'
85 return f'<h4>{node.get("text", "")}</h4>'
86 elif ntype in ['PARAGRAPH', 'BOOK_INFO']:
87 if node.get('textHtml'):
88 return f'\n<p>{node.get("textHtml")}</p>'
89 if node.get('textJson'):
90 return f'\n<p>{parse_textjson(node["textJson"])}</p>'
91 return f'\n<p>{node.get("text", "")}</p>'
92 elif (ntype == 'IMAGE') or (node.get('__typename', '') == 'ImageComponent'):
93 alt = '' if node.get('altText') is None else node.get('altText')
94 cap = ''
95 if node.get('caption'):
96 if node['caption'].get('textHtml') is not None:
97 cap = node['caption']['textHtml']
98 elif node['caption'].get('textJson') is not None:
99 cap = parse_textjson(node['caption']['textJson'])
100 elif node['caption'].get('text') is not None:
101 cap = node['caption']['text']
102 return f'<div><img src="{node["url"]}" title="{alt}"></div><div style="text-align:center; font-size:small;">{cap}</div>'
103 elif ntype == 'PULL_QUOTE':
104 if node.get('textHtml'):
105 return f'<blockquote>{node.get("textHtml")}</blockquote>'
106 if node.get('textJson'):
107 return f'<blockquote>{parse_textjson(node["textJson"])}</blockquote>'
108 return f'<blockquote>{node.get("text", "")}</blockquote>'
109 elif ntype == 'BLOCK_QUOTE':
110 if node.get('textHtml'):
111 return f'<blockquote><i>{node.get("textHtml")}</i></blockquote>'
112 if node.get('textJson'):
113 return f'<blockquote><i>{parse_textjson(node["textJson"])}</i></blockquote>'
114 return f'<blockquote><i>{node.get("text", "")}</i></blockquote>'
115 elif ntype == 'DIVIDER':
116 return '<hr>'
117 elif ntype == 'INFOGRAPHIC':
118 if node.get('fallback'):
119 return process_web_node(node['fallback'])
120 elif ntype == 'INFOBOX':
121 return process_info_box(node)
122 elif ntype == 'UNORDERED_LIST':
123 if node.get('items'):
124 return process_web_list(node)
125 elif ntype:
126 print('** ', ntype)
127 return ''
128
129
130 def load_article_from_web_json(raw):
131 # open('/t/raw.json', 'w').write(raw)
132 body = ''
133 data = json.loads(raw)['data']['findArticleByUrl']
134 body += f'<div style="color: red; font-size:small; font-weight:bold;">{data.get("flyTitle", "")}</div>'
135 body += f'<h1>{data["headline"]}</h1>'
136 if data.get('rubric') and data.get('rubric') is not None:
137 body += f'<div style="font-style: italic; color:#202020;">{data.get("rubric", "")}</div>'
138 try:
139 date = data['dateModified']
140 except Exception:
141 date = data['datePublished']
142 dt = datetime.fromisoformat(date[:-1]) + timedelta(seconds=time.timezone)
143 dt = dt.strftime('%b %d, %Y %I:%M %p')
144 if data.get('dateline') is None:
145 body += f'<p style="color: gray; font-size: small;">{dt}</p>'
146 else:
147 body += f'<p style="color: gray; font-size: small;">{dt + " | " + (data["dateline"])}</p>'
148 main_image_url = safe_dict(data, 'leadComponent') or ''
149 if main_image_url:
150 body += process_web_node(data['leadComponent'])
151 if data.get('byline'):
152 if data['byline'] is not None:
153 body += f'<p style="color: gray; font-size: small;"><i>{"By " + data["byline"]}</i></p>'
154 for node in data.get('body'):
155 body += process_web_node(node)
156 return '<html><body><article>' + body + '</article></body></html>'
157
158
159 class NoArticles(Exception):
160 pass
161
162
163 def get_content(url_):
164
165 headers = {
166 'User-Agent': 'TheEconomist-Liskov-android',
167 'accept': 'multipart/mixed; deferSpec=20220824, application/json',
168 'accept-encoding': 'gzip',
169 'content-type': 'application/json',
170 'x-app-trace-id': str(uuid4()),
171 'x-economist-consumer': 'TheEconomist-Liskov-android',
172 'x-teg-client-name': 'Economist-Android',
173 'x-teg-client-os': 'Android',
174 'x-teg-client-version': '4.40.0',
175 }
176 br = browser()
177 req = Request(
178 url_,
179 headers=headers,
180 )
181 res = br.open(req)
182 return res.read()
183
184
185 def process_url(url):
186 if url.startswith('/'):
187 url = 'https://www.economist.com' + url
188 return url
189
190
191 class EconomistWorld(BasicNewsRecipe):
192 title = 'The Economist World Ahead'
193 language = 'en_GB'
194 encoding = 'utf-8'
195 masthead_url = 'https://www.livemint.com/lm-img/dev/economist-logo-oneline.png'
196
197 __author__ = 'unkn0wn'
198 description = (
199 'The World Ahead is The Economist’s future-gazing publication. It prepares audiences for what is to '
200 'come with mind-stretching insights and expert analysis—all in The Economist’s clear, elegant style.'
201 ' Best downloaded in late November.'
202 )
203 extra_css = '''
204 em { color:#202020; }
205 img {display:block; margin:0 auto;}
206 '''
207 resolve_internal_links = True
208
209 # economist.com has started throttling after about 60% of the total has
210 # downloaded with connection reset by peer (104) errors.
211 delay = 1
212 browser_type = 'webengine'
213
214 recipe_specific_options = {
215 'res': {
216 'short': 'For hi-res images, select a resolution from the\nfollowing options: 834, 960, 1096, 1280, 1424',
217 'long': 'This is useful for non e-ink devices, and for a lower file size\nthan the default, use from 480, 384, 360, 256.',
218 'default': '600',
219 },
220 }
221
222 def get_browser(self, *args, **kwargs):
223 br = BasicNewsRecipe.get_browser(self, *args, **kwargs)
224 return br
225
226 def economist_test_article(self):
227 return [
228 (
229 'Articles',
230 [{'title': 'test', 'url': 'https://www.economist.com/the-world-ahead/2024/11/20/ten-business-trends-for-2025-and-forecasts-for-15-industries'}],
231 )
232 ]
233
234 def economist_return_index(self, ans):
235 if not ans:
236 raise NoArticles(
237 'Could not find any articles, either the '
238 'economist.com server is having trouble and you should '
239 'try later or the website format has changed and the '
240 'recipe needs to be updated.'
241 )
242 return ans
243
244 def parse_index(self):
245 # return self.economist_test_article()
246 raw = self.index_to_soup('https://www.economist.com/the-world-ahead')
247 ans = self.economist_parse_index(raw)
248 return self.economist_return_index(ans)
249
250 def economist_parse_index(self, soup):
251 script_tag = soup.find('script', id='__NEXT_DATA__')
252 if script_tag is not None:
253 data = json.loads(script_tag.string)
254 # open('/t/raw.json', 'w').write(json.dumps(data, indent=2, sort_keys=True))
255 self.title = safe_dict(data, 'props', 'pageProps', 'content', 'headline')
256 self.cover_url = 'https://pbs.twimg.com/media/G5j0UuqXsAI9Rv3.jpg'
257
258 feeds = []
259
260 for coll in safe_dict(data, 'props', 'pageProps', 'content', 'components'):
261 section = safe_dict(coll, 'headline') or ''
262 self.log(section)
263 articles = []
264 for part in safe_dict(coll, 'items'):
265 title = safe_dict(part, 'headline') or ''
266 url = process_url(safe_dict(part, 'url') or '')
267 desc = safe_dict(part, 'rubric') or ''
268 sub = safe_dict(part, 'flyTitle') or ''
269 if sub and section != sub:
270 desc = sub + ' :: ' + desc
271 self.log('\t', title, '\n\t', desc, '\n\t\t', url)
272 articles.append({'title': title, 'description': desc, 'url': url})
273 if articles:
274 feeds.append((section, articles))
275 return feeds
276
277 def preprocess_html(self, soup):
278 width = '600'
279 w = self.recipe_specific_options.get('res')
280 if w and isinstance(w, str):
281 width = w
282 for img in soup.findAll('img', src=True):
283 qua = 'economist.com/cdn-cgi/image/width=' + width + ',quality=80,format=auto/'
284 img['src'] = img['src'].replace('economist.com/', qua)
285 return soup
286
287 def preprocess_raw_html(self, raw, url):
288 # open('/t/raw.html', 'wb').write(raw.encode('utf-8'))
289 html = load_article_from_web_json(raw)
290 root = parse(html)
291 # the economist uses <small> for small caps with a custom font
292 for init in root.xpath('//span[@data-caps="initial"]'):
293 init.set('style', 'font-weight:bold;')
294 for x in root.xpath('//small'):
295 if x.text and len(x) == 0:
296 x.text = x.text.upper()
297 x.tag = 'span'
298 x.set(
299 'style',
300 'text-transform: uppercase; font-size: 0.85em; letter-spacing: 0.05em;',
301 )
302 for h2 in root.xpath('//h2'):
303 h2.tag = 'h4'
304 for x in root.xpath('//figcaption'):
305 x.set('style', 'text-align:center; font-size:small;')
306 for x in root.xpath('//cite'):
307 x.tag = 'blockquote'
308 x.set('style', 'color:#404040;')
309 raw = etree.tostring(root, encoding='unicode')
310 return raw
311
312 def get_article(self, url):
313 query = {
314 'operationName': 'ArticleDeeplinkQuery',
315 'variables': '{{"ref":"{}"}}'.format(url),
316 'query': 'query ArticleDeeplinkQuery($ref: String!, $includeRelatedArticles: Boolean = true ) { findArticleByUrl(url: $ref) { __typename ...ArticleDataFragment } } fragment ContentIdentityFragment on ContentIdentity { articleType forceAppWebView leadMediaType } fragment NarrationFragment on Narration { album bitrate duration filename id provider url isAiGenerated fileHash } fragment ImageTeaserFragment on ImageComponent { altText height imageType source url width } fragment PodcastAudioFragment on PodcastEpisode { id audio { url durationInSeconds } } fragment ArticleTeaserFragment on Article { id tegId url rubric headline flyTitle brand byline dateFirstPublished dateline dateModified datePublished dateRevised estimatedReadTime wordCount printHeadline contentIdentity { __typename ...ContentIdentityFragment } section { tegId name } teaserImage { __typename type ...ImageTeaserFragment } leadComponent { __typename type ...ImageTeaserFragment } narration(selectionMethod: PREFER_ACTOR_NARRATION) { __typename ...NarrationFragment } podcast { __typename ...PodcastAudioFragment } } fragment AnnotatedTextFragment on AnnotatedText { text textJson annotations { type length index attributes { name value } } } fragment ImageComponentFragment on ImageComponent { altText caption { __typename ...AnnotatedTextFragment } credit height imageType mode source url width } fragment BlockQuoteComponentFragment on BlockQuoteComponent { text textJson annotations { type length index attributes { name value } } } fragment BookInfoComponentFragment on BookInfoComponent { text textJson annotations { type length index attributes { name value } } } fragment ParagraphComponentFragment on ParagraphComponent { text textJson annotations { type length index attributes { name value } } } fragment PullQuoteComponentFragment on PullQuoteComponent { text textJson annotations { type length index attributes { name value } } } fragment CrossheadComponentFragment on CrossheadComponent { text } fragment OrderedListComponentFragment on OrderedListComponent { items { __typename ...AnnotatedTextFragment } } fragment UnorderedListComponentFragment on UnorderedListComponent { items { __typename ...AnnotatedTextFragment } } fragment VideoComponentFragment on VideoComponent { url title thumbnailImage } fragment InfoboxComponentFragment on InfoboxComponent { components { __typename type ...BlockQuoteComponentFragment ...BookInfoComponentFragment ...ParagraphComponentFragment ...PullQuoteComponentFragment ...CrossheadComponentFragment ...OrderedListComponentFragment ...UnorderedListComponentFragment ...VideoComponentFragment } } fragment InfographicComponentFragment on InfographicComponent { url title width fallback { __typename ...ImageComponentFragment } altText height width } fragment ArticleDataFragment on Article { id url brand byline rubric headline layout { headerStyle } contentIdentity { __typename ...ContentIdentityFragment } dateline dateFirstPublished dateModified datePublished dateRevised estimatedReadTime narration(selectionMethod: PREFER_ACTOR_NARRATION) { __typename ...NarrationFragment } printFlyTitle printHeadline printRubric flyTitle wordCount section { tegId name articles(pagingInfo: { pagingType: OFFSET pageSize: 6 pageNumber: 1 } ) @include(if: $includeRelatedArticles) { edges { node { __typename ...ArticleTeaserFragment } } } } teaserImage { __typename type ...ImageComponentFragment } tegId leadComponent { __typename type ...ImageComponentFragment } body { __typename type ...BlockQuoteComponentFragment ...BookInfoComponentFragment ...ParagraphComponentFragment ...PullQuoteComponentFragment ...CrossheadComponentFragment ...OrderedListComponentFragment ...UnorderedListComponentFragment ...InfoboxComponentFragment ...ImageComponentFragment ...VideoComponentFragment ...InfographicComponentFragment } footer { __typename type ...ParagraphComponentFragment } tags { name } ads { adData } podcast { __typename ...PodcastAudioFragment } }', # noqa: E501
317 }
318 deep_url = 'https://cp2-graphql-gateway.p.aws.economist.com/graphql?' + urlencode(query, safe='()!', quote_via=quote)
319 raw = get_content(deep_url)
320 return raw
321
322 def print_version(self, url):
323 art_cont = self.get_article(url)
324 pt = PersistentTemporaryFile('.html')
325 pt.write(art_cont)
326 pt.close()
327 return 'file:///' + pt.name