dominiks commited on
Commit
639849f
·
verified ·
1 Parent(s): b9400c5

Upload 2 files

Browse files
Files changed (2) hide show
  1. README.md +4 -4
  2. app_public_version.py +268 -0
README.md CHANGED
@@ -1,11 +1,11 @@
1
  ---
2
- title: NJ Caselaw Index (with 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: NJ caselaw with metadata-based reranker -- work in progress
11
- ---
 
1
  ---
2
+ title: NJ Caselaw Index Prototype
3
  emoji: 📈
4
  colorFrom: pink
5
  colorTo: green
6
  sdk: gradio
7
  sdk_version: 5.23.1
8
+ app_file: app_public_version.py
9
  pinned: false
10
+ short_description: NJ caselaw version 0, work in progress
11
+ ---
app_public_version.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import spaces
2
+ import bm25s
3
+ import gradio as gr
4
+ import json
5
+ import Stemmer
6
+ import time
7
+ import torch
8
+ import os
9
+ from transformers import AutoTokenizer, AutoModel, pipeline , AutoModelForSequenceClassification, AutoModelForCausalLM
10
+ from sentence_transformers import SentenceTransformer
11
+ import faiss
12
+ import numpy as np
13
+ import pandas as pd
14
+ import torch.nn.functional as F
15
+ from datasets import concatenate_datasets, load_dataset, load_from_disk
16
+ from huggingface_hub import hf_hub_download
17
+ from contextual import ContextualAI
18
+ from openai import AzureOpenAI
19
+ from datetime import datetime
20
+ import sys
21
+
22
+
23
+ def format_metadata_as_str(metadata):
24
+ try:
25
+ out = metadata["case_name"] + ", " + metadata["court_short_name"] + ", " + metadata["date_filed"] + ", precedential status " + metadata["precedential_status"]
26
+ except:
27
+ out = ""
28
+ return out
29
+
30
+ def show_user_query(user_message, history):
31
+ '''
32
+ Displays user query in the chatbot and removes from textbox.
33
+ :param user_message: user query inputted.
34
+ :param history: 2D array representing chatbot-user conversation.
35
+ :return:
36
+ '''
37
+ return "", history + [[user_message, None]]
38
+
39
+
40
+ def run_extractive_qa(query, contexts):
41
+ extracted_passages = extractive_qa([{"question": query, "context": context} for context in contexts])
42
+ return extracted_passages
43
+
44
+
45
+ @spaces.GPU(duration=15)
46
+ def respond_user_query(history):
47
+ '''
48
+ Overwrite the value of current pairing's history with generated text
49
+ and displays response character-by-character with some lag.
50
+ :param history: 2D array of chatbot history filled with user-bot interactions
51
+ :return: history updated with bot's latest message.
52
+ '''
53
+ start_time_global = time.time()
54
+
55
+ query = history[0][0]
56
+ start_time_global = time.time()
57
+
58
+ responses = run_retrieval(query)
59
+ print("--- run retrieval: %s seconds ---" % (time.time() - start_time_global))
60
+ #print (responses)
61
+
62
+ contexts = [individual_response["text"] for individual_response in responses][:NUM_RESULTS]
63
+ extracted_passages = run_extractive_qa(query, contexts)
64
+
65
+ for individual_response, extracted_passage in zip(responses, extracted_passages):
66
+ start, end = extracted_passage["start"], extracted_passage["end"]
67
+ # highlight text
68
+ text = individual_response["text"]
69
+ text = text[:start] + " **" + text[start:end] + "** " + text[end:]
70
+
71
+ # display queries in interface
72
+ formatted_response = "##### "
73
+ if individual_response["meta_data"]:
74
+ formatted_response += individual_response["meta_data"]
75
+ else:
76
+ formatted_response += individual_response["opinion_idx"]
77
+ formatted_response += "\n" + text + "\n\n"
78
+ history = history + [[None, formatted_response]]
79
+ print("--- Extractive QA: %s seconds ---" % (time.time() - start_time_global))
80
+
81
+ return [history, responses]
82
+
83
+ def switch_to_reviewing_framework():
84
+ '''
85
+ Replaces textbox for entering user query with annotator review select.
86
+ :return: updated visibility for textbox and radio button props.
87
+ '''
88
+ return gr.Textbox(visible=False), gr.Dataset(visible=False), gr.Textbox(visible=True, interactive=True), gr.Button(visible=True)
89
+
90
+ def reset_interface():
91
+ '''
92
+ Resets chatbot interface to original position where chatbot history,
93
+ reviewing is invisbile is empty and user input textbox is visible.
94
+ :return: textbox visibility, review radio button invisibility,
95
+ next_button invisibility, empty chatbot
96
+ '''
97
+
98
+ # remove tmp highlighted word documents
99
+ #for fn in os.listdir("tmp-docs"):
100
+ # os.remove(os.path.join("tmp-docs", fn))
101
+ return gr.Textbox(visible=True), gr.Button(visible=False), gr.Textbox(visible=False, value=""), None, gr.JSON(visible=False, value=[]), gr.Dataset(visible=True)
102
+
103
+ ###################################################
104
+ def mark_like(response_json, like_data: gr.LikeData):
105
+ index_of_msg_reviewed = like_data.index[0] - 1 # 0-indexing
106
+ # add liked information to res
107
+ response_json[index_of_msg_reviewed]["is_msg_liked"] = like_data.liked
108
+ return response_json
109
+
110
+ """
111
+ def save_json(name: str, greetings: str) -> None:
112
+
113
+ """
114
+ def register_review(history, additional_feedback, response_json):
115
+ '''
116
+ Writes user review to output file.
117
+ :param history: 2D array representing bot-user conversation so far.
118
+ :return: None, writes to output file.
119
+ '''
120
+
121
+ res = { "user_query": history[0][0],
122
+ "responses": response_json,
123
+ "timestamp": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
124
+ "additional_feedback": additional_feedback
125
+ }
126
+ print (res)
127
+
128
+
129
+ # load search functionality here
130
+
131
+
132
+ def load_bm25():
133
+ stemmer = Stemmer.Stemmer("english")
134
+ retriever = bm25s.BM25.load("NJ_index_LLM_chunking", mmap=False)
135
+ return retriever, stemmer # titles
136
+
137
+ def run_bm25(query):
138
+ query_tokens = bm25s.tokenize(query, stemmer=stemmer)
139
+ results, scores = retriever.retrieve(query_tokens, k=5)
140
+ return results[0]
141
+
142
+ def load_faiss_index(embeddings):
143
+ nb, d = embeddings.shape # database size, dimension
144
+ faiss_index = faiss.IndexFlatL2(d) # build the index
145
+ faiss_index.add(embeddings) # add vectors to the index
146
+ return faiss_index
147
+
148
+ #@spaces.GPU(duration=10)
149
+ def run_dense_retrieval(query):
150
+ if "NV" in model_name:
151
+ query_prefix = "Instruct: Given a question, retrieve passages that answer the question\nQuery: "
152
+ max_length = 32768
153
+ print (query)
154
+ with torch.no_grad():
155
+ query_embeddings = model.encode([query], instruction=query_prefix, max_length=max_length)
156
+ query_embeddings = F.normalize(query_embeddings, p=2, dim=1)
157
+ query_embeddings = query_embeddings.cpu().numpy()
158
+ return query_embeddings
159
+
160
+
161
+ def load_NJ_caselaw():
162
+ if os.path.exists("/scratch/gpfs/ds8100/datasets/NJ_opinions_modernbert_splitter.jsonl"):
163
+ df = pd.read_json("/scratch/gpfs/ds8100/datasets/NJ_opinions_modernbert_splitter.jsonl", lines=True)
164
+ else:
165
+ df = pd.read_json("NJ_opinions_modernbert_splitter.jsonl", lines=True)
166
+ titles, chunks = [],[]
167
+
168
+ for i, row in df.iterrows():
169
+ texts = [i for i in row["texts"] if len(i.split()) > 25 and len(i.split()) < 750]
170
+ texts = [" ".join(i.strip().split()) for i in texts]
171
+ chunks.extend(texts)
172
+ titles.extend([row["id"]] * len(texts))
173
+ ids = list(range(len(titles)))
174
+ assert len(ids) == len(titles) == len(chunks)
175
+ return ids, titles, chunks
176
+
177
+
178
+ def run_retrieval(query):
179
+ query = " ".join(query.split())
180
+ print ("query", query)
181
+
182
+ query_embeddings = run_dense_retrieval(query)
183
+ D, I = faiss_index.search(query_embeddings, 45)
184
+ scores_embeddings = D[0]
185
+ indices_embeddings = I[0]
186
+
187
+ results = [{"index":i, "NV_score":j, "text": chunks[i]} for i,j in zip(indices_embeddings, scores_embeddings)]
188
+
189
+ out_dict = []
190
+ covered = set()
191
+ for item in results:
192
+ index = item["index"]
193
+ item["query"] = query
194
+ item["opinion_idx"] = str(titles[index])
195
+
196
+ # only recover one paragraph / opinion
197
+ if item["opinion_idx"] in covered:
198
+ continue
199
+ covered.add(item["opinion_idx"])
200
+
201
+ if item["opinion_idx"] in metadata:
202
+ item["meta_data"] = format_metadata_as_str(metadata[item["opinion_idx"]])
203
+ else:
204
+ item["meta_data"] = ""
205
+ out_dict.append(tmp)
206
+ return out_dict
207
+
208
+
209
+ NUM_RESULTS = 5
210
+ model_name = 'nvidia/NV-Embed-v2'
211
+
212
+ device = torch.device("cuda")
213
+
214
+ 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'))
215
+ ids, titles, chunks = load_NJ_caselaw()
216
+
217
+ ds = load_dataset("ai-law-society-lab/NJ_embeddings", token=os.getenv('hf_token'))["train"]
218
+ ds = ds.with_format("np")
219
+ faiss_index = load_faiss_index(ds["embeddings"])
220
+
221
+
222
+ with open("NJ_caselaw_metadata.json") as f:
223
+ metadata = json.load(f)
224
+
225
+
226
+ def load_embeddings_model(model_name = "intfloat/e5-large-v2"):
227
+ if "NV" in model_name:
228
+ model = AutoModel.from_pretrained('nvidia/NV-Embed-v2', trust_remote_code=True, torch_dtype=torch.bfloat16, device_map="auto")
229
+ #model = AutoModel.from_pretrained('nvidia/NV-Embed-v2', trust_remote_code=True, torch_dtype=torch.float16, device_map="auto")
230
+ model.eval()
231
+ return model
232
+
233
+ if "NV" in model_name:
234
+ model = load_embeddings_model(model_name=model_name)
235
+
236
+
237
+ 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"]
238
+
239
+ css = """
240
+ .svelte-i3tvor {visibility: hidden}
241
+ .row.svelte-hrj4a0.unequal-height {
242
+ align-items: stretch !important
243
+ }
244
+ """
245
+
246
+ with gr.Blocks(css=css, theme = gr.themes.Monochrome(primary_hue="pink",)) as demo:
247
+ chatbot = gr.Chatbot(height="45vw", autoscroll=False)
248
+ query_textbox = gr.Textbox()
249
+ #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.")
250
+ examples = gr.Examples(examples, query_textbox)
251
+ response_json = gr.JSON(visible=False, value=[])
252
+ print (response_json)
253
+ chatbot.like(mark_like, response_json, response_json)
254
+
255
+ feedback_textbox = gr.Textbox(label="Additional feedback?", visible=False)
256
+ next_button = gr.Button(value="Submit Feedback", visible=False)
257
+
258
+ query_textbox.submit(show_user_query, [query_textbox, chatbot], [query_textbox, chatbot], queue=False).then(
259
+ respond_user_query, chatbot, [chatbot, response_json]).then(
260
+ switch_to_reviewing_framework, None, [query_textbox, examples.dataset, feedback_textbox, next_button]
261
+ )
262
+
263
+ # Handle page reset and review save in database
264
+ next_button.click(register_review, [chatbot, feedback_textbox, response_json], None).then(
265
+ reset_interface, None, [query_textbox, next_button, feedback_textbox, chatbot, response_json, examples.dataset])
266
+
267
+ # Launch application
268
+ demo.launch()