TabasumDev commited on
Commit
6e424ff
Β·
verified Β·
1 Parent(s): 9b75287

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +131 -0
app.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import os
3
+ import re
4
+ import torch
5
+ from transformers import AutoModelForCausalLM, AutoTokenizer
6
+ from PyPDF2 import PdfReader
7
+ from peft import get_peft_model, LoraConfig, TaskType
8
+
9
+ # βœ… Force CPU execution
10
+ device = torch.device("cpu")
11
+
12
+ # πŸ”Ή Load IBM Granite Model (CPU-Compatible)
13
+ MODEL_NAME = "ibm-granite/granite-3.1-2b-instruct"
14
+
15
+ model = AutoModelForCausalLM.from_pretrained(
16
+ MODEL_NAME,
17
+ device_map="cpu", # Force CPU execution
18
+ torch_dtype=torch.float32 # Use float32 since Hugging Face runs on CPU
19
+ )
20
+
21
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
22
+
23
+ # πŸ”Ή Apply LoRA Fine-Tuning Configuration
24
+ lora_config = LoraConfig(
25
+ r=8,
26
+ lora_alpha=32,
27
+ target_modules=["q_proj", "v_proj"],
28
+ lora_dropout=0.1,
29
+ bias="none",
30
+ task_type=TaskType.CAUSAL_LM
31
+ )
32
+ model = get_peft_model(model, lora_config)
33
+ model.eval()
34
+
35
+ # πŸ›  Function to Read & Extract Text from PDFs
36
+ def read_files(file):
37
+ file_context = ""
38
+ reader = PdfReader(file)
39
+
40
+ for page in reader.pages:
41
+ text = page.extract_text()
42
+ if text:
43
+ file_context += text + "\n"
44
+
45
+ return file_context.strip()
46
+
47
+ # πŸ›  Function to Format AI Prompts
48
+ def format_prompt(system_msg, user_msg, file_context=""):
49
+ if file_context:
50
+ 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."
51
+ return [
52
+ {"role": "system", "content": system_msg},
53
+ {"role": "user", "content": user_msg}
54
+ ]
55
+
56
+ # πŸ›  Function to Generate AI Responses
57
+ def generate_response(input_text, max_tokens=1000, top_p=0.9, temperature=0.7):
58
+ model_inputs = tokenizer([input_text], return_tensors="pt").to(device)
59
+
60
+ with torch.no_grad():
61
+ output = model.generate(
62
+ **model_inputs,
63
+ max_new_tokens=max_tokens,
64
+ do_sample=True,
65
+ top_p=top_p,
66
+ temperature=temperature,
67
+ num_return_sequences=1,
68
+ pad_token_id=tokenizer.eos_token_id
69
+ )
70
+
71
+ return tokenizer.decode(output[0], skip_special_tokens=True)
72
+
73
+ # πŸ›  Function to Clean AI Output
74
+ def post_process(text):
75
+ cleaned = re.sub(r'ζˆ₯+', '', text) # Remove unwanted symbols
76
+ lines = cleaned.splitlines()
77
+ unique_lines = list(dict.fromkeys([line.strip() for line in lines if line.strip()]))
78
+ return "\n".join(unique_lines)
79
+
80
+ # πŸ›  Function to Handle RAG with IBM Granite & Streamlit
81
+ def granite_simple(prompt, file):
82
+ file_context = read_files(file) if file else ""
83
+
84
+ system_message = "You are IBM Granite, a legal AI assistant specializing in contract analysis."
85
+
86
+ messages = format_prompt(system_message, prompt, file_context)
87
+ input_text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
88
+
89
+ response = generate_response(input_text)
90
+ return post_process(response)
91
+
92
+ # πŸ”Ή Streamlit UI
93
+ def main():
94
+ st.set_page_config(page_title="Contract Analysis AI", page_icon="πŸ“œ")
95
+
96
+ st.title("πŸ“œ AI-Powered Contract Analysis Tool")
97
+ st.write("Upload a contract document (PDF) for a detailed AI-driven legal and technical analysis.")
98
+
99
+ # πŸ”Ή Sidebar Settings
100
+ with st.sidebar:
101
+ st.header("βš™οΈ Settings")
102
+ max_tokens = st.slider("Max Tokens", 50, 1000, 250, 50)
103
+ top_p = st.slider("Top P (sampling)", 0.1, 1.0, 0.9, 0.1)
104
+ temperature = st.slider("Temperature (creativity)", 0.1, 1.0, 0.7, 0.1)
105
+
106
+ # πŸ”Ή File Upload Section
107
+ uploaded_file = st.file_uploader("πŸ“‚ Upload a contract document (PDF)", type="pdf")
108
+
109
+ # βœ… Ensure file upload message is displayed
110
+ if uploaded_file is not None:
111
+ st.session_state["uploaded_file"] = uploaded_file # Persist file in session state
112
+ st.success("βœ… File uploaded successfully!")
113
+ st.write("Click the button below to analyze the contract.")
114
+
115
+ # Force button to always render
116
+ st.markdown('<style>div.stButton > button {display: block; width: 100%;}</style>', unsafe_allow_html=True)
117
+
118
+ if st.button("πŸ” Analyze Document"):
119
+ with st.spinner("Analyzing contract document... ⏳"):
120
+ final_answer = granite_simple(
121
+ "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.",
122
+ uploaded_file
123
+ )
124
+
125
+ # πŸ”Ή Display Analysis Result
126
+ st.subheader("πŸ“‘ Analysis Result")
127
+ st.write(final_answer)
128
+
129
+ # πŸ”₯ Run Streamlit App
130
+ if __name__ == '__main__':
131
+ main()