Skip to content

Commit be911c8

Browse files
committed
test demo_llm_webkit_with_preprocessed_html_evaluation()
2 parents 7fc576b + 6481088 commit be911c8

11 files changed

Lines changed: 273 additions & 2532 deletions

data/WebMainBench_dataset_sample2.jsonl

Lines changed: 2 additions & 0 deletions
Large diffs are not rendered by default.

examples/basic_usage.py

Lines changed: 70 additions & 158 deletions
Original file line numberDiff line numberDiff line change
@@ -947,163 +947,74 @@ def demo_multi_extraction():
947947

948948
def demo_llm_webkit_with_preprocessed_html_evaluation():
949949
"""演示LLM-WebKit预处理HTML功能的评测"""
950-
950+
951951
print("\n=== LLM-WebKit 预处理HTML功能演示 ===\n")
952-
952+
953953
# 设置日志
954954
setup_logging(level="INFO")
955+
956+
# 1. 从真实数据集加载包含预处理HTML的数据
957+
print("1. 从真实数据集加载预处理HTML数据...")
958+
959+
# 使用DataLoader加载真实的样本数据
960+
dataset_path = Path("data/WebMainBench_dataset_sample2.jsonl")
961+
print(f"📂 数据集文件: {dataset_path}")
962+
963+
if not dataset_path.exists():
964+
print(f"❌ 数据文件不存在: {dataset_path}")
965+
print("请确保已运行数据提取命令创建样本数据集")
966+
return
967+
968+
# 加载数据集
969+
dataset = DataLoader.load_jsonl(dataset_path, include_results=False)
970+
dataset.name = "real_preprocessed_html_test"
971+
dataset.description = "基于真实数据的预处理HTML功能测试"
955972

