Souvik3333 commited on
Commit
e3a2d49
·
verified ·
1 Parent(s): 815571c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +262 -164
app.py CHANGED
@@ -1,28 +1,42 @@
 
 
 
 
 
 
1
  import gradio as gr
2
  from PIL import Image
3
- from transformers import AutoTokenizer, AutoProcessor, AutoModelForImageTextToText, TextIteratorStreamer
4
- import torch
5
  import spaces
6
  from threading import Thread
 
 
 
 
 
 
7
 
 
 
8
  model_path = "nanonets/Nanonets-OCR-s"
9
 
10
- # Load model once at startup
11
  print("Loading Nanonets OCR model...")
12
  model = AutoModelForImageTextToText.from_pretrained(
13
- model_path,
14
- torch_dtype="auto",
15
- device_map="auto",
16
  attn_implementation="flash_attention_2"
17
  )
18
  model.eval()
19
 
20
- tokenizer = AutoTokenizer.from_pretrained(model_path)
21
  processor = AutoProcessor.from_pretrained(model_path)
 
22
  print("Model loaded successfully!")
23
 
24
 
 
25
  def process_tags(content: str) -> str:
 
26
  content = content.replace("<img>", "&lt;img&gt;")
27
  content = content.replace("</img>", "&lt;/img&gt;")
28
  content = content.replace("<watermark>", "&lt;watermark&gt;")
@@ -31,115 +45,229 @@ def process_tags(content: str) -> str:
31
  content = content.replace("</page_number>", "&lt;/page_number&gt;")
32
  content = content.replace("<signature>", "&lt;signature&gt;")
33
  content = content.replace("</signature>", "&lt;/signature&gt;")
34
-
35
  return content
36
 
37
- @spaces.GPU()
38
- def ocr_image_gradio_stream(image, max_tokens=4096):
39
- """Process image through Nanonets OCR model with streaming output"""
40
- if image is None:
41
- yield "Please upload an image.", gr.update(interactive=True)
42
- return
 
 
 
 
 
 
 
 
 
 
43
 
44
- # Disable button at start of processing
45
- yield "Processing image...", gr.update(interactive=False)
 
 
 
46
 
47
- try:
48
- prompt = """Extract the text from the above document as if you were reading it naturally. Return the tables in html format. Watermarks should be wrapped in brackets. Ex: <watermark>OFFICIAL COPY</watermark>. Page numbers should be wrapped in brackets. Ex: <page_number>14</page_number> or <page_number>9/22</page_number>. Prefer using ☐ and ☑ for check boxes."""
49
-
50
- # Convert PIL image if needed
51
- if not isinstance(image, Image.Image):
52
- image = Image.fromarray(image)
53
-
54
- messages = [
55
- {"role": "system", "content": "You are a helpful assistant."},
56
- {"role": "user", "content": [
57
- {"type": "image", "image": image},
58
- {"type": "text", "text": prompt},
59
- ]},
60
- ]
61
-
62
- text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
63
- inputs = processor(text=[text], images=[image], padding=True, return_tensors="pt")
64
- inputs = inputs.to(model.device)
65
-
66
- # Set up streaming
67
- streamer = TextIteratorStreamer(
68
- tokenizer,
69
- timeout=60.0,
70
- skip_prompt=True,
71
- skip_special_tokens=True
72
- )
73
-
74
- generation_kwargs = {
75
- **inputs,
76
- "max_new_tokens": max_tokens,
77
- "do_sample": False,
78
- "streamer": streamer
79
- }
80
-
81
- # Start generation in a separate thread
82
- thread = Thread(target=model.generate, kwargs=generation_kwargs)
83
- thread.start()
84
-
85
- # Stream the results
86
- generated_text = ""
87
- for new_text in streamer:
88
- generated_text += new_text
89
- processed_text = process_tags(generated_text)
90
- yield process_tags(processed_text), gr.update(interactive=False)
91
-
92
- # Re-enable button when complete
93
- yield process_tags(processed_text), gr.update(interactive=True)
94
 
