Coverage for src/scixplorer/cli/output.py: 96%

175 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-18 23:06 +0000

1"""What the ``scix`` command shows: documents as text, sized and styled for a terminal.""" 

2 

3from __future__ import annotations 

4 

5import html 

6import re 

7import unicodedata 

8from collections.abc import Sequence 

9from dataclasses import dataclass 

10from urllib.parse import quote 

11 

12from ..models.document import Document 

13from ..models.journal import Journal 

14from ..utils import parse_bibcode 

15from .interpret import Interpretation 

16 

17__all__ = [ 

18 "FIELDS", 

19 "SORTS", 

20 "Style", 

21 "authors_line", 

22 "explanation", 

23 "fit", 

24 "listing", 

25 "page_url", 

26 "pdf_url", 

27 "reference", 

28 "short_authors", 

29 "title_of", 

30 "wrap", 

31] 

32 

33#: The fields the command fetches for every document. 

34FIELDS = ( 

35 "bibcode", 

36 "title", 

37 "author", 

38 "year", 

39 "pub", 

40 "volume", 

41 "page", 

42 "doctype", 

43 "citation_count", 

44 "abstract", 

45 "doi", 

46 "identifier", 

47 "property", 

48 "esources", 

49) 

50 

51#: The orders ``--sort`` accepts: name -> (field, descending, how to say it). 

52SORTS: dict[str, tuple[str, bool, str]] = { 

53 "date": ("date", True, "newest first"), 

54 "citations": ("citation_count", True, "most cited first"), 

55 "reads": ("read_count", True, "most read first"), 

56 "relevance": ("score", True, "most relevant first"), 

57 "oldest": ("date", False, "oldest first"), 

58 "author": ("first_author", False, "by first author"), 

59} 

60 

61#: Where a document's page is. 

62SITE = "https://scixplorer.org" 

63 

64#: The full-text sources ``pdf_url`` opens, best first. 

65_PDF_SOURCES = ("PUB_PDF", "EPRINT_PDF", "ADS_PDF", "AUTHOR_PDF") 

66 

67_TAG = re.compile(r"</?[A-Za-z][^>]*>") 

68 

69 

70@dataclass(frozen=True) 

71class Style: 

72 """Text styles, as ANSI escape sequences when ``enabled`` and as nothing otherwise.""" 

73 

74 enabled: bool = False 

75 

76 def _wrap(self, code: str, text: str) -> str: 

77 return f"\x1b[{code}m{text}\x1b[0m" if self.enabled and text else text 

78 

79 def bold(self, text: str) -> str: 

80 return self._wrap("1", text) 

81 

82 def dim(self, text: str) -> str: 

83 return self._wrap("2", text) 

84 

85 def accent(self, text: str) -> str: 

86 return self._wrap("36", text) 

87 

88 def warn(self, text: str) -> str: 

89 return self._wrap("33", text) 

90 

91 def selected(self, text: str) -> str: 

92 return self._wrap("7", text) 

93 

94 

95# Text that fits. 

96 

97 

98def _width(character: str) -> int: 

99 if unicodedata.combining(character): 99 ↛ 100line 99 didn't jump to line 100 because the condition on line 99 was never true

100 return 0 

101 return 2 if unicodedata.east_asian_width(character) in ("W", "F") else 1 

102 

103 

104def width_of(text: str) -> int: 

105 """How many terminal columns ``text`` takes.""" 

106 return sum(_width(character) for character in text) 

107 

108 

109def fit(text: str, width: int, *, pad: bool = False, right: bool = False) -> str: 

110 """``text`` cut to ``width`` columns (ending in ``…`` if cut), and padded to it if ``pad``.""" 

111 if width <= 0: 

112 return "" 

113 if width_of(text) > width: 

114 kept, used = [], 0 

115 for character in text: 115 ↛ 121line 115 didn't jump to line 121 because the loop on line 115 didn't complete

116 step = _width(character) 

117 if used + step > width - 1: 

118 break 

119 kept.append(character) 

120 used += step 

121 text = "".join(kept).rstrip() + "…" 

122 if not pad: 

123 return text 

124 space = " " * (width - width_of(text)) 

125 return space + text if right else text + space 

126 

127 

128def wrap(text: str, width: int) -> list[str]: 

129 """``text`` as lines of at most ``width`` columns, broken at spaces.""" 

130 width = max(width, 8) 

131 lines: list[str] = [] 

132 for paragraph in text.splitlines() or [""]: 

133 line = "" 

134 for word in paragraph.split(): 

135 while width_of(word) > width: # a word longer than a line: cut it 

136 head = fit(word, width + 1)[:-1] 

137 if line: 137 ↛ 138line 137 didn't jump to line 138 because the condition on line 137 was never true

138 lines.append(line) 

139 line = "" 

140 lines.append(head) 

141 word = word[len(head) :] 

142 if not line: 

143 line = word 

144 elif width_of(line) + 1 + width_of(word) <= width: 

145 line += " " + word 

146 else: 

147 lines.append(line) 

148 line = word 

149 lines.append(line) 

150 return lines 

151 

152 

153def _clean(text: str) -> str: 

154 """Text from SciX without the markup some records carry (``<SUB>``, ``&amp;``).""" 

155 return " ".join(html.unescape(_TAG.sub("", text)).split()) 

156 

157 

158# Parts of a document. 

159 

160 

161def title_of(document: Document) -> str: 

162 titles = document._data.get("title") or [] 

163 return _clean(titles[0]) if titles else "(no title)" 

164 

165 

166def abstract_of(document: Document) -> str: 

167 return _clean(document._data.get("abstract") or "") 

168 

169 

