Coverage for app / documents / markdown.py: 100%

72 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-10-31 11:23 +0000

1"""The one Markdown parser a document's body is read with — and the repairs 

2image links in model-written Markdown get. 

3 

4The PDF renderer draws the body with it, and the ``render_document`` tool 

5finds the body's images with it, so an image's link is the same string to 

6both: markdown-it normalises a link (percent-encoding ``ü`` and ``[``), and a 

7stored copy is matched on that normalised form (``DocumentImage.src``). 

8 

9Repairs (:func:`unwrap_link_targets`, :func:`tidy_answer_links`): gpt-oss 

10writes ``![alt]([https://…])`` — its source-id brackets around a link — which 

11every Markdown renderer reads as a link to ``[https:…`` and draws blank; and 

12an answer links a Wikimedia file's *page*, which is HTML, not a picture. 

13""" 

14 

15from __future__ import annotations 

16 

17import re 

18from collections.abc import Iterator 

19from dataclasses import dataclass 

20from typing import Any 

21 

22from markdown_it import MarkdownIt 

23from markdown_it.token import Token 

24 

25#: CommonMark with raw HTML off, plus tables and strikethrough. 

26MD = MarkdownIt("commonmark", {"html": False}).enable("table").enable("strikethrough") 

27 

28 

29@dataclass(frozen=True) 

30class ImageRef: 

31 #: The link as the parser normalised it. 

32 src: str 

33 #: The alt text — what the image shows, and what is drawn without it. 

34 alt: str 

35 

36 

37def _images(tokens: list[Token]) -> Iterator[Token]: 

38 for token in tokens: 

39 if token.type == "inline": 

40 yield from (c for c in token.children or [] if c.type == "image") 

41 

42 

43def image_refs(body: str) -> list[ImageRef]: 

44 """Every distinct image the body shows, in order — wherever it sits: a 

45 paragraph, a heading, a list item or a table cell. A link the parser 

46 refuses outright (``javascript:``) is no image at all; anything else is 

47 listed, however unfetchable, so the tool can say why it was not.""" 

48 refs: list[ImageRef] = [] 

49 seen: set[str] = set() 

50 for image in _images(MD.parse(body or "")): 

51 src = str(image.attrs.get("src") or "") 

52 if src not in seen: 

53 seen.add(src) 

54 refs.append(ImageRef(src, image.content or "")) 

55 return refs 

56 

57 

58#: Code is left as written: fences (an unterminated one runs to the end) and 

59#: inline spans. 

60_CODE = re.compile(r"```.*?(?:```|$)|`[^`\n]*`", re.DOTALL) 

61#: A link or image target that is a URL in square brackets: ``]( [https://…] )``. 

62_BRACKETED_TARGET = re.compile(r"\]\(\s*\[(https?://[^\s\[\]]+)\]\s*\)") 

63#: An image, its https target bare or in angle brackets, and an optional title. 

64_IMAGE = re.compile( 

65 r"(!\[[^\]\n]*\]\()\s*(?:<(https://[^>\s]+)>|(https://[^\s)]+))" 

66 r'(\s+"[^"\n]*")?\s*\)' 

67) 

68 

69 

70def _prose(text: str, repair: Any) -> str: 

71 """``text`` with ``repair`` applied outside code.""" 

72 out: list[str] = [] 

73 last = 0 

74 for code in _CODE.finditer(text): 

75 out.append(repair(text[last : code.start()])) 

76 out.append(code.group(0)) 

77 last = code.end() 

78 out.append(repair(text[last:])) 

79 return "".join(out) 

80 

81 

82def _unwrap(text: str) -> str: 

83 return _BRACKETED_TARGET.sub(r"](\1)", text) 

84 

85 

86def unwrap_link_targets(text: str) -> str: 

87 """``text`` with every link or image target written ``([https://…])`` 

88 unwrapped to ``(https://…)``. Code is left alone. Idempotent.""" 

89 if not text or "](" not in text: 

90 return text 

91 return _prose(text, _unwrap) 

92 

93 

94def normalised_link(url: str) -> str: 

95 """``url`` as the parser reads an image link (``ImageRef.src``).""" 

96 return MD.normalizeLink(url) 

97 

98 

99def relink_images(body: str, relinks: dict[str, str]) -> tuple[str, set[str]]: 

100 """``body`` with each image whose link (as the parser reads it) is a key 

101 of ``relinks`` linking that key's value instead, and the keys it 

102 replaced. Code is left alone, and an image written in a form this does 

103 not rewrite keeps its link.""" 

104 if not body or not relinks: 

105 return body, set() 

106 replaced: set[str] = set() 

107 

108 def images(segment: str) -> str: 

109 def one(m: re.Match[str]) -> str: 

110 src = normalised_link(m.group(2) or m.group(3)) 

111 new = relinks.get(src) 

112 if new is None: 

113 return m.group(0) 

114 replaced.add(src) 

115 return f"{m.group(1)}{new}{m.group(4) or ''})" 

116 

117 return _IMAGE.sub(one, segment) 

118 

119 return _prose(body, images), replaced 

120 

121 

122def tidy_answer_links(text: str, settings: Any) -> str: 

123 """An answer's links made to render: bracketed targets unwrapped, and an 

124 image whose host renders its files to a picture on request linked to that 

125 rendering (``image_sources.fetch_url``) — a Wikimedia file page is a web 

126 page, and an ``<img>`` of it draws nothing. Code is left alone. 

127 Idempotent.""" 

128 if not text or "](" not in text: 

129 return text 

130 from .image_sources import fetch_url 

131 

132 def images(segment: str) -> str: 

133 def one(m: re.Match[str]) -> str: 

134 target = m.group(2) or m.group(3) 

135 rendered = fetch_url(target, settings) 

136 if rendered == target: 

137 return m.group(0) 

138 return f"{m.group(1)}{rendered}{m.group(4) or ''})" 

139 

140 return _IMAGE.sub(one, _unwrap(segment)) 

141 

142 return _prose(text, images)