Spaces:
Sleeping
Sleeping
File size: 11,564 Bytes
1adc2e7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 | import os
import re
import json
import math
import tempfile
import fitz # PyMuPDF
import cv2
import numpy as np
from PIL import Image
import streamlit as st
# -------------------
# Config
# -------------------
DPI = 300
OUT_DIR = "outputs"
KEEP_ONLY_STRESS_STRAIN = False
CAP_RE = re.compile(r"^(Fig\.?\s*\d+|Figure\s*\d+)\b", re.IGNORECASE)
SS_KW = re.compile(
r"(stress\s*[-–]?\s*strain|stress|strain|tensile|MPa|GPa|kN|yield|elongation)",
re.IGNORECASE
)
# -------------------
# Render helpers
# -------------------
def render_page(page, dpi=DPI):
mat = fitz.Matrix(dpi/72, dpi/72)
pix = page.get_pixmap(matrix=mat, alpha=False)
img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
return img, mat
def pdf_to_px_bbox(bbox_pdf, mat):
x0, y0, x1, y1 = bbox_pdf
sx, sy = mat.a, mat.d
return (int(float(x0) * sx), int(float(y0) * sy), int(float(x1) * sx), int(float(y1) * sy))
def safe_crop_px(pil_img, box):
if not isinstance(box, (tuple, list)):
return None
if len(box) == 1 and isinstance(box[0], (tuple, list)) and len(box[0]) == 4:
box = box[0]
if len(box) != 4:
return None
x0, y0, x1, y1 = box
if any(isinstance(v, (tuple, list)) for v in (x0, y0, x1, y1)):
return None
try:
x0 = int(x0)
y0 = int(y0)
x1 = int(x1)
y1 = int(y1)
except (TypeError, ValueError):
return None
if x1 < x0:
x0, x1 = x1, x0
if y1 < y0:
y0, y1 = y1, y0
W, H = pil_img.size
x0 = max(0, min(W, x0))
x1 = max(0, min(W, x1))
y0 = max(0, min(H, y0))
y1 = max(0, min(H, y1))
if x1 <= x0 or y1 <= y0:
return None
return pil_img.crop((x0, y0, x1, y1))
# -------------------
# Captions
# -------------------
def find_caption_blocks(page):
caps = []
blocks = page.get_text("blocks")
for b in blocks:
x0, y0, x1, y1, text = b[0], b[1], b[2], b[3], b[4]
t = " ".join(str(text).strip().split())
if CAP_RE.match(t):
caps.append({"bbox": (x0, y0, x1, y1), "text": t})
return caps
# -------------------
# Dedupe: dHash
# -------------------
def dhash64(pil_img):
gray = pil_img.convert("L").resize((9, 8), Image.LANCZOS)
pixels = list(gray.getdata())
bits = 0
for r in range(8):
for c in range(8):
left = pixels[r * 9 + c]
right = pixels[r * 9 + c + 1]
bits = (bits << 1) | (1 if left > right else 0)
return bits
# -------------------
# Rejectors
# -------------------
def has_colorbar_like_strip(pil_img):
img = np.array(pil_img)
if img.ndim != 3:
return False
H, W, _ = img.shape
if W < 250 or H < 150:
return False
strip_w = max(18, int(0.07 * W))
strip = img[:, W-strip_w:W, :]
q = (strip // 24).reshape(-1, 3)
uniq = np.unique(q, axis=0)
return len(uniq) > 70
def texture_score(pil_img):
gray = cv2.cvtColor(np.array(pil_img), cv2.COLOR_RGB2GRAY)
lap = cv2.Laplacian(gray, cv2.CV_64F)
return float(lap.var())
def is_mostly_legend(pil_img):
gray = cv2.cvtColor(np.array(pil_img), cv2.COLOR_RGB2GRAY)
bw = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
bw = cv2.medianBlur(bw, 3)
H, W = bw.shape
fill = float(np.count_nonzero(bw)) / float(H * W)
return (0.03 < fill < 0.18) and (min(H, W) < 260)
# -------------------
# Plot detection
# -------------------
def detect_axes_lines(pil_img):
gray = cv2.cvtColor(np.array(pil_img), cv2.COLOR_RGB2GRAY)
edges = cv2.Canny(gray, 50, 150)
H, W = gray.shape
min_len = int(0.28 * min(H, W))
lines = cv2.HoughLinesP(
edges, 1, np.pi/180,
threshold=90,
minLineLength=min_len,
maxLineGap=14
)
if lines is None:
return None, None
horizontals, verticals = [], []
for x1, y1, x2, y2 in lines[:, 0]:
dx, dy = abs(x2-x1), abs(y2-y1)
length = math.hypot(dx, dy)
if dy < 18 and dx > 0.35 * W:
horizontals.append((length, (x1, y1, x2, y2)))
if dx < 18 and dy > 0.35 * H:
verticals.append((length, (x1, y1, x2, y2)))
if not horizontals or not verticals:
return None, None
horizontals.sort(key=lambda t: t[0], reverse=True)
verticals.sort(key=lambda t: t[0], reverse=True)
return horizontals[0][1], verticals[0][1]
def axis_intersection_ok(x_axis, y_axis, W, H):
xa_y = int(round((x_axis[1] + x_axis[3]) / 2))
ya_x = int(round((y_axis[0] + y_axis[2]) / 2))
if not (0 <= xa_y < H and 0 <= ya_x < W):
return False
if ya_x > int(0.95 * W) or xa_y < int(0.05 * H):
return False
return True
def tick_text_presence_score(pil_img, x_axis, y_axis):
img = np.array(pil_img)
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
bw = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
bw = cv2.medianBlur(bw, 3)
H, W = gray.shape
xa_y = int(round((x_axis[1] + x_axis[3]) / 2))
ya_x = int(round((y_axis[0] + y_axis[2]) / 2))
y0a = max(0, xa_y - 40)
y1a = min(H, xa_y + 110)
x_roi = bw[y0a:y1a, 0:W]
x0b = max(0, ya_x - 180)
x1b = min(W, ya_x + 50)
y_roi = bw[0:H, x0b:x1b]
def count_small_components(mask):
num, _, stats, _ = cv2.connectedComponentsWithStats(mask, connectivity=8)
cnt = 0
for i in range(1, num):
x, y, w, h, area = stats[i]
if 4 <= w <= 150 and 4 <= h <= 150 and 20 <= area <= 5000:
cnt += 1
return cnt
return count_small_components(x_roi) + count_small_components(y_roi)
def is_real_plot(pil_img):
if has_colorbar_like_strip(pil_img):
return False
if is_mostly_legend(pil_img):
return False
x_axis, y_axis = detect_axes_lines(pil_img)
if x_axis is None or y_axis is None:
return False
arr = np.array(pil_img)
H, W = arr.shape[0], arr.shape[1]
if not axis_intersection_ok(x_axis, y_axis, W, H):
return False
if texture_score(pil_img) > 2200:
return False
score = tick_text_presence_score(pil_img, x_axis, y_axis)
return score >= 18
# -------------------
# Candidate boxes in a region
# -------------------
def connected_components_boxes(pil_img):
img_bgr = cv2.cvtColor(np.array(pil_img), cv2.COLOR_RGB2BGR)
gray = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2GRAY)
mask = (gray < 245).astype(np.uint8) * 255
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, np.ones((7, 7), np.uint8), iterations=2)
num, _, stats, _ = cv2.connectedComponentsWithStats(mask, connectivity=8)
boxes = []
for i in range(1, num):
x, y, w, h, area = stats[i]
boxes.append((int(area), (int(x), int(y), int(x + w), int(y + h))))
boxes.sort(key=lambda t: t[0], reverse=True)
return boxes
def expand_box(box, W, H, left=0.10, right=0.06, top=0.06, bottom=0.18):
x0, y0, x1, y1 = box
bw = x1 - x0
bh = y1 - y0
ex0 = max(0, int(x0 - left * bw))
ex1 = min(W, int(x1 + right * bw))
ey0 = max(0, int(y0 - top * bh))
ey1 = min(H, int(y1 + bottom * bh))
return (ex0, ey0, ex1, ey1)
# -------------------
# Crop plot from caption
# -------------------
def crop_plot_from_caption(page_img, cap_bbox_pdf, mat):
cap_px = pdf_to_px_bbox(cap_bbox_pdf, mat)
cap_y0 = cap_px[1]
cap_y1 = cap_px[3]
W, H = page_img.size
search_top = max(0, cap_y0 - int(0.95 * H))
search_bot = min(H, cap_y1 + int(0.20 * H))
region = safe_crop_px(page_img, (0, search_top, W, search_bot))
if region is None:
return None
comps = connected_components_boxes(region)
best = None
best_area = -1
for area, box in comps[:35]:
x0, y0, x1, y1 = box
bw = x1 - x0
bh = y1 - y0
if bw < 220 or bh < 180:
continue
exp = expand_box(box, region.size[0], region.size[1])
cand = safe_crop_px(region, exp)
if cand is None:
continue
if not is_real_plot(cand):
continue
if area > best_area:
best_area = area
best = cand
return best
# -------------------
# Streamlit UI
# -------------------
def run_extraction(pdf_path, paper_id="uploaded_paper"):
out_paper = os.path.join(OUT_DIR, paper_id)
out_imgs = os.path.join(out_paper, "plots_with_axes")
os.makedirs(out_imgs, exist_ok=True)
doc = fitz.open(pdf_path)
results = []
seen = set()
saved = 0
for p in range(len(doc)):
page = doc[p]
caps = find_caption_blocks(page)
if not caps:
continue
page_img, mat = render_page(page, dpi=DPI)
for cap in caps:
cap_text = cap["text"]
if KEEP_ONLY_STRESS_STRAIN and not SS_KW.search(cap_text):
continue
fig = crop_plot_from_caption(page_img, cap["bbox"], mat)
if fig is None:
continue
if fig.size[0] > 8 and fig.size[1] > 8:
fig = fig.crop((2, 2, fig.size[0]-2, fig.size[1]-2))
try:
h = dhash64(fig)
except Exception:
continue
if h in seen:
continue
seen.add(h)
img_name = f"p{p+1:02d}_{saved:04d}.png"
img_path = os.path.join(out_imgs, img_name)
fig.save(img_path)
results.append({
"page": p + 1,
"caption": cap_text,
"image": img_path
})
saved += 1
out_json = os.path.join(out_paper, "plots_with_axes.json")
with open(out_json, "w", encoding="utf-8") as f:
json.dump(results, f, indent=2, ensure_ascii=False)
return results, out_json
def main():
st.set_page_config(page_title="Research Paper Plot Extractor", layout="wide")
st.title(" Plot Extractor (Upload PDF)")
uploaded = st.file_uploader("Upload a research paper PDF", type=["pdf"])
if not uploaded:
st.info("Upload a PDF to extract plots.")
return
paper_id = os.path.splitext(uploaded.name)[0].replace(" ", "_")
with tempfile.TemporaryDirectory() as tmpdir:
pdf_path = os.path.join(tmpdir, uploaded.name)
with open(pdf_path, "wb") as f:
f.write(uploaded.read())
with st.spinner("Extracting plots..."):
results, out_json = run_extraction(pdf_path, paper_id=paper_id)
st.success(f"Extracted {len(results)} plots.")
# Show images + captions
for r in results:
st.markdown(f"**Page {r['page']}** — {r['caption']}")
st.image(r["image"], use_container_width=True)
st.divider()
# JSON viewer + download
st.subheader("JSON Output")
st.json(results)
with open(out_json, "rb") as f:
st.download_button(
"Download JSON",
data=f,
file_name=os.path.basename(out_json),
mime="application/json"
)
if __name__ == "__main__":
main()
|