dingo-python 2.2.2__py3-none-any.whl → 2.4.0__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.
Files changed (39) hide show
  1. dingo/config/input_args.py +16 -1
  2. dingo/data/converter/__init__.py +1 -0
  3. dingo/data/converter/mineru.py +245 -0
  4. dingo/data/datasource/local.py +1 -1
  5. dingo/exec/local.py +2 -1
  6. dingo/io/output/__init__.py +1 -0
  7. dingo/io/output/result_info.py +16 -0
  8. dingo/model/llm/compare/llm_html_extract_compare.py +17 -2
  9. dingo/model/llm/compare/llm_html_extract_compare_v2.py +1 -1
  10. dingo/model/llm/compare/llm_html_extract_compare_v3.py +221 -0
  11. dingo/model/llm/hhh/llm_text_3h.py +1 -1
  12. dingo/model/llm/llm_classify_qr.py +4 -2
  13. dingo/model/llm/llm_custom_metric.py +211 -0
  14. dingo/model/llm/llm_document_parsing_ocr.py +6 -2
  15. dingo/model/llm/llm_factcheck_public.py +1 -1
  16. dingo/model/llm/llm_keyword_matcher.py +1 -1
  17. dingo/model/llm/llm_scout.py +1 -1
  18. dingo/model/llm/mineru/vlm_document_parsing.py +4 -8
  19. dingo/model/llm/mineru/vlm_document_parsing_ocr_train.py +4 -8
  20. dingo/model/llm/rag/llm_rag_answer_relevancy.py +1 -1
  21. dingo/model/llm/rag/llm_rag_chunk_quality.py +99 -0
  22. dingo/model/llm/rag/llm_rag_context_precision.py +1 -1
  23. dingo/model/llm/rag/llm_rag_context_recall.py +1 -1
  24. dingo/model/llm/rag/llm_rag_faithfulness.py +1 -1
  25. dingo/model/llm/vlm_image_relevant.py +9 -52
  26. dingo/model/llm/vlm_layout_quality.py +3 -54
  27. dingo/model/model.py +37 -24
  28. dingo/model/rule/rule_common.py +76 -0
  29. dingo/model/rule/rule_image.py +41 -32
  30. dingo/model/rule/scibase/__init__.py +1 -0
  31. dingo/model/rule/scibase/rule_quanliang.py +655 -0
  32. dingo/run/cli.py +22 -1
  33. dingo/utils/image_loader.py +141 -0
  34. {dingo_python-2.2.2.dist-info → dingo_python-2.4.0.dist-info}/METADATA +22 -1
  35. {dingo_python-2.2.2.dist-info → dingo_python-2.4.0.dist-info}/RECORD +39 -32
  36. {dingo_python-2.2.2.dist-info → dingo_python-2.4.0.dist-info}/WHEEL +0 -0
  37. {dingo_python-2.2.2.dist-info → dingo_python-2.4.0.dist-info}/entry_points.txt +0 -0
  38. {dingo_python-2.2.2.dist-info → dingo_python-2.4.0.dist-info}/licenses/LICENSE +0 -0
  39. {dingo_python-2.2.2.dist-info → dingo_python-2.4.0.dist-info}/top_level.txt +0 -0
@@ -53,6 +53,10 @@ class DatasetFieldArgs(BaseModel):
53
53
  image: str = ''
54
54
 
55
55
 
56
+ class DatasetMinerUArgs(BaseModel):
57
+ include_types: Optional[List[str]] = None # 只保留指定的 block 类型,None 表示全部保留
58
+
59
+
56
60
  class DatasetArgs(BaseModel):
57
61
  source: str = 'hugging_face'
58
62
  format: str = 'json'
@@ -64,6 +68,7 @@ class DatasetArgs(BaseModel):
64
68
  excel_config: DatasetExcelArgs = DatasetExcelArgs()
65
69
  csv_config: DatasetCsvArgs = DatasetCsvArgs()
66
70
  parquet_config: DatasetParquetArgs = DatasetParquetArgs()
71
+ mineru_config: DatasetMinerUArgs = DatasetMinerUArgs()
67
72
 
68
73
 
69
74
  class ExecutorResultSaveArgs(BaseModel):
@@ -87,6 +92,8 @@ class ExecutorArgs(BaseModel):
87
92
 
88
93
 
89
94
  class EvaluatorRuleArgs(BaseModel):
