diff --git a/scripts/README.md b/scripts/README.md index 9c61d23..4aa09f1 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -6,12 +6,13 @@ ### 数据处理脚本 -| 脚本 | 功能 | 添加字段 | +| 脚本 | 功能 | 添加/处理字段 | |------|------|----------| | `statics.py` | 统计分析 | `meta.level`, `meta.table`, `meta.code`, `meta.equation` | | `language_classify.py` | 语言检测 | `meta.language` | | `style_classify.py` | 类型分类 | `meta.style` | -| `process_dataset.sh` | 一键处理 | 上述所有字段 | +| `simplify_meta.py` | 简化字段 | 保留核心字段,移除统计信息 | +| `process_dataset.sh` | 一键处理 | 上述所有步骤 | ### 数据管理脚本 @@ -64,9 +65,14 @@ python scripts/language_classify.py \ # 步骤 3: 类型分类 python scripts/style_classify.py \ data/step2.jsonl \ - --output data/final.jsonl \ + --output data/step3.jsonl \ --api-key YOUR_API_KEY \ --base-url https://api.deepseek.com/v1 + +# 步骤 4: 简化 meta 字段(无需 API) +python scripts/simplify_meta.py \ + data/step3.jsonl \ + --output data/final.jsonl ``` ## 🔑 环境变量 @@ -88,6 +94,16 @@ python scripts/statics.py --input --output **无需 API 密钥** +### simplify_meta.py + +```bash +python scripts/simplify_meta.py --output +``` + +**功能:** 简化 meta 字段,只保留核心字段(language, style, level, table, code, equation),移除复杂的统计信息 + +**无需 API 密钥** + ### language_classify.py ```bash diff --git a/scripts/process_dataset.sh b/scripts/process_dataset.sh index 6452466..23ba517 100755 --- a/scripts/process_dataset.sh +++ b/scripts/process_dataset.sh @@ -7,6 +7,7 @@ # - meta.level, meta.table, meta.code, meta.equation (通过 statics.py) # - meta.language (通过 language_classify.py) # - meta.style (通过 style_classify.py) +# - 简化 meta 字段 (通过 simplify_meta.py) # # 使用方法: # ./scripts/process_dataset.sh [base_url] @@ -83,6 +84,7 @@ TIMESTAMP=$(date +%Y%m%d_%H%M%S) TEMP_DIR="data/temp_${TIMESTAMP}" STEP1_OUTPUT="${TEMP_DIR}/step1_with_stats.jsonl" STEP2_OUTPUT="${TEMP_DIR}/step2_with_language.jsonl" +STEP3_OUTPUT="${TEMP_DIR}/step3_with_style.jsonl" # 验证输入文件 if [ ! -f "$INPUT_FILE" ]; then @@ -110,7 +112,7 @@ echo "" # ============================================================================ # 步骤 1: 添加统计字段 # ============================================================================ -print_step "📊 步骤 1/3: 计算统计字段 (level, table, code, equation)" +print_step "📊 步骤 1/4: 计算统计字段 (level, table, code, equation)" if python scripts/statics.py --input "$INPUT_FILE" --output "$STEP1_OUTPUT"; then STEP1_LINES=$(wc -l < "$STEP1_OUTPUT" | tr -d ' ') @@ -129,7 +131,7 @@ fi # ============================================================================ # 步骤 2: 添加语言字段 # ============================================================================ -print_step "🌐 步骤 2/3: 检测语言 (language)" +print_step "🌐 步骤 2/4: 检测语言 (language)" export OPENAI_API_KEY="$API_KEY" @@ -156,21 +158,21 @@ fi # ============================================================================ # 步骤 3: 添加网页类型字段 # ============================================================================ -print_step "🎨 步骤 3/3: 分类网页类型 (style)" +print_step "🎨 步骤 3/4: 分类网页类型 (style)" if python scripts/style_classify.py \ "$STEP2_OUTPUT" \ - --output "$FINAL_OUTPUT" \ + --output "$STEP3_OUTPUT" \ --api-key "$API_KEY" \ --base-url "$BASE_URL" \ --batch-size "$BATCH_SIZE"; then - FINAL_LINES=$(wc -l < "$FINAL_OUTPUT" | tr -d ' ') - print_success "步骤 3 完成!处理了 $FINAL_LINES 条数据" + STEP3_LINES=$(wc -l < "$STEP3_OUTPUT" | tr -d ' ') + print_success "步骤 3 完成!处理了 $STEP3_LINES 条数据" # 验证数据完整性 - if [ "$STEP2_LINES" -ne "$FINAL_LINES" ]; then - print_warning "数据行数不一致!输入: $STEP2_LINES, 输出: $FINAL_LINES" + if [ "$STEP2_LINES" -ne "$STEP3_LINES" ]; then + print_warning "数据行数不一致!输入: $STEP2_LINES, 输出: $STEP3_LINES" fi else print_error "步骤 3 失败!" @@ -178,6 +180,28 @@ else exit 1 fi +# ============================================================================ +# 步骤 4: 简化 meta 字段 +# ============================================================================ +print_step "🔧 步骤 4/4: 简化 meta 字段 (只保留核心字段)" + +if python scripts/simplify_meta.py \ + "$STEP3_OUTPUT" \ + --output "$FINAL_OUTPUT"; then + + FINAL_LINES=$(wc -l < "$FINAL_OUTPUT" | tr -d ' ') + print_success "步骤 4 完成!处理了 $FINAL_LINES 条数据" + + # 验证数据完整性 + if [ "$STEP3_LINES" -ne "$FINAL_LINES" ]; then + print_warning "数据行数不一致!输入: $STEP3_LINES, 输出: $FINAL_LINES" + fi +else + print_error "步骤 4 失败!" + print_warning "保留中间文件: $STEP3_OUTPUT" + exit 1 +fi + # ============================================================================ # 完成与清理 # ============================================================================ @@ -199,7 +223,7 @@ fi # 显示输出文件示例 print_step "📋 输出数据示例" -print_info "查看第一条数据的 meta 字段:" +print_info "查看第一条数据的 meta 字段(已简化):" echo "" head -n 1 "$FINAL_OUTPUT" | python -c " import json @@ -208,8 +232,10 @@ import sys data = json.loads(sys.stdin.read()) meta = data.get('meta', {}) -print('Meta 字段内容:') +print('Meta 字段内容(已简化):') print(json.dumps(meta, indent=2, ensure_ascii=False)) +print() +print('包含字段:', ', '.join(meta.keys())) " print_success "全部完成!🎊" diff --git a/scripts/simplify_meta.py b/scripts/simplify_meta.py new file mode 100644 index 0000000..ea0d179 --- /dev/null +++ b/scripts/simplify_meta.py @@ -0,0 +1,239 @@ +#!/usr/bin/env python3 +""" +简化meta字段工具 +只保留指定的meta字段,移除其他复杂的统计信息 +""" + +import json +import argparse +import sys +from pathlib import Path +from typing import Dict, Any, List + +class MetaSimplifier: + """Meta字段简化器""" + + def __init__(self): + """初始化简化器""" + self.processed_count = 0 + self.error_count = 0 + + def simplify_meta(self, data: Dict[str, Any]) -> Dict[str, Any]: + """ + 简化meta字段 + + Args: + data: 原始数据记录 + + Returns: + 简化后的数据记录 + """ + if 'meta' not in data: + return data + + original_meta = data['meta'] + + # 构建简化的meta字段 + simplified_meta = {} + + # 保留指定字段 + if 'language' in original_meta: + simplified_meta['language'] = original_meta['language'] + + if 'table' in original_meta: + simplified_meta['table'] = original_meta['table'] + else: + simplified_meta['table'] = [] + + if 'code' in original_meta: + simplified_meta['code'] = original_meta['code'] + else: + simplified_meta['code'] = [] + + if 'equation' in original_meta: + simplified_meta['equation'] = original_meta['equation'] + else: + simplified_meta['equation'] = [] + + if 'level' in original_meta: + simplified_meta['level'] = original_meta['level'] + + # 处理style字段 - 只保留category值作为style + if 'style' in original_meta and isinstance(original_meta['style'], dict): + style_category = original_meta['style'].get('category', 'Other') + simplified_meta['style'] = style_category + elif 'style' in original_meta and isinstance(original_meta['style'], str): + # 如果style已经是字符串,直接使用 + simplified_meta['style'] = original_meta['style'] + else: + simplified_meta['style'] = 'Other' + + # 更新数据记录 + data['meta'] = simplified_meta + return data + + def process_file(self, input_file: str, output_file: str) -> None: + """ + 处理文件,简化meta字段 + + Args: + input_file: 输入文件路径 + output_file: 输出文件路径 + """ + print(f"📄 正在处理文件: {input_file}") + print(f"📄 输出文件: {output_file}") + + try: + with open(input_file, 'r', encoding='utf-8') as infile, \ + open(output_file, 'w', encoding='utf-8') as outfile: + + for line_num, line in enumerate(infile, 1): + if not line.strip(): + continue + + try: + data = json.loads(line) + + # 简化meta字段 + simplified_data = self.simplify_meta(data) + + # 写入输出文件 + outfile.write(json.dumps(simplified_data, ensure_ascii=False) + '\n') + + self.processed_count += 1 + + if line_num % 1000 == 0: + print(f" 已处理 {line_num:,} 条数据...") + + except json.JSONDecodeError as e: + print(f"⚠️ 第{line_num}行JSON解析错误: {e}") + self.error_count += 1 + continue + except Exception as e: + print(f"⚠️ 第{line_num}行处理错误: {e}") + self.error_count += 1 + continue + + except FileNotFoundError: + print(f"❌ 文件未找到: {input_file}") + sys.exit(1) + except Exception as e: + print(f"❌ 处理文件时出错: {e}") + sys.exit(1) + + def print_summary(self) -> None: + """打印处理统计摘要""" + print(f"\n📊 处理统计摘要:") + print(f" 成功处理记录数: {self.processed_count:,}") + print(f" 错误记录数: {self.error_count:,}") + + if self.processed_count > 0: + success_rate = (self.processed_count / (self.processed_count + self.error_count)) * 100 + print(f" 成功率: {success_rate:.2f}%") + + +def show_before_after_example(input_file: str) -> None: + """ + 显示简化前后的示例对比 + + Args: + input_file: 输入文件路径 + """ + print("\n📋 简化前后对比示例:") + + try: + with open(input_file, 'r', encoding='utf-8') as f: + # 读取第一条记录 + for line in f: + if line.strip(): + data = json.loads(line) + + if 'meta' in data: + print("\n🔍 简化前的meta字段:") + print(json.dumps(data['meta'], ensure_ascii=False, indent=2)[:500] + "...") + + # 简化 + simplifier = MetaSimplifier() + simplified_data = simplifier.simplify_meta(data.copy()) + + print("\n✨ 简化后的meta字段:") + print(json.dumps(simplified_data['meta'], ensure_ascii=False, indent=2)) + + break + + except Exception as e: + print(f"⚠️ 无法显示示例: {e}") + + +def main(): + """主函数""" + parser = argparse.ArgumentParser( + description="简化meta字段,只保留指定的字段", + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog=""" +简化后的meta字段包含: + - language: str - 语言标识 + - table: list[str] - 表格相关信息 + - code: list[str] - 代码相关信息 + - equation: list[str] - 公式相关信息 + - level: str - 复杂度级别 + - style: str - 网页类型(原meta.style.category) + +示例用法: + # 基本简化 + python scripts/simplify_meta.py \\ + data/WebMainBench_7887_with_meta.jsonl \\ + --output data/WebMainBench_7887_simplified.jsonl + + # 显示简化示例 + python scripts/simplify_meta.py \\ + data/WebMainBench_7887_with_meta.jsonl \\ + --output data/WebMainBench_7887_simplified.jsonl \\ + --show-example + """ + ) + + parser.add_argument( + "input_file", + help="输入JSONL文件路径" + ) + + parser.add_argument( + "--output", "-o", + required=True, + help="输出简化后的JSONL文件路径" + ) + + parser.add_argument( + "--show-example", + action="store_true", + help="显示简化前后的示例对比" + ) + + args = parser.parse_args() + + # 验证输入文件 + if not Path(args.input_file).exists(): + print(f"❌ 输入文件不存在: {args.input_file}") + sys.exit(1) + + # 显示示例 + if args.show_example: + show_before_after_example(args.input_file) + print("\n" + "="*60) + + # 创建简化器 + simplifier = MetaSimplifier() + + # 处理文件 + simplifier.process_file(args.input_file, args.output) + + # 打印统计摘要 + simplifier.print_summary() + + print(f"\n✅ 简化完成! 输出文件: {args.output}") + + +if __name__ == "__main__": + main() +