File size: 21,712 Bytes
297372e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6523d34
 
 
 
1a19f21
6523d34
 
 
297372e
 
6523d34
297372e
6523d34
 
 
 
297372e
 
1a19f21
6523d34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
297372e
6523d34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1a19f21
6523d34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
297372e
 
6523d34
 
297372e
6523d34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
297372e
6523d34
 
 
 
 
297372e
 
 
6523d34
 
 
 
 
297372e
6523d34
 
 
 
 
 
 
 
8c156f5
b8ea32a
 
 
5ae9056
 
 
b8ea32a
5ae9056
b8ea32a
5ae9056
 
 
b8ea32a
5ae9056
 
 
b165b5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ae9056
 
 
b165b5d
5ae9056
b165b5d
5ae9056
b165b5d
 
 
5ae9056
b165b5d
 
 
 
 
 
 
 
 
5ae9056
b165b5d
 
5ae9056
 
 
b8ea32a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c156f5
b8ea32a
 
 
 
8c156f5
b8ea32a
 
 
 
 
 
 
 
 
 
 
 
 
 
8c156f5
b8ea32a
 
 
 
 
 
 
 
 
 
8c156f5
b8ea32a
 
 
 
 
 
 
 
 
 
 
 
8c156f5
b8ea32a
8c156f5
b8ea32a
 
8c156f5
b8ea32a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c156f5
 
838eb5c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
# # import streamlit as st
# # import os
# # import re
# # import torch
# # from transformers import AutoModelForCausalLM, AutoTokenizer
# # from PyPDF2 import PdfReader
# # from peft import get_peft_model, LoraConfig, TaskType

# # # βœ… Force CPU execution for Streamlit Cloud
# # device = torch.device("cpu")

# # # πŸ”Ή Load IBM Granite Model (CPU-Compatible)
# # MODEL_NAME = "ibm-granite/granite-3.1-2b-instruct"

# # model = AutoModelForCausalLM.from_pretrained(
# #     MODEL_NAME,
# #     device_map="cpu",  # Force CPU execution
# #     torch_dtype=torch.float32  # Use float32 since Streamlit runs on CPU
# # )

# # tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)

# # # πŸ”Ή Apply LoRA Fine-Tuning Configuration
# # lora_config = LoraConfig(
# #     r=8,
# #     lora_alpha=32,
# #     target_modules=["q_proj", "v_proj"],
# #     lora_dropout=0.1,
# #     bias="none",
# #     task_type=TaskType.CAUSAL_LM
# # )
# # model = get_peft_model(model, lora_config)
# # model.eval()

# # # πŸ›  Function to Read & Extract Text from PDFs
# # def read_files(file):
# #     file_context = ""
# #     reader = PdfReader(file)
    
# #     for page in reader.pages:
# #         text = page.extract_text()
# #         if text:
# #             file_context += text + "\n"
    
# #     return file_context.strip()

# # # πŸ›  Function to Format AI Prompts
# # def format_prompt(system_msg, user_msg, file_context=""):
# #     if file_context:
# #         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."
# #     return [
# #         {"role": "system", "content": system_msg},
# #         {"role": "user", "content": user_msg}
# #     ]

# # # πŸ›  Function to Generate AI Responses
# # def generate_response(input_text, max_tokens=1000, top_p=0.9, temperature=0.7):
# #     model_inputs = tokenizer([input_text], return_tensors="pt").to(device)
    
# #     with torch.no_grad():
# #         output = model.generate(
# #             **model_inputs,
# #             max_new_tokens=max_tokens,
# #             do_sample=True,
# #             top_p=top_p,
# #             temperature=temperature,
# #             num_return_sequences=1,
# #             pad_token_id=tokenizer.eos_token_id
# #         )
    
# #     return tokenizer.decode(output[0], skip_special_tokens=True)

# # # πŸ›  Function to Clean AI Output
# # def post_process(text):
# #     cleaned = re.sub(r'ζˆ₯+', '', text)  # Remove unwanted symbols
# #     lines = cleaned.splitlines()
# #     unique_lines = list(dict.fromkeys([line.strip() for line in lines if line.strip()]))
# #     return "\n".join(unique_lines)

# # # πŸ›  Function to Handle RAG with IBM Granite & Streamlit
# # def granite_simple(prompt, file):
# #     file_context = read_files(file) if file else ""
    
# #     system_message = "You are IBM Granite, a legal AI assistant specializing in contract analysis."
    
# #     messages = format_prompt(system_message, prompt, file_context)
# #     input_text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
    