95
+ model_config = {"extra": "forbid"}
96
+
90
97
  threshold: Optional[float] = None
91
98
  pattern: Optional[str] = None
92
99
  key_list: Optional[List[str]] = None
@@ -101,6 +108,13 @@ class EmbeddingConfigArgs(BaseModel):
101
108
  api_url: Optional[str] = None
102
109
 
103
110
 
111
+ class CustomLLMMetricArgs(BaseModel):
112
+ metric: str
113
+ description: Optional[str] = ""
114
+ criteria: List[str]
115
+ input_fields: List[str]
116
+
117
+
104
118
  class EvaluatorLLMArgs(BaseModel):
105
119
  model_config = {"extra": "allow"}
106
120
 
@@ -108,10 +122,11 @@ class EvaluatorLLMArgs(BaseModel):
108
122
  key: Optional[str] = None
109
123
  api_url: Optional[str] = None
110
124
  embedding_config: Optional[EmbeddingConfigArgs] = None
125
+ custom_metric: Optional[CustomLLMMetricArgs] = None
111
126
 
112
127
 
113
128
  class EvalPiplineConfig(BaseModel):
114
- """Single evaluator configuration item"""
129
+ """Single evaluator configuration item."""
115
130
  name: str
116
131
  config: Optional[EvaluatorRuleArgs | EvaluatorLLMArgs] = None
117
132
 
@@ -1,3 +1,4 @@
1
+ import dingo.data.converter.mineru # noqa: F401 — registers mineru / mineru_v2
1
2
  from dingo.data.converter.base import BaseConverter
2
3
 
3
4
  converters = BaseConverter.converters
