Skip to content

Commit 627a89c

Browse files
authored
Merge pull request #105 from linkml/ccr-8db10bbe-nmwf03
Read SVG figures as the text they render (#104, phase 1)
2 parents 35fac0f + 3a69728 commit 627a89c

17 files changed

Lines changed: 2349 additions & 24 deletions

File tree

‎docs/concepts/content-types.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ When fetching references, the validator tracks what type of content was retrieve
1111
| `abstract_only` | PMID, DOI | Only the abstract was available |
1212
| `summary` | GEO, BioProject, BioSample, ClinicalTrials | Database summary/description field |
1313
| `local_file` | file: | Content read from local filesystem |
14+
| `local_svg` | file: (`.svg`) | Text an SVG figure renders, a blank line between labels; a quote must fall within one label |
1415
| `url` | url: | Content fetched from web URL |
1516
| `unavailable` | Any | No content could be retrieved |
1617

‎docs/how-to/use-local-files-and-urls.md‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,51 @@ linkml-reference-validator validate text \
105105
url:https://example.com/pangram-examples.html
106106
```
107107

108+
## Diagrams as References (SVG)
109+
110+
A `file:` reference can point at an `.svg` figure, such as a pathway diagram.
111+
The quote is then matched against the text the figure **renders**, not its
112+
markup:
113+
114+
```bash
115+
linkml-reference-validator validate text \
116+
"loss of PTEN activates AKT" \
117+
file:./figures/pathway.svg
118+
```
119+
120+
- Each `<text>` element is one label. A label split over several `<tspan>`
121+
lines can be quoted across the break.
122+
- A quote must fall within one label. A figure with a `PTEN` label and a
123+
separate `activates AKT` label does not support `"PTEN activates AKT"`,
124+
however close together they sit: neither label says it. To cite both, quote
125+
them as separate parts, `"PTEN ... activates AKT"`.
126+
- HTML labels inside `<foreignObject>`, which is how drawio's **Export as SVG**
127+
writes them, are read too.
128+
- Text the reader cannot see is never quotable. That covers `<desc>`, `<title>`,
129+
`<metadata>`, comments, attribute values (`id`, `fill`, `class`, ...),
130+
`<defs>`/`<symbol>` content that no `<use>` draws, and text hidden by
131+
`display:none`, `visibility:hidden`, zero `opacity`, `fill="none"` or a zero
132+
`font-size`, whether set on the element, inherited from a group, or set by a
133+
`<style>` rule.
134+
- If the extractor cannot tell what the figure renders, the reference is
135+
`unavailable` rather than read as raw markup. That happens when a `<style>`
136+
rule hides or shows text through a selector other than a type, class or id
137+
selector (`g > text`, `:first-child`, `@media`), when visibility depends on
138+
`var()` or `calc()`, when a stylesheet is imported or linked, when the SVG
139+
contains a `<script>` or animates visibility, or when something changes the
140+
characters drawn: CSS `content`, a string `list-style-type` or `quotes`,
141+
`-webkit-text-security`, a `unicode-bidi` override, `<bdo>`, or a bidi
142+
control character in the text.
143+
144+
Known limits: a label drawn as several `<text>` elements, one per line, is
145+
read as several labels, so quote its lines with `...` between them. Text
146+
clipped by `clip-path` or `mask`, placed outside the
147+
`viewBox`, scaled to nothing, covered by another shape, drawn in the
148+
background colour, or cut short by CSS `text-overflow` or `-webkit-line-clamp`
149+
is still read. Text converted to outlines is not text and
150+
cannot be quoted. Native `.drawio` files and connector (edge) labels between
151+
nodes are not yet supported.
152+
108153
## Using in Data Files
109154

110155
Both file and URL references work in LinkML data files:
@@ -145,6 +190,8 @@ Both file and URL references work in LinkML data files:
145190

146191
## Limitations
147192

193+
- **Local files are read as text**, apart from `.svg` figures (see above).
194+
An `.html` file is matched against its raw markup.
148195
- **Local PDF files**: Not yet supported as `file:` references. PDFs fetched by `url:` are supported.
149196
- **Authentication**: URLs requiring login are not supported
150197
- **Dynamic content**: JavaScript-rendered pages may not work

‎docs/reference/cache-format.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,8 @@ All other known fields are optional and may be null:
4747
- Bibliography: `title`, `authors`, `journal`, `year`, `doi`, `keywords`, and
4848
`publication_types`.
4949
- Extraction stamps: `extractor_version`, `html_full_text_version`,
50-
`xml_extraction_version`, `url_source_version`, and `absent_content_version`.
50+
`xml_extraction_version`, `url_source_version`, `svg_extraction_version`, and
51+
`absent_content_version`.
5152
- Publication status: `is_preprint` and `peer_review_status`.
5253
- Full-text metadata: `full_text_attempted`, `full_text_declined`,
5354
`full_text_provider`, `full_text_url`, `oa_status`, `license`, `local_pdf_path`,

‎docs/troubleshooting.md‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -915,6 +915,18 @@ the old entry is still served and is not rewritten, so a later run retries.
915915
Other sources are unaffected. With `trust_cached_entries` set, old entries are
916916
served as they are and are not refreshed.
917917

918+
`file:` references to `.svg` figures carry their own stamp,
919+
`svg_extraction_version`. Version 1 reads a figure as the text it renders
920+
(issue #104); before it, the file was cached as raw markup, so a quote could
921+
match a `<desc>`, an attribute value or hidden text. Such an entry is re-read
922+
once on the next validation fetch. **A quote that only matched the markup will
923+
then fail**, which is the point: cite text the figure actually shows. Unlike
924+
other stale entries, an old SVG entry is never served in place of a fresh
925+
read: not when the file has moved, not when the new read finds no rendered
926+
text, and not with `trust_cached_entries`. The file is the source, and its raw
927+
markup is not evidence. Version 2 separates a figure's labels, so a quote is
928+
matched within one label; version 1 entries are re-read once for it.
929+
918930
**A quote that verified against a `url:` page can fail after that refresh.**
919931
Sanitizing removes `<noscript>` and `<template>` elements with their text.
920932
Some publisher pages put a fallback copy of the abstract inside `<noscript>`,

‎pyproject.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ dependencies = [
1919
"linkml-runtime >=1.9.4",
2020
"biopython >= 1.80",
2121
"beautifulsoup4 >= 4.9.0",
22-
"lxml >= 4.9.0",
22+
"lxml >= 5.0.0",
2323
"requests >= 2.28.0",
2424
"pydantic >= 2.0.0",
2525
"ruamel-yaml >= 0.18.0",

‎src/linkml_reference_validator/cache.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ class CacheFrontmatter(BaseModel):
5858
html_full_text_version: int | None = None
5959
xml_extraction_version: int | None = None
6060
url_source_version: int | None = None
61+
svg_extraction_version: int | None = None
6162
absent_content_version: int | None = None
6263
title: str | None = None
6364
authors: list[str] | None = None

‎src/linkml_reference_validator/etl/acquire.py‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""Download bytes from a URL with a size cap, and resolve the content format."""
22

33
import logging
4+
import re
45
import time
56
from pathlib import Path
67
from typing import Optional
@@ -19,6 +20,7 @@
1920
"application/xml": "xml",
2021
"text/xml": "xml",
2122
"text/plain": "text",
23+
"image/svg+xml": "svg",
2224
}
2325

2426
_SUFFIX_FORMATS = {
@@ -27,8 +29,16 @@
2729
".htm": "html",
2830
".xml": "xml",
2931
".txt": "text",
32+
".svg": "svg",
3033
}
3134

35+
#: How much of a payload :func:`sniff_format` reads to find an XML root element.
36+
SNIFF_WINDOW = 64 * 1024
37+
38+
#: The first element of an XML document, past its declaration, comments,
39+
#: processing instructions and doctype.
40+
_ROOT_ELEMENT = re.compile(rb"<([A-Za-z_][\w.:-]*)")
41+
3242

3343
def sniff_format(data: bytes) -> Optional[str]:
3444
"""Identify a format from the leading bytes of a payload, or ``None`` if unknown.
@@ -46,6 +56,14 @@ def sniff_format(data: bytes) -> Optional[str]:
4656
'html'
4757
>>> sniff_format(b"<?xml version='1.0'?><article/>")
4858
'xml'
59+
>>> sniff_format(b'<svg xmlns="http://www.w3.org/2000/svg"/>')
60+
'svg'
61+
>>> sniff_format(b"<?xml version='1.0'?><!-- by Inkscape --><svg/>")
62+
'svg'
63+
>>> sniff_format(b"<!-- Created with Inkscape -->\\n<svg/>")
64+
'svg'
65+
>>> sniff_format(b'\\xef\\xbb\\xbf<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "x"><svg/>')
66+
'svg'
4967
>>> sniff_format(b"just some text") is None
5068
True
5169
>>> sniff_format(b"") is None
@@ -58,11 +76,64 @@ def sniff_format(data: bytes) -> Optional[str]:
5876
head = data[:512].lstrip().lower()
5977
if head.startswith(b"<!doctype html") or head.startswith(b"<html"):
6078
return "html"
79+
# A byte order mark is not markup; Illustrator writes one, and a bare
80+
# <!DOCTYPE svg ...> with no XML declaration.
81+
prolog = head.removeprefix(b"\xef\xbb\xbf")
82+
prolog_starts = (b"<svg", b"<?xml", b"<!--", b"<!doctype svg")
83+
if prolog.startswith(prolog_starts) and _root_element(data) in (b"svg", b"svg:svg"):
84+
return "svg"
6185
if head.startswith(b"<?xml"):
6286
return "xml"
6387
return None
6488

6589

90+
def _root_element(data: bytes) -> Optional[bytes]:
91+
"""Name the root element of an XML payload from its first 64 KB, lowercased.
92+
93+
The window is wide because exporters put licence comments and doctypes
94+
with internal subsets ahead of the root. A comment, declaration or
95+
doctype the window cuts off is still not markup, so nothing after its
96+
start is read as the root; the root is then unknown.
97+
98+
Examples:
99+
>>> _root_element(b'<?xml version="1.0"?><!DOCTYPE svg [<!ENTITY a "b">]><svg/>')
100+
b'svg'
101+
>>> _root_element(b"<!-- <svg> in a comment --><article/>")
102+
b'article'
103+
>>> _root_element(b"<!-- cut off by the window <svg>") is None
104+
True
105+
"""
106+
head = data[:SNIFF_WINDOW]
107+
position = 0
108+
# One forward scan, so a window of unterminated "<!--" stays linear.
109+
while (start := head.find(b"<", position)) != -1:
110+
if head.startswith(b"<!--", start):
111+
end, closing = head.find(b"-->", start + 4), 3
112+
elif head.startswith(b"<?", start):
113+
end, closing = head.find(b"?>", start + 2), 2
114+
elif head[start : start + 9].upper() == b"<!DOCTYPE":
115+
end, closing = _doctype_end(head, start + 9), 1
116+
else:
117+
match = _ROOT_ELEMENT.match(head, start)
118+
return match.group(1).lower() if match else None
119+
if end == -1:
120+
return None
121+
position = end + closing
122+
return None
123+
124+
125+
def _doctype_end(head: bytes, position: int) -> int:
126+
"""Index of the ``>`` closing a doctype, past any internal subset; -1 if absent."""
127+
close = head.find(b">", position)
128+
subset = head.find(b"[", position)
129+
if subset != -1 and (close == -1 or subset < close):
130+
subset_end = head.find(b"]", subset)
131+
if subset_end == -1:
132+
return -1
133+
close = head.find(b">", subset_end)
134+
return close
135+
136+
66137
def resolve_format(
67138
content_type: Optional[str], url: Optional[str], format_hint: Optional[str]
68139
) -> Optional[str]:

‎src/linkml_reference_validator/etl/extract/__init__.py‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
"""Content extractors (PDF, HTML, XML).
1+
"""Content extractors (PDF, HTML, XML, SVG).
22
33
Changing what these produce for the same input does not rewrite the text they
44
already wrote to the reference cache, which is served in preference to a fetch.
@@ -7,7 +7,8 @@
77
:mod:`linkml_reference_validator.etl.reference_fetcher` so existing entries are
88
re-fetched instead of keeping the old output forever. For changes confined to
99
XML table extraction, bump ``XML_EXTRACTION_CACHE_VERSION`` instead; HTML
10-
acceptance has its own ``HTML_FULL_TEXT_CACHE_VERSION``. These format-specific
10+
acceptance has its own ``HTML_FULL_TEXT_CACHE_VERSION``, and SVG extraction
11+
``SVG_EXTRACTION_CACHE_VERSION``. These format-specific
1112
stamps avoid refreshing unchanged formats.
1213
"""
1314

@@ -20,6 +21,7 @@
2021
XMLExtractor,
2122
)
2223
from linkml_reference_validator.etl.extract.pdf import PDFExtractor
24+
from linkml_reference_validator.etl.extract.svg import SVGExtractor
2325

2426
__all__ = [
2527
"MIN_FULLTEXT_CHARS",
@@ -28,4 +30,5 @@
2830
"HTMLExtractor",
2931
"XMLExtractor",
3032
"PDFExtractor",
33+
"SVGExtractor",
3134
]

0 commit comments

Comments
 (0)