import os import sys import json import sqlite3 import argparse import subprocess import logging from pathlib import Path import numpy as np from PIL import Image, ImageFilter # Reconfigure stdout/stderr to utf-8 to avoid encoding issues on Windows sys.stdout.reconfigure(encoding='utf-8') sys.stderr.reconfigure(encoding='utf-8') # Logging setup logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') logger = logging.getLogger("quality_gate_broll") def validate_image_asset(img_path, min_width=500, min_height=300): """ Perform deep validation of a B-roll image file. Checks: file existence, PIL verification, resolution, aspect ratio, blankness, and watermarks. Returns: (bool, str) -> (is_valid, reason) """ path = Path(img_path) if not path.exists(): return False, "File does not exist" # Check minimum file size (e.g. 5KB) try: size = path.stat().st_size if size < 5120: return False, f"File size is too small ({size} bytes). Likely a corrupt download or placeholder." except Exception as e: return False, f"Failed to get file stats: {e}" # 1. PIL opening and integrity check try: with Image.open(path) as img: img.verify() # verify integrity of the file container except Exception as e: return False, f"Image container is corrupted or invalid: {e}" # Re-open because verify() makes the file handle unusable try: with Image.open(path) as img: w, h = img.size # 2. Resolution check if w < min_width or h < min_height: return False, f"Resolution too low ({w}x{h}). Minimum required is {min_width}x{min_height}." # 3. Aspect Ratio check aspect = w / h # Normal landscape should be around 1.33 to 1.78. # Reject vertical portrait (aspect < 0.75) and extreme panoramas (aspect > 2.5) if aspect < 0.75: return False, f"Asset is vertical / portrait (aspect ratio: {aspect:.2f}). 16:9 crop will lose context." if aspect > 2.5: return False, f"Asset is too wide / panoramic (aspect ratio: {aspect:.2f}). 16:9 crop will look extremely stretched or cropped." # 4. Blank screen / Solid color check # Convert to grayscale to simplify calculation gray_img = img.convert("L") arr = np.array(gray_img, dtype=np.float32) std_dev = np.std(arr) # A standard deviation < 5.0 indicates almost zero contrast (solid color / blank / broken download) if std_dev < 5.0: return False, f"Blank or solid color image detected (standard deviation: {std_dev:.2f})." # 5. Watermark / logo detection detected = detect_watermarks(img_path) if detected: return False, f"Watermark or logo pattern detected in regions: {detected}." except Exception as e: return False, f"Unexpected error during visual analysis: {e}" return True, "Pass" def detect_watermarks(img_path): """ Scan the corners and central-right/bottom-center of the image and return a list of regions that contain watermarks. """ path = Path(img_path) if not path.exists(): return [] # Check if the filename contains stock/news keywords for adaptive thresholding path_lower = str(path).lower() is_stock_source = any(x in path_lower for x in ["getty", "alamy", "stock", "shutter", "anadolu", "reuters", "exclusive", "refinery"]) try: with Image.open(path) as img: w, h = img.size gray_img = img.convert("L") arr = np.array(gray_img, dtype=np.float32) diff_x = np.abs(arr[:, 1:] - arr[:, :-1]) diff_y = np.abs(arr[1:, :] - arr[:-1, :]) edges = np.zeros_like(arr) edges[:, :-1] += diff_x edges[:-1, :] += diff_y cw = int(w * 0.15) ch = int(h * 0.15) cw = max(cw, 10) ch = max(ch, 10) regions = { "top_left": (0, 0, cw, ch), "top_right": (w-cw, 0, w, ch), "bottom_left": (0, h-ch, cw, h), "bottom_right": (w-cw, h-ch, w, h), "center_right": (int(w * 0.55), int(h * 0.45), int(w * 0.98), int(h * 0.80)), "bottom_center": (int(w * 0.20), int(h * 0.82), int(w * 0.80), h), "center": (int(w * 0.30), int(h * 0.30), int(w * 0.70), int(h * 0.70)) } detected = [] for name, (x1, y1, x2, y2) in regions.items(): region = edges[y1:y2, x1:x2] if region.size == 0: continue mean_edge = np.mean(region) max_edge = np.max(region) # Corner heuristics (normally low texture, so strict threshold) if name in ["top_left", "top_right", "bottom_left", "bottom_right"]: if mean_edge > 15.0 and max_edge > 150.0: detected.append(name) # Central/Bottom heuristics (higher natural texture, adaptive check to avoid false positives) else: if is_stock_source: high_contrast_pixels = np.sum(region > 120.0) # Detect even if the mean edge is diluted in a large region, as long as strong local edges exist if (mean_edge > 5.0 and max_edge > 80.0 and high_contrast_pixels > 15) or (high_contrast_pixels > 40): detected.append(name) else: if mean_edge > 20.0 and max_edge > 200.0: high_contrast_pixels = np.sum(region > 200.0) if high_contrast_pixels > 30: detected.append(name) return detected except Exception as e: logger.error(f"Error checking watermarks for {img_path}: {e}") return [] def generate_watermark_mask(img_path, output_mask_path, detected_corners=None): """ Generate a binary mask where detected watermark pixels are white (255) and dilated. """ path = Path(img_path) if not path.exists(): return False if detected_corners is None: detected_corners = detect_watermarks(img_path) if not detected_corners: # Create empty mask if no corners detected try: with Image.open(path) as img: mask = Image.new("L", img.size, color=0) mask.save(output_mask_path, "JPEG") return True except Exception as e: logger.error(f"Failed to create empty mask: {e}") return False try: with Image.open(path) as img: w, h = img.size gray_img = img.convert("L") arr = np.array(gray_img, dtype=np.float32) # Recompute edges to find watermark pixels diff_x = np.abs(arr[:, 1:] - arr[:, :-1]) diff_y = np.abs(arr[1:, :] - arr[:-1, :]) edges = np.zeros_like(arr) edges[:, :-1] += diff_x edges[:-1, :] += diff_y # Create a base black mask mask_arr = np.zeros((h, w), dtype=np.uint8) cw = int(w * 0.15) ch = int(h * 0.15) cw = max(cw, 10) ch = max(ch, 10) regions = { "top_left": (0, 0, cw, ch), "top_right": (w-cw, 0, w, ch), "bottom_left": (0, h-ch, cw, h), "bottom_right": (w-cw, h-ch, w, h), "center_right": (int(w * 0.55), int(h * 0.45), int(w * 0.98), int(h * 0.80)), "bottom_center": (int(w * 0.20), int(h * 0.82), int(w * 0.80), h), "center": (int(w * 0.30), int(h * 0.30), int(w * 0.70), int(h * 0.70)) } for name in detected_corners: if name not in regions: continue x1, y1, x2, y2 = regions[name] # In the region, pixels with edge strength > 15 are likely watermark strokes region_edges = edges[y1:y2, x1:x2] mask_region = np.zeros_like(region_edges, dtype=np.uint8) mask_region[region_edges > 15.0] = 255 mask_arr[y1:y2, x1:x2] = mask_region mask_img = Image.fromarray(mask_arr) # Dilate the mask using PIL's MaxFilter to cover surrounding pixels of the watermark text/logo dilated_mask = mask_img.filter(ImageFilter.MaxFilter(size=9)) # Save mask dilated_mask.save(output_mask_path, "JPEG") return True except Exception as e: logger.error(f"Error generating mask for {img_path}: {e}") return False def remove_watermark_with_lama(img_path, output_path=None): """ Detect, mask, and inpaint watermark/logo out of the image using LaMa. Then re-validate the result. Returns: (bool, str) -> (success, reason) """ path = Path(img_path) if not path.exists(): return False, "File does not exist" if output_path is None: output_path = img_path detected_corners = detect_watermarks(img_path) if not detected_corners: return True, "No watermark detected" logger.info(f"Watermark detected in corners {detected_corners} of {path.name}. Initiating removal...") # Paths for temporary mask and temporary output temp_mask_path = path.parent / f".temp_mask_{path.stem}.jpg" temp_out_path = path.parent / f".temp_out_{path.stem}.jpg" try: # 1. Generate mask if not generate_watermark_mask(path, temp_mask_path, detected_corners): return False, "Failed to generate watermark mask" # 2. Run LaMa inpainting lama_script = r"C:\Roaming\.agents\skills\lama-inpainting\lama_inpaint.py" if not os.path.exists(lama_script): return False, f"LaMa script not found at {lama_script}" cmd = [ sys.executable, lama_script, "--image", str(path), "--mask", str(temp_mask_path), "--output", str(temp_out_path), "--device", "cpu" ] logger.info(f"Running LaMa inpainting: {' '.join(cmd)}") res = subprocess.run(cmd, capture_output=True, text=True, timeout=90) if res.returncode != 0: return False, f"LaMa inpainting script failed: {res.stderr.strip()}" if not temp_out_path.exists(): return False, "LaMa script returned 0 but output file was not created" # 3. Re-validate the output image ok, reason = validate_image_asset(temp_out_path) if not ok: # If it failed because of watermark again, it means the removal failed or was incomplete return False, f"Watermark removal validation failed: {reason}" # 4. Overwrite/Save to target destination out_path = Path(output_path) if out_path.exists(): out_path.unlink() temp_out_path.rename(out_path) logger.info(f"Watermark successfully removed and verified for {path.name}") return True, "Pass" except subprocess.TimeoutExpired: return False, "LaMa inpainting execution timed out" except Exception as e: logger.error(f"Unexpected error during watermark removal: {e}") return False, f"Unexpected error during removal: {e}" finally: # Cleanup temp files if temp_mask_path.exists(): temp_mask_path.unlink(missing_ok=True) if temp_out_path.exists(): temp_out_path.unlink(missing_ok=True) def validate_video_asset(video_path): """ Perform validation of a B-roll video file (Ken-Burns clip). Checks: file existence, size, and container integrity using ffprobe. Returns: (bool, str) -> (is_valid, reason) """ path = Path(video_path) if not path.exists(): return False, "File does not exist" try: size = path.stat().st_size if size < 10240: # 10KB minimum return False, f"File size is too small ({size} bytes). Likely a failed render." except Exception as e: return False, f"Failed to get file stats: {e}" # Use ffprobe to verify video integrity ffprobe = os.environ.get("VIDEO_AGENT_FFPROBE", "ffprobe") cmd = [ ffprobe, "-v", "error", "-show_entries", "format=duration,size:stream=codec_type", "-of", "json", str(path) ] try: res = subprocess.run(cmd, capture_output=True, text=True, timeout=10) if res.returncode != 0: return False, f"ffprobe container validation failed: {res.stderr.strip()}" data = json.loads(res.stdout) # Check duration duration_str = data.get("format", {}).get("duration") if not duration_str: return False, "No duration found in video container metadata" duration = float(duration_str) if duration <= 0: return False, f"Invalid video duration: {duration}s" # Check for video stream streams = data.get("streams", []) has_video_stream = any(s.get("codec_type") == "video" for s in streams) if not has_video_stream: return False, "No video stream found in the container" except subprocess.TimeoutExpired: return False, "ffprobe container validation timed out" except Exception as e: return False, f"Failed to validate video container via ffprobe: {e}" return True, "Pass" def scan_and_cleanup_broll_database(db_path, dry_run=False): """ Scan the local SQLite DB, validate all registered B-roll video and source image assets, delete failed ones, and clean up database records. """ if not os.path.exists(db_path): logger.error(f"Database {db_path} does not exist.") return {"error": "DB not found"} conn = sqlite3.connect(db_path) cursor = conn.cursor() try: cursor.execute("SELECT id, title, query, image_url, local_path FROM broll_assets") rows = cursor.fetchall() except Exception as e: logger.error(f"Failed to query database: {e}") conn.close() return {"error": str(e)} logger.info(f"Scanning {len(rows)} registered B-roll records...") scanned = 0 passed = 0 failed_video = 0 failed_image = 0 missing_files = 0 deleted_records = [] # We will track which images are associated with which videos to locate the source images. # The source images are typically in C:\ComfyUI\Broll\images with a name derived from URL hash and title. # The database local_path points to the video (.mp4). for row_id, title, query, url, local_path_str in rows: scanned += 1 if not local_path_str: logger.warning(f"Record ID {row_id} has empty local_path. Removing record.") deleted_records.append(row_id) missing_files += 1 continue video_path = Path(local_path_str) # Locate corresponding source image in ComfyUI\Broll\images # The filename of the video is [hash]_[title].mp4 and the image is [hash]_[title].jpg video_name = video_path.name img_name = video_name.replace(".mp4", ".jpg") img_path = Path(r"C:\ComfyUI\Broll\images") / img_name # 1. Check file existence if not video_path.exists(): logger.warning(f"Video file missing: {video_path}. Removing record.") deleted_records.append(row_id) missing_files += 1 # Clean up image if it exists if img_path.exists() and not dry_run: img_path.unlink() continue # 2. Validate Video vid_ok, vid_reason = validate_video_asset(video_path) if not vid_ok: logger.warning(f"Video {video_name} failed Quality Gate: {vid_reason}") failed_video += 1 deleted_records.append(row_id) if not dry_run: video_path.unlink(missing_ok=True) if img_path.exists(): img_path.unlink(missing_ok=True) continue # 3. Validate Source Image (if exists) if img_path.exists(): img_ok, img_reason = validate_image_asset(img_path) if not img_ok: # If failed because of watermark, try to remove it if "Watermark" in img_reason: logger.info(f"Source image {img_name} has watermark. Attempting automatic removal...") if not dry_run: removed, remove_reason = remove_watermark_with_lama(img_path) if removed: # Re-generate video because the old video has the watermark logger.info(f"Watermark removed from image. Regenerating video clip {video_name}...") try: from collect_broll_agent import generate_ken_burns_clip # Delete old video video_path.unlink(missing_ok=True) if generate_ken_burns_clip(img_path, video_path): logger.info(f"Video regenerated successfully: {video_name}") img_ok = True else: logger.error(f"Failed to regenerate video {video_name} from restored image") except Exception as ex: logger.error(f"Error during video regeneration: {ex}") else: logger.warning(f"Watermark removal failed for {img_name}: {remove_reason}") if not img_ok: logger.warning(f"Source image {img_name} failed Quality Gate: {img_reason}") failed_image += 1 deleted_records.append(row_id) if not dry_run: video_path.unlink(missing_ok=True) img_path.unlink(missing_ok=True) continue else: # If the source image is missing but the video exists and is valid, we let it pass # because the video is already compiled and good to go. pass passed += 1 # Apply database deletions if deleted_records and not dry_run: logger.info(f"Removing {len(deleted_records)} failed/missing records from database...") try: # SQLite supports up to 999 variables, chunk if needed for i in range(0, len(deleted_records), 500): chunk = deleted_records[i:i+500] cursor.execute(f"DELETE FROM broll_assets WHERE id IN ({','.join('?' for _ in chunk)})", chunk) conn.commit() except Exception as e: logger.error(f"Failed to delete records from DB: {e}") conn.close() summary = { "scanned": scanned, "passed": passed, "failed_video": failed_video, "failed_image": failed_image, "missing_files": missing_files, "deleted_records_count": len(deleted_records) } logger.info(f"Cleanup finished. Summary: {summary}") return summary def main(): parser = argparse.ArgumentParser(description="B-roll Quality Gate Scanner & Cleaner") parser.add_argument("--db-path", type=str, default=r"C:\ComfyUI\Articles\broll_assets.db", help="Path to SQLite DB") parser.add_argument("--cleanup", action="store_true", help="Perform database scanning and cleanup.") parser.add_argument("--dry-run", action="store_true", help="Scan only, do not delete files or DB records.") parser.add_argument("--image", type=str, help="Validate a single image file.") parser.add_argument("--remove-watermark", action="store_true", help="Remove watermark from single image (must specify --image)") parser.add_argument("--video", type=str, help="Validate a single video file.") args = parser.parse_args() if args.image: if args.remove_watermark: ok, reason = remove_watermark_with_lama(args.image) print(f"Watermark removal for {args.image}: {'PASS' if ok else 'FAIL'}") if not ok: print(f"Reason: {reason}") sys.exit(0 if ok else 1) else: ok, reason = validate_image_asset(args.image) print(f"Image validation for {args.image}: {'PASS' if ok else 'FAIL'}") if not ok: print(f"Reason: {reason}") sys.exit(0 if ok else 1) if args.video: ok, reason = validate_video_asset(args.video) print(f"Video validation for {args.video}: {'PASS' if ok else 'FAIL'}") if not ok: print(f"Reason: {reason}") sys.exit(0 if ok else 1) if args.cleanup: summary = scan_and_cleanup_broll_database(args.db_path, dry_run=args.dry_run) print("\n=== Cleanup Scan Report ===") print(json.dumps(summary, indent=4)) sys.exit(0) parser.print_help() if __name__ == "__main__": main()