Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,536 +1,223 @@
|
|
| 1 |
import os
|
| 2 |
-
import
|
| 3 |
import time
|
| 4 |
-
import threading
|
| 5 |
-
import requests
|
| 6 |
-
import wikipedia
|
| 7 |
import torch
|
| 8 |
-
import cv2
|
| 9 |
import numpy as np
|
| 10 |
-
|
| 11 |
-
from PIL import Image
|
| 12 |
-
import base64 # Added import
|
| 13 |
-
|
| 14 |
import gradio as gr
|
| 15 |
-
|
|
|
|
|
|
|
| 16 |
from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
|
| 17 |
-
|
|
|
|
| 18 |
from realesrgan import RealESRGANer
|
| 19 |
from basicsr.archs.rrdbnet_arch import RRDBNet
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
else:
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
models['qa_pipeline'] = None
|
| 47 |
-
|
| 48 |
-
# Initialize the Gemma model
|
| 49 |
-
try:
|
| 50 |
-
models['gemma_tokenizer'] = AutoTokenizer.from_pretrained("google/gemma-2-2b-it")
|
| 51 |
-
models['gemma_model'] = AutoModelForCausalLM.from_pretrained(
|
| 52 |
-
"google/gemma-2-2b-it",
|
| 53 |
-
device_map="auto",
|
| 54 |
-
torch_dtype=torch.bfloat16 if device == 'cuda' else torch.float32
|
| 55 |
-
)
|
| 56 |
-
print("Gemma model initialized.")
|
| 57 |
-
except Exception as e:
|
| 58 |
-
print(f"Error initializing the Gemma model: {e}")
|
| 59 |
-
models['gemma_model'] = None
|
| 60 |
-
|
| 61 |
-
# Initialize the depth estimation model using MarigoldDepthPipeline exactly as per your sample
|
| 62 |
-
try:
|
| 63 |
-
if device == 'cuda':
|
| 64 |
-
models['depth_pipe'] = MarigoldDepthPipeline.from_pretrained(
|
| 65 |
-
"prs-eth/marigold-depth-lcm-v1-0",
|
| 66 |
-
variant="fp16",
|
| 67 |
-
torch_dtype=torch.float16
|
| 68 |
-
).to('cuda')
|
| 69 |
-
else:
|
| 70 |
-
# For CPU or MPS devices, keep on 'cpu' to avoid unsupported operators
|
| 71 |
-
models['depth_pipe'] = MarigoldDepthPipeline.from_pretrained(
|
| 72 |
-
"prs-eth/marigold-depth-lcm-v1-0",
|
| 73 |
-
torch_dtype=torch.float32
|
| 74 |
-
).to('cpu')
|
| 75 |
-
print("Depth estimation model initialized.")
|
| 76 |
-
except Exception as e:
|
| 77 |
-
error_message = f"Error initializing the depth estimation model: {e}"
|
| 78 |
-
print(error_message)
|
| 79 |
-
models['depth_pipe'] = None
|
| 80 |
-
models['depth_init_error'] = error_message # Store the error message
|
| 81 |
-
|
| 82 |
-
# Initialize the upscaling model
|
| 83 |
-
try:
|
| 84 |
-
upscaler_model_path = 'weights/RealESRGAN_x4plus.pth' # Ensure this path is correct
|
| 85 |
-
if not os.path.exists(upscaler_model_path):
|
| 86 |
-
print(f"Upscaling model weights not found at {upscaler_model_path}. Please download them.")
|
| 87 |
-
models['upscaler'] = None
|
| 88 |
-
else:
|
| 89 |
-
# Define the model architecture
|
| 90 |
-
model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64,
|
| 91 |
-
num_block=23, num_grow_ch=32, scale=4)
|
| 92 |
-
|
| 93 |
-
# Initialize RealESRGANer
|
| 94 |
-
models['upscaler'] = RealESRGANer(
|
| 95 |
-
scale=4,
|
| 96 |
-
model_path=upscaler_model_path,
|
| 97 |
-
model=model,
|
| 98 |
-
pre_pad=0,
|
| 99 |
-
half=(device == 'cuda'),
|
| 100 |
-
device=device
|
| 101 |
-
)
|
| 102 |
-
print("Real-ESRGAN upscaler initialized.")
|
| 103 |
-
except Exception as e:
|
| 104 |
-
print(f"Error initializing the upscaling model: {e}")
|
| 105 |
-
models['upscaler'] = None
|
| 106 |
-
|
| 107 |
-
# Initialize YOLO model
|
| 108 |
-
try:
|
| 109 |
-
source_weights_path = "/Users/David/Downloads/WheelOfFortuneLab-DavidDriscoll/Eurybia1.3/mbari_315k_yolov8.pt"
|
| 110 |
-
if not os.path.exists(source_weights_path):
|
| 111 |
-
print(f"YOLO weights not found at {source_weights_path}. Please download them.")
|
| 112 |
-
models['yolo_model'] = None
|
| 113 |
-
else:
|
| 114 |
-
models['yolo_model'] = YOLO(source_weights_path)
|
| 115 |
-
print("YOLO model initialized.")
|
| 116 |
-
except Exception as e:
|
| 117 |
-
print(f"Error initializing YOLO model: {e}")
|
| 118 |
-
models['yolo_model'] = None
|
| 119 |
-
|
| 120 |
-
return models
|
| 121 |
-
|
| 122 |
-
models = initialize_models()
|
| 123 |
-
|
| 124 |
-
# Utility Functions
|
| 125 |
-
def search_class_description(class_name):
|
| 126 |
-
wikipedia.set_lang("en")
|
| 127 |
-
wikipedia.set_rate_limiting(True)
|
| 128 |
-
description = ""
|
| 129 |
-
|
| 130 |
-
try:
|
| 131 |
-
page = wikipedia.page(class_name)
|
| 132 |
-
if page:
|
| 133 |
-
description = page.content[:5000] # Get more content
|
| 134 |
-
except Exception as e:
|
| 135 |
-
print(f"Error fetching description for {class_name}: {e}")
|
| 136 |
-
|
| 137 |
-
return description
|
| 138 |
-
|
| 139 |
-
def search_class_image(class_name):
|
| 140 |
wikipedia.set_lang("en")
|
| 141 |
wikipedia.set_rate_limiting(True)
|
| 142 |
-
img_url = ""
|
| 143 |
-
|
| 144 |
try:
|
| 145 |
page = wikipedia.page(class_name)
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
def process_image(image):
|
| 157 |
-
if models['yolo_model'] is None:
|
| 158 |
-
return None, "YOLO model is not initialized.", "YOLO model is not initialized.", [], None
|
| 159 |
-
|
| 160 |
-
try:
|
| 161 |
-
if image is None:
|
| 162 |
-
return None, "No image uploaded.", "No image uploaded.", [], None
|
| 163 |
-
|
| 164 |
-
# Convert Gradio Image to OpenCV format
|
| 165 |
-
image_np = np.array(image)
|
| 166 |
-
if image_np.dtype != np.uint8:
|
| 167 |
-
image_np = image_np.astype(np.uint8)
|
| 168 |
-
|
| 169 |
-
if len(image_np.shape) != 3 or image_np.shape[2] != 3:
|
| 170 |
-
return None, "Invalid image format. Please upload a RGB image.", "Invalid image format. Please upload a RGB image.", [], None
|
| 171 |
-
|
| 172 |
-
image_cv = cv2.cvtColor(image_np, cv2.COLOR_RGB2BGR)
|
| 173 |
-
|
| 174 |
-
# Store the original image before drawing bounding boxes
|
| 175 |
-
original_image_cv = image_cv.copy()
|
| 176 |
-
original_image_pil = Image.fromarray(cv2.cvtColor(original_image_cv, cv2.COLOR_BGR2RGB))
|
| 177 |
-
|
| 178 |
-
# Perform YOLO prediction
|
| 179 |
-
results = models['yolo_model'].predict(
|
| 180 |
-
source=image_cv, conf=0.075)[0] # Lowered the threshold
|
| 181 |
-
|
| 182 |
-
bounding_boxes = []
|
| 183 |
-
image_processed = image_cv.copy()
|
| 184 |
-
|
| 185 |
-
if results.boxes is not None:
|
| 186 |
-
for box in results.boxes:
|
| 187 |
-
x1, y1, x2, y2 = map(int, box.xyxy[0].tolist())
|
| 188 |
-
class_name = models['yolo_model'].names[int(box.cls)]
|
| 189 |
-
confidence = box.conf.item() * 100 # Convert to percentage
|
| 190 |
-
|
| 191 |
-
bounding_boxes.append({
|
| 192 |
-
"coords": (x1, y1, x2, y2),
|
| 193 |
-
"class_name": class_name,
|
| 194 |
-
"confidence": confidence
|
| 195 |
-
})
|
| 196 |
-
|
| 197 |
-
cv2.rectangle(image_processed, (x1, y1), (x2, y2), (0, 0, 255), 2)
|
| 198 |
-
cv2.putText(image_processed, f'{class_name} {confidence:.2f}%',
|
| 199 |
-
(x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX,
|
| 200 |
-
0.9, (0, 0, 255), 2)
|
| 201 |
-
|
| 202 |
-
# Convert back to PIL Image
|
| 203 |
-
processed_image = Image.fromarray(cv2.cvtColor(image_processed, cv2.COLOR_BGR2RGB))
|
| 204 |
-
|
| 205 |
-
# Prepare detection info
|
| 206 |
-
if bounding_boxes:
|
| 207 |
-
detection_info = "\n".join(
|
| 208 |
-
[f'{box["class_name"]}: {box["confidence"]:.2f}%' for box in bounding_boxes]
|
| 209 |
-
)
|
| 210 |
else:
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
# Prepare detection details as Markdown
|
| 214 |
-
if bounding_boxes:
|
| 215 |
-
details = ""
|
| 216 |
-
for idx, box in enumerate(bounding_boxes):
|
| 217 |
-
class_name = box['class_name']
|
| 218 |
-
confidence = box['confidence']
|
| 219 |
-
description = search_class_description(class_name)
|
| 220 |
-
img_url = search_class_image(class_name)
|
| 221 |
-
img_md = ""
|
| 222 |
-
if img_url:
|
| 223 |
-
try:
|
| 224 |
-
headers = {
|
| 225 |
-
'User-Agent': 'MyApp/1.0 (https://example.com/contact; [email protected])'
|
| 226 |
-
}
|
| 227 |
-
response = requests.get(img_url, headers=headers, timeout=10)
|
| 228 |
-
img_data = response.content
|
| 229 |
-
img = Image.open(BytesIO(img_data)).convert("RGB")
|
| 230 |
-
img.thumbnail((400, 400)) # Resize for faster loading
|
| 231 |
-
buffered = BytesIO()
|
| 232 |
-
img.save(buffered, format="PNG")
|
| 233 |
-
img_str = base64.b64encode(buffered.getvalue()).decode()
|
| 234 |
-
img_md = f"\n\n"
|
| 235 |
-
except Exception as e:
|
| 236 |
-
print(f"Error fetching image for {class_name}: {e}")
|
| 237 |
-
details += f"### {idx+1}. {class_name} ({confidence:.2f}%)\n\n"
|
| 238 |
-
if description:
|
| 239 |
-
details += f"{description}\n\n"
|
| 240 |
-
if img_md:
|
| 241 |
-
details += f"{img_md}\n\n"
|
| 242 |
-
detection_details_md = details
|
| 243 |
-
else:
|
| 244 |
-
detection_details_md = "No detections to show."
|
| 245 |
-
|
| 246 |
-
return processed_image, detection_info, detection_details_md, bounding_boxes, original_image_pil
|
| 247 |
except Exception as e:
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
return "No detected objects to ask about.", state
|
| 257 |
-
|
| 258 |
-
# Combine descriptions of all detected objects as context
|
| 259 |
-
context = ""
|
| 260 |
-
for box in state['bounding_boxes']:
|
| 261 |
-
description = search_class_description(box['class_name'])
|
| 262 |
-
if description:
|
| 263 |
-
context += description + "\n"
|
| 264 |
-
|
| 265 |
-
if not context.strip():
|
| 266 |
-
return "No sufficient context available to answer the question.", state
|
| 267 |
-
|
| 268 |
try:
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
answer
|
| 273 |
-
answer_text = answer['answer'].strip()
|
| 274 |
-
if not answer_text:
|
| 275 |
-
return "I couldn't find an answer to that question based on the detected objects.", state
|
| 276 |
-
return answer_text, state
|
| 277 |
except Exception as e:
|
| 278 |
-
|
| 279 |
-
return f"Error during question answering: {e}", state
|
| 280 |
|
| 281 |
-
def enhance_image(
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
try:
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
# Run the model to enhance the image
|
| 290 |
-
output, _ = models['upscaler'].enhance(img, outscale=4)
|
| 291 |
-
|
| 292 |
enhanced_image = Image.fromarray(output)
|
| 293 |
-
|
| 294 |
-
return enhanced_image, "Image enhanced successfully."
|
| 295 |
except Exception as e:
|
| 296 |
-
|
| 297 |
-
return None, f"Error during image enhancement: {e}"
|
| 298 |
-
|
| 299 |
-
def run_depth_prediction(original_image):
|
| 300 |
-
if models['depth_pipe'] is None:
|
| 301 |
-
error_msg = models.get('depth_init_error', "Depth estimation model is not initialized.")
|
| 302 |
-
return None, error_msg
|
| 303 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 304 |
try:
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
result = models['depth_pipe'](input_image)
|
| 313 |
-
|
| 314 |
-
# Access the depth prediction
|
| 315 |
-
depth_prediction = result.prediction # Adjust based on sample code
|
| 316 |
-
|
| 317 |
-
# Visualize the depth map
|
| 318 |
-
vis_depth = models['depth_pipe'].image_processor.visualize_depth(depth_prediction)
|
| 319 |
-
|
| 320 |
-
# Ensure vis_depth is a list and extract the first image
|
| 321 |
-
if isinstance(vis_depth, list) and len(vis_depth) > 0:
|
| 322 |
-
vis_depth_image = vis_depth[0]
|
| 323 |
-
else:
|
| 324 |
-
vis_depth_image = vis_depth # Fallback if not a list
|
| 325 |
-
|
| 326 |
-
return vis_depth_image, "Depth prediction completed."
|
| 327 |
except Exception as e:
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 332 |
with gr.Blocks() as demo:
|
| 333 |
-
gr.Markdown("# Eurybia Mini
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
with gr.Row():
|
| 337 |
-
with gr.Column():
|
| 338 |
-
image_input = gr.Image(type="pil", label="Upload Image")
|
| 339 |
-
process_button = gr.Button("Process Image")
|
| 340 |
-
clear_button = gr.Button("Clear")
|
| 341 |
-
with gr.Column():
|
| 342 |
-
processed_image = gr.Image(type="pil", label="Processed Image")
|
| 343 |
-
detection_info = gr.Textbox(label="Detection Information", lines=10)
|
| 344 |
-
|
| 345 |
-
with gr.Tab("Detection Details"):
|
| 346 |
-
with gr.Accordion("Click to see detection details", open=False):
|
| 347 |
-
detection_details_md = gr.Markdown("No detections to show.")
|
| 348 |
|
| 349 |
-
with gr.
|
| 350 |
-
with gr.
|
| 351 |
-
|
| 352 |
-
question_input = gr.Textbox(label="Ask a question about the detected objects")
|
| 353 |
-
ask_button = gr.Button("Ask Eurybia")
|
| 354 |
-
with gr.Column():
|
| 355 |
-
answer_output = gr.Markdown(label="Eurybia's Answer")
|
| 356 |
-
|
| 357 |
-
with gr.Tab("Depth Estimation"):
|
| 358 |
-
with gr.Row():
|
| 359 |
-
with gr.Column():
|
| 360 |
-
depth_button = gr.Button("Run Depth Prediction")
|
| 361 |
-
with gr.Column():
|
| 362 |
-
depth_output = gr.Image(type="pil", label="Depth Map")
|
| 363 |
-
depth_status = gr.Textbox(label="Status", lines=2)
|
| 364 |
-
|
| 365 |
-
# Display error message if depth estimation model failed to initialize
|
| 366 |
-
if models.get('depth_init_error'):
|
| 367 |
-
gr.Markdown(f"**Depth Estimation Initialization Error:** {models['depth_init_error']}")
|
| 368 |
-
|
| 369 |
-
with gr.Tab("Enhance Detected Objects"):
|
| 370 |
-
if models['yolo_model'] is not None and models['upscaler'] is not None:
|
| 371 |
with gr.Row():
|
| 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 |
-
- **Dataset**: Sourced from [FathomNet](https://fathomnet.org).
|
| 408 |
-
- **Model**: Derived from MBARI’s curated dataset of 315,000 marine annotations.
|
| 409 |
-
- **License**: Dataset and models adhere to MBARI’s Creative Commons Attribution-NonCommercial 4.0 International License (CC BY-NC 4.0).
|
| 410 |
-
|
| 411 |
-
## Datasets
|
| 412 |
-
- **FathomNet MBARI Dataset**:
|
| 413 |
-
- A large-scale dataset for marine biodiversity image annotations.
|
| 414 |
-
- All content adheres to the [CC BY-NC 4.0 License](https://creativecommons.org/licenses/by-nc/4.0/).
|
| 415 |
-
|
| 416 |
-
## Acknowledgments
|
| 417 |
-
- **Ultralytics YOLO**: For the YOLOv8 architecture used for object detection.
|
| 418 |
-
- **FathomNet and MBARI**: For providing the marine dataset and annotations that support object detection in underwater imagery.
|
| 419 |
-
- **Gradio**: For providing an intuitive interface for machine learning applications.
|
| 420 |
-
- **Hugging Face**: For pretrained models and pipelines (e.g., Transformers, Diffusers).
|
| 421 |
-
- **Real-ESRGAN**: For image enhancement and upscaling models.
|
| 422 |
-
- **Wikipedia API**: For fetching object descriptions and images.
|
| 423 |
-
""")
|
| 424 |
-
|
| 425 |
-
# Hidden state to store bounding boxes, original and processed images
|
| 426 |
-
state = gr.State({"bounding_boxes": [], "last_image": None, "original_image": None})
|
| 427 |
-
|
| 428 |
-
# Event Handlers
|
| 429 |
-
def on_process_image(image, state):
|
| 430 |
-
processed_img, info, details, bounding_boxes, original_image_pil = process_image(image)
|
| 431 |
-
if processed_img is not None:
|
| 432 |
-
# Update the state with new bounding boxes and images
|
| 433 |
-
state['bounding_boxes'] = bounding_boxes
|
| 434 |
-
state['last_image'] = processed_img
|
| 435 |
-
state['original_image'] = original_image_pil
|
| 436 |
-
# Update the dropdown choices for detected objects
|
| 437 |
-
choices = [f"{idx+1}. {box['class_name']} ({box['confidence']:.2f}%)" for idx, box in enumerate(bounding_boxes)]
|
| 438 |
-
else:
|
| 439 |
-
choices = []
|
| 440 |
-
return processed_img, info, details, gr.update(choices=choices), state
|
| 441 |
-
|
| 442 |
-
process_button.click(
|
| 443 |
-
on_process_image,
|
| 444 |
-
inputs=[image_input, state],
|
| 445 |
-
outputs=[processed_image, detection_info, detection_details_md, detected_objects, state]
|
| 446 |
-
)
|
| 447 |
-
|
| 448 |
-
def on_clear(state):
|
| 449 |
-
state = {"bounding_boxes": [], "last_image": None, "original_image": None}
|
| 450 |
-
return None, "No detections found.", "No detections to show.", gr.update(choices=[]), state
|
| 451 |
-
|
| 452 |
-
clear_button.click(
|
| 453 |
-
on_clear,
|
| 454 |
-
inputs=state,
|
| 455 |
-
outputs=[processed_image, detection_info, detection_details_md, detected_objects, state]
|
| 456 |
-
)
|
| 457 |
-
|
| 458 |
-
def on_ask_eurybia(question, state):
|
| 459 |
-
answer, state = ask_eurybia(question, state)
|
| 460 |
-
return answer, state
|
| 461 |
-
|
| 462 |
-
ask_button.click(
|
| 463 |
-
on_ask_eurybia,
|
| 464 |
-
inputs=[question_input, state],
|
| 465 |
-
outputs=[answer_output, state]
|
| 466 |
-
)
|
| 467 |
-
|
| 468 |
-
def on_depth_prediction(state):
|
| 469 |
-
original_image = state.get('original_image')
|
| 470 |
-
depth_img, status = run_depth_prediction(original_image)
|
| 471 |
-
return depth_img, status
|
| 472 |
-
|
| 473 |
-
depth_button.click(
|
| 474 |
-
on_depth_prediction,
|
| 475 |
-
inputs=state,
|
| 476 |
-
outputs=[depth_output, depth_status]
|
| 477 |
-
)
|
| 478 |
-
|
| 479 |
-
def on_enhance_image(selected_object, state):
|
| 480 |
-
if not selected_object:
|
| 481 |
-
return None, "No object selected.", state
|
| 482 |
-
|
| 483 |
-
try:
|
| 484 |
-
idx = int(selected_object.split('.')[0]) - 1
|
| 485 |
-
box = state['bounding_boxes'][idx]
|
| 486 |
-
class_name = box['class_name']
|
| 487 |
-
x1, y1, x2, y2 = box['coords']
|
| 488 |
-
|
| 489 |
-
if not state.get('last_image'):
|
| 490 |
-
return None, "Processed image is not available.", state
|
| 491 |
-
|
| 492 |
-
# Ensure processed_image is stored in state
|
| 493 |
-
processed_img_pil = state['last_image']
|
| 494 |
-
if not isinstance(processed_img_pil, Image.Image):
|
| 495 |
-
return None, "Processed image is in an unsupported format.", state
|
| 496 |
-
|
| 497 |
-
# Convert processed_image to OpenCV format with checks
|
| 498 |
-
processed_img_cv = np.array(processed_img_pil)
|
| 499 |
-
if processed_img_cv.dtype != np.uint8:
|
| 500 |
-
processed_img_cv = processed_img_cv.astype(np.uint8)
|
| 501 |
-
|
| 502 |
-
if len(processed_img_cv.shape) != 3 or processed_img_cv.shape[2] != 3:
|
| 503 |
-
return None, "Invalid processed image format.", state
|
| 504 |
-
|
| 505 |
-
processed_img_cv = cv2.cvtColor(processed_img_cv, cv2.COLOR_RGB2BGR)
|
| 506 |
-
|
| 507 |
-
# Crop the detected object from the processed image
|
| 508 |
-
cropped_img_cv = processed_img_cv[y1:y2, x1:x2]
|
| 509 |
-
if cropped_img_cv.size == 0:
|
| 510 |
-
return None, "Cropped image is empty.", state
|
| 511 |
-
|
| 512 |
-
cropped_img_pil = Image.fromarray(cv2.cvtColor(cropped_img_cv, cv2.COLOR_BGR2RGB))
|
| 513 |
-
|
| 514 |
-
# Enhance the cropped image
|
| 515 |
-
enhanced_img, status = enhance_image(cropped_img_pil)
|
| 516 |
-
return enhanced_img, status, state
|
| 517 |
-
except Exception as e:
|
| 518 |
-
return None, f"Error: {e}", state
|
| 519 |
-
|
| 520 |
-
if models['yolo_model'] is not None and models['upscaler'] is not None:
|
| 521 |
-
enhance_btn.click(
|
| 522 |
-
on_enhance_image,
|
| 523 |
-
inputs=[detected_objects, state],
|
| 524 |
-
outputs=[enhanced_image, enhance_status, state]
|
| 525 |
-
)
|
| 526 |
-
|
| 527 |
-
# Optional: Add a note if the depth model isn't initialized
|
| 528 |
-
if models['depth_pipe'] is None and not models.get('depth_init_error'):
|
| 529 |
-
gr.Markdown("**Warning:** Depth estimation model is not initialized. Depth prediction functionality will be unavailable.")
|
| 530 |
-
|
| 531 |
-
# Optional: Add a note if the upscaler isn't initialized
|
| 532 |
-
if models['upscaler'] is None:
|
| 533 |
-
gr.Markdown("**Warning:** Upscaling model is not initialized. Image enhancement functionality will be unavailable.")
|
| 534 |
|
| 535 |
-
# Launch the Gradio app
|
| 536 |
demo.launch()
|
|
|
|
| 1 |
import os
|
| 2 |
+
import cv2
|
| 3 |
import time
|
|
|
|
|
|
|
|
|
|
| 4 |
import torch
|
|
|
|
| 5 |
import numpy as np
|
| 6 |
+
import requests
|
|
|
|
|
|
|
|
|
|
| 7 |
import gradio as gr
|
| 8 |
+
import wikipedia
|
| 9 |
+
from io import BytesIO
|
| 10 |
+
from PIL import Image, ImageDraw
|
| 11 |
from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
|
| 12 |
+
import diffusers
|
| 13 |
+
from ultralytics import YOLO
|
| 14 |
from realesrgan import RealESRGANer
|
| 15 |
from basicsr.archs.rrdbnet_arch import RRDBNet
|
| 16 |
+
from huggingface_hub import hf_hub_download
|
| 17 |
+
|
| 18 |
+
# Determine device
|
| 19 |
+
if torch.cuda.is_available():
|
| 20 |
+
device = "cuda"
|
| 21 |
+
elif torch.backends.mps.is_available():
|
| 22 |
+
device = "mps"
|
| 23 |
+
else:
|
| 24 |
+
device = "cpu"
|
| 25 |
+
|
| 26 |
+
# ---------------------------
|
| 27 |
+
# Load models from Hugging Face
|
| 28 |
+
# ---------------------------
|
| 29 |
+
|
| 30 |
+
# YOLO detection model – replace the URL with your actual Hugging Face model URL.
|
| 31 |
+
yolo_model = YOLO("https://huggingface.co/your-hf-username/your-yolov8-model/resolve/main/model.pt")
|
| 32 |
+
|
| 33 |
+
# QA pipeline (for Ask Eurybia)
|
| 34 |
+
qa_pipeline = pipeline("question-answering", model="deepset/roberta-base-squad2")
|
| 35 |
+
|
| 36 |
+
# Gemma model (if needed) – already loaded from Hugging Face:
|
| 37 |
+
# gemma_tokenizer = AutoTokenizer.from_pretrained("google/gemma-2-2b-it")
|
| 38 |
+
# gemma_model = AutoModelForCausalLM.from_pretrained(
|
| 39 |
+
# "google/gemma-2-2b-it", device_map="auto",
|
| 40 |
+
# torch_dtype=torch.bfloat16 if device == "cuda" else torch.float32)
|
| 41 |
+
|
| 42 |
+
# Depth estimation model (using Diffusers)
|
| 43 |
+
if device == "cuda":
|
| 44 |
+
depth_pipe = diffusers.MarigoldDepthPipeline.from_pretrained(
|
| 45 |
+
"prs-eth/marigold-depth-lcm-v1-0",
|
| 46 |
+
variant="fp16",
|
| 47 |
+
torch_dtype=torch.float16
|
| 48 |
+
).to(device)
|
| 49 |
+
else:
|
| 50 |
+
depth_pipe = diffusers.MarigoldDepthPipeline.from_pretrained(
|
| 51 |
+
"prs-eth/marigold-depth-lcm-v1-0"
|
| 52 |
+
).to(device)
|
| 53 |
+
|
| 54 |
+
# RealESRGAN upscaling model – download weights from Hugging Face.
|
| 55 |
+
# (Ensure that the repo_id and filename point to a valid model on Hugging Face.)
|
| 56 |
+
upscaler_weight_path = hf_hub_download(repo_id="RealESRGAN/RealESRGAN_x4plus", filename="RealESRGAN_x4plus.pth")
|
| 57 |
+
model_rrdb = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64,
|
| 58 |
+
num_block=23, num_grow_ch=32, scale=4)
|
| 59 |
+
upscaler = RealESRGANer(
|
| 60 |
+
scale=4,
|
| 61 |
+
model_path=upscaler_weight_path,
|
| 62 |
+
model=model_rrdb,
|
| 63 |
+
pre_pad=0,
|
| 64 |
+
half=(device == "cuda"),
|
| 65 |
+
device=device
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
# ---------------------------
|
| 69 |
+
# Define functional endpoints
|
| 70 |
+
# ---------------------------
|
| 71 |
+
|
| 72 |
+
def detect_objects(input_image):
|
| 73 |
+
"""
|
| 74 |
+
Runs YOLO detection on an input image, draws bounding boxes, and returns
|
| 75 |
+
both the processed image and detection info.
|
| 76 |
+
"""
|
| 77 |
+
# Convert PIL to NumPy array and then to BGR (OpenCV format)
|
| 78 |
+
image_np = np.array(input_image)
|
| 79 |
+
image_bgr = cv2.cvtColor(image_np, cv2.COLOR_RGB2BGR)
|
| 80 |
+
|
| 81 |
+
# Run detection with a lower confidence threshold (0.075)
|
| 82 |
+
results = yolo_model.predict(source=image_bgr, conf=0.075)[0]
|
| 83 |
+
|
| 84 |
+
# Create a copy for drawing
|
| 85 |
+
image_out = image_bgr.copy()
|
| 86 |
+
detection_info = ""
|
| 87 |
|
| 88 |
+
if results.boxes is not None:
|
| 89 |
+
for box in results.boxes:
|
| 90 |
+
x1, y1, x2, y2 = map(int, box.xyxy[0].tolist())
|
| 91 |
+
class_name = yolo_model.names[int(box.cls)]
|
| 92 |
+
confidence = box.conf.item() * 100
|
| 93 |
+
detection_info += f"{class_name}: {confidence:.2f}%\n"
|
| 94 |
+
cv2.rectangle(image_out, (x1, y1), (x2, y2), (0, 0, 255), 2)
|
| 95 |
+
cv2.putText(image_out, f"{class_name} {confidence:.2f}%",
|
| 96 |
+
(x1, max(y1 - 10, 0)), cv2.FONT_HERSHEY_SIMPLEX,
|
| 97 |
+
0.9, (0, 0, 255), 2)
|
| 98 |
else:
|
| 99 |
+
detection_info = "No detections found."
|
| 100 |
+
|
| 101 |
+
# Convert back to RGB for display in Gradio
|
| 102 |
+
image_out_rgb = cv2.cvtColor(image_out, cv2.COLOR_BGR2RGB)
|
| 103 |
+
output_image = Image.fromarray(image_out_rgb)
|
| 104 |
+
return output_image, detection_info
|
| 105 |
+
|
| 106 |
+
def get_object_info(class_name):
|
| 107 |
+
"""
|
| 108 |
+
Looks up the given class name on Wikipedia and returns a short description
|
| 109 |
+
and an image (if one is found).
|
| 110 |
+
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
wikipedia.set_lang("en")
|
| 112 |
wikipedia.set_rate_limiting(True)
|
|
|
|
|
|
|
| 113 |
try:
|
| 114 |
page = wikipedia.page(class_name)
|
| 115 |
+
description = page.content[:5000]
|
| 116 |
+
img_url = None
|
| 117 |
+
for img in page.images:
|
| 118 |
+
if img.lower().endswith(('.jpg', '.jpeg', '.png', '.gif')):
|
| 119 |
+
img_url = img
|
| 120 |
+
break
|
| 121 |
+
if img_url:
|
| 122 |
+
response = requests.get(img_url)
|
| 123 |
+
info_image = Image.open(BytesIO(response.content))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
else:
|
| 125 |
+
info_image = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
except Exception as e:
|
| 127 |
+
description = f"Error fetching info: {e}"
|
| 128 |
+
info_image = None
|
| 129 |
+
return description, info_image
|
| 130 |
+
|
| 131 |
+
def ask_eurybia(context, question):
|
| 132 |
+
"""
|
| 133 |
+
Uses the QA pipeline to answer a question given a context.
|
| 134 |
+
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
try:
|
| 136 |
+
answer = qa_pipeline(question=question, context=context)
|
| 137 |
+
if not answer['answer'].strip():
|
| 138 |
+
return "Unknown"
|
| 139 |
+
return answer['answer']
|
|
|
|
|
|
|
|
|
|
|
|
|
| 140 |
except Exception as e:
|
| 141 |
+
return f"Error: {e}"
|
|
|
|
| 142 |
|
| 143 |
+
def enhance_image(input_image):
|
| 144 |
+
"""
|
| 145 |
+
Enhances (upscales) the input image using the RealESRGAN model.
|
| 146 |
+
"""
|
| 147 |
try:
|
| 148 |
+
# Ensure the image is in RGB
|
| 149 |
+
img_np = np.array(input_image.convert("RGB"))
|
| 150 |
+
output, _ = upscaler.enhance(img_np, outscale=4)
|
|
|
|
|
|
|
|
|
|
| 151 |
enhanced_image = Image.fromarray(output)
|
| 152 |
+
return enhanced_image
|
|
|
|
| 153 |
except Exception as e:
|
| 154 |
+
return f"Error during enhancement: {e}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
|
| 156 |
+
def predict_depth(input_image):
|
| 157 |
+
"""
|
| 158 |
+
Predicts a depth map from the input image using the Diffusers pipeline.
|
| 159 |
+
"""
|
| 160 |
try:
|
| 161 |
+
image_rgb = input_image.convert("RGB")
|
| 162 |
+
result = depth_pipe(image_rgb)
|
| 163 |
+
depth_prediction = result.prediction
|
| 164 |
+
vis_depth = depth_pipe.image_processor.visualize_depth(depth_prediction)
|
| 165 |
+
# Assume the first image is the desired output
|
| 166 |
+
depth_img = vis_depth[0]
|
| 167 |
+
return depth_img
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
except Exception as e:
|
| 169 |
+
# If an error occurs, create a blank image with the error message.
|
| 170 |
+
img = Image.new("RGB", (400, 300), color=(255, 255, 255))
|
| 171 |
+
draw = ImageDraw.Draw(img)
|
| 172 |
+
draw.text((10, 150), f"Error: {e}", fill=(255, 0, 0))
|
| 173 |
+
return img
|
| 174 |
+
|
| 175 |
+
# ---------------------------
|
| 176 |
+
# Build the Gradio Interface
|
| 177 |
+
# ---------------------------
|
| 178 |
with gr.Blocks() as demo:
|
| 179 |
+
gr.Markdown("# Eurybia Mini")
|
| 180 |
+
gr.Markdown("This Gradio app replicates the functionalities of your original Tkinter app. "
|
| 181 |
+
"The YOLO and upscaling model weights are now loaded from Hugging Face.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 182 |
|
| 183 |
+
with gr.Tabs():
|
| 184 |
+
with gr.Tab("Object Detection"):
|
| 185 |
+
gr.Markdown("Upload an image for object detection.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 186 |
with gr.Row():
|
| 187 |
+
input_image = gr.Image(label="Input Image", source="upload", type="pil")
|
| 188 |
+
output_image = gr.Image(label="Detected Image")
|
| 189 |
+
detection_text = gr.Textbox(label="Detection Info")
|
| 190 |
+
btn_detect = gr.Button("Detect")
|
| 191 |
+
btn_detect.click(detect_objects, inputs=input_image, outputs=[output_image, detection_text])
|
| 192 |
+
|
| 193 |
+
with gr.Tab("Object Info"):
|
| 194 |
+
gr.Markdown("Enter a class name to fetch info from Wikipedia.")
|
| 195 |
+
class_input = gr.Textbox(label="Class Name")
|
| 196 |
+
info_text = gr.Textbox(label="Description")
|
| 197 |
+
info_image = gr.Image(label="Info Image")
|
| 198 |
+
btn_info = gr.Button("Get Info")
|
| 199 |
+
btn_info.click(get_object_info, inputs=class_input, outputs=[info_text, info_image])
|
| 200 |
+
|
| 201 |
+
with gr.Tab("Ask Eurybia"):
|
| 202 |
+
gr.Markdown("Provide a context and ask a question.")
|
| 203 |
+
context_input = gr.Textbox(label="Context", lines=10, placeholder="Paste context (e.g., detection info) here...")
|
| 204 |
+
question_input = gr.Textbox(label="Question", placeholder="Enter your question here...")
|
| 205 |
+
answer_output = gr.Textbox(label="Answer")
|
| 206 |
+
btn_ask = gr.Button("Ask")
|
| 207 |
+
btn_ask.click(ask_eurybia, inputs=[context_input, question_input], outputs=answer_output)
|
| 208 |
+
|
| 209 |
+
with gr.Tab("Enhance Image"):
|
| 210 |
+
gr.Markdown("Upload an image to enhance (upscale).")
|
| 211 |
+
enhance_input = gr.Image(label="Input Image", source="upload", type="pil")
|
| 212 |
+
enhanced_output = gr.Image(label="Enhanced Image")
|
| 213 |
+
btn_enhance = gr.Button("Enhance")
|
| 214 |
+
btn_enhance.click(enhance_image, inputs=enhance_input, outputs=enhanced_output)
|
| 215 |
+
|
| 216 |
+
with gr.Tab("Depth Prediction"):
|
| 217 |
+
gr.Markdown("Upload an image for depth prediction.")
|
| 218 |
+
depth_input = gr.Image(label="Input Image", source="upload", type="pil")
|
| 219 |
+
depth_output = gr.Image(label="Depth Image")
|
| 220 |
+
btn_depth = gr.Button("Predict Depth")
|
| 221 |
+
btn_depth.click(predict_depth, inputs=depth_input, outputs=depth_output)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 222 |
|
|
|
|
| 223 |
demo.launch()
|