@@ -0,0 +1,245 @@
1
+ """MinerU output format converters.
2
+
3
+ Supports two MinerU structured output files:
4
+ - ``content_list.json`` (format: ``"mineru"``) — flat array of blocks
5
+ - ``content_list_v2.json`` (format: ``"mineru_v2"``) — pages × blocks
6
+ """
7
+
8
+ import json
9
+ from typing import Callable, Dict, List, Union
10
+
11
+ from dingo.config import InputArgs
12
+ from dingo.data.converter.base import BaseConverter
13
+ from dingo.io import Data
14
+
15
+
16
+ def _flatten_spans(spans: List[Dict]) -> str:
17
+ """Concatenate a V2 span list into plain text.
18
+
19
+ Spans look like ``[{"type": "text", "content": "..."}, ...]``.
20
+ Hyperlink spans may carry ``children`` with nested text spans;
21
+ when present we use the top-level ``content`` which is already the
22
+ concatenated text.
23
+ """
24
+ parts = []
25
+ for span in spans:
26
+ parts.append(span.get("content", ""))
27
+ return "".join(parts)
28
+
29
+
30
+ def _wrap_image(img_path) -> List[str]:
31
+ """Ensure img_path is a list of strings (Dingo convention)."""
32
+ if not img_path:
33
+ return []
34
+ if isinstance(img_path, list):
35
+ return img_path
36
+ return [img_path]
37
+
38
+
39
+ # ---------------------------------------------------------------------------
40
+ # V1: content_list.json
41
+ # ---------------------------------------------------------------------------
42
+
43
+ _V1_TEXT_TYPES = frozenset({
44
+ "text", "equation", "header", "footer",
45
+ "page_number", "aside_text", "page_footnote",
46
+ })
47
+
48
+
49
+ def _map_block_v1(block: dict, block_idx: int) -> dict:
50
+ """Map a single content_list.json block to a Data-compatible dict."""
51
+ btype = block.get("type", "")
52
+ page_idx = block.get("page_idx", 0)
53
+
54
+ data_dict = dict(block)
55
+ data_dict["data_id"] = f"p{page_idx}-b{block_idx}"
56
+
57
+ if btype in _V1_TEXT_TYPES:
58
+ data_dict["content"] = block.get("text", "")
59
+
60
+ elif btype == "image":
61
+ data_dict["content"] = ""
62
+ data_dict["image"] = _wrap_image(block.get("img_path"))
63
+
64
+ elif btype == "table":
65
+ data_dict["content"] = block.get("table_body", "")
66
+ data_dict["image"] = _wrap_image(block.get("img_path"))
67
+
68
+ elif btype == "chart":
69
+ data_dict["content"] = block.get("content", "")
70
+ data_dict["image"] = _wrap_image(block.get("img_path"))
71
+
72
+ elif btype == "code":
73
+ data_dict["content"] = block.get("code_body", "")
74
+
75
+ elif btype == "list":
76
+ items = block.get("list_items", [])
77
+ data_dict["content"] = "\n".join(items) if items else ""
78
+
79
+ else:
80
+ data_dict.setdefault("content", block.get("text", ""))
81
+
82
+ if "img_path" in data_dict and "image" not in data_dict:
83
+ img = _wrap_image(data_dict["img_path"])
84
+ if img:
85
+ data_dict["image"] = img
86
+
87
+ return data_dict
88
+
89
+
90
+ @BaseConverter.register("mineru")
91
+ class MinerUConverter(BaseConverter):
92
+ """Converter for MinerU ``content_list.json`` (flat block array)."""
93
+
94
+ def __init__(self):
95
+ super().__init__()
96
+
97
+ @classmethod
98
+ def convertor(cls, input_args: InputArgs) -> Callable:
99
+ include = None
100
+ if hasattr(input_args.dataset, "mineru_config"):
101
+ cfg = input_args.dataset.mineru_config
102
+ if cfg.include_types:
103
+ include = frozenset(cfg.include_types)
104
+
105
+ def _convert(raw: Union[str, list]):
106
+ blocks = raw
107
+ if isinstance(raw, str):
108
+ blocks = json.loads(raw)
109
+ for block_idx, block in enumerate(blocks):
110
+ if include and block.get("type", "") not in include:
111
+ continue
112
+ data_dict = _map_block_v1(block, block_idx)
113
+ yield Data(**data_dict)
114
+
115
+ return _convert
116
+
117
+
118
+ # ---------------------------------------------------------------------------
119
+ # V2: content_list_v2.json
120
+ # ---------------------------------------------------------------------------
121
+
122
+ def _map_block_v2(block: dict, page_idx: int, block_idx: int) -> dict:
123
+ """Map a single content_list_v2.json block to a Data-compatible dict."""
124
+ btype = block.get("type", "")
125
+ inner = block.get("content")
126
+
127
+ if not isinstance(inner, dict):
128
+ data_dict = {
129
+ "data_id": f"p{page_idx}-b{block_idx}",
130
+ "type": btype,
131
+ "page_idx": page_idx,
132
+ "content": inner if isinstance(inner, str) else "",
133
+ "raw_content": inner,
134
+ }
135
+ if "bbox" in block:
136
+ data_dict["bbox"] = block["bbox"]
137
+ return data_dict
138
+
139
+ data_dict = {
140
+ "data_id": f"p{page_idx}-b{block_idx}",
141
+ "type": btype,
142
+ "page_idx": page_idx,
143
+ }
144
+
145
+ if "bbox" in block:
146
+ data_dict["bbox"] = block["bbox"]
147
+ if "anchor" in block:
148
+ data_dict["anchor"] = block["anchor"]
149
+ if "sub_type" in block:
150
+ data_dict["sub_type"] = block["sub_type"]
151
+
152
+ if btype == "title":
153
+ spans = inner.get("title_content", [])
154
+ data_dict["content"] = _flatten_spans(spans)
155
+ data_dict["text_level"] = inner.get("level", 0)
156
+
157
+ elif btype == "paragraph":
158
+ spans = inner.get("paragraph_content", [])
159
+ data_dict["content"] = _flatten_spans(spans)
160
+
161
+ elif btype == "equation_interline":
162
+ data_dict["content"] = inner.get("math_content", "")
163
+ if "math_type" in inner:
164
+ data_dict["math_type"] = inner["math_type"]
165
+
166
+ elif btype == "image":
167
+ data_dict["content"] = ""
168
+ data_dict["image"] = _wrap_image(inner.get("img_path"))
169
+ for key in ("image_caption", "image_footnote"):
170
+ if key in inner:
171
+ data_dict[key] = inner[key]
172
+
173
+ elif btype == "table":
174
+ data_dict["content"] = inner.get("table_body", "")
175
+ data_dict["image"] = _wrap_image(inner.get("img_path"))
176
+ for key in ("table_caption", "table_footnote"):
177
+ if key in inner:
178
+ data_dict[key] = inner[key]
179
+
180
+ elif btype == "chart":
181
+ data_dict["content"] = inner.get("content", "")
182
+ data_dict["image"] = _wrap_image(inner.get("img_path"))
183
+ for key in ("chart_caption", "chart_footnote"):
184
+ if key in inner:
185
+ data_dict[key] = inner[key]
186
+
187
+ elif btype == "code":
188
+ data_dict["content"] = inner.get("code_content", "")
189
+ for key in ("code_caption", "code_footnote", "code_language"):
190
+ if key in inner:
191
+ data_dict[key] = inner[key]
192
+
193
+ elif btype == "algorithm":
194
+ data_dict["content"] = inner.get("algorithm_content", "")
195
+ for key in ("algorithm_caption", "algorithm_footnote"):
196
+ if key in inner:
197
+ data_dict[key] = inner[key]
198
+
199
+ elif btype in ("list", "index"):
200
+ items = inner.get("list_items", [])
201
+ data_dict["content"] = "\n".join(items) if items else ""
202
+ data_dict["list_items"] = items
203
+
204
+ else:
205
+ content_key = f"{btype}_content"
206
+ spans = inner.get(content_key, [])
207
+ if isinstance(spans, list) and spans and isinstance(spans[0], dict):
208
+ data_dict["content"] = _flatten_spans(spans)
209
+ elif isinstance(inner, str):
210
+ data_dict["content"] = inner
211
+ else:
212
+ data_dict["content"] = ""
213
+
214
+ data_dict["raw_content"] = inner
215
+
216
+ return data_dict
217
+
218
+
219
+ @BaseConverter.register("mineru_v2")
220
+ class MinerUV2Converter(BaseConverter):
221
+ """Converter for MinerU ``content_list_v2.json`` (pages x blocks)."""
222
+
223
+ def __init__(self):
224
+ super().__init__()
225
+
226
+ @classmethod
227
+ def convertor(cls, input_args: InputArgs) -> Callable:
228
+ include = None
229
+ if hasattr(input_args.dataset, "mineru_config"):
230
+ cfg = input_args.dataset.mineru_config
231
+ if cfg.include_types:
232
+ include = frozenset(cfg.include_types)
233
+
234
+ def _convert(raw: Union[str, list]):
235
+ pages = raw
236
+ if isinstance(raw, str):
237
+ pages = json.loads(raw)
238
+ for page_idx, page_blocks in enumerate(pages):
239
+ for block_idx, block in enumerate(page_blocks):
240
+ if include and block.get("type", "") not in include:
241
+ continue
242
+ data_dict = _map_block_v2(block, page_idx, block_idx)
243
+ yield Data(**data_dict)
244
+
245
+ return _convert
@@ -395,7 +395,7 @@ class LocalDataSource(DataSource):
395
395
  elif os.path.exists(self.path) and os.path.isdir(self.path):
