summaryrefslogtreecommitdiffstats
path: root/mlscraper/matches.py
blob: 3b039d5f6f50080a4d87d35da2be01d7335c18b8 (plain)
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
"""
Matches are specific elements found on a page that match a sample.
"""
import logging
import typing
from functools import cached_property
from itertools import combinations
from itertools import product

from mlscraper.html import get_relative_depth
from mlscraper.html import get_root_node
from mlscraper.html import get_similarity
from mlscraper.html import HTMLAttributeMatch
from mlscraper.html import HTMLExactTextMatch
from mlscraper.html import Node


class Match:
    """
    Occurrence of a specific sample on a page
    """

    @property
    def root(self) -> Node:
        """
        The lowest element that contains matched elements.
        """
        raise NotImplementedError()

    def has_overlap(self, other_match: "Match"):
        assert isinstance(other_match, Match)

        return (
            # overlap if same root node
            self.root == other_match.root
            # or if one is a parent of the other one
            or self.root.has_ancestor(other_match.root)
            or other_match.root.has_ancestor(self.root)
        )

    @property
    def depth(self):
        """
        How deep inside the DOM the match is.
        """
        # depth of root compared to document
        return self.root.depth

    @property
    def span(self):
        """
        Heuristic for how big of a subtree the match spans.
        """
        raise NotImplementedError()

    def get_similarity_to(self, match: "Match"):
        raise NotImplementedError()


class Extractor:
    """
    Class that extracts values from a node.
    """

    def extract(self, node: Node):
        raise NotImplementedError()


class TextValueExtractor(Extractor):
    """
    Class to extract text from a node.
    """

    def extract(self, node: Node):
        return node.soup.text.strip()

    def __repr__(self):
        return f"<{self.__class__.__name__}>"

    def __hash__(self):
        # todo each instance equals each other instance,
        #  so this holds,
        #  but it isn't pretty
        return 0

    def __eq__(self, other):
        return isinstance(other, TextValueExtractor)


class AttributeValueExtractor(Extractor):
    """
    Extracts a value from the attribute in an html tag.
    """

    attr = None

    def __init__(self, attr):
        self.attr = attr

    def extract(self, node: Node):
        if self.attr in node.soup.attrs:
            return node.soup[self.attr]

    def __repr__(self):
        return f"<{self.__class__.__name__} {self.attr=}>"

    def __hash__(self):
        return self.attr.__hash__()

    def __eq__(self, other):
        return isinstance(other, AttributeValueExtractor) and self.attr == other.attr


class DictMatch(Match):
    match_by_key = None

    def __init__(self, match_by_key: dict):
        self.match_by_key = match_by_key

    @cached_property
    def root(self) -> Node:
        match_roots = [m.root for m in self.match_by_key.values()]
        return get_root_node(match_roots)

    @cached_property
    def span(self):
        # add span from this root to match root
        return sum(
            m.span + get_relative_depth(m.root, self.root)
            for m in self.match_by_key.values()
        )

    def get_similarity_to(self, match: "Match"):
        assert isinstance(match, self.__class__)
        keys = set(self.match_by_key.keys()).intersection(
            set(match.match_by_key.keys())
        )
        return sum(
            self.match_by_key[key].get_similarity_to(match.match_by_key[key])
            for key in keys
        )

    def __repr__(self):
        return f"<{self.__class__.__name__} {self.match_by_key=}>"


class ListMatch(Match):
    matches = None

    def __init__(self, matches: tuple):
        self.matches = matches

    def __repr__(self):
        return f"<{self.__class__.__name__} {self.matches=}>"

    @cached_property
    def root(self) -> Node:
        return get_root_node([m.root for m in self.matches])

    @cached_property
    def span(self):
        return sum(get_relative_depth(m.root, self.root) + m.span for m in self.matches)

    def get_similarity_to(self, match: "Match"):
        assert isinstance(match, self.__class__)
        return sum(
            lm1.get_similarity_to(lm2)
            for lm1, lm2 in product(self.matches, match.matches)
        )


class ValueMatch(Match):
    node = None
    extractor = None

    def __init__(self, node: Node, extractor: Extractor):
        self.node = node
        self.extractor = extractor

    def __repr__(self):
        return f"<{self.__class__.__name__} {self.node=}, {self.extractor=}>"

    @property
    def root(self) -> Node:
        return self.node

    @property
    def span(self):
        return 0

    def get_similarity_to(self, match: "Match"):
        assert isinstance(match, self.__class__)

        if self.extractor != match.extractor:
            return 0

        return get_similarity(self.node, match.node)


def generate_all_value_matches(
    node: Node, item: str
) -> typing.Generator[Match, None, None]:
    logging.info(f"generating all value matches ({node=}, {item=})")
    for html_match in node.find_all(item):
        matched_node = html_match.node
        if isinstance(html_match, HTMLExactTextMatch):
            extractor = TextValueExtractor()
            yield ValueMatch(matched_node, extractor)
        elif isinstance(html_match, HTMLAttributeMatch):
            extractor = AttributeValueExtractor(html_match.attr)
            yield ValueMatch(matched_node, extractor)
        else:
            logging.warning(
                "Cannot deal with HTMLMatch type, ignoring "
                f"({html_match=}, {type(html_match)=}))"
            )


def is_disjoint_match_combination(matches):
    """
    Check if the given matches have no overlap.
    """
    return all(not m1.has_overlap(m2) for m1, m2 in combinations(matches, 2))


def is_dimensions_match(m: Match):
    if not isinstance(m, ValueMatch):
        return False

    if not isinstance(m.extractor, AttributeValueExtractor):
        return False

    return m.extractor.attr in ["width", "height"]