# #     response = generate_response(input_text)
# #     return post_process(response)

# # # πŸ”Ή Streamlit UI
# # def main():
# #     st.set_page_config(page_title="Contract Analysis AI", page_icon="πŸ“œ", layout="wide")

# #     st.title("πŸ“œ AI-Powered Contract Analysis Tool")
# #     st.write("Upload a contract document (PDF) for a detailed AI-driven legal and technical analysis.")

# #     # πŸ”Ή Sidebar Settings
# #     with st.sidebar:
# #         st.header("βš™οΈ Settings")
# #         max_tokens = st.slider("Max Tokens", 50, 1000, 250, 50)
# #         top_p = st.slider("Top P (sampling)", 0.1, 1.0, 0.9, 0.1)
# #         temperature = st.slider("Temperature (creativity)", 0.1, 1.0, 0.7, 0.1)

# #     # πŸ”Ή File Upload Section
# #     uploaded_file = st.file_uploader("πŸ“‚ Upload a contract document (PDF)", type="pdf")

# #     if uploaded_file is not None:
# #         temp_file_path = "temp_uploaded_contract.pdf"
# #         with open(temp_file_path, "wb") as f:
# #             f.write(uploaded_file.getbuffer())

# #         st.success("βœ… File uploaded successfully!")

# #         # πŸ”Ή User Input for Analysis
# #         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."

# #         if st.button("πŸ” Analyze Document"):
# #             with st.spinner("Analyzing contract document... ⏳"):
# #                 final_answer = granite_simple(user_prompt, temp_file_path)

# #             # πŸ”Ή Display Analysis Result
# #             st.subheader("πŸ“‘ Analysis Result")
# #             st.write(final_answer)

# #             # πŸ”Ή Remove Temporary File
# #             os.remove(temp_file_path)

# # # πŸ”₯ Run Streamlit App
# # if __name__ == '__main__':
# #     main()





# import streamlit as st
# import os
# import re
# import torch
# from transformers import AutoModelForCausalLM, AutoTokenizer
# from PyPDF2 import PdfReader
# from peft import get_peft_model, LoraConfig, TaskType

# # βœ… Auto-detect GPU for Hugging Face Spaces
# device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

# # πŸ”Ή Load IBM Granite Model (CPU/GPU Compatible)
# MODEL_NAME = "ibm-granite/granite-3.1-2b-instruct"

# model = AutoModelForCausalLM.from_pretrained(
#     MODEL_NAME,
#     device_map="auto",  # Auto-detect GPU if available
#     torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32
# )

# tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)

# # πŸ”Ή Apply LoRA Fine-Tuning Configuration
# lora_config = LoraConfig(
#     r=8,
#     lora_alpha=32,
#     target_modules=["q_proj", "v_proj"],
#     lora_dropout=0.1,
#     bias="none",
#     task_type=TaskType.CAUSAL_LM
# )
# model = get_peft_model(model, lora_config)
# model.eval()

# # πŸ›  Function to Read & Extract Text from PDFs (No Temp File Needed)
# def read_files(file):
#     file_context = ""
#     reader = PdfReader(file)
    
#     for page in reader.pages:
#         text = page.extract_text()
#         if text:
#             file_context += text + "\n"
    
#     return file_context.strip()

# # πŸ›  Function to Format AI Prompts
# def format_prompt(system_msg, user_msg, file_context=""):
#     if file_context:
#         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."
#     return [
#         {"role": "system", "content": system_msg},
#         {"role": "user", "content": user_msg}
#     ]

# # πŸ›  Function to Generate AI Responses
# def generate_response(input_text, max_tokens=1000, top_p=0.9, temperature=0.7):
#     model_inputs = tokenizer([input_text], return_tensors="pt").to(device)
    
#     with torch.no_grad():
#         output = model.generate(
#             **model_inputs,
#             max_new_tokens=max_tokens,
#             do_sample=True,
#             top_p=top_p,
#             temperature=temperature,
#             num_return_sequences=1,
#             pad_token_id=tokenizer.eos_token_id
#         )
    
#     return tokenizer.decode(output[0], skip_special_tokens=True)

# # πŸ›  Function to Clean AI Output
# def post_process(text):
#     cleaned = re.sub(r'ζˆ₯+', '', text)  # Remove unwanted symbols
#     lines = cleaned.splitlines()
#     unique_lines = list(dict.fromkeys([line.strip() for line in lines if line.strip()]))
#     return "\n".join(unique_lines)

