Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 99 additions & 0 deletions examples/manual_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Manual test for translation logic without external dependencies."""

import re

def test_russian_detection():
"""Test Russian character detection logic."""
test_cases = [
("Как перевести hello на английский?", True),
("How to translate красота?", False),
("как переводится beautiful", True),
("translate house", False),
("перевод машина", True),
]

print("Testing Russian character detection:")
print("-" * 40)

for text, expected in test_cases:
is_russian = bool(re.search(r'[а-яё]', text, re.IGNORECASE))
result = "✓" if is_russian == expected else "✗"
print(f"{result} '{text}' -> Russian: {is_russian} (expected: {expected})")

print()

def test_word_extraction():
"""Test word extraction from various patterns."""
patterns_and_tests = [
# Pattern similar to TRANSLATE_TO_ENGLISH_RU
(r'(как перевести|как переводится)\s+(.+?)\s+(на английский|на англ)',
"Как перевести hello на английский?", "hello"),

# Pattern similar to TRANSLATE_TO_RUSSIAN_RU
(r'(как переводится|как перевести)\s+(.+?)(\?|$)',
"Как переводится beautiful?", "beautiful"),

# Pattern similar to TRANSLATE_TO_ENGLISH_EN
(r'(how to translate|what is translation of)\s+(.+?)(\?|$)',
"How to translate красота?", "красота"),

# Pattern similar to TRANSLATE_WORD
(r'(translate|перевести|переводить|перевод)\s+(.+?)(\?|$)',
"translate house", "house"),
]

print("Testing word extraction patterns:")
print("-" * 40)

for pattern, text, expected_word in patterns_and_tests:
match = re.search(pattern, text, re.IGNORECASE)
if match:
extracted = match.group(2).strip()
result = "✓" if extracted == expected_word else "✗"
print(f"{result} '{text}' -> '{extracted}' (expected: '{expected_word}')")
else:
print(f"✗ '{text}' -> No match")

print()

def test_language_logic():
"""Test the language detection and translation direction logic."""
print("Testing translation direction logic (updated):")
print("-" * 40)

test_cases = [
("Как перевести hello на английский?", "hello", "en->ru"),
("How to translate красота?", "красота", "ru->en"),
("Как переводится beautiful?", "beautiful", "en->ru"),
("translate house", "house", "en->ru"),
("перевод машина", "машина", "ru->en"),
]

for msg, word, expected_direction in test_cases:
# Use updated logic: check message without the word
message_without_word = msg.replace(word, '')
is_russian_message = bool(re.search(r'[а-яё]', message_without_word, re.IGNORECASE))
word_is_russian = bool(re.search(r'[а-яё]', word, re.IGNORECASE))

# Simplified logic: translate based on word language
if word_is_russian:
source_lang = 'ru'
target_lang = 'en'
else:
source_lang = 'en'
target_lang = 'ru'

actual_direction = f"{source_lang}->{target_lang}"

result = "✓" if expected_direction == actual_direction else "✗"
print(f"{result} '{msg}' with word '{word}':")
print(f" Expected: {expected_direction}")
print(f" Actual: {actual_direction}")
print()

if __name__ == '__main__':
test_russian_detection()
test_word_extraction()
test_language_logic()
44 changes: 44 additions & 0 deletions examples/test_api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Test the actual translation API."""

import json
import urllib.request
import urllib.parse

def test_translation_api():
"""Test MyMemory translation API."""
print("Testing MyMemory Translation API:")
print("=" * 40)

test_cases = [
('hello', 'en', 'ru'),
('beautiful', 'en', 'ru'),
('красота', 'ru', 'en'),
('дом', 'ru', 'en'),
('house', 'en', 'ru'),
]

for word, source, target in test_cases:
try:
# URL encode the word to handle special characters
encoded_word = urllib.parse.quote(word)
url = f"https://api.mymemory.translated.net/get?q={encoded_word}&langpair={source}|{target}"

print(f"\nTranslating '{word}' from {source} to {target}...")
print(f"URL: {url}")

with urllib.request.urlopen(url, timeout=10) as response:
data = json.loads(response.read().decode())

if data.get('responseStatus') == 200:
translation = data.get('responseData', {}).get('translatedText', '')
print(f"✓ Result: '{word}' -> '{translation}'")
else:
print(f"✗ API Error: {data.get('responseStatus')} - {data.get('responseDetails', 'Unknown error')}")

except Exception as e:
print(f"✗ Network Error: {e}")

