Upload app.py
Browse files
app.py
CHANGED
|
@@ -1,500 +1,545 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import json
|
| 3 |
-
import gc
|
| 4 |
-
import
|
| 5 |
-
import
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
import
|
| 9 |
-
import
|
| 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 |
-
def
|
| 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 |
-
self.
|
| 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 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
gr.
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import gc
|
| 4 |
+
import traceback
|
| 5 |
+
from typing import Optional, Tuple, Any
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
import gradio as gr
|
| 9 |
+
import supervision as sv
|
| 10 |
+
from PIL import Image
|
| 11 |
+
|
| 12 |
+
# Try to import optional dependencies
|
| 13 |
+
try:
|
| 14 |
+
from transformers import (
|
| 15 |
+
AutoModelForCausalLM,
|
| 16 |
+
AutoTokenizer,
|
| 17 |
+
AutoModelForImageTextToText,
|
| 18 |
+
AutoProcessor,
|
| 19 |
+
BitsAndBytesConfig,
|
| 20 |
+
)
|
| 21 |
+
except Exception:
|
| 22 |
+
AutoModelForCausalLM = None
|
| 23 |
+
AutoTokenizer = None
|
| 24 |
+
AutoModelForImageTextToText = None
|
| 25 |
+
AutoProcessor = None
|
| 26 |
+
BitsAndBytesConfig = None
|
| 27 |
+
|
| 28 |
+
# Try to import huggingface_hub for model downloading
|
| 29 |
+
try:
|
| 30 |
+
from huggingface_hub import hf_hub_download
|
| 31 |
+
except ImportError:
|
| 32 |
+
hf_hub_download = None
|
| 33 |
+
|
| 34 |
+
# Import RF-DETR (assumes it's in the same directory or installed)
|
| 35 |
+
try:
|
| 36 |
+
from rfdetr import RFDETRMedium
|
| 37 |
+
except ImportError:
|
| 38 |
+
print("Warning: RF-DETR not found. Please ensure it's properly installed.")
|
| 39 |
+
RFDETRMedium = None
|
| 40 |
+
|
| 41 |
+
# ============================================================================
|
| 42 |
+
# Configuration for Hugging Face Spaces
|
| 43 |
+
# ============================================================================
|
| 44 |
+
|
| 45 |
+
class SpacesConfig:
|
| 46 |
+
"""Configuration optimized for Hugging Face Spaces."""
|
| 47 |
+
|
| 48 |
+
def __init__(self):
|
| 49 |
+
self.settings = {
|
| 50 |
+
'results_dir': '/tmp/results',
|
| 51 |
+
'checkpoint': None,
|
| 52 |
+
'hf_model_repo': 'edeler/lorai', # Hugging Face model repository
|
| 53 |
+
'hf_model_filename': 'lorai.pth',
|
| 54 |
+
'resolution': 576,
|
| 55 |
+
'threshold': 0.7,
|
| 56 |
+
'use_llm': True,
|
| 57 |
+
'llm_model_id': 'google/medgemma-4b-it',
|
| 58 |
+
'llm_max_new_tokens': 200,
|
| 59 |
+
'llm_temperature': 0.2,
|
| 60 |
+
'llm_4bit': True,
|
| 61 |
+
'enable_caching': True,
|
| 62 |
+
'max_cache_size': 100,
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
def get(self, key: str, default: Any = None) -> Any:
|
| 66 |
+
return self.settings.get(key, default)
|
| 67 |
+
|
| 68 |
+
def set_hf_model_repo(self, repo_id: str, filename: str = 'lorai.pth'):
|
| 69 |
+
"""Set Hugging Face model repository."""
|
| 70 |
+
self.settings['hf_model_repo'] = repo_id
|
| 71 |
+
self.settings['hf_model_filename'] = filename
|
| 72 |
+
|
| 73 |
+
# ============================================================================
|
| 74 |
+
# Memory Management (simplified for Spaces)
|
| 75 |
+
# ============================================================================
|
| 76 |
+
|
| 77 |
+
class MemoryManager:
|
| 78 |
+
"""Simplified memory management for Spaces."""
|
| 79 |
+
|
| 80 |
+
def __init__(self):
|
| 81 |
+
self.memory_thresholds = {
|
| 82 |
+
'gpu_warning': 0.8,
|
| 83 |
+
'system_warning': 0.85,
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
def cleanup_memory(self, force: bool = False) -> None:
|
| 87 |
+
"""Perform memory cleanup."""
|
| 88 |
+
try:
|
| 89 |
+
gc.collect()
|
| 90 |
+
if torch and torch.cuda.is_available():
|
| 91 |
+
torch.cuda.empty_cache()
|
| 92 |
+
torch.cuda.synchronize()
|
| 93 |
+
except Exception as e:
|
| 94 |
+
print(f"Memory cleanup error: {e}")
|
| 95 |
+
|
| 96 |
+
# Global memory manager
|
| 97 |
+
memory_manager = MemoryManager()
|
| 98 |
+
|
| 99 |
+
# ============================================================================
|
| 100 |
+
# Model Loading
|
| 101 |
+
# ============================================================================
|
| 102 |
+
|
| 103 |
+
def find_checkpoint(hf_repo: Optional[str] = None, hf_filename: str = 'lorai.pth') -> Optional[str]:
|
| 104 |
+
"""Find RF-DETR checkpoint in various locations or download from Hugging Face Hub."""
|
| 105 |
+
|
| 106 |
+
# First check if we should download from Hugging Face
|
| 107 |
+
repo_id = hf_repo or os.environ.get('HF_MODEL_REPO')
|
| 108 |
+
|
| 109 |
+
if repo_id and hf_hub_download is not None:
|
| 110 |
+
try:
|
| 111 |
+
print(f"Downloading checkpoint from Hugging Face Hub: {repo_id}/{hf_filename}")
|
| 112 |
+
checkpoint_path = hf_hub_download(
|
| 113 |
+
repo_id=repo_id,
|
| 114 |
+
filename=hf_filename,
|
| 115 |
+
cache_dir="/tmp/hf_cache"
|
| 116 |
+
)
|
| 117 |
+
print(f"✓ Downloaded checkpoint to: {checkpoint_path}")
|
| 118 |
+
return checkpoint_path
|
| 119 |
+
except Exception as e:
|
| 120 |
+
print(f"Warning: Failed to download from Hugging Face Hub: {e}")
|
| 121 |
+
print("Falling back to local checkpoints...")
|
| 122 |
+
|
| 123 |
+
# Fall back to local file search
|
| 124 |
+
candidates = [
|
| 125 |
+
"lorai.pth", # Current directory
|
| 126 |
+
"rf-detr-medium.pth",
|
| 127 |
+
"/tmp/results/checkpoint_best_total.pth",
|
| 128 |
+
"/tmp/results/checkpoint_best_ema.pth",
|
| 129 |
+
"/tmp/results/checkpoint_best_regular.pth",
|
| 130 |
+
"/tmp/results/checkpoint.pth",
|
| 131 |
+
]
|
| 132 |
+
|
| 133 |
+
for path in candidates:
|
| 134 |
+
if os.path.isfile(path):
|
| 135 |
+
print(f"Found local checkpoint: {path}")
|
| 136 |
+
return path
|
| 137 |
+
|
| 138 |
+
return None
|
| 139 |
+
|
| 140 |
+
def load_model(checkpoint_path: str, resolution: int):
|
| 141 |
+
"""Load RF-DETR model."""
|
| 142 |
+
if RFDETRMedium is None:
|
| 143 |
+
raise RuntimeError("RF-DETR not available. Please install it properly.")
|
| 144 |
+
|
| 145 |
+
model = RFDETRMedium(pretrain_weights=checkpoint_path, resolution=resolution)
|
| 146 |
+
try:
|
| 147 |
+
model.optimize_for_inference()
|
| 148 |
+
except Exception:
|
| 149 |
+
pass
|
| 150 |
+
return model
|
| 151 |
+
|
| 152 |
+
# ============================================================================
|
| 153 |
+
# LLM Integration
|
| 154 |
+
# ============================================================================
|
| 155 |
+
|
| 156 |
+
class TextGenerator:
|
| 157 |
+
"""Simplified text generator for Spaces."""
|
| 158 |
+
|
| 159 |
+
def __init__(self, model_id: str, max_tokens: int = 200, temperature: float = 0.2):
|
| 160 |
+
self.model_id = model_id
|
| 161 |
+
self.max_tokens = max_tokens
|
| 162 |
+
self.temperature = temperature
|
| 163 |
+
self.model = None
|
| 164 |
+
self.tokenizer = None
|
| 165 |
+
self.processor = None
|
| 166 |
+
self.is_multimodal = False
|
| 167 |
+
|
| 168 |
+
def load_model(self):
|
| 169 |
+
"""Load the LLM model."""
|
| 170 |
+
if self.model is not None:
|
| 171 |
+
return
|
| 172 |
+
|
| 173 |
+
if (AutoModelForCausalLM is None and AutoModelForImageTextToText is None):
|
| 174 |
+
raise RuntimeError("Transformers not available")
|
| 175 |
+
|
| 176 |
+
# Clear memory before loading
|
| 177 |
+
memory_manager.cleanup_memory()
|
| 178 |
+
|
| 179 |
+
print(f"Loading model: {self.model_id}")
|
| 180 |
+
|
| 181 |
+
model_kwargs = {
|
| 182 |
+
"device_map": "auto",
|
| 183 |
+
"low_cpu_mem_usage": True,
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
if torch and torch.cuda.is_available():
|
| 187 |
+
model_kwargs["torch_dtype"] = torch.bfloat16
|
| 188 |
+
|
| 189 |
+
# Use 4-bit quantization if available
|
| 190 |
+
if BitsAndBytesConfig is not None:
|
| 191 |
+
try:
|
| 192 |
+
compute_dtype = torch.bfloat16 if torch and torch.cuda.is_available() else torch.float16
|
| 193 |
+
model_kwargs["quantization_config"] = BitsAndBytesConfig(
|
| 194 |
+
load_in_4bit=True,
|
| 195 |
+
bnb_4bit_compute_dtype=compute_dtype,
|
| 196 |
+
bnb_4bit_use_double_quant=True,
|
| 197 |
+
bnb_4bit_quant_type="nf4"
|
| 198 |
+
)
|
| 199 |
+
model_kwargs["torch_dtype"] = compute_dtype
|
| 200 |
+
except Exception:
|
| 201 |
+
pass
|
| 202 |
+
|
| 203 |
+
# Check if it's a multimodal model
|
| 204 |
+
is_multimodal = "medgemma" in self.model_id.lower()
|
| 205 |
+
|
| 206 |
+
if is_multimodal and AutoModelForImageTextToText is not None and AutoProcessor is not None:
|
| 207 |
+
self.processor = AutoProcessor.from_pretrained(self.model_id)
|
| 208 |
+
self.model = AutoModelForImageTextToText.from_pretrained(self.model_id, **model_kwargs)
|
| 209 |
+
self.is_multimodal = True
|
| 210 |
+
elif AutoModelForCausalLM is not None and AutoTokenizer is not None:
|
| 211 |
+
self.tokenizer = AutoTokenizer.from_pretrained(self.model_id)
|
| 212 |
+
self.model = AutoModelForCausalLM.from_pretrained(self.model_id, **model_kwargs)
|
| 213 |
+
self.is_multimodal = False
|
| 214 |
+
else:
|
| 215 |
+
raise RuntimeError("Required model classes not available")
|
| 216 |
+
|
| 217 |
+
print("✓ Model loaded successfully")
|
| 218 |
+
|
| 219 |
+
def generate(self, text: str, image: Optional[Image.Image] = None) -> str:
|
| 220 |
+
"""Generate text using the loaded model."""
|
| 221 |
+
self.load_model()
|
| 222 |
+
|
| 223 |
+
if self.model is None:
|
| 224 |
+
return f"[Model not loaded: {text}]"
|
| 225 |
+
|
| 226 |
+
try:
|
| 227 |
+
# Create messages
|
| 228 |
+
system_text = "You are a concise medical assistant. Provide a brief, clear summary of detection results. Avoid repetition and be direct. Do not give medical advice."
|
| 229 |
+
user_text = f"Summarize these detection results in 3 clear sentences:\n\n{text}"
|
| 230 |
+
|
| 231 |
+
if self.is_multimodal:
|
| 232 |
+
# Multimodal model
|
| 233 |
+
user_content = [{"type": "text", "text": user_text}]
|
| 234 |
+
if image is not None:
|
| 235 |
+
user_content.append({"type": "image", "image": image})
|
| 236 |
+
|
| 237 |
+
messages = [
|
| 238 |
+
{"role": "system", "content": [{"type": "text", "text": system_text}]},
|
| 239 |
+
{"role": "user", "content": user_content},
|
| 240 |
+
]
|
| 241 |
+
|
| 242 |
+
inputs = self.processor.apply_chat_template(
|
| 243 |
+
messages,
|
| 244 |
+
add_generation_prompt=True,
|
| 245 |
+
tokenize=True,
|
| 246 |
+
return_dict=True,
|
| 247 |
+
return_tensors="pt",
|
| 248 |
+
)
|
| 249 |
+
|
| 250 |
+
if torch:
|
| 251 |
+
inputs = inputs.to(self.model.device, dtype=torch.bfloat16)
|
| 252 |
+
|
| 253 |
+
with torch.inference_mode():
|
| 254 |
+
generation = self.model.generate(
|
| 255 |
+
**inputs,
|
| 256 |
+
max_new_tokens=self.max_tokens,
|
| 257 |
+
do_sample=self.temperature > 0,
|
| 258 |
+
temperature=max(0.01, self.temperature) if self.temperature > 0 else None,
|
| 259 |
+
use_cache=False,
|
| 260 |
+
)
|
| 261 |
+
|
| 262 |
+
input_len = inputs["input_ids"].shape[-1]
|
| 263 |
+
generation = generation[0][input_len:]
|
| 264 |
+
decoded = self.processor.decode(generation, skip_special_tokens=True)
|
| 265 |
+
return decoded.strip()
|
| 266 |
+
|
| 267 |
+
else:
|
| 268 |
+
# Text-only model
|
| 269 |
+
messages = [
|
| 270 |
+
{"role": "system", "content": system_text},
|
| 271 |
+
{"role": "user", "content": user_text},
|
| 272 |
+
]
|
| 273 |
+
|
| 274 |
+
inputs = self.tokenizer.apply_chat_template(
|
| 275 |
+
messages,
|
| 276 |
+
add_generation_prompt=True,
|
| 277 |
+
tokenize=True,
|
| 278 |
+
return_dict=True,
|
| 279 |
+
return_tensors="pt",
|
| 280 |
+
)
|
| 281 |
+
|
| 282 |
+
inputs = inputs.to(self.model.device)
|
| 283 |
+
|
| 284 |
+
with torch.inference_mode():
|
| 285 |
+
generation = self.model.generate(
|
| 286 |
+
**inputs,
|
| 287 |
+
max_new_tokens=self.max_tokens,
|
| 288 |
+
do_sample=self.temperature > 0,
|
| 289 |
+
temperature=max(0.01, self.temperature) if self.temperature > 0 else None,
|
| 290 |
+
use_cache=False,
|
| 291 |
+
)
|
| 292 |
+
|
| 293 |
+
input_len = inputs["input_ids"].shape[-1]
|
| 294 |
+
generation = generation[0][input_len:]
|
| 295 |
+
decoded = self.tokenizer.decode(generation, skip_special_tokens=True)
|
| 296 |
+
return decoded.strip()
|
| 297 |
+
|
| 298 |
+
except Exception as e:
|
| 299 |
+
error_msg = f"[Generation error: {e}]"
|
| 300 |
+
print(f"Generation error: {traceback.format_exc()}")
|
| 301 |
+
return f"{error_msg}\n\n{text}"
|
| 302 |
+
|
| 303 |
+
# ============================================================================
|
| 304 |
+
# Application State
|
| 305 |
+
# ============================================================================
|
| 306 |
+
|
| 307 |
+
class AppState:
|
| 308 |
+
"""Application state for Spaces."""
|
| 309 |
+
|
| 310 |
+
def __init__(self):
|
| 311 |
+
self.config = SpacesConfig()
|
| 312 |
+
self.model = None
|
| 313 |
+
self.class_names = None
|
| 314 |
+
self.text_generator = None
|
| 315 |
+
|
| 316 |
+
def load_model(self):
|
| 317 |
+
"""Load the detection model."""
|
| 318 |
+
if self.model is not None:
|
| 319 |
+
return
|
| 320 |
+
|
| 321 |
+
checkpoint = find_checkpoint(
|
| 322 |
+
hf_repo=self.config.get('hf_model_repo'),
|
| 323 |
+
hf_filename=self.config.get('hf_model_filename', 'lorai.pth')
|
| 324 |
+
)
|
| 325 |
+
if not checkpoint:
|
| 326 |
+
hf_repo = self.config.get('hf_model_repo') or os.environ.get('HF_MODEL_REPO')
|
| 327 |
+
if hf_repo:
|
| 328 |
+
raise FileNotFoundError(
|
| 329 |
+
f"No RF-DETR checkpoint found. Could not download from '{hf_repo}'. "
|
| 330 |
+
"Please check the repository ID and ensure the model file exists."
|
| 331 |
+
)
|
| 332 |
+
else:
|
| 333 |
+
raise FileNotFoundError(
|
| 334 |
+
"No RF-DETR checkpoint found. Please either:\n"
|
| 335 |
+
"1. Set HF_MODEL_REPO environment variable (e.g., 'edeler/lorai'), or\n"
|
| 336 |
+
"2. Upload lorai.pth to your Space's root directory"
|
| 337 |
+
)
|
| 338 |
+
|
| 339 |
+
print(f"Loading RF-DETR from: {checkpoint}")
|
| 340 |
+
self.model = load_model(checkpoint, self.config.get('resolution'))
|
| 341 |
+
|
| 342 |
+
# Try to load class names
|
| 343 |
+
try:
|
| 344 |
+
results_json = "/tmp/results/results.json"
|
| 345 |
+
if os.path.isfile(results_json):
|
| 346 |
+
with open(results_json, 'r') as f:
|
| 347 |
+
data = json.load(f)
|
| 348 |
+
classes = []
|
| 349 |
+
for split in ("valid", "test", "train"):
|
| 350 |
+
if "class_map" in data and split in data["class_map"]:
|
| 351 |
+
for item in data["class_map"][split]:
|
| 352 |
+
name = item.get("class")
|
| 353 |
+
if name and name != "all" and name not in classes:
|
| 354 |
+
classes.append(name)
|
| 355 |
+
self.class_names = classes if classes else None
|
| 356 |
+
except Exception:
|
| 357 |
+
pass
|
| 358 |
+
|
| 359 |
+
print("✓ RF-DETR model loaded")
|
| 360 |
+
|
| 361 |
+
def get_text_generator(self, model_size: str = "4B") -> TextGenerator:
|
| 362 |
+
"""Get or create text generator."""
|
| 363 |
+
# Determine model ID based on size selection
|
| 364 |
+
model_id = 'google/medgemma-27b-it' if model_size == "27B" else 'google/medgemma-4b-it'
|
| 365 |
+
|
| 366 |
+
# Check if we need to create a new generator for different model size
|
| 367 |
+
if (self.text_generator is None or
|
| 368 |
+
hasattr(self.text_generator, 'model_id') and
|
| 369 |
+
self.text_generator.model_id != model_id):
|
| 370 |
+
|
| 371 |
+
max_tokens = self.config.get('llm_max_new_tokens')
|
| 372 |
+
temperature = self.config.get('llm_temperature')
|
| 373 |
+
|
| 374 |
+
self.text_generator = TextGenerator(model_id, max_tokens, temperature)
|
| 375 |
+
return self.text_generator
|
| 376 |
+
|
| 377 |
+
# ============================================================================
|
| 378 |
+
# UI and Inference
|
| 379 |
+
# ============================================================================
|
| 380 |
+
|
| 381 |
+
def create_detection_interface():
|
| 382 |
+
"""Create the Gradio interface."""
|
| 383 |
+
|
| 384 |
+
# Color palette for annotations
|
| 385 |
+
COLOR_PALETTE = sv.ColorPalette.from_hex([
|
| 386 |
+
"#ffff00", "#ff9b00", "#ff66ff", "#3399ff", "#ff66b2",
|
| 387 |
+
"#ff8080", "#b266ff", "#9999ff", "#66ffff", "#33ff99",
|
| 388 |
+
"#66ff66", "#99ff00",
|
| 389 |
+
])
|
| 390 |
+
|
| 391 |
+
def annotate_image(image: Image.Image, threshold: float, model_size: str = "4B") -> Tuple[Image.Image, str]:
|
| 392 |
+
"""Process an image and return annotated version with description."""
|
| 393 |
+
|
| 394 |
+
if image is None:
|
| 395 |
+
return None, "Please upload an image."
|
| 396 |
+
|
| 397 |
+
try:
|
| 398 |
+
# Load model if needed
|
| 399 |
+
app_state.load_model()
|
| 400 |
+
|
| 401 |
+
# Run detection
|
| 402 |
+
detections = app_state.model.predict(image, threshold=threshold)
|
| 403 |
+
|
| 404 |
+
# Annotate image
|
| 405 |
+
bbox_annotator = sv.BoxAnnotator(color=COLOR_PALETTE, thickness=2)
|
| 406 |
+
label_annotator = sv.LabelAnnotator(text_scale=0.5, text_color=sv.Color.BLACK)
|
| 407 |
+
|
| 408 |
+
labels = []
|
| 409 |
+
for i in range(len(detections)):
|
| 410 |
+
class_id = int(detections.class_id[i]) if detections.class_id is not None else None
|
| 411 |
+
conf = float(detections.confidence[i]) if detections.confidence is not None else 0.0
|
| 412 |
+
|
| 413 |
+
if app_state.class_names and class_id is not None:
|
| 414 |
+
if 0 <= class_id < len(app_state.class_names):
|
| 415 |
+
label_name = app_state.class_names[class_id]
|
| 416 |
+
else:
|
| 417 |
+
label_name = str(class_id)
|
| 418 |
+
else:
|
| 419 |
+
label_name = str(class_id) if class_id is not None else "object"
|
| 420 |
+
|
| 421 |
+
labels.append(f"{label_name} {conf:.2f}")
|
| 422 |
+
|
| 423 |
+
annotated = image.copy()
|
| 424 |
+
annotated = bbox_annotator.annotate(annotated, detections)
|
| 425 |
+
annotated = label_annotator.annotate(annotated, detections, labels)
|
| 426 |
+
|
| 427 |
+
# Generate description
|
| 428 |
+
description = f"Found {len(detections)} detections above threshold {threshold}:\n\n"
|
| 429 |
+
|
| 430 |
+
if len(detections) > 0:
|
| 431 |
+
counts = {}
|
| 432 |
+
for i in range(len(detections)):
|
| 433 |
+
class_id = int(detections.class_id[i]) if detections.class_id is not None else None
|
| 434 |
+
if app_state.class_names and class_id is not None:
|
| 435 |
+
if 0 <= class_id < len(app_state.class_names):
|
| 436 |
+
name = app_state.class_names[class_id]
|
| 437 |
+
else:
|
| 438 |
+
name = str(class_id)
|
| 439 |
+
else:
|
| 440 |
+
name = str(class_id) if class_id is not None else "object"
|
| 441 |
+
counts[name] = counts.get(name, 0) + 1
|
| 442 |
+
|
| 443 |
+
for name, count in counts.items():
|
| 444 |
+
description += f"- {count}× {name}\n"
|
| 445 |
+
|
| 446 |
+
# Use LLM for description if enabled
|
| 447 |
+
if app_state.config.get('use_llm'):
|
| 448 |
+
try:
|
| 449 |
+
generator = app_state.get_text_generator(model_size)
|
| 450 |
+
llm_description = generator.generate(description, image=annotated)
|
| 451 |
+
description = llm_description
|
| 452 |
+
except Exception as e:
|
| 453 |
+
description = f"[LLM error: {e}]\n\n{description}"
|
| 454 |
+
else:
|
| 455 |
+
description += "No objects detected above the confidence threshold."
|
| 456 |
+
|
| 457 |
+
return annotated, description
|
| 458 |
+
|
| 459 |
+
except Exception as e:
|
| 460 |
+
error_msg = f"Error processing image: {str(e)}"
|
| 461 |
+
print(f"Processing error: {traceback.format_exc()}")
|
| 462 |
+
return None, error_msg
|
| 463 |
+
|
| 464 |
+
# Create the interface
|
| 465 |
+
with gr.Blocks(title="Medical Image Analysis", theme=gr.themes.Soft()) as demo:
|
| 466 |
+
gr.Markdown("# 🏥 Medical Image Analysis")
|
| 467 |
+
gr.Markdown("Upload a medical image to detect and analyze findings using AI.")
|
| 468 |
+
|
| 469 |
+
with gr.Row():
|
| 470 |
+
with gr.Column():
|
| 471 |
+
input_image = gr.Image(type="pil", label="Upload Image", height=400)
|
| 472 |
+
threshold_slider = gr.Slider(
|
| 473 |
+
minimum=0.1,
|
| 474 |
+
maximum=1.0,
|
| 475 |
+
value=0.7,
|
| 476 |
+
step=0.05,
|
| 477 |
+
label="Confidence Threshold",
|
| 478 |
+
info="Higher values = fewer but more confident detections"
|
| 479 |
+
)
|
| 480 |
+
|
| 481 |
+
model_size_radio = gr.Radio(
|
| 482 |
+
choices=["4B", "27B"],
|
| 483 |
+
value="4B",
|
| 484 |
+
label="MedGemma Model Size",
|
| 485 |
+
info="4B: Faster, less memory | 27B: More accurate, more memory"
|
| 486 |
+
)
|
| 487 |
+
|
| 488 |
+
analyze_btn = gr.Button("🔍 Analyze Image", variant="primary")
|
| 489 |
+
|
| 490 |
+
with gr.Column():
|
| 491 |
+
output_image = gr.Image(type="pil", label="Results", height=400)
|
| 492 |
+
output_text = gr.Textbox(
|
| 493 |
+
label="Analysis Results",
|
| 494 |
+
lines=8,
|
| 495 |
+
max_lines=15,
|
| 496 |
+
show_copy_button=True
|
| 497 |
+
)
|
| 498 |
+
|
| 499 |
+
# Wire up the interface
|
| 500 |
+
analyze_btn.click(
|
| 501 |
+
fn=annotate_image,
|
| 502 |
+
inputs=[input_image, threshold_slider, model_size_radio],
|
| 503 |
+
outputs=[output_image, output_text]
|
| 504 |
+
)
|
| 505 |
+
|
| 506 |
+
# Also run when image is uploaded
|
| 507 |
+
input_image.change(
|
| 508 |
+
fn=annotate_image,
|
| 509 |
+
inputs=[input_image, threshold_slider, model_size_radio],
|
| 510 |
+
outputs=[output_image, output_text]
|
| 511 |
+
)
|
| 512 |
+
|
| 513 |
+
# Footer
|
| 514 |
+
gr.Markdown("---")
|
| 515 |
+
|
| 516 |
+
return demo
|
| 517 |
+
|
| 518 |
+
# ============================================================================
|
| 519 |
+
# Main Application
|
| 520 |
+
# ============================================================================
|
| 521 |
+
|
| 522 |
+
# Global app state
|
| 523 |
+
app_state = AppState()
|
| 524 |
+
|
| 525 |
+
def main():
|
| 526 |
+
"""Main entry point for the Spaces app."""
|
| 527 |
+
print("🚀 Starting Medical Image Analysis App")
|
| 528 |
+
|
| 529 |
+
# Ensure results directory exists
|
| 530 |
+
os.makedirs(app_state.config.get('results_dir'), exist_ok=True)
|
| 531 |
+
|
| 532 |
+
# Create and launch the interface
|
| 533 |
+
demo = create_detection_interface()
|
| 534 |
+
|
| 535 |
+
# Launch with Spaces-optimized settings
|
| 536 |
+
demo.launch(
|
| 537 |
+
server_name="0.0.0.0",
|
| 538 |
+
server_port=7860,
|
| 539 |
+
share=False, # Spaces handles this
|
| 540 |
+
show_error=True,
|
| 541 |
+
show_api=False,
|
| 542 |
+
)
|
| 543 |
+
|
| 544 |
+
if __name__ == "__main__":
|
| 545 |
+
main()
|