File size: 8,891 Bytes
8e12b39
d136bc8
 
 
 
8e12b39
 
d136bc8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e12b39
d136bc8
 
 
 
 
 
 
 
 
 
 
 
8e12b39
 
 
 
 
 
 
 
 
d136bc8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e12b39
d136bc8
 
 
 
 
 
 
 
 
 
 
 
8e12b39
 
 
 
 
 
 
 
 
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
from typing import Optional

import Levenshtein
import pandas as pd

from .data import read_aste_file, read_sem_eval_file
from .types import CharacterIndices, WordSpan


def get_original_text(
    aste_file: str,
    sem_eval_file: str,
    debug: bool = False,
) -> pd.DataFrame:
    approximate_matches = 0

    def best_match(text: str) -> str:
        comparison = text.replace(" ", "")
        if comparison in comparison_to_text:
            return comparison_to_text[comparison]

        nonlocal approximate_matches
        approximate_matches += 1
        distances = sem_eval_comparison.apply(
            lambda se_comparison: Levenshtein.distance(comparison, se_comparison)
        )
        best = sem_eval_df.iloc[distances.argmin()].text
        return best

    sem_eval_df = read_sem_eval_file(sem_eval_file)
    sem_eval_comparison = sem_eval_df.text.str.replace(" ", "")
    comparison_to_text = dict(zip(sem_eval_comparison, sem_eval_df.text))

    aste_df = read_aste_file(aste_file)
    aste_df = aste_df.rename(columns={"text": "preprocessed_text"})
    aste_df["text"] = aste_df.preprocessed_text.apply(best_match)
    if debug:
        print(f"Read {len(aste_df):,} rows")
        print(f"Had to use {approximate_matches:,} approximate matches")
    return aste_df[["text", "preprocessed_text", "triples"]]


def edit(original: str, preprocessed: str) -> list[Optional[int]]:
    indices: list[Optional[int]] = list(range(len(preprocessed)))
    for operation, _source_position, destination_position in Levenshtein.editops(
        preprocessed, original
    ):
        if operation == "replace":
            indices[destination_position] = None
        elif operation == "insert":
            indices.insert(destination_position, None)
        elif operation == "delete":
            del indices[destination_position]
    return indices


def has_unmapped(indicies: list[Optional[int]]) -> bool:
    return any(index is None for index in indicies)


def has_unmapped_non_space(row: pd.Series) -> bool:
    letter_and_index: list[tuple[str, Optional[int]]] = list(
        zip(row.text, row.text_indices)
    )
    return any(index is None for letter, index in letter_and_index if letter != " ")


def row_to_character_indices(row: pd.Series) -> pd.Series:
    try:
        return pd.Series(
            to_character_indices(
                triplet=row.triples,
                preprocessed=row.preprocessed_text,
                text=row.text,
                text_indices=row.text_indices,
            )
        )
    except:
        print(f"failed to process row {row.name}")
        print(row)
        raise


def to_character_indices(
    *,
    triplet: tuple[tuple[int], tuple[int], str],
    preprocessed: str,
    text: str,
    text_indices: list[Optional[int]],
) -> CharacterIndices:
    def find_start_index(span: WordSpan) -> int:
        # the starting letter in the lookup can be missing or None
        # this would cause a lookup failure
        # to recover from this we can find the following letter index and backtrack
        for index in range(span.start_index, span.end_index):
            try:
                text_index = text_indices.index(index)
                for _ in range(index - span.start_index):
                    if text_index - 1 <= 0:
                        break
                    if text_indices[text_index - 1] is not None:
                        break
                    text_index -= 1
                return text_index
            except ValueError:
                pass
                # not present in list
        raise ValueError(f"cannot find any part of {span}")

    def find_end_index(span: WordSpan) -> int:
        # the ending letter in the lookup can be missing or None
        # this would cause a lookup failure
        # to recover from this we can find the preceding letter index and backtrack
        for index in range(span.end_index - 1, span.start_index - 1, -1):
            try:
                text_index = text_indices.index(index)
                for _ in range(span.end_index - index):
                    if text_index + 1 >= len(text_indices):
                        break
                    if text_indices[text_index + 1] is not None:
                        break
                    text_index += 1
                return text_index
            except ValueError:
                pass
                # not present in list
        raise ValueError(f"cannot find any part of {span}")

    def to_indices(span: tuple[int]) -> tuple[int, int]:
        word_start = span[0]
        word_start_span = word_indices[word_start]

        word_end = span[-1]
        word_end_span = word_indices[word_end]

        start_index = find_start_index(word_start_span)
        end_index = find_end_index(word_end_span)
        return start_index, end_index

    aspect_span, opinion_span, sentiment = triplet
    assert is_sequential(aspect_span), f"aspect span not sequential: {aspect_span}"
    assert is_sequential(opinion_span), f"opinion span not sequential: {opinion_span}"
    assert sentiment in {"POS", "NEG", "NEU"}, f"unknown sentiment: {sentiment}"

    word_indices = WordSpan.to_spans(preprocessed)

    aspect_start_index, aspect_end_index = to_indices(aspect_span)
    aspect_term = text[aspect_start_index : aspect_end_index + 1]
    opinion_start_index, opinion_end_index = to_indices(opinion_span)
    opinion_term = text[opinion_start_index : opinion_end_index + 1]

    nice_sentiment = {
        "POS": "positive",
        "NEG": "negative",
        "NEU": "neutral",
    }[sentiment]

    return CharacterIndices(
        aspect_start_index=aspect_start_index,
        aspect_end_index=aspect_end_index,
        aspect_term=aspect_term,
        opinion_start_index=opinion_start_index,
        opinion_end_index=opinion_end_index,
        opinion_term=opinion_term,
        sentiment=nice_sentiment,
    )


