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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# import streamlit as st
|
2 |
+
# import os
|
3 |
+
# import re
|
4 |
+
# import torch
|
5 |
+
# from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
|
6 |
+
# from PyPDF2 import PdfReader
|
7 |
+
# from peft import get_peft_model, LoraConfig, TaskType
|
8 |
+
|
9 |
+
# # β
Fix CUDA Memory Fragmentation
|
10 |
+
# os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"
|
11 |
+
|
12 |
+
# # πΉ Load IBM Granite Model with 4-bit Quantization
|
13 |
+
# MODEL_NAME = "ibm-granite/granite-3.1-2b-instruct"
|
14 |
+
# quant_config = BitsAndBytesConfig(load_in_4bit=True) # Use 4-bit quantization
|
15 |
+
|
16 |
+
# device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
17 |
+
|
18 |
+
# # β
Ensure model initialization correctly
|
19 |
+
# torch.cuda.empty_cache() # Clear GPU memory before loading model
|
20 |
+
|
21 |
+
# model = AutoModelForCausalLM.from_pretrained(
|
22 |
+
# MODEL_NAME,
|
23 |
+
# quantization_config=quant_config,
|
24 |
+
# device_map="auto", # Auto-assign layers to available GPUs/CPUs
|
25 |
+
# torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32 # Use FP16 if GPU is available
|
26 |
+
# ).to(device) # Move model to correct device
|
27 |
+
|
28 |
+
# tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
|
29 |
+
|
30 |
+
# # πΉ Apply LoRA Fine-Tuning Configuration
|
31 |
+
# lora_config = LoraConfig(
|
32 |
+
# r=8,
|
33 |
+
# lora_alpha=32,
|
34 |
+
# target_modules=["q_proj", "v_proj"],
|
35 |
+
# lora_dropout=0.1,
|
36 |
+
# bias="none",
|
37 |
+
# task_type=TaskType.CAUSAL_LM
|
38 |
+
# )
|
39 |
+
# model = get_peft_model(model, lora_config)
|
40 |
+
# model.eval()
|
41 |
+
|
42 |
+
# # π Function to Read & Extract Text from PDFs
|
43 |
+
# def read_files(file):
|
44 |
+
# file_context = ""
|
45 |
+
# reader = PdfReader(file)
|
46 |
+
|
47 |
+
# for page in reader.pages:
|
48 |
+
# text = page.extract_text()
|
49 |
+
# if text:
|
50 |
+
# file_context += text + "\n"
|
51 |
+
|
52 |
+
# return file_context.strip()
|
53 |
+
|
54 |
+
# # π Function to Format AI Prompts
|
55 |
+
# # π Function to Format AI Prompts
|
56 |
+
# def format_prompt(system_msg, user_msg, file_context=""):
|
57 |
+
# if file_context:
|
58 |
+
# system_msg += f" The user has provided a contract document. Use its context to generate insights, but do not repeat or summarize the document itself."
|
59 |
+
# return [
|
60 |
+
# {"role": "system", "content": system_msg},
|
61 |
+
# {"role": "user", "content": user_msg}
|
62 |
+
# ]
|
63 |
+
# # π Function to Generate AI Responses
|
64 |
+
# def generate_response(input_text, max_tokens=1000, top_p=0.9, temperature=0.7):
|
65 |
+
# torch.cuda.empty_cache() # β
Clear GPU memory before inference
|
66 |
+
|
67 |
+
# model_inputs = tokenizer([input_text], return_tensors="pt").to(device)
|
68 |
+
|
69 |
+
# with torch.no_grad():
|
70 |
+
# output = model.generate(
|
71 |
+
# **model_inputs,
|
72 |
+
# max_new_tokens=max_tokens,
|
73 |
+
# do_sample=True,
|
74 |
+
# top_p=top_p,
|
75 |
+
# temperature=temperature,
|
76 |
+
# num_return_sequences=1,
|
77 |
+
# pad_token_id=tokenizer.eos_token_id
|
78 |
+
# )
|
79 |
+
|
80 |
+
# return tokenizer.decode(output[0], skip_special_tokens=True)
|
81 |
+
|
82 |
+
# # π Function to Clean AI Output
|
83 |
+
# def post_process(text):
|
84 |
+
# cleaned = re.sub(r'ζ₯+', '', text) # Remove unwanted symbols
|
85 |
+
# lines = cleaned.splitlines()
|
86 |
+
# unique_lines = list(dict.fromkeys([line.strip() for line in lines if line.strip()]))
|
87 |
+
# return "\n".join(unique_lines)
|
88 |
+
|
89 |
+
# # π Function to Handle RAG with IBM Granite & Streamlit
|
90 |
+
# def granite_simple(prompt, file):
|
91 |
+
# file_context = read_files(file) if file else ""
|
92 |
+
|
93 |
+
# system_message = "You are IBM Granite, a legal AI assistant specializing in contract analysis."
|
94 |
+
|
95 |
+
# messages = format_prompt(system_message, prompt, file_context)
|
96 |
+
# input_text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
97 |
+
|
98 |
+
# response = generate_response(input_text)
|
99 |
+
# return post_process(response)
|
100 |
+
|
101 |
+
# # πΉ Streamlit UI
|
102 |
+
# def main():
|
103 |
+
# st.set_page_config(page_title="Contract Analysis AI", page_icon="π", layout="wide")
|
104 |
+
|
105 |
+
# st.title("π AI-Powered Contract Analysis Tool")
|
106 |
+
# st.write("Upload a contract document (PDF) for a detailed AI-driven legal and technical analysis.")
|
107 |
+
|
108 |
+
# # πΉ Sidebar Settings
|
109 |
+
# with st.sidebar:
|
110 |
+
# st.header("βοΈ Settings")
|
111 |
+
# max_tokens = st.slider("Max Tokens", 50, 1000, 250, 50)
|
112 |
+
# top_p = st.slider("Top P (sampling)", 0.1, 1.0, 0.9, 0.1)
|
113 |
+
# temperature = st.slider("Temperature (creativity)", 0.1, 1.0, 0.7, 0.1)
|
114 |
+
|
115 |
+
# # πΉ File Upload Section
|
116 |
+
# uploaded_file = st.file_uploader("π Upload a contract document (PDF)", type="pdf")
|
117 |
+
|
118 |
+
# if uploaded_file is not None:
|
119 |
+
# temp_file_path = "temp_uploaded_contract.pdf"
|
120 |
+
# with open(temp_file_path, "wb") as f:
|
121 |
+
# f.write(uploaded_file.getbuffer())
|
122 |
+
|
123 |
+
# st.success("β
File uploaded successfully!")
|
124 |
+
|
125 |
+
# # πΉ User Input for Analysis
|
126 |
+
# user_prompt = "Perform a detailed technical analysis of the attached contract document, highlighting potential risks, legal pitfalls, compliance issues, and areas where contractual terms may lead to future disputes or operational challenges."
|
127 |
+
|
128 |
+
# # user_prompt = st.text_area(
|
129 |
+
# # "π Describe what you want to analyze:",
|
130 |
+
# # "Perform a detailed technical analysis of the attached contract document, highlighting potential risks, legal pitfalls, compliance issues, and areas where contractual terms may lead to future disputes or operational challenges."
|
131 |
+
# # )
|
132 |
+
# # with st.empty(): # This hides the text area
|
133 |
+
# # user_prompt = st.text_area(
|
134 |
+
# # "π Describe what you want to analyze:",
|
135 |
+
# # "Perform a detailed technical analysis of the attached contract document, highlighting potential risks, legal pitfalls, compliance issues, and areas where contractual terms may lead to future disputes or operational challenges."
|
136 |
+
# # )
|
137 |
+
|
138 |
+
|
139 |
+
# if st.button("π Analyze Document"):
|
140 |
+
# with st.spinner("Analyzing contract document... β³"):
|
141 |
+
# final_answer = granite_simple(user_prompt, temp_file_path)
|
142 |
+
|
143 |
+
# # πΉ Display Analysis Result
|
144 |
+
# st.subheader("π Analysis Result")
|
145 |
+
# st.write(final_answer)
|
146 |
+
|
147 |
+
# # πΉ Remove Temporary File
|
148 |
+
# os.remove(temp_file_path)
|
149 |
+
|
150 |
+
# # π₯ Run Streamlit App
|
151 |
+
# if __name__ == '__main__':
|
152 |
+
# main()
|
153 |
+
|
154 |
+
|
155 |
+
import streamlit as st
|
156 |
+
import os
|
157 |
+
import re
|
158 |
+
import torch
|
159 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
160 |
+
from PyPDF2 import PdfReader
|
161 |
+
from peft import get_peft_model, LoraConfig, TaskType
|
162 |
+
|
163 |
+
# β
Force CPU execution for Streamlit Cloud
|
164 |
+
device = torch.device("cpu")
|
165 |
+
|
166 |
+
# πΉ Load IBM Granite Model (CPU-Compatible)
|
167 |
+
MODEL_NAME = "ibm-granite/granite-3.1-2b-instruct"
|
168 |
+
|
169 |
+
model = AutoModelForCausalLM.from_pretrained(
|
170 |
+
MODEL_NAME,
|
171 |
+
device_map="cpu", # Force CPU execution
|
172 |
+
torch_dtype=torch.float32 # Use float32 since Streamlit runs on CPU
|
173 |
+
)
|
174 |
+
|
175 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
|
176 |
+
|
177 |
+
# πΉ Apply LoRA Fine-Tuning Configuration
|
178 |
+
lora_config = LoraConfig(
|
179 |
+
r=8,
|
180 |
+
lora_alpha=32,
|
181 |
+
target_modules=["q_proj", "v_proj"],
|
182 |
+
lora_dropout=0.1,
|
183 |
+
bias="none",
|
184 |
+
task_type=TaskType.CAUSAL_LM
|
185 |
+
)
|
186 |
+
model = get_peft_model(model, lora_config)
|
187 |
+
model.eval()
|
188 |
+
|
189 |
+
# π Function to Read & Extract Text from PDFs
|
190 |
+
def read_files(file):
|
191 |
+
file_context = ""
|
192 |
+
reader = PdfReader(file)
|
193 |
+
|
194 |
+
for page in reader.pages:
|
195 |
+
text = page.extract_text()
|
196 |
+
if text:
|
197 |
+
file_context += text + "\n"
|
198 |
+
|
199 |
+
return file_context.strip()
|
200 |
+
|
201 |
+
# π Function to Format AI Prompts
|
202 |
+
def format_prompt(system_msg, user_msg, file_context=""):
|
203 |
+
if file_context:
|
204 |
+
system_msg += f" The user has provided a contract document. Use its context to generate insights, but do not repeat or summarize the document itself."
|
205 |
+
return [
|
206 |
+
{"role": "system", "content": system_msg},
|
207 |
+
{"role": "user", "content": user_msg}
|
208 |
+
]
|
209 |
+
|
210 |
+
# π Function to Generate AI Responses
|
211 |
+
def generate_response(input_text, max_tokens=1000, top_p=0.9, temperature=0.7):
|
212 |
+
model_inputs = tokenizer([input_text], return_tensors="pt").to(device)
|
213 |
+
|
214 |
+
with torch.no_grad():
|
215 |
+
output = model.generate(
|
216 |
+
**model_inputs,
|
217 |
+
max_new_tokens=max_tokens,
|
218 |
+
do_sample=True,
|
219 |
+
top_p=top_p,
|
220 |
+
temperature=temperature,
|
221 |
+
num_return_sequences=1,
|
222 |
+
pad_token_id=tokenizer.eos_token_id
|
223 |
+
)
|
224 |
+
|
225 |
+
return tokenizer.decode(output[0], skip_special_tokens=True)
|
226 |
+
|
227 |
+
# π Function to Clean AI Output
|
228 |
+
def post_process(text):
|
229 |
+
cleaned = re.sub(r'ζ₯+', '', text) # Remove unwanted symbols
|
230 |
+
lines = cleaned.splitlines()
|
231 |
+
unique_lines = list(dict.fromkeys([line.strip() for line in lines if line.strip()]))
|
232 |
+
return "\n".join(unique_lines)
|
233 |
+
|
234 |
+
# π Function to Handle RAG with IBM Granite & Streamlit
|
235 |
+
def granite_simple(prompt, file):
|
236 |
+
file_context = read_files(file) if file else ""
|
237 |
+
|
238 |
+
system_message = "You are IBM Granite, a legal AI assistant specializing in contract analysis."
|
239 |
+
|
240 |
+
messages = format_prompt(system_message, prompt, file_context)
|
241 |
+
input_text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
242 |
+
|
243 |
+
response = generate_response(input_text)
|
244 |
+
return post_process(response)
|
245 |
+
|
246 |
+
# πΉ Streamlit UI
|
247 |
+
def main():
|
248 |
+
st.set_page_config(page_title="Contract Analysis AI", page_icon="π", layout="wide")
|
249 |
+
|
250 |
+
st.title("π AI-Powered Contract Analysis Tool")
|
251 |
+
st.write("Upload a contract document (PDF) for a detailed AI-driven legal and technical analysis.")
|
252 |
+
|
253 |
+
# πΉ Sidebar Settings
|
254 |
+
with st.sidebar:
|
255 |
+
st.header("βοΈ Settings")
|
256 |
+
max_tokens = st.slider("Max Tokens", 50, 1000, 250, 50)
|
257 |
+
top_p = st.slider("Top P (sampling)", 0.1, 1.0, 0.9, 0.1)
|
258 |
+
temperature = st.slider("Temperature (creativity)", 0.1, 1.0, 0.7, 0.1)
|
259 |
+
|
260 |
+
# πΉ File Upload Section
|
261 |
+
uploaded_file = st.file_uploader("π Upload a contract document (PDF)", type="pdf")
|
262 |
+
|
263 |
+
if uploaded_file is not None:
|
264 |
+
temp_file_path = "temp_uploaded_contract.pdf"
|
265 |
+
with open(temp_file_path, "wb") as f:
|
266 |
+
f.write(uploaded_file.getbuffer())
|
267 |
+
|
268 |
+
st.success("β
File uploaded successfully!")
|
269 |
+
|
270 |
+
# πΉ User Input for Analysis
|
271 |
+
user_prompt = "Perform a detailed technical analysis of the attached contract document, highlighting potential risks, legal pitfalls, compliance issues, and areas where contractual terms may lead to future disputes or operational challenges."
|
272 |
+
|
273 |
+
if st.button("π Analyze Document"):
|
274 |
+
with st.spinner("Analyzing contract document... β³"):
|
275 |
+
final_answer = granite_simple(user_prompt, temp_file_path)
|
276 |
+
|
277 |
+
# πΉ Display Analysis Result
|
278 |
+
st.subheader("π Analysis Result")
|
279 |
+
st.write(final_answer)
|
280 |
+
|
281 |
+
# πΉ Remove Temporary File
|
282 |
+
os.remove(temp_file_path)
|
283 |
+
|
284 |
+
# π₯ Run Streamlit App
|
285 |
+
if __name__ == '__main__':
|
286 |
+
main()
|