Spaces:
Sleeping
Sleeping
Upload 3 files
Browse filesFiles changed (3)
- app.pyAdded+193
- encryption_utils_py.pyAdded+71
- requirement.txtAdded+21
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193# -*- coding: utf-8 -*-"""rag_inference.py
Automatically generated by Colab.
Original file is located at https://colab.research.google.com/drive/1LBqnnCYw5p0PWIacQoD1ZG7AZCx88KeQ"""
from google.colab import drivedrive.mount('/content/drive')
pip install faiss-cpu
from huggingface_hub import loginlogin()
clean_code = '''from sentence_transformers import SentenceTransformerfrom transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig, pipelineimport faissimport jsonimport numpy as npimport torch
# Load embedding modelembed_model = SentenceTransformer("intfloat/multilingual-e5-base")
# Load Mistral-7B-Instruct modelmodel_id = "mistralai/Mistral-7B-Instruct-v0.1"tokenizer = AutoTokenizer.from_pretrained(model_id)
bnb_config = BitsAndBytesConfig(load_in_4bit=True)
gen_model = AutoModelForCausalLM.from_pretrained( model_id, device_map="auto", quantization_config=bnb_config, torch_dtype=torch.float16)
generator = pipeline("text-generation", model=gen_model, tokenizer=tokenizer)
# Load FAISS index and metadataindex_path = "/content/drive/MyDrive/CCC/court_companion_chatbot/faiss_index.index"metadata_path = "/content/drive/MyDrive/CCC/court_companion_chatbot/embedding_metadata.json"
faiss_index = faiss.read_index(index_path)metadata = json.load(open(metadata_path, "r", encoding="utf-8"))
def build_prompt(query, chunks): prompt = ( "You are a legal assistant AI trained specifically on Pakistani criminal law. " "Always cite relevant sections from the Pakistan Penal Code (PPC) or Criminal Procedure Code (CrPC). " "If there is any similar case precedent in the context, mention how the court processed or judged it. " "Provide clear, concise legal answers based on the user's question and the legal context provided.\\n\\n" f"User Query: {query}\\n\\n" "Relevant Legal Context:" )
for i, chunk in enumerate(chunks): context_id = chunk.get("case_number", f"Chunk #{{i+1}}") prompt += f"\\n\\n--- {context_id} ---\\n{{chunk.get('text', '').strip()}}"
prompt += "\\n\\nAnswer (mention specific sections and case precedents where possible):" return prompt
# Retrieve top-k relevant chunksdef retrieve_chunks(query, k=5): query_embedding = embed_model.encode(f"query: {query}", normalize_embeddings=True) scores, indices = faiss_index.search(np.array([query_embedding]).astype("float32"), k) return [metadata[i] | {"text": ""} for i in indices[0]]
# Clean up unwanted phrasesdef filter_response(text): for bad in ["I am not a lawyer", "I'm just an AI", "I can't provide legal"]: text = text.replace(bad, "") return text.strip()
# Final answer functiondef answer_query(user_query): chunks = retrieve_chunks(user_query) prompt = build_prompt(user_query, chunks) response = generator(prompt, max_new_tokens=512, temperature=0.7, top_p=0.95, do_sample=True)[0]["generated_text"] return filter_response(response.replace(prompt, "").strip())'''
with open("/content/drive/MyDrive/CCC/rag_inference.py", "w", encoding="utf-8") as f: f.write(clean_code)
print("β
Mistral-based rag_inference.py saved successfully.")
!pip install bitsandbytes!pip install accelerate!pip install transformers --upgrade
import syssys.path.append('/content/drive/MyDrive/CCC')
from rag_inference import answer_query# print(answer_query("My neighbor accused me of theft and called the police. I have no proof. What can I do?"))
!wget -q -nc https://bin.equinox.io/c/bNyj1mQVY4c/ngrok-stable-linux-amd64.zip!unzip -o ngrok-stable-linux-amd64.zip!mv ngrok /usr/local/bin
!pip install fastapi uvicorn pyngrok nest_asyncio faiss-cpu sentence-transformers transformers
# !ngrok config add-authtoken 2voW7LcwiPnvxj6Hk229R0oV6o5_4wvCsD3nG3Cdi1f5ejFj1# !ngrok version!ngrok config add-authtoken 2voW7LcwiPnvxj6Hk229R0oV6o5_4wvCsD3nG3Cdi1f5ejFj1!fuser -k 8000/tcp!pkill -f ngrok
!pip install pycryptodome
import osimport nest_asyncioimport threadingimport uvicornfrom pyngrok import ngrokfrom fastapi import FastAPIfrom fastapi.middleware.cors import CORSMiddlewarefrom pydantic import BaseModelimport sysimport traceback
# Cleanup BEFORE binding anythingtry: os.system("fuser -k 8000/tcp") # Kill if already runningexcept: pass
try: os.system("pkill -f ngrok")except: pass
# Mount your RAG codesys.path.append('/content/drive/MyDrive/CCC')from rag_inference import answer_queryfrom encryption_utils import encrypt_message, decrypt_message
# FastAPI appapp = FastAPI()app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"],)
class QueryRequest(BaseModel): question: str
@app.post("/ask")def ask(req: QueryRequest): try: raw_input = req.question print("π§Ύ Raw input:", raw_input)
try: decrypted_question = decrypt_message(raw_input) print("π Decrypted:", decrypted_question) except Exception: print("β οΈ Input was not encrypted, using as-is.") decrypted_question = raw_input
answer = answer_query(decrypted_question) answer = answer.encode("utf-8", errors="ignore").decode("utf-8") print("β
Cleaned Answer:", repr(answer)) print("β
Answer:", answer)
encrypted_answer = encrypt_message(answer) return {"answer": encrypted_answer}
except Exception as e: traceback.print_exc() return {"answer": f"ERROR: {str(e)}"}
# Start FastAPI in a separate threaddef run(): uvicorn.run(app, host="0.0.0.0", port=8000)
nest_asyncio.apply()threading.Thread(target=run).start()
# Restart ngrok session!ngrok config add-authtoken 2voW7LcwiPnvxj6Hk229R0oV6o5_4wvCsD3nG3Cdi1f5ejFj1public_url = ngrok.connect(8000)print(f"β
Ngrok URL: {public_url.public_url}")1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071# -*- coding: utf-8 -*-"""encryption_utils.py
Automatically generated by Colab.
Original file is located at https://colab.research.google.com/drive/1KJ6xbIvVJoRB3OzezicrpTGkZBhOjlTm"""
from google.colab import drivedrive.mount('/content/drive')
!pip install cryptography
# from cryptography.fernet import Fernet# print(Fernet.generate_key())
!pip install pycryptodome
# Set file path in Google Drivecode_path = "/content/drive/MyDrive/CCC/encryption_utils.py"
# Write the encryption/decryption utility code using PKCS7 paddingwith open(code_path, "w") as f: f.write("""from Crypto.Cipher import AESfrom Crypto.Util.Padding import pad, unpadfrom Crypto.Random import get_random_bytesimport base64
# AES key in base64 format (must match Flutter)raw_key_b64 = 'KqkSHMHRWxjeMj-72YCOn1AJLleiAlyFGZIEjgMY5iY='
# β
FIXED: Decode using standard base64 with safe replacement and paddingtry: safe_key_b64 = raw_key_b64.replace('-', '+').replace('_', '/') padded_key_b64 = safe_key_b64 + '=' * ((4 - len(safe_key_b64) % 4) % 4) key = base64.b64decode(padded_key_b64)except Exception as e: print(f"β Error decoding key: {e}") raise
def encrypt_message(message: str) -> str: try: iv = get_random_bytes(16) # β
generate random IV (same as Flutter) cipher = AES.new(key, AES.MODE_CBC, iv) padded = pad(message.encode('utf-8'), AES.block_size) encrypted = cipher.encrypt(padded)
combined = iv + encrypted # π prepend IV to ciphertext return base64.b64encode(combined).decode('utf-8') except Exception as e: print(f"β Encryption error: {e}") return f"ENCRYPTION_ERROR:{e}"
def decrypt_message(token: str) -> str: try: raw = base64.b64decode(token)
iv = raw[:16] # π First 16 bytes = IV ciphertext = raw[16:] # π Remaining = encrypted message
cipher = AES.new(key, AES.MODE_CBC, iv) decrypted = cipher.decrypt(ciphertext) return unpad(decrypted, AES.block_size).decode('utf-8') except Exception as e: print(f"β Decryption error: {e}") return f"DECRYPTION_ERROR:{e}"""")
print(f"β
Successfully saved encryption_utils.py to {code_path}")123456789101112131415161718192021{\rtf1\ansi\ansicpg1252\cocoartf2869\cocoatextscaling0\cocoaplatform0{\fonttbl\f0\fswiss\fcharset0 Helvetica;}{\colortbl;\red255\green255\blue255;}{\*\expandedcolortbl;;}\paperw11900\paperh16840\margl1440\margr1440\vieww11520\viewh8400\viewkind0\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\pardirnatural\partightenfactor0
\f0\fs24 \cf0 drive\faiss-cpu\Bitsandbytes\Accelerate\Transform\Os\nest_asyncio\Threading\Pyngrok\Fastapi\Pydantic\Sys\Traceback\}app.pyAdded+193
encryption_utils_py.pyAdded+71
requirement.txtAdded+21