396
396
  self._find_all_files(self.path, f_list)
397
397
 
398
- by_line = self.input_args.dataset.format not in ["json", "listjson"]
398
+ by_line = self.input_args.dataset.format not in ["json", "listjson", "mineru", "mineru_v2"]
399
399
 
400
400
  for f in f_list:
401
401
  # Check if file is CSV
dingo/exec/local.py CHANGED
@@ -178,8 +178,9 @@ class LocalExecutor(ExecProto):
178
178
  Model.set_config_rule(model, e_c_i.config)
179
179
  elif eval_type == 'llm':
180
180
  model_cls = Model.llm_name_map.get(e_c_i.name)
181
- model = model_cls() # 实例化类为对象,避免多线程配置覆盖
181
+ model = model_cls()
182
182
  Model.set_config_llm(model, e_c_i.config)
183
+ Model.set_config_llm(model_cls, e_c_i.config)
183
184
  else:
184
185
  raise ValueError(f"Error eval_type: {eval_type}")
185
186
 
@@ -1,2 +1,3 @@
1
+ # from dingo.io.output.benchmark_report import BenchmarkReport # noqa E402.
1
2
  from dingo.io.output.result_info import ResultInfo # noqa E402.
2
3
  from dingo.io.output.summary_model import SummaryModel # noqa E402.
@@ -33,6 +33,19 @@ class ResultInfo(BaseModel):
33
33
  Returns:
34
34
  包含原始数据和dingo_result的字典
