Docgenie-API / api /test_api.py
Ahadhassan-2003
deploy: update HF Space
9650a1d
#!/usr/bin/env python3
"""
Test script for DocGenie API.
Verifies all components are properly installed and configured.
"""
import sys
import os
from pathlib import Path
def test_imports():
"""Test that all required modules can be imported."""
print("Testing imports...")
try:
import fastapi
print(" βœ“ FastAPI")
except ImportError as e:
print(f" βœ— FastAPI: {e}")
return False
try:
import uvicorn
print(" βœ“ Uvicorn")
except ImportError as e:
print(f" βœ— Uvicorn: {e}")
return False
try:
import pydantic
print(" βœ“ Pydantic")
except ImportError as e:
print(f" βœ— Pydantic: {e}")
return False
try:
import requests
print(" βœ“ Requests")
except ImportError as e:
print(f" βœ— Requests: {e}")
return False
try:
from PIL import Image
print(" βœ“ Pillow")
except ImportError as e:
print(f" βœ— Pillow: {e}")
return False
try:
from bs4 import BeautifulSoup
print(" βœ“ BeautifulSoup4")
except ImportError as e:
print(f" βœ— BeautifulSoup4: {e}")
return False
try:
from playwright.async_api import async_playwright
print(" βœ“ Playwright")
except ImportError as e:
print(f" βœ— Playwright: {e}")
return False
try:
import anthropic
print(" βœ“ Anthropic")
except ImportError as e:
print(f" βœ— Anthropic: {e}")
return False
try:
from docgenie import ENV
print(" βœ“ DocGenie")
except ImportError as e:
print(f" βœ— DocGenie: {e}")
return False
return True
def test_api_structure():
"""Test that API files are in place."""
print("\nTesting API structure...")
api_dir = Path(__file__).parent
files = {
"main.py": "Main API application",
"schemas.py": "Request/Response models",
"utils.py": "Processing utilities",
"README.md": "Documentation",
"__init__.py": "Package init"
}
all_present = True
for filename, description in files.items():
filepath = api_dir / filename
if filepath.exists():
print(f" βœ“ {filename}: {description}")
else:
print(f" βœ— {filename}: Missing!")
all_present = False
return all_present
def test_docgenie_integration():
"""Test integration with DocGenie modules."""
print("\nTesting DocGenie integration...")
try:
from docgenie import ENV
prompt_template = ENV.PROMPT_TEMPLATES_DIR / "ClaudeRefined12" / "seed-based-json.txt"
if prompt_template.exists():
print(f" βœ“ Prompt template found: {prompt_template}")
else:
print(f" βœ— Prompt template not found: {prompt_template}")
return False
# Test reading template
content = prompt_template.read_text(encoding='utf-8')
if "{language}" in content and "{doc_type}" in content:
print(" βœ“ Prompt template has required placeholders")
else:
print(" βœ— Prompt template missing placeholders")
return False
return True
except Exception as e:
print(f" βœ— Error: {e}")
return False
def test_environment():
"""Test environment configuration."""
print("\nTesting environment...")
api_key = os.getenv("ANTHROPIC_API_KEY")
if api_key:
print(f" βœ“ ANTHROPIC_API_KEY is set (length: {len(api_key)})")
else:
print(" ⚠ ANTHROPIC_API_KEY not set (optional for testing)")
python_version = sys.version_info
if python_version >= (3, 10):
print(f" βœ“ Python version: {python_version.major}.{python_version.minor}.{python_version.micro}")
else:
print(f" βœ— Python version: {python_version.major}.{python_version.minor}.{python_version.micro} (3.10+ required)")
return False
return True
def test_playwright_browsers():
"""Test if Playwright browsers are installed."""
print("\nTesting Playwright browsers...")
try:
import subprocess
result = subprocess.run(
["playwright", "show-trace", "--help"],
capture_output=True,
timeout=5
)
if result.returncode == 0:
print(" βœ“ Playwright CLI is available")
else:
print(" ⚠ Playwright CLI might have issues")
# Check if chromium is installed
# This is a basic check - actual browser installation is verified at runtime
print(" β„Ή Chromium will be verified when rendering PDFs")
return True
except FileNotFoundError:
print(" βœ— Playwright CLI not found")
return False
except Exception as e:
print(f" ⚠ Could not verify Playwright: {e}")
return True # Non-critical for this test
def test_api_modules():
"""Test that API modules can be imported."""
print("\nTesting API modules...")
try:
# Add parent and current directory to path
api_dir = Path(__file__).parent
project_root = api_dir.parent
sys.path.insert(0, str(project_root))
sys.path.insert(0, str(api_dir))
import schemas
print(" βœ“ schemas module")
import utils
print(" βœ“ utils module")
# Test that schema models exist
schemas.GenerateDocumentRequest
schemas.GenerateDocumentResponse
schemas.DocumentResult
print(" βœ“ All schema models defined")
return True
except Exception as e:
print(f" βœ— Error importing API modules: {e}")
return False
def main():
"""Run all tests."""
print("="*60)
print("DocGenie API - Test Suite")
print("="*60)
results = {
"Imports": test_imports(),
"API Structure": test_api_structure(),
"Environment": test_environment(),
"DocGenie Integration": test_docgenie_integration(),
"Playwright": test_playwright_browsers(),
"API Modules": test_api_modules()
}
print("\n" + "="*60)
print("Test Results Summary")
print("="*60)
for test_name, result in results.items():
status = "βœ“ PASS" if result else "βœ— FAIL"
print(f"{status}: {test_name}")
all_passed = all(results.values())
print("\n" + "="*60)
if all_passed:
print("βœ… All tests passed! API is ready to use.")
print("\nTo start the API:")
print(" cd api")
print(" python main.py")
print("\nThen visit: http://localhost:8000/docs")
else:
print("⚠️ Some tests failed. Please fix issues before running the API.")
print("\nCommon fixes:")
print(" uv sync # or: pip install -e .")
print(" playwright install chromium")
print(" export ANTHROPIC_API_KEY='your-key'")
print("="*60)
return 0 if all_passed else 1
if __name__ == "__main__":
sys.exit(main())