Spaces:
Sleeping
Sleeping
Create main.py
Browse files
main.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import PyPDF2
|
| 3 |
+
from docx import Document
|
| 4 |
+
import json
|
| 5 |
+
from google import genai
|
| 6 |
+
from dotenv import load_dotenv
|
| 7 |
+
import os
|
| 8 |
+
import re
|
| 9 |
+
|
| 10 |
+
# Load API Key from .env
|
| 11 |
+
load_dotenv()
|
| 12 |
+
api_key = os.getenv("GEMINI_API_KEY")
|
| 13 |
+
|
| 14 |
+
if not api_key:
|
| 15 |
+
st.error("β Gemini API key not found in .env.")
|
| 16 |
+
st.stop()
|
| 17 |
+
|
| 18 |
+
# Utility: Extract text from PDF
|
| 19 |
+
def extract_text_from_pdf(file):
|
| 20 |
+
reader = PyPDF2.PdfReader(file)
|
| 21 |
+
text = ""
|
| 22 |
+
for page in reader.pages:
|
| 23 |
+
content = page.extract_text()
|
| 24 |
+
if content:
|
| 25 |
+
text += content + "\n"
|
| 26 |
+
return text.strip()
|
| 27 |
+
|
| 28 |
+
# Utility: Extract text from DOCX
|
| 29 |
+
def extract_text_from_docx(file):
|
| 30 |
+
doc = Document(file)
|
| 31 |
+
return "\n".join([para.text for para in doc.paragraphs]).strip()
|
| 32 |
+
|
| 33 |
+
# Utility: Parse Gemini JSON response
|
| 34 |
+
def safe_parse_json(response_text):
|
| 35 |
+
try:
|
| 36 |
+
clean_text = re.sub(r"^```(?:json)?|```$", "", response_text.strip(), flags=re.MULTILINE)
|
| 37 |
+
return json.loads(clean_text)
|
| 38 |
+
except Exception as e:
|
| 39 |
+
st.error("β οΈ Could not parse Gemini response as JSON. Showing raw response.")
|
| 40 |
+
return {
|
| 41 |
+
"summary": response_text,
|
| 42 |
+
"highlights": None,
|
| 43 |
+
"glossary": None
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
# Call Gemini API
|
| 47 |
+
def call_gemini_api(document_text):
|
| 48 |
+
client = genai.Client(api_key=api_key)
|
| 49 |
+
|
| 50 |
+
prompt = (
|
| 51 |
+
f"Analyze the following legal document:\n\n{document_text}\n\n"
|
| 52 |
+
"Instructions:\n"
|
| 53 |
+
"- Summarize the key points of the document.\n"
|
| 54 |
+
"- Highlight obligations, rights, and critical clauses (as a list of objects with 'clause' and 'description').\n"
|
| 55 |
+
"- Provide simplified explanations of complex legal terms (as a dictionary).\n"
|
| 56 |
+
"Return the result as JSON with keys: 'summary', 'highlights', 'glossary'."
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
response = client.models.generate_content(
|
| 60 |
+
model="gemini-2.0-flash",
|
| 61 |
+
contents=prompt
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
return safe_parse_json(response.text)
|
| 65 |
+
|
| 66 |
+
# Render Highlights Beautifully
|
| 67 |
+
def render_highlights(highlights):
|
| 68 |
+
if isinstance(highlights, list) and all(isinstance(item, dict) for item in highlights):
|
| 69 |
+
for idx, item in enumerate(highlights, 1):
|
| 70 |
+
clause = item.get("clause", "").strip()
|
| 71 |
+
desc = item.get("description", "").strip()
|
| 72 |
+
if clause and desc:
|
| 73 |
+
st.markdown(f"""
|
| 74 |
+
<div style="background-color:#f5f5f5;padding:10px;border-radius:8px;margin-bottom:10px">
|
| 75 |
+
<strong>{idx}. {clause}</strong><br>
|
| 76 |
+
<span style="font-size: 0.95rem;">{desc}</span>
|
| 77 |
+
</div>
|
| 78 |
+
""", unsafe_allow_html=True)
|
| 79 |
+
elif isinstance(highlights, str):
|
| 80 |
+
st.markdown(highlights)
|
| 81 |
+
else:
|
| 82 |
+
st.info("No highlights available.")
|
| 83 |
+
|
| 84 |
+
# Render Glossary Beautifully
|
| 85 |
+
def render_glossary(glossary):
|
| 86 |
+
if isinstance(glossary, dict):
|
| 87 |
+
for term, explanation in glossary.items():
|
| 88 |
+
st.markdown(f"""
|
| 89 |
+
<div style="margin-bottom: 8px;">
|
| 90 |
+
<strong>{term}:</strong> {explanation}
|
| 91 |
+
</div>
|
| 92 |
+
""", unsafe_allow_html=True)
|
| 93 |
+
elif isinstance(glossary, str):
|
| 94 |
+
st.markdown(glossary)
|
| 95 |
+
else:
|
| 96 |
+
st.info("No glossary available.")
|
| 97 |
+
|
| 98 |
+
# Main App
|
| 99 |
+
def main():
|
| 100 |
+
st.set_page_config(page_title="Legal Document Summarizer", layout="wide")
|
| 101 |
+
st.title("π Legal Document Summarizer")
|
| 102 |
+
st.caption("Upload a legal document (PDF or DOCX) to get a summary, key highlights, and glossary of legal terms.")
|
| 103 |
+
|
| 104 |
+
uploaded_file = st.file_uploader("Upload your document", type=["pdf", "docx"])
|
| 105 |
+
|
| 106 |
+
if uploaded_file:
|
| 107 |
+
if uploaded_file.type == "application/pdf":
|
| 108 |
+
document_text = extract_text_from_pdf(uploaded_file)
|
| 109 |
+
elif uploaded_file.type == "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
|
| 110 |
+
document_text = extract_text_from_docx(uploaded_file)
|
| 111 |
+
else:
|
| 112 |
+
st.error("Unsupported file format.")
|
| 113 |
+
return
|
| 114 |
+
|
| 115 |
+
if not document_text.strip():
|
| 116 |
+
st.error("No text extracted from the document.")
|
| 117 |
+
return
|
| 118 |
+
|
| 119 |
+
st.subheader("π Document Preview")
|
| 120 |
+
st.text_area("Extracted Text", document_text, height=300)
|
| 121 |
+
|
| 122 |
+
if st.button("Summarize Document"):
|
| 123 |
+
with st.spinner("Calling Gemini..."):
|
| 124 |
+
result = call_gemini_api(document_text)
|
| 125 |
+
|
| 126 |
+
st.subheader("π Summary")
|
| 127 |
+
st.write(result.get("summary", "No summary found."))
|
| 128 |
+
|
| 129 |
+
st.subheader("π Highlights")
|
| 130 |
+
render_highlights(result.get("highlights"))
|
| 131 |
+
|
| 132 |
+
st.subheader("π Glossary")
|
| 133 |
+
render_glossary(result.get("glossary"))
|
| 134 |
+
|
| 135 |
+
if __name__ == "__main__":
|
| 136 |
+
main()
|