robotframework-doctestlibrary 0.30.0.dev1__py3-none-any.whl → 0.32.0.dev1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- DocTest/Ai/__init__.py +454 -454
- DocTest/Ai/prompts.py +24 -24
- DocTest/Ai/renderers.py +53 -53
- DocTest/Ai/responses.py +30 -30
- DocTest/DocumentRepresentation.py +1357 -1357
- DocTest/Downloader.py +47 -47
- DocTest/HeaderFooterDetector.py +230 -0
- DocTest/IgnoreAreaManager.py +129 -129
- DocTest/Ocr.py +242 -242
- DocTest/PdfStructureComparator.py +677 -322
- DocTest/PdfStructureModels.py +366 -249
- DocTest/PdfTest.py +1359 -1023
- DocTest/PrintJob.py +5 -5
- DocTest/PrintJobTests.py +458 -458
- DocTest/StructureReportBuilder.py +558 -0
- DocTest/TextNormalization.py +97 -2
- DocTest/VisualTest.py +3789 -3728
- DocTest/__init__.py +473 -473
- DocTest/config.py +9 -9
- DocTest/llm/__init__.py +19 -19
- DocTest/llm/client.py +274 -254
- DocTest/llm/config.py +231 -231
- DocTest/llm/exceptions.py +10 -10
- DocTest/llm/prompts.py +42 -42
- DocTest/llm/types.py +27 -27
- {robotframework_doctestlibrary-0.30.0.dev1.dist-info → robotframework_doctestlibrary-0.32.0.dev1.dist-info}/METADATA +142 -39
- robotframework_doctestlibrary-0.32.0.dev1.dist-info/RECORD +29 -0
- {robotframework_doctestlibrary-0.30.0.dev1.dist-info → robotframework_doctestlibrary-0.32.0.dev1.dist-info}/WHEEL +1 -1
- {robotframework_doctestlibrary-0.30.0.dev1.dist-info → robotframework_doctestlibrary-0.32.0.dev1.dist-info/licenses}/LICENSE +200 -200
- robotframework_doctestlibrary-0.30.0.dev1.dist-info/RECORD +0 -27
DocTest/Ai/__init__.py
CHANGED
|
@@ -1,454 +1,454 @@
|
|
|
1
|
-
from __future__ import annotations
|
|
2
|
-
|
|
3
|
-
import re
|
|
4
|
-
import textwrap
|
|
5
|
-
from typing import Dict, Iterable, List, Optional, Sequence
|
|
6
|
-
|
|
7
|
-
import cv2
|
|
8
|
-
from robot.api.deco import keyword, library
|
|
9
|
-
|
|
10
|
-
from DocTest.DocumentRepresentation import DocumentRepresentation
|
|
11
|
-
from DocTest.Downloader import download_file_from_url, is_url
|
|
12
|
-
from DocTest.config import DEFAULT_DPI
|
|
13
|
-
from DocTest.llm import load_llm_settings
|
|
14
|
-
from DocTest.llm.client import create_binary_content, run_structured_prompt
|
|
15
|
-
from DocTest.llm.types import LLMDecision
|
|
16
|
-
|
|
17
|
-
from DocTest.Ai.prompts import (
|
|
18
|
-
AREA_EXTRACTION_PROMPT,
|
|
19
|
-
CHAT_SYSTEM_PROMPT,
|
|
20
|
-
COUNT_PROMPT,
|
|
21
|
-
OBJECT_DETECTION_PROMPT,
|
|
22
|
-
TEXT_EXTRACTION_PROMPT,
|
|
23
|
-
)
|
|
24
|
-
from DocTest.Ai.renderers import load_document_pages, prepare_image_attachments
|
|
25
|
-
from DocTest.Ai.responses import LLMChatResponse, LLMCountResponse, LLMExtractionResult
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
def _coerce_override(value) -> Optional[str]:
|
|
29
|
-
if value is None:
|
|
30
|
-
return None
|
|
31
|
-
if isinstance(value, (list, tuple)):
|
|
32
|
-
return ",".join(str(item) for item in value if item is not None)
|
|
33
|
-
return str(value)
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
def _collect_overrides(**kwargs) -> Dict[str, Optional[str]]:
|
|
37
|
-
mapping: Dict[str, Optional[str]] = {}
|
|
38
|
-
for key, value in kwargs.items():
|
|
39
|
-
if value is not None:
|
|
40
|
-
mapping[key] = _coerce_override(value)
|
|
41
|
-
return mapping
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
def _ensure_local(path_or_url: str) -> str:
|
|
45
|
-
if is_url(path_or_url):
|
|
46
|
-
return download_file_from_url(path_or_url)
|
|
47
|
-
return path_or_url
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
def _summaries_from_text(pages: Iterable[Dict], char_limit: int = 1200) -> List[str]:
|
|
51
|
-
summaries: List[str] = []
|
|
52
|
-
for page in pages:
|
|
53
|
-
text = (page.get("text") or "").strip()
|
|
54
|
-
if not text:
|
|
55
|
-
continue
|
|
56
|
-
snippet = textwrap.shorten(text, width=char_limit, placeholder=" ...")
|
|
57
|
-
summaries.append(f"Page {page['number']} text:\n{snippet}")
|
|
58
|
-
return summaries
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
@library
|
|
62
|
-
class Ai:
|
|
63
|
-
"""Optional LLM-assisted keywords backed by Large Language Models.
|
|
64
|
-
|
|
65
|
-
This library is distributed as part of :mod:`robotframework-doctestlibrary`.
|
|
66
|
-
The keywords exposed here require the optional ``[ai]`` extra to be installed,
|
|
67
|
-
appropriate API credentials to be configured (for example via ``.env``), and
|
|
68
|
-
access to a compatible multimodal LLM.
|
|
69
|
-
|
|
70
|
-
Keywords provided:
|
|
71
|
-
- ``Get Text With LLM`` – extract text from whole documents or images.
|
|
72
|
-
- ``Get Text From Area With LLM`` – extract text from a defined region.
|
|
73
|
-
- ``Chat With Document`` – run question/answer conversations over one or
|
|
74
|
-
more attachments.
|
|
75
|
-
- ``Image Should Contain`` – assert whether specified objects are present.
|
|
76
|
-
- ``Get Item Count From Image`` – count occurrences of described objects.
|
|
77
|
-
|
|
78
|
-
See the project documentation for configuration guidance and examples.
|
|
79
|
-
"""
|
|
80
|
-
|
|
81
|
-
def __init__(self, dpi: int = DEFAULT_DPI):
|
|
82
|
-
"""
|
|
83
|
-
Initialize the Ai library.
|
|
84
|
-
|
|
85
|
-
| =Arguments= | =Description= |
|
|
86
|
-
| ``dpi`` | DPI to use when rasterising PDFs or images prior to sending them to the LLM. Default is 200. |
|
|
87
|
-
|
|
88
|
-
The constructor accepts no other positional arguments; LLM settings are
|
|
89
|
-
controlled via environment variables and per-keyword overrides.
|
|
90
|
-
"""
|
|
91
|
-
self.dpi = dpi
|
|
92
|
-
|
|
93
|
-
# ---------------- Text Extraction ---------------- #
|
|
94
|
-
|
|
95
|
-
@keyword(name="Get Text With LLM", tags=("ai",))
|
|
96
|
-
def get_text_with_llm(
|
|
97
|
-
self,
|
|
98
|
-
document: str,
|
|
99
|
-
prompt: Optional[str] = None,
|
|
100
|
-
include_pdf_text: bool = True,
|
|
101
|
-
model: Optional[str] = None,
|
|
102
|
-
provider: Optional[str] = None,
|
|
103
|
-
temperature: Optional[float] = None,
|
|
104
|
-
max_output_tokens: Optional[int] = None,
|
|
105
|
-
request_timeout: Optional[float] = None,
|
|
106
|
-
max_pages: Optional[int] = None,
|
|
107
|
-
) -> str:
|
|
108
|
-
"""Extract textual content from a document using an LLM.
|
|
109
|
-
|
|
110
|
-
| =Arguments= | =Description= |
|
|
111
|
-
| ``document`` | Path or URL to the source file (image or PDF). |
|
|
112
|
-
| ``prompt`` | Optional instructions for the LLM. Default is ``None`` which uses the built-in transcription prompt. |
|
|
113
|
-
| ``include_pdf_text`` | When ``${True}``, embed direct PDF text alongside rendered pages. Default ``${True}``. |
|
|
114
|
-
| ``model`` | Override the configured LLM model name. Default ``None`` uses environment defaults. |
|
|
115
|
-
| ``provider`` | Override the provider identifier (for example ``openai`` or ``azure``). Default ``None``. |
|
|
116
|
-
| ``temperature`` | Sampling temperature for the model. Default ``None`` (provider default). |
|
|
117
|
-
| ``max_output_tokens`` | Hard limit for generated tokens. Default ``None``. |
|
|
118
|
-
| ``request_timeout`` | Timeout in seconds for the API call. Default ``None``. |
|
|
119
|
-
| ``max_pages`` | Maximum number of pages to send to the LLM. Default ``None`` (all pages). |
|
|
120
|
-
|
|
121
|
-
Returns the extracted text as a string.
|
|
122
|
-
|
|
123
|
-
Raises ``AssertionError`` when the document cannot be loaded or produces no renderable pages.
|
|
124
|
-
|
|
125
|
-
Example:
|
|
126
|
-
| ${text}= Get Text With LLM testdata/invoice.pdf prompt=Transcribe all text exactly
|
|
127
|
-
| Should Contain ${text} INVOICE
|
|
128
|
-
"""
|
|
129
|
-
|
|
130
|
-
overrides = _collect_overrides(
|
|
131
|
-
llm_enabled="true",
|
|
132
|
-
llm_models=model,
|
|
133
|
-
llm_provider=provider,
|
|
134
|
-
llm_temperature=temperature,
|
|
135
|
-
llm_max_output_tokens=max_output_tokens,
|
|
136
|
-
llm_request_timeout=request_timeout,
|
|
137
|
-
)
|
|
138
|
-
|
|
139
|
-
settings = load_llm_settings(overrides)
|
|
140
|
-
_, pages = _load_pages_or_fail(document, self.dpi, max_pages=max_pages)
|
|
141
|
-
|
|
142
|
-
attachments = [
|
|
143
|
-
create_binary_content(payload, "image/png")
|
|
144
|
-
for _, payload in prepare_image_attachments(pages)
|
|
145
|
-
]
|
|
146
|
-
extra = _summaries_from_text(pages) if include_pdf_text else []
|
|
147
|
-
|
|
148
|
-
base_prompt = prompt.strip() if prompt else TEXT_EXTRACTION_PROMPT
|
|
149
|
-
result = run_structured_prompt(
|
|
150
|
-
settings=settings,
|
|
151
|
-
purpose="vision",
|
|
152
|
-
prompt=base_prompt,
|
|
153
|
-
attachments=attachments,
|
|
154
|
-
extra_messages=extra,
|
|
155
|
-
output_type=LLMExtractionResult,
|
|
156
|
-
)
|
|
157
|
-
if not isinstance(result, LLMExtractionResult):
|
|
158
|
-
raise AssertionError("LLM returned an unexpected response for text extraction.")
|
|
159
|
-
return result.text
|
|
160
|
-
|
|
161
|
-
@keyword(name="Get Text From Area With LLM", tags=("ai",))
|
|
162
|
-
def get_text_from_area_with_llm(
|
|
163
|
-
self,
|
|
164
|
-
document: str,
|
|
165
|
-
area: Dict,
|
|
166
|
-
prompt: Optional[str] = None,
|
|
167
|
-
model: Optional[str] = None,
|
|
168
|
-
provider: Optional[str] = None,
|
|
169
|
-
temperature: Optional[float] = None,
|
|
170
|
-
request_timeout: Optional[float] = None,
|
|
171
|
-
) -> str:
|
|
172
|
-
"""Extract text from a specified area using an LLM.
|
|
173
|
-
|
|
174
|
-
| =Arguments= | =Description= |
|
|
175
|
-
| ``document`` | Path or URL to the source file (image or PDF). |
|
|
176
|
-
| ``area`` | Dictionary describing the region. Keys: ``x``, ``y``, ``width``, ``height`` and optional ``page`` / ``unit``. |
|
|
177
|
-
| ``prompt`` | Optional instructions for the LLM. Default ``None`` uses a generic area-transcription prompt. |
|
|
178
|
-
| ``model`` | Override the configured model name. Default ``None``. |
|
|
179
|
-
| ``provider`` | Override the provider identifier. Default ``None``. |
|
|
180
|
-
| ``temperature`` | Sampling temperature. Default ``None``. |
|
|
181
|
-
| ``request_timeout`` | Timeout in seconds for the API call. Default ``None``. |
|
|
182
|
-
|
|
183
|
-
Returns the extracted text as a string.
|
|
184
|
-
|
|
185
|
-
Raises ``AssertionError`` when the document cannot be loaded or the area is invalid.
|
|
186
|
-
|
|
187
|
-
Example:
|
|
188
|
-
| &{area}= Create Dictionary x=0 y=0 width=400 height=200 page=1
|
|
189
|
-
| ${text}= Get Text From Area With LLM testdata/invoice.pdf ${area}
|
|
190
|
-
| Should Contain ${text} Invoice
|
|
191
|
-
"""
|
|
192
|
-
|
|
193
|
-
overrides = _collect_overrides(
|
|
194
|
-
llm_enabled="true",
|
|
195
|
-
llm_models=model,
|
|
196
|
-
llm_provider=provider,
|
|
197
|
-
llm_temperature=temperature,
|
|
198
|
-
llm_request_timeout=request_timeout,
|
|
199
|
-
)
|
|
200
|
-
settings = load_llm_settings(overrides)
|
|
201
|
-
|
|
202
|
-
doc_path, pages = _load_pages_or_fail(document, self.dpi)
|
|
203
|
-
|
|
204
|
-
target_page = area.get("page", "all")
|
|
205
|
-
unit = area.get("unit", "px")
|
|
206
|
-
attachments: List = []
|
|
207
|
-
area_text_snippets: List[str] = []
|
|
208
|
-
|
|
209
|
-
doc_representation = DocumentRepresentation(doc_path, dpi=self.dpi)
|
|
210
|
-
page_list = list(doc_representation.pages)
|
|
211
|
-
|
|
212
|
-
for idx, (page_meta, page_obj) in enumerate(zip(pages, page_list), 1):
|
|
213
|
-
if target_page != "all" and int(target_page) != idx:
|
|
214
|
-
continue
|
|
215
|
-
try:
|
|
216
|
-
x, y, w, h = page_obj._convert_to_pixels(area, unit)
|
|
217
|
-
except Exception as exc:
|
|
218
|
-
raise AssertionError(f"Invalid area specification: {exc}") from exc
|
|
219
|
-
crop = page_meta["image"][y : y + h, x : x + w]
|
|
220
|
-
if crop.size == 0:
|
|
221
|
-
continue
|
|
222
|
-
attachments.append(create_binary_content(cv2.imencode(".png", crop)[1].tobytes(), "image/png"))
|
|
223
|
-
snippet = page_obj._get_text_from_area(area)
|
|
224
|
-
if snippet:
|
|
225
|
-
area_text_snippets.append(f"Page {idx} area text:\n{snippet}")
|
|
226
|
-
|
|
227
|
-
if not attachments:
|
|
228
|
-
raise AssertionError("Specified area produced no image data.")
|
|
229
|
-
|
|
230
|
-
base_prompt = prompt.strip() if prompt else AREA_EXTRACTION_PROMPT
|
|
231
|
-
result = run_structured_prompt(
|
|
232
|
-
settings=settings,
|
|
233
|
-
purpose="vision",
|
|
234
|
-
prompt=base_prompt,
|
|
235
|
-
attachments=attachments,
|
|
236
|
-
extra_messages=area_text_snippets or None,
|
|
237
|
-
output_type=LLMExtractionResult,
|
|
238
|
-
)
|
|
239
|
-
if not isinstance(result, LLMExtractionResult):
|
|
240
|
-
raise AssertionError("LLM returned an unexpected response for area extraction.")
|
|
241
|
-
return result.text
|
|
242
|
-
|
|
243
|
-
# ---------------- Chat ---------------- #
|
|
244
|
-
|
|
245
|
-
@keyword(name="Chat With Document", tags=("ai",))
|
|
246
|
-
def chat_with_document(
|
|
247
|
-
self,
|
|
248
|
-
prompt: str,
|
|
249
|
-
documents,
|
|
250
|
-
include_pdf_text: bool = True,
|
|
251
|
-
model: Optional[str] = None,
|
|
252
|
-
provider: Optional[str] = None,
|
|
253
|
-
temperature: Optional[float] = None,
|
|
254
|
-
max_output_tokens: Optional[int] = None,
|
|
255
|
-
request_timeout: Optional[float] = None,
|
|
256
|
-
max_pages: Optional[int] = None,
|
|
257
|
-
) -> str:
|
|
258
|
-
"""Chat with one or more documents using an LLM.
|
|
259
|
-
|
|
260
|
-
| =Arguments= | =Description= |
|
|
261
|
-
| ``prompt`` | User question or instruction passed to the LLM. |
|
|
262
|
-
| ``documents`` | Path/URL or list of paths/URLs to include in the conversation. |
|
|
263
|
-
| ``include_pdf_text`` | When ``${True}``, include direct PDF text in the prompt. Default ``${True}``. |
|
|
264
|
-
| ``model`` | Override the configured model name. Default ``None``. |
|
|
265
|
-
| ``provider`` | Override the provider identifier. Default ``None``. |
|
|
266
|
-
| ``temperature`` | Sampling temperature. Default ``None``. |
|
|
267
|
-
| ``max_output_tokens`` | Maximum number of tokens the model may produce. Default ``None``. |
|
|
268
|
-
| ``request_timeout`` | Timeout in seconds for the API call. Default ``None``. |
|
|
269
|
-
| ``max_pages`` | Limit the number of pages per document. Default ``None``. |
|
|
270
|
-
|
|
271
|
-
Returns the assistant's textual response.
|
|
272
|
-
|
|
273
|
-
Raises ``AssertionError`` when any document cannot be read or rendered.
|
|
274
|
-
|
|
275
|
-
Example:
|
|
276
|
-
| ${answer}= Chat With Document prompt=Summarise the document total. documents=testdata/invoice.pdf
|
|
277
|
-
| Should Contain ${answer} EUR
|
|
278
|
-
"""
|
|
279
|
-
|
|
280
|
-
if not documents:
|
|
281
|
-
raise ValueError("No documents supplied.")
|
|
282
|
-
if isinstance(documents, str):
|
|
283
|
-
doc_list = [documents]
|
|
284
|
-
else:
|
|
285
|
-
doc_list = list(documents)
|
|
286
|
-
|
|
287
|
-
overrides = _collect_overrides(
|
|
288
|
-
llm_enabled="true",
|
|
289
|
-
llm_models=model,
|
|
290
|
-
llm_provider=provider,
|
|
291
|
-
llm_temperature=temperature,
|
|
292
|
-
llm_max_output_tokens=max_output_tokens,
|
|
293
|
-
llm_request_timeout=request_timeout,
|
|
294
|
-
)
|
|
295
|
-
settings = load_llm_settings(overrides)
|
|
296
|
-
|
|
297
|
-
attachments: List = []
|
|
298
|
-
extra_messages: List[str] = [prompt]
|
|
299
|
-
|
|
300
|
-
for doc in doc_list:
|
|
301
|
-
_, pages = _load_pages_or_fail(doc, self.dpi, max_pages=max_pages)
|
|
302
|
-
for _, payload in prepare_image_attachments(pages):
|
|
303
|
-
attachments.append(create_binary_content(payload, "image/png"))
|
|
304
|
-
if include_pdf_text:
|
|
305
|
-
extra_messages.extend(_summaries_from_text(pages))
|
|
306
|
-
|
|
307
|
-
result = run_structured_prompt(
|
|
308
|
-
settings=settings,
|
|
309
|
-
purpose="vision",
|
|
310
|
-
prompt=CHAT_SYSTEM_PROMPT,
|
|
311
|
-
attachments=attachments,
|
|
312
|
-
extra_messages=extra_messages,
|
|
313
|
-
output_type=LLMChatResponse,
|
|
314
|
-
)
|
|
315
|
-
if not isinstance(result, LLMChatResponse):
|
|
316
|
-
raise AssertionError("LLM returned an unexpected chat response.")
|
|
317
|
-
return result.response
|
|
318
|
-
|
|
319
|
-
# ---------------- Detection & Counting ---------------- #
|
|
320
|
-
|
|
321
|
-
@keyword(name="Image Should Contain", tags=("ai",))
|
|
322
|
-
def image_should_contain(
|
|
323
|
-
self,
|
|
324
|
-
document: str,
|
|
325
|
-
expected: str,
|
|
326
|
-
prompt: Optional[str] = None,
|
|
327
|
-
model: Optional[str] = None,
|
|
328
|
-
provider: Optional[str] = None,
|
|
329
|
-
temperature: Optional[float] = None,
|
|
330
|
-
request_timeout: Optional[float] = None,
|
|
331
|
-
):
|
|
332
|
-
"""Assert that a document contains the expected visual content.
|
|
333
|
-
|
|
334
|
-
| =Arguments= | =Description= |
|
|
335
|
-
| ``document`` | Path or URL to the source file. |
|
|
336
|
-
| ``expected`` | Description of the object or concept that must be present. |
|
|
337
|
-
| ``prompt`` | Optional detailed instructions for the LLM. Default ``None`` uses the built-in detector prompt. |
|
|
338
|
-
| ``model`` | Override the configured model name. Default ``None``. |
|
|
339
|
-
| ``provider`` | Override the provider identifier. Default ``None``. |
|
|
340
|
-
| ``temperature`` | Sampling temperature. Default ``None``. |
|
|
341
|
-
| ``request_timeout`` | Timeout in seconds for the API call. Default ``None``. |
|
|
342
|
-
|
|
343
|
-
Raises ``AssertionError`` when the document cannot be read or when the expected content is not detected.
|
|
344
|
-
|
|
345
|
-
Example:
|
|
346
|
-
| Image Should Contain testdata/invoice.pdf Invoice header with company logo
|
|
347
|
-
"""
|
|
348
|
-
|
|
349
|
-
overrides = _collect_overrides(
|
|
350
|
-
llm_enabled="true",
|
|
351
|
-
llm_models=model,
|
|
352
|
-
llm_provider=provider,
|
|
353
|
-
llm_temperature=temperature,
|
|
354
|
-
llm_request_timeout=request_timeout,
|
|
355
|
-
)
|
|
356
|
-
settings = load_llm_settings(overrides)
|
|
357
|
-
|
|
358
|
-
_, pages = _load_pages_or_fail(document, self.dpi)
|
|
359
|
-
attachments = [
|
|
360
|
-
create_binary_content(payload, "image/png")
|
|
361
|
-
for _, payload in prepare_image_attachments(pages)
|
|
362
|
-
]
|
|
363
|
-
base_prompt = prompt.strip() if prompt else OBJECT_DETECTION_PROMPT
|
|
364
|
-
combined_prompt = f"{base_prompt}\nRequired objects: {expected}"
|
|
365
|
-
|
|
366
|
-
decision = run_structured_prompt(
|
|
367
|
-
settings=settings,
|
|
368
|
-
purpose="vision",
|
|
369
|
-
prompt=combined_prompt,
|
|
370
|
-
attachments=attachments,
|
|
371
|
-
output_type=LLMDecision,
|
|
372
|
-
)
|
|
373
|
-
if not isinstance(decision, LLMDecision):
|
|
374
|
-
raise AssertionError(f"LLM returned an unexpected response while checking '{expected}'.")
|
|
375
|
-
if decision.decision == decision.decision.APPROVE:
|
|
376
|
-
found_text = any(
|
|
377
|
-
expected.lower() in (page.get("text") or "").lower()
|
|
378
|
-
for page in pages
|
|
379
|
-
)
|
|
380
|
-
if found_text:
|
|
381
|
-
return
|
|
382
|
-
print("LLM approved but keyword could not verify the expected content in document text; treating as failure.")
|
|
383
|
-
raise AssertionError(f"Expected object '{expected}' not found in '{document}'.")
|
|
384
|
-
if decision.reason:
|
|
385
|
-
print(f"LLM reason: {decision.reason}")
|
|
386
|
-
raise AssertionError(f"Expected object '{expected}' not found in '{document}'.")
|
|
387
|
-
|
|
388
|
-
@keyword(name="Get Item Count From Image", tags=("ai",))
|
|
389
|
-
def get_item_count_from_image(
|
|
390
|
-
self,
|
|
391
|
-
document: str,
|
|
392
|
-
item_description: str,
|
|
393
|
-
prompt: Optional[str] = None,
|
|
394
|
-
model: Optional[str] = None,
|
|
395
|
-
provider: Optional[str] = None,
|
|
396
|
-
temperature: Optional[float] = None,
|
|
397
|
-
request_timeout: Optional[float] = None,
|
|
398
|
-
) -> int:
|
|
399
|
-
"""Count items in an image or document using an LLM.
|
|
400
|
-
|
|
401
|
-
| =Arguments= | =Description= |
|
|
402
|
-
| ``document`` | Path or URL to the source image/PDF. |
|
|
403
|
-
| ``item_description`` | Natural-language description of the item to count. |
|
|
404
|
-
| ``prompt`` | Optional custom instructions for the LLM. Default ``None`` uses a structured counting prompt. |
|
|
405
|
-
| ``model`` | Override the configured model name. Default ``None``. |
|
|
406
|
-
| ``provider`` | Override the provider identifier. Default ``None``. |
|
|
407
|
-
| ``temperature`` | Sampling temperature. Default ``None``. |
|
|
408
|
-
| ``request_timeout`` | Timeout in seconds for the API call. Default ``None``. |
|
|
409
|
-
|
|
410
|
-
Returns the counted integer (``0`` when no candidate is found).
|
|
411
|
-
|
|
412
|
-
Raises ``AssertionError`` when the document cannot be read.
|
|
413
|
-
|
|
414
|
-
Example:
|
|
415
|
-
| ${count}= Get Item Count From Image testdata/invoice.pdf item_description=number of tables
|
|
416
|
-
| Should Be True ${count} >= 1
|
|
417
|
-
"""
|
|
418
|
-
|
|
419
|
-
overrides = _collect_overrides(
|
|
420
|
-
llm_enabled="true",
|
|
421
|
-
llm_models=model,
|
|
422
|
-
llm_provider=provider,
|
|
423
|
-
llm_temperature=temperature,
|
|
424
|
-
llm_request_timeout=request_timeout,
|
|
425
|
-
)
|
|
426
|
-
settings = load_llm_settings(overrides)
|
|
427
|
-
|
|
428
|
-
_, pages = _load_pages_or_fail(document, self.dpi)
|
|
429
|
-
attachments = [
|
|
430
|
-
create_binary_content(payload, "image/png")
|
|
431
|
-
for _, payload in prepare_image_attachments(pages)
|
|
432
|
-
]
|
|
433
|
-
base_prompt = prompt.strip() if prompt else COUNT_PROMPT
|
|
434
|
-
combined_prompt = f"{base_prompt}\nItem to count: {item_description}"
|
|
435
|
-
|
|
436
|
-
result = run_structured_prompt(
|
|
437
|
-
settings=settings,
|
|
438
|
-
purpose="vision",
|
|
439
|
-
prompt=combined_prompt,
|
|
440
|
-
attachments=attachments,
|
|
441
|
-
output_type=LLMCountResponse,
|
|
442
|
-
)
|
|
443
|
-
if not isinstance(result, LLMCountResponse):
|
|
444
|
-
raise AssertionError("LLM returned an unexpected response for item count.")
|
|
445
|
-
return int(result.count)
|
|
446
|
-
def _load_pages_or_fail(document: str, dpi: int, max_pages: Optional[int] = None):
|
|
447
|
-
path = _ensure_local(document)
|
|
448
|
-
try:
|
|
449
|
-
pages = load_document_pages(path, dpi=dpi, max_pages=max_pages)
|
|
450
|
-
except Exception as exc:
|
|
451
|
-
raise AssertionError(f"Unable to load document '{document}': {exc}") from exc
|
|
452
|
-
if not pages:
|
|
453
|
-
raise AssertionError(f"Document '{document}' produced no renderable pages.")
|
|
454
|
-
return path, pages
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
import textwrap
|
|
5
|
+
from typing import Dict, Iterable, List, Optional, Sequence
|
|
6
|
+
|
|
7
|
+
import cv2
|
|
8
|
+
from robot.api.deco import keyword, library
|
|
9
|
+
|
|
10
|
+
from DocTest.DocumentRepresentation import DocumentRepresentation
|
|
11
|
+
from DocTest.Downloader import download_file_from_url, is_url
|
|
12
|
+
from DocTest.config import DEFAULT_DPI
|
|
13
|
+
from DocTest.llm import load_llm_settings
|
|
14
|
+
from DocTest.llm.client import create_binary_content, run_structured_prompt
|
|
15
|
+
from DocTest.llm.types import LLMDecision
|
|
16
|
+
|
|
17
|
+
from DocTest.Ai.prompts import (
|
|
18
|
+
AREA_EXTRACTION_PROMPT,
|
|
19
|
+
CHAT_SYSTEM_PROMPT,
|
|
20
|
+
COUNT_PROMPT,
|
|
21
|
+
OBJECT_DETECTION_PROMPT,
|
|
22
|
+
TEXT_EXTRACTION_PROMPT,
|
|
23
|
+
)
|
|
24
|
+
from DocTest.Ai.renderers import load_document_pages, prepare_image_attachments
|
|
25
|
+
from DocTest.Ai.responses import LLMChatResponse, LLMCountResponse, LLMExtractionResult
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _coerce_override(value) -> Optional[str]:
|
|
29
|
+
if value is None:
|
|
30
|
+
return None
|
|
31
|
+
if isinstance(value, (list, tuple)):
|
|
32
|
+
return ",".join(str(item) for item in value if item is not None)
|
|
33
|
+
return str(value)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _collect_overrides(**kwargs) -> Dict[str, Optional[str]]:
|
|
37
|
+
mapping: Dict[str, Optional[str]] = {}
|
|
38
|
+
for key, value in kwargs.items():
|
|
39
|
+
if value is not None:
|
|
40
|
+
mapping[key] = _coerce_override(value)
|
|
41
|
+
return mapping
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _ensure_local(path_or_url: str) -> str:
|
|
45
|
+
if is_url(path_or_url):
|
|
46
|
+
return download_file_from_url(path_or_url)
|
|
47
|
+
return path_or_url
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _summaries_from_text(pages: Iterable[Dict], char_limit: int = 1200) -> List[str]:
|
|
51
|
+
summaries: List[str] = []
|
|
52
|
+
for page in pages:
|
|
53
|
+
text = (page.get("text") or "").strip()
|
|
54
|
+
if not text:
|
|
55
|
+
continue
|
|
56
|
+
snippet = textwrap.shorten(text, width=char_limit, placeholder=" ...")
|
|
57
|
+
summaries.append(f"Page {page['number']} text:\n{snippet}")
|
|
58
|
+
return summaries
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@library
|
|
62
|
+
class Ai:
|
|
63
|
+
"""Optional LLM-assisted keywords backed by Large Language Models.
|
|
64
|
+
|
|
65
|
+
This library is distributed as part of :mod:`robotframework-doctestlibrary`.
|
|
66
|
+
The keywords exposed here require the optional ``[ai]`` extra to be installed,
|
|
67
|
+
appropriate API credentials to be configured (for example via ``.env``), and
|
|
68
|
+
access to a compatible multimodal LLM.
|
|
69
|
+
|
|
70
|
+
Keywords provided:
|
|
71
|
+
- ``Get Text With LLM`` – extract text from whole documents or images.
|
|
72
|
+
- ``Get Text From Area With LLM`` – extract text from a defined region.
|
|
73
|
+
- ``Chat With Document`` – run question/answer conversations over one or
|
|
74
|
+
more attachments.
|
|
75
|
+
- ``Image Should Contain`` – assert whether specified objects are present.
|
|
76
|
+
- ``Get Item Count From Image`` – count occurrences of described objects.
|
|
77
|
+
|
|
78
|
+
See the project documentation for configuration guidance and examples.
|
|
79
|
+
"""
|
|
80
|
+
|
|
81
|
+
def __init__(self, dpi: int = DEFAULT_DPI):
|
|
82
|
+
"""
|
|
83
|
+
Initialize the Ai library.
|
|
84
|
+
|
|
85
|
+
| =Arguments= | =Description= |
|
|
86
|
+
| ``dpi`` | DPI to use when rasterising PDFs or images prior to sending them to the LLM. Default is 200. |
|
|
87
|
+
|
|
88
|
+
The constructor accepts no other positional arguments; LLM settings are
|
|
89
|
+
controlled via environment variables and per-keyword overrides.
|
|
90
|
+
"""
|
|
91
|
+
self.dpi = dpi
|
|
92
|
+
|
|
93
|
+
# ---------------- Text Extraction ---------------- #
|
|
94
|
+
|
|
95
|
+
@keyword(name="Get Text With LLM", tags=("ai",))
|
|
96
|
+
def get_text_with_llm(
|
|
97
|
+
self,
|
|
98
|
+
document: str,
|
|
99
|
+
prompt: Optional[str] = None,
|
|
100
|
+
include_pdf_text: bool = True,
|
|
101
|
+
model: Optional[str] = None,
|
|
102
|
+
provider: Optional[str] = None,
|
|
103
|
+
temperature: Optional[float] = None,
|
|
104
|
+
max_output_tokens: Optional[int] = None,
|
|
105
|
+
request_timeout: Optional[float] = None,
|
|
106
|
+
max_pages: Optional[int] = None,
|
|
107
|
+
) -> str:
|
|
108
|
+
"""Extract textual content from a document using an LLM.
|
|
109
|
+
|
|
110
|
+
| =Arguments= | =Description= |
|
|
111
|
+
| ``document`` | Path or URL to the source file (image or PDF). |
|
|
112
|
+
| ``prompt`` | Optional instructions for the LLM. Default is ``None`` which uses the built-in transcription prompt. |
|
|
113
|
+
| ``include_pdf_text`` | When ``${True}``, embed direct PDF text alongside rendered pages. Default ``${True}``. |
|
|
114
|
+
| ``model`` | Override the configured LLM model name. Default ``None`` uses environment defaults. |
|
|
115
|
+
| ``provider`` | Override the provider identifier (for example ``openai`` or ``azure``). Default ``None``. |
|
|
116
|
+
| ``temperature`` | Sampling temperature for the model. Default ``None`` (provider default). |
|
|
117
|
+
| ``max_output_tokens`` | Hard limit for generated tokens. Default ``None``. |
|
|
118
|
+
| ``request_timeout`` | Timeout in seconds for the API call. Default ``None``. |
|
|
119
|
+
| ``max_pages`` | Maximum number of pages to send to the LLM. Default ``None`` (all pages). |
|
|
120
|
+
|
|
121
|
+
Returns the extracted text as a string.
|
|
122
|
+
|
|
123
|
+
Raises ``AssertionError`` when the document cannot be loaded or produces no renderable pages.
|
|
124
|
+
|
|
125
|
+
Example:
|
|
126
|
+
| ${text}= Get Text With LLM testdata/invoice.pdf prompt=Transcribe all text exactly
|
|
127
|
+
| Should Contain ${text} INVOICE
|
|
128
|
+
"""
|
|
129
|
+
|
|
130
|
+
overrides = _collect_overrides(
|
|
131
|
+
llm_enabled="true",
|
|
132
|
+
llm_models=model,
|
|
133
|
+
llm_provider=provider,
|
|
134
|
+
llm_temperature=temperature,
|
|
135
|
+
llm_max_output_tokens=max_output_tokens,
|
|
136
|
+
llm_request_timeout=request_timeout,
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
settings = load_llm_settings(overrides)
|
|
140
|
+
_, pages = _load_pages_or_fail(document, self.dpi, max_pages=max_pages)
|
|
141
|
+
|
|
142
|
+
attachments = [
|
|
143
|
+
create_binary_content(payload, "image/png")
|
|
144
|
+
for _, payload in prepare_image_attachments(pages)
|
|
145
|
+
]
|
|
146
|
+
extra = _summaries_from_text(pages) if include_pdf_text else []
|
|
147
|
+
|
|
148
|
+
base_prompt = prompt.strip() if prompt else TEXT_EXTRACTION_PROMPT
|
|
149
|
+
result = run_structured_prompt(
|
|
150
|
+
settings=settings,
|
|
151
|
+
purpose="vision",
|
|
152
|
+
prompt=base_prompt,
|
|
153
|
+
attachments=attachments,
|
|
154
|
+
extra_messages=extra,
|
|
155
|
+
output_type=LLMExtractionResult,
|
|
156
|
+
)
|
|
157
|
+
if not isinstance(result, LLMExtractionResult):
|
|
158
|
+
raise AssertionError("LLM returned an unexpected response for text extraction.")
|
|
159
|
+
return result.text
|
|
160
|
+
|
|
161
|
+
@keyword(name="Get Text From Area With LLM", tags=("ai",))
|
|
162
|
+
def get_text_from_area_with_llm(
|
|
163
|
+
self,
|
|
164
|
+
document: str,
|
|
165
|
+
area: Dict,
|
|
166
|
+
prompt: Optional[str] = None,
|
|
167
|
+
model: Optional[str] = None,
|
|
168
|
+
provider: Optional[str] = None,
|
|
169
|
+
temperature: Optional[float] = None,
|
|
170
|
+
request_timeout: Optional[float] = None,
|
|
171
|
+
) -> str:
|
|
172
|
+
"""Extract text from a specified area using an LLM.
|
|
173
|
+
|
|
174
|
+
| =Arguments= | =Description= |
|
|
175
|
+
| ``document`` | Path or URL to the source file (image or PDF). |
|
|
176
|
+
| ``area`` | Dictionary describing the region. Keys: ``x``, ``y``, ``width``, ``height`` and optional ``page`` / ``unit``. |
|
|
177
|
+
| ``prompt`` | Optional instructions for the LLM. Default ``None`` uses a generic area-transcription prompt. |
|
|
178
|
+
| ``model`` | Override the configured model name. Default ``None``. |
|
|
179
|
+
| ``provider`` | Override the provider identifier. Default ``None``. |
|
|
180
|
+
| ``temperature`` | Sampling temperature. Default ``None``. |
|
|
181
|
+
| ``request_timeout`` | Timeout in seconds for the API call. Default ``None``. |
|
|
182
|
+
|
|
183
|
+
Returns the extracted text as a string.
|
|
184
|
+
|
|
185
|
+
Raises ``AssertionError`` when the document cannot be loaded or the area is invalid.
|
|
186
|
+
|
|
187
|
+
Example:
|
|
188
|
+
| &{area}= Create Dictionary x=0 y=0 width=400 height=200 page=1
|
|
189
|
+
| ${text}= Get Text From Area With LLM testdata/invoice.pdf ${area}
|
|
190
|
+
| Should Contain ${text} Invoice
|
|
191
|
+
"""
|
|
192
|
+
|
|
193
|
+
overrides = _collect_overrides(
|
|
194
|
+
llm_enabled="true",
|
|
195
|
+
llm_models=model,
|
|
196
|
+
llm_provider=provider,
|
|
197
|
+
llm_temperature=temperature,
|
|
198
|
+
llm_request_timeout=request_timeout,
|
|
199
|
+
)
|
|
200
|
+
settings = load_llm_settings(overrides)
|
|
201
|
+
|
|
202
|
+
doc_path, pages = _load_pages_or_fail(document, self.dpi)
|
|
203
|
+
|
|
204
|
+
target_page = area.get("page", "all")
|
|
205
|
+
unit = area.get("unit", "px")
|
|
206
|
+
attachments: List = []
|
|
207
|
+
area_text_snippets: List[str] = []
|
|
208
|
+
|
|
209
|
+
doc_representation = DocumentRepresentation(doc_path, dpi=self.dpi)
|
|
210
|
+
page_list = list(doc_representation.pages)
|
|
211
|
+
|
|
212
|
+
for idx, (page_meta, page_obj) in enumerate(zip(pages, page_list), 1):
|
|
213
|
+
if target_page != "all" and int(target_page) != idx:
|
|
214
|
+
continue
|
|
215
|
+
try:
|
|
216
|
+
x, y, w, h = page_obj._convert_to_pixels(area, unit)
|
|
217
|
+
except Exception as exc:
|
|
218
|
+
raise AssertionError(f"Invalid area specification: {exc}") from exc
|
|
219
|
+
crop = page_meta["image"][y : y + h, x : x + w]
|
|
220
|
+
if crop.size == 0:
|
|
221
|
+
continue
|
|
222
|
+
attachments.append(create_binary_content(cv2.imencode(".png", crop)[1].tobytes(), "image/png"))
|
|
223
|
+
snippet = page_obj._get_text_from_area(area)
|
|
224
|
+
if snippet:
|
|
225
|
+
area_text_snippets.append(f"Page {idx} area text:\n{snippet}")
|
|
226
|
+
|
|
227
|
+
if not attachments:
|
|
228
|
+
raise AssertionError("Specified area produced no image data.")
|
|
229
|
+
|
|
230
|
+
base_prompt = prompt.strip() if prompt else AREA_EXTRACTION_PROMPT
|
|
231
|
+
result = run_structured_prompt(
|
|
232
|
+
settings=settings,
|
|
233
|
+
purpose="vision",
|
|
234
|
+
prompt=base_prompt,
|
|
235
|
+
attachments=attachments,
|
|
236
|
+
extra_messages=area_text_snippets or None,
|
|
237
|
+
output_type=LLMExtractionResult,
|
|
238
|
+
)
|
|
239
|
+
if not isinstance(result, LLMExtractionResult):
|
|
240
|
+
raise AssertionError("LLM returned an unexpected response for area extraction.")
|
|
241
|
+
return result.text
|
|
242
|
+
|
|
243
|
+
# ---------------- Chat ---------------- #
|
|
244
|
+
|
|
245
|
+
@keyword(name="Chat With Document", tags=("ai",))
|
|
246
|
+
def chat_with_document(
|
|
247
|
+
self,
|
|
248
|
+
prompt: str,
|
|
249
|
+
documents,
|
|
250
|
+
include_pdf_text: bool = True,
|
|
251
|
+
model: Optional[str] = None,
|
|
252
|
+
provider: Optional[str] = None,
|
|
253
|
+
temperature: Optional[float] = None,
|
|
254
|
+
max_output_tokens: Optional[int] = None,
|
|
255
|
+
request_timeout: Optional[float] = None,
|
|
256
|
+
max_pages: Optional[int] = None,
|
|
257
|
+
) -> str:
|
|
258
|
+
"""Chat with one or more documents using an LLM.
|
|
259
|
+
|
|
260
|
+
| =Arguments= | =Description= |
|
|
261
|
+
| ``prompt`` | User question or instruction passed to the LLM. |
|
|
262
|
+
| ``documents`` | Path/URL or list of paths/URLs to include in the conversation. |
|
|
263
|
+
| ``include_pdf_text`` | When ``${True}``, include direct PDF text in the prompt. Default ``${True}``. |
|
|
264
|
+
| ``model`` | Override the configured model name. Default ``None``. |
|
|
265
|
+
| ``provider`` | Override the provider identifier. Default ``None``. |
|
|
266
|
+
| ``temperature`` | Sampling temperature. Default ``None``. |
|
|
267
|
+
| ``max_output_tokens`` | Maximum number of tokens the model may produce. Default ``None``. |
|
|
268
|
+
| ``request_timeout`` | Timeout in seconds for the API call. Default ``None``. |
|
|
269
|
+
| ``max_pages`` | Limit the number of pages per document. Default ``None``. |
|
|
270
|
+
|
|
271
|
+
Returns the assistant's textual response.
|
|
272
|
+
|
|
273
|
+
Raises ``AssertionError`` when any document cannot be read or rendered.
|
|
274
|
+
|
|
275
|
+
Example:
|
|
276
|
+
| ${answer}= Chat With Document prompt=Summarise the document total. documents=testdata/invoice.pdf
|
|
277
|
+
| Should Contain ${answer} EUR
|
|
278
|
+
"""
|
|
279
|
+
|
|
280
|
+
if not documents:
|
|
281
|
+
raise ValueError("No documents supplied.")
|
|
282
|
+
if isinstance(documents, str):
|
|
283
|
+
doc_list = [documents]
|
|
284
|
+
else:
|
|
285
|
+
doc_list = list(documents)
|
|
286
|
+
|
|
287
|
+
overrides = _collect_overrides(
|
|
288
|
+
llm_enabled="true",
|
|
289
|
+
llm_models=model,
|
|
290
|
+
llm_provider=provider,
|
|
291
|
+
llm_temperature=temperature,
|
|
292
|
+
llm_max_output_tokens=max_output_tokens,
|
|
293
|
+
llm_request_timeout=request_timeout,
|
|
294
|
+
)
|
|
295
|
+
settings = load_llm_settings(overrides)
|
|
296
|
+
|
|
297
|
+
attachments: List = []
|
|
298
|
+
extra_messages: List[str] = [prompt]
|
|
299
|
+
|
|
300
|
+
for doc in doc_list:
|
|
301
|
+
_, pages = _load_pages_or_fail(doc, self.dpi, max_pages=max_pages)
|
|
302
|
+
for _, payload in prepare_image_attachments(pages):
|
|
303
|
+
attachments.append(create_binary_content(payload, "image/png"))
|
|
304
|
+
if include_pdf_text:
|
|
305
|
+
extra_messages.extend(_summaries_from_text(pages))
|
|
306
|
+
|
|
307
|
+
result = run_structured_prompt(
|
|
308
|
+
settings=settings,
|
|
309
|
+
purpose="vision",
|
|
310
|
+
prompt=CHAT_SYSTEM_PROMPT,
|
|
311
|
+
attachments=attachments,
|
|
312
|
+
extra_messages=extra_messages,
|
|
313
|
+
output_type=LLMChatResponse,
|
|
314
|
+
)
|
|
315
|
+
if not isinstance(result, LLMChatResponse):
|
|
316
|
+
raise AssertionError("LLM returned an unexpected chat response.")
|
|
317
|
+
return result.response
|
|
318
|
+
|
|
319
|
+
# ---------------- Detection & Counting ---------------- #
|
|
320
|
+
|
|
321
|
+
@keyword(name="Image Should Contain", tags=("ai",))
|
|
322
|
+
def image_should_contain(
|
|
323
|
+
self,
|
|
324
|
+
document: str,
|
|
325
|
+
expected: str,
|
|
326
|
+
prompt: Optional[str] = None,
|
|
327
|
+
model: Optional[str] = None,
|
|
328
|
+
provider: Optional[str] = None,
|
|
329
|
+
temperature: Optional[float] = None,
|
|
330
|
+
request_timeout: Optional[float] = None,
|
|
331
|
+
):
|
|
332
|
+
"""Assert that a document contains the expected visual content.
|
|
333
|
+
|
|
334
|
+
| =Arguments= | =Description= |
|
|
335
|
+
| ``document`` | Path or URL to the source file. |
|
|
336
|
+
| ``expected`` | Description of the object or concept that must be present. |
|
|
337
|
+
| ``prompt`` | Optional detailed instructions for the LLM. Default ``None`` uses the built-in detector prompt. |
|
|
338
|
+
| ``model`` | Override the configured model name. Default ``None``. |
|
|
339
|
+
| ``provider`` | Override the provider identifier. Default ``None``. |
|
|
340
|
+
| ``temperature`` | Sampling temperature. Default ``None``. |
|
|
341
|
+
| ``request_timeout`` | Timeout in seconds for the API call. Default ``None``. |
|
|
342
|
+
|
|
343
|
+
Raises ``AssertionError`` when the document cannot be read or when the expected content is not detected.
|
|
344
|
+
|
|
345
|
+
Example:
|
|
346
|
+
| Image Should Contain testdata/invoice.pdf Invoice header with company logo
|
|
347
|
+
"""
|
|
348
|
+
|
|
349
|
+
overrides = _collect_overrides(
|
|
350
|
+
llm_enabled="true",
|
|
351
|
+
llm_models=model,
|
|
352
|
+
llm_provider=provider,
|
|
353
|
+
llm_temperature=temperature,
|
|
354
|
+
llm_request_timeout=request_timeout,
|
|
355
|
+
)
|
|
356
|
+
settings = load_llm_settings(overrides)
|
|
357
|
+
|
|
358
|
+
_, pages = _load_pages_or_fail(document, self.dpi)
|
|
359
|
+
attachments = [
|
|
360
|
+
create_binary_content(payload, "image/png")
|
|
361
|
+
for _, payload in prepare_image_attachments(pages)
|
|
362
|
+
]
|
|
363
|
+
base_prompt = prompt.strip() if prompt else OBJECT_DETECTION_PROMPT
|
|
364
|
+
combined_prompt = f"{base_prompt}\nRequired objects: {expected}"
|
|
365
|
+
|
|
366
|
+
decision = run_structured_prompt(
|
|
367
|
+
settings=settings,
|
|
368
|
+
purpose="vision",
|
|
369
|
+
prompt=combined_prompt,
|
|
370
|
+
attachments=attachments,
|
|
371
|
+
output_type=LLMDecision,
|
|
372
|
+
)
|
|
373
|
+
if not isinstance(decision, LLMDecision):
|
|
374
|
+
raise AssertionError(f"LLM returned an unexpected response while checking '{expected}'.")
|
|
375
|
+
if decision.decision == decision.decision.APPROVE:
|
|
376
|
+
found_text = any(
|
|
377
|
+
expected.lower() in (page.get("text") or "").lower()
|
|
378
|
+
for page in pages
|
|
379
|
+
)
|
|
380
|
+
if found_text:
|
|
381
|
+
return
|
|
382
|
+
print("LLM approved but keyword could not verify the expected content in document text; treating as failure.")
|
|
383
|
+
raise AssertionError(f"Expected object '{expected}' not found in '{document}'.")
|
|
384
|
+
if decision.reason:
|
|
385
|
+
print(f"LLM reason: {decision.reason}")
|
|
386
|
+
raise AssertionError(f"Expected object '{expected}' not found in '{document}'.")
|
|
387
|
+
|
|
388
|
+
@keyword(name="Get Item Count From Image", tags=("ai",))
|
|
389
|
+
def get_item_count_from_image(
|
|
390
|
+
self,
|
|
391
|
+
document: str,
|
|
392
|
+
item_description: str,
|
|
393
|
+
prompt: Optional[str] = None,
|
|
394
|
+
model: Optional[str] = None,
|
|
395
|
+
provider: Optional[str] = None,
|
|
396
|
+
temperature: Optional[float] = None,
|
|
397
|
+
request_timeout: Optional[float] = None,
|
|
398
|
+
) -> int:
|
|
399
|
+
"""Count items in an image or document using an LLM.
|
|
400
|
+
|
|
401
|
+
| =Arguments= | =Description= |
|
|
402
|
+
| ``document`` | Path or URL to the source image/PDF. |
|
|
403
|
+
| ``item_description`` | Natural-language description of the item to count. |
|
|
404
|
+
| ``prompt`` | Optional custom instructions for the LLM. Default ``None`` uses a structured counting prompt. |
|
|
405
|
+
| ``model`` | Override the configured model name. Default ``None``. |
|
|
406
|
+
| ``provider`` | Override the provider identifier. Default ``None``. |
|
|
407
|
+
| ``temperature`` | Sampling temperature. Default ``None``. |
|
|
408
|
+
| ``request_timeout`` | Timeout in seconds for the API call. Default ``None``. |
|
|
409
|
+
|
|
410
|
+
Returns the counted integer (``0`` when no candidate is found).
|
|
411
|
+
|
|
412
|
+
Raises ``AssertionError`` when the document cannot be read.
|
|
413
|
+
|
|
414
|
+
Example:
|
|
415
|
+
| ${count}= Get Item Count From Image testdata/invoice.pdf item_description=number of tables
|
|
416
|
+
| Should Be True ${count} >= 1
|
|
417
|
+
"""
|
|
418
|
+
|
|
419
|
+
overrides = _collect_overrides(
|
|
420
|
+
llm_enabled="true",
|
|
421
|
+
llm_models=model,
|
|
422
|
+
llm_provider=provider,
|
|
423
|
+
llm_temperature=temperature,
|
|
424
|
+
llm_request_timeout=request_timeout,
|
|
425
|
+
)
|
|
426
|
+
settings = load_llm_settings(overrides)
|
|
427
|
+
|
|
428
|
+
_, pages = _load_pages_or_fail(document, self.dpi)
|
|
429
|
+
attachments = [
|
|
430
|
+
create_binary_content(payload, "image/png")
|
|
431
|
+
for _, payload in prepare_image_attachments(pages)
|
|
432
|
+
]
|
|
433
|
+
base_prompt = prompt.strip() if prompt else COUNT_PROMPT
|
|
434
|
+
combined_prompt = f"{base_prompt}\nItem to count: {item_description}"
|
|
435
|
+
|
|
436
|
+
result = run_structured_prompt(
|
|
437
|
+
settings=settings,
|
|
438
|
+
purpose="vision",
|
|
439
|
+
prompt=combined_prompt,
|
|
440
|
+
attachments=attachments,
|
|
441
|
+
output_type=LLMCountResponse,
|
|
442
|
+
)
|
|
443
|
+
if not isinstance(result, LLMCountResponse):
|
|
444
|
+
raise AssertionError("LLM returned an unexpected response for item count.")
|
|
445
|
+
return int(result.count)
|
|
446
|
+
def _load_pages_or_fail(document: str, dpi: int, max_pages: Optional[int] = None):
|
|
447
|
+
path = _ensure_local(document)
|
|
448
|
+
try:
|
|
449
|
+
pages = load_document_pages(path, dpi=dpi, max_pages=max_pages)
|
|
450
|
+
except Exception as exc:
|
|
451
|
+
raise AssertionError(f"Unable to load document '{document}': {exc}") from exc
|
|
452
|
+
if not pages:
|
|
453
|
+
raise AssertionError(f"Document '{document}' produced no renderable pages.")
|
|
454
|
+
return path, pages
|