dominiks commited on
Commit
62a5a12
·
verified ·
1 Parent(s): f456503

Upload 4 files

Browse files
Files changed (5) hide show
  1. .gitattributes +1 -0
  2. Federal_caselaw_metadata.json +3 -0
  3. README.md +4 -5
  4. app.py +429 -0
  5. requirements.txt +16 -0
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ Federal_caselaw_metadata.json filter=lfs diff=lfs merge=lfs -text
Federal_caselaw_metadata.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5b388c1ea23e3265e9117bc49d6ea0f65d8ef8cb071f59dc2d65df6bc437a9fd
3
+ size 132147090
README.md CHANGED
@@ -1,12 +1,11 @@
1
  ---
2
- title: Federal Caselaw Index
3
- emoji:
4
- colorFrom: yellow
5
  colorTo: green
6
  sdk: gradio
7
  sdk_version: 5.23.1
8
  app_file: app.py
9
  pinned: false
 
10
  ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: Federal Caselaw Index (with metadata-based reranker)
3
+ emoji: 📈
4
+ colorFrom: pink
5
  colorTo: green
6
  sdk: gradio
7
  sdk_version: 5.23.1
8
  app_file: app.py
9
  pinned: false
10
+ short_description: Federal caselaw with metadata-based reranker
11
  ---
 
 
