examples.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. """演示如何使用 MinerU File转Markdown客户端的示例。"""
  2. import os
  3. import asyncio
  4. from mcp.client import MCPClient
  5. async def convert_file_url_example():
  6. """从 URL 转换 File 的示例。"""
  7. client = MCPClient("http://localhost:8000")
  8. # 转换单个 File URL
  9. result = await client.call(
  10. "convert_file_url", url="https://example.com/sample.pdf", enable_ocr=True
  11. )
  12. print(f"转换结果: {result}")
  13. # 转换多个 File URL
  14. urls = """
  15. https://example.com/doc1.pdf
  16. https://example.com/doc2.pdf
  17. """
  18. result = await client.call("convert_file_url", url=urls, enable_ocr=True)
  19. print(f"多个转换结果: {result}")
  20. async def convert_file_file_example():
  21. """转换本地 File 文件的示例。"""
  22. client = MCPClient("http://localhost:8000")
  23. # 获取测试 File 的绝对路径
  24. script_dir = os.path.dirname(os.path.abspath(__file__))
  25. project_root = os.path.dirname(os.path.dirname(os.path.dirname(script_dir)))
  26. test_file_path = os.path.join(project_root, "test_files", "test.pdf")
  27. # 转换单个 File 文件
  28. result = await client.call(
  29. "convert_file_file", file_path=test_file_path, enable_ocr=True
  30. )
  31. print(f"文件转换结果: {result}")
  32. async def get_api_status_example():
  33. """获取 API 状态的示例。"""
  34. client = MCPClient("http://localhost:8000")
  35. # 获取 API 状态
  36. status = await client.get_resource("status://api")
  37. print(f"API 状态: {status}")
  38. # 获取使用帮助
  39. help_text = await client.get_resource("help://usage")
  40. print(f"使用帮助: {help_text[:100]}...") # 显示前 100 个字符
  41. async def main():
  42. """运行所有示例。"""
  43. print("运行 File 到 Markdown 转换示例...")
  44. # 检查是否设置了 API_KEY
  45. if not os.environ.get("MINERU_API_KEY"):
  46. print("警告: MINERU_API_KEY 环境变量未设置。")
  47. print("使用以下命令设置: export MINERU_API_KEY=your_api_key")
  48. print("跳过需要 API 访问的示例...")
  49. # 仅获取 API 状态
  50. await get_api_status_example()
  51. else:
  52. # 运行所有示例
  53. await convert_file_url_example()
  54. await convert_file_file_example()
  55. await get_api_status_example()
  56. if __name__ == "__main__":
  57. asyncio.run(main())