956-
# 1. 创建包含预处理HTML的测试数据集
957-
print("1. 创建包含预处理HTML的测试数据集...")
958-
959-
samples = []
960-
961-
# 样本1: 包含预处理的HTML(模拟第一阶段LLM简化后的结果)
962-
sample_1_data = {
963-
"id": "preprocessed_sample_1",
964-
"html": """<html><body><h1>原始复杂HTML</h1><p>这里是原始的复杂HTML内容...</p></body></html>""",
965-
# 这是关键:包含llm_webkit_html字段(预处理后的简化HTML)
966-
"llm_webkit_html": """
967-
<div _item_id="1">
968-
<h1>深度学习基础教程</h1>
969-
<p>深度学习是机器学习的一个重要分支,通过多层神经网络来学习数据的表征。</p>
970-
</div>
971-
<div _item_id="2">
972-
<h2>核心概念</h2>
973-
<p>神经网络由多个层组成,每层包含多个神经元。</p>
974-
</div>
975-
<div _item_id="3">
976-
<pre><code class="language-python">
977-
import torch
978-
import torch.nn as nn
979-
980-
class SimpleNet(nn.Module):
981-
def __init__(self):
982-
super().__init__()
983-
self.fc = nn.Linear(784, 10)
984-
985-
def forward(self, x):
986-
return self.fc(x)
987-
</code></pre>
988-
</div>
989-
""",
990-
"groundtruth_content": """# 深度学习基础教程
991-
992-
深度学习是机器学习的一个重要分支,通过多层神经网络来学习数据的表征。
993-
994-
## 核心概念
995-
996-
神经网络由多个层组成,每层包含多个神经元。
997-
998-
```python
999-
import torch
1000-
import torch.nn as nn
1001-
1002-
class SimpleNet(nn.Module):
1003-
def __init__(self):
1004-
super().__init__()
1005-
self.fc = nn.Linear(784, 10)
1006-
1007-
def forward(self, x):
1008-
return self.fc(x)
1009-
```""",
1010-
"groundtruth_content_list": [
1011-
{"type": "heading", "content": "深度学习基础教程", "level": 1},
1012-
{"type": "paragraph", "content": "深度学习是机器学习的一个重要分支,通过多层神经网络来学习数据的表征。"},
1013-
{"type": "heading", "content": "核心概念", "level": 2},
1014-
{"type": "paragraph", "content": "神经网络由多个层组成,每层包含多个神经元。"},
1015-
{"type": "code", "content": "import torch\nimport torch.nn as nn\n\nclass SimpleNet(nn.Module):\n def __init__(self):\n super().__init__()\n self.fc = nn.Linear(784, 10)\n \n def forward(self, x):\n return self.fc(x)", "language": "python"}
1016-
]
1017-
}
1018-
# samples.append(DataSample.from_dict(sample_1_data))
1019-
1020-
# 样本2: 包含表格的预处理HTML
1021-
sample_2_data = {
1022-
"id": "preprocessed_sample_2",
1023-
"html": """<html><body><h1>原始表格页面</h1><table>...</table></body></html>""",
1024-
"llm_webkit_html": """
1025-
<div _item_id="1">
1026-
<h1>模型性能对比</h1>
1027-
<p>以下是不同深度学习模型在CIFAR-10数据集上的表现:</p>
1028-
</div>
1029-
<div _item_id="2">
1030-
<table>
1031-
<thead>
1032-
<tr>
1033-
<th>模型</th>
1034-
<th>准确率</th>
1035-
<th>参数量</th>
1036-
</tr>
1037-
</thead>
1038-
<tbody>
1039-
<tr>
1040-
<td>ResNet-18</td>
1041-
<td>95.3%</td>
1042-
<td>11.7M</td>
1043-
</tr>
1044-
<tr>
1045-
<td>VGG-16</td>
1046-
<td>92.7%</td>
1047-
<td>138M</td>
1048-
</tr>
1049-
</tbody>
1050-
</table>
1051-
</div>
1052-
""",
1053-
"groundtruth_content": """# 模型性能对比
1054-
1055-
以下是不同深度学习模型在CIFAR-10数据集上的表现:
1056-
1057-
| 模型 | 准确率 | 参数量 |
1058-
|------|--------|--------|
1059-
| ResNet-18 | 95.3% | 11.7M |
1060-
| VGG-16 | 92.7% | 138M |""",
1061-
"groundtruth_content_list": [
1062-
{"type": "heading", "content": "模型性能对比", "level": 1},
1063-
{"type": "paragraph", "content": "以下是不同深度学习模型在CIFAR-10数据集上的表现:"},
1064-
{"type": "table", "content": "| 模型 | 准确率 | 参数量 |\n|------|--------|---------|\n| ResNet-18 | 95.3% | 11.7M |\n| VGG-16 | 92.7% | 138M |"}
1065-
]
1066-
}
1067-
# samples.append(DataSample.from_dict(sample_2_data))
1068-
1069-
# 创建数据集并添加样本
1070-
# dataset = BenchmarkDataset(name="preprocessed_html_test", description="预处理HTML功能测试数据集")
1071-
1072-
1073-
1074-
# 本地加载数据集
1075-
jsonl_file_path = "/home/lulindong/Pycharm_projects/cc/WebMainBench_llm-webkit_v1_WebMainBench_dataset_merge_with_llm_webkit.jsonl"
1076-
1077-
# 使用DataLoader加载本地JSONL数据
1078-
dataset = DataLoader.load_jsonl(jsonl_file_path)
1079-
# for sample in samples:
1080-
# dataset.add_sample(sample)
1081-
# 在评测前添加,验证抽取器是否使用了正确的HTML字段
1082-
1083-
1084-
print(f"✅ 测试数据集包含 {len(dataset)} 个样本")
1085-
print("📋 每个样本都包含:")
1086-
print(" - html: 原始复杂HTML")
1087-
print(" - llm_webkit_html: 预处理后的简化HTML(包含_item_id标记)")
1088-
print(" - groundtruth_content: 标准答案")
973+
974+
print(f"✅ 真实数据集加载成功,包含 {len(dataset)} 个样本")
975+
print("📋 真实数据样本包含:")
976+
print(" - html: 原始网页HTML")
977+
print(" - llm_webkit_html: LLM预处理后的简化HTML(包含_item_id标记)")
978+
print(" - groundtruth_content: 人工标注的标准答案")
979+
print(" - llm_webkit_md: LLM提取的markdown内容")
980+
981+
# 显示第一个样本的预览
982+
if len(dataset.samples) > 0:
983+
first_sample = dataset.samples[0]
984+
sample_dict = first_sample.to_dict()
985+
986+
print(f"\n🔍 第一个样本预览:")
987+
print(f" - ID: {sample_dict.get('track_id', 'N/A')}")
988+
print(f" - URL: {sample_dict.get('url', 'N/A')[:60]}...")
989+
990+
# 检查是否有llm_webkit_html字段
991+
if hasattr(first_sample, 'llm_webkit_html') or 'llm_webkit_html' in sample_dict:
992+
llm_html = getattr(first_sample, 'llm_webkit_html', sample_dict.get('llm_webkit_html', ''))
993+
if llm_html:
994+
print(f" - 预处理HTML长度: {len(llm_html)} 字符")
995+
print(f" - 包含_item_id数量: {llm_html.count('_item_id')}")
996+
else:
997+
print(f" - ⚠️ 预处理HTML字段为空")
998+
else:
999+
print(f" - ❌ 未找到llm_webkit_html字段")
10891000
print()
1090-
1001+
10911002
# 2. 创建预处理HTML模式的LLM-WebKit抽取器
10921003
print("2. 创建预处理HTML模式的LLM-WebKit抽取器...")
1093-
1004+
10941005
config = {
10951006
"use_preprocessed_html": True, # 🔑 关键配置:启用预处理HTML模式
10961007
"preprocessed_html_field": "llm_webkit_html" # 指定预处理HTML字段名
10971008
}
1098-
1009+
10991010
extractor = ExtractorFactory.create("llm-webkit", config=config)
11001011
print(f"✅ 抽取器创建成功")
11011012
print(f"📋 配置信息:")
11021013
print(f" - use_preprocessed_html: {extractor.inference_config.use_preprocessed_html}")
11031014
print(f" - preprocessed_html_field: {extractor.inference_config.preprocessed_html_field}")
11041015
print(f" - 跳过LLM推理: 是(直接处理预处理HTML)")
11051016
print()
1106-
1017+
11071018
# 3. 性能对比:展示预处理HTML模式的优势
11081019
print("3. 性能优势演示...")
11091020
print("🚀 预处理HTML模式的优势:")
@@ -1112,36 +1023,35 @@ def forward(self, x):
11121023
print(" ✅ 只需要基础的llm_web_kit依赖")
11131024
print(" ✅ 适合批量处理已预处理的数据")
11141025
print()
1115-
1026+
11161027
# 4. 运行评测
11171028
print("4. 开始评测...")
11181029
print("=" * 50)
1119-
1030+
11201031
evaluator = Evaluator()
11211032
result = evaluator.evaluate(
11221033
dataset=dataset,
11231034
extractor=extractor,
11241035
max_samples=None
11251036
)
1126-
1037+
11271038
# 5. 显示评测结果
11281039
print("\n5. 📊 预处理HTML模式评测结果:")
11291040
print("=" * 50)
1130-
1041+
11311042
results_dict = result.to_dict()
11321043
metrics = results_dict.get('overall_metrics', {})
1133-
1044+
11341045
# 显示关键指标
11351046
print(f"\n🏆 综合指标:")
11361047
print(f" overall: {metrics.get('overall', 0):.4f}")
1137-
1048+
11381049
print(f"\n📝 内容提取质量:")
1139-
print(f" formula_edit: {metrics.get('formula_edit', 0):.4f}")
11401050
print(f" text_edit: {metrics.get('text_edit', 0):.4f}")
11411051
print(f" code_edit: {metrics.get('code_edit', 0):.4f}")
11421052
print(f" table_edit: {metrics.get('table_edit', 0):.4f}")
11431053
print(f" table_TEDS: {metrics.get('table_TEDS', 0):.4f}")
1144-
1054+
11451055
print(f"\n⚡ 性能统计:")
11461056
sample_results = results_dict.get('sample_results', [])
11471057
if sample_results:
@@ -1150,14 +1060,14 @@ def forward(self, x):
11501060
avg_time = sum(extraction_times) / len(extraction_times)
11511061
print(f" 平均提取时间: {avg_time:.3f}秒")
11521062
print(f" 处理速度: {1/avg_time:.1f}样本/秒")
1153-
1063+
11541064
success_count = len([s for s in sample_results if s.get('extraction_success', False)])
11551065
print(f" 成功样本数: {success_count}/{len(dataset)}")
1156-
1066+
11571067
# 6. 展示样本提取结果
11581068
print(f"\n6. 📄 样本提取结果预览:")
11591069
print("-" * 50)
1160-
1070+
11611071
for i, sample_result in enumerate(sample_results[:2]): # 只显示前2个样本
11621072
print(f"\n样本 {i+1}: {sample_result.get('sample_id', 'Unknown')}")
11631073
if sample_result.get('extraction_success'):
@@ -1168,21 +1078,22 @@ def forward(self, x):
11681078
print(f" ⏱️ 提取时间: {sample_result.get('extraction_time', 0):.3f}秒")
11691079
else:
11701080
print(f" ❌ 提取失败")
1081+
11711082
# 7. 保存结果
11721083
print(f"\n7. 💾 保存评测结果...")
1173-
1084+
11741085
results_dir = Path("results")
11751086
results_dir.mkdir(exist_ok=True)
1176-
1087+
11771088
results_path = results_dir / "preprocessed_html_evaluation_results.json"
11781089
report_path = results_dir / "preprocessed_html_evaluation_report.csv"
1179-
1090+
11801091
DataSaver.save_evaluation_results(result, results_path)
11811092
DataSaver.save_summary_report(result, report_path)
1182-
1093+
11831094
print(f"✅ 详细结果已保存到: {results_path}")
11841095
print(f"✅ CSV报告已保存到: {report_path}")
1185-
1096+
11861097
# 8. 使用建议
11871098
print(f"\n8. 💡 实际使用建议:")
11881099
print("=" * 50)
@@ -1200,17 +1111,18 @@ def forward(self, x):
12001111
print("⚙️ 配置参数说明:")
12011112
print(" - use_preprocessed_html: True/False")
12021113
print(" - preprocessed_html_field: 字段名(默认'llm_webkit_html')")
1203-
1114+
12041115
print("\n✅ 预处理HTML功能演示完成!")
12051116

1117+
12061118
if __name__ == "__main__":
12071119
try:
12081120
# demo_basic_mock_evaluation()
12091121
# demo_llm_webkit_evaluation() # 使用LLM-WebKit评测示例
1210-
# demo_llm_webkit_with_preprocessed_html_evaluation()
1122+
demo_llm_webkit_with_preprocessed_html_evaluation()
12111123
# demo_extractor_comparison()
12121124
# demo_dataset_with_extraction() # 演示保存带有抽取内容的数据集
1213-
demo_multi_extraction() # 演示多个抽取器同时评测
1125+
# demo_multi_extraction() # 演示多个抽取器同时评测
12141126
# demo_lld_workers_extraction()
12151127
print("\n✅ 示例运行完成!")
12161128

0 commit comments

Comments
 (0)