test_converter.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. PDF Converter v2 测试脚本
  5. 测试API接口调用、zip文件处理和JSON转换功能
  6. """
  7. import asyncio
  8. import os
  9. import sys
  10. from pathlib import Path
  11. # 添加项目路径
  12. project_root = Path(__file__).parent.parent
  13. sys.path.insert(0, str(project_root))
  14. from pdf_converter_v2.processor.converter import convert_to_markdown
  15. from pdf_converter_v2.parser.json_converter import parse_markdown_to_json
  16. from pdf_converter_v2.utils.logging_config import get_logger
  17. logger = get_logger("pdf_converter_v2.test")
  18. async def test_api_conversion(input_file: str, output_dir: str = "./test_output"):
  19. """测试API转换功能"""
  20. print(f"\n{'='*60}")
  21. print(f"测试API转换功能")
  22. print(f"{'='*60}")
  23. print(f"输入文件: {input_file}")
  24. print(f"输出目录: {output_dir}")
  25. if not os.path.exists(input_file):
  26. print(f"❌ 错误: 输入文件不存在: {input_file}")
  27. return False
  28. try:
  29. result = await convert_to_markdown(
  30. input_file=input_file,
  31. output_dir=output_dir,
  32. max_pages=10,
  33. formula_enable=True,
  34. table_enable=True,
  35. language="ch",
  36. backend="vlm-vllm-async-engine",
  37. url="http://127.0.0.1:5282",
  38. embed_images=True,
  39. output_json=True, # 启用JSON转换
  40. start_page_id=0,
  41. end_page_id=99999,
  42. parse_method="auto",
  43. response_format_zip=True
  44. )
  45. if result:
  46. print(f"\n✅ 转换成功!")
  47. print(f" Markdown文件: {result.get('markdown_file')}")
  48. if result.get('json_file'):
  49. print(f" JSON文件: {result.get('json_file')}")
  50. if result.get('json_data'):
  51. doc_type = result['json_data'].get('document_type', 'unknown')
  52. print(f" 文档类型: {doc_type}")
  53. if doc_type != 'unknown' and result['json_data'].get('data'):
  54. data = result['json_data']['data']
  55. if doc_type == 'noise_detection':
  56. print(f" 项目名称: {data.get('project', '未找到')}")
  57. print(f" 噪声数据条数: {len(data.get('noise', []))}")
  58. elif doc_type == 'electromagnetic_detection':
  59. print(f" 项目名称: {data.get('project', '未找到')}")
  60. print(f" 电磁数据条数: {len(data.get('electricMagnetic', []))}")
  61. return True
  62. else:
  63. print(f"\n❌ 转换失败")
  64. return False
  65. except Exception as e:
  66. print(f"\n❌ 转换过程出错: {e}")
  67. import traceback
  68. traceback.print_exc()
  69. return False
  70. async def test_json_conversion_from_existing_md(md_file: str):
  71. """测试从现有md文件进行JSON转换"""
  72. print(f"\n{'='*60}")
  73. print(f"测试JSON转换功能(使用现有md文件)")
  74. print(f"{'='*60}")
  75. print(f"MD文件: {md_file}")
  76. if not os.path.exists(md_file):
  77. print(f"❌ 错误: MD文件不存在: {md_file}")
  78. return False
  79. try:
  80. # 读取md文件
  81. with open(md_file, 'r', encoding='utf-8') as f:
  82. markdown_content = f.read()
  83. print(f" MD内容长度: {len(markdown_content)} 字符")
  84. # 转换为JSON
  85. json_data = parse_markdown_to_json(
  86. markdown_content,
  87. first_page_image=None,
  88. output_dir=None
  89. )
  90. if json_data:
  91. doc_type = json_data.get('document_type', 'unknown')
  92. print(f"\n✅ JSON转换成功!")
  93. print(f" 文档类型: {doc_type}")
  94. if doc_type != 'unknown' and json_data.get('data'):
  95. data = json_data['data']
  96. if doc_type == 'noise_detection':
  97. print(f" 项目名称: {data.get('project', '未找到')}")
  98. print(f" 检测依据: {data.get('standardReferences', '未找到')}")
  99. print(f" 声级计型号: {data.get('soundLevelMeterMode', '未找到')}")
  100. print(f" 噪声数据条数: {len(data.get('noise', []))}")
  101. if data.get('noise'):
  102. print(f" 第一条数据: {data['noise'][0]}")
  103. elif doc_type == 'electromagnetic_detection':
  104. print(f" 项目名称: {data.get('project', '未找到')}")
  105. print(f" 监测依据: {data.get('standardReferences', '未找到')}")
  106. print(f" 电磁数据条数: {len(data.get('electricMagnetic', []))}")
  107. if data.get('electricMagnetic'):
  108. print(f" 第一条数据: {data['electricMagnetic'][0]}")
  109. else:
  110. print(f" ⚠️ 未识别到文档类型或数据为空")
  111. return True
  112. else:
  113. print(f"\n❌ JSON转换失败")
  114. return False
  115. except Exception as e:
  116. print(f"\n❌ JSON转换过程出错: {e}")
  117. import traceback
  118. traceback.print_exc()
  119. return False
  120. async def test_from_output_dir():
  121. """测试从output目录中的md文件进行JSON转换"""
  122. print(f"\n{'='*60}")
  123. print(f"测试从output目录中的md文件")
  124. print(f"{'='*60}")
  125. output_dir = Path(__file__).parent / "out"
  126. if not output_dir.exists():
  127. print(f"❌ 错误: output目录不存在: {output_dir}")
  128. return False
  129. md_files = list(output_dir.glob("*.md"))
  130. if not md_files:
  131. print(f"❌ 错误: 在output目录中未找到md文件")
  132. return False
  133. success_count = 0
  134. for md_file in md_files:
  135. print(f"\n处理文件: {md_file.name}")
  136. if await test_json_conversion_from_existing_md(str(md_file)):
  137. success_count += 1
  138. print(f"\n{'='*60}")
  139. print(f"总计: {success_count}/{len(md_files)} 个文件转换成功")
  140. print(f"{'='*60}")
  141. return success_count == len(md_files)
  142. async def main():
  143. """主测试函数"""
  144. print("\n" + "="*60)
  145. print("PDF Converter v2 测试脚本")
  146. print("="*60)
  147. # 解析命令行参数
  148. if len(sys.argv) > 1:
  149. input_file = sys.argv[1]
  150. output_dir = sys.argv[2] if len(sys.argv) > 2 else "./test_output"
  151. # 测试1: API转换测试
  152. print("\n【测试1】API接口转换测试")
  153. result = await test_api_conversion(input_file, output_dir)
  154. if result:
  155. print("\n✅ 所有测试通过!")
  156. else:
  157. print("\n❌ 测试失败!")
  158. sys.exit(1)
  159. else:
  160. # 如果没有提供输入文件,则测试从output目录中的md文件
  161. print("\n【测试】从output目录中的md文件进行JSON转换测试")
  162. print("提示: 如果要测试API转换,请提供PDF文件路径:")
  163. print(" python test_converter.py <pdf_file> [output_dir]")
  164. # 测试2: 从output目录测试
  165. result = await test_from_output_dir()
  166. if result:
  167. print("\n✅ 所有测试通过!")
  168. else:
  169. print("\n⚠️ 部分测试失败!")
  170. sys.exit(1)
  171. if __name__ == "__main__":
  172. asyncio.run(main())