35
35
  """
36
+ def move_conflict_field(field_name: str):
37
+ if field_name not in self.raw_data:
38
+ return
39
+
40
+ index = 1
41
+ while True:
42
+ backup_field = f'{field_name}_old_v{index}'
43
+ if backup_field not in self.raw_data:
44
+ self.raw_data[backup_field] = self.raw_data[field_name]
45
+ del self.raw_data[field_name]
46
+ return
47
+ index += 1
48
+
36
49
  dingo_result = {
37
50
  'eval_status': self.eval_status,
38
51
  'eval_details': {
@@ -40,5 +53,8 @@ class ResultInfo(BaseModel):
40
53
  for k, v in self.eval_details.items()
41
54
  },
42
55
  }
56
+ move_conflict_field('dingo_id')
57
+ move_conflict_field('dingo_result')
58
+ self.raw_data['dingo_id'] = self.dingo_id
43
59
  self.raw_data['dingo_result'] = dingo_result
44
60
  return self.raw_data
@@ -95,13 +95,28 @@ class LLMHtmlExtractCompare(BaseOpenAI):
95
95
 
96
96
  @classmethod
97
97
  def build_messages(cls, input_data: Data) -> List:
98
+ raw_data = getattr(input_data, "raw_data", None) or {}
99
+ # Backward-compatible input handling:
100
+ # - Preferred: raw_data["magic_md"] and raw_data["content"] (legacy dataset schema)
101
+ # - Fallback: input_data.prompt (tool A) and input_data.reference (tool B)
102
+ # - Last resort: input_data.prompt (tool A) and input_data.extra fields if provided
103
+ tool_a_md = raw_data.get("magic_md", None) or getattr(input_data, "prompt", None)
104
+ tool_b_md = raw_data.get("content", None) or getattr(input_data, "reference", None)
105
+
106
+ if tool_a_md is None or tool_b_md is None:
107
+ raise ValueError(
108
+ "LLMHtmlExtractCompare requires Tool A and Tool B markdown. "
109
+ "Provide raw_data['magic_md'] and raw_data['content'], or provide Data.prompt (tool A) "
110
+ "and Data.reference (tool B)."
111
+ )
112
+
98
113
  messages = [
99
114
  {
100
115
  "role": "user",
101
116
  "content": cls.prompt.format(
102
117
  input_data.content,
103
- input_data.raw_data["magic_md"],
104
- input_data.raw_data["content"],
118
+ tool_a_md,
119
+ tool_b_md,
105
120
  ),
106
121
  }
107
122
  ]
@@ -36,7 +36,7 @@ class LLMHtmlExtractCompareV2(BaseOpenAI):
36
36
  'paper_url': '',
37
37
  }
38
38
 
39
- _required_fields = [RequiredField.CONTENT, RequiredField.PROMPT]
39
+ _required_fields = [RequiredField.PROMPT, RequiredField.CONTENT]
40
40
  prompt = {
41
41
  "content_en": r"""Please compare the following two texts, each extracted from the same webpage using different HTML parsing methods. Your task is to determine whether there is a difference in the core informational content between them.
42
42
 
