File size: 9,529 Bytes
dbabef2 5baef2a dbabef2 5baef2a dbabef2 5baef2a dbabef2 5baef2a dbabef2 5baef2a dbabef2 5baef2a dbabef2 5baef2a dbabef2 5baef2a dbabef2 5baef2a dbabef2 5baef2a dbabef2 5baef2a dbabef2 5baef2a dbabef2 5baef2a dbabef2 5baef2a dbabef2 5baef2a dbabef2 5baef2a dbabef2 5baef2a dbabef2 5baef2a dbabef2 5baef2a dbabef2 5baef2a dbabef2 5baef2a dbabef2 5baef2a dbabef2 5baef2a dbabef2 5baef2a dbabef2 5baef2a dbabef2 5baef2a dbabef2 5baef2a dbabef2 5baef2a dbabef2 5baef2a dbabef2 5baef2a dbabef2 5baef2a dbabef2 5baef2a dbabef2 5baef2a dbabef2 5baef2a dbabef2 | 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 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 | from __future__ import annotations
from db.embedder import (
LegalEmbedder
)
from db.vector_store import (
QdrantStore
)
from db.neo4j_store import Neo4jStore
from symspellpy import SymSpell, Verbosity
sym_spell = SymSpell(
max_dictionary_edit_distance=2,
prefix_length=7
)
sym_spell.load_dictionary(
"frequency_dictionary_en_82_765.txt",
term_index=0,
count_index=1
)
def spell_correct(text: str) -> str:
suggestions = sym_spell.lookup_compound(
text,
max_edit_distance=2
)
if suggestions:
return suggestions[0].term
return text
class LegalRetriever:
def __init__(
self,
collection_name: str = "legal_rag"
):
self.embedder = (
LegalEmbedder()
)
self.qdrant = (
QdrantStore(
collection_name=
collection_name
)
)
self.graph = (
Neo4jStore(
uri="bolt://localhost:7687",
username="neo4j",
password="password"
)
)
# =====================================================
# VECTOR SEARCH
# =====================================================
def vector_search(
self,
query: str,
limit: int = 10
):
query_vector = (
self.embedder
.embed_query(
query
)
)
results = (
self.qdrant.search(
query_vector,
limit
)
)
return results.points
# =====================================================
# NODE EXTRACTION
# =====================================================
def extract_nodes(
self,
points
):
nodes = []
seen = set()
for point in points:
payload = point.payload
node_id = payload.get(
"node_id"
)
node_type = payload.get(
"node_type"
)
if not node_id:
continue
if node_id in seen:
continue
seen.add(
node_id
)
nodes.append(
{
"node_id":
node_id,
"node_type":
node_type,
"document":
payload.get(
"document"
)
}
)
return nodes
# =====================================================
# SECTION EXPANSION
# =====================================================
def expand_section(
self,
node_id: str
):
query = """
MATCH (s:Section {id:$id})
OPTIONAL MATCH (s)-[:HAS_CLAUSE]->(c)
OPTIONAL MATCH (s)-[:HAS_EXPLANATION]->(e)
OPTIONAL MATCH (s)-[:HAS_ILLUSTRATION]->(i)
OPTIONAL MATCH (s)-[:REFERENCES]->(r)
RETURN
s,
collect(distinct c) as clauses,
collect(distinct e) as explanations,
collect(distinct i) as illustrations,
collect(distinct r) as references
"""
return (
self.graph.run_query(
query,
{
"id": node_id
}
)
)
# =====================================================
# ARTICLE EXPANSION
# =====================================================
def expand_article(
self,
node_id: str
):
query = """
MATCH (a:Article {id:$id})
OPTIONAL MATCH (a)-[:HAS_CLAUSE]->(c)
OPTIONAL MATCH (a)-[:HAS_PROVISO]->(p)
OPTIONAL MATCH (a)-[:HAS_EXPLANATION]->(e)
OPTIONAL MATCH (a)-[:REFERENCES]->(r)
RETURN
a,
collect(distinct c) as clauses,
collect(distinct p) as provisos,
collect(distinct e) as explanations,
collect(distinct r) as references
"""
return (
self.graph.run_query(
query,
{
"id": node_id
}
)
)
# =====================================================
# CLAUSE EXPANSION
# =====================================================
def expand_clause(
self,
node_id: str
):
query = """
MATCH (c:Clause {id:$id})
OPTIONAL MATCH (c)-[:HAS_SUBCLAUSE]->(s)
RETURN
c,
collect(distinct s) as subclauses
"""
return (
self.graph.run_query(
query,
{
"id": node_id
}
)
)
# =====================================================
# GENERIC EXPANSION
# =====================================================
def expand_node(
self,
node
):
node_type = (
node["node_type"]
)
node_id = (
node["node_id"]
)
if node_type == "Section":
return self.expand_section(
node_id
)
if node_type == "Article":
return self.expand_article(
node_id
)
if node_type == "Clause":
return self.expand_clause(
node_id
)
return []
# =====================================================
# HYBRID RETRIEVAL
# =====================================================
def retrieve(
self,
query: str,
vector_k: int = 10
):
vector_points = (
self.vector_search(
query,
vector_k
)
)
nodes = (
self.extract_nodes(
vector_points
)
)
graph_context = []
for node in nodes:
graph_context.extend(
self.expand_node(
node
)
)
return {
"query":
query,
"vector_results":
vector_points,
"expanded_nodes":
nodes,
"graph_context":
graph_context
}
# =========================================================
# TEST
# =========================================================
if __name__ == "__main__":
searcher = (
LegalRetriever(
collection_name=
"legal_rag"
)
)
hard_queries = [
"attemptive mudder",
"can police arrest me without magistrate permission",
"facts accepted by court without proof",
"government cannot take away my freedom without following law",
"computer records admissible in court",
"person killed while protecting property from robbery",
"proof responsibility of accused",
"maximum time police can keep arrested person before court",
"freedom of speech restrictions",
"when witness statement can be used after witness dies",
"person dies after making statement explaining cause of death"
]
expert_queries = [
"attemptive mudder",
"judical notice",
"burdan of proof",
"wife can testify against husband in criminal case",
"secondary evidence of lost document",
"statement made before death about cause of death",
"when police officer can arrest without warrant",
"person resisting lawful apprehension",
"right of private defence causing death",
"electronic record certificate requirements",
"facts court must presume unless disproved",
"who has burden of proving exception in criminal case",
"anticipatory bail before arrest",
"public document versus private document",
"admission made by agent binding principal",
"constitutional remedy against state action",
"freedom of speech reasonable restrictions",
"offence committed outside india by indian citizen",
"confession made to police officer admissibility",
"expert opinion relevance in court"
]
output_file = "retrieval_results.txt"
with open(output_file, "w", encoding="utf-8") as f:
for query in hard_queries:
query = spell_correct(query)
if not query:
continue
results = searcher.search(
query=query,
limit=10
)
f.write("=" * 100 + "\n")
f.write(f"QUERY: {query}\n")
f.write("=" * 100 + "\n\n")
for rank, result in enumerate(results, start=1):
f.write(f"Rank {rank}\n")
f.write(str(result))
f.write("\n\n")
print(f"Results saved to {output_file}")
# for query in hard_queries:
# if not query:
# continue
# if query.lower() in {
# "exit",
# "quit"
# }:
# break
# results = (
# searcher.search(
# query=query,
# limit=10
# )
# )
# searcher.print_results(
# results
# ) |