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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from openai import OpenAI
|
| 3 |
+
from dotenv import load_dotenv
|
| 4 |
+
import plotly.express as px
|
| 5 |
+
import plotly.graph_objects as go
|
| 6 |
+
import requests
|
| 7 |
+
from PIL import Image
|
| 8 |
+
from io import BytesIO
|
| 9 |
+
import numpy as np
|
| 10 |
+
import json
|
| 11 |
+
|
| 12 |
+
load_dotenv()
|
| 13 |
+
client = OpenAI(
|
| 14 |
+
base_url = "",
|
| 15 |
+
api_key = os.environ["HF_TOKEN"]
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
prompt = """\
|
| 19 |
+
Please output the layout information from the PDF image, including each layout element's bbox, its category, and the corresponding text content within the bbox.
|
| 20 |
+
1. Bbox format: [x1, y1, x2, y2]
|
| 21 |
+
2. Layout Categories: The possible categories are ['Caption', 'Footnote', 'Formula', 'List-item', 'Page-footer', 'Page-header', 'Picture', 'Section-header', 'Table', 'Text', 'Title'].
|
| 22 |
+
3. Text Extraction & Formatting Rules:
|
| 23 |
+
- Picture: For the 'Picture' category, the text field should be omitted.
|
| 24 |
+
- Formula: Format its text as LaTeX.
|
| 25 |
+
- Table: Format its text as HTML.
|
| 26 |
+
- All Others (Text, Title, etc.): Format their text as Markdown.
|
| 27 |
+
4. Constraints:
|
| 28 |
+
- The output text must be the original text from the image, with no translation.
|
| 29 |
+
- All layout elements must be sorted according to human reading order.
|
| 30 |
+
5. Final Output: The entire output must be a single JSON object.\
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
chat_completion = client.chat.completions.create(
|
| 34 |
+
model = "rednote-hilab/dots.ocr",
|
| 35 |
+
messages = [
|
| 36 |
+
{
|
| 37 |
+
"role": "user",
|
| 38 |
+
"content": [
|
| 39 |
+
{
|
| 40 |
+
"type": "image_url",
|
| 41 |
+
"image_url": {
|
| 42 |
+
"url": "https://github.com/rednote-hilab/dots.ocr/blob/master/demo/demo_image1.jpg?raw=true"
|
| 43 |
+
}
|
| 44 |
+
},
|
| 45 |
+
{
|
| 46 |
+
"type": "text",
|
| 47 |
+
"text": prompt,
|
| 48 |
+
}
|
| 49 |
+
]
|
| 50 |
+
}
|
| 51 |
+
],
|
| 52 |
+
stream = True,
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
text = ""
|
| 56 |
+
for message in chat_completion:
|
| 57 |
+
text = text + message.choices[0].delta.content
|
| 58 |
+
|
| 59 |
+
annotations = json.loads(text)
|
| 60 |
+
|
| 61 |
+
# Load image
|
| 62 |
+
url = "https://github.com/rednote-hilab/dots.ocr/blob/master/demo/demo_image1.jpg?raw=true"
|
| 63 |
+
response = requests.get(url)
|
| 64 |
+
img = Image.open(BytesIO(response.content))
|
| 65 |
+
img_array = np.array(img)
|
| 66 |
+
|
| 67 |
+
# Enhanced color mapping for different categories
|
| 68 |
+
category_colors = {
|
| 69 |
+
'Title': '#FF6B6B',
|
| 70 |
+
'Section-header': '#4ECDC4',
|
| 71 |
+
'Text': '#45B7D1',
|
| 72 |
+
'Picture': '#96CEB4',
|
| 73 |
+
'Table': '#FFEAA7',
|
| 74 |
+
'Formula': '#DDA0DD',
|
| 75 |
+
'Caption': '#98D8C8',
|
| 76 |
+
'List-item': '#F7DC6F',
|
| 77 |
+
'Footnote': '#BB8FCE',
|
| 78 |
+
'Page-header': '#85C1E9',
|
| 79 |
+
'Page-footer': '#F8C471'
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
# Create figure with enhanced settings
|
| 83 |
+
fig = px.imshow(img_array, aspect='equal')
|
| 84 |
+
|
| 85 |
+
# Enhanced layout configuration
|
| 86 |
+
fig.update_layout(
|
| 87 |
+
title={
|
| 88 |
+
'text': "Interactive OCR Layout Analysis",
|
| 89 |
+
'x': 0.5,
|
| 90 |
+
'xanchor': 'center',
|
| 91 |
+
'font': {'size': 18, 'family': 'Arial Black'}
|
| 92 |
+
},
|
| 93 |
+
dragmode="pan", # Enable panning
|
| 94 |
+
hovermode="closest",
|
| 95 |
+
margin=dict(l=20, r=20, t=60, b=20),
|
| 96 |
+
showlegend=True,
|
| 97 |
+
legend=dict(
|
| 98 |
+
orientation="v",
|
| 99 |
+
yanchor="top",
|
| 100 |
+
y=1,
|
| 101 |
+
xanchor="left",
|
| 102 |
+
x=1.02,
|
| 103 |
+
bgcolor="rgba(255,255,255,0.8)",
|
| 104 |
+
bordercolor="rgba(0,0,0,0.2)",
|
| 105 |
+
borderwidth=1
|
| 106 |
+
),
|
| 107 |
+
plot_bgcolor='white',
|
| 108 |
+
paper_bgcolor='white'
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
# Track categories for legend
|
| 112 |
+
added_categories = set()
|
| 113 |
+
|
| 114 |
+
# Add enhanced bounding boxes with category-based colors
|
| 115 |
+
for i, ann in enumerate(annotations):
|
| 116 |
+
x1, y1, x2, y2 = ann['bbox']
|
| 117 |
+
category = ann.get('category', 'Unknown')
|
| 118 |
+
color = category_colors.get(category, '#FF4444')
|
| 119 |
+
|
| 120 |
+
# Enhanced bounding box with category-specific styling
|
| 121 |
+
line_width = 3 if category in ['Title', 'Section-header'] else 2
|
| 122 |
+
opacity = 0.8 if category == 'Picture' else 1.0
|
| 123 |
+
|
| 124 |
+
fig.add_shape(
|
| 125 |
+
type="rect",
|
| 126 |
+
x0=x1, y0=y1, x1=x2, y1=y2,
|
| 127 |
+
line=dict(color=color, width=line_width),
|
| 128 |
+
opacity=opacity
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
# Enhanced hover information with better formatting
|
| 132 |
+
text_content = ann.get('text', 'No text available')
|
| 133 |
+
if len(text_content) > 200:
|
| 134 |
+
text_content = text_content[:200] + "..."
|
| 135 |
+
|
| 136 |
+
# Format hover text based on category
|
| 137 |
+
if category == 'Formula':
|
| 138 |
+
hover_text = f"<b>π’ {category}</b><br><i>{text_content}</i>"
|
| 139 |
+
elif category == 'Picture':
|
| 140 |
+
hover_text = f"<b>πΌοΈ {category}</b><br>Image element"
|
| 141 |
+
elif category == 'Table':
|
| 142 |
+
hover_text = f"<b>π {category}</b><br>{text_content}"
|
| 143 |
+
elif category == 'Title':
|
| 144 |
+
hover_text = f"<b>π {category}</b><br><b>{text_content}</b>"
|
| 145 |
+
else:
|
| 146 |
+
hover_text = f"<b>π {category}</b><br>{text_content}"
|
| 147 |
+
|
| 148 |
+
# Add bbox dimensions to hover
|
| 149 |
+
width = x2 - x1
|
| 150 |
+
height = y2 - y1
|
| 151 |
+
hover_text += f"<br><br><i>Box: {width:.0f}Γ{height:.0f}px</i>"
|
| 152 |
+
|
| 153 |
+
# Create hover point with legend entry
|
| 154 |
+
show_legend = category not in added_categories
|
| 155 |
+
if show_legend:
|
| 156 |
+
added_categories.add(category)
|
| 157 |
+
|
| 158 |
+
fig.add_trace(go.Scatter(
|
| 159 |
+
x=[(x1 + x2) / 2],
|
| 160 |
+
y=[(y1 + y2) / 2],
|
| 161 |
+
mode="markers",
|
| 162 |
+
marker=dict(
|
| 163 |
+
size=20,
|
| 164 |
+
opacity=0, # Invisible marker
|
| 165 |
+
color=color
|
| 166 |
+
),
|
| 167 |
+
text=[hover_text],
|
| 168 |
+
hoverinfo="text",
|
| 169 |
+
hovertemplate="%{text}<extra></extra>",
|
| 170 |
+
name=category,
|
| 171 |
+
showlegend=show_legend,
|
| 172 |
+
legendgroup=category
|
| 173 |
+
))
|
| 174 |
+
|
| 175 |
+
# Enhanced axes configuration
|
| 176 |
+
fig.update_xaxes(
|
| 177 |
+
showticklabels=False,
|
| 178 |
+
showgrid=False,
|
| 179 |
+
zeroline=False
|
| 180 |
+
)
|
| 181 |
+
fig.update_yaxes(
|
| 182 |
+
showticklabels=False,
|
| 183 |
+
showgrid=False,
|
| 184 |
+
zeroline=False,
|
| 185 |
+
scaleanchor="x",
|
| 186 |
+
scaleratio=1
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
# Add custom controls info
|
| 190 |
+
fig.add_annotation(
|
| 191 |
+
text="π‘ Hover over colored boxes to see content β’ Pan: drag β’ Zoom: scroll",
|
| 192 |
+
xref="paper", yref="paper",
|
| 193 |
+
x=0.5, y=-0.05,
|
| 194 |
+
showarrow=False,
|
| 195 |
+
font=dict(size=12, color="gray"),
|
| 196 |
+
xanchor="center"
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
# Display statistics
|
| 200 |
+
total_elements = len(annotations)
|
| 201 |
+
category_counts = {}
|
| 202 |
+
for ann in annotations:
|
| 203 |
+
cat = ann.get('category', 'Unknown')
|
| 204 |
+
category_counts[cat] = category_counts.get(cat, 0) + 1
|
| 205 |
+
|
| 206 |
+
print(f"π Layout Analysis Complete!")
|
| 207 |
+
print(f"Total elements detected: {total_elements}")
|
| 208 |
+
print("Category breakdown:")
|
| 209 |
+
for cat, count in sorted(category_counts.items()):
|
| 210 |
+
print(f" β’ {cat}: {count}")
|
| 211 |
+
|
| 212 |
+
fig.show()
|