hanszhu commited on
Commit
fd9d3d4
Β·
1 Parent(s): 659aa40

chore(docker): dedupe deps; restore Gradio app; move installs to Dockerfile; no runtime installs

Browse files
Files changed (3) hide show
  1. Dockerfile +2 -1
  2. app.py +846 -6
  3. requirements.txt +6 -2
Dockerfile CHANGED
@@ -15,6 +15,7 @@ COPY requirements.txt /app/requirements.txt
15
  RUN python -m pip install --upgrade pip wheel setuptools openmim \
16
  && pip install --no-cache-dir -r requirements.txt \
17
  && pip install --no-cache-dir --index-url https://download.pytorch.org/whl/cpu torch==2.1.0 torchvision==0.16.0 \
 
18
  && mim install "mmengine==0.10.4" \
19
  && mim install "mmcv==2.1.0" \
20
  && mim install "mmdet==3.3.0"
@@ -23,4 +24,4 @@ COPY . /app
23
 
24
  EXPOSE 7860
25
 
26
- CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
 
15
  RUN python -m pip install --upgrade pip wheel setuptools openmim \
16
  && pip install --no-cache-dir -r requirements.txt \
17
  && pip install --no-cache-dir --index-url https://download.pytorch.org/whl/cpu torch==2.1.0 torchvision==0.16.0 \
18
+ && pip install --no-cache-dir 'git+https://github.com/facebookresearch/segment-anything.git' \
19
  && mim install "mmengine==0.10.4" \
20
  && mim install "mmcv==2.1.0" \
21
  && mim install "mmdet==3.3.0"
 
24
 
25
  EXPOSE 7860
26
 
27
+ CMD ["python", "app.py"]
app.py CHANGED
@@ -1,8 +1,848 @@
1
- from fastapi import FastAPI
 
 
 
 
 
 
2
 
3
- app = FastAPI()
 
 
 
 
 
4
 
5
- @app.get("/")
6
- def greet_json():
7
- return {"Hello": "World!"}
8
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import gradio as gr
4
+ from PIL import Image
5
+ import torch
6
+ import numpy as np
7
+ import cv2
8
 
9
+ # Add custom modules to path - try multiple possible locations
10
+ possible_paths = [
11
+ "./custom_models",
12
+ "../custom_models",
13
+ "./Dense-Captioning-Platform/custom_models"
14
+ ]
15
 
