File size: 9,234 Bytes
cb92c6a
8153b52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb92c6a
8153b52
 
cb92c6a
8153b52
 
 
cb92c6a
 
8153b52
cb92c6a
8153b52
cb92c6a
8153b52
cb92c6a
 
 
8153b52
 
 
 
 
 
 
 
 
 
 
 
180275e
cb92c6a
8153b52
cb92c6a
8153b52
 
 
 
 
 
 
 
 
 
 
 
 
 
cb92c6a
 
180275e
8153b52
 
180275e
8153b52
 
 
 
cb92c6a
8153b52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
180275e
 
8153b52
 
 
 
 
 
180275e
8153b52
 
 
 
 
 
cb92c6a
8153b52
 
 
 
cb92c6a
8153b52
 
 
 
 
 
 
180275e
 
8153b52
 
 
 
 
 
 
 
 
 
 
 
180275e
8153b52
 
 
 
 
 
 
 
 
 
cb92c6a
8153b52
 
 
 
 
 
 
cb92c6a
8153b52
 
 
 
 
 
 
 
 
 
180275e
8153b52
 
180275e
8153b52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
180275e
8153b52
 
 
 
 
 
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
"""
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": "<text>", "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": "<path or message>", "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": "<text>", "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),
            }