Spaces:
Sleeping
Sleeping
Upload 3 files
Browse files- src/__init__.py +0 -0
- src/data_processor.py +105 -0
- src/hybrid_retriever.py +568 -0
src/__init__.py
ADDED
|
File without changes
|
src/data_processor.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
import re
|
| 4 |
+
|
| 5 |
+
class LegalDocProcessor:
|
| 6 |
+
def __init__(self, parent_path, child_path):
|
| 7 |
+
self.parent_path = parent_path
|
| 8 |
+
self.child_path = child_path
|
| 9 |
+
# RECOMENDED: Simplify these to base keywords for maximum "looseness"
|
| 10 |
+
self.allowed_sources = [
|
| 11 |
+
"Constitution",
|
| 12 |
+
"Criminal Code",
|
| 13 |
+
"Civil Code",
|
| 14 |
+
"Electronic Transactions",
|
| 15 |
+
"Domestic Violence",
|
| 16 |
+
"Human Trafficking",
|
| 17 |
+
"Motor Vehicles",
|
| 18 |
+
"Labor Act",
|
| 19 |
+
"Income Tax",
|
| 20 |
+
"Banking",
|
| 21 |
+
"Consumer Protection",
|
| 22 |
+
"Environment",
|
| 23 |
+
"Citizenship",
|
| 24 |
+
"Witchcraft",
|
| 25 |
+
"Acid",
|
| 26 |
+
"Muluki Ain",
|
| 27 |
+
"Land Act",
|
| 28 |
+
"Public Health",
|
| 29 |
+
"Copyright Act",
|
| 30 |
+
"Education Act",
|
| 31 |
+
"Public Health",
|
| 32 |
+
"Banks",
|
| 33 |
+
"Companies Act",
|
| 34 |
+
"Muluki Civil",
|
| 35 |
+
"Children's Act",
|
| 36 |
+
"National Women Commission",
|
| 37 |
+
"Public",
|
| 38 |
+
"Discrimination",
|
| 39 |
+
"Social",
|
| 40 |
+
"Motherhood",
|
| 41 |
+
"Sexual Harassment",
|
| 42 |
+
"Sexual Harassment at the Workplace (Elimination) Act, 2015"
|
| 43 |
+
]
|
| 44 |
+
|
| 45 |
+
def _get_base_clause(self, clause_id):
|
| 46 |
+
if not clause_id: return None
|
| 47 |
+
match = re.match(r"([0-9A-Za-z]+)", str(clause_id))
|
| 48 |
+
return match.group(1) if match else str(clause_id)
|
| 49 |
+
|
| 50 |
+
# NEW HELPER: Reusable loose check
|
| 51 |
+
def _is_source_allowed(self, src_name):
|
| 52 |
+
if not src_name: return False
|
| 53 |
+
src_lower = str(src_name).lower()
|
| 54 |
+
return any(allowed.lower() in src_lower for allowed in self.allowed_sources)
|
| 55 |
+
|
| 56 |
+
def load_and_clean(self):
|
| 57 |
+
parent_lookup = {}
|
| 58 |
+
processed_docs = []
|
| 59 |
+
|
| 60 |
+
# 1. PROCESS PARENTS (Now with loose matching)
|
| 61 |
+
if os.path.exists(self.parent_path):
|
| 62 |
+
with open(self.parent_path, 'r', encoding='utf-8') as f:
|
| 63 |
+
parents = json.load(f)
|
| 64 |
+
for p in parents:
|
| 65 |
+
src = p.get('legal_document_source', "").strip()
|
| 66 |
+
|
| 67 |
+
# LOOSE CHECK APPLIED HERE
|
| 68 |
+
if self._is_source_allowed(src):
|
| 69 |
+
cid = str(p.get('clause_id')).strip().lower()
|
| 70 |
+
# Use (src, cid) to match exactly how children identify parents
|
| 71 |
+
parent_lookup[(src, cid)] = p.get('text')
|
| 72 |
+
|
| 73 |
+
# 2. PROCESS CHILDREN
|
| 74 |
+
if os.path.exists(self.child_path):
|
| 75 |
+
with open(self.child_path, 'r', encoding='utf-8') as f:
|
| 76 |
+
children = json.load(f)
|
| 77 |
+
for child in children:
|
| 78 |
+
src = child.get('legal_document_source', "").strip()
|
| 79 |
+
|
| 80 |
+
# LOOSE CHECK APPLIED HERE
|
| 81 |
+
if not self._is_source_allowed(src):
|
| 82 |
+
continue
|
| 83 |
+
|
| 84 |
+
raw_id = str(child.get('clause_id')).strip().lower()
|
| 85 |
+
raw_p_id = str(child.get('parent_clause_id') or child.get('clause_id')).strip().lower()
|
| 86 |
+
base_p_id = self._get_base_clause(raw_p_id).lower()
|
| 87 |
+
|
| 88 |
+
# Try to find parent using the exact source name found in this chunk
|
| 89 |
+
p_text = parent_lookup.get((src, raw_p_id)) or \
|
| 90 |
+
parent_lookup.get((src, base_p_id), "Parent context not found.")
|
| 91 |
+
|
| 92 |
+
processed_docs.append({
|
| 93 |
+
"search_content": child.get('text', ""),
|
| 94 |
+
"metadata": {
|
| 95 |
+
"clause_id": raw_id,
|
| 96 |
+
"text": child.get('text'),
|
| 97 |
+
"legal_document_source": src,
|
| 98 |
+
"parent_clause_id": base_p_id,
|
| 99 |
+
"parent_clause_text": p_text,
|
| 100 |
+
"chapter": child.get('chapter', ""),
|
| 101 |
+
"part": child.get('part', "")
|
| 102 |
+
}
|
| 103 |
+
})
|
| 104 |
+
|
| 105 |
+
return processed_docs
|
src/hybrid_retriever.py
ADDED
|
@@ -0,0 +1,568 @@
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# src/hybrid_retriever.py
|
| 2 |
+
import numpy as np
|
| 3 |
+
import faiss
|
| 4 |
+
import re
|
| 5 |
+
import pickle
|
| 6 |
+
import os
|
| 7 |
+
from sentence_transformers import SentenceTransformer, CrossEncoder
|
| 8 |
+
from rank_bm25 import BM25Okapi
|
| 9 |
+
|
| 10 |
+
class HybridRetriever:
|
| 11 |
+
def __init__(self, documents=None, index_dir="index_storage"):
|
| 12 |
+
self.index_dir = index_dir
|
| 13 |
+
|
| 14 |
+
# 1. Hardcoded Source Mapping
|
| 15 |
+
self.alias_map = {
|
| 16 |
+
"constitution": "Constitution of Nepal, 2015",
|
| 17 |
+
"criminal": "National Criminal Code, 2017 AD",
|
| 18 |
+
"penal": "National Criminal Code, 2017 AD",
|
| 19 |
+
"civil": "National Civil Code, 2017 AD",
|
| 20 |
+
"trafficking": "Human Trafficking and Transportation (Control) Act, 2007",
|
| 21 |
+
"cyber": "Electronic Transactions Act, 2063 (2008)",
|
| 22 |
+
"traffic": "Motor Vehicles and Transport Management Act, 2049",
|
| 23 |
+
"labor": "Labor Act, 2074",
|
| 24 |
+
"tax": "Income Tax Act, 2058",
|
| 25 |
+
"banking": "Banks and Financial Institutions Act, 2073",
|
| 26 |
+
"consumer": "Consumer Protection Act, 2075",
|
| 27 |
+
"environment": "Environment Protection Act, 2076",
|
| 28 |
+
"citizenship": "Nepal Citizenship Act, 2006",
|
| 29 |
+
"domestic violence": "Domestic Violence (Crime and Punishment) Act, 2009",
|
| 30 |
+
"dv act": "Domestic Violence (Crime and Punishment) Act, 2009"
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
# 2. KEYWORD TRIGGER MAP: Strictly routes specific topics to Chapters/Parts
|
| 34 |
+
# 2. COMPREHENSIVE TRIGGER MAP (Criminal, Civil, and Constitution)
|
| 35 |
+
self.TRIGGER_MAP = {
|
| 36 |
+
# ============================================================
|
| 37 |
+
# 1. NATIONAL CRIMINAL CODE, 2017 AD
|
| 38 |
+
# ============================================================
|
| 39 |
+
|
| 40 |
+
# General Criminal Principles
|
| 41 |
+
r"\b(criminal justice|conspiracy|abetment|accomplice|sentencing|mitigating|aggravating)\b": {
|
| 42 |
+
"source": "National Criminal Code, 2017 AD",
|
| 43 |
+
"chapter_keywords": ["General Principles of Criminal Justice", "Criminal Conspiracy, Attempt, Abetment and Accomplice", "Punishment and Interim Relief"]
|
| 44 |
+
},
|
| 45 |
+
|
| 46 |
+
# Offences Against the State and Public Order
|
| 47 |
+
r"\b(treason|rebellion|sedition|insurrection|state|public tranquility|riot|unlawful assembly|contempt|public servant|justice|perjury)\b": {
|
| 48 |
+
"source": "National Criminal Code, 2017 AD",
|
| 49 |
+
"chapter_keywords": ["Offences Against the State", "Public Tranquility", "Contempt of Public Servants", "Public Justice"]
|
| 50 |
+
},
|
| 51 |
+
|
| 52 |
+
# Public Health and Safety
|
| 53 |
+
r"\b(public health|adulteration|medicine|safety|morals|obscene|pollution)\b": {
|
| 54 |
+
"source": "National Criminal Code, 2017 AD",
|
| 55 |
+
"chapter_keywords": ["Public Interest, Health, Safety and Morals"]
|
| 56 |
+
},
|
| 57 |
+
|
| 58 |
+
# Weapons and Heritage
|
| 59 |
+
r"\b(weapon|gun|arms|ammunition|explosive|bomb|heritage|ancient monument|archaeological)\b": {
|
| 60 |
+
"source": "National Criminal Code, 2017 AD",
|
| 61 |
+
"chapter_keywords": ["Arms and Ammunitions", "Explosives", "National and Public Heritage"]
|
| 62 |
+
},
|
| 63 |
+
|
| 64 |
+
# Discrimination and Religion (Criminal)
|
| 65 |
+
r"\b(untouchability|discrimination|degrading treatment|caste|religion|religious site|blasphemy)\b": {
|
| 66 |
+
"source": "National Criminal Code, 2017 AD",
|
| 67 |
+
"chapter_keywords": ["Religion-related Offences", "Discrimination and Degrading Treatment"]
|
| 68 |
+
},
|
| 69 |
+
|
| 70 |
+
# Violence Against Human Body
|
| 71 |
+
r"\b(assault|beating|hurt|grievous hurt|acid|injury)\b": {
|
| 72 |
+
"source": "National Criminal Code, 2017 AD",
|
| 73 |
+
"chapter_keywords": ["Human Body and Assault", "Hurt/Grievous Hurt"]
|
| 74 |
+
},
|
| 75 |
+
|
| 76 |
+
r"\b(homicide|killing|kill|killed|kills|murdered|murder)\b": {
|
| 77 |
+
"source": "National Criminal Code, 2017 AD",
|
| 78 |
+
"chapter_keywords": ["Offences Relating to Human Body","Homicide"]
|
| 79 |
+
},
|
| 80 |
+
|
| 81 |
+
# Liberty and Kidnapping
|
| 82 |
+
r"\b(detention|arrest|disappearance|kidnapping|hostage|abduction|unlawful detention)\b": {
|
| 83 |
+
"source": "National Criminal Code, 2017 AD",
|
| 84 |
+
"chapter_keywords": ["Unlawful Detention", "Enforced Disappearance", "Kidnapping/Hostage-taking"]
|
| 85 |
+
},
|
| 86 |
+
|
| 87 |
+
# Pregnancy and Sexual Offences
|
| 88 |
+
r"\b(abortion|pregnancy|foetus|rape)\b": {
|
| 89 |
+
"source": "National Criminal Code, 2017 AD",
|
| 90 |
+
"chapter_keywords": ["Protection of Pregnancy", "Sexual Offences"]
|
| 91 |
+
},
|
| 92 |
+
r"\b(sexual harassement|sexual harassment|workplace harassement|workplace harassment)\b":{
|
| 93 |
+
"sources":["National Criminal Code, 2017 AD","Sexual Harassment at the Workplace (Elimination) Act, 2015"],
|
| 94 |
+
"chapter_keywords":["Sexual Offences","Sexual Harassment"]
|
| 95 |
+
|
| 96 |
+
},
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
# Financial Crimes (Theft, Fraud, Forgery)
|
| 101 |
+
r"\b(theft|robbery|stealing|burglary|robbed|stole|steals|robs|robbing)\b": {
|
| 102 |
+
"source": "National Criminal Code, 2017 AD",
|
| 103 |
+
"chapter_keywords": ["Theft and Robbery"]
|
| 104 |
+
},
|
| 105 |
+
r"\b(cheating|fraud|forgery|fake document|extortion|breach of trust)\b": {
|
| 106 |
+
"source": "National Criminal Code, 2017 AD",
|
| 107 |
+
"chapter_keywords": ["Offences Relating to Documents"]
|
| 108 |
+
},
|
| 109 |
+
|
| 110 |
+
r"\b(stamp|stamps)\b": {
|
| 111 |
+
"source": "National Criminal Code, 2017 AD",
|
| 112 |
+
"chapter_keywords": ["Stamps"]
|
| 113 |
+
},
|
| 114 |
+
|
| 115 |
+
# Privacy and Animal Cruelty
|
| 116 |
+
r"\b(animal|killing animal|cow|bull|bird|dog)\b": {
|
| 117 |
+
"source": "National Criminal Code, 2017 AD",
|
| 118 |
+
"chapter_keywords": ["Animals and Birds","Animals","Birds"]
|
| 119 |
+
},
|
| 120 |
+
r"\b(child abuse|sexual abuse of a minor|sexual abuse of minor|sexual abuse of a child)":{
|
| 121 |
+
"sources": ["National Criminal Code, 2017 AD","Children's Act, 2018"],
|
| 122 |
+
"chapter_keywords": ["Sexual"]
|
| 123 |
+
},
|
| 124 |
+
r"\b(privacy|wiretapping|confidentiality|eavesdropping)\b":{
|
| 125 |
+
"source":"National Criminal Code, 2017 AD",
|
| 126 |
+
"chapter_keywords":["Privacy Offences","Privacy"]
|
| 127 |
+
},
|
| 128 |
+
|
| 129 |
+
# Medical Negligence
|
| 130 |
+
r"\b(medical|doctor|negligence|surgery|treatment|wrong treatment)\b": {
|
| 131 |
+
"source": "National Criminal Code, 2017 AD",
|
| 132 |
+
"chapter_keywords": ["Medical Treatment Offences"]
|
| 133 |
+
},
|
| 134 |
+
|
| 135 |
+
# ============================================================
|
| 136 |
+
# 2. NATIONAL CIVIL CODE, 2017 AD
|
| 137 |
+
# ============================================================
|
| 138 |
+
|
| 139 |
+
# Persons and Rights
|
| 140 |
+
r"\b(natural person|legal person|minor|incapacity|bankruptcy|civil rights)\b": {
|
| 141 |
+
"source": "National Civil Code, 2017 AD",
|
| 142 |
+
"chapter_keywords": ["Natural Persons", "Legal Persons", "Bankruptcy of Natural Persons", "Civil Rights"]
|
| 143 |
+
},
|
| 144 |
+
|
| 145 |
+
# Marriage and Family (Civil aspects)
|
| 146 |
+
r"\b(marriage|divorce|wedding|wife|husband|separation|alimony|nullity)\b": {
|
| 147 |
+
"sources": ["National Civil Code, 2017 AD", "National Criminal Code, 2017 AD"],
|
| 148 |
+
"chapter_keywords": ["Marriage", "Divorce", "Consequences of Marriage", "Marriage-related"]
|
| 149 |
+
},
|
| 150 |
+
|
| 151 |
+
# Children and Adoption
|
| 152 |
+
r"\b(adoption|adopted|adopt|child|guardian|curatorship|custody|maternal authority|paternal authority)\b": {
|
| 153 |
+
"source": "National Civil Code, 2017 AD",
|
| 154 |
+
"chapter_keywords": ["Relationship of Parents and Children", "Maternal and Paternal Authority", "Guardianship", "Curatorship", "Adoption"]
|
| 155 |
+
},
|
| 156 |
+
|
| 157 |
+
# Inheritance and Property Division
|
| 158 |
+
r"\b(partition|succession|property|inheritance|will|legacy|ancestral property)\b": {
|
| 159 |
+
"source": "National Civil Code, 2017 AD",
|
| 160 |
+
"chapter_keywords": ["Partition", "Succession","Property"]
|
| 161 |
+
},
|
| 162 |
+
|
| 163 |
+
# Land and Property Law
|
| 164 |
+
r"\b(property|land|tenancy|ownership|possession|usufruct|servitude|rent|house rent|mortgage|pre-emption|registration of deeds)\b": {
|
| 165 |
+
"source": "National Civil Code, 2017 AD",
|
| 166 |
+
"chapter_keywords": ["General Provisions Relating to Property", "Ownership and Possession", "House Rent", "Mortgage of Immovable Property", "Registration of Deeds"]
|
| 167 |
+
},
|
| 168 |
+
|
| 169 |
+
# Contracts and Obligations
|
| 170 |
+
r"\b(contract|agreement|guarantee|bailment|pledge|deposit|agency|sales|hire-purchase|wages|unjust enrichment|obligation)\b": {
|
| 171 |
+
"source": "National Civil Code, 2017 AD",
|
| 172 |
+
"chapter_keywords": ["Formation of Contracts", "Validity of Contracts", "Performance of Contracts", "Contracts of Sales of Goods", "Contracts of Agency"]
|
| 173 |
+
},
|
| 174 |
+
|
| 175 |
+
# Torts and Liability
|
| 176 |
+
r"\b(tort|torts)\b": {
|
| 177 |
+
"source": "National Civil Code, 2017 AD",
|
| 178 |
+
"chapter_keywords": ["Provisions Relating to Torts"]
|
| 179 |
+
},
|
| 180 |
+
r"\b(damage|compensation|defective product|vicarious liability|defective|damaged|damaged product)\b": {
|
| 181 |
+
"source": "National Civil Code, 2017 AD",
|
| 182 |
+
"chapter_keywords": ["Defective Products"]
|
| 183 |
+
},
|
| 184 |
+
|
| 185 |
+
# ============================================================
|
| 186 |
+
# 3. CONSTITUTION OF NEPAL, 2015
|
| 187 |
+
# ============================================================
|
| 188 |
+
|
| 189 |
+
# Fundamental Rights and Citizenship
|
| 190 |
+
r"\b(fundamental right|citizen|citizenship|freedom|equality|justice|press|speech|expression|rights of woman|rights of dalit)\b": {
|
| 191 |
+
"source": "Constitution of Nepal, 2015",
|
| 192 |
+
"part_keywords": ["Fundamental Rights and Duties", "Citizenship"]
|
| 193 |
+
},
|
| 194 |
+
|
| 195 |
+
# Organs of State (Executive, Legislative, Judiciary)
|
| 196 |
+
r"\b(president|vice-president|prime minister|council of ministers|parliament|house of representatives|national assembly|supreme court|judge|judiciary|attorney general|state legislature)\b": {
|
| 197 |
+
"source": "Constitution of Nepal, 2015",
|
| 198 |
+
"part_keywords": ["Federal Executive", "Federal Legislature", "Judiciary", "President and Vice-President", "Attorney General"]
|
| 199 |
+
},
|
| 200 |
+
|
| 201 |
+
# Federalism and Local Governance
|
| 202 |
+
r"\b(federal|province|local level|municipality|village body|distribution of state power|federal power|provincial power|concurrent power)\b": {
|
| 203 |
+
"source": "Constitution of Nepal, 2015",
|
| 204 |
+
"part_keywords": ["Structure of State and Distribution of State Power", "Interrelations between Federation, State and Local level", "Local Executive", "Local Legislature"]
|
| 205 |
+
},
|
| 206 |
+
|
| 207 |
+
# Constitutional Commissions
|
| 208 |
+
r"\b(ciaa|abuse of authority|corruption commission|auditor general|public service commission|election commission|human rights commission|tharu commission|madhesi commission)\b": {
|
| 209 |
+
"source": "Constitution of Nepal, 2015",
|
| 210 |
+
"part_keywords": ["Commission for the Investigation of Abuse of Authority", "Auditor General", "Public Service Commission", "Election Commission", "National Human Rights Commission"]
|
| 211 |
+
},
|
| 212 |
+
|
| 213 |
+
# Emergency and Security
|
| 214 |
+
r"\b(emergency|crisis|suspension of rights|national security|army|police|political party)\b": {
|
| 215 |
+
"source": "Constitution of Nepal, 2015",
|
| 216 |
+
"part_keywords": ["Emergency Power", "Provision Relating National Security", "Provision relating to Political Parties"]
|
| 217 |
+
},
|
| 218 |
+
|
| 219 |
+
# Symbols and Miscellaneous
|
| 220 |
+
r"\b(flag|anthem|coat of arms|official language|preamble|amendment|schedules)\b": {
|
| 221 |
+
"source": "Constitution of Nepal, 2015",
|
| 222 |
+
"part_keywords": ["Preamble","Amendment to the Constitution", "Short Title, Commencement and Repeal"]
|
| 223 |
+
},
|
| 224 |
+
r"\b(what is nepal|What is nepal|What is Nepal|Nepal|nepal|state of nepal|State of Nepal)\b": {
|
| 225 |
+
"source": "Constitution of Nepal, 2015",
|
| 226 |
+
"part_keywords": ["Preliminary"]
|
| 227 |
+
},
|
| 228 |
+
#Extras
|
| 229 |
+
r"\b(trafficking|human trafficking|selling person|prostitution|transportation of people)\b": {
|
| 230 |
+
"source": "Human Trafficking and Transportation (Control) Act",
|
| 231 |
+
"chapter_keywords": ["Trafficking"] # Empty list means "Match any chapter in this source"
|
| 232 |
+
},
|
| 233 |
+
|
| 234 |
+
# 5. DOMESTIC VIOLENCE ACT
|
| 235 |
+
r"\b(domestic violence|domestic abuse|family violence|protection order|beating wife|husband abuse|beat my wife|beat my husband|husband beats|wife beats)\b": {
|
| 236 |
+
"source": "Domestic Violence (Crime and Punishment) Act",
|
| 237 |
+
"chapter_keywords": ["Domestic Violence"]
|
| 238 |
+
},
|
| 239 |
+
r"\b(women's rights|lineage|reproductive health|safe motherhood|proportional inclusion|equal property|affirmative action|positive discrimination)\b": {
|
| 240 |
+
"source": "Constitution of Nepal, 2015",
|
| 241 |
+
"part_keywords": ["Fundamental Rights"]
|
| 242 |
+
},
|
| 243 |
+
r"\b(citizenship|descent|birth|naturalized|nrn|non-resident|honorary citizenship|district administration office)\b": {
|
| 244 |
+
"source": "Constitution of Nepal, 2015",
|
| 245 |
+
"part_keywords": ["Citizenship"]
|
| 246 |
+
},
|
| 247 |
+
|
| 248 |
+
# === FAMILY and DOMESTIC VIOLENCE ===
|
| 249 |
+
r"\b(domestic violence|domestic abuse|beating wife|mental torture|protection order|economic abuse|family member abuse|physical harm)\b": {
|
| 250 |
+
"source": "Domestic Violence (Crime and Punishment) Act, 2009",
|
| 251 |
+
"chapter_keywords": ["Domestic Violence"]
|
| 252 |
+
},
|
| 253 |
+
r"\b(muslim|nikah|talaq|triple talaq|mahr|dower|polygamy|bigamy|multiple wives)\b": {
|
| 254 |
+
"sources": ["Muluki","Criminal","Civil","Muluki Civil (Code) Act, 2074 (2017), Section 173"],
|
| 255 |
+
"chapter_keywords": ["Marriage", "Divorce","Polygamy","Prohibition of Polygamy"]
|
| 256 |
+
},
|
| 257 |
+
r"\b(prenuptial|postnuptial|alimony|separation of assets|marital property agreement|section 102)\b": {
|
| 258 |
+
"source": "Civil Code",
|
| 259 |
+
"chapter_keywords": ["Marriage", "Divorce", "Property Partition"]
|
| 260 |
+
},
|
| 261 |
+
|
| 262 |
+
# === SPECIFIC CRIMINAL OFFENCES (Muluki Ain / Penal Code) ===
|
| 263 |
+
r"\b(rape|marital rape|sexual assault|sexual exploitation|forced nudity|prostitution|blackmail)\b": {
|
| 264 |
+
"sources": ["Muluki Ain (General Code)","National Criminal Code, 2017 AD"],
|
| 265 |
+
"chapter_keywords": ["Rape", "Sexual Offences"]
|
| 266 |
+
},
|
| 267 |
+
r"\b(acid attack|corrosive|hazardous chemicals|section 193)\b": {
|
| 268 |
+
"sources": ["The Acid and Other Hazardous Chemicals (Regulation) Act", "Criminal Code"],
|
| 269 |
+
"chapter_keywords": ["Hurt and Battery"]
|
| 270 |
+
},
|
| 271 |
+
r"\b(witchcraft|bokxi|boksi|witch|accusation of witch|witch accusation|superstition)\b": {
|
| 272 |
+
"source": "Anti-Witchcraft (Crime and Punishment) Act",
|
| 273 |
+
"chapter_keywords": ["Witchcraft"]
|
| 274 |
+
},
|
| 275 |
+
r"\b(child marriage|age of 20|early marriage)\b": {
|
| 276 |
+
"sources": ["Muluki Ain (General Code)","Children's Act, 2018","National Criminal Code, 2017 AD"],
|
| 277 |
+
"chapter_keywords": ["Child Marriage","Offences Relating to Marriage"]
|
| 278 |
+
},
|
| 279 |
+
r"\b(|abduction|kidnapping)\b": {
|
| 280 |
+
"source": ["National Criminal Code, 2017 AD"],
|
| 281 |
+
"chapter_keywords": ["Abduction"]
|
| 282 |
+
},
|
| 283 |
+
|
| 284 |
+
# === TRAFFIC and VEHICLES (Ma Pa Se, License, Registration) ===
|
| 285 |
+
r"\b(traffic|drunk driving|ma pa se|ma-pa-se|alcohol|speeding|helmet|seatbelt|reckless driving|accident)\b": {
|
| 286 |
+
"source": "Motor Vehicles and Transport Management Act",
|
| 287 |
+
"chapter_keywords": ["Traffic Rules","Traffic"]
|
| 288 |
+
},
|
| 289 |
+
r"\b(license|driving license|10 year validity|renew license|bluebook|registration|embossed plate|number plate|ownership transfer)\b": {
|
| 290 |
+
"source": "Motor Vehicles and Transport Management Act",
|
| 291 |
+
"chapter_keywords": ["Vehicle Registration", "Bluebook"]
|
| 292 |
+
},
|
| 293 |
+
r"\b(insurance|third party|3rd party|liability|beema samiti|comprehensive insurance)\b": {
|
| 294 |
+
"source": "Motor Vehicles and Transport Management Act",
|
| 295 |
+
"chapter_keywords": ["Insurance"]
|
| 296 |
+
},
|
| 297 |
+
|
| 298 |
+
# === LABOR and EMPLOYMENT ===
|
| 299 |
+
r"\b(labor|minimum wage|19550|overtime|overtime pay|maternity leave|paternity leave|sick leave|working hours|8 hours)\b": {
|
| 300 |
+
"source": "Labor Act",
|
| 301 |
+
"chapter_keywords": ["Labor"]
|
| 302 |
+
},
|
| 303 |
+
r"\b(ssf|social security fund|provident fund|gratuity|pension|contribution based)\b": {
|
| 304 |
+
"source": "Contribution-Based Social Security Act",
|
| 305 |
+
"chapter_keywords": ["Social Security"]
|
| 306 |
+
},
|
| 307 |
+
r"\b(termination|dismissal|resignation|labor court|dispute|trade union)\b": {
|
| 308 |
+
"source": "Labor Act, 2074",
|
| 309 |
+
"chapter_keywords": ["Termination", "Dispute Resolution","Labor"]
|
| 310 |
+
},
|
| 311 |
+
|
| 312 |
+
# === CYBER CRIME and ELECTRONIC TRANSACTIONS ===
|
| 313 |
+
r"\b(cyber|hacking|unauthorized access|hacking|computer fraud|online harassment|deepfake|social media scam|phishing|e-wallet fraud|doxxing)\b": {
|
| 314 |
+
"source": "Electronic Transactions Act, 2063 (2008)",
|
| 315 |
+
"chapter_keywords": ["Electronic Transactions"]
|
| 316 |
+
},
|
| 317 |
+
|
| 318 |
+
# === BUSINESS, TAX and BANKING ===
|
| 319 |
+
r"\b(register company|ocr|camis|private limited|sole proprietorship|fdi|foreign investment|repatriation)\b": {
|
| 320 |
+
"source": "Companies Act",
|
| 321 |
+
"chapter_keywords": ["Business Setup"]
|
| 322 |
+
},
|
| 323 |
+
r"\b(tax|income tax|vat|excise|pan|tax slabs|13%|evasion|ird|inland revenue)\b": {
|
| 324 |
+
"source": "Income Tax Act",
|
| 325 |
+
"chapter_keywords": ["Tax","Income Tax"]
|
| 326 |
+
},
|
| 327 |
+
r"\b(banking|nrb|bafia|cheque bounce|aml|cft|money laundering|kyc|blacklisting|loan fraud)\b": {
|
| 328 |
+
"source": "Banks and Financial Institutions Act",
|
| 329 |
+
"chapter_keywords": ["Banks","Financial Institutions"]
|
| 330 |
+
},
|
| 331 |
+
|
| 332 |
+
# === LAND and PROPERTY ===
|
| 333 |
+
r"\b(land|lalpurja|ownership|mohi|tenancy|land ceiling|ropani|land revenue|acquisition|fragmentation)\b": {
|
| 334 |
+
"source": "Land Act",
|
| 335 |
+
"chapter_keywords": ["Land"]
|
| 336 |
+
},
|
| 337 |
+
|
| 338 |
+
# === PUBLIC SERVICES (Health, Education, Reservation) ===
|
| 339 |
+
r"\b(medical negligence|hospital|free basic health|organ transplant|epidemic|doctor|negligence|consumer court)\b": {
|
| 340 |
+
"source": "Public Health",
|
| 341 |
+
"chapter_keywords": ["Public Health", "Medical Law"]
|
| 342 |
+
},
|
| 343 |
+
r"\b(education|compulsory education|grade 1-8|teacher license|scholarship|school licensing|fee regulation)\b": {
|
| 344 |
+
"source": "Education Act, 2028 B.S.",
|
| 345 |
+
"chapter_keywords": ["Education Law"]
|
| 346 |
+
},
|
| 347 |
+
r"\b(reservation|quota|dalit|janajati|madhesi|33% women|inclusion|public service commission|psc)\b": {
|
| 348 |
+
"source": "Constitution of Nepal, 2015",
|
| 349 |
+
"part_keywords": ["Fundamental Rights", "Reservation"]
|
| 350 |
+
},
|
| 351 |
+
|
| 352 |
+
# === CONSUMER and ENVIRONMENT ===
|
| 353 |
+
r"\b(consumer|misleading ad|overcharging|labeling|defective product|fake discount|compensation)\b": {
|
| 354 |
+
"source": "Consumer Protection Act, 2075",
|
| 355 |
+
"chapter_keywords": ["Consumer Protection","Consumer"]
|
| 356 |
+
},
|
| 357 |
+
r"\b(environment|pollution|eia|iee|climate change|solid waste|noise pollution|forest|biodiversity)\b": {
|
| 358 |
+
"source": "Environment Protection Act, 2076",
|
| 359 |
+
"chapter_keywords": ["Environment Protection","Environment"]
|
| 360 |
+
},
|
| 361 |
+
r"\b(copyright|trademark|patent|industrial design|gi|ilam tea|software protection|infringement)\b": {
|
| 362 |
+
"source": "Copyright Act, 2059",
|
| 363 |
+
"chapter_keywords": ["Intellectual Property","Copyright"]
|
| 364 |
+
}
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
}
|
| 368 |
+
|
| 369 |
+
# 3. Models
|
| 370 |
+
self.model = SentenceTransformer('all-MiniLM-L6-v2')
|
| 371 |
+
self.reranker = CrossEncoder('cross-encoder/ms-marco-MiniLM-L-12-v2')
|
| 372 |
+
|
| 373 |
+
if documents is not None:
|
| 374 |
+
self.docs = documents
|
| 375 |
+
self._build_index()
|
| 376 |
+
else:
|
| 377 |
+
self._load_index()
|
| 378 |
+
|
| 379 |
+
def _build_index(self):
|
| 380 |
+
print("[*] Encoding vectors and building BM25...")
|
| 381 |
+
self.raw_texts = [d['search_content'] for d in self.docs]
|
| 382 |
+
embeddings = self.model.encode(self.raw_texts, show_progress_bar=True)
|
| 383 |
+
self.index = faiss.IndexFlatL2(embeddings.shape[1])
|
| 384 |
+
self.index.add(embeddings.astype('float32'))
|
| 385 |
+
tokenized_corpus = [doc.lower().split() for doc in self.raw_texts]
|
| 386 |
+
self.bm25 = BM25Okapi(tokenized_corpus)
|
| 387 |
+
|
| 388 |
+
def save_index(self):
|
| 389 |
+
if not os.path.exists(self.index_dir): os.makedirs(self.index_dir)
|
| 390 |
+
faiss.write_index(self.index, os.path.join(self.index_dir, "faiss.index"))
|
| 391 |
+
with open(os.path.join(self.index_dir, "data.pkl"), "wb") as f:
|
| 392 |
+
pickle.dump({"docs": self.docs, "bm25": self.bm25}, f)
|
| 393 |
+
print(f"[*] Index saved to '{self.index_dir}'")
|
| 394 |
+
|
| 395 |
+
def _load_index(self):
|
| 396 |
+
print("[*] Loading index from disk...")
|
| 397 |
+
self.index = faiss.read_index(os.path.join(self.index_dir, "faiss.index"))
|
| 398 |
+
with open(os.path.join(self.index_dir, "data.pkl"), "rb") as f:
|
| 399 |
+
data = pickle.load(f)
|
| 400 |
+
self.docs = data["docs"]
|
| 401 |
+
self.bm25 = data["bm25"]
|
| 402 |
+
print("[*] Index loaded successfully.")
|
| 403 |
+
|
| 404 |
+
def _parse_query(self, query):
|
| 405 |
+
"""Extracts Source and Clause ID (e.g., 'clause 22')."""
|
| 406 |
+
q = query.lower()
|
| 407 |
+
target_src, target_id = None, None
|
| 408 |
+
for alias, formal in self.alias_map.items():
|
| 409 |
+
if alias in q:
|
| 410 |
+
target_src = formal
|
| 411 |
+
break
|
| 412 |
+
match = re.search(r"\b(clause|section|article|sec|art|no\.?)\s*([0-9a-zA-Z\(\)]+)", q)
|
| 413 |
+
if match:
|
| 414 |
+
target_id = match.group(2).strip().lower()
|
| 415 |
+
return target_src, target_id
|
| 416 |
+
|
| 417 |
+
def _get_active_filters(self, query):
|
| 418 |
+
"""Identifies if the query should be restricted to specific chapters/parts."""
|
| 419 |
+
q = query.lower()
|
| 420 |
+
filters = []
|
| 421 |
+
for pattern, config in self.TRIGGER_MAP.items():
|
| 422 |
+
if re.search(pattern, q):
|
| 423 |
+
filters.append(config)
|
| 424 |
+
return filters
|
| 425 |
+
|
| 426 |
+
def _apply_filters(self, doc_indices, filters):
|
| 427 |
+
if not filters: return doc_indices
|
| 428 |
+
filtered_indices = []
|
| 429 |
+
|
| 430 |
+
def to_str_list(val):
|
| 431 |
+
"""Flatten any value (str, list, nested list) into a flat list of strings."""
|
| 432 |
+
if not val:
|
| 433 |
+
return []
|
| 434 |
+
if isinstance(val, str):
|
| 435 |
+
return [val]
|
| 436 |
+
if isinstance(val, list):
|
| 437 |
+
result = []
|
| 438 |
+
for item in val:
|
| 439 |
+
result.extend(to_str_list(item)) # recurse to handle nesting
|
| 440 |
+
return result
|
| 441 |
+
return [str(val)]
|
| 442 |
+
|
| 443 |
+
for idx in doc_indices:
|
| 444 |
+
doc = self.docs[idx]
|
| 445 |
+
meta = doc['metadata']
|
| 446 |
+
|
| 447 |
+
# Safely handle list-type metadata
|
| 448 |
+
raw_src = meta.get('legal_document_source') or ""
|
| 449 |
+
doc_src = " ".join(to_str_list(raw_src)).lower()
|
| 450 |
+
doc_ch = str(meta.get('chapter') or "").lower()
|
| 451 |
+
doc_part = str(meta.get('part') or "").lower()
|
| 452 |
+
doc_text = str(doc.get('search_content') or "").lower()
|
| 453 |
+
|
| 454 |
+
match_found = False
|
| 455 |
+
for f in filters:
|
| 456 |
+
# 1. Source Match — safely flatten source/sources
|
| 457 |
+
targets = []
|
| 458 |
+
if f.get('source'):
|
| 459 |
+
targets.extend([s.lower() for s in to_str_list(f['source'])])
|
| 460 |
+
if f.get('sources'):
|
| 461 |
+
targets.extend([s.lower() for s in to_str_list(f['sources'])])
|
| 462 |
+
|
| 463 |
+
if not targets:
|
| 464 |
+
continue
|
| 465 |
+
|
| 466 |
+
src_match = any((t in doc_src or doc_src in t) for t in targets)
|
| 467 |
+
|
| 468 |
+
if src_match:
|
| 469 |
+
chapter_kws = [str(kw).lower() for kw in f.get('chapter_keywords', [])]
|
| 470 |
+
part_kws = [str(kw).lower() for kw in f.get('part_keywords', [])]
|
| 471 |
+
all_kws = chapter_kws + part_kws
|
| 472 |
+
|
| 473 |
+
if not all_kws:
|
| 474 |
+
match_found = True
|
| 475 |
+
break
|
| 476 |
+
|
| 477 |
+
meta_match = any(kw in doc_ch for kw in chapter_kws) or \
|
| 478 |
+
any(kw in doc_part for kw in part_kws)
|
| 479 |
+
|
| 480 |
+
if meta_match:
|
| 481 |
+
match_found = True
|
| 482 |
+
break
|
| 483 |
+
|
| 484 |
+
text_match = any(f" {kw} " in f" {doc_text} " for kw in all_kws if len(kw) > 4)
|
| 485 |
+
if text_match:
|
| 486 |
+
match_found = True
|
| 487 |
+
break
|
| 488 |
+
|
| 489 |
+
if match_found:
|
| 490 |
+
filtered_indices.append(idx)
|
| 491 |
+
|
| 492 |
+
return filtered_indices
|
| 493 |
+
|
| 494 |
+
def _rerank(self, query, candidate_docs):
|
| 495 |
+
if not candidate_docs: return []
|
| 496 |
+
pairs = [[query, doc['search_content']] for doc in candidate_docs]
|
| 497 |
+
scores = self.reranker.predict(pairs)
|
| 498 |
+
for i, score in enumerate(scores): candidate_docs[i]['rerank_score'] = score
|
| 499 |
+
return sorted(candidate_docs, key=lambda x: x['rerank_score'], reverse=True)
|
| 500 |
+
|
| 501 |
+
def _deduplicate_and_group(self, flat_results):
|
| 502 |
+
grouped = {}
|
| 503 |
+
for item in flat_results:
|
| 504 |
+
meta = item['metadata']
|
| 505 |
+
parent_key = (meta['legal_document_source'], meta['parent_clause_id'])
|
| 506 |
+
if parent_key not in grouped:
|
| 507 |
+
grouped[parent_key] = {
|
| 508 |
+
"legal_document_source": meta['legal_document_source'],
|
| 509 |
+
"parent_clause_id": meta['parent_clause_id'],
|
| 510 |
+
"parent_clause_text": meta['parent_clause_text'],
|
| 511 |
+
"chapter": meta.get('chapter', 'N/A'),
|
| 512 |
+
"part": meta.get('part', 'N/A'),
|
| 513 |
+
"sub_clauses": [],
|
| 514 |
+
"score": item.get('rerank_score', 0)
|
| 515 |
+
}
|
| 516 |
+
if not any(s['id'] == meta['clause_id'] for s in grouped[parent_key]["sub_clauses"]):
|
| 517 |
+
grouped[parent_key]["sub_clauses"].append({"id": meta['clause_id'], "text": meta['text']})
|
| 518 |
+
return sorted(list(grouped.values()), key=lambda x: x['score'], reverse=True)
|
| 519 |
+
|
| 520 |
+
def hybrid_search(self, query, top_k=5):
|
| 521 |
+
target_src, target_id = self._parse_query(query)
|
| 522 |
+
active_filters = self._get_active_filters(query)
|
| 523 |
+
|
| 524 |
+
# --- PATH 1: DIRECT HIT ---
|
| 525 |
+
raw_results = []
|
| 526 |
+
if target_id:
|
| 527 |
+
for d in self.docs:
|
| 528 |
+
meta = d['metadata']
|
| 529 |
+
id_match = (meta['clause_id'] == target_id or meta['parent_clause_id'] == target_id)
|
| 530 |
+
if target_src:
|
| 531 |
+
if meta['legal_document_source'] == target_src and id_match: raw_results.append(d)
|
| 532 |
+
elif id_match: raw_results.append(d)
|
| 533 |
+
if raw_results: return self._deduplicate_and_group(raw_results)[:top_k]
|
| 534 |
+
|
| 535 |
+
# --- PATH 2: HYBRID SEARCH ---
|
| 536 |
+
search_depth = 1000 if active_filters else 100
|
| 537 |
+
|
| 538 |
+
if active_filters:
|
| 539 |
+
print(f"[*] Strict Filtering Active. Searching deeper (top {search_depth})...")
|
| 540 |
+
|
| 541 |
+
|
| 542 |
+
triggered_names = [f.get('source') or f.get('sources') for f in active_filters]
|
| 543 |
+
if active_filters: print(f"[*] Strict Filtering Active for keywords in: {[f.get('chapter_keywords') or f.get('part_keywords') for f in active_filters]}")
|
| 544 |
+
if active_filters: print(f"Legal Source:{triggered_names}")
|
| 545 |
+
|
| 546 |
+
# Retrieve larger pool for filtering (search_depth = 100 if no filter 500 if filter)
|
| 547 |
+
query_vec = self.model.encode([query]).astype('float32')
|
| 548 |
+
_, v_indices = self.index.search(query_vec, search_depth)
|
| 549 |
+
v_indices = v_indices[0].tolist()
|
| 550 |
+
|
| 551 |
+
scores = self.bm25.get_scores(query.lower().split())
|
| 552 |
+
b_indices = np.argsort(scores)[::-1][:search_depth].tolist()
|
| 553 |
+
|
| 554 |
+
# Apply Metadata Scoping
|
| 555 |
+
v_indices = self._apply_filters(v_indices, active_filters)
|
| 556 |
+
b_indices = self._apply_filters(b_indices, active_filters)
|
| 557 |
+
|
| 558 |
+
# RRF
|
| 559 |
+
rrf_scores = {}
|
| 560 |
+
for rank, idx in enumerate(v_indices): rrf_scores[idx] = rrf_scores.get(idx, 0) + 1/(rank+60)
|
| 561 |
+
for rank, idx in enumerate(b_indices): rrf_scores[idx] = rrf_scores.get(idx, 0) + 1/(rank+60)
|
| 562 |
+
|
| 563 |
+
sorted_idx = sorted(rrf_scores.keys(), key=lambda x: rrf_scores[x], reverse=True)
|
| 564 |
+
top_candidates = [self.docs[i] for i in sorted_idx[:25]]
|
| 565 |
+
|
| 566 |
+
# Rerank and Group
|
| 567 |
+
reranked = self._rerank(query, top_candidates)
|
| 568 |
+
return self._deduplicate_and_group(reranked)[:top_k]
|