Sebbe33 commited on
Commit
e0d120b
Β·
verified Β·
1 Parent(s): 88817f3

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +352 -34
src/streamlit_app.py CHANGED
@@ -1,40 +1,358 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
 
4
  import streamlit as st
 
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
 
12
 
13
- In the meantime, below is an example of what you can do with just a few lines of code:
 
 
 
 
 
 
 
 
 
14
  """
15
 
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import io
4
+ import json
5
  import streamlit as st
6
+ from PIL import Image, ImageDraw, ImageFont
7
+ from google import generativeai as genai # Renamed for clarity from 'google.genai'
8
+ from google.generativeai.types import GenerationConfig, HarmCategory, HarmBlockThreshold
9
+ from pdf2image import convert_from_bytes
10
+ from typing import List, Dict, Any, Tuple, Optional
11
 
12
+ # --- Constants ---
13
+ MODEL_NAME = "gemini-2.5-pro-exp-03-25" # Using Gemini 1.5 Flash
14
+
15
+ # Unified prompt to get bounding boxes and text content in one go
16
+ UNIFIED_DETECTION_EXTRACTION_PROMPT = """\
17
+ Analyze this document image. Identify text regions and extract the text from each region.
18
+
19
+ Follow these rules for text regions:
20
+ 1. GROUP RELATED CONTENT:
21
+ - Full tables as SINGLE regions (including headers and all rows).
22
+ - Paragraphs as SINGLE rectangular blocks (multiple lines as one box).
23
+ - Keep text columns intact.
24
+ - Treat list items as single region if visually grouped.
25
+
26
+ 2. TEXT REGION REQUIREMENTS:
27
+ - Boundaries must tightly wrap text content.
28
+ - Include approximately 2% padding around text clusters, but ensure the box stays within image bounds.
29
+ - Exclude isolated decorative elements unless they contain text.
30
+ - Merge adjacent text fragments with ≀1% spacing into a single region.
31
+
32
+ 3. COORDINATE FORMAT:
33
+ - Normalized coordinates (0.0 to 1.0) with 3 decimal places.
34
+ - Format: [xmin, ymin, xmax, ymax].
35
+ - Order: Top-to-bottom, then left-to-right.
36
+
37
+ 4. SPECIAL CASES:
38
+ - Table cells should NOT have individual boxes; the entire table is one box.
39
+ - Page headers/footers as separate regions.
40
+ - Text wrapped around images as distinct regions.
41
 
42
+ OUTPUT FORMAT:
43
+ Return a JSON list of objects. Each object MUST have:
44
+ - "box": A list of 4 normalized coordinates [xmin, ymin, xmax, ymax].
45
+ - "text": The extracted text string from that box. Ensure all text within the box is captured.
46
 
