File size: 2,337 Bytes
6064cea cdb5924 6064cea 5f6d20c 6064cea 5f6d20c 6064cea 5f6d20c 6064cea 5f6d20c 6064cea 5f6d20c 6064cea | 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 | import requests
import os
from dotenv import load_dotenv
load_dotenv()
from google import genai
class LegalQueryRewriter:
def __init__(self, api_key):
self.client = genai.Client(
api_key=api_key
)
def rewrite(
self,
query: str
):
prompt = f"""
You are an Indian legal search expert.
Convert the user question into a concise legal search query suitable for Indian Kanoon.
Rules:
- Include legal concepts.
- Include section names if obvious.
- Remove conversational words.
- Return ONLY the search query.
Question:
{query}
"""
response = (
self.client.models.generate_content(
model="gemini-2.5-flash-lite",
contents=prompt
)
)
return response.text.strip()
class KanoonClient:
def __init__(self):
self.token = os.getenv(
"kanoon_token"
)
self.headers = {
"Authorization":
f"Token {self.token}"
}
self.rewriter = LegalQueryRewriter(
api_key=os.getenv("GEMINI_API_KEY")
)
def search(
self,
query: str
):
url = (
"https://api.indiankanoon.org/search/"
)
response = requests.post(
url,
headers=self.headers,
data={
"formInput": query
}
)
return response.json()
def get_document(
self,
doc_id: str
):
url = (
f"https://api.indiankanoon.org/doc/{doc_id}/"
)
response = requests.get(
url,
headers=self.headers
)
return response.json()
def retrieve(self, query: str, top_k: int = 5):
kanoon_query = self.rewriter.rewrite(query) or query
search_results = self.search(kanoon_query)
judgments = []
for doc in search_results.get("docs", [])[:top_k]:
doc_id = doc.get("tid") or doc.get("id")
if not doc_id:
continue
try:
full_doc = self.get_document(doc_id)
judgments.append(full_doc)
except Exception as e:
print(f"Failed to fetch {doc_id}: {e}")
return judgments |