@@ -0,0 +1,221 @@
1
+ import json
2
+ import re
3
+ from typing import List
4
+
5
+ from dingo.io.input import Data, RequiredField
6
+ from dingo.io.output.eval_detail import EvalDetail
7
+ from dingo.model import Model
8
+ from dingo.model.llm.base_openai import BaseOpenAI
9
+ from dingo.model.response.response_class import ResponseScoreTypeNameReason
10
+ from dingo.utils import log
11
+ from dingo.utils.exception import ConvertJsonError
12
+
13
+
14
+ @Model.llm_register("LLMHtmlExtractCompareV3")
15
+ class LLMHtmlExtractCompareV3(BaseOpenAI):
16
+ """
17
+ HTML提取工具对比评估 V3 版本
18
+
19
+ 基于 LLMTextQualityV5 的质量维度(Completeness / Effectiveness / Similarity / Security)
20
+ 对两个 HTML 提取工具的完整输出做对比评估,判断哪个工具的提取质量更高。
21
+
22
+ 与 V2 的区别:V2 侧重"谁保留了更多信息内容",V3 侧重"谁引入了更少质量缺陷"。
23
+ V3 直接发送全文(不做 diff 预处理),保留完整上下文,确保质量缺陷(尤其是
24
+ Error_Formula 等需要上下文才能正确归因的问题)能被准确识别。
25
+
26
+ 输入数据要求:
27
+ - input_data.prompt: 工具A提取的文本(对应 Data.prompt 字段)
28
+ - input_data.content: 工具B提取的文本(对应 Data.content 字段)
29
+ - language: 可选,来自 input_data.language 或 raw_data["language"],缺省为 "en"
30
+
31
+ EvalDetail.label 前缀与 Data 字段对齐(避免 TOOL_ONE/TOOL_TWO 歧义):
32
+ - PROMPT_BETTER:score=1,Data.prompt 侧提取质量更好
33
+ - CONTENT_BETTER:score=2,Data.content 侧更好
34
+ - EXTRACTION_EQUAL:score=0,两者相当
35
+ """
36
+
37
+ _metric_info = {
38
+ "category": "Pretrain Text Quality Assessment Metrics",
39
+ "metric_name": "LLMHtmlExtractCompareV3",
40
+ "description": "Compares two HTML extraction tools using LLM pretraining quality dimensions (completeness, effectiveness, similarity, security) with full-text evaluation for accurate defect attribution",
41
+ }
42
+
43
+ _required_fields = [RequiredField.PROMPT, RequiredField.CONTENT]
44
+
45
+ prompt = {
46
+ "content_en": r"""You are an expert in assessing pretraining data quality for large language models. You will compare two texts extracted from the same HTML page by different tools, and determine which extraction is of higher quality for LLM pretraining.
47
+
48
+ # Quality Dimensions
49
+
50
+ Evaluate BOTH texts against these dimensions and compare:
51
+
52
+ ## 1. Completeness
53
+ - **Error_Content_Coverage**: One extraction tool failed to capture the full main-body content of the page — at least one complete paragraph or named section present in the other extraction is entirely absent (e.g., an "Applications" or "Common Algorithms" section is missing). This is about **extraction-level omission** (the tool did not locate or include that block), NOT about individual missing words, broken formatting, or formula stripping (use the specific error types below for those).
54
+ - **Error_Formula**: Mathematical content with broken LaTeX syntax (unmatched delimiters, unclosed environments) OR systematically stripped symbols/formulas (orphan hyphens from stripped Greek letters like "-solutions" instead of "κ-solutions", empty positions after connective words like "thus ;" where a formula was removed)
55
+ - **Error_Table**: Malformed or unreadable table structures (misaligned columns, missing headers, garbled HTML tags)
56
+ - **Error_Code**: Code blocks with formatting corruption (missing code fences, lost indentation, broken identifiers like "sys .argv", line numbers mixed with code)
57
+
58
+ ## 2. Effectiveness
59
+ - **Error_Garbled_Characters**: Encoding issues or anti-crawler artifacts ("’", "□□□", ""); threshold: >1% of characters garbled
60
+ - **Error_Words_Stuck**: Missing spaces breaking tokenization ("Thequickbrownfox"); threshold: >1% of text affected
61
+ - **Error_Lack_Punctuation**: Unclear sentence boundaries ("I like apples they are red also I like oranges")
62
+
63
+ ## 3. Similarity
64
+ - **Error_Duplicate**: Excessive repetition dominating the text; threshold: same phrase repeats >5 times OR duplicate ratio >30%
65
+
66
+ ## 4. Security
67
+ - **Error_Politics**: Content promoting extremism, terrorism, ethnic hatred
68
+ - **Error_Prohibition**: Violence, pornography, gambling, drugs
69
+
70
+ # Input
71
+
72
+ **Text A** (Data.prompt — first extraction tool):
73
+ {text_tool_a}
74
+
75
+ **Text B** (Data.content — second extraction tool):
76
+ {text_tool_b}
77
+
78
+ # Evaluation Rules
79
+
80
+ 1. Evaluate each text independently against the quality dimensions above, then compare.
81
+ 2. Identify the dimension with the **largest quality difference** between the two texts.
82
+ 3. Minor formatting or whitespace differences that do not affect training quality should be ignored.
83
+
84
+ ⚠️ The order of Text A and Text B reflects the fixed field mapping: A = `Data.prompt`, B = `Data.content`. Do NOT favor either text based on its position.
85
+
86
+ # Output Format
87
+
88
+ Return JSON only:
89
+ {{
90
+ "score": [0|1|2],
91
+ "name": "[error_type from the dimension with greatest difference]",
92
+ "reason": "[objective description of quality differences]"
93
+ }}
94
+
95
+ Where:
96
+ - `score`: 1 if Text A (`Data.prompt`) is better, 2 if Text B (`Data.content`) is better, 0 if equal
97
+ - `name`: The specific error type with the biggest quality difference (e.g., "Error_Content_Coverage", "Error_Formula", "Error_Table", "Error_Code", "Error_Garbled_Characters", "Error_Words_Stuck", "Error_Lack_Punctuation", "Error_Duplicate", "Error_Politics", "Error_Prohibition"). Use "None" if both are equal.
98
+ - `reason`: Brief objective description (1-3 sentences)
99
+ """,
100
+ "content_cn": r"""你是一位大语言模型预训练数据质量评估专家。你将对比两个不同 HTML 提取工具从同一网页中提取的文本,判断哪个提取结果的质量更高,更适合用于 LLM 预训练。
101
+
102
+ # 质量维度
103
+
104
+ 请基于以下维度分别评估两段文本并进行对比:
105
+
106
+ ## 1. 完整性 (Completeness)
107
+ - **Error_Content_Coverage**:一个提取工具未能覆盖网页的完整主体内容——另一方存在的至少一个完整段落或命名小节在这方完全缺失(例如"应用场景"或"常用算法"整节不见)。这针对的是**提取层面的遗漏**(工具未识别或未包含该区块),而非个别词语缺失、格式损坏或公式剥离(这些请用下方对应的专用错误类型)。
108
+ - **Error_Formula**:数学内容存在 LaTeX 语法错误(未匹配的定界符、未关闭的环境)或符号/公式被系统性剥离(如 "κ-solutions" 被剥离为 "-solutions",连接词后公式缺失如 "thus ;" )
109
+ - **Error_Table**:表格结构畸形或不可读(列未对齐、缺少表头、HTML标签残留)
110
+ - **Error_Code**:代码块格式损坏(缺少代码围栏、缩进丢失、标识符断裂如 "sys .argv"、行号混入代码)
111
+
112
+ ## 2. 有效性 (Effectiveness)
113
+ - **Error_Garbled_Characters**:编码问题或反爬虫伪影("’"、"□□□"、"");阈值:>1% 的字符为乱码
114
+ - **Error_Words_Stuck**:缺失空格导致分词错误("Thequickbrownfox");阈值:>1% 的文本受影响
115
+ - **Error_Lack_Punctuation**:句子边界不清("I like apples they are red also I like oranges")
116
+
117
+ ## 3. 相似性 (Similarity)
118
+ - **Error_Duplicate**:过度重复内容;阈值:同一短语重复>5次 或 重复率>30%
119
+
120
+ ## 4. 安全性 (Security)
121
+ - **Error_Politics**:宣扬极端主义、恐怖主义、民族仇恨的内容
122
+ - **Error_Prohibition**:暴力、色情、赌博、毒品相关内容
123
+
124
+ # 输入
125
+
126
+ **文本A**(Data.prompt — 第一个提取工具的结果):
127
+ {text_tool_a}
128
+
129
+ **文本B**(Data.content — 第二个提取工具的结果):
130
+ {text_tool_b}
131
+
132
+ # 评估规则
133
+
134
+ 1. 独立按上述质量维度评估每段文本,再进行对比。
135
+ 2. 找出两段文本之间**质量差异最大**的维度。
136
+ 3. 不影响训练质量的细微格式差异或空白差异应忽略。
137
+
138
+ ⚠️ 文本A和文本B的顺序反映固定字段映射:A = `Data.prompt`,B = `Data.content`。请勿因位置先后偏好任何一方。
139
+
140
+ # 输出格式
141
+
142
+ 仅返回 JSON:
143
+ {{
144
+ "score": [0|1|2],
145
+ "name": "[差异最大维度中的具体错误类型]",
146
+ "reason": "[客观描述两段文本的质量差异]"
147
+ }}
148
+
149
+ 其中:
150
+ - `score`:文本A(`Data.prompt`)更好为 1,文本B(`Data.content`)更好为 2,质量相当为 0
151
+ - `name`:差异最大的具体错误类型(如 "Error_Content_Coverage"、"Error_Formula"、"Error_Table"、"Error_Code"、"Error_Garbled_Characters"、"Error_Words_Stuck"、"Error_Lack_Punctuation"、"Error_Duplicate"、"Error_Politics"、"Error_Prohibition")。如果两者相当则为 "None"。
152
+ - `reason`:简要客观描述(1-3句话)
153
+ """,
154
+ }
155
+
156
+ @classmethod
157
+ def build_messages(cls, input_data: Data) -> List:
158
+ text_tool_a = input_data.prompt
159
+ text_tool_b = input_data.content
160
+
161
+ raw_data = getattr(input_data, "raw_data", {}) or {}
162
+ language = raw_data.get("language", getattr(input_data, "language", "en"))
163
+
164
+ if language == "zh":
165
+ prompt_template = cls.prompt["content_cn"]
166
+ else:
167
+ prompt_template = cls.prompt["content_en"]
168
+
169
+ prompt_content = prompt_template.format(
170
+ text_tool_a=text_tool_a,
171
+ text_tool_b=text_tool_b,
172
+ )
173
+
174
+ return [{"role": "user", "content": prompt_content}]
175
+
176
+ @classmethod
177
+ def process_response(cls, response: str) -> EvalDetail:
178
+ log.info(response)
179
+
180
+ response_think = ""
181
+ if response.startswith("<think>"):
182
+ think_content = re.search(
183
+ r"<think>(.*?)</think>", response, flags=re.DOTALL
184
+ )
185
+ if think_content:
186
+ response_think = think_content.group(1).strip()
187
+ response = re.sub(r"<think>.*?</think>", "", response, flags=re.DOTALL)
188
+ response = response.strip()
189
+
190
+ if response.startswith("```json"):
191
+ response = response[7:]
192
+ if response.startswith("```"):
193
+ response = response[3:]
194
+ if response.endswith("```"):
195
+ response = response[:-3]
196
+ response = response.strip()
197
+
198
+ try:
199
+ response_json = json.loads(response)
200
+ if response_think:
201
+ response_json["reason"] = response_json.get("reason", "") + "\n" + response_think
202
+ except json.JSONDecodeError:
203
+ raise ConvertJsonError(f"Convert to JSON format failed: {response}")
204
+
205
+ response_model = ResponseScoreTypeNameReason(**response_json)
206
+
207
+ result = EvalDetail(metric=cls.__name__)
208
+
209
+ # Label prefixes match Data fields: prompt=first extraction, content=second.
210
+ if response_model.score == 1:
211
+ tmp_type = "PROMPT_BETTER"
212
+ elif response_model.score == 2:
213
+ tmp_type = "CONTENT_BETTER"
214
+ else:
215
+ tmp_type = "EXTRACTION_EQUAL"
216
+
217
+ result.status = response_model.score != 1
218
+ result.label = [f"{tmp_type}"]
219
+ result.reason = [json.dumps(response_json, ensure_ascii=False)]
220
+
221
+ return result
@@ -10,7 +10,7 @@ from dingo.utils.exception import ConvertJsonError
10
10
 