# # πŸ›  Function to Handle AI Analysis (No Temp File)
# def granite_simple(prompt, file_content):
#     system_message = "You are IBM Granite, a legal AI assistant specializing in contract analysis."
    
#     messages = format_prompt(system_message, prompt, file_content)
#     input_text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
    
#     response = generate_response(input_text)
#     return post_process(response)

# # πŸ”Ή Streamlit UI
# def main():
#     st.set_page_config(page_title="Contract Analysis AI", page_icon="πŸ“œ", layout="wide")

#     st.title("πŸ“œ AI-Powered Contract Analysis Tool")
#     st.write("Upload a contract document (PDF) for a detailed AI-driven legal and technical analysis.")

#     # πŸ”Ή Sidebar Settings
#     with st.sidebar:
#         st.header("βš™οΈ Settings")
#         max_tokens = st.slider("Max Tokens", 50, 1000, 250, 50)
#         top_p = st.slider("Top P (sampling)", 0.1, 1.0, 0.9, 0.1)
#         temperature = st.slider("Temperature (creativity)", 0.1, 1.0, 0.7, 0.1)

#     # πŸ”Ή File Upload Section (No Temp File)
#     uploaded_file = st.file_uploader("πŸ“‚ Upload a contract document (PDF)", type="pdf")

#     if uploaded_file is not None:
#         st.success("βœ… File uploaded successfully!")

#         # πŸ”Ή Read PDF Content (No Temp File)
#         file_content = read_files(uploaded_file)

#         # πŸ”Ή User Input for Analysis
#         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."

#         if st.button("πŸ” Analyze Document"):
#             with st.spinner("Analyzing contract document... ⏳"):
#                 final_answer = granite_simple(user_prompt, file_content)

#             # πŸ”Ή Display Analysis Result
#             st.subheader("πŸ“‘ Analysis Result")
#             st.write(final_answer)

# # πŸ”₯ Run Streamlit App
# if __name__ == '__main__':
#     main()




# import streamlit as st

# st.title("File Upload Debugging")

# uploaded_file = st.file_uploader("Upload a PDF file", type="pdf")

# if uploaded_file:
#     st.success(f"File uploaded: {uploaded_file.name}")
#     st.write(f"File Size: {uploaded_file.size / 1024:.2f} KB")

# ###################################################################################


# import streamlit as st
# import os
# import re
# import torch
# from transformers import AutoModelForCausalLM, AutoTokenizer
# from PyPDF2 import PdfReader
# from peft import get_peft_model, LoraConfig, TaskType

# # βœ… Force CPU execution for Hugging Face Spaces
# device = torch.device("cpu")

# # πŸ”Ή Load IBM Granite Model (CPU-Compatible)
# MODEL_NAME = "ibm-granite/granite-3.1-2b-instruct"

# model = AutoModelForCausalLM.from_pretrained(
#     MODEL_NAME,
#     device_map="cpu",  # Force CPU execution
#     torch_dtype=torch.float32  # Use float32 since Hugging Face runs on CPU
# )

# tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)

# # πŸ”Ή Apply LoRA Fine-Tuning Configuration
# lora_config = LoraConfig(
#     r=8,
#     lora_alpha=32,
#     target_modules=["q_proj", "v_proj"],
#     lora_dropout=0.1,
#     bias="none",
#     task_type=TaskType.CAUSAL_LM
# )
# model = get_peft_model(model, lora_config)
# model.eval()

# # πŸ›  Function to Read & Extract Text from PDFs
# def read_files(file):
#     file_context = ""
#     try:
#         reader = PdfReader(file)
#         for page in reader.pages:
#             text = page.extract_text()
#             if text:
#                 file_context += text + "\n"
#     except Exception as e:
#         st.error(f"⚠️ Error reading PDF file: {e}")
#         return ""

#     return file_context.strip()

# # πŸ›  Function to Format AI Prompts
# def format_prompt(system_msg, user_msg, file_context=""):
#     if file_context:
#         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."
#     return [
#         {"role": "system", "content": system_msg},
#         {"role": "user", "content": user_msg}
#     ]

# # πŸ›  Function to Generate AI Responses
# def generate_response(input_text, max_tokens=1000, top_p=0.9, temperature=0.7):
#     st.write("πŸ” Generating response...")  # Debugging message
#     model_inputs = tokenizer([input_text], return_tensors="pt").to(device)

