File size: 20,336 Bytes
2e036a2 0e577bf 2e036a2 a962d35 2e036a2 f4586bd e7a274f ee9e0d6 2e036a2 e7a274f 2e036a2 0e577bf 2e036a2 e7a274f 2e036a2 e7a274f 0e577bf 2e036a2 0e577bf 2e036a2 ee9e0d6 2e036a2 e7a274f 2e036a2 e7a274f ee9e0d6 e7a274f 2e036a2 ee9e0d6 2e036a2 ee9e0d6 0e577bf ee9e0d6 2e036a2 ee9e0d6 f4586bd ee9e0d6 2e036a2 f4586bd 2e036a2 e7a274f 2e036a2 64fab87 2e036a2 e7a274f 2e036a2 e7a274f 2e036a2 e7a274f 2e036a2 ee9e0d6 e7a274f 9598e21 e7a274f 9598e21 ee9e0d6 e7a274f ee9e0d6 f4586bd ee9e0d6 e7a274f f4586bd e7a274f 2e036a2 f4586bd 2e036a2 4946ff5 ee9e0d6 4946ff5 ee9e0d6 4946ff5 f8b26de 4946ff5 a962d35 2e036a2 4946ff5 ee9e0d6 4946ff5 ee9e0d6 4946ff5 2e036a2 f4586bd ee9e0d6 2e036a2 e7a274f 2e036a2 f4586bd ee9e0d6 f4586bd ee9e0d6 2e036a2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 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 | """
Gradio fő interface 3-stage pipeline támogatással.
UI komponensek a ui.components modulból töltődnek
"""
import gradio as gr
import numpy as np
from typing import Dict, Optional, List
from ui.styles import get_custom_css
from ui.components import (
create_header,
create_pipeline_steps_block,
ResultStep,
InputSection,
ControlsSection,
PreviewSection,
PipelineInfo,
DebugLog
)
from preprocessing import IdentityPreprocessor
from game import TwoPlayerGameWrapper
from core.preprocessing_pipeline import PreprocessingPipeline
from core.preprocessing_factory import create_preprocessing_module
from ui.components.preprocessing_pipeline_ui import (
add_step_handler, reset_handler, render_pipeline_steps_html
)
class MainInterface:
def __init__(self, pipeline):
self.pipeline = pipeline
self.game_wrapper: Optional[TwoPlayerGameWrapper] = None
self.preprocessors: Dict[str, Optional[object]] = {}
self.preprocessor_dependencies: Dict[str, Optional[List[str]]] = {}
self.feature_extractors: Dict[str, Optional[object]] = {}
self.classifiers: Dict[str, Optional[object]] = {}
self.current_image = None
self.processed_image = None
self.annotated_image = None
self.current_features = None
self.input_section = InputSection()
self.controls_section = ControlsSection()
self.preview_section = PreviewSection()
self.result_step = ResultStep()
self.pipeline_info = PipelineInfo()
self.debug_log = DebugLog()
def set_game_wrapper(self, game_wrapper: TwoPlayerGameWrapper):
self.game_wrapper = game_wrapper
def register_preprocessor(self, name: str, module, deps: Optional[List[str]]=None):
self.preprocessors[name] = module
if module is not None:
self.preprocessor_dependencies[module.name]=deps
def register_feature_extractor(self, name: str, extractor):
self.feature_extractors[name] = extractor
def register_classifier(self, name: str, classifier):
self.classifiers[name] = classifier
def process_image(self, image, preprocessing_pipeline_state: str,
feature_extractor_name: str, classifier_name: str,
display_mode: str, game_mode: str = "Single Hand"):
if image is None:
return (
None,
*self.result_step.reset(),
self.pipeline_info.update("Preprocessing: No preprocessing"),
self.debug_log.set_text("[Info] No image to process")
)
if game_mode == "Two Player Game":
return self._process_game_mode(image, preprocessing_pipeline_state,
feature_extractor_name, classifier_name,
display_mode)
self.current_image = image
self.debug_log.clear()
# Load preprocessing pipeline from state
preprocessing_pipeline = PreprocessingPipeline(step_factory=create_preprocessing_module)
if preprocessing_pipeline_state:
preprocessing_pipeline.from_json(preprocessing_pipeline_state)
# Build modules from pipeline
modules = preprocessing_pipeline.build_modules()
self.pipeline.clear_preprocessing()
if modules:
for i, module in enumerate(modules):
self.pipeline.add_preprocessing(module, deps=None if module is None else self.preprocessor_dependencies[module.name])
self.debug_log.append(f"[Stage 1.{i+1}] Preprocessing: {module.name}")
else:
# No preprocessing steps - use None to ensure pipeline works
self.pipeline.add_preprocessing(IdentityPreprocessor())
self.debug_log.append(f"[Stage 1] Preprocessing: None")
if feature_extractor_name not in self.feature_extractors:
self.debug_log.append("[Stage 2] ERROR: No feature extractor selected")
return (
image,
*self.result_step.set_error(),
self.pipeline_info.update("Pipeline incomplete"),
self.debug_log.get_text()
)
self.pipeline.set_feature_extractor(self.feature_extractors[feature_extractor_name], name="feature_extractor")
self.debug_log.append(f"[Stage 2] Feature Extractor: {feature_extractor_name}")
if classifier_name not in self.classifiers:
self.debug_log.append("[Stage 3] ERROR: No classifier selected")
return (
image,
*self.result_step.set_error(),
self.pipeline_info.update("Pipeline incomplete"),
self.debug_log.get_text()
)
self.pipeline.set_classifier(self.classifiers[classifier_name])
self.debug_log.append(f"[Stage 3] Classifier: {classifier_name}")
try:
self.debug_log.append("\n[Pipeline] Starting full processing...")
preprocessed, features, result, annotated = self.pipeline.process_full_pipeline(image)
# ==================================================
# átmeneti megoldás: ha lista a pipeline output, akkor csak az 1. elemekkel foglalkozunk
if isinstance(preprocessed, list):
self.debug_log.append(f"preproc count: {len(preprocessed)}")
preprocessed=preprocessed[0].data
else:
preprocessed=preprocessed.data
if isinstance(features, list):
self.debug_log.append(f"features count: {len(features)}")
features=features[0]
if isinstance(result, list):
self.debug_log.append(f"classifications count: {len(result)}")
result=result[0]
# átmeneti megoldás vége
# ==================================================
self.processed_image = preprocessed
self.annotated_image = annotated
self.current_features = features
self.debug_log.append(f"\n[Features] Type: {features.feature_type.value}")
self.debug_log.append(f"[Features] Dimension: {features.feature_dimension}")
self.debug_log.append(f"[Features] Time: {features.extraction_time_ms:.2f}ms")
if features.named_features:
self.debug_log.append("[Features] Values:")
for key, value in features.named_features.items():
self.debug_log.append(f" - {key}: {value:.4f}")
self.debug_log.append(f"\n[Classification] Predicted: {result.predicted_class.value.upper()}")
self.debug_log.append(f"[Classification] Confidence: {result.get_confidence_percentage():.1f}%")
self.debug_log.append(f"[Classification] Time: {result.processing_time_ms:.2f}ms")
class_text, conf_text = self.result_step.update(
result.predicted_class.value,
result.get_confidence_percentage()
)
self.debug_log.append("\n[Pipeline] ✓ Complete!")
except Exception as e:
self.debug_log.append(f"\n[ERROR] {str(e)}")
class_text, conf_text = self.result_step.set_error()
preprocessed = image
if display_mode == "Original":
output_image = self.current_image
elif display_mode == "Annotated":
output_image = self.annotated_image if self.annotated_image is not None else self.current_image
else: # Preprocessed
output_image = self.processed_image if self.processed_image is not None else self.current_image
self.preview_section.set_images(self.current_image, self.processed_image, self.annotated_image)
self.preview_section.set_display_mode(display_mode)
pipeline_info_text = self.pipeline_info.update(self.pipeline.get_pipeline_info())
return (
output_image,
class_text,
conf_text,
pipeline_info_text,
self.debug_log.get_text()
)
def _process_game_mode(self, image, preprocessing_pipeline_state: str,
feature_extractor_name: str, classifier_name: str,
display_mode: str):
"""Process image in two-player game mode."""
self.current_image = image
self.debug_log.clear()
# Check if game wrapper is available
if self.game_wrapper is None:
self.debug_log.append("[ERROR] Game mode not available - game wrapper not initialized")
return (
image,
*self.result_step.set_error(),
self.pipeline_info.update("Game mode error"),
self.debug_log.get_text()
)
# Setup pipeline for game mode
self.pipeline.clear_preprocessing()
from preprocessing.image_splitter import ImageSplitterModule
self.pipeline.add_preprocessing(ImageSplitterModule())
self.debug_log.append(f"[Stage 1a] Image Splitter: Split image for 2-player batch mode")
# Load preprocessing pipeline from state
preprocessing_pipeline = PreprocessingPipeline(step_factory=create_preprocessing_module)
if preprocessing_pipeline_state:
preprocessing_pipeline.from_json(preprocessing_pipeline_state)
# Build modules from pipeline
modules = preprocessing_pipeline.build_modules()
if modules:
for i, module in enumerate(modules):
self.pipeline.add_preprocessing(module)
self.debug_log.append(f"[Stage 1b.{i+1}] Additional Preprocessing: {module.name}")
else:
# No preprocessing steps - use None to ensure pipeline works
self.pipeline.add_preprocessing(IdentityPreprocessor())
self.debug_log.append(f"[Stage 1b] Additional Preprocessing: None")
if feature_extractor_name not in self.feature_extractors:
self.debug_log.append("[Stage 2] ERROR: No feature extractor selected")
return (
image,
*self.result_step.set_error(),
self.pipeline_info.update("Pipeline incomplete"),
self.debug_log.get_text()
)
self.pipeline.set_feature_extractor(self.feature_extractors[feature_extractor_name], name="feature_extractor")
self.debug_log.append(f"[Stage 2] Feature Extractor: {feature_extractor_name}")
if classifier_name not in self.classifiers:
self.debug_log.append("[Stage 3] ERROR: No classifier selected")
return (
image,
*self.result_step.set_error(),
self.pipeline_info.update("Pipeline incomplete"),
self.debug_log.get_text()
)
self.pipeline.set_classifier(self.classifiers[classifier_name])
self.debug_log.append(f"[Stage 3] Classifier: {classifier_name}")
try:
self.debug_log.append("\n[Game Mode] Running two-player game evaluation...")
# Run game wrapper with visualization
game_result, annotated = self.game_wrapper.run_with_visualization(image)
# Store annotated image
self.annotated_image = annotated
# Log player results
p1 = game_result.player1_result
p2 = game_result.player2_result
self.debug_log.append(f"\n[Player 1] Class: {p1.predicted_class.value.upper()}")
self.debug_log.append(f"[Player 1] Confidence: {p1.get_confidence_percentage():.1f}%")
self.debug_log.append(f"\n[Player 2] Class: {p2.predicted_class.value.upper()}")
self.debug_log.append(f"[Player 2] Confidence: {p2.get_confidence_percentage():.1f}%")
# Log game result
self.debug_log.append(f"\n[Game] Status: {game_result.status.upper()}")
if game_result.status == 'valid':
self.debug_log.append(f"[Game] Winner: {game_result.winner.upper()}")
elif game_result.reason:
self.debug_log.append(f"[Game] Reason: {game_result.reason}")
# Format result for display
class_text, conf_text = self._format_game_result(game_result)
self.debug_log.append("\n[Game Mode] ✓ Complete!")
except Exception as e:
self.debug_log.append(f"\n[ERROR] {str(e)}")
import traceback
self.debug_log.append(traceback.format_exc())
class_text, conf_text = self.result_step.set_error()
# Display mode (game mode uses annotated by default)
if display_mode == "Original":
output_image = self.current_image
elif display_mode == "Annotated":
output_image = self.annotated_image if self.annotated_image is not None else self.current_image
else: # Preprocessed
output_image = self.current_image # Game mode doesn't have preprocessed for full image
pipeline_info_text = self.pipeline_info.update(self.pipeline.get_pipeline_info())
return (
output_image,
class_text,
conf_text,
pipeline_info_text,
self.debug_log.get_text()
)
def _format_game_result(self, game_result):
"""Format game result for UI display."""
p1_class = game_result.player1_result.predicted_class.value.upper()
p2_class = game_result.player2_result.predicted_class.value.upper()
p1_conf = game_result.player1_result.get_confidence_percentage()
p2_conf = game_result.player2_result.get_confidence_percentage()
if game_result.status == 'invalid':
class_text = f"❌ Invalid Game\n\nPlayer 1: {p1_class}\nPlayer 2: {p2_class}"
conf_text = f"Reason:\n{game_result.reason}"
elif game_result.status == 'draw':
class_text = f"🤝 Draw!\n\nPlayer 1: {p1_class}\nPlayer 2: {p2_class}"
conf_text = f"P1 conf: {p1_conf:.1f}%\nP2 conf: {p2_conf:.1f}%"
else: # valid
winner = "Player 1" if game_result.winner == 'player1' else "Player 2"
class_text = f"🎉 {winner} Wins!\n\nPlayer 1: {p1_class}\nPlayer 2: {p2_class}"
conf_text = f"P1 conf: {p1_conf:.1f}%\nP2 conf: {p2_conf:.1f}%"
return class_text, conf_text
def create_interface(self) -> gr.Blocks:
with gr.Blocks(
title="Rock-Paper-Scissors"
) as demo:
create_header()
with gr.Row():
with gr.Column(scale=3):
with gr.Tabs():
with gr.Tab("Settings"):
# Game mode selector
with gr.Row():
game_mode_dropdown = gr.Dropdown(
choices=["Single Hand", "Two Player Game"],
value="Single Hand",
label="🎮 Mode",
info="Single Hand: classify one gesture | Two Player Game: evaluate RPS match"
)
with gr.Row(equal_height=True):
(preproc_pipeline_state, feature_dropdown, classifier_dropdown,
preproc_steps_container, preproc_add_dropdown, preproc_add_btn,
preproc_reset_btn) = create_pipeline_steps_block(
self.preprocessors,
self.feature_extractors,
self.classifiers,
step_factory=create_preprocessing_module
)
with gr.Row(equal_height=False):
stream_image, upload_image, input_mode = self.input_section.create()
process_btn = self.controls_section.create()
with gr.Tab("Logs"):
pipeline_out = self.pipeline_info.create()
log_out = self.debug_log.create()
with gr.Column(scale=7):
output_image, display_radio = self.preview_section.create()
with gr.Row():
with gr.Column(scale=1):
class_out = gr.Textbox(
label="",
value=self.result_step._current_class,
container=False,
interactive=False,
elem_classes="class-output-inline",
lines=4
)
self.result_step.class_component = class_out
with gr.Column(scale=1):
conf_out = gr.Textbox(
label="",
value=self.result_step._current_confidence,
container=False,
interactive=False,
elem_classes="confidence-output-inline",
lines=4
)
self.result_step.confidence_component = conf_out
# Common inputs (image will be added dynamically)
common_inputs = [
preproc_pipeline_state,
feature_dropdown,
classifier_dropdown,
display_radio,
game_mode_dropdown
]
outputs = [output_image, class_out, conf_out, pipeline_out, log_out]
# Stream inputs (for live webcam)
stream_inputs = [stream_image] + common_inputs
# Upload inputs (for upload/snapshot)
upload_inputs = [upload_image] + common_inputs
# Mode switching
input_mode.change(
fn=self.input_section.switch_mode,
inputs=[input_mode],
outputs=[stream_image, upload_image]
)
# Stream for real-time webcam processing
stream_image.stream(fn=self.process_image, inputs=stream_inputs, outputs=outputs)
# Upload/snapshot mode events
upload_image.change(fn=self.process_image, inputs=upload_inputs, outputs=outputs)
process_btn.click(fn=self.process_image, inputs=upload_inputs, outputs=outputs)
# Pipeline state changes (use upload_image as default, stream handles itself)
preproc_pipeline_state.change(fn=self.process_image, inputs=upload_inputs, outputs=outputs)
feature_dropdown.change(fn=self.process_image, inputs=upload_inputs, outputs=outputs)
classifier_dropdown.change(fn=self.process_image, inputs=upload_inputs, outputs=outputs)
display_radio.change(fn=self.process_image, inputs=upload_inputs, outputs=outputs)
game_mode_dropdown.change(fn=self.process_image, inputs=upload_inputs, outputs=outputs)
# Preprocessing pipeline UI handlers
def add_step_wrapper(step_type, current_state):
new_state, html = add_step_handler(step_type, current_state, self.preprocessors, create_preprocessing_module)
return new_state, html
def reset_wrapper(current_state):
new_state, html = reset_handler(current_state, create_preprocessing_module)
return new_state, html
# Connect pipeline UI events
preproc_add_btn.click(
fn=add_step_wrapper,
inputs=[preproc_add_dropdown, preproc_pipeline_state],
outputs=[preproc_pipeline_state, preproc_steps_container]
)
preproc_reset_btn.click(
fn=reset_wrapper,
inputs=[preproc_pipeline_state],
outputs=[preproc_pipeline_state, preproc_steps_container]
)
return demo |