Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor (translator) + fix(cache): Continue writing to cache after setting the ignore cache flag and ensure translate engine name length validation #365

Merged
merged 4 commits into from
Dec 28, 2024
Merged
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
3 changes: 3 additions & 0 deletions pdf2zh/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,9 @@ def _sort_dict_recursively(obj):
return obj

def __init__(self, translate_engine: str, translate_engine_params: dict = None):
assert (
len(translate_engine) < 20
), "current cache require translate engine name less than 20 characters"
self.translate_engine = translate_engine
self.replace_params(translate_engine_params)

Expand Down
3 changes: 1 addition & 2 deletions pdf2zh/translator.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,7 @@ def translate(self, text, ignore_cache=False):
return cache

translation = self.do_translate(text)
if not (self.ignore_cache or ignore_cache):
self.cache.set(text, translation)
self.cache.set(text, translation)
return translation

def do_translate(self, text):
Expand Down
10 changes: 5 additions & 5 deletions test/test_translator.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,17 +50,17 @@ def test_add_cache_impact_parameters(self):
self.assertNotEqual(first_result, second_result)

# Test cache with ignore_cache=True
no_cache_result = translator.translate(text, ignore_cache=True)
self.assertNotEqual(first_result, no_cache_result)
no_cache_result1 = translator.translate(text, ignore_cache=True)
self.assertNotEqual(first_result, no_cache_result1)

translator.ignore_cache = True
no_cache_result = translator.translate(text)
self.assertNotEqual(first_result, no_cache_result)
no_cache_result2 = translator.translate(text)
self.assertNotEqual(no_cache_result1, no_cache_result2)

# Test cache with ignore_cache=False
translator.ignore_cache = False
cache_result = translator.translate(text)
self.assertEqual(second_result, cache_result)
self.assertEqual(no_cache_result2, cache_result)

# Test cache with another parameter
translator.add_cache_impact_parameters("test2", "value2")
Expand Down
Loading