#     with torch.no_grad():
#         output = model.generate(
#             **model_inputs,
#             max_new_tokens=max_tokens,
#             do_sample=True,
#             top_p=top_p,
#             temperature=temperature,
#             num_return_sequences=1,
#             pad_token_id=tokenizer.eos_token_id
#         )

#     response = tokenizer.decode(output[0], skip_special_tokens=True)
#     st.write("βœ… Response Generated!")  # Debugging message
#     return response

# # πŸ›  Function to Clean AI Output
# def post_process(text):
#     cleaned = re.sub(r'ζˆ₯+', '', text)  # Remove unwanted symbols
#     lines = cleaned.splitlines()
#     unique_lines = list(dict.fromkeys([line.strip() for line in lines if line.strip()]))
#     return "\n".join(unique_lines)

# # πŸ›  Function to Handle RAG with IBM Granite & Streamlit
# def granite_simple(prompt, file):
#     file_context = read_files(file) if file else ""

#     # Debugging: Show extracted file content preview
#     if not file_context:
#         st.error("⚠️ No content extracted from the PDF. It might be a scanned image or encrypted.")
#         return "Error: No content found in the document."

#     system_message = "You are IBM Granite, a legal AI assistant specializing in contract analysis."

#     messages = format_prompt(system_message, prompt, file_context)
#     input_text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)

#     response = generate_response(input_text)
#     return post_process(response)

# # πŸ”Ή Streamlit UI
# def main():
#     st.set_page_config(page_title="Contract Analysis AI", page_icon="πŸ“œ")

#     st.title("πŸ“œ AI-Powered Contract Analysis Tool")
#     st.write("Upload a contract document (PDF) for a detailed AI-driven legal and technical analysis.")

#     # πŸ”Ή Sidebar Settings
#     with st.sidebar:
#         st.header("βš™οΈ Settings")
#         max_tokens = st.slider("Max Tokens", 50, 1000, 250, 50)
#         top_p = st.slider("Top P (sampling)", 0.1, 1.0, 0.9, 0.1)
#         temperature = st.slider("Temperature (creativity)", 0.1, 1.0, 0.7, 0.1)

#     # πŸ”Ή File Upload Section
#     uploaded_file = st.file_uploader("πŸ“‚ Upload a contract document (PDF)", type="pdf")

#     if uploaded_file:
#         st.success(f"βœ… File uploaded successfully! File Name: {uploaded_file.name}")
#         st.write(f"**File Size:** {uploaded_file.size / 1024:.2f} KB")

#         # Debugging: Show extracted text preview
#         pdf_text = read_files(uploaded_file)
#         if pdf_text:
#             st.write("**Extracted Sample Text:**")
#             st.code(pdf_text[:500])  # Show first 500 characters
#         else:
#             st.error("⚠️ No readable text found in the document.")

#         st.write("Click the button below to analyze the contract.")

#         # Force button to always render
#         st.markdown('<style>div.stButton > button {display: block; width: 100%;}</style>', unsafe_allow_html=True)

#         if st.button("πŸ” Analyze Document"):
#             with st.spinner("Analyzing contract document... ⏳"):
#                 final_answer = granite_simple(
#                     "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.",
#                     uploaded_file
#                 )

#             # πŸ”Ή Display Analysis Result
#             st.subheader("πŸ“‘ Analysis Result")
#             st.write(final_answer)

# # πŸ”₯ Run Streamlit App
# if __name__ == '__main__':
#     main()

import streamlit as st
from PyPDF2 import PdfReader

st.title("πŸ“‚ PDF Upload Debugger")

uploaded_file = st.file_uploader("Upload a PDF", type="pdf")

if uploaded_file:
    st.success(f"βœ… File uploaded: {uploaded_file.name}")
    st.write(f"πŸ“ File Size: {uploaded_file.size / 1024:.2f} KB")

    try:
        reader = PdfReader(uploaded_file)
        text = "\n".join([page.extract_text() for page in reader.pages if page.extract_text()])
        
        if text.strip():
            st.subheader("Extracted Text (First 500 characters)")
            st.code(text[:500])  # Show a preview of the text
        else:
            st.error("⚠️ No text found. The document might be scanned or encrypted.")

    except Exception as e:
        st.error(f"⚠️ Error reading PDF: {e}")


# ###################################################################################

# import streamlit as st
# import os
# import re
# import torch
# from transformers import AutoModelForCausalLM, AutoTokenizer
# from PyPDF2 import PdfReader
# from peft import get_peft_model, LoraConfig, TaskType

# # βœ… Force CPU execution
# device = torch.device("cpu")