if __name__ == '__main__':
test_translation_api()
112 changes: 112 additions & 0 deletions examples/test_final_logic.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Test the final translation logic according to issue requirements."""

import re

def test_translation_logic():
"""Test complete translation logic according to issue requirements."""
print("Testing Final Translation Logic:")
print("=" * 50)

test_cases = [
# Issue examples
{
'msg': 'Как перевести hello на английский?',
'word': 'hello',
'expected_source': 'en',
'expected_target': 'en', # Explicitly asking for English
'expected_response_lang': 'russian',
'expected_format': '"hello" переводится как "привет"'
},
{
'msg': 'Как переводится beautiful?',
'word': 'beautiful',
'expected_source': 'en',
'expected_target': 'ru', # Inferred Russian target
'expected_response_lang': 'russian',
'expected_format': '"beautiful" переводится как "красивый"'
},
{
'msg': 'How to translate красота?',
'word': 'красота',
'expected_source': 'ru',
'expected_target': 'en', # Inferred English target
'expected_response_lang': 'english',
'expected_format': '"красота" translates to "beauty"'
},
{
'msg': 'What is translation of дом?',
'word': 'дом',
'expected_source': 'ru',
'expected_target': 'en', # Inferred English target
'expected_response_lang': 'english',
'expected_format': '"дом" translates to "house"'
},
# Additional test cases
{
'msg': 'translate house',
'word': 'house',
'expected_source': 'en',
'expected_target': 'ru', # English word -> Russian
'expected_response_lang': 'english',
'expected_format': '"house" translates to "дом"'
}
]

for i, case in enumerate(test_cases, 1):
print(f"\nTest {i}: {case['msg']}")
print("-" * 40)

msg = case['msg']
word = case['word']

# Apply the logic from the implementation
message_without_word = msg.replace(word, '')
is_russian_message = bool(re.search(r'[а-яё]', message_without_word, re.IGNORECASE))
word_is_russian = bool(re.search(r'[а-яё]', word, re.IGNORECASE))

if re.search(r'на английский|на англ', msg, re.IGNORECASE):
# Explicitly asking for English translation
source_lang = 'ru' if word_is_russian else 'en'
target_lang = 'en'
response_in_russian = True
elif is_russian_message:
# Russian message without explicit target - infer target language
if word_is_russian:
source_lang = 'ru'
target_lang = 'en'
else:
source_lang = 'en'
target_lang = 'ru'
response_in_russian = True
else:
# English message - infer target as English
if word_is_russian:
source_lang = 'ru'
target_lang = 'en'
else:
# English word in English message - might want Russian translation
source_lang = 'en'
target_lang = 'ru'
response_in_russian = False

# Check results
source_ok = source_lang == case['expected_source']
target_ok = target_lang == case['expected_target']
response_lang_ok = (
(response_in_russian and case['expected_response_lang'] == 'russian') or
(not response_in_russian and case['expected_response_lang'] == 'english')
)

print(f"Word: '{word}' ({'Russian' if word_is_russian else 'English'} detected)")
print(f"Message language: {'Russian' if is_russian_message else 'English'}")
print(f"Source language: {source_lang} {'✓' if source_ok else '✗ (expected ' + case['expected_source'] + ')'}")
print(f"Target language: {target_lang} {'✓' if target_ok else '✗ (expected ' + case['expected_target'] + ')'}")
print(f"Response language: {'Russian' if response_in_russian else 'English'} {'✓' if response_lang_ok else '✗ (expected ' + case['expected_response_lang'] + ')'}")

all_ok = source_ok and target_ok and response_lang_ok
print(f"Overall result: {'✓ PASS' if all_ok else '✗ FAIL'}")

if __name__ == '__main__':
test_translation_logic()
73 changes: 73 additions & 0 deletions examples/test_translation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Test script for translation patterns."""

import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'python'))

from regex import match
import patterns

def test_pattern(pattern, text, expected_word):
"""Test if pattern matches text and extracts expected word."""
matched = match(pattern, text)
if matched:
word = matched.group('word')
print(f"✓ Pattern matched: '{text}' -> word: '{word}'")
if word.strip() == expected_word:
print(f" ✓ Extracted word matches expected: '{expected_word}'")
return True
else:
print(f" ✗ Expected '{expected_word}', got '{word.strip()}'")
return False
else:
print(f"✗ Pattern did NOT match: '{text}'")
return False

def run_tests():
"""Run all pattern tests."""
print("Testing Translation Patterns")
print("=" * 50)

test_cases = [
# Russian patterns asking for English translation
(patterns.TRANSLATE_TO_ENGLISH_RU, "Как перевести hello на английский?", "hello"),
(patterns.TRANSLATE_TO_ENGLISH_RU, "как переводится world на англ", "world"),
(patterns.TRANSLATE_TO_ENGLISH_RU, "Как перевести красивый на английский", "красивый"),

# Russian patterns asking for translation (inferred as Russian target)
(patterns.TRANSLATE_TO_RUSSIAN_RU, "Как переводится beautiful?", "beautiful"),
(patterns.TRANSLATE_TO_RUSSIAN_RU, "как перевести computer", "computer"),

# English patterns asking for translation
(patterns.TRANSLATE_TO_ENGLISH_EN, "How to translate красота?", "красота"),
(patterns.TRANSLATE_TO_ENGLISH_EN, "What is translation of дом", "дом"),

# Generic translate pattern
(patterns.TRANSLATE_WORD, "translate house", "house"),
(patterns.TRANSLATE_WORD, "перевести дом", "дом"),
(patterns.TRANSLATE_WORD, "перевод машина", "машина"),
]

passed = 0
total = len(test_cases)

for i, (pattern, text, expected_word) in enumerate(test_cases, 1):
print(f"\nTest {i}/{total}:")
if test_pattern(pattern, text, expected_word):
passed += 1

print(f"\n" + "=" * 50)
print(f"Results: {passed}/{total} tests passed")

if passed == total:
print("🎉 All tests passed!")
return True
else:
print(f"❌ {total - passed} tests failed")
return False

if __name__ == '__main__':
success = run_tests()
sys.exit(0 if success else 1)
6 changes: 5 additions & 1 deletion python/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,11 @@ def __init__(
(patterns.WHAT_IS, self.commands.what_is),
(patterns.WHAT_MEAN, self.commands.what_is),
(patterns.APPLY_KARMA, self.commands.apply_karma),
(patterns.GITHUB_COPILOT, self.commands.github_copilot)
(patterns.GITHUB_COPILOT, self.commands.github_copilot),
(patterns.TRANSLATE_TO_ENGLISH_RU, self.commands.translate_word),
(patterns.TRANSLATE_TO_RUSSIAN_RU, self.commands.translate_word),
(patterns.TRANSLATE_TO_ENGLISH_EN, self.commands.translate_word),
(patterns.TRANSLATE_WORD, self.commands.translate_word)
)

def message_new(
Expand Down
Loading
Loading