""" Vision – OCR, screenshot, and image/text-to-text processing. Capabilities: - OCR: image → text - Describe: image → caption/description (if a VLM is available) - Screenshot: capture local or (in future) remote screenshots - Text-to-text: generic text transformation (e.g., summarization), if a local/installed NLP model is available. IMPORTANT: - This module is runtime-only. The LLM never calls it directly. - Orchestrator invokes these methods via the "Vision" tool with a "mode" parameter (ocr, describe, screenshot, text). - No mock or stub behavior: all functions either call real libraries/tools or return explicit error messages. """ import logging import os import subprocess from typing import Dict, Any, Optional from PIL import Image import pytesseract try: # Optional VLM for image description from transformers import pipeline VLM_AVAILABLE = True except ImportError: VLM_AVAILABLE = False pipeline = None # type: ignore try: # Optional text-to-text model for local summarization/paraphrase, etc. from transformers import AutoTokenizer, AutoModelForSeq2SeqLM NLP_AVAILABLE = True except ImportError: NLP_AVAILABLE = False AutoTokenizer = None # type: ignore AutoModelForSeq2SeqLM = None # type: ignore logger = logging.getLogger(__name__) class VisionProcessor: def __init__( self, vlm_model_name: str = "microsoft/Florence-2-large", vlm_device: str = "cpu", nlp_model_name: Optional[str] = None, nlp_device: str = "cpu", ) -> None: """ :param vlm_model_name: HF model id for image-to-text pipeline. :param vlm_device: device for VLM ("cpu", "cuda:0", etc.). :param nlp_model_name: optional HF model id for text-to-text. :param nlp_device: device for text-to-text model. """ # Image-to-text VLM self.vlm = None if VLM_AVAILABLE: try: self.vlm = pipeline("image-to-text", model=vlm_model_name, device=vlm_device) logger.info(f"VisionProcessor: Loaded VLM '{vlm_model_name}' on {vlm_device}") except Exception as e: logger.warning(f"VisionProcessor: VLM init failed: {e}") self.vlm = None else: logger.info("VisionProcessor: transformers not installed; VLM not available") # Text-to-text NLP self.nlp_tokenizer = None self.nlp_model = None if nlp_model_name and NLP_AVAILABLE: try: self.nlp_tokenizer = AutoTokenizer.from_pretrained(nlp_model_name) self.nlp_model = AutoModelForSeq2SeqLM.from_pretrained(nlp_model_name) self.nlp_model.to(nlp_device) logger.info( f"VisionProcessor: Loaded text2text model '{nlp_model_name}' on {nlp_device}" ) except Exception as e: logger.warning(f"VisionProcessor: text2text model init failed: {e}") self.nlp_tokenizer = None self.nlp_model = None elif nlp_model_name and not NLP_AVAILABLE: logger.info( "VisionProcessor: transformers not installed; text2text not available" ) # ------------------------------------------------------------------------- # Public methods – all return structured dicts # ------------------------------------------------------------------------- def ocr(self, image_path: str, lang: str = "eng") -> Dict[str, Any]: """ OCR: image → text. :param image_path: path to image file. :param lang: language code for Tesseract (e.g., "eng"). :return: { "status": "...", "result": "", "stderr": "..." } """ try: img = Image.open(image_path) text = pytesseract.image_to_string(img, lang=lang) return { "status": "success", "result": text, "stderr": "", } except Exception as e: logger.error(f"VisionProcessor.ocr failed: {e}") return { "status": "error", "result": "", "stderr": str(e), } def describe(self, image_path: str) -> Dict[str, Any]: """ Image description: image → caption/description via VLM if available. """ if self.vlm is None: msg = "VLM not available; install transformers/torch or configure model." logger.warning(f"VisionProcessor.describe: {msg}") return { "status": "error", "result": "", "stderr": msg, } try: result = self.vlm(image_path) if not result: return { "status": "error", "result": "", "stderr": "No description generated.", } text = result[0].get("generated_text", "") or result[0].get("caption", "") return { "status": "success", "result": text, "stderr": "", } except Exception as e: logger.error(f"VisionProcessor.describe error: {e}") return { "status": "error", "result": "", "stderr": str(e), } def screenshot(self, save_path: str, remote_target: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: """ Capture a screenshot. - If remote_target is None: use local 'scrot' (Linux) or OS-specific tools. - If remote_target is provided: for now, returns a clear "not implemented" message. You can extend this to call OS-specific screenshot commands on the remote host via TerminalAdapter. :return: { "status": "...", "result": "", "stderr": "..." } """ if remote_target: # Placeholder hook: you can implement remote screenshots via SSH/WinRM msg = f"Remote screenshot not implemented for {remote_target.get('ip')}" logger.warning(f"VisionProcessor.screenshot: {msg}") return { "status": "error", "result": "", "stderr": msg, } # Local screenshot – basic Linux 'scrot' example try: # Ensure directory exists os.makedirs(os.path.dirname(save_path) or ".", exist_ok=True) subprocess.run(["scrot", save_path], check=True, timeout=10) return { "status": "success", "result": f"Screenshot saved to {save_path}", "stderr": "", } except Exception as e: logger.error(f"VisionProcessor.screenshot failed: {e}") return { "status": "error", "result": "", "stderr": str(e), } def text(self, input_text: str, task: str = "summarize", max_new_tokens: int = 256) -> Dict[str, Any]: """ Generic text-to-text transformation using a local model if available. Examples: - Summarize long OCR output. - Normalize noisy text for easier LLM consumption. :param input_text: text to transform. :param task: logical task hint ("summarize", "paraphrase", etc.) – you can encode this as a prefix or special token for your chosen model, if needed. :param max_new_tokens: generation limit. :return: { "status": "...", "result": "", "stderr": "..." } """ if self.nlp_model is None or self.nlp_tokenizer is None: msg = "Text2text model not available; configure nlp_model_name or install transformers." logger.warning(f"VisionProcessor.text: {msg}") return { "status": "error", "result": "", "stderr": msg, } try: # For simple usage, you can use task as a prefix if task: prompt = f"{task}: {input_text}" else: prompt = input_text tokens = self.nlp_tokenizer( prompt, return_tensors="pt", truncation=True, max_length=1024, ) tokens = {k: v.to(self.nlp_model.device) for k, v in tokens.items()} outputs = self.nlp_model.generate( **tokens, max_new_tokens=max_new_tokens, do_sample=False, ) text = self.nlp_tokenizer.decode( outputs[0], skip_special_tokens=True, ) return { "status": "success", "result": text, "stderr": "", } except Exception as e: logger.error(f"VisionProcessor.text error: {e}") return { "status": "error", "result": "", "stderr": str(e), }