import json import os import torch import faiss import numpy as np from sentence_transformers import SentenceTransformer from transformers import ( AutoTokenizer, AutoModelForCausalLM, ) # ============================================================ # CONFIG # ============================================================ EMBEDDING_MODEL = ( "intfloat/multilingual-e5-base" ) MODEL_ID = ( "mistralai/Mistral-7B-Instruct-v0.1" ) BASE_DIR = os.path.dirname( os.path.abspath(__file__) ) INDEX_PATH = os.path.join( BASE_DIR, "faiss_index.index", ) METADATA_PATH = os.path.join( BASE_DIR, "embedding_metadata.json", ) # ============================================================ # DEVICE # ============================================================ DEVICE = "cuda" print( f"Using device: {DEVICE}" ) print( f"CUDA available: " f"{torch.cuda.is_available()}" ) # ============================================================ # EMBEDDING MODEL # ============================================================ print( "Loading embedding model..." ) embed_model = SentenceTransformer( EMBEDDING_MODEL, device="cpu", ) print( "Embedding model loaded." ) # ============================================================ # TOKENIZER # ============================================================ print( "Loading Mistral tokenizer..." ) tokenizer = AutoTokenizer.from_pretrained( MODEL_ID, ) if tokenizer.pad_token is None: tokenizer.pad_token = tokenizer.eos_token print( "Tokenizer loaded." ) # ============================================================ # MISTRAL MODEL # ============================================================ print( "Loading Mistral-7B on CUDA..." ) gen_model = AutoModelForCausalLM.from_pretrained( MODEL_ID, torch_dtype=torch.float16, ) gen_model = gen_model.to( DEVICE ) gen_model.eval() print( "Mistral-7B loaded on CUDA." ) # ============================================================ # FAISS # ============================================================ if not os.path.exists(INDEX_PATH): raise FileNotFoundError( f"FAISS index not found: {INDEX_PATH}" ) print( "Loading FAISS index..." ) faiss_index = faiss.read_index( INDEX_PATH ) print( f"FAISS index loaded. " f"Total vectors: {faiss_index.ntotal}" ) # ============================================================ # METADATA # ============================================================ if not os.path.exists(METADATA_PATH): raise FileNotFoundError( f"Metadata file not found: " f"{METADATA_PATH}" ) print( "Loading metadata..." ) with open( METADATA_PATH, "r", encoding="utf-8", ) as f: metadata = json.load(f) print( f"Metadata loaded. " f"Entries: {len(metadata)}" ) # ============================================================ # PROMPT # ============================================================ def build_prompt( query, chunks, ): prompt = f""" You are Court Companion, an AI legal assistant specialized in Pakistani criminal law. Answer the user's question using the provided legal context. Use relevant Pakistani laws such as the Pakistan Penal Code (PPC), Criminal Procedure Code (CrPC), and other applicable Pakistani legal material when supported by the context. If case precedents are present in the context, mention them only when supported by the retrieved material. Do not invent: - legal sections - case names - citations - facts - authorities - legal provisions If the retrieved context is insufficient, clearly state that the available legal context is insufficient to answer confidently. User Question: {query} Relevant Legal Context: """ for i, chunk in enumerate(chunks): if not isinstance(chunk, dict): continue title = chunk.get( "case_number", chunk.get( "title", f"Context {i + 1}", ), ) text = chunk.get( "text", "", ) if not text: text = chunk.get( "content", "", ) if not text: text = chunk.get( "chunk", "", ) text = str( text ).strip() if not text: continue prompt += ( f"\n\n--- {title} ---\n" f"{text}" ) prompt += "\n\nAnswer:\n" return prompt # ============================================================ # RETRIEVAL # ============================================================ def retrieve_chunks( query, k=5, ): if faiss_index.ntotal == 0: return [] k = min( k, faiss_index.ntotal, ) query_embedding = embed_model.encode( f"query: {query}", normalize_embeddings=True, ) query_embedding = np.asarray( query_embedding, dtype="float32", ).reshape( 1, -1, ) scores, indices = faiss_index.search( query_embedding, k, ) chunks = [] for index in indices[0]: if index < 0: continue if index >= len(metadata): continue item = metadata[index] if isinstance(item, dict): chunks.append(item) else: chunks.append( { "text": str(item) } ) return chunks # ============================================================ # CLEAN ANSWER # ============================================================ def filter_response( text, ): unwanted_phrases = [ "I am not a lawyer", "I'm not a lawyer", "I am just an AI", "I'm just an AI", "I can't provide legal advice", "I cannot provide legal advice", ] for phrase in unwanted_phrases: text = text.replace( phrase, "", ) return text.strip() # ============================================================ # GENERATION # ============================================================ def answer_query( user_query, ): if not user_query: return ( "Please provide a legal question." ) user_query = str( user_query ).strip() if not user_query: return ( "Please provide a legal question." ) print( "Retrieving legal context..." ) chunks = retrieve_chunks( user_query, k=5, ) print( f"Retrieved {len(chunks)} chunks." ) prompt = build_prompt( user_query, chunks, ) print( "Tokenizing prompt..." ) inputs = tokenizer( prompt, return_tensors="pt", truncation=True, max_length=7000, ) inputs = { key: value.to(DEVICE) for key, value in inputs.items() } print( "Generating answer..." ) with torch.no_grad(): output_ids = gen_model.generate( **inputs, max_new_tokens=512, temperature=0.7, top_p=0.95, do_sample=True, pad_token_id=tokenizer.eos_token_id, ) # Only take newly generated tokens input_length = inputs[ "input_ids" ].shape[1] generated_ids = output_ids[ 0 ][input_length:] generated_text = tokenizer.decode( generated_ids, skip_special_tokens=True, ) answer = filter_response( generated_text ) print( "Generation completed." ) return answer