95
- except Exception as e:
96
- error_msg = f"Error processing image: {str(e)}"
97
- yield error_msg, gr.update(interactive=True)
98
-
99
- # Keep the original function for non-streaming use if needed
100
- @spaces.GPU()
101
- def ocr_image_gradio(image, max_tokens=4096):
102
- """Process image through Nanonets OCR model for Gradio interface (non-streaming)"""
103
- if image is None:
104
- return "Please upload an image."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
 
106
- try:
107
- prompt = """Extract the text from the above document as if you were reading it naturally. Return the tables in html format. Watermarks should be wrapped in brackets. Ex: <watermark>OFFICIAL COPY</watermark>. Page numbers should be wrapped in brackets. Ex: <page_number>14</page_number> or <page_number>9/22</page_number>. Prefer using ☐ and ☑ for check boxes."""
108
-
109
- # Convert PIL image if needed
110
- if not isinstance(image, Image.Image):
111
- image = Image.fromarray(image)
112
-
113
- messages = [
114
- {"role": "system", "content": "You are a helpful assistant."},
115
- {"role": "user", "content": [
116
- {"type": "image", "image": image},
117
- {"type": "text", "text": prompt},
118
- ]},
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
  ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
 
121
- text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
122
- inputs = processor(text=[text], images=[image], padding=True, return_tensors="pt")
123
- inputs = inputs.to(model.device)
124
-
125
- with torch.no_grad():
126
- output_ids = model.generate(**inputs, max_new_tokens=max_tokens, do_sample=False)
127
- generated_ids = [output_ids[len(input_ids):] for input_ids, output_ids in zip(inputs.input_ids, output_ids)]
128
 
129
- output_text = processor.batch_decode(generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True)
130
- return process_tags(output_text[0])
131
-
 
 
 
132
  except Exception as e:
133
- return f"Error processing image: {str(e)}"
134
 
135
- # Create Gradio interface
136
- with gr.Blocks(title="Nanonets OCR Demo") as demo:
137
- # Replace simple markdown with styled HTML header that includes resources
138
  gr.HTML("""
139
  <div class="title" style="text-align: center">
140
- <h1>🔍 Nanonets OCR - Document Text Extraction</h1>
141
  <p style="font-size: 1.1em; color: #6b7280; margin-bottom: 0.6em;">
142
- A model for transforming documents into structured markdown with intelligent content recognition and semantic tagging
143
  </p>
144
  <div style="display: flex; justify-content: center; gap: 20px; margin: 15px 0;">
145
  <a href="https://huggingface.co/nanonets/Nanonets-OCR-s" target="_blank" style="text-decoration: none; color: #2563eb; font-weight: 500;">
@@ -154,84 +282,54 @@ with gr.Blocks(title="Nanonets OCR Demo") as demo:
154
  </div>
155
  </div>
156
  """)
157
-
158
  with gr.Row():
159
  with gr.Column(scale=1):
160
- image_input = gr.Image(
161
- label="Upload Document Image",
162
- type="pil",
163
- height=400
164
  )
165
  max_tokens_slider = gr.Slider(
166
  minimum=1024,
167
  maximum=8192,
168
  value=4096,
169
  step=512,
170
- label="Max Tokens",
171
- info="Maximum number of tokens to generate"
172
  )
173
- extract_btn = gr.Button("Extract Text", variant="primary", size="lg")
174
-
 
 
 
 
 
175
  with gr.Column(scale=2):
176
  output_text = gr.Markdown(
177
- label="Formatted model prediction",
178
- latex_delimiters=[
179
- {"left": "$$", "right": "$$", "display": True},
180
- {"left": "$", "right": "$", "display": False},
181
- {
182
- "left": "\\begin{align*}",
183
- "right": "\\end{align*}",
184
- "display": True,
185
- },
186
- ],
187
  line_breaks=True,
188
  show_copy_button=True,
 
189
  )
190
-
191
- # Event handlers - Updated to use streaming
192
  extract_btn.click(
193
- fn=ocr_image_gradio_stream,
194
- inputs=[image_input, max_tokens_slider],
195
- outputs=[output_text, extract_btn],
196
- show_progress=True
197
  )
198
-
199
- # image_input.change(
200
- # fn=ocr_image_gradio_stream,
201
- # inputs=[image_input, max_tokens_slider],
202
- # outputs=[output_text, extract_btn],
203
- # show_progress=True
204
- # )
205
-
206
- # Add model information section
207
- with gr.Accordion("About Nanonets-OCR-s", open=False):
208
- gr.Markdown("""
209
- ## Nanonets-OCR-s
210
-
211
- Nanonets-OCR-s is a powerful, state-of-the-art image-to-markdown OCR model that goes far beyond traditional text extraction.
212
- It transforms documents into structured markdown with intelligent content recognition and semantic tagging, making it ideal
213
- for downstream processing by Large Language Models (LLMs).
214
-
215
- ### Key Features
216
 
217
- - **LaTeX Equation Recognition**: Automatically converts mathematical equations and formulas into properly formatted LaTeX syntax.
218
- It distinguishes between inline `($...$)` and display `($$...$$)` equations.
219
-
220
- - **Intelligent Image Description**: Describes images within documents using structured `<img>` tags, making them digestible
221
- for LLM processing. It can describe various image types, including logos, charts, graphs and so on, detailing their content,
222
- style, and context.
223
-
224
- - **Signature Detection & Isolation**: Identifies and isolates signatures from other text, outputting them within a `<signature>` tag.
225
- This is crucial for processing legal and business documents.
226
-
227
- - **Watermark Extraction**: Detects and extracts watermark text from documents, placing it within a `<watermark>` tag.
228
-
229
- - **Smart Checkbox Handling**: Converts form checkboxes and radio buttons into standardized Unicode symbols (☐, ☑, ☒)
230
- for consistent and reliable processing.
231
-
232
- - **Complex Table Extraction**: Accurately extracts complex tables from documents and converts them into both markdown
233
- and HTML table formats.
234
- """)
235
 
236
  if __name__ == "__main__":
237
- demo.queue().launch()
 
1
+ # app.py
2
+ # Remember to add 'PyMuPDF', 'pdf2image', and 'torch' to your requirements.txt or install them.
3
+ # For PDF processing, you might also need to install poppler:
4
+ # On Debian/Ubuntu: sudo apt-get install poppler-utils
5
+ # On macOS (using Homebrew): brew install poppler
6
+
7
  import gradio as gr
8
  from PIL import Image
9
+ from transformers import AutoModelForImageTextToText, AutoProcessor, AutoTokenizer, TextIteratorStreamer
 
10
  import spaces
11
  from threading import Thread
12
+ from pdf2image import convert_from_path
13
+ import os
14
+ import tempfile
15
+ import base64
16
+ from io import BytesIO
17
+ import time
18
 
19
+ # --- Model Loading ---
20
+ # Load the model, processor, and tokenizer once when the app starts.
21
  model_path = "nanonets/Nanonets-OCR-s"
22
 
 
23
  print("Loading Nanonets OCR model...")
24
  model = AutoModelForImageTextToText.from_pretrained(
25
+ model_path,
26
+ torch_dtype="auto",
27
+ device_map="auto",
28
  attn_implementation="flash_attention_2"
29
  )
30
  model.eval()
31
 
 
32
  processor = AutoProcessor.from_pretrained(model_path)
33
+ tokenizer = AutoTokenizer.from_pretrained(model_path)
34
  print("Model loaded successfully!")
35
 
36
 
37
+ # --- Helper Functions ---
38
  def process_tags(content: str) -> str:
39
+ """Replaces special tags with HTML entities to prevent them from being rendered as HTML."""
40
  content = content.replace("<img>", "&lt;img&gt;")
41
  content = content.replace("</img>", "&lt;/img&gt;")
42
  content = content.replace("<watermark>", "&lt;watermark&gt;")
 
45
  content = content.replace("</page_number>", "&lt;/page_number&gt;")
46
  content = content.replace("<signature>", "&lt;signature&gt;")
47
  content = content.replace("</signature>", "&lt;/signature&gt;")
 
48
  return content
49
 
50
+ def encode_image(image: Image) -> str:
51
+ """Encodes an image to a base64 string."""
52
+ buffered = BytesIO()
53
+ image.save(buffered, format="JPEG")
54
+ img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
55
+ return img_str
56
+
57
+ @spaces.GPU
58
+ def stream_request(
59
+ messages: list[dict],
60
+ model_name: str,
61
+ max_tokens: int = 8000,
62
+ temperature: float = 0.0,
63
+ ):
64
+ """
65
+ Stream text generation from the OCR model given messages with images and text.
66
 
67
+ Args:
68
+ messages: List of message dictionaries with role and content
69
+ model_name: Name of the model (unused but kept for compatibility)
70
+ max_tokens: Maximum number of tokens to generate
71
+ temperature: Temperature for generation (unused, model runs deterministically)
72
 
73
+ Yields:
74
+ str: Generated text chunks
75
+ """
76
+ # Extract the image and text from messages
77
+ for message in messages:
78
+ if message["role"] == "user":
79
+ content = message["content"]
80
+ image_data = None
81
+ text_prompt = ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
 
83
+ for item in content:
84
+ if item["type"] == "image_url":
85
+ # Decode base64 image
86
+ image_url = item["image_url"]["url"]
87
+ if image_url.startswith("data:image/jpeg;base64,"):
88
+ image_base64 = image_url.split(",")[1]
89
+ image_bytes = base64.b64decode(image_base64)
90
+ image_data = Image.open(BytesIO(image_bytes))
91
+ elif item["type"] == "text":
92
+ text_prompt = item["text"]
93
+
94
+ if image_data is not None:
95
+ # Format messages in the expected format for the model
96
+ formatted_messages = [
97
+ {"role": "system", "content": "You are a helpful assistant."},
98
+ {"role": "user", "content": [
99
+ {"type": "image", "image": image_data},
100
+ {"type": "text", "text": text_prompt},
101
+ ]},
102
+ ]
103
+
104
+ # Apply chat template to format the input properly
105
+ text = processor.apply_chat_template(
106
+ formatted_messages,
107
+ tokenize=False,
108
+ add_generation_prompt=True
109
+ )
110
+
111
+ # Process the formatted text and image
112
+ inputs = processor(
113
+ text=[text],
114
+ images=[image_data],
115
+ padding=True,
116
+ return_tensors="pt"
117
+ )
118
+
119
+ # Move inputs to the same device as the model
120
+ inputs = {k: v.to(model.device) if hasattr(v, 'to') else v for k, v in inputs.items()}
121
+
122
+ # Set up streaming
123
+ streamer = TextIteratorStreamer(
124
+ tokenizer,
125
+ timeout=60.0,
126
+ skip_prompt=True,
127
+ skip_special_tokens=True
128
+ )
129
+
130
+ generation_kwargs = {
131
+ **inputs,
132
+ "streamer": streamer,
133
+ "max_new_tokens": max_tokens,
134
+ "do_sample": False, # Deterministic generation
135
+ "pad_token_id": tokenizer.eos_token_id,
136
+ }
137
+
138
+ # Start generation in a separate thread
139
+ thread = Thread(target=model.generate, kwargs=generation_kwargs)
140
+ thread.start()
141
+
142
+ # Yield generated tokens as they come
143
+ for new_text in streamer:
144
+ yield new_text
145
+
146
+ thread.join()
147
+ return
148
 
149
+ # If no valid image/text pair found, return empty
150
+ yield ""
151
+
152
+ def convert_to_markdown_stream(
153
+ images: Image, model_name, max_gen_tokens, with_img_desc: bool = False
154
+ ):
155
+ """
156
+ Generator function that yields streaming markdown conversion results
157
+ Processes images one by one and concatenates results
158
+ """
159
+ images = [images]
160
+ # validate_file_paths(file_paths)
161
+ # file_paths = convert_files_to_images(file_paths)
162
+ # resize_images(file_paths, max_img_size)
163
+
164
+ # Create system prompt for PDF to markdown conversion
165
+ if with_img_desc:
166
+ user_prompt = """Extract the text from the above document as if you were reading it naturally. Return the tables in html format. Return the equations in LaTeX representation. If there is an image in the document and image caption is not present, add a small description of the image inside the <img></img> tag; otherwise, add the image caption inside <img></img>. Watermarks should be wrapped in brackets. Ex: <watermark>OFFICIAL COPY</watermark>. Page numbers should be wrapped in brackets. Ex: <page_number>14</page_number> or <page_number>9/22</page_number>. Prefer using ☐ and ☑ for check boxes."""
167
+ else:
168
+ user_prompt = """Extract the text from the above document as if you were reading it naturally. Return the tables in html format. Watermarks should be wrapped in brackets. Ex: <watermark>OFFICIAL COPY</watermark>. Page numbers should be wrapped in brackets. Ex: <page_number>14</page_number> or <page_number>9/22</page_number>. Prefer using ☐ and ☑ for check boxes."""
169
+
170
+
171
+ # Accumulate results from all pages
172
+ full_markdown_content = ""
173
+
174
+ # Process each image individually
175
+ for i, image in enumerate(images):
176
+ # Build messages for this single image
177
+ content = [
178
+ {
179
+ "type": "image_url",
180
+ "image_url": {
181
+ "url": f"data:image/jpeg;base64,{encode_image(image)}"
182
+ },
183
+ },
184
+ {"type": "text", "text": user_prompt},
185
  ]
186
+
187
+ messages = [{"role": "user", "content": content}]
188
+
189
+ # Stream this individual page
190
+ page_content = ""
191
+ try:
192
+ for chunk in stream_request(
193
+ messages=messages,
194
+ model_name=model_name,
195
+ max_tokens=max_gen_tokens,
196
+ ):
197
+ page_content += chunk
198
+ # Yield accumulated content from all pages processed so far + current page
199
+ current_total = (
200
+ full_markdown_content
201
+ + f"Page {i + 1} of {len(images)}\n"
202
+ + page_content
203
+ )
204
+ time.sleep(0.05)
205
+ yield current_total
206
+
207
+ # Process the completed page content and add it to the full content
208
+ full_markdown_content += (
209
+ f"Page {i + 1} of {len(images)}\n" + page_content
210
+ )
211
+
212
+ except Exception as e:
213
+ return f"Error: {e}"
214
+
215
+ def process_document(file_path, max_tokens, with_img_desc: bool = False):
216
+ """
217
+ Process uploaded document (PDF or image) and convert to markdown.
218
+
219
+ Args:
220
+ file_path: Path to uploaded file
221
+ max_tokens: Maximum tokens per page
222
+
223
+ Returns:
224
+ Generator yielding markdown content
225
+ """
226
+ if file_path is None:
227
+ return "Please upload a file first."
228
+
229
+ try:
230
+ # Handle PDF files
231
+ if file_path.name.lower().endswith('.pdf'):
232
+ # Convert PDF to images
233
+ with tempfile.TemporaryDirectory() as temp_dir:
234
+ # Copy uploaded file to temp directory
235
+ temp_pdf_path = os.path.join(temp_dir, "document.pdf")
236
+ import shutil
237
+ shutil.copy(file_path.name, temp_pdf_path)
238
+
239
+ # Convert PDF pages to images
240
+ images = convert_from_path(temp_pdf_path, dpi=150)
241
+ images = [image.convert("RGB") for image in images]
242
+ images = [image.resize((2048, 2048)) for image in images]
243
+ # Process each page
244
+ for result in convert_to_markdown_stream(
245
+ images, "nanonets/Nanonets-OCR-s", max_tokens, with_img_desc
246
+ ):
247
+ yield process_tags(result)
248
 
249
+ # Handle image files
250
+ else:
251
+ # Open image directly
252
+ image = Image.open(file_path.name).convert("RGB")
253
+ image = image.resize((2048, 2048))
 
 
254
 
255
+ # Process single image
256
+ for result in convert_to_markdown_stream(
257
+ image, "nanonets/Nanonets-OCR-s", max_tokens, with_img_desc
258
+ ):
259
+ yield process_tags(result)
260
+
261
  except Exception as e:
262
+ yield f"Error processing document: {str(e)}"
263
 
264
+ # --- Gradio Interface ---
265
+ with gr.Blocks(title="PDF to Markdown Converter", theme=gr.themes.Soft()) as demo:
 
266
  gr.HTML("""
267
  <div class="title" style="text-align: center">
268
+ <h1>📄 Nanonets-OCR-s: PDF & Image to Markdown Converter</h1>
269
  <p style="font-size: 1.1em; color: #6b7280; margin-bottom: 0.6em;">
270
+ Powered by <strong>Nanonets-OCR-s</strong>, A model for transforming documents into structured markdown with intelligent content recognition and semantic tagging.
271
  </p>
272
  <div style="display: flex; justify-content: center; gap: 20px; margin: 15px 0;">
273
  <a href="https://huggingface.co/nanonets/Nanonets-OCR-s" target="_blank" style="text-decoration: none; color: #2563eb; font-weight: 500;">
 
282
  </div>
283
  </div>
284
  """)
285
+
286
  with gr.Row():
287
  with gr.Column(scale=1):
288
+ file_input = gr.File(
289
+ label="Upload PDF or Image Document",
290
+ file_types=["pdf", "image"],
291
+ height=200
292
  )
293
  max_tokens_slider = gr.Slider(
294
  minimum=1024,
295
  maximum=8192,
296
  value=4096,
297
  step=512,
298
+ label="Max Tokens per Page",
299
+ info="Maximum number of new tokens to generate for each page."
300
  )
301
+ with_img_desc_checkbox = gr.Checkbox(
302
+ label="Include Image Description",
303
+ value=False,
304
+ info="If enabled, the model will include a description of the image in the output. If no image is present, use with_img_desc=False."
305
+ )
306
+ extract_btn = gr.Button("Convert to Markdown", variant="primary", size="lg")
307
+
308
  with gr.Column(scale=2):
309
  output_text = gr.Markdown(
310
+ label="Formatted Model Prediction",
311
+ latex_delimiters=[{"left": "$$", "right": "$$", "display": True}, {"left": "$", "right": "$", "display": False}],
 
 
 
 
 
 
 
 
312
  line_breaks=True,
313
  show_copy_button=True,
314
+ height=600,
315
  )
316
+
 
317
  extract_btn.click(
318
+ fn=process_document,
319
+ inputs=[file_input, max_tokens_slider, with_img_desc_checkbox],
320
+ concurrency_limit=4,
321
+ outputs=output_text
322
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
323
 
324
+ with gr.Accordion("About the Model (Nanonets-OCR-s)", open=False):
325
+ gr.Markdown("""
326
+ ### Key Features
327
+ - **LaTeX Equation Recognition**: Converts mathematical equations into properly formatted LaTeX.
328
+ - **Intelligent Image Description**: Describes images within documents using structured `<img>` tags.
329
+ - **Signature & Watermark Detection**: Identifies and isolates signatures and watermarks within `<signature>` and `<watermark>` tags.
330
+ - **Smart Checkbox Handling**: Converts form checkboxes into standardized Unicode symbols (☐, ☑).
331
+ - **Complex Table Extraction**: Accurately converts tables into HTML format.
332
+ """)
 
 
 
 
 
 
 
 
 
333
 
334
  if __name__ == "__main__":
335
+ demo.queue().launch(debug=True)