app.py ADDED
@@ -0,0 +1,429 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import spaces
2
+ import bm25s
3
+ import gradio as gr
4
+ import json
5
+ import Stemmer # from PyStemmer
6
+ import time
7
+ import torch
8
+ # from retrieval import *
9
+ import os
10
+ from transformers import AutoTokenizer, AutoModel, pipeline , AutoModelForSequenceClassification, AutoModelForCausalLM
11
+ from sentence_transformers import SentenceTransformer
12
+ import faiss
13
+ import numpy as np
14
+ import pandas as pd
15
+ import torch.nn.functional as F
16
+ from datasets import concatenate_datasets, load_dataset, load_from_disk
17
+ from huggingface_hub import hf_hub_download
18
+ from contextual import ContextualAI
19
+ from openai import AzureOpenAI
20
+ from datetime import datetime
21
+
22
+ """
23
+ # to switch:
24
+ device to cuda
25
+ enable bfloat16
26
+
27
+ """
28
+
29
+
30
+
31
+ sandbox_api_key=os.getenv('AI_SANDBOX_KEY')
32
+ sandbox_endpoint="https://api-ai-sandbox.princeton.edu/"
33
+ sandbox_api_version="2024-02-01"
34
+
35
+ def text_prompt_call(model_to_be_used, system_prompt, user_prompt ):
36
+ client_gpt = AzureOpenAI(
37
+ api_key=sandbox_api_key,
38
+ azure_endpoint = sandbox_endpoint,
39
+ api_version=sandbox_api_version # current api version not in preview
40
+ )
41
+ response = client_gpt.chat.completions.create(
42
+ model=model_to_be_used,
43
+ temperature=0.7, # temperature = how creative/random the model is in generating response - 0 to 1 with 1 being most creative
44
+ max_tokens=1000, # max_tokens = token limit on context to send to the model
45
+ messages=[
46
+ {"role": "system", "content": system_prompt}, # describes model identity and purpose
47
+ {"role": "user", "content": user_prompt}, # user prompt
48
+ ]
49
+ )
50
+ return response.choices[0].message.content
51
+
52
+
53
+
54
+ api_key = os.getenv("contextual_apikey")
55
+ base_url = "https://api.contextual.ai/v1"
56
+ rerank_api_endpoint = f"{base_url}/rerank"
57
+ reranker = "ctxl-rerank-en-v1-instruct"
58
+ client = ContextualAI (api_key = api_key, base_url = base_url)
59
+
60
+
61
+ #instruction_model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-7B-Instruct", torch_dtype=torch.bfloat16, device_map="auto")
62
+ #instruction_tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-7B-Instruct")
63
+
64
+ def update_instruction(query):
65
+ system_prompt_instructions = """You are given a query and an instruction. Modify the instruction to prioritize the types of documents the query specifies. If the query asks for specific details (e.g., court level, timeframe, citation importance), incorporate those details into the instruction while maintaining its original structure. If the query does not specify particular document preferences, return "not applicable."
66
+
67
+ Example 1
68
+
69
+ Query: Find me older appellate court opinions on whether officers can always order passengers out of a car.
70
+ Instruction: Prioritize older appellate court opinions
71
+
72
+ Example 2
73
+
74
+ Query: Show me recent Supreme Court rulings on digital privacy rights.
75
+ Output: Prioritize recent Supreme Court opinions.
76
+
77
+ Example 3
78
+
79
+ Query: Find legal opinions on self-defense laws.
80
+ Output: not applicable
81
+
82
+ Example 4
83
+ Query: Locate federal district court rulings from the last five years on employer vaccine mandates.
84
+ Output: Prioritize federal district court rulings from the last five years.
85
+
86
+ Example 5
87
+
88
+ Query: Show me influential appellate court decisions on contract interpretation.
89
+ Output: Prioritize influential appellate court decisions.
90
+
91
+ Example 6
92
+
93
+ Query: Find state supreme court cases that discuss the necessity of search warrants for vehicle searches.
94
+ Output: Prioritize state supreme court cases on search warrants for vehicle searches.
95
+
96
+ Example 7
97
+
98
+ Query: Show me legal opinions about landlord-tenant disputes.
99
+ Output: not applicable
100
+ """
101
+
102
+
103
+ """
104
+ messages = [{"role": "system", "content": system_prompt_instructions}]
105
+ messages.append({"role": "user", "content": "Query: " + query})
106
+ example = instruction_tokenizer.apply_chat_template(messages, add_generation_prompt = True, tokenize=True,pad_to_multiple_of=8, do_pan_and_scan=True, return_tensors="pt")
107
+ out = instruction_model.generate(example, max_new_tokens=50)
108
+ updated = instruction_tokenizer.decode(out[0])
109
+ updated = updated.split("<|im_start|>assistant")[-1].split("<|im_end|>")[0].strip()
110
+ """
111
+
112
+ updated = text_prompt_call("gpt-4o", system_prompt_instructions, query)
113
+
114
+ print ("UPDATED INSTRUCTION HERE", updated)
115
+ if updated == "not applicable":
116
+ return "Prioritize Supreme Court opinions or opinions from higher courts. More recent, highly cited and published documents should also be weighted higher."
117
+
118
+ return updated
119
+ # oh god
120
+
121
+
122
+
123
+
124
+
125
+
126
+ def rerank_with_contextual_AI(results):
127
+ instruction = "Prioritize Supreme Court opinions or opinions from higher courts. More recent, highly cited and published documents should also be weighted higher."
128
+ #instruction = rerank_instruction
129
+ query = results[0]["query"]
130
+ docs = [i["text"] for i in results]
131
+ metadata = [i["meta_data"] for i in results]
132
+
133
+ # rewrite instruction if applicable
134
+ instruction = update_instruction(query)
135
+
136
+ rerank_response = client.rerank.create(
137
+ query = query,
138
+ instruction = instruction,
139
+ documents = docs,
140
+ metadata = metadata,
141
+ model = reranker
142
+ ).to_dict()
143
+ print (rerank_response)
144
+ # {'results': [{'index': 3, 'relevance_score': 0.39700255}, {'index': 2, 'relevance_score': 0.38903061}, {'index': 10, 'relevance_score': 0.36989796}, {'index': 8, 'relevance_score': 0.36830357}, {'index': 1, 'relevance_score': 0.36415816}, {'index': 11, 'relevance_score': 0.35778061}, {'index': 0, 'relevance_score': 0.35586735}, {'index': 4, 'relevance_score': 0.32589286}, {'index': 12, 'relevance_score': 0.32589286}, {'index': 7, 'relevance_score': 0.30931122}, {'index': 9, 'relevance_score': 0.30739796}, {'index': 13, 'relevance_score': 0.29145408}, {'index': 5, 'relevance_score': 0.2755102}, {'index': 6, 'relevance_score': 0.27295918}]}
145
+
146
+ #ok, what next?
147
+ reranked_docs = []
148
+ for i in rerank_response["results"]:
149
+ reranked_docs.append(results[i["index"]])
150
+ reranked_docs[-1]["relevance_score"] = i["relevance_score"]
151
+ return reranked_docs
152
+
153
+ def format_metadata_for_reranking(metadata):
154
+ try:
155
+ out = metadata["case_name"] + ", " + metadata["court_short_name"] + ", " + "year: " + metadata["date_filed"] + " citation count: " + str(metadata["citation_count"]) + ", precedential status " + metadata["precedential_status"]
156
+ except:
157
+ out = ""
158
+ return out
159
+
160
+
161
+ def format_metadata_as_str(metadata):
162
+ try:
163
+ out = metadata["case_name"] + ", " + metadata["court_short_name"] + ", " + metadata["date_filed"] + ", precedential status " + metadata["precedential_status"]
164
+ except:
165
+ out = ""
166
+ return out
167
+
168
+ def show_user_query(user_message, history):
169
+ '''
170
+ Displays user query in the chatbot and removes from textbox.
171
+ :param user_message: user query inputted.
172
+ :param history: 2D array representing chatbot-user conversation.
173
+ :return:
174
+ '''
175
+ return "", history + [[user_message, None]]
176
+
177
+
178
+
179
+ def run_extractive_qa(query, contexts):
180
+ extracted_passages = extractive_qa([{"question": query, "context": context} for context in contexts])
181
+ return extracted_passages
182
+
183
+
184
+ @spaces.GPU(duration=15)
185
+ def respond_user_query(history):
186
+ '''
187
+ Overwrite the value of current pairing's history with generated text
188
+ and displays response character-by-character with some lag.
189
+ :param history: 2D array of chatbot history filled with user-bot interactions
190
+ :return: history updated with bot's latest message.
191
+ '''
192
+ start_time_global = time.time()
193
+
194
+ query = history[0][0]
195
+ start_time_global = time.time()
196
+
197
+ responses = run_retrieval(query)
198
+ print("--- run retrieval: %s seconds ---" % (time.time() - start_time_global))
199
+ #print (responses)
200
+
201
+ contexts = [individual_response["text"] for individual_response in responses][:NUM_RESULTS]
202
+ extracted_passages = run_extractive_qa(query, contexts)
203
+
204
+ for individual_response, extracted_passage in zip(responses, extracted_passages):
205
+ start, end = extracted_passage["start"], extracted_passage["end"]
206
+ # highlight text
207
+ text = individual_response["text"]
208
+ text = text[:start] + " **" + text[start:end] + "** " + text[end:]
209
+
210
+ # display queries in interface
211
+ formatted_response = "##### "
212
+ if individual_response["meta_data"]:
213
+ formatted_response += individual_response["meta_data"]
214
+ else:
215
+ formatted_response += individual_response["opinion_idx"]
216
+ formatted_response += "\n" + text + "\n\n"
217
+ history = history + [[None, formatted_response]]
218
+ print("--- Extractive QA: %s seconds ---" % (time.time() - start_time_global))
219
+
220
+ return [history, responses]
221
+
222
+ def switch_to_reviewing_framework():
223
+ '''
224
+ Replaces textbox for entering user query with annotator review select.
225
+ :return: updated visibility for textbox and radio button props.
226
+ '''
227
+ return gr.Textbox(visible=False), gr.Dataset(visible=False), gr.Textbox(visible=True, interactive=True), gr.Button(visible=True)
228
+
229
+ def reset_interface():
230
+ '''
231
+ Resets chatbot interface to original position where chatbot history,
232
+ reviewing is invisbile is empty and user input textbox is visible.
233
+ :return: textbox visibility, review radio button invisibility,
234
+ next_button invisibility, empty chatbot
235
+ '''
236
+
237
+ # remove tmp highlighted word documents
238
+ #for fn in os.listdir("tmp-docs"):
239
+ # os.remove(os.path.join("tmp-docs", fn))
240
+ return gr.Textbox(visible=True), gr.Button(visible=False), gr.Textbox(visible=False, value=""), None, gr.JSON(visible=False, value=[]), gr.Dataset(visible=True)
241
+
242
+ ###################################################
243
+ def mark_like(response_json, like_data: gr.LikeData):
244
+ index_of_msg_reviewed = like_data.index[0] - 1 # 0-indexing
245
+ # add liked information to res
246
+ response_json[index_of_msg_reviewed]["is_msg_liked"] = like_data.liked
247
+ return response_json
248
+
249
+ """
250
+ def save_json(name: str, greetings: str) -> None:
251
+
252
+ """
253
+ def register_review(history, additional_feedback, response_json):
254
+ '''
255
+ Writes user review to output file.
256
+ :param history: 2D array representing bot-user conversation so far.
257
+ :return: None, writes to output file.
258
+ '''
259
+
260
+ res = { "user_query": history[0][0],
261
+ "responses": response_json,
262
+ "timestamp": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
263
+ "additional_feedback": additional_feedback
264
+ }
265
+ print (res)
266
+
267
+
268
+ # load search functionality here
269
+
270
+
271
+ def load_bm25():
272
+ stemmer = Stemmer.Stemmer("english")
273
+ retriever = bm25s.BM25.load("NJ_index_LLM_chunking", mmap=False)
274
+ return retriever, stemmer # titles
275
+
276
+ def run_bm25(query):
277
+ query_tokens = bm25s.tokenize(query, stemmer=stemmer)
278
+ results, scores = retriever.retrieve(query_tokens, k=5)
279
+ return results[0]
280
+
281
+ def load_faiss_index(embeddings):
282
+ nb, d = embeddings.shape # database size, dimension
283
+ faiss_index = faiss.IndexFlatL2(d) # build the index
284
+ faiss_index.add(embeddings) # add vectors to the index
285
+ return faiss_index
286
+
287
+ #@spaces.GPU(duration=10)
288
+ def run_dense_retrieval(query):
289
+ if "NV" in model_name:
290
+ query_prefix = "Instruct: Given a question, retrieve passages that answer the question\nQuery: "
291
+ max_length = 32768
292
+ print (query)
293
+ with torch.no_grad():
294
+ query_embeddings = model.encode([query], instruction=query_prefix, max_length=max_length)
295
+ query_embeddings = F.normalize(query_embeddings, p=2, dim=1)
296
+ query_embeddings = query_embeddings.cpu().numpy()
297
+ return query_embeddings
298
+
299
+
300
+ def load_NJ_caselaw():
301
+ if os.path.exists("/scratch/gpfs/ds8100/datasets/NJ_opinions_modernbert_splitter.jsonl"):
302
+ df = pd.read_json("/scratch/gpfs/ds8100/datasets/NJ_opinions_modernbert_splitter.jsonl", lines=True)
303
+ else:
304
+ df = pd.read_json("NJ_opinions_modernbert_splitter.jsonl", lines=True)
305
+ titles, chunks = [],[]
306
+
307
+ for i, row in df.iterrows():
308
+ texts = [i for i in row["texts"] if len(i.split()) > 25 and len(i.split()) < 750]
309
+ texts = [" ".join(i.strip().split()) for i in texts]
310
+ chunks.extend(texts)
311
+ titles.extend([row["id"]] * len(texts))
312
+ ids = list(range(len(titles)))
313
+ assert len(ids) == len(titles) == len(chunks)
314
+ return ids, titles, chunks
315
+
316
+
317
+ def run_retrieval(query):
318
+ query = " ".join(query.split())
319
+
320
+ print ("query", query)
321
+ """
322
+ indices_bm25 = run_bm25(query)
323
+ scores_embeddings, indices_embeddings = run_dense_retrieval(query)
324
+ indices = list(set(indices_bm25).union(indices_embeddings))
325
+ #docs = [{"id":i, "text":chunks[i]} for i in indices]
326
+ docs = [chunks[i] for i in indices]
327
+ results_reranking = rerank(query, docs, indices) #results = [{"doc":docs[i], "score":probs[i], "id":indices[i]} for i in argsort]
328
+ """
329
+ start_time = time.time()
330
+ query_embeddings = run_dense_retrieval(query)
331
+ print("--- Nvidia Embedding: %s seconds ---" % (time.time() - start_time))
332
+ D, I = faiss_index.search(query_embeddings, 45)
333
+ print("--- Faiss retrieval: %s seconds ---" % (time.time() - start_time))
334
+
335
+ scores_embeddings = D[0]
336
+ indices_embeddings = I[0]
337
+
338
+ docs = [chunks[i] for i in indices_embeddings]
339
+ results = [{"id":i, "score":j} for i,j in zip(indices_embeddings, scores_embeddings)]
340
+
341
+ out_dict = []
342
+ covered = set()
343
+ for item in results:
344
+ tmp = {}
345
+ index = item["id"]
346
+ tmp["query"] = query
347
+ tmp["index"] = index #indices[index]
348
+ tmp["NV_score"] = item["score"]
349
+ tmp["opinion_idx"] = str(titles[index])
350
+
351
+ # only recover one paragraph / opinion
352
+ if tmp["opinion_idx"] in covered:
353
+ continue
354
+ covered.add(tmp["opinion_idx"])
355
+
356
+ if tmp["opinion_idx"] in metadata:
357
+ tmp["meta_data"] = format_metadata_for_reranking(metadata[tmp["opinion_idx"]])
358
+ else:
359
+ tmp["meta_data"] = ""
360
+ # so far so good
361
+ tmp["text"] = chunks[tmp["index"]]
362
+ out_dict.append(tmp)
363
+ print (out_dict)
364
+ # and now, rerank
365
+ out_dict = rerank_with_contextual_AI(out_dict)
366
+ return out_dict
367
+
368
+
369
+ NUM_RESULTS = 5
370
+ model_name = 'nvidia/NV-Embed-v2'
371
+
372
+ device = torch.device("cuda")
373
+ #device = torch.device("cpu")
374
+ #device = torch.device("mps")
375
+
376
+ extractive_qa = pipeline("question-answering", model="ai-law-society-lab/extractive-qa-model", tokenizer="FacebookAI/roberta-large", device_map="auto", token=os.getenv('hf_token'))
377
+ ids, titles, chunks = load_NJ_caselaw()
378
+
379
+ ds = load_dataset("ai-law-society-lab/federal-caselaw-embeddings", token=os.getenv('hf_token'))["train"]
380
+ ds = ds.with_format("np")
381
+ print (ds)
382
+ faiss_index = load_faiss_index(ds["embeddings"])
383
+
384
+ with open("Federal_caselaw_metadata.json") as f:
385
+ metadata = json.load(f)
386
+
387
+
388
+ def load_embeddings_model(model_name = "intfloat/e5-large-v2"):
389
+ if "NV" in model_name:
390
+ model = AutoModel.from_pretrained('nvidia/NV-Embed-v2', trust_remote_code=True, torch_dtype=torch.bfloat16, device_map="auto")
391
+ model.eval()
392
+ return model
393
+
394
+ if "NV" in model_name:
395
+ model = load_embeddings_model(model_name=model_name)
396
+
397
+
398
+ examples = ["Can officers always order a passenger out of a car?","Find me briefs about credential searches", "Can police search an impounded car without a warrant?", "State is arguing State v. Carty is not good law"]
399
+
400
+ css = """
401
+ .svelte-i3tvor {visibility: hidden}
402
+ .row.svelte-hrj4a0.unequal-height {
403
+ align-items: stretch !important
404
+ }
405
+ """
406
+
407
+ with gr.Blocks(css=css, theme = gr.themes.Monochrome(primary_hue="pink",)) as demo:
408
+ chatbot = gr.Chatbot(height="45vw", autoscroll=False)
409
+ query_textbox = gr.Textbox()
410
+ #rerank_instruction = gr.Textbox(label="Rerank Instruction Prompt", value="If not otherwise specified in the query, prioritize Supreme Court opinions or opinions from higher courts. More recent, highly cited and published documents should also be weighted higher, unless otherwise specified in the query.")
411
+ examples = gr.Examples(examples, query_textbox)
412
+ response_json = gr.JSON(visible=False, value=[])
413
+ print (response_json)
414
+ chatbot.like(mark_like, response_json, response_json)
415
+
416
+ feedback_textbox = gr.Textbox(label="Additional feedback?", visible=False)
417
+ next_button = gr.Button(value="Submit Feedback", visible=False)
418
+
419
+ query_textbox.submit(show_user_query, [query_textbox, chatbot], [query_textbox, chatbot], queue=False).then(
420
+ respond_user_query, chatbot, [chatbot, response_json]).then(
421
+ switch_to_reviewing_framework, None, [query_textbox, examples.dataset, feedback_textbox, next_button]
422
+ )
423
+
424
+ # Handle page reset and review save in database
425
+ next_button.click(register_review, [chatbot, feedback_textbox, response_json], None).then(
426
+ reset_interface, None, [query_textbox, next_button, feedback_textbox, chatbot, response_json, examples.dataset])
427
+
428
+ # Launch application
429
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ spaces
2
+ --extra-index-url https://download.pytorch.org/whl/cu113
3
+ contextual-client
4
+ openai
5
+ gradio==5.23.1
6
+ accelerate
7
+ bm25s
8
+ PyStemmer
9
+ python-docx
10
+ torch==2.2.0
11
+ faiss-cpu
12
+ sentence-transformers==2.7.0
13
+ transformers==4.37.2
14
+ einops
15
+ numpy<2
16
+ datasets