47
+ Example of a valid JSON response:
48
+ [
49
+ {"box": [0.070, 0.120, 0.930, 0.280], "text": "Document Title and Header Information"},
50
+ {"box": [0.120, 0.350, 0.880, 0.650], "text": "Table content including headers and all rows..."},
51
+ {"box": [0.100, 0.700, 0.900, 0.850], "text": "This is the first paragraph of text, potentially spanning multiple lines but grouped as one logical block."},
52
+ {"box": [0.100, 0.880, 0.900, 0.950], "text": "Another paragraph or distinct text block."}
53
+ ]
54
+
55
+ ONLY RETURN THE VALID JSON LIST. No explanations, apologies, or other text outside the JSON structure.
56
+ If no text regions are found, return an empty JSON list: [].
57
  """
58
 
59
+ # --- Helper Functions ---
60
+
61
+ def get_gemini_api_key() -> Optional[str]:
62
+ """Gets the Gemini API key from Streamlit secrets, environment variables, or user input."""
63
+ if "GOOGLE_API_KEY" in st.secrets:
64
+ return st.secrets["GOOGLE_API_KEY"]
65
+ api_key_env = os.getenv("GOOGLE_API_KEY")
66
+ if api_key_env:
67
+ return api_key_env
68
+
69
+ st.sidebar.warning("Google API Key not found in secrets or environment variables.")
70
+ api_key_input = st.sidebar.text_input(
71
+ "Enter your Google API Key:", type="password", key="api_key_input"
72
+ )
73
+ if api_key_input:
74
+ st.session_state.GOOGLE_API_KEY = api_key_input
75
+ return api_key_input
76
+ return None
77
+
78
+ def parse_gemini_response(response_text: str) -> List[Dict[str, Any]]:
79
+ """
80
+ Parses the Gemini response to extract a list of dicts with "box" and "text".
81
+ Tries to load as JSON, falls back to regex if needed (though ideally not).
82
+ """
83
+ try:
84
+ # Attempt to find JSON block if model wraps it in markdown
85
+ match = re.search(r"```json\s*([\s\S]*?)\s*```", response_text, re.DOTALL)
86
+ if match:
87
+ json_str = match.group(1)
88
+ else:
89
+ # Assume the response is plain JSON or a Python list string
90
+ json_str = response_text.strip()
91
+ if not (json_str.startswith('[') and json_str.endswith(']')):
92
+ # If it doesn't look like a list, try to find the list within the text
93
+ list_match = re.search(r'(\[[\s\S]*\])', json_str)
94
+ if list_match:
95
+ json_str = list_match.group(1)
96
+ else:
97
+ st.warning(f"Response doesn't appear to be a list: {response_text[:200]}...")
98
+ return []
99
+
100
+
101
+ # Try direct JSON parsing
102
+ parsed_data = json.loads(json_str)
103
+ if isinstance(parsed_data, list):
104
+ # Validate structure
105
+ validated_data = []
106
+ for item in parsed_data:
107
+ if isinstance(item, dict) and "box" in item and "text" in item and \
108
+ isinstance(item["box"], list) and len(item["box"]) == 4:
109
+ validated_data.append(item)
110
+ else:
111
+ st.warning(f"Skipping invalid item in JSON: {item}")
112
+ return validated_data
113
+ else:
114
+ st.warning(f"Parsed JSON is not a list: {type(parsed_data)}")
115
+ return []
116
+
117
+ except json.JSONDecodeError as e:
118
+ st.warning(f"JSONDecodeError: {e}. Raw response: {response_text[:500]}")
119
+ # Fallback to regex if JSON parsing fails (less robust)
120
+ # This regex assumes the "box" and "text" structure as described in the prompt
121
+ # It's a simplified regex for demonstration and might need adjustment for complex texts.
122
+ regions = []
123
+ # Regex to find "box": [coords], "text": "content"
124
+ # This is a simplified regex and might struggle with escaped quotes in text
125
+ pattern = r'\{\s*"box"\s*:\s*\[([\d\.]+),\s*([\d\.]+),\s*([\d\.]+),\s*([\d\.]+)\]\s*,\s*"text"\s*:\s*"(.*?)"\s*\}'
126
+ matches = re.findall(pattern, response_text, re.DOTALL)
127
+ for match in matches:
128
+ try:
129
+ box = [float(c) for c in match[:4]]
130
+ text = match[4].replace('\\n', '\n').replace('\\"', '"') # Handle basic escapes
131
+ regions.append({"box": box, "text": text})
132
+ except ValueError:
133
+ st.warning(f"Could not parse box coordinates from regex match: {match}")
134
+ if not regions and response_text.strip() and response_text.strip() != "[]":
135
+ st.error(f"Failed to parse response using JSON and regex. Raw: {response_text[:200]}")
136
+ return regions
137
+ except Exception as e:
138
+ st.error(f"Error parsing Gemini response: {e}. Raw response: {response_text[:500]}")
139
+ return []
140
+
141
+
142
+ def draw_bounding_boxes(image: Image.Image, regions: List[Dict[str, Any]]) -> Image.Image:
143
+ """Draws numbered bounding boxes on the image."""
144
+ if not regions:
145
+ return image
146
+
147
+ draw = ImageDraw.Draw(image)
148
+ width, height = image.size
149
+
150
+ try:
151
+ # Try to load a common font, fall back to default
152
+ font = ImageFont.truetype("arial.ttf", int(height * 0.02)) # Adjust size as needed
153
+ except IOError:
154
+ font = ImageFont.load_default()
155
+
156
+ for i, region_data in enumerate(regions):
157
+ try:
158
+ box = region_data.get("box")
159
+ if not (isinstance(box, list) and len(box) == 4):
160
+ st.warning(f"Skipping invalid box data for region {i+1}: {box}")
161
+ continue
162
+
163
+ # Convert normalized coordinates to pixel values, clamping to image bounds
164
+ xmin = max(0.0, min(1.0, box[0])) * width
165
+ ymin = max(0.0, min(1.0, box[1])) * height
166
+ xmax = max(0.0, min(1.0, box[2])) * width
167
+ ymax = max(0.0, min(1.0, box[3])) * height
168
+
169
+ if xmin >= xmax or ymin >= ymax:
170
+ st.warning(f"Skipping invalid box dimensions for region {i+1}: {[xmin, ymin, xmax, ymax]}")
171
+ continue
172
+
173
+ draw.rectangle([xmin, ymin, xmax, ymax], outline="#00FF00", width=3)
174
+ label = str(i + 1)
175
+
176
+ # Position label inside the box, handle potential small boxes
177
+ text_x = xmin + 5
178
+ text_y = ymin + 5
179
+
180
+ # For very small boxes, drawing text might be an issue, but let's try
181
+ text_bbox = draw.textbbox((text_x, text_y), label, font=font)
182
+ text_width = text_bbox[2] - text_bbox[0]
183
+ text_height = text_bbox[3] - text_bbox[1]
184
+
185
+ # Simple check to ensure text fits somewhat
186
+ if text_x + text_width > xmax - 5:
187
+ text_x = max(xmin, xmax - text_width - 5)
188
+ if text_y + text_height > ymax - 5:
189
+ text_y = max(ymin, ymax - text_height - 5)
190
+
191
+ draw.text((text_x, text_y), label, fill="red", font=font)
192
+
193
+ except Exception as e:
194
+ st.error(f"Error drawing box for region {i+1}: {str(e)}")
195
+ return image
196
+
197
+ def process_image_with_gemini(
198
+ client: genai.GenerativeModel, image_bytes: bytes
199
+ ) -> Tuple[List[Dict[str, Any]], str]:
200
+ """Sends image to Gemini and gets bounding boxes and text."""
201
+ try:
202
+ response = client.generate_content(
203
+ contents=[
204
+ UNIFIED_DETECTION_EXTRACTION_PROMPT,
205
+ {"mime_type": "image/png", "data": image_bytes}
206
+ ],
207
+ generation_config=GenerationConfig(
208
+ temperature=0.1, # Lower temperature for more deterministic output
209
+ # max_output_tokens=8192 # Max for flash 1.5
210
+ ),
211
+ safety_settings={ # Adjust as needed
212
+ HarmCategory.HARM_CATEGORY_HARASSMENT: HarmBlockThreshold.BLOCK_NONE,
213
+ HarmCategory.HARM_CATEGORY_HATE_SPEECH: HarmBlockThreshold.BLOCK_NONE,
214
+ HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT: HarmBlockThreshold.BLOCK_NONE,
215
+ HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: HarmBlockThreshold.BLOCK_NONE,
216
+ }
217
+ )
218
+ if response.parts:
219
+ raw_text_response = response.text # .text often combines parts
220
+ else: # Fallback if .text is empty but candidates exist
221
+ raw_text_response = response.candidates[0].content.parts[0].text if response.candidates and response.candidates[0].content.parts else ""
222
+
223
+ if not raw_text_response:
224
+ st.error("Received empty response from Gemini API.")
225
+ return [], ""
226
+
227
+ regions = parse_gemini_response(raw_text_response)
228
+ return regions, raw_text_response
229
+ except Exception as e:
230
+ st.error(f"Error calling Gemini API: {str(e)}")
231
+ if hasattr(e, 'response') and e.response: # For google.api_core.exceptions
232
+ st.error(f"API Response Error Details: {e.response}")
233
+ return [], f"API Error: {str(e)}"
234
+
235
+ # --- Streamlit UI ---
236
+ st.set_page_config(layout="wide")
237
+ st.title("πŸ“„ PDF Text Detection & Extraction with Gemini")
238
+
239
+ # --- API Key Configuration ---
240
+ st.sidebar.header("πŸ”‘ API Configuration")
241
+ api_key = get_gemini_api_key()
242
+ gemini_client = None
243
+
244
+ if api_key:
245
+ try:
246
+ genai.configure(api_key=api_key)
247
+ gemini_client = genai.GenerativeModel(MODEL_NAME)
248
+ st.sidebar.success("Gemini API Key configured.")
249
+ except Exception as e:
250
+ st.sidebar.error(f"Failed to configure Gemini: {e}")
251
+ api_key = None # Invalidate API key if configuration fails
252
+ else:
253
+ st.sidebar.info("Please provide your Google API Key to use the application.")
254
+ st.info("Please enter your Google API Key in the sidebar to proceed.")
255
+
256
+
257
+ # --- File Upload and Processing ---
258
+ st.header("πŸ“€ Upload PDF")
259
+ uploaded_file = st.file_uploader("Choose a PDF file", type=["pdf"])
260
+ dpi_options = [150, 200, 300, 400]
261
+ selected_dpi = st.select_slider(
262
+ "Select DPI for PDF to Image conversion:",
263
+ options=dpi_options,
264
+ value=200 # Default DPI
265
+ )
266
+
267
+ if uploaded_file and st.button("πŸš€ Analyze PDF", disabled=not api_key or not gemini_client):
268
+ if not api_key or not gemini_client:
269
+ st.error("API Key not configured. Please enter it in the sidebar.")
270
+ else:
271
+ with st.spinner(f"Processing PDF ({uploaded_file.name})... This may take a moment."):
272
+ try:
273
+ pdf_bytes = uploaded_file.read()
274
+ pil_images: List[Image.Image] = convert_from_bytes(pdf_bytes, dpi=selected_dpi)
275
+
276
+ if not pil_images:
277
+ st.warning("Could not extract any images from the PDF.")
278
+ else:
279
+ st.success(f"PDF converted to {len(pil_images)} image(s). Analyzing with Gemini...")
280
+
281
+ page_results = []
282
+ for i, p_image in enumerate(pil_images):
283
+ page_progess = st.progress(0, text=f"Processing Page {i+1}/{len(pil_images)}...")
284
+
285
+ # Convert PIL image to bytes for API
286
+ img_byte_arr = io.BytesIO()
287
+ p_image.save(img_byte_arr, format='PNG')
288
+ img_bytes = img_byte_arr.getvalue()
289
+ page_progess.progress(30, text=f"Page {i+1}: Sending to Gemini...")
290
+
291
+ regions, raw_response = process_image_with_gemini(gemini_client, img_bytes)
292
+ page_progess.progress(90, text=f"Page {i+1}: Received response.")
293
+
294
+ page_results.append({
295
+ "original_image": p_image,
296
+ "regions": regions,
297
+ "raw_response": raw_response
298
+ })
299
+ page_progess.progress(100, text=f"Page {i+1}: Done.")
300
+ page_progess.empty()
301
+
302
+ # Store results in session state to avoid re-processing on minor UI interaction
303
+ # Though with the button click, this is less critical for single runs.
304
+ st.session_state.page_results = page_results
305
+
306
+ except Exception as e:
307
+ st.error(f"An error occurred during PDF processing: {str(e)}")
308
+ if "page_results" in st.session_state:
309
+ del st.session_state.page_results # Clear partial results
310
+
311
+ # --- Display Results ---
312
+ if "page_results" in st.session_state and st.session_state.page_results:
313
+ st.header("πŸ“Š Analysis Results")
314
+ results = st.session_state.page_results
315
+
316
+ tab_titles = [f"Page {i+1}" for i in range(len(results))]
317
+ tabs = st.tabs(tab_titles)
318
+
319
+ for idx, (tab, page_data) in enumerate(zip(tabs, results)):
320
+ with tab:
321
+ st.subheader(f"Page {idx + 1} Analysis")
322
+ original_image = page_data["original_image"]
323
+ regions = page_data["regions"]
324
+ raw_response = page_data["raw_response"]
325
+
326
+ col1, col2 = st.columns(2)
327
+
328
+ with col1:
329
+ st.image(original_image, caption="Original Image", use_container_width=True)
330
+
331
+ with col2:
332
+ if regions:
333
+ annotated_image = draw_bounding_boxes(original_image.copy(), regions)
334
+ st.image(annotated_image, caption=f"Detected {len(regions)} Text Regions", use_container_width=True)
335
+ else:
336
+ st.image(original_image.copy(), caption="No text regions detected by model", use_container_width=True)
337
+ st.warning("No text regions were successfully parsed from the model's response for this page.")
338
+
339
+ if regions:
340
+ st.subheader("πŸ“ Extracted Texts & Regions")
341
+ for i, region_data in enumerate(regions):
342
+ box = region_data.get("box", "N/A")
343
+ text_content = region_data.get("text", "No text extracted for this region.")
344
+ with st.expander(f"Region {i+1} (Box: {box})", expanded= (i<3) ): # Expand first 3 by default
345
+ st.markdown(f"**Coordinates:** `{box}`")
346
+ st.markdown("**Text:**")
347
+ st.text_area(f"text_area_{idx}_{i}", text_content, height=max(100, int(len(text_content)*0.5)), disabled=True, label_visibility="collapsed")
348
+ else:
349
+ st.info("No text regions to display for this page.")
350
+
351
+ with st.expander("πŸ” Debug: Raw Gemini API Response", expanded=False):
352
+ st.code(raw_response, language='json')
353
+
354
+ elif uploaded_file and not api_key:
355
+ st.warning("Please enter your API key in the sidebar and click 'Analyze PDF' again.")
356
+
357
+ st.markdown("---")
358
+ st.markdown("Developed with Gemini & Streamlit.")