File size: 5,987 Bytes
d47cb66 22473f8 d47cb66 1305a78 d47cb66 1305a78 d47cb66 22473f8 d47cb66 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 |
#!/usr/bin/env python3
"""
Test script to verify OpenRouter API key and translation functionality
"""
import os
import asyncio
import aiohttp
from translator import DocumentTranslator
async def test_api_key():
"""Test if the API key is working"""
print("π Testing OpenRouter API key...")
api_key = os.getenv("OPENROUTER_API_KEY")
if not api_key:
print("β OPENROUTER_API_KEY environment variable not set!")
print("Please set it with: set OPENROUTER_API_KEY=your_key_here")
return False
print(f"β
API key found: {api_key[:10]}...")
# Test API connection
try:
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
"HTTP-Referer": "https://huggingface.co",
"X-Title": "Document Translator"
}
async with aiohttp.ClientSession() as session:
async with session.get(
"https://openrouter.ai/api/v1/models",
headers=headers
) as response:
if response.status == 200:
print("β
API connection successful!")
return True
elif response.status == 429:
error_text = await response.text()
print(f"β οΈ Rate limit exceeded: {error_text}")
print("This is normal for free models. Try again later or use a different model.")
return True # API key is valid, just rate limited
else:
print(f"β API connection failed: {response.status}")
error_text = await response.text()
print(f"Error: {error_text}")
return False
except Exception as e:
print(f"β API test failed: {e}")
return False
async def test_translation():
"""Test basic translation functionality"""
print("\nπ Testing translation functionality...")
translator = DocumentTranslator()
if not translator.is_ready():
print("β Translator not ready - API key issue")
return False
try:
# Get available models first
models = await translator.get_available_models()
if not models:
print("β No models available")
return False
selected_model = models[0]["id"]
print(f"Using model: {selected_model}")
# Test simple translation
test_text = "Hello, this is a test document."
print(f"Original text: {test_text}")
translated = await translator.translate_text(
text=test_text,
model=selected_model,
source_lang="en",
target_lang="ar"
)
print(f"Translated text: {translated}")
if translated != test_text:
print("β
Translation working correctly!")
return True
else:
print("β Translation returned original text - may indicate an issue")
return False
except Exception as e:
print(f"β Translation test failed: {e}")
return False
async def test_specific_model(model_id: str):
"""Test a specific model for translation"""
print(f"\nπ§ͺ Testing model: {model_id}")
api_key = os.getenv("OPENROUTER_API_KEY")
if not api_key:
print("β OPENROUTER_API_KEY not set")
return False
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
"HTTP-Referer": "https://huggingface.co",
"X-Title": "Document Translator"
}
test_payload = {
"model": model_id,
"messages": [
{"role": "system", "content": "You are a professional translator."},
{"role": "user", "content": "Translate 'Hello world' to Arabic"}
],
"max_tokens": 50,
"temperature": 0.1
}
try:
async with aiohttp.ClientSession() as session:
async with session.post(
"https://openrouter.ai/api/v1/chat/completions",
headers=headers,
json=test_payload
) as response:
if response.status == 200:
data = await response.json()
result = data["choices"][0]["message"]["content"]
print(f"β
Model works! Translation: {result}")
return True
elif response.status == 429:
error_text = await response.text()
print(f"β οΈ Model rate limited: {error_text}")
print("Try again later or use a different model.")
return True # Model exists, just rate limited
else:
error_text = await response.text()
print(f"β Model test failed: {response.status} - {error_text}")
return False
except Exception as e:
print(f"β Test error: {e}")
return False
async def main():
"""Run all tests"""
print("π§ͺ Testing Document Translator Setup\n")
# Test API key
api_ok = await test_api_key()
if api_ok:
# Test translation
translation_ok = await test_translation()
if translation_ok:
print("\nπ All tests passed! The translator should work correctly.")
else:
print("\nβ οΈ Translation test failed. Check the logs for details.")
else:
print("\nβ API key test failed. Please check your OPENROUTER_API_KEY.")
print("\nπ Next steps:")
print("1. Make sure OPENROUTER_API_KEY is set correctly")
print("2. Upload a PDF or DOCX file to test the full workflow")
print("3. Check the translation.log file for detailed logs")
if __name__ == "__main__":
asyncio.run(main()) |