11
11
  # @Model.llm_register("LLMText3H")
12
12
  class LLMText3H(BaseOpenAI):
13
- _required_fields = [RequiredField.CONTENT, RequiredField.PROMPT]
13
+ _required_fields = [RequiredField.PROMPT, RequiredField.CONTENT]
14
14
 
15
15
  @classmethod
16
16
  def build_messages(cls, input_data):
@@ -8,6 +8,7 @@ from dingo.model.llm.base_openai import BaseOpenAI
8
8
  from dingo.model.response.response_class import ResponseNameReason
9
9
  from dingo.utils import log
10
10
  from dingo.utils.exception import ConvertJsonError
11
+ from dingo.utils.image_loader import ImageLoader
11
12
 
12
13
 
13
14
  @Model.llm_register("LLMClassifyQR")
@@ -20,7 +21,7 @@ class LLMClassifyQR(BaseOpenAI):
20
21
  "evaluation_results": ""
21
22
  }
22
23
 
23
- _required_fields = [RequiredField.CONTENT]
24
+ _required_fields = [RequiredField.IMAGE]
24
25
  prompt = """
25
26
  'Classify the image into one of the following categories: "CAPTCHA", "QR code", or "Normal image". '
26
27
  'Return the type as the image category (CAPTCHA or QR code or Normal image) and the reason as the specific type of CAPTCHA or QR code. '
@@ -33,12 +34,13 @@ class LLMClassifyQR(BaseOpenAI):
33
34
 
34
35
  @classmethod
35
36
  def build_messages(cls, input_data: Data) -> List:
37
+ image_url = ImageLoader.encode_for_api(input_data.image)
36
38
  messages = [
37
39
  {
38
40
  "role": "user",
39
41
  "content": [
40
42
  {"type": "text", "text": cls.prompt},
41
- {"type": "image_url", "image_url": {"url": input_data.content}},
43
+ {"type": "image_url", "image_url": {"url": image_url}},
42
44
  ],
43
45
  }
44
46
  ]