16
+ for path in possible_paths:
17
+ if os.path.exists(path):
18
+ sys.path.insert(0, os.path.abspath(path))
19
+ break
20
+
21
+ # Add mmcv to path if it exists
22
+ if os.path.exists('./mmcv'):
23
+ sys.path.insert(0, os.path.abspath('./mmcv'))
24
+ print("βœ… Added local mmcv to path")
25
+
26
+ # Import and register custom modules
27
+ try:
28
+ from custom_models import register
29
+ print("βœ… Custom modules registered successfully")
30
+ except Exception as e:
31
+ print(f"⚠️ Warning: Could not register custom modules: {e}")
32
+
33
+ # ----------------------
34
+ # Optional MedSAM integration
35
+ # ----------------------
36
+ class MedSAMIntegrator:
37
+ def __init__(self):
38
+ self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
39
+ self.medsam_model = None
40
+ self.current_image = None
41
+ self.current_image_path = None
42
+ self.embedding = None
43
+ self._load_medsam_model()
44
+
45
+ def _ensure_segment_anything(self):
46
+ try:
47
+ import segment_anything # noqa: F401
48
+ return True
49
+ except Exception as e:
50
+ print(f"⚠ segment_anything not available: {e}. Install it in Dockerfile to enable MedSAM.")
51
+ return False
52
+
53
+ def _load_medsam_model(self):
54
+ try:
55
+ # Ensure library is present
56
+ if not self._ensure_segment_anything():
57
+ print("MedSAM features disabled (segment_anything not available)")
58
+ return
59
+
60
+ from segment_anything import sam_model_registry as _reg
61
+ import torch as _torch
62
+
63
+ # Preferred local path
64
+ medsam_ckpt_path = "models/medsam_vit_b.pth"
65
+
66
+ # If not present, fetch from HF Hub using provided repo or default
67
+ if not os.path.exists(medsam_ckpt_path):
68
+ try:
69
+ from huggingface_hub import hf_hub_download, list_repo_files
70
+ repo_id = os.environ.get("HF_MEDSAM_REPO", "Aniketg6/Fine-Tuned-MedSAM")
71
+ # Try to find a .pth/.pt in the repo
72
+ print(f"πŸ”„ Trying to download MedSAM checkpoint from {repo_id} ...")
73
+ files = list_repo_files(repo_id)
74
+ candidate = None
75
+ for f in files:
76
+ lf = f.lower()
77
+ if lf.endswith(".pth") or lf.endswith(".pt"):
78
+ candidate = f
79
+ break
80
+ if candidate is None:
81
+ # Fallback to a common name
82
+ candidate = "medsam_vit_b.pth"
83
+ ckpt_path = hf_hub_download(repo_id=repo_id, filename=candidate, cache_dir="./models")
84
+ medsam_ckpt_path = ckpt_path
85
+ print(f"βœ… Downloaded MedSAM checkpoint: {medsam_ckpt_path}")
86
+ except Exception as dl_err:
87
+ print(f"⚠ Could not fetch MedSAM checkpoint from HF Hub: {dl_err}")
88
+ print("MedSAM features disabled (no checkpoint)")
89
+ return
90
+
91
+ # Load checkpoint
92
+ checkpoint = _torch.load(medsam_ckpt_path, map_location='cpu')
93
+ self.medsam_model = _reg["vit_b"](checkpoint=None)
94
+ self.medsam_model.load_state_dict(checkpoint)
95
+ self.medsam_model.to(self.device)
96
+ self.medsam_model.eval()
97
+ print("βœ“ MedSAM model loaded successfully")
98
+ except Exception as e:
99
+ print(f"⚠ MedSAM model not available: {e}. MedSAM features disabled.")
100
+
101
+ def is_available(self):
102
+ return self.medsam_model is not None
103
+
104
+ def load_image(self, image_path, precomputed_embedding=None):
105
+ try:
106
+ from skimage import transform, io # local import to avoid hard dep if unused
107
+ img_np = io.imread(image_path)
108
+ if len(img_np.shape) == 2:
109
+ img_3c = np.repeat(img_np[:, :, None], 3, axis=-1)
110
+ else:
111
+ img_3c = img_np
112
+ self.current_image = img_3c
113
+ self.current_image_path = image_path
114
+ if precomputed_embedding is not None:
115
+ if not self.set_precomputed_embedding(precomputed_embedding):
116
+ self.get_embeddings()
117
+ else:
118
+ self.get_embeddings()
119
+ return True
120
+ except Exception as e:
121
+ print(f"Error loading image for MedSAM: {e}")
122
+ return False
123
+
124
+ @torch.no_grad()
125
+ def get_embeddings(self):
126
+ if self.current_image is None or self.medsam_model is None:
127
+ return None
128
+ from skimage import transform
129
+ img_1024 = transform.resize(
130
+ self.current_image, (1024, 1024), order=3, preserve_range=True, anti_aliasing=True
131
+ ).astype(np.uint8)
132
+ img_1024 = (img_1024 - img_1024.min()) / np.clip(img_1024.max() - img_1024.min(), a_min=1e-8, a_max=None)
133
+ img_1024_tensor = (
134
+ torch.tensor(img_1024).float().permute(2, 0, 1).unsqueeze(0).to(self.device)
135
+ )
136
+ self.embedding = self.medsam_model.image_encoder(img_1024_tensor)
137
+ return self.embedding
138
+
139
+ def set_precomputed_embedding(self, embedding_array):
140
+ try:
141
+ if isinstance(embedding_array, np.ndarray):
142
+ embedding_tensor = torch.tensor(embedding_array).to(self.device)
143
+ self.embedding = embedding_tensor
144
+ return True
145
+ return False
146
+ except Exception as e:
147
+ print(f"Error setting precomputed embedding: {e}")
148
+ return False
149
+
150
+ @torch.no_grad()
151
+ def medsam_inference(self, box_1024, height, width):
152
+ if self.embedding is None or self.medsam_model is None:
153
+ return None
154
+ box_torch = torch.as_tensor(box_1024, dtype=torch.float, device=self.embedding.device)
155
+ if len(box_torch.shape) == 2:
156
+ box_torch = box_torch[:, None, :]
157
+ sparse_embeddings, dense_embeddings = self.medsam_model.prompt_encoder(
158
+ points=None, boxes=box_torch, masks=None,
159
+ )
160
+ low_res_logits, _ = self.medsam_model.mask_decoder(
161
+ image_embeddings=self.embedding,
162
+ image_pe=self.medsam_model.prompt_encoder.get_dense_pe(),
163
+ sparse_prompt_embeddings=sparse_embeddings,
164
+ dense_prompt_embeddings=dense_embeddings,
165
+ multimask_output=False,
166
+ )
167
+ low_res_pred = torch.sigmoid(low_res_logits)
168
+ low_res_pred = torch.nn.functional.interpolate(
169
+ low_res_pred, size=(height, width), mode="bilinear", align_corners=False,
170
+ )
171
+ low_res_pred = low_res_pred.squeeze().cpu().numpy()
172
+ medsam_seg = (low_res_pred > 0.5).astype(np.uint8)
173
+ return medsam_seg
174
+
175
+ def segment_with_box(self, bbox):
176
+ if self.embedding is None or self.current_image is None:
177
+ return None
178
+ try:
179
+ H, W, _ = self.current_image.shape
180
+ x1, y1, x2, y2 = bbox
181
+ x1 = max(0, min(int(x1), W - 1))
182
+ y1 = max(0, min(int(y1), H - 1))
183
+ x2 = max(0, min(int(x2), W - 1))
184
+ y2 = max(0, min(int(y2), H - 1))
185
+ if x2 <= x1:
186
+ x2 = min(x1 + 10, W - 1)
187
+ if y2 <= y1:
188
+ y2 = min(y1 + 10, H - 1)
189
+ box_np = np.array([[x1, y1, x2, y2]], dtype=float)
190
+ box_1024 = box_np / np.array([W, H, W, H]) * 1024.0
191
+ medsam_mask = self.medsam_inference(box_1024, H, W)
192
+ if medsam_mask is not None:
193
+ return {"mask": medsam_mask, "confidence": 1.0, "method": "medsam_box"}
194
+ return None
195
+ except Exception as e:
196
+ print(f"Error in MedSAM box-based segmentation: {e}")
197
+ return None
198
+
199
+ # Single global instance
200
+ _medsam = MedSAMIntegrator()
201
+
202
+
203
+ def _extract_bboxes_from_mmdet_result(det_result):
204
+ """Extract Nx4 xyxy bboxes from various MMDet result formats."""
205
+ boxes = []
206
+ try:
207
+ # MMDet 3.x: list of DetDataSample
208
+ if isinstance(det_result, list) and len(det_result) > 0:
209
+ sample = det_result[0]
210
+ if hasattr(sample, 'pred_instances'):
211
+ inst = sample.pred_instances
212
+ if hasattr(inst, 'bboxes'):
213
+ b = inst.bboxes
214
+ # mmengine structures may use .tensor for boxes
215
+ if hasattr(b, 'tensor'):
216
+ b = b.tensor
217
+ boxes = b.detach().cpu().numpy().tolist()
218
+ # Single DetDataSample
219
+ elif hasattr(det_result, 'pred_instances'):
220
+ inst = det_result.pred_instances
221
+ if hasattr(inst, 'bboxes'):
222
+ b = inst.bboxes
223
+ if hasattr(b, 'tensor'):
224
+ b = b.tensor
225
+ boxes = b.detach().cpu().numpy().tolist()
226
+ # MMDet 2.x: tuple of (bbox_result, segm_result)
227
+ elif isinstance(det_result, tuple) and len(det_result) >= 1:
228
+ bbox_result = det_result[0]
229
+ # bbox_result is list per class, each Nx5 [x1,y1,x2,y2,score]
230
+ if isinstance(bbox_result, (list, tuple)):
231
+ for arr in bbox_result:
232
+ try:
233
+ arr_np = np.array(arr)
234
+ if arr_np.ndim == 2 and arr_np.shape[1] >= 4:
235
+ boxes.extend(arr_np[:, :4].tolist())
236
+ except Exception:
237
+ continue
238
+ except Exception as e:
239
+ print(f"Failed to parse MMDet result for boxes: {e}")
240
+ return boxes
241
+
242
+
243
+ def _overlay_masks_on_image(image_pil, mask_list, alpha=0.4):
244
+ """Overlay binary masks on an image with random colors."""
245
+ if image_pil is None or not mask_list:
246
+ return image_pil
247
+ img = np.array(image_pil.convert('RGB'))
248
+ overlay = img.copy()
249
+ for idx, m in enumerate(mask_list):
250
+ if m is None or 'mask' not in m or m['mask'] is None:
251
+ continue
252
+ mask = m['mask'].astype(bool)
253
+ color = np.random.RandomState(seed=idx + 1234).randint(0, 255, size=3)
254
+ overlay[mask] = (0.5 * overlay[mask] + 0.5 * color).astype(np.uint8)
255
+ blended = (alpha * overlay + (1 - alpha) * img).astype(np.uint8)
256
+ return Image.fromarray(blended)
257
+
258
+
259
+ def _mask_to_polygons(mask: np.ndarray):
260
+ """Convert a binary mask (H,W) to a list of polygons ([[x,y], ...]) using OpenCV contours."""
261
+ try:
262
+ mask_u8 = (mask.astype(np.uint8) * 255)
263
+ contours, _ = cv2.findContours(mask_u8, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
264
+ polygons = []
265
+ for cnt in contours:
266
+ if cnt is None or len(cnt) < 3:
267
+ continue
268
+ # Simplify contour slightly
269
+ epsilon = 0.002 * cv2.arcLength(cnt, True)
270
+ approx = cv2.approxPolyDP(cnt, epsilon, True)
271
+ poly = approx.reshape(-1, 2).tolist()
272
+ polygons.append(poly)
273
+ return polygons
274
+ except Exception as e:
275
+ print(f"_mask_to_polygons failed: {e}")
276
+ return []
277
+
278
+
279
+ def _find_largest_foreground_bbox(pil_img: Image.Image):
280
+ """Heuristic: find largest foreground region bbox via Otsu threshold on grayscale.
281
+ Returns [x1, y1, x2, y2] or full-image bbox if none found."""
282
+ try:
283
+ img = np.array(pil_img.convert('RGB'))
284
+ gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
285
+ # Otsu threshold (invert if needed by checking mean)
286
+ _, th = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
287
+ # Assume foreground is darker; invert if threshold yields background as white majority
288
+ if th.mean() > 127:
289
+ th = 255 - th
290
+ # Morph close to connect regions
291
+ kernel = np.ones((5, 5), np.uint8)
292
+ th = cv2.morphologyEx(th, cv2.MORPH_CLOSE, kernel, iterations=2)
293
+ contours, _ = cv2.findContours(th, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
294
+ if not contours:
295
+ W, H = pil_img.size
296
+ return [0, 0, W - 1, H - 1]
297
+ # Largest contour by area
298
+ cnt = max(contours, key=cv2.contourArea)
299
+ x, y, w, h = cv2.boundingRect(cnt)
300
+ # Pad a little
301
+ pad = int(0.02 * max(w, h))
302
+ x1 = max(0, x - pad)
303
+ y1 = max(0, y - pad)
304
+ x2 = min(img.shape[1] - 1, x + w + pad)
305
+ y2 = min(img.shape[0] - 1, y + h + pad)
306
+ return [x1, y1, x2, y2]
307
+ except Exception as e:
308
+ print(f"_find_largest_foreground_bbox failed: {e}")
309
+ W, H = pil_img.size
310
+ return [0, 0, W - 1, H - 1]
311
+
312
+
313
+ def _find_topk_foreground_bboxes(pil_img: Image.Image, max_regions: int = 20, min_area: int = 100):
314
+ """Find top-K foreground bboxes via Otsu threshold + morphology. Returns list of [x1,y1,x2,y2]."""
315
+ try:
316
+ img = np.array(pil_img.convert('RGB'))
317
+ gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
318
+ _, th = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
319
+ if th.mean() > 127:
320
+ th = 255 - th
321
+ kernel = np.ones((3, 3), np.uint8)
322
+ th = cv2.morphologyEx(th, cv2.MORPH_OPEN, kernel, iterations=1)
323
+ th = cv2.morphologyEx(th, cv2.MORPH_CLOSE, kernel, iterations=2)
324
+ contours, _ = cv2.findContours(th, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
325
+ if not contours:
326
+ return []
327
+ contours = sorted(contours, key=cv2.contourArea, reverse=True)
328
+ bboxes = []
329
+ H, W = img.shape[:2]
330
+ for cnt in contours:
331
+ area = cv2.contourArea(cnt)
332
+ if area < min_area:
333
+ continue
334
+ x, y, w, h = cv2.boundingRect(cnt)
335
+ # Filter very thin shapes
336
+ if w < 5 or h < 5:
337
+ continue
338
+ pad = int(0.01 * max(w, h))
339
+ x1 = max(0, x - pad)
340
+ y1 = max(0, y - pad)
341
+ x2 = min(W - 1, x + w + pad)
342
+ y2 = min(H - 1, y + h + pad)
343
+ bboxes.append([x1, y1, x2, y2])
344
+ if len(bboxes) >= max_regions:
345
+ break
346
+ return bboxes
347
+ except Exception as e:
348
+ print(f"_find_topk_foreground_bboxes failed: {e}")
349
+ return []
350
+
351
+ # Try to import mmdet for inference
352
+ try:
353
+ from mmdet.apis import init_detector, inference_detector
354
+ MM_DET_AVAILABLE = True
355
+ print("βœ… MMDetection available for inference")
356
+ except ImportError as e:
357
+ print(f"⚠️ MMDetection import failed: {e}")
358
+ print("❌ MMDetection not available - install in Dockerfile")
359
+ MM_DET_AVAILABLE = False
360
+
361
+ # === Chart Type Classification (DocFigure) ===
362
+ print("πŸ”„ Loading Chart Classification Model...")
363
+
364
+ # Chart type labels from DocFigure dataset (28 classes)
365
+ CHART_TYPE_LABELS = [
366
+ 'Line graph', 'Natural image', 'Table', '3D object', 'Bar plot', 'Scatter plot',
367
+ 'Medical image', 'Sketch', 'Geographic map', 'Flow chart', 'Heat map', 'Mask',
368
+ 'Block diagram', 'Venn diagram', 'Confusion matrix', 'Histogram', 'Box plot',
369
+ 'Vector plot', 'Pie chart', 'Surface plot', 'Algorithm', 'Contour plot',
370
+ 'Tree diagram', 'Bubble chart', 'Polar plot', 'Area chart', 'Pareto chart', 'Radar chart'
371
+ ]
372
+
373
+ try:
374
+ # Load the chart_type.pth model file from Hugging Face Hub
375
+ from huggingface_hub import hf_hub_download
376
+ from torchvision import transforms
377
+
378
+ print("πŸ”„ Downloading chart_type.pth from Hugging Face Hub...")
379
+ chart_type_path = hf_hub_download(
380
+ repo_id="hanszhu/ChartTypeNet-DocFigure",
381
+ filename="chart_type.pth",
382
+ cache_dir="./models"
383
+ )
384
+ print(f"βœ… Downloaded to: {chart_type_path}")
385
+
386
+ # Load the PyTorch model
387
+ loaded_data = torch.load(chart_type_path, map_location='cpu')
388
+
389
+ # Check if it's a state dict or a complete model
390
+ if isinstance(loaded_data, dict):
391
+ # Check if it's a checkpoint with model_state_dict
392
+ if "model_state_dict" in loaded_data:
393
+ print("πŸ”„ Loading checkpoint, extracting model_state_dict...")
394
+ state_dict = loaded_data["model_state_dict"]
395
+ else:
396
+ # It's a direct state dict
397
+ print("πŸ”„ Loading state dict, creating model architecture...")
398
+ state_dict = loaded_data
399
+
400
+ # Strip "backbone." prefix from state dict keys if present
401
+ cleaned_state_dict = {}
402
+ for key, value in state_dict.items():
403
+ if key.startswith("backbone."):
404
+ # Remove "backbone." prefix
405
+ new_key = key[9:]
406
+ cleaned_state_dict[new_key] = value
407
+ else:
408
+ cleaned_state_dict[key] = value
409
+
410
+ print(f"πŸ”„ Cleaned state dict: {len(cleaned_state_dict)} keys")
411
+
412
+ # Create the model architecture
413
+ from torchvision.models import resnet50
414
+ chart_type_model = resnet50(pretrained=False)
415
+
416
+ # Create the correct classifier structure to match the state dict
417
+ import torch.nn as nn
418
+ in_features = chart_type_model.fc.in_features
419
+ dropout = nn.Dropout(0.5)
420
+
421
+ chart_type_model.fc = nn.Sequential(
422
+ nn.Linear(in_features, 512),
423
+ nn.ReLU(inplace=True),
424
+ dropout,
425
+ nn.Linear(512, 28)
426
+ )
427
+
428
+ # Load the cleaned state dict
429
+ chart_type_model.load_state_dict(cleaned_state_dict)
430
+ else:
431
+ # It's a complete model
432
+ chart_type_model = loaded_data
433
+
434
+ chart_type_model.eval()
435
+
436
+ # Create a simple processor for the model
437
+ chart_type_processor = transforms.Compose([
438
+ transforms.Resize((224, 224)),
439
+ transforms.ToTensor(),
440
+ transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
441
+ ])
442
+
443
+ CHART_TYPE_AVAILABLE = True
444
+ print("βœ… Chart classification model loaded")
445
+ except Exception as e:
446
+ print(f"⚠️ Failed to load chart classification model: {e}")
447
+ import traceback
448
+ print("πŸ” Full traceback:")
449
+ traceback.print_exc()
450
+ CHART_TYPE_AVAILABLE = False
451
+
452
+ # === Chart Element Detection (Cascade R-CNN) ===
453
+ element_model = None
454
+ datapoint_model = None
455
+
456
+ print(f"πŸ” MM_DET_AVAILABLE: {MM_DET_AVAILABLE}")
457
+
458
+ if MM_DET_AVAILABLE:
459
+ # Check if config files exist
460
+ element_config = "models/chart_elementnet_swin.py"
461
+ point_config = "models/chart_pointnet_swin.py"
462
+
463
+ print(f"πŸ” Checking config files...")
464
+ print(f"πŸ” Element config exists: {os.path.exists(element_config)}")
465
+ print(f"πŸ” Point config exists: {os.path.exists(point_config)}")
466
+ print(f"πŸ” Current working directory: {os.getcwd()}")
467
+ print(f"πŸ” Files in models directory: {os.listdir('models') if os.path.exists('models') else 'models directory not found'}")
468
+
469
+ try:
470
+ print("πŸ”„ Loading ChartElementNet-MultiClass (Cascade R-CNN)...")
471
+ print(f"πŸ” Config path: {element_config}")
472
+ print(f"πŸ” Weights path: hanszhu/ChartElementNet-MultiClass")
473
+ print(f"πŸ” About to call init_detector...")
474
+
475
+ # Download model from Hugging Face Hub
476
+ from huggingface_hub import hf_hub_download
477
+ print("πŸ”„ Downloading ChartElementNet weights from Hugging Face Hub...")
478
+ element_checkpoint = hf_hub_download(
479
+ repo_id="hanszhu/ChartElementNet-MultiClass",
480
+ filename="chart_label+.pth",
481
+ cache_dir="./models"
482
+ )
483
+ print(f"βœ… Downloaded to: {element_checkpoint}")
484
+
485
+ # Use local config with downloaded weights
486
+ element_model = init_detector(element_config, element_checkpoint, device="cpu")
487
+ print("βœ… ChartElementNet loaded successfully")
488
+ except Exception as e:
489
+ print(f"❌ Failed to load ChartElementNet: {e}")
490
+ print(f"πŸ” Error type: {type(e).__name__}")
491
+ print(f"πŸ” Error details: {str(e)}")
492
+ import traceback
493
+ print("πŸ” Full traceback:")
494
+ traceback.print_exc()
495
+
496
+ try:
497
+ print("πŸ”„ Loading ChartPointNet-InstanceSeg (Mask R-CNN)...")
498
+ print(f"πŸ” Config path: {point_config}")
499
+ print(f"πŸ” Weights path: hanszhu/ChartPointNet-InstanceSeg")
500
+ print(f"πŸ” About to call init_detector...")
501
+
502
+ # Download model from Hugging Face Hub
503
+ print("πŸ”„ Downloading ChartPointNet weights from Hugging Face Hub...")
504
+ datapoint_checkpoint = hf_hub_download(
505
+ repo_id="hanszhu/ChartPointNet-InstanceSeg",
506
+ filename="chart_datapoint.pth",
507
+ cache_dir="./models"
508
+ )
509
+ print(f"βœ… Downloaded to: {datapoint_checkpoint}")
510
+
511
+ # Use local config with downloaded weights
512
+ datapoint_model = init_detector(point_config, datapoint_checkpoint, device="cpu")
513
+ print("βœ… ChartPointNet loaded successfully")
514
+ except Exception as e:
515
+ print(f"❌ Failed to load ChartPointNet: {e}")
516
+ print(f"πŸ” Error type: {type(e).__name__}")
517
+ print(f"πŸ” Error details: {str(e)}")
518
+ import traceback
519
+ print("πŸ” Full traceback:")
520
+ traceback.print_exc()
521
+ else:
522
+ print("❌ MMDetection not available - cannot load custom models")
523
+ print(f"πŸ” MM_DET_AVAILABLE was False")
524
+
525
+ print(f"πŸ” Final model status:")
526
+ print(f"πŸ” element_model: {element_model is not None}")
527
+ print(f"πŸ” datapoint_model: {datapoint_model is not None}")
528
+
529
+ # === Main prediction function ===
530
+ def analyze(image):
531
+ """
532
+ Analyze a chart image and return comprehensive results.
533
+
534
+ Args:
535
+ image: Input chart image (filepath string or PIL.Image)
536
+
537
+ Returns:
538
+ dict: Analysis results containing:
539
+ - chart_type_id (int): Numeric chart type identifier (0-27)
540
+ - chart_type_label (str): Human-readable chart type name
541
+ - element_result (str): Detected chart elements (titles, axes, legends, etc.)
542
+ - datapoint_result (str): Segmented data points and regions
543
+ - status (str): Processing status message
544
+ - processing_time (float): Time taken for analysis in seconds
545
+ """
546
+ import time
547
+ from PIL import Image
548
+
549
+ start_time = time.time()
550
+
551
+ # Handle filepath input (convert to PIL Image)
552
+ if isinstance(image, str):
553
+ # It's a filepath, load the image
554
+ image = Image.open(image).convert("RGB")
555
+ elif image is None:
556
+ return {"error": "No image provided"}
557
+
558
+ # Ensure we have a PIL Image
559
+ if not isinstance(image, Image.Image):
560
+ return {"error": "Invalid image format"}
561
+
562
+ result = {
563
+ "chart_type_id": "Model not available",
564
+ "chart_type_label": "Model not available",
565
+ "element_result": "MMDetection models not available",
566
+ "datapoint_result": "MMDetection models not available",
567
+ "status": "Basic chart classification only",
568
+ "processing_time": 0.0,
569
+ "medsam": {"available": False}
570
+ }
571
+
572
+ # Chart Type Classification
573
+ if CHART_TYPE_AVAILABLE:
574
+ try:
575
+ # Preprocess image for PyTorch model
576
+ processed_image = chart_type_processor(image).unsqueeze(0) # Add batch dimension
577
+
578
+ # Get prediction
579
+ with torch.no_grad():
580
+ outputs = chart_type_model(processed_image)
581
+ # Handle different output formats
582
+ if isinstance(outputs, torch.Tensor):
583
+ logits = outputs
584
+ elif hasattr(outputs, 'logits'):
585
+ logits = outputs.logits
586
+ else:
587
+ logits = outputs
588
+
589
+ predicted_class = logits.argmax(dim=-1).item()
590
+
591
+ result["chart_type_id"] = predicted_class
592
+ result["chart_type_label"] = CHART_TYPE_LABELS[predicted_class] if 0 <= predicted_class < len(CHART_TYPE_LABELS) else f"Unknown ({predicted_class})"
593
+ result["status"] = "Chart classification completed"
594
+
595
+ except Exception as e:
596
+ result["chart_type_id"] = f"Error: {str(e)}"
597
+ result["chart_type_label"] = f"Error: {str(e)}"
598
+ result["status"] = "Error in chart classification"
599
+
600
+ # Chart Element Detection (Cascade R-CNN)
601
+ if element_model is not None:
602
+ try:
603
+ # Convert PIL image to numpy array for MMDetection
604
+ np_img = np.array(image.convert("RGB"))[:, :, ::-1] # PIL β†’ BGR
605
+
606
+ element_result = inference_detector(element_model, np_img)
607
+
608
+ # Convert result to more API-friendly format
609
+ if isinstance(element_result, tuple):
610
+ bbox_result, segm_result = element_result
611
+ element_data = {
612
+ "bboxes": bbox_result.tolist() if hasattr(bbox_result, 'tolist') else str(bbox_result),
613
+ "segments": segm_result.tolist() if hasattr(segm_result, 'tolist') else str(segm_result)
614
+ }
615
+ else:
616
+ element_data = str(element_result)
617
+
618
+ result["element_result"] = element_data
619
+ result["status"] = "Chart classification + element detection completed"
620
+ except Exception as e:
621
+ result["element_result"] = f"Error: {str(e)}"
622
+
623
+ # Chart Data Point Segmentation (Mask R-CNN)
624
+ if datapoint_model is not None:
625
+ try:
626
+ # Convert PIL image to numpy array for MMDetection
627
+ np_img = np.array(image.convert("RGB"))[:, :, ::-1] # PIL β†’ BGR
628
+
629
+ datapoint_result = inference_detector(datapoint_model, np_img)
630
+
631
+ # Convert result to more API-friendly format
632
+ if isinstance(datapoint_result, tuple):
633
+ bbox_result, segm_result = datapoint_result
634
+ datapoint_data = {
635
+ "bboxes": bbox_result.tolist() if hasattr(bbox_result, 'tolist') else str(bbox_result),
636
+ "segments": segm_result.tolist() if hasattr(segm_result, 'tolist') else str(segm_result)
637
+ }
638
+ else:
639
+ datapoint_data = str(datapoint_result)
640
+
641
+ result["datapoint_result"] = datapoint_data
642
+ result["status"] = "Full analysis completed"
643
+ except Exception as e:
644
+ result["datapoint_result"] = f"Error: {str(e)}"
645
+
646
+ # If predicted as medical image and MedSAM is available, include mask data (polygons)
647
+ try:
648
+ label_lower = str(result.get("chart_type_label", "")).strip().lower()
649
+ if label_lower == "medical image":
650
+ if _medsam.is_available():
651
+ # Indicate availability; masks are generated in then-chain
652
+ result["medsam"] = {"available": True}
653
+ else:
654
+ # Not available; include reason
655
+ result["medsam"] = {"available": False, "reason": "segment_anything or checkpoint missing"}
656
+ except Exception as e:
657
+ print(f"MedSAM JSON augmentation failed: {e}")
658
+
659
+ result["processing_time"] = round(time.time() - start_time, 3)
660
+ return result
661
+
662
+
663
+ def analyze_with_medsam(base_result, image):
664
+ """Auto-generate segmentations for medical images using SAM ViT-H if available,
665
+ otherwise fallback to MedSAM over top-K foreground boxes. Returns updated JSON and overlay image."""
666
+ try:
667
+ if not isinstance(base_result, dict):
668
+ return base_result, None
669
+ label = str(base_result.get("chart_type_label", "")).strip().lower()
670
+ if label != "medical image" or not _medsam.is_available():
671
+ return base_result, None
672
+
673
+ pil_img = Image.open(image).convert("RGB") if isinstance(image, str) else image
674
+ if pil_img is None:
675
+ return base_result, None
676
+
677
+ # Prepare embedding
678
+ img_path = image if isinstance(image, str) else None
679
+ if img_path is None:
680
+ tmp_path = "./_tmp_input_image.png"
681
+ pil_img.save(tmp_path)
682
+ img_path = tmp_path
683
+ _medsam.load_image(img_path)
684
+
685
+ segmentations = []
686
+ masks_for_overlay = []
687
+
688
+ # AUTO segmentation path
689
+ try:
690
+ from segment_anything import sam_model_registry, SamAutomaticMaskGenerator
691
+ import cv2 as _cv2
692
+ # If ViT-H checkpoint present, use SAM automatic mask generator (download if missing)
693
+ vit_h_ckpt = "models/sam_vit_h_4b8939.pth"
694
+ if not os.path.exists(vit_h_ckpt):
695
+ try:
696
+ from huggingface_hub import hf_hub_download
697
+ vit_h_ckpt = hf_hub_download(
698
+ repo_id="Aniketg6/SAM",
699
+ filename="sam_vit_h_4b8939.pth",
700
+ cache_dir="./models"
701
+ )
702
+ print(f"βœ… Downloaded SAM ViT-H checkpoint to: {vit_h_ckpt}")
703
+ except Exception as dlh:
704
+ print(f"⚠ Failed to download SAM ViT-H checkpoint: {dlh}")
705
+ if os.path.exists(vit_h_ckpt):
706
+ img_bgr = _cv2.imread(img_path)
707
+ sam = sam_model_registry["vit_h"](checkpoint=vit_h_ckpt)
708
+ mask_generator = SamAutomaticMaskGenerator(sam)
709
+ masks = mask_generator.generate(img_bgr)
710
+ for m in masks:
711
+ seg = m.get('segmentation', None)
712
+ if seg is None:
713
+ continue
714
+ seg_u8 = seg.astype(np.uint8)
715
+ segmentations.append({
716
+ "mask": seg_u8.tolist(),
717
+ "confidence": float(m.get('stability_score', 1.0)),
718
+ "method": "sam_auto"
719
+ })
720
+ masks_for_overlay.append({"mask": seg_u8})
721
+ else:
722
+ # Fallback: derive candidate boxes and run MedSAM per box
723
+ cand_bboxes = _find_topk_foreground_bboxes(pil_img, max_regions=20, min_area=200)
724
+ for bbox in cand_bboxes:
725
+ m = _medsam.segment_with_box(bbox)
726
+ if m is None or not isinstance(m.get('mask'), np.ndarray):
727
+ continue
728
+ segmentations.append({
729
+ "mask": m['mask'].astype(np.uint8).tolist(),
730
+ "confidence": float(m.get('confidence', 1.0)),
731
+ "method": m.get("method", "medsam_box_auto")
732
+ })
733
+ masks_for_overlay.append(m)
734
+ except Exception as auto_e:
735
+ print(f"Automatic MedSAM segmentation failed: {auto_e}")
736
+
737
+ W, H = pil_img.size
738
+ base_result["medsam"] = {
739
+ "available": True,
740
+ "height": H,
741
+ "width": W,
742
+ "segmentations": segmentations,
743
+ "num_segments": len(segmentations)
744
+ }
745
+
746
+ overlay_img = _overlay_masks_on_image(pil_img, masks_for_overlay) if masks_for_overlay else None
747
+ return base_result, overlay_img
748
+ except Exception as e:
749
+ print(f"analyze_with_medsam failed: {e}")
750
+ return base_result, None
751
+
752
+ # === Gradio UI with API enhancements ===
753
+ # Create Blocks interface with explicit API name for stable API surface
754
+ with gr.Blocks(
755
+ title="πŸ“Š Dense Captioning Platform"
756
+ ) as demo:
757
+
758
+ gr.Markdown("# πŸ“Š Dense Captioning Platform")
759
+ gr.Markdown("""
760
+ **Comprehensive Chart Analysis API**
761
+
762
+ Upload a chart image to get:
763
+ - **Chart Type Classification**: Identifies the type of chart (line, bar, scatter, etc.)
764
+ - **Element Detection**: Detects chart elements like titles, axes, legends, data points
765
+ - **Data Point Segmentation**: Segments individual data points and regions
766
+
767
+ Masks will be automatically generated for medical images when supported.
768
+
769
+ **API Usage:**
770
+ ```python
771
+ from gradio_client import Client, handle_file
772
+
773
+ client = Client("hanszhu/Dense-Captioning-Platform")
774
+ result = client.predict(
775
+ image=handle_file('path/to/your/chart.png'),
776
+ api_name="/predict"
777
+ )
778
+ print(result)
779
+ ```
780
+
781
+ **Supported Chart Types:** Line graphs, Bar plots, Scatter plots, Pie charts, Heat maps, and 23+ more
782
+ """)
783
+
784
+ with gr.Row():
785
+ with gr.Column():
786
+ # Input
787
+ image_input = gr.Image(
788
+ type="filepath", # βœ… REQUIRED for gradio_client
789
+ label="Upload Chart Image",
790
+ height=400
791
+ )
792
+
793
+ # Analyze button (single)
794
+ analyze_btn = gr.Button(
795
+ "πŸ” Analyze",
796
+ variant="primary",
797
+ size="lg"
798
+ )
799
+
800
+ with gr.Column():
801
+ # Output JSON
802
+ result_output = gr.JSON(
803
+ label="Analysis Results",
804
+ height=400
805
+ )
806
+ # Overlay image output (populated only for medical images)
807
+ overlay_output = gr.Image(
808
+ label="MedSAM Overlay (Medical images)",
809
+ height=400
810
+ )
811
+
812
+ # Single API endpoint for JSON
813
+ analyze_event = analyze_btn.click(
814
+ fn=analyze,
815
+ inputs=image_input,
816
+ outputs=result_output,
817
+ api_name="/predict" # βœ… Standard API name that gradio_client expects
818
+ )
819
+
820
+ # Automatic overlay generation step for medical images
821
+ analyze_event.then(
822
+ fn=analyze_with_medsam,
823
+ inputs=[result_output, image_input],
824
+ outputs=[result_output, overlay_output],
825
+ )
826
+
827
+ # Add some examples
828
+ gr.Examples(
829
+ examples=[
830
+ ["https://raw.githubusercontent.com/gradio-app/gradio/main/test/test_files/bus.png"]
831
+ ],
832
+ inputs=image_input,
833
+ label="Try with this example"
834
+ )
835
+
836
+ # Launch with API-friendly settings
837
+ if __name__ == "__main__":
838
+ launch_kwargs = {
839
+ "server_name": "0.0.0.0", # Allow external connections
840
+ "server_port": 7860,
841
+ "share": False, # Set to True if you want a public link
842
+ "show_error": True, # Show detailed errors for debugging
843
+ "quiet": False, # Show startup messages
844
+ "show_api": True # Enable API documentation
845
+ }
846
+
847
+ # Enable queue for gradio_client compatibility
848
+ demo.queue().launch(**launch_kwargs) # βœ… required for gradio_client to work
requirements.txt CHANGED
@@ -1,2 +1,6 @@
1
- fastapi==0.115.0
2
- uvicorn[standard]==0.30.6
 
 
 
 
 
1
+ gradio==5.39.0
2
+ huggingface-hub>=0.23.0
3
+ numpy>=1.24.0
4
+ opencv-python>=4.8.0
5
+ Pillow>=9.0.0
6
+ scikit-image>=0.21.0