import os
# os.environ['ROBOFIT_DEBUG_ENABLE'] = "yes"
# cdir = os.getcwd().split("robofit")
# cdir = cdir[0] + "robofit"
# os.environ["TEAM_NAME"] = "RobotScripts"
# os.environ["ROBOT_ROOT_PATH"] = cdir
# os.environ["ROBOT_REPORT_PATH"] = f"{cdir}\CRE\RobotScripts"r"\Test_Reports"
# os.environ["TEST_MODULE_FOLDER"] = cdir
import re
import shutil
import time
from dataclasses import dataclass
from datetime import datetime, timedelta
from itertools import product # For generating combinations
from typing import Tuple, Union, List
import easyocr
from pathlib import Path
import cv2
import numpy as np
from skimage.metrics import structural_similarity as ssim
import os
from CRE.Resources.Variables.VisionAcquisition.VisionAcquisitionVar import *
from Robo_FIT.GenericLibraries.GenericOpLibs.TestArtifacts.CommonKeywordsClass import CommonKeywordsClass
from Robo_FIT.GenericLibraries.GenericOpLibs.TestArtifacts.CustomPrint import robot_print_error, robot_print_info, \
robot_print_warning, robot_print_debug
from Robo_FIT.GenericLibraries.GenericOpLibs.VisionAcquisition.VisionAcquisition import VisionAcquisition
from Robo_FIT.GenericLibraries.GenericOpLibs.VisionAcquisition.ConfigurationManager import ConfigurationManager
RoiTuple = Tuple[int, int, int, int]
@dataclass
class BootUpConfig:
"""
A dataclass to store the Regions of Interest (ROI) for the three main boards.
By default, dataclasses are mutable. You can change CID_BOARD, PID_BOARD,
and DID_BOARD directly after instantiation.
"""
CID_BOARD: RoiTuple = (0, 0, 0, 0)
PID_BOARD: RoiTuple = (0, 0, 0, 0)
DID_BOARD: RoiTuple = (0, 0, 0, 0)
@property
def monitoring_areas(self) -> dict[str, RoiTuple]:
"""
Returns the ROIs in a dictionary format compatible with the existing processing functions.
"""
return {
"CID_BOARD": self.CID_BOARD,
"PID_BOARD": self.PID_BOARD,
"DID_BOARD": self.DID_BOARD,
}
class VisionComparisonProvider:
def __init__(self):
self.comparison_methods = {
'histogram': self._compare_histograms,
'template_matching': self._template_matching,
'feature_matching': self._feature_matching,
'pixel_difference': self._pixel_difference,
'ssim': self._ssim_comparison,
'combined': self._combined_comparison
}
self.reference_combinations_paths = REFERENCE_COMBINATIONS_PATHS
self.combination_names = self._generate_combination_names() # Generates descriptive names
self.config_manager = ConfigurationManager()
self.common_keywords = CommonKeywordsClass()
self.vision_acq = VisionAcquisition()
self.boot_up_config = BootUpConfig()
self.ocr_reader = easyocr.Reader(['en'])
def launch_vision_acq_app(self):
self.vision_acq.launch_process()
def close_vision_acq_app(self):
self.vision_acq.close_exe_by_name(exe_name='VisionAcquisition.exe')
def preprocess_frame(self, image):
"""Standard image preprocessing for OCR."""
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.medianBlur(gray, 3)
_, thresh = cv2.threshold(blurred, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
return thresh
def get_latest_frame_from_vision_acq(self, frame_name):
"""
Uses VisionComparisonProvider's method to capture the latest image from the buffer.
"""
robot_print_info("Requesting latest frame from Vision Acquisition buffer...")
self.launch_vision_acq_app()
temp_image_path = self.use_vision_acq_to_capture_and_save_latest_image(rename_to=frame_name)
if temp_image_path is None or not os.path.exists(temp_image_path):
robot_print_error("Failed to acquire latest image from Vision Acquisition buffer.")
return None, None
frame = cv2.imread(temp_image_path)
if frame is None:
robot_print_error(f"Failed to load image from path: {temp_image_path}")
return None, None
return frame, temp_image_path
def select_roi(self, frame):
"""
Allows the user to manually select a Region of Interest (ROI) on a given frame.
max_width = 800, max_height = 600
"""
height, width = frame.shape[:2]
scale = min(800 / width, 600 / height, 1.0)
resized_frame = cv2.resize(frame, (int(width * scale), int(height * scale)))
cv2.namedWindow("Select ROI", cv2.WINDOW_NORMAL)
cv2.resizeWindow("Select ROI", int(width * scale), int(height * scale))
robot_print_info("Please select the Region of Interest (ROI) for OCR.")
roi = cv2.selectROI("Select ROI", resized_frame, False, False)
cv2.destroyAllWindows()
roi_x = int(roi[0] / scale)
roi_y = int(roi[1] / scale)
roi_w = int(roi[2] / scale)
roi_h = int(roi[3] / scale)
robot_print_info(f"Selected ROI: x={roi_x}, y={roi_y}, width={roi_w}, height={roi_h}")
# Show cropped image for confirmation
cv2.imshow("Selected ROI", frame[roi_y:roi_y + roi_h, roi_x:roi_x + roi_w])
robot_print_info("Press any key to confirm ROI and continue...")
cv2.waitKey(0)
cv2.destroyAllWindows()
return roi_x, roi_y, roi_w, roi_h
def get_rois_from_vision_frame(self, frame_name, num_rois=3):
"""
Acquires a single frame and prompts the user to select multiple ROIs.
After selection, it updates the BootUpConfig instance with the new ROIs.
Returns:
list: A list of (x, y, w, h) tuples, or None if image acquisition fails.
"""
frame, temp_path = self.get_latest_frame_from_vision_acq(frame_name)
if frame is None:
return None
rois = []
for index in range(1, num_rois + 1):
robot_print_info(f"\n--- Selecting ROI {index} of {num_rois} ---")
roi = self.select_roi(frame)
rois.append(roi)
# Update the dataclass with the newly selected ROI coordinates
# This ensures the configuration is saved to the instance.
if index == 1:
self.boot_up_config.CID_BOARD = roi
elif index == 2:
self.boot_up_config.PID_BOARD = roi
elif index == 3:
self.boot_up_config.DID_BOARD = roi
self.save_boot_up_config()
robot_print_info(
f"ROIS: \nCID: {self.boot_up_config.CID_BOARD} \nPID: {self.boot_up_config.PID_BOARD} \nDID: {self.boot_up_config.DID_BOARD}")
def load_boot_up_config(self, filepath=ROIS_CONFIG_PATH):
"""Loads the BootUpConfig from a file if it exists."""
import json
if os.path.exists(filepath):
try:
with open(filepath, 'r') as f:
data = json.load(f)
# Update the dataclass instance
self.boot_up_config.CID_BOARD = tuple(data.get("CID_BOARD", (0, 0, 0, 0)))
self.boot_up_config.PID_BOARD = tuple(data.get("PID_BOARD", (0, 0, 0, 0)))
self.boot_up_config.DID_BOARD = tuple(data.get("DID_BOARD", (0, 0, 0, 0)))
robot_print_info(f"ROIs successfully loaded from {filepath}")
except Exception as e:
robot_print_error(f"Failed to load ROIs from file: {e}. Using default (0,0,0,0).")
def save_boot_up_config(self, filepath=ROIS_CONFIG_PATH):
"""Saves the current BootUpConfig to a file."""
# Example using JSON serialization
import json
with open(filepath, 'w') as f:
# Convert dataclass to a dictionary of plain tuples
data = {k: v for k, v in self.boot_up_config.monitoring_areas.items()}
json.dump(data, f, indent=4)
robot_print_info(f"ROIs saved to {filepath}")
def _generate_combination_names(self):
"""Generates descriptive names for the 8 combinations (e.g., 'A is on, B is off, C is on')."""
screens = ['CID', 'PID', 'DID'] # <--- CHANGED: Only 2 screens now
# Generates all combinations like (True, True), (True, False), etc.
combinations = list(product([True, False], repeat=len(screens)))
names_map = {}
for combo in combinations:
name_parts = [f"{screens[i]} is {'on' if combo[i] else 'off'}" for i in range(len(screens))]
names_map[combo] = ", ".join(name_parts)
return names_map
def compare_images(self, image1_path, image2_path, method='combined', threshold=80.0):
"""
Compare two images using specified method
Args:
image1_path: Path to first image
image2_path: Path to second image
method: Comparison method ('histogram', 'template_matching', 'feature_matching',
'pixel_difference', 'ssim', 'combined')
threshold: Similarity threshold percentage
Returns:
tuple: (is_similar: bool, similarity_score: float, details: dict)
"""
try:
# Load images
img1 = cv2.imread(image1_path)
img2 = cv2.imread(image2_path)
if img1 is None or img2 is None:
return False, 0.0, {"error": "Could not load one or both images"}
# Get comparison function
if method not in self.comparison_methods:
method = 'combined'
comparison_func = self.comparison_methods[method]
result = comparison_func(img1, img2)
# Extract similarity score
if isinstance(result, dict):
similarity_score = result.get('overall_score', 0.0)
details = result
else:
similarity_score = result
details = {"method": method, "score": similarity_score}
is_similar = similarity_score >= threshold
return is_similar, similarity_score, details
except Exception as e:
return False, 0.0, {"error": str(e)}
def _compare_histograms(self, img1, img2):
"""Compare images using color histograms"""
# Convert to HSV for better color comparison
hsv1 = cv2.cvtColor(img1, cv2.COLOR_BGR2HSV)
hsv2 = cv2.cvtColor(img2, cv2.COLOR_BGR2HSV)
# Calculate histograms
hist1 = cv2.calcHist([hsv1], [0, 1, 2], None, [50, 60, 60], [0, 180, 0, 256, 0, 256])
hist2 = cv2.calcHist([hsv2], [0, 1, 2], None, [50, 60, 60], [0, 180, 0, 256, 0, 256])
# Compare histograms using correlation
correlation = cv2.compareHist(hist1, hist2, cv2.HISTCMP_CORREL)
return max(0, correlation) * 100
def _template_matching(self, img1, img2):
"""Compare images using template matching"""
# Resize images to same size
h1, w1 = img1.shape[:2]
h2, w2 = img2.shape[:2]
if h1 != h2 or w1 != w2:
img2 = cv2.resize(img2, (w1, h1))
# Convert to grayscale
gray1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
gray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
# Template matching
result = cv2.matchTemplate(gray1, gray2, cv2.TM_CCOEFF_NORMED)
_, max_val, _, _ = cv2.minMaxLoc(result)
return max(0, max_val) * 100
def _feature_matching(self, img1, img2):
"""Compare images using feature matching (ORB)"""
# Convert to grayscale
gray1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
gray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
# Initialize ORB detector
orb = cv2.ORB_create(nfeatures=1000)
# Find keypoints and descriptors
kp1, des1 = orb.detectAndCompute(gray1, None)
kp2, des2 = orb.detectAndCompute(gray2, None)
if des1 is None or des2 is None:
return 0.0
# Match features
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
matches = bf.match(des1, des2)
# Sort matches by distance
matches = sorted(matches, key=lambda x: x.distance)
# Calculate similarity based on good matches
good_matches = [m for m in matches if m.distance < 50]
if len(kp1) == 0 or len(kp2) == 0:
return 0.0
similarity = (len(good_matches) / min(len(kp1), len(kp2))) * 100
return min(100, similarity)
def _pixel_difference(self, img1, img2):
"""Compare images using pixel-wise difference"""
# Resize to same dimensions
h1, w1 = img1.shape[:2]
h2, w2 = img2.shape[:2]
if h1 != h2 or w1 != w2:
img2 = cv2.resize(img2, (w1, h1))
# Calculate absolute difference
diff = cv2.absdiff(img1, img2)
# Calculate mean difference
mean_diff = np.mean(diff)
# Convert to similarity percentage (inverse of difference)
max_possible_diff = 255.0
similarity = (1 - (mean_diff / max_possible_diff)) * 100
return max(0, similarity)
def _ssim_comparison(self, img1, img2):
"""Improved SSIM comparison with preprocessing"""
# Resize to same dimensions
h1, w1 = img1.shape[:2]
h2, w2 = img2.shape[:2]
if h1 != h2 or w1 != w2:
img2 = cv2.resize(img2, (w1, h1))
# Convert to grayscale
gray1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
gray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
# Apply Gaussian blur to reduce noise
gray1 = cv2.GaussianBlur(gray1, (5, 5), 0)
gray2 = cv2.GaussianBlur(gray2, (5, 5), 0)
score, _ = ssim(gray1, gray2, full=True)
return max(0, score) * 100
def _combined_comparison(self, img1, img2):
"""Combined comparison using multiple methods with weights"""
methods_weights = {
'histogram': 0.25,
'pixel_difference': 0.25,
'feature_matching': 0.25,
'ssim': 0.25
}
scores = {}
weighted_sum = 0
total_weight = 0
for method, weight in methods_weights.items():
try:
score = self.comparison_methods[method](img1, img2)
scores[method] = score
weighted_sum += score * weight
total_weight += weight
except Exception as e:
scores[method] = f"Error: {str(e)}"
overall_score = weighted_sum / total_weight if total_weight > 0 else 0
return {
'overall_score': overall_score,
'individual_scores': scores,
'method': 'combined'
}
def use_vision_acq_to_capture_and_save_latest_image(self, rename_to=None):
try:
self.vision_acq.copy_all_files()
time.sleep(30)
vision_frames_dir = self.config_manager.get_destination_folder()
vision_frames = [os.path.join(vision_frames_dir, f) for f in os.listdir(vision_frames_dir)
if f.endswith(('.jpg', '.png', '.jpeg'))]
def extract_timestamp(filename):
match = re.search(r'(-?\d+-\d{2}d_\d{2}h_\d{2}m_\d{2}\.\d{3})', filename)
if match:
return match.group(1)
return ''
vision_frames.sort(key=extract_timestamp)
robot_print_info(f"{vision_frames[-1]}")
latest_path = vision_frames[-1]
dir_path = os.path.join(self.common_keywords.get_input_files_dir_path(), "copied_image")
if not os.path.isdir(dir_path):
os.makedirs(dir_path)
if rename_to:
# Ensure the new name has an extension, or append .jpg if missing
if not re.search(r'\.(jpg|jpeg|png)$', rename_to, re.IGNORECASE):
original_ext = os.path.splitext(latest_path)[1]
rename_to = f"{rename_to}{original_ext if original_ext else '.jpg'}" # Default to .jpg if original has no ext
destination_filename = rename_to
else:
timestamp_str = time.strftime("%Y%m%d_%H%M%S")
# Use the original extension if possible
original_ext = os.path.splitext(latest_path)[1]
destination_filename = f"latest_captured_image_{timestamp_str}{original_ext}"
saved_image_path = shutil.copy2(latest_path, os.path.join(dir_path, destination_filename))
robot_print_info(f"Latest image saved for comparison at: {saved_image_path}")
return saved_image_path
except FileNotFoundError:
robot_print_error("FileNotFoundError during image acquisition. Check source/destination paths.")
return None
except Exception as e:
robot_print_error(f"An unexpected error occurred during image acquisition: {e}")
return None
def check_board_status_full_image(self, latest_captured_image_path, method='combined', min_threshold=70.0):
"""
Determines the overall status of the board by comparing the captured image
directly against all 8 full reference combination images.
Args:
latest_captured_image_path (str): Path to the image captured from vision acquisition.
method (str): Image comparison method to use (e.g., 'combined', 'ssim').
min_threshold (float): Minimum similarity score for a match to be considered valid.
If the highest score is below this, status is "Undetermined".
Returns:
tuple: (board_status_description: str, highest_match_percentage: float, detailed_results: dict)
"""
robot_print_info(f"Initiating full image comparison for: {latest_captured_image_path}")
if not os.path.exists(latest_captured_image_path):
robot_print_error(f"Error: Captured image not found at: {latest_captured_image_path}")
return "Error: Captured image not found", 0.0, {"error": "Captured image not found"}
match_results = []
highest_match_percentage = 0.0
best_match_combo_tuple = None
# Iterate through each known combination and its reference image
for combo_tuple, ref_image_path in self.reference_combinations_paths.items():
combo_name = self.combination_names.get(combo_tuple, "Unknown Combination")
if not os.path.exists(ref_image_path):
robot_print_error(
f"Reference image not found for '{combo_name}': {ref_image_path}. Skipping comparison.")
match_results.append({
'combination_name': combo_name,
'combination_state': combo_tuple,
'score': 0.0,
'is_similar': False,
'error': 'Reference image missing'
})
continue
robot_print_info(f"Comparing captured image with '{combo_name}' reference: {ref_image_path}")
# Use a threshold of 0.0 here to get the raw score, then apply min_threshold later
is_similar, score, details = self.compare_images(
latest_captured_image_path,
ref_image_path,
method=method,
threshold=0.0
)
match_results.append({
'combination_name': combo_name,
'combination_state': combo_tuple,
'score': score,
'is_similar': score >= min_threshold, # Re-evaluating similarity based on min_threshold
'details': details
})
# Update highest match, but only if it meets the minimum confidence threshold
if score > highest_match_percentage and score >= min_threshold:
highest_match_percentage = score
best_match_combo_tuple = combo_tuple
final_board_status_description = "Undetermined Status (No high-confidence match)"
if best_match_combo_tuple:
final_board_status_description = self.combination_names.get(best_match_combo_tuple)
robot_print_info(f"Board Status determined: '{final_board_status_description}' "
f"with highest match of {highest_match_percentage:.2f}%")
else:
robot_print_error(f"No combination matched above the minimum threshold of {min_threshold}%.")
robot_print_info("\n--- Full Comparison Table for Captured Image ---")
robot_print_info(f"Captured Image: {os.path.basename(latest_captured_image_path)}")
robot_print_info(f"Comparison Method: {method.replace('_', ' ').title()}") # Nicer method name
robot_print_info(f"Minimum Match Threshold: {min_threshold:.1f}%")
# Define column widths for formatting
name_width = max(len(d['combination_name']) for d in match_results) if match_results else 30
name_width = max(name_width, len("Combination State")) # Ensure header fits
score_width = len("Score (%)")
match_width = len("Match Status")
header = f"| {('Combination State').ljust(name_width)} | {'Score (%)'.center(score_width)} | {'Match Status'.center(match_width)} |"
separator = f"|-{'-' * name_width}-|-{'-' * score_width}-|-{'-' * match_width}-|"
robot_print_info(separator)
robot_print_info(header)
robot_print_info(separator)
# Sort results for consistent table output (e.g., by score descending)
# Or you might want to keep the original order based on `product([True, False], repeat=3)`
# For this example, let's sort by score to highlight best matches
sorted_match_results = sorted(match_results, key=lambda x: x['score'], reverse=True)
for result in sorted_match_results:
combo_name = result['combination_name']
score = result['score']
is_similar = result['is_similar']
error = result.get('error')
match_status = ""
if error:
match_status = f"ERROR: {error}"
elif is_similar:
match_status = "MATCHED"
else:
match_status = "NOT MATCHED"
row = f"| {combo_name.ljust(name_width)} | {score:>{score_width - 1}.2f}% | {match_status.ljust(match_width)} |"
robot_print_info(row)
robot_print_info(separator)
robot_print_info(f"Overall Best Match: '{final_board_status_description}' ({highest_match_percentage:.2f}%)")
robot_print_info("----------------------------------------------------\n") # End table marker
return final_board_status_description, highest_match_percentage, {
"all_combination_scores": match_results,
"best_matched_combination": best_match_combo_tuple,
"best_matched_description": final_board_status_description,
"overall_highest_score": highest_match_percentage
}
def check_board_status_via_text_in_latest_frame(self, frame_name="status_check.png"):
"""
Performs a single-shot OCR check across all predefined ROIs on the latest image
acquired from the vision provider using EasyOCR.
"""
if self.ocr_reader is None:
return "OCR_ENGINE_FAILED", None, {"error": "EasyOCR engine failed to initialize."}
self.load_boot_up_config()
frame, temp_path = self.get_latest_frame_from_vision_acq(frame_name)
if frame is None:
return "ACQUISITION_FAILED", {"error": "Could not acquire or load source image."}
current_monitoring_areas = self.boot_up_config.monitoring_areas
valid_roi_found = False
for _, roi in current_monitoring_areas.items():
if roi[2] > 0 and roi[3] > 0: # Check if width (index 2) and height (index 3) are greater than zero
valid_roi_found = True
break
if not valid_roi_found:
robot_print_error("ERROR: ROI coordinates are invalid (likely width/height is zero).")
robot_print_error(
"ACTION REQUIRED: Run the setup function get_rois_from_vision_frame() to select and save ROIs before checking status.")
return "ROI_NOT_CONFIGURED", None, {
"error": "ROIs must be configured via get_rois_from_vision_frame first."}
results = {}
overall_status = "ALL_SCREENS_UP"
robot_print_info(f"\n--- Starting OCR Status Check on Image: {frame_name} using EasyOCR ---")
# Process each defined monitoring area
for name, roi in current_monitoring_areas.items():
roi_x, roi_y, roi_w, roi_h = roi
try:
roi_frame = frame[roi_y:roi_y + roi_h, roi_x:roi_x + roi_w]
ocr_results = self.ocr_reader.readtext(roi_frame)
detected_texts = [text for (bbox, text, confidence) in ocr_results]
full_text = " ".join(detected_texts).strip()
is_meaningful_up = any(len(text.strip()) >= MIN_TEXT_LENGTH for text in detected_texts)
status = "UP" if is_meaningful_up else "DOWN (Blank/No Meaningful Text)"
if status.startswith("DOWN"):
overall_status = "PARTIALLY_DOWN"
results[name] = {
"status": status,
"text_detected": full_text,
"roi": roi
}
robot_print_info(f" {name} Status: {status}. Text found: '{full_text[:30]}...'")
except Exception as e:
status = "ERROR"
overall_status = "ERROR"
results[name] = {"status": status, "error": str(e), "roi": roi}
robot_print_error(f" {name} Status: ERROR during OCR: {e}")
robot_print_info("\n--- Status Check Complete ---")
# Final status determination
if overall_status == "PARTIALLY_DOWN" and all(r['status'].startswith("DOWN") for r in results.values()):
overall_status = "BOARD_DOWN"
if overall_status in ["ACQUISITION_FAILED", "ERROR"]:
return overall_status, None, results
cid_status = results.get('CID_BOARD', {}).get('status') == 'UP'
pid_status = results.get('PID_BOARD', {}).get('status') == 'UP'
did_status = results.get('DID_BOARD', {}).get('status') == 'UP'
combination_tuple = (cid_status, pid_status, did_status)
combination_names_map = self._generate_combination_names()
board_status_description = combination_names_map.get(combination_tuple, "Unknown Combination")
robot_print_info(f"OCR determined board combination: '{board_status_description}'")
return board_status_description, combination_tuple, results
def verify_text_in_all_boards(
self,
expected_texts: dict,
timeout_minutes: int = 5,
check_interval_seconds: float = 2.0,
require_all: bool = True
) -> dict:
"""
Verify expected text in all three board ROIs simultaneously.
Args:
expected_texts (dict): Dictionary mapping board names to expected text.
Example: {
'CID_BOARD': 'Ready',
'PID_BOARD': 'Connected',
'DID_BOARD': 'Active'
}
timeout_minutes (int): Maximum time to search
check_interval_seconds (float): Time between checks
require_all (bool): If True, all boards must match. If False, any board match succeeds.
Returns:
dict: Overall results with per-board status
"""
robot_print_info("=" * 80)
robot_print_info("Starting Multi-Board Text Verification")
robot_print_info(f"Boards to verify: {list(expected_texts.keys())}")
robot_print_info(f"Match requirement: {'ALL' if require_all else 'ANY'}")
robot_print_info("=" * 80)
start_time = datetime.now()
end_time = start_time + timedelta(minutes=timeout_minutes)
attempts = 0
try:
# Load saved ROI configuration
self.load_boot_up_config()
roi_map = self.boot_up_config.monitoring_areas
# Validate all required ROIs exist
for board_name in expected_texts.keys():
if board_name not in roi_map:
robot_print_error(f"Board '{board_name}' not found in saved ROI configuration")
return {'error': f'Board {board_name} not configured'}
roi = roi_map[board_name]
if roi[2] <= 0 or roi[3] <= 0:
robot_print_error(f"Invalid ROI for board '{board_name}': {roi}")
return {'error': f'Invalid ROI for {board_name}'}
# Launch vision acquisition
self.launch_vision_acq_app()
time.sleep(2)
# Track match status for each board
board_status = {board: False for board in expected_texts.keys()}
board_texts = {board: "" for board in expected_texts.keys()}
# Start verification loop
while datetime.now() < end_time:
attempts += 1
current_time = datetime.now()
elapsed = (current_time - start_time).total_seconds()
try:
# Capture latest image
img_path = self.use_vision_acq_to_capture_and_save_latest_image(
rename_to=f"multi_board_verify_{attempts}.png"
)
if not img_path or not os.path.exists(img_path):
robot_print_error(f"[Attempt {attempts}] Failed to capture image")
time.sleep(check_interval_seconds)
continue
img = cv2.imread(img_path)
if img is None:
time.sleep(check_interval_seconds)
continue
# Check each board ROI
for board_name, expected_text in expected_texts.items():
if board_status[board_name]: # Already matched
continue
roi = roi_map[board_name]
roi_x, roi_y, roi_w, roi_h = roi
# Extract ROI
roi_img = img[roi_y:roi_y + roi_h, roi_x:roi_x + roi_w]
if roi_img.size == 0:
continue
# Perform OCR
ocr_results = self.ocr_reader.readtext(roi_img)
detected_texts = [text for (bbox, text, confidence) in ocr_results]
extracted_text = " ".join(detected_texts).strip()
board_texts[board_name] = extracted_text
# Check match (case-insensitive)
if expected_text.lower() in extracted_text.lower():
board_status[board_name] = True
robot_print_info(
f"{board_name} matched: '{expected_text}' found in '{extracted_text[:30]}...'")
# Check if verification complete
matched_count = sum(board_status.values())
if require_all:
all_matched = all(board_status.values())
if all_matched:
robot_print_info("=" * 80)
robot_print_info("SUCCESS: All boards matched!")
robot_print_info(f" Time: {elapsed:.1f}s | Attempts: {attempts}")
robot_print_info("=" * 80)
return {
'success': True,
'elapsed_time': elapsed,
'attempts': attempts,
'board_status': board_status,
'board_texts': board_texts
}
else:
if matched_count > 0:
robot_print_info("=" * 80)
robot_print_info("SUCCESS: At least one board matched!")
robot_print_info(f" Matched boards: {[k for k, v in board_status.items() if v]}")
robot_print_info(f" Time: {elapsed:.1f}s | Attempts: {attempts}")
robot_print_info("=" * 80)
return {
'success': True,
'elapsed_time': elapsed,
'attempts': attempts,
'board_status': board_status,
'board_texts': board_texts
}
robot_print_info(
f"[Attempt {attempts:3d}] Elapsed: {elapsed:6.1f}s | "
f"Matched: {matched_count}/{len(expected_texts)}"
)
except Exception as e:
robot_print_error(f"[Attempt {attempts}] Error: {e}")
# Wait before next check
remaining = (end_time - datetime.now()).total_seconds()
if remaining > check_interval_seconds:
time.sleep(check_interval_seconds)
elif remaining > 0:
time.sleep(remaining)
else:
break
# Timeout
elapsed = (datetime.now() - start_time).total_seconds()
matched_boards = [k for k, v in board_status.items() if v]
unmatched_boards = [k for k, v in board_status.items() if not v]
robot_print_error(f"✗ TIMEOUT: Verification incomplete after {elapsed:.1f}s")
robot_print_info(f" Matched boards: {matched_boards}")
robot_print_info(f" Unmatched boards: {unmatched_boards}")
for board in unmatched_boards:
robot_print_info(f" {board} last text: '{board_texts[board][:50]}'")
return {
'success': False,
'elapsed_time': elapsed,
'attempts': attempts,
'board_status': board_status,
'board_texts': board_texts,
'matched_boards': matched_boards,
'unmatched_boards': unmatched_boards
}
except Exception as exp:
robot_print_error(f"Error in verify_text_in_all_boards: {exp}", print_in_report=True)
return {'error': str(exp)}
# finally:
# try:
# self.close_vision_acq_app()
# except:
# pass
def verify_text_in_roi_continuously(
self,
target_text: Union[str, List[str]],
fail_text: Union[str, List[str], None] = None,
timeout_minutes: int = 5,
check_interval_seconds: float = 2.0,
case_sensitive: bool = False,
match_all: bool = False,
save_frames: bool = False,
save_result_image: bool = True,
result_image_name: str = None,
result_image_dir: str = None,
roi_coords: RoiTuple = None,
roi_name: str = None
) -> dict:
"""
Continuously verify text in a selected ROI for up to specified timeout.
Returns True if pass text found, False if fail text found.
Supports both single text and list of texts for pass/fail conditions.
Args:
target_text (str or List[str]): The text(s) to search for (PASS case)
Can be a single string or list of strings
fail_text (str or List[str] or None): The text(s) that indicate failure (FAIL case)
If any found, returns immediately with found=False
timeout_minutes (int): Maximum time to search in minutes (default: 5)
check_interval_seconds (float): Time between checks (default: 2.0)
case_sensitive (bool): Whether text matching should be case-sensitive (default: False)
match_all (bool): For target_text list - True: all texts must be found,
False: any one text is enough (default: False)
save_frames (bool): Whether to save captured frames during verification
save_result_image (bool): Whether to save the final result image (default: True)
result_image_name (str): Custom name for result image (without extension)
Final format: {result_image_name}_{STATUS}.png
If None, uses timestamp
result_image_dir (str): Directory to save result images
If None, uses current working directory
roi_coords (RoiTuple): Optional pre-defined ROI coordinates (x, y, w, h)
If None, user will be prompted to select ROI
roi_name (str): Optional name for the ROI (e.g., 'CID_BOARD', 'PID_BOARD')
If provided and exists in boot_up_config, uses that ROI
Returns:
dict: {
'found': bool (True if pass text found, False if fail text found or timeout),
'elapsed_time': float,
'attempts': int,
'found_at': str,
'roi_coordinates': RoiTuple,
'captured_text': str,
'result_type': str ('pass', 'fail', 'timeout'),
'matched_pass_texts': List[str],
'matched_fail_texts': List[str],
'result_image_path': str,
'verification_history': list
}
"""
# Convert single strings to lists for uniform processing
pass_texts = [target_text] if isinstance(target_text, str) else target_text
fail_texts = []
if fail_text:
fail_texts = [fail_text] if isinstance(fail_text, str) else fail_text
robot_print_info("=" * 80)
robot_print_info(f"Starting ROI Text Verification")
robot_print_info(f"PASS text(s): {pass_texts}")
if fail_texts:
robot_print_info(f"FAIL text(s): {fail_texts}")
robot_print_info(f"Case Sensitive: {case_sensitive}")
robot_print_info(f"Match All Pass Texts: {match_all}")
robot_print_info(f"Timeout: {timeout_minutes} minutes | Check interval: {check_interval_seconds}s")
robot_print_info("=" * 80)
start_time = datetime.now()
end_time = start_time + timedelta(minutes=timeout_minutes)
attempts = 0
last_captured_text = ""
verification_history = []
result_image_path = None
# Setup result image directory
if result_image_dir is None:
result_image_dir = os.getcwd()
# Create directory if it doesn't exist
os.makedirs(result_image_dir, exist_ok=True)
try:
# Launch vision acquisition app
self.launch_vision_acq_app()
time.sleep(2)
# Determine ROI to use
if roi_name and hasattr(self, 'boot_up_config'):
# Try to use ROI from saved configuration
self.load_boot_up_config()
roi_map = self.boot_up_config.monitoring_areas
if roi_name in roi_map:
roi_coords = roi_map[roi_name]
robot_print_info(f"Using saved ROI '{roi_name}': {roi_coords}")
else:
robot_print_error(f"ROI name '{roi_name}' not found in configuration")
roi_coords = None
if roi_coords is None:
# Get ROI from user selection
robot_print_info("ROI not provided. Please select the ROI on the reference frame...")
frame, temp_path = self.get_latest_frame_from_vision_acq("roi_selection_frame.png")
if frame is None:
return {
'found': False,
'elapsed_time': 0,
'attempts': 0,
'found_at': None,
'roi_coordinates': None,
'captured_text': None,
'result_type': 'error',
'matched_pass_texts': [],
'matched_fail_texts': [],
'result_image_path': None,
'error': 'Failed to acquire frame for ROI selection'
}
# Use existing select_roi method
roi_coords = self.select_roi(frame)
robot_print_info(f"User selected ROI: {roi_coords}")
roi_x, roi_y, roi_w, roi_h = roi_coords
# Validate ROI coordinates
if roi_w <= 0 or roi_h <= 0:
robot_print_error(f"Invalid ROI dimensions: width={roi_w}, height={roi_h}")
return {
'found': False,
'elapsed_time': 0,
'attempts': 0,
'found_at': None,
'roi_coordinates': roi_coords,
'captured_text': None,
'result_type': 'error',
'matched_pass_texts': [],
'matched_fail_texts': [],
'result_image_path': None,
'error': 'Invalid ROI dimensions'
}
# Prepare target texts for comparison (normalize case if needed)
search_pass_texts = [txt if case_sensitive else txt.lower() for txt in pass_texts]
search_fail_texts = [txt if case_sensitive else txt.lower() for txt in fail_texts]
robot_print_info(f"Starting continuous verification loop...")
robot_print_info(f"Monitoring ROI: {roi_coords}")
# Start continuous verification loop
while datetime.now() < end_time:
attempts += 1
current_time = datetime.now()
elapsed = (current_time - start_time).total_seconds()
try:
# Capture latest image using existing method
frame_name = f"text_verify_attempt_{attempts}.png" if save_frames else "temp_text_verify.png"
img_path = self.use_vision_acq_to_capture_and_save_latest_image(rename_to=frame_name)
if not img_path or not os.path.exists(img_path):
robot_print_error(f"[Attempt {attempts}] Failed to capture/save image")
time.sleep(check_interval_seconds)
continue
# Load the captured image
img = cv2.imread(img_path)
if img is None:
robot_print_error(f"[Attempt {attempts}] Failed to load image: {img_path}")
time.sleep(check_interval_seconds)
continue
# Extract ROI from the image
roi_img = img[roi_y:roi_y + roi_h, roi_x:roi_x + roi_w]
if roi_img.size == 0:
robot_print_error(f"[Attempt {attempts}] Empty ROI extracted")
time.sleep(check_interval_seconds)
continue
# Preprocess ROI using existing method
preprocessed_roi = self.preprocess_frame(roi_img)
# Perform OCR using existing EasyOCR reader
if self.ocr_reader is None:
robot_print_error("EasyOCR reader not initialized")
return {
'found': False,
'elapsed_time': elapsed,
'attempts': attempts,
'found_at': None,
'roi_coordinates': roi_coords,
'captured_text': None,
'result_type': 'error',
'matched_pass_texts': [],
'matched_fail_texts': [],
'result_image_path': None,
'error': 'OCR reader not initialized'
}
# Use EasyOCR to read text from ROI
ocr_results = self.ocr_reader.readtext(roi_img)
# Extract text from OCR results
detected_texts = [text for (bbox, text, confidence) in ocr_results]
extracted_text = " ".join(detected_texts).strip()
last_captured_text = extracted_text
robot_print_warning(f"Extracted: {last_captured_text}")
# Prepare extracted text for comparison
compare_text = extracted_text if case_sensitive else extracted_text.lower()
# Check for FAIL texts first (priority check)
matched_fail_texts = []
for fail_txt in search_fail_texts:
if fail_txt in compare_text:
# Find original text for reporting
original_fail_idx = search_fail_texts.index(fail_txt)
matched_fail_texts.append(fail_texts[original_fail_idx])
# Check for PASS texts
matched_pass_texts = []
for pass_txt in search_pass_texts:
if pass_txt in compare_text:
# Find original text for reporting
original_pass_idx = search_pass_texts.index(pass_txt)
matched_pass_texts.append(pass_texts[original_pass_idx])
# Determine if pass condition is met
if match_all:
# All pass texts must be found
pass_condition_met = len(matched_pass_texts) == len(pass_texts)
else:
# At least one pass text must be found
pass_condition_met = len(matched_pass_texts) > 0
# Record verification attempt
verification_history.append({
'attempt': attempts,
'timestamp': current_time.strftime('%H:%M:%S'),
'elapsed': round(elapsed, 2),
'matched_pass_texts': matched_pass_texts.copy(),
'matched_fail_texts': matched_fail_texts.copy(),
'extracted_text': extracted_text[:50] # Truncate for history
})
robot_print_info(
f"[Attempt {attempts:3d}] [{current_time.strftime('%H:%M:%S')}] "
f"Elapsed: {elapsed:6.1f}s | "
f"PASS matched: {len(matched_pass_texts)}/{len(pass_texts)} | "
f"FAIL matched: {len(matched_fail_texts)}"
)
# Check FAIL condition first (higher priority)
if matched_fail_texts:
# Save result image with FAIL status
if save_result_image:
result_image_path = self._save_result_image(
img_path,
result_image_name,
"FAIL",
result_image_dir
)
result = {
'found': False,
'elapsed_time': elapsed,
'attempts': attempts,
'found_at': current_time.strftime('%Y-%m-%d %H:%M:%S'),
'roi_coordinates': roi_coords,
'captured_text': extracted_text,
'result_type': 'fail',
'matched_pass_texts': matched_pass_texts,
'matched_fail_texts': matched_fail_texts,
'result_image_path': result_image_path,
'image_path': img_path if save_frames else None,
'verification_history': verification_history
}
robot_print_info("=" * 80)
robot_print_error(f"✗ FAIL: Fail text(s) detected in ROI!")
robot_print_error(f" Matched FAIL texts: {matched_fail_texts}")
robot_print_info(f" Time elapsed: {elapsed:.1f} seconds")
robot_print_info(f" Total attempts: {attempts}")
robot_print_info(f" Found at: {result['found_at']}")
robot_print_info(f" Full extracted text: '{extracted_text}'")
if result_image_path:
robot_print_info(f" Result image saved: {result_image_path}")
robot_print_info("=" * 80)
return result
# Check PASS condition
if pass_condition_met:
# Save result image with PASS status
if save_result_image:
result_image_path = self._save_result_image(
img_path,
result_image_name,
"PASS",
result_image_dir
)
result = {
'found': True,
'elapsed_time': elapsed,
'attempts': attempts,
'found_at': current_time.strftime('%Y-%m-%d %H:%M:%S'),
'roi_coordinates': roi_coords,
'captured_text': extracted_text,
'result_type': 'pass',
'matched_pass_texts': matched_pass_texts,
'matched_fail_texts': [],
'result_image_path': result_image_path,
'image_path': img_path if save_frames else None,
'verification_history': verification_history
}
robot_print_info("=" * 80)
robot_print_info(f" SUCCESS: Pass condition met!")
robot_print_info(f" Matched PASS texts: {matched_pass_texts}")
robot_print_info(f" Time elapsed: {elapsed:.1f} seconds")
robot_print_info(f" Total attempts: {attempts}")
robot_print_info(f" Found at: {result['found_at']}")
robot_print_info(f" Full extracted text: '{extracted_text}'")
if result_image_path:
robot_print_info(f" Result image saved: {result_image_path}")
robot_print_info("=" * 80)
return result
# Optional debug: print extracted text every 10 attempts
if attempts % 10 == 0:
robot_print_info(f" [Debug] PASS matched: {matched_pass_texts}")
robot_print_info(f" [Debug] Latest extracted text: '{last_captured_text[:60]}...'")
except Exception as e:
robot_print_error(f"[Attempt {attempts}] Error during verification: {e}")
last_captured_text = f"Error: {str(e)}"
verification_history.append({
'attempt': attempts,
'timestamp': current_time.strftime('%H:%M:%S'),
'elapsed': round(elapsed, 2),
'matched_pass_texts': [],
'matched_fail_texts': [],
'error': str(e)
})
# Wait before next check
remaining_time = (end_time - datetime.now()).total_seconds()
if remaining_time > check_interval_seconds:
time.sleep(check_interval_seconds)
elif remaining_time > 0:
time.sleep(remaining_time)
else:
break
# Timeout reached - capture last image
elapsed = (datetime.now() - start_time).total_seconds()
# Try to capture one last image for timeout case
try:
img_path = self.use_vision_acq_to_capture_and_save_latest_image(rename_to="timeout_final.png")
if save_result_image and img_path and os.path.exists(img_path):
result_image_path = self._save_result_image(
img_path,
result_image_name,
"TIMEOUT",
result_image_dir
)
except:
pass
result = {
'found': False,
'elapsed_time': elapsed,
'attempts': attempts,
'found_at': None,
'roi_coordinates': roi_coords,
'captured_text': last_captured_text,
'result_type': 'timeout',
'matched_pass_texts': [],
'matched_fail_texts': [],
'result_image_path': result_image_path,
'verification_history': verification_history
}
robot_print_info("=" * 80)
robot_print_error(f" TIMEOUT: Pass condition not met within timeout")
robot_print_info(f" Expected PASS texts: {pass_texts}")
robot_print_info(f" Match requirement: {'ALL' if match_all else 'ANY'}")
robot_print_info(f" Time elapsed: {elapsed:.1f} seconds ({timeout_minutes} min timeout)")
robot_print_info(f" Total attempts: {attempts}")
robot_print_info(f" Last extracted text: '{last_captured_text[:100]}'")
if result_image_path:
robot_print_info(f" Result image saved: {result_image_path}")
robot_print_info("=" * 80)
return result
except Exception as exp:
robot_print_error(f"Overall error in verify_text_in_roi_continuously: {exp}", print_in_report=True)
return {
'found': False,
'elapsed_time': (datetime.now() - start_time).total_seconds(),
'attempts': attempts,
'found_at': None,
'roi_coordinates': roi_coords,
'captured_text': None,
'result_type': 'error',
'matched_pass_texts': [],
'matched_fail_texts': [],
'result_image_path': None,
'error': str(exp),
'verification_history': verification_history
}
# finally:
# # Close vision acquisition app
# try:
# self.close_vision_acq_app()
# except:
# pass
def _save_result_image(self, source_img_path: str, custom_name: str, status: str, save_dir: str) -> str:
"""
Helper method to save result image with custom naming.
Args:
source_img_path (str): Path to the source image
custom_name (str): Custom name for the result image (without extension)
status (str): Status string ('PASS', 'FAIL', 'TIMEOUT')
save_dir (str): Directory to save the result image
Returns:
str: Path to the saved result image
"""
try:
# Generate filename
if custom_name:
# Use custom name: custom_name_STATUS.png
filename = f"{custom_name}_{status}.png"
else:
# Use timestamp if no custom name provided
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
filename = f"result_{timestamp}_{status}.png"
# Full path for result image
result_path = os.path.join(save_dir, filename)
# Copy the source image to result location
import shutil
shutil.copy2(source_img_path, result_path)
robot_print_info(f"Result image saved: {result_path}")
return result_path
except Exception as e:
robot_print_error(f"Failed to save result image: {e}")
return None
def verify_text_in_predefined_board_roi(
self,
board_name: str,
target_text: Union[str, List[str]],
fail_text: Union[str, List[str], None] = None,
timeout_minutes: int = 25,
check_interval_seconds: float = 2.0,
case_sensitive: bool = False,
match_all: bool = False,
save_frames: bool = False,
save_result_image: bool = True,
result_image_name: str = None,
result_image_dir: str = None
) -> dict:
"""
Convenience method to verify text in one of the predefined board ROIs.
Supports both single text and list of texts for pass/fail conditions.
Args:
board_name (str): One of 'CID_BOARD', 'PID_BOARD', or 'DID_BOARD'
target_text (str or List[str]): The text(s) to search for (PASS case)
Can be a single string or list of strings
fail_text (str or List[str] or None): The text(s) that indicate failure (FAIL case)
If any found, returns immediately with found=False
timeout_minutes (int): Maximum time to search in minutes (default: 5)
check_interval_seconds (float): Time between checks (default: 2.0)
case_sensitive (bool): Whether text matching should be case-sensitive (default: False)
match_all (bool): For target_text list - True: all texts must be found,
False: any one text is enough (default: False)
save_frames (bool): Whether to save captured frames during verification (default: False)
save_result_image (bool): Whether to save the final result image (default: True)
result_image_name (str): Custom name for result image (without extension)
Final format: {result_image_name}_{STATUS}.png
If None, uses board_name as prefix
result_image_dir (str): Directory to save result images
If None, uses current working directory
Returns:
dict: {
'found': bool,
'elapsed_time': float,
'attempts': int,
'found_at': str,
'roi_coordinates': RoiTuple,
'captured_text': str,
'result_type': str ('pass', 'fail', 'timeout'),
'matched_pass_texts': List[str],
'matched_fail_texts': List[str],
'result_image_path': str,
'verification_history': list,
'board_name': str
}
"""
valid_boards = ['CID_BOARD', 'PID_BOARD', 'DID_BOARD']
if board_name not in valid_boards:
robot_print_error(
f"Invalid board name: '{board_name}'. "
f"Must be one of: {', '.join(valid_boards)}"
)
return {
'found': False,
'elapsed_time': 0,
'attempts': 0,
'found_at': None,
'roi_coordinates': None,
'captured_text': None,
'result_type': 'error',
'matched_pass_texts': [],
'matched_fail_texts': [],
'result_image_path': None,
'board_name': board_name,
'error': f'Invalid board name: {board_name}'
}
robot_print_info("=" * 80)
robot_print_info(f"Starting Text Verification for Board: {board_name}")
# Display pass texts
if isinstance(target_text, list):
robot_print_info(f"PASS text(s): {target_text}")
robot_print_info(f"Match mode: {'ALL texts required' if match_all else 'ANY text sufficient'}")
else:
robot_print_info(f"PASS text: '{target_text}'")
# Display fail texts
if fail_text:
if isinstance(fail_text, list):
robot_print_info(f"FAIL text(s): {fail_text}")
else:
robot_print_info(f"FAIL text: '{fail_text}'")
robot_print_info(f"Case sensitive: {case_sensitive}")
# If no custom result_image_name provided, use board_name as default
if result_image_name is None and save_result_image:
result_image_name = board_name
robot_print_info(f"Result image name: {result_image_name}_{{STATUS}}.png")
if result_image_dir:
robot_print_info(f"Result image directory: {result_image_dir}")
robot_print_info("=" * 80)
result = self.verify_text_in_roi_continuously(
target_text=target_text,
fail_text=fail_text,
timeout_minutes=timeout_minutes,
check_interval_seconds=check_interval_seconds,
case_sensitive=case_sensitive,
match_all=match_all,
save_frames=save_frames,
save_result_image=save_result_image,
result_image_name=result_image_name,
result_image_dir=result_image_dir,
roi_name=board_name
)
# Add board name to result for tracking
result['board_name'] = board_name
return result
def _capture_latest_image_for_reboot(
self,
output_dir,
sequence_number,
settle_time_seconds=0.0
):
"""
Capture the latest image from Vision Acquisition
and save it inside the current test-case iteration folder.
"""
from pathlib import Path
try:
# Request latest image from Vision Acquisition
capture_start = time.monotonic()
robot_print_info("Requesting latest image from Vision Acquisition..." )
self.vision_acq.copy_all_files()
copy_duration = time.monotonic() - capture_start
robot_print_info(
f"Vision Acquisition copy operation completed "
f"in {copy_duration:.2f} seconds.")
# Allow the acquisition buffer to settle if required
if settle_time_seconds > 0:
time.sleep(settle_time_seconds)
vision_frames_dir = self.config_manager.get_destination_folder()
if not os.path.isdir(vision_frames_dir):
robot_print_error(
f"Vision Acquisition destination not found: {vision_frames_dir}"
)
return None
supported_extensions = (".jpg", ".jpeg", ".png", ".bmp")
vision_frames = [
os.path.join(vision_frames_dir, filename)
for filename in os.listdir(vision_frames_dir)
if filename.lower().endswith(supported_extensions)
and os.path.isfile(os.path.join(vision_frames_dir, filename))
]
if not vision_frames:
robot_print_warning("No images found in Vision Acquisition buffer.")
return None
robot_print_info(f"Vision Acquisition source directory: {vision_frames_dir}")
robot_print_info(f"Available image files: {len(vision_frames)}")
# Extract Vision Acquisition timestamp from filename
def extract_timestamp(filepath):
filename = os.path.basename(filepath)
match = re.search(
r'(-?\d+-\d{2}d_\d{2}h_\d{2}m_\d{2}\.\d{3})',
str(filename)
)
return match.group(1) if match else ""
# Prefer acquisition timestamp; use file modification time as fallback
vision_frames.sort(
key=lambda filepath: (
bool(extract_timestamp(filepath)),
extract_timestamp(filepath),
os.path.getmtime(filepath)
)
)
latest_path = vision_frames[-1]
# Prepare destination directory
output_dir = Path(output_dir)
output_dir.mkdir(parents=True, exist_ok=True)
# Generate unique destination filename
timestamp_str = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
original_ext = os.path.splitext(latest_path)[1].lower()
destination_filename = (
f"reboot_image_{sequence_number:04d}_{timestamp_str}"
f"{original_ext}")
destination_path = output_dir / destination_filename
# Copy image
shutil.copy2(latest_path, destination_path)
robot_print_info( f"Reboot image saved: {destination_path}")
return str(destination_path)
except Exception as e:
robot_print_error(
f"Reboot image capture failed: {e}"
)
return None
def _reboot_image_capture_worker(
self,
stop_event,
interval_seconds,
output_dir,
settle_time_seconds,
capture_immediately
):
"""Background worker for periodic reboot image capture."""
sequence_number = 0
success_count = 0
failure_count = 0
next_capture_time = time.monotonic()
if not capture_immediately:
next_capture_time += interval_seconds
robot_print_info("=" * 60)
robot_print_info("REBOOT IMAGE CAPTURE WORKER STARTED")
robot_print_info(f"Output folder: {output_dir}")
robot_print_info(f"Capture interval: {interval_seconds} seconds")
robot_print_info("=" * 60)
while not stop_event.is_set():
remaining = next_capture_time - time.monotonic()
if remaining > 0:
if stop_event.wait(remaining):
break
if stop_event.is_set():
break
sequence_number += 1
capture_start = time.monotonic()
robot_print_info(
f"[CAPTURE {sequence_number}] Started."
)
try:
saved_path = self._capture_latest_image_for_reboot(
output_dir=output_dir,
sequence_number=sequence_number,
settle_time_seconds=settle_time_seconds
)
capture_duration = time.monotonic() - capture_start
if saved_path:
success_count += 1
robot_print_info(
f"[CAPTURE {sequence_number}] SUCCESS"
)
robot_print_info(
f"Saved image: {saved_path}"
)
else:
failure_count += 1
robot_print_error(
f"[CAPTURE {sequence_number}] FAILED - "
"No image was saved."
)
robot_print_info(
f"[CAPTURE {sequence_number}] "
f"Duration: {capture_duration:.2f} seconds"
)
except Exception as exp:
failure_count += 1
import traceback
robot_print_error(
f"[CAPTURE {sequence_number}] EXCEPTION: {exp}"
)
robot_print_error(traceback.format_exc())
# Schedule next capture. If the current capture took
# longer than the interval, start the next one immediately.
next_capture_time = max(
next_capture_time + interval_seconds,
time.monotonic()
)
robot_print_info("=" * 60)
robot_print_info("REBOOT IMAGE CAPTURE WORKER STOPPED")
robot_print_info(f"Total attempts : {sequence_number}")
robot_print_info(f"Successful : {success_count}")
robot_print_info(f"Failed : {failure_count}")
robot_print_info(f"Output folder : {output_dir}")
robot_print_info("=" * 60)
def start_reboot_image_capture(
self,
test_case_name,
iteration_number,
interval_seconds=20.0,
settle_time_seconds=0.0,
capture_immediately=True
):
"""
Start background image capture for a specific test case and iteration.
Folder structure:
reboot_images/
Test_Case_Name/
Iteration_001/
reboot_image_0001.png
reboot_image_0002.png
Args:
test_case_name: Test case name.
iteration_number: Current test iteration number.
interval_seconds: Time between captures.
settle_time_seconds: Optional buffer settling delay.
capture_immediately: Capture immediately after starting.
Returns:
True - Thread started successfully.
False - Thread could not be started.
"""
import threading
from pathlib import Path
try:
# Validate input parameters
if not test_case_name or not str(test_case_name).strip():
robot_print_error("Test case name cannot be empty.")
return False
if (
isinstance(iteration_number, bool)
or not isinstance(iteration_number, int)
or iteration_number < 1
):
robot_print_error("Iteration number must be a positive integer." )
return False
if interval_seconds <= 0:
robot_print_error("Capture interval must be greater than zero.")
return False
if settle_time_seconds < 0:
robot_print_error("Settle time cannot be negative.")
return False
# Prevent multiple capture threads
if not hasattr(self, "_reboot_capture_lock"):
self._reboot_capture_lock = threading.Lock()
with self._reboot_capture_lock:
existing_thread = getattr(self, "_reboot_capture_thread", None)
if existing_thread and existing_thread.is_alive():
robot_print_error("Reboot image capture is already running.")
return False
# Sanitize test case name for Windows-compatible folder naming
safe_test_case_name = re.sub(
r'[<>:"/\\|?*\x00-\x1f]',
"_",
str(test_case_name).strip()
).rstrip(" .")
if not safe_test_case_name:
robot_print_error("Invalid test case name after sanitization.")
return False
# Create folder structure
base_dir = (
Path(self.common_keywords.get_input_files_dir_path())
/ "reboot_images" )
test_case_dir = base_dir / safe_test_case_name
iteration_dir = (
test_case_dir
/ f"Iteration_{iteration_number:03d}")
# Do not mix images from previous execution
if iteration_dir.exists():
robot_print_error(
f"Iteration folder already exists: {iteration_dir}. "
f"Use a new iteration number or archive the existing folder."
)
return False
iteration_dir.mkdir(parents=True, exist_ok=False)
# Create stop event
stop_event = threading.Event()
# Create worker thread
capture_thread = threading.Thread(
target=self._reboot_image_capture_worker,
args=(
stop_event,
float(interval_seconds),
str(iteration_dir),
float(settle_time_seconds),
capture_immediately
),
name="RebootImageCaptureThread",
daemon=True
)
# Store thread references and session information
self._reboot_capture_stop_event = stop_event
self._reboot_capture_thread = capture_thread
self._reboot_capture_output_dir = str(iteration_dir)
robot_print_info("=" * 60)
robot_print_info("STARTING REBOOT IMAGE CAPTURE")
robot_print_info( f"Test Case : {safe_test_case_name}")
robot_print_info(f"Iteration : {iteration_number}")
robot_print_info( f"Interval : {interval_seconds} seconds")
robot_print_info( f"Output : {iteration_dir}")
robot_print_info("=" * 60)
capture_thread.start()
return True
except Exception as e:
robot_print_error(f"Unable to start reboot image capture: {e}")
return False
def stop_reboot_image_capture(self, join_timeout=35.0):
"""
Stop the background capture thread safely.
Waits for any current capture operation to finish.
Returns True only when the thread has terminated.
"""
import threading
try:
stop_event = getattr(self, "_reboot_capture_stop_event", None)
capture_thread = getattr(self, "_reboot_capture_thread", None)
output_dir = getattr(self, "_reboot_capture_output_dir", None)
if stop_event is None or capture_thread is None:
robot_print_warning(
"No reboot image capture session is active."
)
return True
if not capture_thread.is_alive():
robot_print_info("Reboot image capture thread is already stopped.")
return True
robot_print_info("Stopping reboot image capture...")
# Request graceful shutdown
stop_event.set()
# Do not join the current thread
if threading.current_thread() is capture_thread:
robot_print_warning( "Stop requested from capture thread itself.")
return False
# Wait for current capture operation to complete
capture_thread.join(timeout=join_timeout)
if capture_thread.is_alive():
robot_print_error(
"Reboot image capture thread has not terminated. "
"The current acquisition may still be running.")
return False
robot_print_info("=" * 60)
robot_print_info("REBOOT IMAGE CAPTURE STOPPED SUCCESSFULLY")
robot_print_info(f"Iteration images saved at: {output_dir}")
robot_print_info("=" * 60)
return True
except Exception as e:
robot_print_error( f"Error while stopping reboot image capture: {e}")
return False
# ******************** Reboot Validation ***************************
def get_reboot_validation_rois(self):
"""
Return the reference ROI coordinates.
Format: (x, y, width, height)
"""
return {
"CID_BOARD": (40, 327, 4024, 1377),
"PID_BOARD": (1766, 1607, 619, 81),
"DID_BOARD": (40, 327, 4024, 1377)
}
def classify_black_screen_roi(self, frame, roi_name, roi_coordinates, brightness_threshold=40, std_threshold=5):
"""
Detect whether a specified ROI is completely black.
BLACK condition:
Mean brightness < 40
Standard deviation < 5
Returns:
BLACK
NORMAL
INVALID
"""
x, y, width, height = roi_coordinates
image_height, image_width = frame.shape[:2]
# Validate ROI coordinates against image dimensions
if (
x < 0 or y < 0 or
width <= 0 or height <= 0 or
x + width > image_width or
y + height > image_height
):
robot_print_error(
f"{roi_name}: Invalid ROI coordinates. "
f"Image size={image_width}x{image_height}, "
f"ROI={roi_coordinates}"
)
return "INVALID"
# Extract ROI
roi = frame[y:y + height, x:x + width]
if roi.size == 0:
robot_print_error(f"{roi_name}: Empty ROI!")
return "INVALID"
# Convert ROI to grayscale
gray_roi = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
# Calculate brightness and uniformity
brightness = float(gray_roi.mean())
std = float(gray_roi.std())
robot_print_info(
f"{roi_name}: "
f"Brightness={brightness:.2f}, "
f"STD={std:.2f}"
)
# Black screen detection
if (
brightness < brightness_threshold
and std < std_threshold
):
return "BLACK"
return "NORMAL"
def validate_reboot_image(self, image_path, brightness_threshold=40, std_threshold=5):
"""
Validate CID, PID and DID ROIs in one image.
Returns:
{
"image": image name,
"status": "PASS" / "FAIL",
"roi_results": {...}
}
"""
image_path = Path(image_path)
frame = cv2.imread(str(image_path))
if frame is None:
robot_print_error(
f"Unable to read image: {image_path.name}"
)
return {
"image": image_path.name,
"status": "FAIL",
"roi_results": {
"IMAGE": "UNREADABLE"
}
}
rois = self.get_reboot_validation_rois()
roi_results = {}
robot_print_debug(
f"\nValidating image: {image_path.name}"
)
for roi_name, coordinates in rois.items():
category = self.classify_black_screen_roi(
frame=frame,
roi_name=roi_name,
roi_coordinates=coordinates,
brightness_threshold=brightness_threshold,
std_threshold=std_threshold
)
roi_results[roi_name] = category
if category == "BLACK":
robot_print_error(
f"BLACK SCREEN DETECTED: "
f"{image_path.name} - {roi_name}")
elif category == "INVALID":
robot_print_error(f"INVALID ROI: {image_path.name} - {roi_name}")
else:
robot_print_info(f"{roi_name}: NORMAL" )
# Fail if any ROI is black or invalid
image_status = (
"FAIL"
if any(
result in ("BLACK", "INVALID")
for result in roi_results.values()
)
else "PASS"
)
return {
"image": image_path.name,
"status": image_status,
"roi_results": roi_results
}
def validate_all_reboot_images(
self,
folder_path=None,
brightness_threshold=40,
std_threshold=5
):
"""
Validate all images inside reboot_images folder.
Returns:
True - No black screen detected in any valid image.
False - Black screen, invalid ROI or unreadable image found.
"""
# Resolve reboot_images folder
if folder_path is None:
folder_path = (
Path(self.common_keywords.get_input_files_dir_path())
/ "reboot_images")
else:
folder_path = Path(folder_path)
robot_print_info(f"\nStarting reboot image validation: {folder_path}")
# Check folder availability
if not folder_path.exists() or not folder_path.is_dir():
robot_print_error(f"Reboot images folder not found: {folder_path}")
return False
# Collect all supported image files
image_extensions = (".png", ".jpg", ".jpeg", ".bmp")
image_files = sorted(
[
path for path in folder_path.iterdir()
if path.is_file()
and path.suffix.lower() in image_extensions
],
key=lambda path: path.stat().st_mtime
)
if not image_files:
robot_print_error("No images available for reboot validation!")
return False
robot_print_info(f"Total images found: {len(image_files)}")
# Validation counters
total_pass = 0
total_fail = 0
black_detections = []
invalid_detections = []
roi_summary = {
"CID_BOARD": {"BLACK": 0, "NORMAL": 0, "INVALID": 0},
"PID_BOARD": {"BLACK": 0, "NORMAL": 0, "INVALID": 0},
"DID_BOARD": {"BLACK": 0, "NORMAL": 0, "INVALID": 0}
}
# Validate every image
for index, image_path in enumerate(image_files, start=1):
robot_print_debug(
f"\n{'=' * 60}\n"
f"Image {index}/{len(image_files)}: "
f"{image_path.name}\n"
f"{'=' * 60}"
)
result = self.validate_reboot_image(
image_path=image_path,
brightness_threshold=brightness_threshold,
std_threshold=std_threshold
)
if result["status"] == "PASS":
total_pass += 1
else:
total_fail += 1
for roi_name, category in result["roi_results"].items():
if roi_name not in roi_summary:
continue
roi_summary[roi_name][category] += 1
if category == "BLACK":
black_detections.append(
(image_path.name, roi_name))
elif category == "INVALID":
invalid_detections.append(
(image_path.name, roi_name))
# Final validation summary
robot_print_debug("\n" + "=" * 60)
robot_print_info("REBOOT IMAGE VALIDATION SUMMARY")
robot_print_debug("=" * 60)
robot_print_info(f"Total images : {len(image_files)}")
robot_print_info(f"PASS images : {total_pass}")
robot_print_info(f"FAIL images : {total_fail}")
robot_print_debug("\nROI-WISE SUMMARY")
for roi_name, counts in roi_summary.items():
robot_print_info(
f"{roi_name}: "
f"BLACK={counts['BLACK']}, "
f"NORMAL={counts['NORMAL']}, "
f"INVALID={counts['INVALID']}"
)
# Black screen failure details
if black_detections:
robot_print_error(
f"\nFAIL: BLACK screen detected "
f"{len(black_detections)} time(s)!")
for image_name, roi_name in black_detections[:20]:
robot_print_error(
f"Image: {image_name} | ROI: {roi_name}")
if len(black_detections) > 20:
robot_print_error(
f"... and {len(black_detections) - 20} "
f"more black detections")
# Invalid image/ROI details
if invalid_detections:
robot_print_error(
f"\nFAIL: {len(invalid_detections)} "
f"invalid ROI detection(s)!")
for image_name, roi_name in invalid_detections[:20]:
robot_print_error(f"Image: {image_name} | ROI: {roi_name}")
robot_print_debug("=" * 60)
# Final decision
if total_fail > 0:
robot_print_error(
"REBOOT VALIDATION FAILED: "
"Black screen or invalid image/ROI detected!")
return False
robot_print_info(
"REBOOT VALIDATION PASSED: "
"No black screen detected in any ROI!")
return True
def start_flashing_image_capture(
self,
test_case_name,
iteration_number,
capture_type, # "upgrade" or "downgrade"
interval_seconds=120.0,
settle_time_seconds=0.0,
capture_immediately=True
):
import threading
from pathlib import Path
import re
try:
if capture_type.lower() not in ["upgrade", "downgrade"]:
robot_print_error(
"capture_type must be 'upgrade' or 'downgrade'"
)
return False
# sanitize test case name
safe_test_case_name = re.sub(
r'[<>:"/\\|?*\x00-\x1f]',
"_",
str(test_case_name).strip()
).rstrip(" .")
base_dir = (
Path(self.common_keywords.get_report_path())
/ "Flashing_images"
)
test_case_dir = base_dir / safe_test_case_name
folder_name = (
f"{capture_type.capitalize()}_Iter_{iteration_number:03d}"
)
capture_dir = test_case_dir / folder_name
capture_dir.mkdir(parents=True, exist_ok=True)
stop_event = threading.Event()
capture_thread = threading.Thread(
target=self._reboot_image_capture_worker,
args=(
stop_event,
float(interval_seconds), # 120 sec
str(capture_dir),
float(settle_time_seconds),
capture_immediately
),
name=f"{capture_type}_capture_thread",
daemon=True
)
self._reboot_capture_stop_event = stop_event
self._reboot_capture_thread = capture_thread
robot_print_info(
f"Starting {capture_type} image capture."
)
robot_print_info(
f"Images will be stored in: {capture_dir}"
)
capture_thread.start()
return True
except Exception as e:
robot_print_error(
f"Unable to start reboot image capture: {e}"
)
return False
def stop_flashing_image_capture(self, join_timeout=35.0):
"""
Stop flashing image capture thread safely.
"""
import threading
try:
join_timeout = float(join_timeout)
stop_event = getattr(
self,
"_reboot_capture_stop_event",
None
)
capture_thread = getattr(
self,
"_reboot_capture_thread",
None
)
if stop_event is None or capture_thread is None:
robot_print_warning(
"No flashing image capture session is active."
)
return True
if not capture_thread.is_alive():
robot_print_info(
"Flashing image capture thread is already stopped."
)
return True
robot_print_info(
"Stopping flashing image capture..."
)
# Request graceful shutdown
stop_event.set()
# Prevent self join
if threading.current_thread() is capture_thread:
robot_print_warning(
"Stop requested from capture thread itself."
)
return False
capture_thread.join(timeout=join_timeout)
if capture_thread.is_alive():
robot_print_error(
"Flashing image capture thread failed to terminate."
)
return False
robot_print_info("=" * 60)
robot_print_info(
"FLASHING IMAGE CAPTURE STOPPED SUCCESSFULLY"
)
robot_print_info("=" * 60)
# Cleanup
self._reboot_capture_stop_event = None
self._reboot_capture_thread = None
return True
except Exception as e:
robot_print_error(
f"Error while stopping flashing image capture: {e}"
)
return False
def validate_skyline_and_software_version(self, image_path):
"""
Reads text from the image using EasyOCR, extracts Skyline OS Version
and Software Version, and validates that their last character matches.
Args:
image_path (str): Path to the image.
Returns:
dict
"""
try:
if not os.path.exists(image_path):
robot_print_error(f"Image not found: {image_path}")
return {
"status": False,
"message": f"Image not found: {image_path}",
"skyline_version": None,
"software_version": None
}
# OCR
ocr_results = self.ocr_reader.readtext(image_path)
detected_texts = [text.strip() for (_, text, _) in ocr_results]
robot_print_info(f"Detected OCR Text: {' | '.join(detected_texts)}")
skyline_version = None
software_version = None
for idx, text in enumerate(detected_texts):
if "Skyline OS Version" in text:
if idx + 1 < len(detected_texts):
skyline_version = detected_texts[idx + 1]
elif "Software Version" in text:
if idx + 1 < len(detected_texts):
software_version = detected_texts[idx + 1]
# Fallback extraction in case OCR combines label and value
if skyline_version is None:
for text in detected_texts:
if "Skyline" in text:
match = re.search(
r"Skyline\s*OS\s*Version[:\s]*([A-Z0-9]+)",
text,
re.IGNORECASE
)
if match:
skyline_version = match.group(1)
break
if software_version is None:
for text in detected_texts:
if "Software" in text:
match = re.search(
r"Software\s*Version[:\s]*([A-Z0-9_]+)",
text,
re.IGNORECASE
)
if match:
software_version = match.group(1)
break
robot_print_info(f"Skyline OS Version : {skyline_version}")
robot_print_info(f"Software Version : {software_version}")
if not skyline_version:
return {
"status": False,
"message": "Failed to extract Skyline OS Version",
"skyline_version": None,
"software_version": software_version
}
if not software_version:
return {
"status": False,
"message": "Failed to extract Software Version",
"skyline_version": skyline_version,
"software_version": None
}
skyline_last_char = skyline_version[-1].upper()
software_last_char = software_version[-1].upper()
if skyline_last_char == software_last_char:
msg = (
f"PASS - Skyline OS Version ({skyline_version}) and "
f"Software Version ({software_version}) "
f"have matching last character '{skyline_last_char}'"
)
robot_print_info(msg)
return {
"status": True,
"message": msg,
"skyline_version": skyline_version,
"software_version": software_version
}
msg = (
f"FAIL - Skyline OS Version ({skyline_version}) ends with "
f"'{skyline_last_char}' but Software Version "
f"({software_version}) ends with '{software_last_char}'"
)
robot_print_error(msg)
return {
"status": False,
"message": msg,
"skyline_version": skyline_version,
"software_version": software_version
}
except Exception as ex:
robot_print_error(
f"Error validating Skyline and Software Version: {str(ex)}"
)
return {
"status": False,
"message": str(ex),
"skyline_version": None,
"software_version": None
}
if __name__ == '__main__':
a = VisionComparisonProvider()
a.get_rois_from_vision_frame('test')
a.validate_all_reboot_images()