You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

171 lines
5.8 KiB

3 weeks ago
#!/usr/bin/env python3
"""
3 weeks ago
Office Document Parsing Test Script for RAG-Anything
3 weeks ago
3 weeks ago
This script demonstrates how to parse various Office document formats
using MinerU, including DOC, DOCX, PPT, PPTX, XLS, and XLSX files.
3 weeks ago
3 weeks ago
Requirements:
- LibreOffice installed on the system
- RAG-Anything package
3 weeks ago
3 weeks ago
Usage:
python office_document_test.py --file path/to/office/document.docx
3 weeks ago
"""
import argparse
import sys
from pathlib import Path
3 weeks ago
from raganything import RAGAnything
3 weeks ago
def check_libreoffice_installation():
3 weeks ago
"""Check if LibreOffice is installed and available"""
3 weeks ago
import subprocess
for cmd in ["libreoffice", "soffice"]:
try:
result = subprocess.run(
3 weeks ago
[cmd, "--version"], capture_output=True, check=True, timeout=10
3 weeks ago
)
3 weeks ago
print(f"✅ LibreOffice found: {result.stdout.decode().strip()}")
3 weeks ago
return True
except (
subprocess.CalledProcessError,
FileNotFoundError,
subprocess.TimeoutExpired,
):
continue
3 weeks ago
print("❌ LibreOffice not found. Please install LibreOffice:")
print(" - Windows: Download from https://www.libreoffice.org/download/download/")
3 weeks ago
print(" - macOS: brew install --cask libreoffice")
print(" - Ubuntu/Debian: sudo apt-get install libreoffice")
print(" - CentOS/RHEL: sudo yum install libreoffice")
return False
def test_office_document_parsing(file_path: str):
3 weeks ago
"""Test Office document parsing with MinerU"""
print(f"🧪 Testing Office document parsing: {file_path}")
# Check if file exists and is a supported Office format
3 weeks ago
file_path = Path(file_path)
if not file_path.exists():
3 weeks ago
print(f"❌ File does not exist: {file_path}")
3 weeks ago
return False
supported_extensions = {".doc", ".docx", ".ppt", ".pptx", ".xls", ".xlsx"}
if file_path.suffix.lower() not in supported_extensions:
3 weeks ago
print(f"❌ Unsupported file format: {file_path.suffix}")
print(f" Supported formats: {', '.join(supported_extensions)}")
3 weeks ago
return False
3 weeks ago
print(f"📄 File format: {file_path.suffix.upper()}")
print(f"📏 File size: {file_path.stat().st_size / 1024:.1f} KB")
3 weeks ago
3 weeks ago
# Initialize RAGAnything (only for parsing functionality)
rag = RAGAnything()
3 weeks ago
try:
3 weeks ago
# Test document parsing with MinerU
print("\n🔄 Testing document parsing with MinerU...")
3 weeks ago
content_list, md_content = rag.parse_document(
file_path=str(file_path),
3 weeks ago
output_dir="./test_output",
3 weeks ago
parse_method="auto",
display_stats=True,
)
3 weeks ago
print("✅ Parsing successful!")
print(f" 📊 Content blocks: {len(content_list)}")
print(f" 📝 Markdown length: {len(md_content)} characters")
# Analyze content types
3 weeks ago
content_types = {}
for item in content_list:
if isinstance(item, dict):
content_type = item.get("type", "unknown")
content_types[content_type] = content_types.get(content_type, 0) + 1
if content_types:
3 weeks ago
print(" 📋 Content distribution:")
3 weeks ago
for content_type, count in sorted(content_types.items()):
print(f"{content_type}: {count}")
3 weeks ago
# Display some parsed content preview
3 weeks ago
if md_content.strip():
3 weeks ago
print("\n📄 Parsed content preview (first 500 characters):")
3 weeks ago
preview = md_content.strip()[:500]
print(f" {preview}{'...' if len(md_content) > 500 else ''}")
3 weeks ago
# Display some structured content examples
3 weeks ago
text_items = [
item
for item in content_list
if isinstance(item, dict) and item.get("type") == "text"
]
if text_items:
3 weeks ago
print("\n📝 Sample text blocks:")
3 weeks ago
for i, item in enumerate(text_items[:3], 1):
text_content = item.get("text", "")
if text_content.strip():
preview = text_content.strip()[:200]
print(
f" {i}. {preview}{'...' if len(text_content) > 200 else ''}"
)
3 weeks ago
# Check for images
3 weeks ago
image_items = [
item
for item in content_list
if isinstance(item, dict) and item.get("type") == "image"
]
if image_items:
3 weeks ago
print(f"\n🖼️ Found {len(image_items)} image(s):")
3 weeks ago
for i, item in enumerate(image_items, 1):
3 weeks ago
print(f" {i}. Image path: {item.get('img_path', 'N/A')}")
3 weeks ago
3 weeks ago
# Check for tables
3 weeks ago
table_items = [
item
for item in content_list
if isinstance(item, dict) and item.get("type") == "table"
]
if table_items:
3 weeks ago
print(f"\n📊 Found {len(table_items)} table(s):")
3 weeks ago
for i, item in enumerate(table_items, 1):
table_body = item.get("table_body", "")
row_count = len(table_body.split("\n"))
3 weeks ago
print(f" {i}. Table with {row_count} rows")
3 weeks ago
3 weeks ago
print("\n🎉 Office document parsing test completed successfully!")
print("📁 Output files saved to: ./test_output")
3 weeks ago
return True
except Exception as e:
3 weeks ago
print(f"\n❌ Office document parsing failed: {str(e)}")
3 weeks ago
import traceback
3 weeks ago
print(f" Full error: {traceback.format_exc()}")
3 weeks ago
return False
def main():
3 weeks ago
file=r"D:\dsWork\dsProject\dsRagAnything\Txt\小学数学教学中的若干问题_MATH_1.docx"
3 weeks ago
3 weeks ago
# Run the parsing test
3 weeks ago
try:
3 weeks ago
success = test_office_document_parsing(file)
3 weeks ago
return 0 if success else 1
except KeyboardInterrupt:
3 weeks ago
print("\n⏹️ Test interrupted by user")
3 weeks ago
return 1
except Exception as e:
3 weeks ago
print(f"\n❌ Unexpected error: {str(e)}")
3 weeks ago
return 1
if __name__ == "__main__":
3 weeks ago
sys.exit(main())