def convert_sem_eval_text(
    aste_file: str,
    sem_eval_file: str,
    debug: bool = False,
) -> pd.DataFrame:
    df = get_original_text(
        aste_file=aste_file,
        sem_eval_file=sem_eval_file,
        debug=debug,
    )
    df = df.explode("triples")
    df = df.reset_index(drop=False)
    df["text_indices"] = df.apply(
        lambda row: edit(original=row.text, preprocessed=row.preprocessed_text),
        axis="columns",
    )
    df = df.merge(
        df.apply(row_to_character_indices, axis="columns"),
        left_index=True,
        right_index=True,
    )
    df = df.drop(columns=["preprocessed_text", "triples", "text_indices"])
    return df


def convert_aste_text(aste_file: str) -> pd.DataFrame:
    df = read_aste_file(aste_file)
    df = df.explode("triples")
    df = df.reset_index(drop=False)
    df = df.merge(
        df.apply(aste_row_to_character_indices, axis="columns"),
        left_index=True,
        right_index=True,
    )
    df = df.drop(columns=["triples"])
    return df


def aste_row_to_character_indices(row: pd.Series) -> pd.Series:
    try:
        return pd.Series(
            aste_to_character_indices(
                triplet=row.triples,
                text=row.text,
            )
        )
    except:
        print(f"failed to process row {row.name}")
        print(row)
        raise


def is_sequential(span: tuple[int]) -> bool:
    return all(span[index + 1] - span[index] == 1 for index in range(len(span) - 1))


def aste_to_character_indices(
    *,
    triplet: tuple[tuple[int], tuple[int], str],
    text: str,
) -> CharacterIndices:
    def to_indices(span: tuple[int]) -> tuple[int, int]:
        word_start = span[0]
        word_start_span = word_indices[word_start]

        word_end = span[-1]
        word_end_span = word_indices[word_end]

        return word_start_span.start_index, word_end_span.end_index - 1

    aspect_span, opinion_span, sentiment = triplet
    assert is_sequential(aspect_span), f"aspect span not sequential: {aspect_span}"
    assert is_sequential(opinion_span), f"opinion span not sequential: {opinion_span}"
    assert sentiment in {"POS", "NEG", "NEU"}, f"unknown sentiment: {sentiment}"

    word_indices = WordSpan.to_spans(text)

    aspect_start_index, aspect_end_index = to_indices(aspect_span)
    aspect_term = text[aspect_start_index : aspect_end_index + 1]
    opinion_start_index, opinion_end_index = to_indices(opinion_span)
    opinion_term = text[opinion_start_index : opinion_end_index + 1]

    nice_sentiment = {
        "POS": "positive",
        "NEG": "negative",
        "NEU": "neutral",
    }[sentiment]

    return CharacterIndices(
        aspect_start_index=aspect_start_index,
        aspect_end_index=aspect_end_index,
        aspect_term=aspect_term,
        opinion_start_index=opinion_start_index,
        opinion_end_index=opinion_end_index,
        opinion_term=opinion_term,
        sentiment=nice_sentiment,
    )