File size: 6,834 Bytes
920001b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
import re
import unicodedata
from pathlib import Path

import bm25s
import pandas as pd
from llama_index.core import Document
from llama_index.core.schema import MetadataMode
from llama_index.core.vector_stores.utils import node_to_metadata_dict
from llama_index.retrievers.bm25 import BM25Retriever



PERSIST_PATH = Path("Save_Index_Local")
LP_INFO_FILE = "legal_position_with_categories_documents_all.xlsx"

INDEX_NAME = "bm25_retriever"
USE_META = False

# INDEX_NAME = "bm25_retriever_meta"
# USE_META = True


def clean_string(text: pd.Series):
    text = text.fillna("")
    text = text.str.replace(r"«|»", '"', regex=True)
    text = text.str.replace(r"\xa0", " ")
    text = text.str.replace(r"§", "№")

    # Handle unicode fractions
    text = text.apply(lambda t: unicodedata.normalize("NFKC", t))  # type: ignore
    text = text.str.replace("⁄", "/")

    return text


def find_matching_pattern(categories):
    """
    Search for matching patterns in the categories list and return the first match found.

    Args:
        categories: List of strings or string to search in

    Returns:
        str: Matching pattern or empty string if no match found
    """
    patterns = [
        "Велика Палата",
        "Касаційний кримінальний суд",
        "Касаційний адміністративний суд",
        "Касаційний господарський суд",
        "Касаційний цивільний суд",
    ]

    # Handle both string and list inputs
    if isinstance(categories, str):
        categories = [categories]
    elif isinstance(categories, list):
        # If list contains lists, flatten it
        categories = [item for sublist in categories for item in sublist]

    # Search for patterns
    for category in categories:
        for pattern in patterns:
            if pattern in category:
                return pattern
    return ""


ukrainian_stopwords_1 = [
    "я",
    "ти",
    "він",
    "вона",
    "воно",
    "ми",
    "ви",
    "вони",
    "це",
    "той",
    "така",
    "таке",
    "такі",
    "цей",
    "моя",
    "твоя",
    "його",
    "її",
    "наш",
    "ваш",
    "їх",
    "де",
    "чи",
    "а",
    "але",
    "і",
    "або",
    "так",
    "ні",
    "чи",
    "в",
    "на",
    "з",
    "до",
    "під",
    "через",
    "після",
    "між",
    "серед",
    "без",
    "для",
    "про",
    "о",
    "за",
    "від",
    "до",
    "як",
    "якби",
    "коли",
    "де",
    "тому",
    "тому що",
    "що",
    "чому",
    "хто",
    "що",
    "якось",
    "коли-небудь",
    "де-небудь",
    "чимало",
]

ukrainian_stopwords_2 = [
    # Articles
    "і",
    "й",
    "у",
    "в",
    "та",
    "і",
    # Pronouns
    "я",
    "ти",
    "він",
    "вона",
    "воно",
    "ми",
    "ви",
    "вони",
    "мене",
    "тебе",
    "його",
    "її",
    "нас",
    "вас",
    "їх",
    "мій",
    "твій",
    "наш",
    "ваш",
    "свій",
    # Prepositions
    "з",
    "до",
    "від",
    "біля",
    "над",
    "під",
    "через",
    "для",
    "без",
    "між",
    "серед",
    "крізь",
    "понад",
    "поза",
    "крім",
    # Conjunctions
    "та",
    "і",
    "але",
    "або",
    "однак",
    "проте",
    "тому",
    "тому що",
    "оскільки",
    "якщо",
    "коли",
    "хоча",
    # Auxiliary words
    "так",
    "ні",
    "не",
    "бути",
    "мати",
    "можна",
    "треба",
    # Common filler words
    "цей",
    "той",
    "це",
    "те",
    "такий",
    "який",
    "котрий",
    # Modal words
    "мабуть",
    "напевно",
    "звичайно",
    "можливо",
    # Particles
    "ось",
    "ніби",
    "майже",
    "майже що",
    "саме",
    "лише",
    "тільки",
]

ukrainian_stopwords = list(set(ukrainian_stopwords_1 + ukrainian_stopwords_2))


final_df = pd.read_excel(LP_INFO_FILE)

if USE_META:
    category_columns = [
        col for col in final_df.columns if re.match(r"category_\d+$", col)
    ]

    text_columns = ["title", "text_lp", "category_all"] + category_columns
    final_df[text_columns] = final_df[text_columns].apply(clean_string)

    final_df["category_search"] = final_df[category_columns].apply(
        lambda row: ", ".join([str(val) for val in row if pd.notna(val)]), axis=1
    )
    final_df["category_filter"] = final_df["category_all"].apply(find_matching_pattern)

    legal_position_title_category = [
        Document(
            text=row["text_lp"],  # type: ignore
            metadata={  # type: ignore
                "lp_id": row["id"],
                "title": row["title"],
                "doc_id": row["document_ids"],
                "category_filter": find_matching_pattern(row["category_all"]),
                "category_search": row["category_search"],
            },
            excluded_embed_metadata_keys=["doc_id", "category_filter"],
            excluded_llm_metadata_keys=["doc_id", "category_filter"],
        )
        for _, row in final_df.iterrows()
    ]
else:
    final_df[["title", "text_lp"]] = final_df[["title", "text_lp"]].apply(clean_string)
    legal_position_title_category = [
        Document(
            text=row["text_lp"],  # type: ignore
            metadata={  # type: ignore
                "title": row["title"],
            },
            excluded_embed_metadata_keys=["title"],
            excluded_llm_metadata_keys=["title"],
        )
        for _, row in final_df.iterrows()
    ]


# Copied from BM25Retriever __init__ method, but note that output looks awful and might work worse (this needs checking)
corpus = [node_to_metadata_dict(node) for node in legal_position_title_category]
corpus_tokens = bm25s.tokenize(
    [
        node.get_content(metadata_mode=MetadataMode.EMBED)
        for node in legal_position_title_category
    ],
    stopwords=ukrainian_stopwords,
)

existing_bm25 = bm25s.BM25(
    k1=1.88,
    b=1.25,
    delta=0.5,
    method="robertson",
    # No corpus is saved without this line:
    corpus=corpus,  # prevents TypeError: 'NoneType' object is not subscriptable
)
existing_bm25.index(corpus=corpus_tokens)

bm25_retriever = BM25Retriever(
    existing_bm25=existing_bm25,
    similarity_top_k=20,
)

bm25_retriever.persist(str(PERSIST_PATH / INDEX_NAME))

# Returns an error on invalid corpus
loaded_retriever = BM25Retriever.from_persist_dir(str(PERSIST_PATH / INDEX_NAME))