sohampawar1030 commited on
Commit
77887eb
·
verified ·
1 Parent(s): 1a570e6

Update legal_document_analysis.py

Browse files
Files changed (1) hide show
  1. legal_document_analysis.py +54 -45
legal_document_analysis.py CHANGED
@@ -15,8 +15,6 @@ from fpdf import FPDF
15
  import getpass
16
  import pandas as pd
17
  import seaborn as sns
18
- import requests
19
- from bs4 import BeautifulSoup
20
 
21
  # Load environment variables from .env file
22
  load_dotenv()
@@ -372,50 +370,33 @@ def generate_pdf_analysis(document_text, summary, detected_clauses, hidden_oblig
372
  pdf.cell(0, 10, f"{risk['phrase']}: {risk['summary']} (Risk Level: {risk['risk_level']})", ln=True)
373
  pdf.ln(10)
374
 
375
- # Save images temporarily and add them to the PDF
376
- def save_base64_image(image_str, filename):
377
- with open(filename, "wb") as img_file:
378
- img_file.write(base64.b64decode(image_str))
379
-
380
- # Save images
381
- image_filenames = [
382
- "risk_assessment_matrix.png",
383
- "risk_level_distribution.png",
384
- "risks_by_type.png",
385
- "stacked_bar_chart.png",
386
- "risk_heatmap.png"
387
- ]
388
 
389
- images = [risk_assessment_matrix, risk_level_distribution, risks_by_type, stacked_bar_chart, risk_heatmap]
390
-
391
- for img_str, filename in zip(images, image_filenames):
392
- save_base64_image(img_str, filename)
393
- pdf.image(filename, x=10, y=pdf.get_y(), w=90) # Use the saved image file
394
 
 
395
  pdf.ln(10)
396
 
397
- # Save PDF to a temporary file
398
- temp_pdf_path = "legal_document_analysis.pdf"
399
- pdf.output(temp_pdf_path, 'F')
400
-
401
- # Load the PDF into a BytesIO object
402
- with open(temp_pdf_path, "rb") as f:
403
- pdf_buffer = io.BytesIO(f.read())
404
 
405
- # Optionally, delete the temporary file
406
- os.remove(temp_pdf_path)
407
-
408
- return pdf_buffer
409
 
410
  # Function to handle chatbot interaction
411
- def chatbot_query(user_input, document_text):
412
- prompt = f"You are a legal expert. Answer the question based on the following document text:\n\n{document_text}\n\nQuestion: {user_input}"
413
  try:
414
- response = model.invoke(prompt)
415
- if hasattr(response, 'content'):
416
- return response.content.strip()
417
  else:
418
- return str(response).strip()
419
  except Exception as e:
420
  return f"Error: {str(e)}"
421
 
@@ -460,6 +441,8 @@ def send_feedback(feedback_content):
460
  def send_pdf_via_email(pdf_buffer, recipient_email):
461
  sender_email = os.getenv("SENDER_EMAIL")
462
  password = os.getenv("EMAIL_PASS")
 
 
463
  msg['From'] = sender_email
464
  msg['To'] = recipient_email
465
  msg['Subject'] = "Legal Document Analysis PDF"
@@ -467,11 +450,8 @@ def send_pdf_via_email(pdf_buffer, recipient_email):
467
  msg.attach(MIMEText("Please find the attached analysis of your legal document.", 'plain'))
468
 
469
  # Attach the PDF
470
- pdf_attachment = io.BytesIO()
471
- pdf_buffer.seek(0)
472
- pdf_attachment.write(pdf_buffer.read())
473
  pdf_attachment.seek(0)
474
-
475
  part = MIMEApplication(pdf_attachment.read(), Name='legal_document_analysis.pdf')
476
  part['Content-Disposition'] = 'attachment; filename="legal_document_analysis.pdf"'
477
  msg.attach(part)
@@ -548,6 +528,7 @@ def display_legal_analysis_page():
548
  with st.expander(clause['clause'], expanded=False):
549
  st.write(f"*Summary:* {clause['summary']}")
550
  st.write(f"*Context:* {clause['explanation']}")
 
551
  else:
552
  st.write("No key clauses detected.")
553
 
@@ -601,12 +582,43 @@ def display_legal_analysis_page():
601
  user_input = st.text_input("Ask the chatbot about your document:")
602
  if st.button("Send"):
603
  if user_input:
604
- chatbot_response = chatbot_query(user_input, document_text)
605
  st.write("*Chatbot Response:*")
606
  st.write(chatbot_response)
607
  else:
608
  st.warning("Please enter a question.")
609
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
610
  with tabs[6]: # Update Tracker Tab
611
  st.subheader("Document Updates")
612
  updates = track_updates(document_text)
@@ -616,9 +628,6 @@ def display_legal_analysis_page():
616
  with st.expander(update['update'], expanded=False):
617
  suggestion = get_update_suggestion(update['update'])
618
  st.write(f"*Suggestion:* {suggestion}")
619
- # Additional functionality
620
- if st.button(f"Mark '{update['update']}' as addressed"):
621
- st.success(f"'{update['update']}' has been marked as addressed.")
622
  else:
623
  st.write("No updates detected.")
624
 
 
15
  import getpass
16
  import pandas as pd
17
  import seaborn as sns
 
 
18
 
19
  # Load environment variables from .env file
20
  load_dotenv()
 
370
  pdf.cell(0, 10, f"{risk['phrase']}: {risk['summary']} (Risk Level: {risk['risk_level']})", ln=True)
371
  pdf.ln(10)
372
 
373
+ # Add visualizations for risks
374
+ pdf.image(base64_to_image(risk_assessment_matrix), x=10, y=pdf.get_y(), w=90)
375
+ pdf.image(base64_to_image(risk_level_distribution), x=110, y=pdf.get_y()-50, w=90) # Position next to the first image
376
+ pdf.ln(60)
 
 
 
 
 
 
 
 
 
377
 
378
+ pdf.image(base64_to_image(risks_by_type), x=10, y=pdf.get_y(), w=90)
379
+ pdf.image(base64_to_image(stacked_bar_chart), x=110, y=pdf.get_y()-50, w=90) # Position next to the previous image
380
+ pdf.ln(60)
 
 
381
 
382
+ pdf.image(base64_to_image(risk_heatmap), x=10, y=pdf.get_y(), w=190) # Fit image to width
383
  pdf.ln(10)
384
 
385
+ # Footer
386
+ pdf.set_y(-15)
387
+ pdf.set_font("Arial", 'I', 8)
388
+ pdf.cell(0, 10, f'Page {pdf.page_no()}', 0, 0, 'C')
 
 
 
389
 
390
+ return pdf
 
 
 
391
 
392
  # Function to handle chatbot interaction
393
+ def chatbot_query(user_input):
 
394
  try:
395
+ response = model({"text": user_input})
396
+ if isinstance(response, dict) and 'text' in response:
397
+ return response['text']
398
  else:
399
+ return "Error: Unexpected response format."
400
  except Exception as e:
401
  return f"Error: {str(e)}"
402
 
 
441
  def send_pdf_via_email(pdf_buffer, recipient_email):
442
  sender_email = os.getenv("SENDER_EMAIL")
443
  password = os.getenv("EMAIL_PASS")
444
+
445
+ msg = MIMEMultipart()
446
  msg['From'] = sender_email
447
  msg['To'] = recipient_email
448
  msg['Subject'] = "Legal Document Analysis PDF"
 
450
  msg.attach(MIMEText("Please find the attached analysis of your legal document.", 'plain'))
451
 
452
  # Attach the PDF
453
+ pdf_attachment = io.BytesIO(pdf_buffer.getvalue())
 
 
454
  pdf_attachment.seek(0)
 
455
  part = MIMEApplication(pdf_attachment.read(), Name='legal_document_analysis.pdf')
456
  part['Content-Disposition'] = 'attachment; filename="legal_document_analysis.pdf"'
457
  msg.attach(part)
 
528
  with st.expander(clause['clause'], expanded=False):
529
  st.write(f"*Summary:* {clause['summary']}")
530
  st.write(f"*Context:* {clause['explanation']}")
531
+
532
  else:
533
  st.write("No key clauses detected.")
534
 
 
582
  user_input = st.text_input("Ask the chatbot about your document:")
583
  if st.button("Send"):
584
  if user_input:
585
+ chatbot_response = chatbot_query(user_input)
586
  st.write("*Chatbot Response:*")
587
  st.write(chatbot_response)
588
  else:
589
  st.warning("Please enter a question.")
590
 
591
+ # Download PDF Analysis Button
592
+ st.subheader("Download Analysis as PDF")
593
+ pdf_buffer = io.BytesIO()
594
+ pdf = generate_pdf_analysis(document_text, summary, detected_clauses, hidden_obligations, detected_risks, risk_assessment_matrix, risk_level_distribution, risks_by_type, stacked_bar_chart, risk_heatmap)
595
+ pdf.output(pdf_buffer, 'F')
596
+ pdf_buffer.seek(0)
597
+
598
+ # Add download button for PDF
599
+ st.download_button(
600
+ label="Download PDF Analysis",
601
+ data=pdf_buffer,
602
+ file_name="legal_document_analysis.pdf",
603
+ mime="application/pdf"
604
+ )
605
+
606
+ # Input for recipient email
607
+ recipient_email = st.text_input("Enter your email address to receive the PDF:")
608
+
609
+ # Button to send PDF via email
610
+ if st.button("Send PDF Analysis"):
611
+ if recipient_email:
612
+ if send_pdf_via_email(pdf_buffer, recipient_email):
613
+ st.success("PDF has been sent successfully!")
614
+ else:
615
+ st.error("Failed to send PDF. Please try again.")
616
+ else:
617
+ st.warning("Please enter a valid email address.")
618
+
619
+ # Feedback Form Section
620
+ display_feedback_form()
621
+
622
  with tabs[6]: # Update Tracker Tab
623
  st.subheader("Document Updates")
624
  updates = track_updates(document_text)
 
628
  with st.expander(update['update'], expanded=False):
629
  suggestion = get_update_suggestion(update['update'])
630
  st.write(f"*Suggestion:* {suggestion}")
 
 
 
631
  else:
632
  st.write("No updates detected.")
633