170def _surname(author: str) -> str: 

171 return author.split(",")[0].strip() 

172 

173 

174def short_authors(document: Document) -> str: 

175 """The authors as a citation names them: ``Kewley``, ``Kewley & Ellison``, ``Kewley et al.``.""" 

176 authors = document._data.get("author") or [] 

177 if not authors: 

178 return "" 

179 surnames = [_surname(author) for author in authors[:3]] 

180 if len(authors) == 1: 

181 return surnames[0] 

182 if len(authors) == 2: 

183 return f"{surnames[0]} & {surnames[1]}" 

184 return f"{surnames[0]} et al." 

185 

186 

187def authors_line(document: Document, limit: int = 8) -> str: 

188 """The first ``limit`` authors in full, and how many more there are.""" 

189 authors = document._data.get("author") or [] 

190 shown = "; ".join(authors[:limit]) 

191 more = len(authors) - limit 

192 return f"{shown}; and {more} more" if more > 0 else shown 

193 

194 

195def reference(document: Document) -> str: 

196 """Where the document appeared: ``ApJ 880, 125 (2019)``.""" 

197 data = document._data 

198 journal = "" 

199 try: 

200 journal = parse_bibcode(data.get("bibcode") or "")["journal_abbreviation"] 

201 except ValueError: 

202 pass 

203 if Journal.lookup(journal) is None: # the journal part of a preprint's bibcode is not an abbreviation 

204 journal = "" 

205 parts = [journal or data.get("pub") or ""] 

206 if data.get("volume"): 

207 parts.append(str(data["volume"])) 

208 text = " ".join(part for part in parts if part) 

209 pages = data.get("page") or [] 

210 if pages and data.get("volume"): 

211 text += f", {pages[0]}" 

212 if data.get("year"): 

213 text += f" ({data['year']})" 

214 return text.strip() 

215 

216 

217def citations(document: Document) -> str: 

218 count = document._data.get("citation_count") or 0 

219 return f"{count} citation{'' if count == 1 else 's'}" 

220 

221 

222def page_url(document: Document) -> str | None: 

223 """The document's page on SciX.""" 

224 bibcode = document._data.get("bibcode") 

225 return f"{SITE}/abs/{quote(bibcode, safe='&')}/abstract" if bibcode else None 

226 

227 

228def pdf_url(document: Document) -> str | None: 

229 """A link to the full text, the publisher's if there is one; ``None`` if SciX lists none.""" 

230 bibcode = document._data.get("bibcode") 

231 sources = document._data.get("esources") or [] 

232 for source in _PDF_SOURCES: 

233 if bibcode and source in sources: 

234 return f"{SITE}/link_gateway/{quote(bibcode, safe='&')}/{source}" 

235 return None 

236 

237 

238def facts(document: Document) -> str: 

239 """One line about a document: where it appeared, how often it is cited, its bibcode.""" 

240 data = document._data 

241 parts = [reference(document), citations(document)] 

242 if "refereed" in (each.lower() for each in data.get("property") or []): 

243 parts.append("refereed") 

244 elif data.get("doctype"): 244 ↛ 246line 244 didn't jump to line 246 because the condition on line 244 was always true

245 parts.append(str(data["doctype"])) 

246 parts.append(data.get("bibcode") or "") 

247 return " · ".join(part for part in parts if part) 

248 

249 

250# Whole outputs. 

251 

252 

253def found_line(total: int, shown: int, sort: str) -> str: 

254 """``498 documents, newest first; showing 10``.""" 

255 noun = "document" if total == 1 else "documents" 

256 line = f"{total} {noun}" 

257 if total > 1: 257 ↛ 259line 257 didn't jump to line 259 because the condition on line 257 was always true

258 line += f", {SORTS[sort][2]}" 

259 if shown < total: 

260 line += f"; showing {shown}" 

261 return line 

262 

263 

264def listing(documents: Sequence[Document], *, width: int, style: Style, start: int = 1) -> list[str]: 

265 """The documents as a numbered list, three lines each.""" 

266 lines: list[str] = [] 

267 gutter = len(str(start + len(documents) - 1)) + 2 

268 indent = " " * gutter 

269 for number, document in enumerate(documents, start): 

270 if lines: 

271 lines.append("") 

272 title = wrap(title_of(document), width - gutter) 

273 lines.append(style.dim(f"{number:>{gutter - 2}} ") + style.bold(title[0])) 

274 lines.extend(indent + style.bold(line) for line in title[1:]) 

275 who = " · ".join(part for part in (short_authors(document), reference(document), citations(document)) if part) 

276 lines.append(indent + fit(who, width - gutter)) 

277 lines.append(indent + style.accent(document._data.get("bibcode") or "")) 

278 return lines 

279 

280 

281def explanation(interpretation: Interpretation, q: str, sort: str, style: Style) -> list[str]: 

282 """How a search was read, piece by piece, and the query it becomes.""" 

283 lines: list[str] = [] 

284 readings = interpretation.readings 

285 typed = max((width_of(reading.source) for reading in readings), default=0) 

286 kinds = max((len(reading.kind) for reading in readings), default=0) 

287 for reading in readings: 

288 lines.append( 

289 f"{fit(reading.source, typed, pad=True)} {style.accent(fit(reading.kind, kinds, pad=True))} {reading.value}" 

290 ) 

291 if readings: 291 ↛ 293line 291 didn't jump to line 293 because the condition on line 291 was always true

292 lines.append("") 

293 lines.append(f"{style.dim('query')} {q}") 

294 lines.append(f"{style.dim('sort ')} {SORTS[sort][2]}") 

295 lines.extend(style.warn(note) for note in interpretation.notes) 

296 return lines