arshad1234321 commited on
Commit
6f4d51b
Β·
verified Β·
1 Parent(s): fb1129b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +105 -98
app.py CHANGED
@@ -3,127 +3,134 @@ import PyPDF2
3
  from docx import Document
4
  import json
5
  from google import genai
 
 
 
6
 
7
- # -------------------------------
8
- # Utility Functions
9
- # -------------------------------
10
 
 
 
 
 
 
11
  def extract_text_from_pdf(file):
12
- """
13
- Extracts textual content from a PDF document.
14
- """
15
- pdf_reader = PyPDF2.PdfReader(file)
16
  text = ""
17
- for page in pdf_reader.pages:
18
- page_text = page.extract_text()
19
- if page_text:
20
- text += page_text + "\n"
21
- return text
22
 
 
23
  def extract_text_from_docx(file):
24
- """
25
- Extracts textual content from a DOCX document.
26
- """
27
- document = Document(file)
28
- text = ""
29
- for para in document.paragraphs:
30
- text += para.text + "\n"
31
- return text
32
-
33
- def call_gemini_api(document_content):
34
- """
35
- Calls the Google GenAI Gemini API (gemini-2.0-flash) with a prompt to analyze and summarize
36
- the legal document, extracting key points, highlighting obligations/rights, and simplifying
37
- complex legal terms.
38
-
39
- The prompt instructs the model to return the output in JSON format with three keys:
40
- - summary: A concise summary of the document.
41
- - highlights: Key obligations, rights, and clauses.
42
- - glossary: Simplified explanations of complex legal terms.
43
- """
44
- # Initialize the Gemini client using your API key stored in Streamlit secrets.
45
- api_key = st.secrets["GEMINI_API_KEY"]
46
  client = genai.Client(api_key=api_key)
47
-
48
- # Construct the prompt with clear instructions
49
  prompt = (
50
- f"Analyze the following legal document:\n\n"
51
- f"{document_content}\n\n"
52
  "Instructions:\n"
53
- "1. Summarize the key points of the document.\n"
54
- "2. Highlight obligations, rights, and critical clauses.\n"
55
- "3. Provide simplified explanations of complex legal terms.\n"
56
- "Output the results as a valid JSON object with the following keys: "
57
- "'summary', 'highlights', 'glossary'."
58
  )
59
-
60
- # Call the Gemini API using the google.genai client
61
  response = client.models.generate_content(
62
  model="gemini-2.0-flash",
63
- contents=prompt,
64
  )
65
-
66
- # Try parsing the output JSON; if parsing fails, return the text as the summary.
67
- try:
68
- result = json.loads(response.text)
69
- except Exception as e:
70
- st.error("Failed to parse Gemini API response as JSON. Returning raw text instead.")
71
- result = {"summary": response.text, "highlights": "N/A", "glossary": "N/A"}
72
-
73
- return result
74
 
75
- # -------------------------------
76
- # Main Application
77
- # -------------------------------
78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
  def main():
80
- st.title("Legal Document Summarizer")
81
- st.write("Upload a legal document (PDF or DOCX) to receive a concise summary, key highlights, and a glossary of complex legal terms.")
 
82
 
83
- uploaded_file = st.file_uploader("Upload Legal Document", type=["pdf", "docx"])
84
 
85
- if uploaded_file is not None:
86
- # Display file details
87
- file_details = {
88
- "Filename": uploaded_file.name,
89
- "File Type": uploaded_file.type,
90
- "File Size (bytes)": uploaded_file.size
91
- }
92
- st.write("**Uploaded File Details**", file_details)
93
-
94
- # Extract text from the document based on the file type
95
- document_text = ""
96
  if uploaded_file.type == "application/pdf":
97
  document_text = extract_text_from_pdf(uploaded_file)
98
  elif uploaded_file.type == "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
99
  document_text = extract_text_from_docx(uploaded_file)
100
  else:
101
- st.error("Unsupported file type.")
102
-
103
- if document_text.strip():
104
- st.subheader("Extracted Document Text")
105
- st.text_area("Document Text", document_text, height=300)
106
-
107
- if st.button("Summarize Document"):
108
- with st.spinner("Analyzing document via Gemini API..."):
109
- result = call_gemini_api(document_text)
110
- if result:
111
- summary = result.get("summary", "No summary provided by the API.")
112
- highlights = result.get("highlights", "No highlights provided by the API.")
113
- glossary = result.get("glossary", "No glossary provided by the API.")
114
-
115
- st.subheader("Document Summary")
116
- st.write(summary)
117
-
118
- st.subheader("Highlights (Obligations, Rights, Critical Clauses)")
119
- st.write(highlights)
120
-
121
- st.subheader("Glossary (Simplified Legal Terms)")
122
- st.write(glossary)
123
- else:
124
- st.error("Failed to retrieve a valid response from the Gemini API.")
125
- else:
126
- st.error("No text could be extracted from the document.")
127
 
128
  if __name__ == "__main__":
129
  main()
 
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()