# # πŸ”Ή Load IBM Granite Model (CPU-Compatible)
# MODEL_NAME = "ibm-granite/granite-3.1-2b-instruct"

# model = AutoModelForCausalLM.from_pretrained(
#     MODEL_NAME,
#     device_map="cpu",  # Force CPU execution
#     torch_dtype=torch.float32  # Use float32 since Hugging Face runs on CPU
# )

# tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)

# # πŸ”Ή Apply LoRA Fine-Tuning Configuration
# lora_config = LoraConfig(
#     r=8,
#     lora_alpha=32,
#     target_modules=["q_proj", "v_proj"],
#     lora_dropout=0.1,
#     bias="none",
#     task_type=TaskType.CAUSAL_LM
# )
# model = get_peft_model(model, lora_config)
# model.eval()

# # πŸ›  Function to Read & Extract Text from PDFs
# def read_files(file):
#     file_context = ""
#     reader = PdfReader(file)
    
#     for page in reader.pages:
#         text = page.extract_text()
#         if text:
#             file_context += text + "\n"
    
#     return file_context.strip()

# # πŸ›  Function to Format AI Prompts
# def format_prompt(system_msg, user_msg, file_context=""):
#     if file_context:
#         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."
#     return [
#         {"role": "system", "content": system_msg},
#         {"role": "user", "content": user_msg}
#     ]

# # πŸ›  Function to Generate AI Responses
# def generate_response(input_text, max_tokens=1000, top_p=0.9, temperature=0.7):
#     model_inputs = tokenizer([input_text], return_tensors="pt").to(device)
    
#     with torch.no_grad():
#         output = model.generate(
#             **model_inputs,
#             max_new_tokens=max_tokens,
#             do_sample=True,
#             top_p=top_p,
#             temperature=temperature,
#             num_return_sequences=1,
#             pad_token_id=tokenizer.eos_token_id
#         )
    
#     return tokenizer.decode(output[0], skip_special_tokens=True)

# # πŸ›  Function to Clean AI Output
# def post_process(text):
#     cleaned = re.sub(r'ζˆ₯+', '', text)  # Remove unwanted symbols
#     lines = cleaned.splitlines()
#     unique_lines = list(dict.fromkeys([line.strip() for line in lines if line.strip()]))
#     return "\n".join(unique_lines)

# # πŸ›  Function to Handle RAG with IBM Granite & Streamlit
# def granite_simple(prompt, file):
#     file_context = read_files(file) if file else ""
    
#     system_message = "You are IBM Granite, a legal AI assistant specializing in contract analysis."
    
#     messages = format_prompt(system_message, prompt, file_context)
#     input_text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
    
#     response = generate_response(input_text)
#     return post_process(response)

# # πŸ”Ή Streamlit UI
# def main():
#     st.set_page_config(page_title="Contract Analysis AI", page_icon="πŸ“œ")

#     st.title("πŸ“œ AI-Powered Contract Analysis Tool")
#     st.write("Upload a contract document (PDF) for a detailed AI-driven legal and technical analysis.")

#     # πŸ”Ή Sidebar Settings
#     with st.sidebar:
#         st.header("βš™οΈ Settings")
#         max_tokens = st.slider("Max Tokens", 50, 1000, 250, 50)
#         top_p = st.slider("Top P (sampling)", 0.1, 1.0, 0.9, 0.1)
#         temperature = st.slider("Temperature (creativity)", 0.1, 1.0, 0.7, 0.1)

#     # πŸ”Ή File Upload Section
#     uploaded_file = st.file_uploader("πŸ“‚ Upload a contract document (PDF)", type="pdf")

#     # βœ… Ensure file upload message is displayed
#     if uploaded_file is not None:
#         st.session_state["uploaded_file"] = uploaded_file  # Persist file in session state
#         st.success("βœ… File uploaded successfully!")
#         st.write("Click the button below to analyze the contract.")

#         # Force button to always render
#         st.markdown('<style>div.stButton > button {display: block; width: 100%;}</style>', unsafe_allow_html=True)

#         if st.button("πŸ” Analyze Document"):
#             with st.spinner("Analyzing contract document... ⏳"):
#                 final_answer = granite_simple(
#                     "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.",
#                     uploaded_file
#                 )

#             # πŸ”Ή Display Analysis Result
#             st.subheader("πŸ“‘ Analysis Result")
#             st.write(final_answer)

# # πŸ”₯ Run Streamlit App
# if __name__ == '__main__':
#     main()