better_translate 0.2.0 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +74 -0
- data/CODE_OF_CONDUCT.md +132 -0
- data/README.md +123 -31
- data/Rakefile +12 -0
- data/lib/better_translate/helper.rb +71 -0
- data/lib/better_translate/providers/base_provider.rb +47 -5
- data/lib/better_translate/providers/chatgpt_provider.rb +5 -5
- data/lib/better_translate/providers/gemini_provider.rb +1 -1
- data/lib/better_translate/service.rb +46 -2
- data/lib/better_translate/translator.rb +117 -37
- data/lib/better_translate/utils.rb +49 -0
- data/lib/better_translate/version.rb +1 -1
- data/lib/better_translate/writer.rb +17 -15
- data/lib/better_translate.rb +17 -8
- data/lib/generators/better_translate/install_generator.rb +1 -1
- data/lib/generators/better_translate/templates/better_translate.rb +12 -12
- data/lib/generators/better_translate/translate_generator.rb +5 -3
- data/sig/better_translate.rbs +4 -0
- metadata +149 -24
checksums.yaml
CHANGED
@@ -1,7 +1,7 @@
|
|
1
1
|
---
|
2
2
|
SHA256:
|
3
|
-
metadata.gz:
|
4
|
-
data.tar.gz:
|
3
|
+
metadata.gz: a2ff034a6db3498226ddff2111cf66e94a371f65741f82986b6ec8324daaf2dc
|
4
|
+
data.tar.gz: 991a78781adfc647d789729f385bca6e7688a6269bf102e0bff8b40b7bf8aca7
|
5
5
|
SHA512:
|
6
|
-
metadata.gz:
|
7
|
-
data.tar.gz:
|
6
|
+
metadata.gz: 68f06a1006c8fc3e43184485d8f71ec9b080649fa68e2f8c5563d55b20c356b501a20a308f0c00f967b5387ac8d3f62abf11d837ca25b325a646658bf8126146
|
7
|
+
data.tar.gz: 719cb1a9bb0217934ca0ecacd455bcc6c81afab081fbc43d24b8add5a50eb33b7947ab715a37938460d162fdcf88e9e629b8cc18d08e1f47ecec085101c35e8c
|
data/CHANGELOG.md
ADDED
@@ -0,0 +1,74 @@
|
|
1
|
+
# Changelog
|
2
|
+
|
3
|
+
All notable changes to BetterTranslate will be documented in this file.
|
4
|
+
|
5
|
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
6
|
+
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
7
|
+
|
8
|
+
## [0.3.1] - 2025-03-11
|
9
|
+
|
10
|
+
### Added
|
11
|
+
- Comprehensive RSpec test suite covering:
|
12
|
+
- Core translation functionality
|
13
|
+
- LRU cache implementation
|
14
|
+
- Provider selection and initialization
|
15
|
+
- Error handling
|
16
|
+
- Configuration management
|
17
|
+
- Improved documentation with badges and testing information
|
18
|
+
|
19
|
+
### Changed
|
20
|
+
- Made `translate` method public in `Service` class for better testability
|
21
|
+
- Reorganized README.md with better structure and modern layout
|
22
|
+
|
23
|
+
## [0.3.0] - 2025-03-11
|
24
|
+
|
25
|
+
### Added
|
26
|
+
- New translation helper methods:
|
27
|
+
- `translate_text_to_languages`: Translate single text to multiple languages
|
28
|
+
- `translate_texts_to_languages`: Translate multiple texts to multiple languages
|
29
|
+
- LRU caching for improved performance
|
30
|
+
|
31
|
+
### Changed
|
32
|
+
- Enhanced error handling in translation providers
|
33
|
+
- Improved method documentation
|
34
|
+
|
35
|
+
## [0.2.0] - 2025-03-11
|
36
|
+
|
37
|
+
### Added
|
38
|
+
- Two-step filtering process:
|
39
|
+
- Global exclusions using `global_exclusions`
|
40
|
+
- Language-specific exclusions using `exclusions_per_language`
|
41
|
+
|
42
|
+
### Changed
|
43
|
+
- Improved filtering logic to handle language-specific exclusions independently
|
44
|
+
- Enhanced documentation for exclusion configuration
|
45
|
+
|
46
|
+
### Fixed
|
47
|
+
- Issue with language-specific exclusions affecting global filtering
|
48
|
+
|
49
|
+
## [0.1.1] - 2025-03-10
|
50
|
+
|
51
|
+
### Added
|
52
|
+
- New Rails generator: `rails generate better_translate:translate`
|
53
|
+
- Triggers translation process
|
54
|
+
- Displays progress messages
|
55
|
+
- Integrates with existing configuration
|
56
|
+
|
57
|
+
## [0.1.0] - 2025-03-10
|
58
|
+
|
59
|
+
### Added
|
60
|
+
- Initial release with core features:
|
61
|
+
- YAML file translation from source to multiple target languages
|
62
|
+
- Multiple provider support (ChatGPT and Google Gemini)
|
63
|
+
- Progress tracking with ruby-progressbar
|
64
|
+
- Centralized configuration via initializer
|
65
|
+
- Two translation modes: override and incremental
|
66
|
+
- Key exclusion system
|
67
|
+
- Rails integration
|
68
|
+
|
69
|
+
### Configuration
|
70
|
+
- API key management for providers
|
71
|
+
- Source and target language settings
|
72
|
+
- Output folder configuration
|
73
|
+
- Translation mode selection
|
74
|
+
- Exclusion patterns support
|
data/CODE_OF_CONDUCT.md
ADDED
@@ -0,0 +1,132 @@
|
|
1
|
+
# Contributor Covenant Code of Conduct
|
2
|
+
|
3
|
+
## Our Pledge
|
4
|
+
|
5
|
+
We as members, contributors, and leaders pledge to make participation in our
|
6
|
+
community a harassment-free experience for everyone, regardless of age, body
|
7
|
+
size, visible or invisible disability, ethnicity, sex characteristics, gender
|
8
|
+
identity and expression, level of experience, education, socio-economic status,
|
9
|
+
nationality, personal appearance, race, caste, color, religion, or sexual
|
10
|
+
identity and orientation.
|
11
|
+
|
12
|
+
We pledge to act and interact in ways that contribute to an open, welcoming,
|
13
|
+
diverse, inclusive, and healthy community.
|
14
|
+
|
15
|
+
## Our Standards
|
16
|
+
|
17
|
+
Examples of behavior that contributes to a positive environment for our
|
18
|
+
community include:
|
19
|
+
|
20
|
+
* Demonstrating empathy and kindness toward other people
|
21
|
+
* Being respectful of differing opinions, viewpoints, and experiences
|
22
|
+
* Giving and gracefully accepting constructive feedback
|
23
|
+
* Accepting responsibility and apologizing to those affected by our mistakes,
|
24
|
+
and learning from the experience
|
25
|
+
* Focusing on what is best not just for us as individuals, but for the overall
|
26
|
+
community
|
27
|
+
|
28
|
+
Examples of unacceptable behavior include:
|
29
|
+
|
30
|
+
* The use of sexualized language or imagery, and sexual attention or advances of
|
31
|
+
any kind
|
32
|
+
* Trolling, insulting or derogatory comments, and personal or political attacks
|
33
|
+
* Public or private harassment
|
34
|
+
* Publishing others' private information, such as a physical or email address,
|
35
|
+
without their explicit permission
|
36
|
+
* Other conduct which could reasonably be considered inappropriate in a
|
37
|
+
professional setting
|
38
|
+
|
39
|
+
## Enforcement Responsibilities
|
40
|
+
|
41
|
+
Community leaders are responsible for clarifying and enforcing our standards of
|
42
|
+
acceptable behavior and will take appropriate and fair corrective action in
|
43
|
+
response to any behavior that they deem inappropriate, threatening, offensive,
|
44
|
+
or harmful.
|
45
|
+
|
46
|
+
Community leaders have the right and responsibility to remove, edit, or reject
|
47
|
+
comments, commits, code, wiki edits, issues, and other contributions that are
|
48
|
+
not aligned to this Code of Conduct, and will communicate reasons for moderation
|
49
|
+
decisions when appropriate.
|
50
|
+
|
51
|
+
## Scope
|
52
|
+
|
53
|
+
This Code of Conduct applies within all community spaces, and also applies when
|
54
|
+
an individual is officially representing the community in public spaces.
|
55
|
+
Examples of representing our community include using an official email address,
|
56
|
+
posting via an official social media account, or acting as an appointed
|
57
|
+
representative at an online or offline event.
|
58
|
+
|
59
|
+
## Enforcement
|
60
|
+
|
61
|
+
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
62
|
+
reported to the community leaders responsible for enforcement at
|
63
|
+
[INSERT CONTACT METHOD].
|
64
|
+
All complaints will be reviewed and investigated promptly and fairly.
|
65
|
+
|
66
|
+
All community leaders are obligated to respect the privacy and security of the
|
67
|
+
reporter of any incident.
|
68
|
+
|
69
|
+
## Enforcement Guidelines
|
70
|
+
|
71
|
+
Community leaders will follow these Community Impact Guidelines in determining
|
72
|
+
the consequences for any action they deem in violation of this Code of Conduct:
|
73
|
+
|
74
|
+
### 1. Correction
|
75
|
+
|
76
|
+
**Community Impact**: Use of inappropriate language or other behavior deemed
|
77
|
+
unprofessional or unwelcome in the community.
|
78
|
+
|
79
|
+
**Consequence**: A private, written warning from community leaders, providing
|
80
|
+
clarity around the nature of the violation and an explanation of why the
|
81
|
+
behavior was inappropriate. A public apology may be requested.
|
82
|
+
|
83
|
+
### 2. Warning
|
84
|
+
|
85
|
+
**Community Impact**: A violation through a single incident or series of
|
86
|
+
actions.
|
87
|
+
|
88
|
+
**Consequence**: A warning with consequences for continued behavior. No
|
89
|
+
interaction with the people involved, including unsolicited interaction with
|
90
|
+
those enforcing the Code of Conduct, for a specified period of time. This
|
91
|
+
includes avoiding interactions in community spaces as well as external channels
|
92
|
+
like social media. Violating these terms may lead to a temporary or permanent
|
93
|
+
ban.
|
94
|
+
|
95
|
+
### 3. Temporary Ban
|
96
|
+
|
97
|
+
**Community Impact**: A serious violation of community standards, including
|
98
|
+
sustained inappropriate behavior.
|
99
|
+
|
100
|
+
**Consequence**: A temporary ban from any sort of interaction or public
|
101
|
+
communication with the community for a specified period of time. No public or
|
102
|
+
private interaction with the people involved, including unsolicited interaction
|
103
|
+
with those enforcing the Code of Conduct, is allowed during this period.
|
104
|
+
Violating these terms may lead to a permanent ban.
|
105
|
+
|
106
|
+
### 4. Permanent Ban
|
107
|
+
|
108
|
+
**Community Impact**: Demonstrating a pattern of violation of community
|
109
|
+
standards, including sustained inappropriate behavior, harassment of an
|
110
|
+
individual, or aggression toward or disparagement of classes of individuals.
|
111
|
+
|
112
|
+
**Consequence**: A permanent ban from any sort of public interaction within the
|
113
|
+
community.
|
114
|
+
|
115
|
+
## Attribution
|
116
|
+
|
117
|
+
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
118
|
+
version 2.1, available at
|
119
|
+
[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
|
120
|
+
|
121
|
+
Community Impact Guidelines were inspired by
|
122
|
+
[Mozilla's code of conduct enforcement ladder][Mozilla CoC].
|
123
|
+
|
124
|
+
For answers to common questions about this code of conduct, see the FAQ at
|
125
|
+
[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
|
126
|
+
[https://www.contributor-covenant.org/translations][translations].
|
127
|
+
|
128
|
+
[homepage]: https://www.contributor-covenant.org
|
129
|
+
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
|
130
|
+
[Mozilla CoC]: https://github.com/mozilla/diversity
|
131
|
+
[FAQ]: https://www.contributor-covenant.org/faq
|
132
|
+
[translations]: https://www.contributor-covenant.org/translations
|
data/README.md
CHANGED
@@ -1,27 +1,39 @@
|
|
1
|
-
# BetterTranslate
|
2
|
-
|
3
|
-
|
4
|
-
|
5
|
-
|
6
|
-
|
7
|
-
|
8
|
-
|
9
|
-
|
10
|
-
|
11
|
-
|
12
|
-
-
|
13
|
-
-
|
14
|
-
-
|
15
|
-
|
16
|
-
|
17
|
-
|
18
|
-
|
19
|
-
|
20
|
-
|
21
|
-
- **
|
22
|
-
-
|
23
|
-
- `
|
24
|
-
|
1
|
+
# BetterTranslate 🌍
|
2
|
+
|
3
|
+
[](https://badge.fury.io/rb/better_translate)
|
4
|
+
[](https://opensource.org/licenses/MIT)
|
5
|
+
[](https://github.com/rubocop/rubocop)
|
6
|
+
|
7
|
+
> 🚀 A powerful Ruby gem for seamless YAML file translations using AI providers like ChatGPT and Google Gemini
|
8
|
+
|
9
|
+
BetterTranslate simplifies the translation of YAML files in your Ruby/Rails applications by leveraging advanced AI models. With support for both ChatGPT (OpenAI) and Google Gemini, it offers:
|
10
|
+
|
11
|
+
✨ **Key Features**
|
12
|
+
- 🔄 Smart translation modes (Override/Incremental)
|
13
|
+
- 🎯 Precise key exclusion control
|
14
|
+
- 📊 Real-time progress tracking
|
15
|
+
- 🧪 Comprehensive test coverage
|
16
|
+
- ⚡️ LRU caching for performance
|
17
|
+
|
18
|
+
## Why BetterTranslate? 🤔
|
19
|
+
|
20
|
+
- 🌐 **AI-Powered Translation**: Leverage ChatGPT and Google Gemini for high-quality translations
|
21
|
+
- 🔄 **Smart Translation Modes**:
|
22
|
+
- `Override`: Full file rewrite
|
23
|
+
- `Incremental`: Update only new/modified keys
|
24
|
+
- 🎯 **Precise Control**:
|
25
|
+
- Global key exclusions
|
26
|
+
- Language-specific exclusions
|
27
|
+
- Dot notation support
|
28
|
+
- 🛠 **Developer-Friendly**:
|
29
|
+
- Rails generators included
|
30
|
+
- Comprehensive test suite
|
31
|
+
- LRU caching for performance
|
32
|
+
- Progress tracking
|
33
|
+
- 🔧 **Flexible Helpers**:
|
34
|
+
- Single text translation
|
35
|
+
- Bulk text translation
|
36
|
+
- Multiple target languages support
|
25
37
|
|
26
38
|
## Installation
|
27
39
|
|
@@ -95,7 +107,7 @@ BetterTranslate.configure do |config|
|
|
95
107
|
config.input_file = Rails.root.join("config", "locales", "en.yml").to_s
|
96
108
|
|
97
109
|
# Translation mode: :override or :incremental
|
98
|
-
config.
|
110
|
+
config.translation_mode = :override
|
99
111
|
end
|
100
112
|
```
|
101
113
|
|
@@ -134,15 +146,95 @@ The gem includes generators to simplify tasks:
|
|
134
146
|
|
135
147
|
The `better_translate:translate` generator will trigger the translation process (via `BetterTranslate.magic`) and display progress in the terminal.
|
136
148
|
|
137
|
-
|
149
|
+
### Translation Helpers
|
150
|
+
|
151
|
+
BetterTranslate provides helper methods to simplify translation tasks.
|
152
|
+
|
153
|
+
#### Single Text Translation
|
154
|
+
|
155
|
+
The `translate_text_to_languages` helper allows you to translate a single text into multiple target languages in one call.
|
156
|
+
|
157
|
+
**Example Usage:**
|
158
|
+
|
159
|
+
```ruby
|
160
|
+
text = "Hello world!"
|
161
|
+
target_languages = [
|
162
|
+
{ short_name: "it", name: "Italian" },
|
163
|
+
{ short_name: "fr", name: "French" }
|
164
|
+
]
|
165
|
+
|
166
|
+
translated = BetterTranslate::TranslationHelper.translate_text_to_languages(
|
167
|
+
text,
|
168
|
+
target_languages,
|
169
|
+
"en", # source language code
|
170
|
+
:chatgpt # provider: can be :chatgpt or :gemini
|
171
|
+
)
|
172
|
+
|
173
|
+
puts translated
|
174
|
+
# Expected output:
|
175
|
+
# { "it" => "Ciao mondo!", "fr" => "Bonjour le monde!" }
|
176
|
+
```
|
177
|
+
|
178
|
+
#### Multiple Texts Translation
|
179
|
+
|
180
|
+
The `translate_texts_to_languages` helper extends the functionality to translate an array of texts into multiple target languages. It returns a hash where each key is a target language code and the value is an array of translated texts.
|
181
|
+
|
182
|
+
**Example Usage:**
|
183
|
+
|
184
|
+
```ruby
|
185
|
+
texts = ["Hello world!", "How are you?"]
|
186
|
+
target_languages = [
|
187
|
+
{ short_name: "it", name: "Italian" },
|
188
|
+
{ short_name: "fr", name: "French" }
|
189
|
+
]
|
190
|
+
|
191
|
+
translated_texts = BetterTranslate::TranslationHelper.translate_texts_to_languages(
|
192
|
+
texts,
|
193
|
+
target_languages,
|
194
|
+
"en", # source language code
|
195
|
+
:chatgpt # provider: can be :chatgpt or :gemini
|
196
|
+
)
|
197
|
+
|
198
|
+
puts translated_texts
|
199
|
+
# Expected output:
|
200
|
+
# {
|
201
|
+
# "it" => ["Ciao mondo!", "Come stai?"],
|
202
|
+
# "fr" => ["Bonjour le monde!", "Comment ça va?"]
|
203
|
+
# }
|
204
|
+
```
|
205
|
+
|
206
|
+
## Testing 🧪
|
207
|
+
|
208
|
+
BetterTranslate comes with a comprehensive test suite using RSpec. To run the tests:
|
209
|
+
|
210
|
+
```bash
|
211
|
+
bundle exec rspec
|
212
|
+
```
|
213
|
+
|
214
|
+
The test suite covers:
|
215
|
+
- Core translation functionality
|
216
|
+
- Cache implementation (LRU)
|
217
|
+
- Provider selection and initialization
|
218
|
+
- Error handling
|
219
|
+
- Configuration management
|
220
|
+
|
221
|
+
## Contributing 🤝
|
222
|
+
|
223
|
+
1. Fork the repository
|
224
|
+
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
|
225
|
+
3. Commit your changes (`git commit -m 'Add amazing feature'`)
|
226
|
+
4. Push to the branch (`git push origin feature/amazing-feature`)
|
227
|
+
5. Open a Pull Request
|
138
228
|
|
139
|
-
|
229
|
+
## Contact & Support 📬
|
140
230
|
|
141
|
-
|
231
|
+
- **Email**: alessio.bussolari@pandev.it
|
232
|
+
- **Issues**: [GitHub Issues](https://github.com/alessiobussolari/better_translate/issues)
|
233
|
+
- **Discussions**: [GitHub Discussions](https://github.com/alessiobussolari/better_translate/discussions)
|
142
234
|
|
143
|
-
|
235
|
+
## License 📄
|
144
236
|
|
145
|
-
|
237
|
+
This project is licensed under the MIT License - see the [LICENSE.txt](LICENSE.txt) file for details.
|
146
238
|
|
147
239
|
BetterTranslate aims to simplify the translation of YAML files in Ruby projects by providing a flexible, configurable, and extensible system. Whether you need a complete file rewrite or an incremental update, BetterTranslate streamlines the translation process using advanced providers like ChatGPT and Google Gemini. Contributions, feedback, and feature requests are highly encouraged to help improve the gem further.
|
148
240
|
|
@@ -150,4 +242,4 @@ For more details, please visit the [GitHub repository](https://github.com/alessi
|
|
150
242
|
|
151
243
|
## License
|
152
244
|
|
153
|
-
BetterTranslate is distributed under the MIT license. See the [LICENSE](LICENSE) file for more details.
|
245
|
+
BetterTranslate is distributed under the MIT license. See the [LICENSE](LICENSE) file for more details.
|
data/Rakefile
ADDED
@@ -0,0 +1,71 @@
|
|
1
|
+
module BetterTranslate
|
2
|
+
class Helper
|
3
|
+
class << self
|
4
|
+
# Translates a given text into multiple target languages.
|
5
|
+
#
|
6
|
+
# @param text [String] The text to be translated.
|
7
|
+
# @param target_languages [Array<Hash>] Array of target language hashes,
|
8
|
+
# e.g. [{ short_name: "it", name: "Italian" }, { short_name: "fr", name: "French" }]
|
9
|
+
# @param source_language [String] The source language code (e.g., "en").
|
10
|
+
# @param provider_name [Symbol] The provider to use (e.g., :chatgpt or :gemini).
|
11
|
+
# @return [Hash] A hash where each key is a target language code and the value is the translated text.
|
12
|
+
#
|
13
|
+
# Example:
|
14
|
+
# translated = BetterTranslate::Helpers.translate_text_to_languages(
|
15
|
+
# "Hello world!",
|
16
|
+
# [{ short_name: "it", name: "Italian" }, { short_name: "fr", name: "French" }],
|
17
|
+
# "en",
|
18
|
+
# :chatgpt
|
19
|
+
# )
|
20
|
+
# # => { "it" => "Ciao mondo!", "fr" => "Bonjour le monde!" }
|
21
|
+
def translate_text_to_languages(text, target_languages, source_language, provider_name)
|
22
|
+
provider_instance = case provider_name
|
23
|
+
when :chatgpt
|
24
|
+
Providers::ChatgptProvider.new(BetterTranslate.configuration.openai_key)
|
25
|
+
when :gemini
|
26
|
+
Providers::GeminiProvider.new(BetterTranslate.configuration.google_gemini_key)
|
27
|
+
else
|
28
|
+
raise "Provider not supported: #{provider_name}"
|
29
|
+
end
|
30
|
+
|
31
|
+
result = {}
|
32
|
+
target_languages.each do |lang|
|
33
|
+
# Optionally, you could also pass the source_language if needed by your provider.
|
34
|
+
translated_text = provider_instance.translate(text, lang[:short_name], lang[:name])
|
35
|
+
result[lang[:short_name]] = translated_text
|
36
|
+
end
|
37
|
+
result
|
38
|
+
end
|
39
|
+
|
40
|
+
# Translates an array of texts into multiple target languages using the translate_text_to_languages helper.
|
41
|
+
#
|
42
|
+
# @param texts [Array<String>] An array of texts to translate.
|
43
|
+
# @param target_languages [Array<Hash>] Array of target language hashes,
|
44
|
+
# e.g. [{ short_name: "it", name: "Italian" }, { short_name: "fr", name: "French" }].
|
45
|
+
# @param source_language [String] The source language code (e.g., "en").
|
46
|
+
# @param provider_name [Symbol] The provider to use (e.g., :chatgpt or :gemini).
|
47
|
+
# @return [Hash] A hash where each key is a target language code and the value is an array of translated texts.
|
48
|
+
#
|
49
|
+
# Example:
|
50
|
+
# texts = ["Hello world!", "How are you?"]
|
51
|
+
# result = BetterTranslate::TranslationHelper.translate_texts_to_languages(
|
52
|
+
# texts,
|
53
|
+
# [{ short_name: "it", name: "Italian" }, { short_name: "fr", name: "French" }],
|
54
|
+
# "en",
|
55
|
+
# :chatgpt
|
56
|
+
# )
|
57
|
+
# # => { "it" => ["Ciao mondo!", "Come stai?"], "fr" => ["Bonjour le monde!", "Comment ça va?"] }
|
58
|
+
def translate_texts_to_languages(texts, target_languages, source_language, provider_name)
|
59
|
+
result = {}
|
60
|
+
target_languages.each do |lang|
|
61
|
+
# For each target language, translate each text and collect translations into an array.
|
62
|
+
result[lang[:short_name]] = texts.map do |text|
|
63
|
+
translation_hash = translate_text_to_languages(text, [lang], source_language, provider_name)
|
64
|
+
translation_hash[lang[:short_name]]
|
65
|
+
end
|
66
|
+
end
|
67
|
+
result
|
68
|
+
end
|
69
|
+
end
|
70
|
+
end
|
71
|
+
end
|
@@ -3,15 +3,57 @@ module BetterTranslate
|
|
3
3
|
class BaseProvider
|
4
4
|
def initialize(api_key)
|
5
5
|
@api_key = api_key
|
6
|
+
@last_request_time = Time.now - 1
|
6
7
|
end
|
7
8
|
|
8
|
-
|
9
|
-
|
10
|
-
|
11
|
-
|
9
|
+
private
|
10
|
+
|
11
|
+
def rate_limit
|
12
|
+
time_since_last_request = Time.now - @last_request_time
|
13
|
+
sleep(0.5 - time_since_last_request) if time_since_last_request < 0.5
|
14
|
+
@last_request_time = Time.now
|
15
|
+
end
|
16
|
+
|
17
|
+
def validate_input(text, target_lang_code)
|
18
|
+
raise ArgumentError, "Text cannot be empty" if text.nil? || text.strip.empty?
|
19
|
+
raise ArgumentError, "Invalid target language code" unless target_lang_code.match?(/^[a-z]{2}(-[A-Z]{2})?$/)
|
20
|
+
end
|
21
|
+
|
22
|
+
# Method to be implemented in derived classes.
|
23
|
+
# @param text [String] text to translate.
|
24
|
+
# @param target_lang_code [String] target language code (e.g. "en").
|
25
|
+
# @param target_lang_name [String] target language name (e.g. "English").
|
12
26
|
# @return [String] testo tradotto.
|
27
|
+
MAX_RETRIES = 3
|
28
|
+
RETRY_DELAY = 2 # seconds
|
29
|
+
|
13
30
|
def translate(text, target_lang_code, target_lang_name)
|
14
|
-
|
31
|
+
retries = 0
|
32
|
+
begin
|
33
|
+
perform_translation(text, target_lang_code, target_lang_name)
|
34
|
+
rescue StandardError => e
|
35
|
+
retries += 1
|
36
|
+
if retries <= MAX_RETRIES
|
37
|
+
message = "Translation attempt #{retries} failed. Retrying in #{RETRY_DELAY} seconds..."
|
38
|
+
BetterTranslate::Utils.logger(message: message)
|
39
|
+
sleep(RETRY_DELAY)
|
40
|
+
retry
|
41
|
+
else
|
42
|
+
message = "Translation failed after #{MAX_RETRIES} attempts: #{e.message}"
|
43
|
+
BetterTranslate::Utils.logger(message: message)
|
44
|
+
raise
|
45
|
+
end
|
46
|
+
end
|
47
|
+
end
|
48
|
+
|
49
|
+
def perform_translation(text, target_lang_code, target_lang_name)
|
50
|
+
validate_input(text, target_lang_code)
|
51
|
+
rate_limit
|
52
|
+
translate_text(text, target_lang_code, target_lang_name)
|
53
|
+
end
|
54
|
+
|
55
|
+
def translate_text(text, target_lang_code, target_lang_name)
|
56
|
+
raise NotImplementedError, "The provider #{self.class} must implement the translate_text method"
|
15
57
|
end
|
16
58
|
end
|
17
59
|
end
|
@@ -1,19 +1,19 @@
|
|
1
1
|
module BetterTranslate
|
2
2
|
module Providers
|
3
3
|
class ChatgptProvider < BaseProvider
|
4
|
-
#
|
5
|
-
def
|
4
|
+
# Uses the OpenAI API to translate the text.
|
5
|
+
def translate_text(text, target_lang_code, target_lang_name)
|
6
6
|
uri = URI("https://api.openai.com/v1/chat/completions")
|
7
7
|
headers = {
|
8
8
|
"Content-Type" => "application/json",
|
9
9
|
"Authorization" => "Bearer #{@api_key}"
|
10
10
|
}
|
11
11
|
|
12
|
-
#
|
12
|
+
# Build the prompt to translate the text.
|
13
13
|
body = {
|
14
14
|
model: "gpt-3.5-turbo",
|
15
15
|
messages: [
|
16
|
-
{ role: "system", content: "
|
16
|
+
{ role: "system", content: "You are a professional translator. Translate the following text exactly from #{BetterTranslate.configuration.source_language} to #{target_lang_name} without adding comments, explanations, or alternatives. Provide only the direct translation:" },
|
17
17
|
{ role: "user", content: "#{text}" }
|
18
18
|
],
|
19
19
|
temperature: 0.3
|
@@ -30,7 +30,7 @@ module BetterTranslate
|
|
30
30
|
translated_text = json.dig("choices", 0, "message", "content")
|
31
31
|
translated_text ? translated_text.strip : text
|
32
32
|
else
|
33
|
-
raise "
|
33
|
+
raise "Error during translation with ChatGPT: #{response.body}"
|
34
34
|
end
|
35
35
|
end
|
36
36
|
end
|
@@ -3,7 +3,7 @@ module BetterTranslate
|
|
3
3
|
class GeminiProvider < BaseProvider
|
4
4
|
# Esempio di implementazione per Google Gemini.
|
5
5
|
# Nota: L'endpoint e i parametri sono ipotetici e vanno sostituiti con quelli reali secondo la documentazione ufficiale.
|
6
|
-
def
|
6
|
+
def translate_text(text, target_lang_code, target_lang_name)
|
7
7
|
uri = URI("https://gemini.googleapis.com/v1/translate")
|
8
8
|
headers = {
|
9
9
|
"Content-Type" => "application/json",
|
@@ -1,16 +1,60 @@
|
|
1
1
|
module BetterTranslate
|
2
2
|
class Service
|
3
|
+
MAX_CACHE_SIZE = 1000
|
4
|
+
|
3
5
|
def initialize
|
4
6
|
@provider_name = BetterTranslate.configuration.provider
|
7
|
+
@translation_cache = {}
|
8
|
+
@cache_order = []
|
5
9
|
end
|
6
10
|
|
7
|
-
#
|
11
|
+
# Method to translate a text using the selected provider.
|
8
12
|
def translate(text, target_lang_code, target_lang_name)
|
9
|
-
|
13
|
+
cache_key = "#{text}:#{target_lang_code}"
|
14
|
+
|
15
|
+
# Prova a recuperare dalla cache
|
16
|
+
cached = cache_get(cache_key)
|
17
|
+
return cached if cached
|
18
|
+
|
19
|
+
# Traduci e salva in cache
|
20
|
+
start_time = Time.now
|
21
|
+
result = provider_instance.translate_text(text, target_lang_code, target_lang_name)
|
22
|
+
duration = Time.now - start_time
|
23
|
+
|
24
|
+
BetterTranslate::Utils.track_metric("translation_request_duration", {
|
25
|
+
provider: @provider_name,
|
26
|
+
text_length: text.length,
|
27
|
+
duration: duration
|
28
|
+
})
|
29
|
+
|
30
|
+
cache_set(cache_key, result)
|
10
31
|
end
|
11
32
|
|
12
33
|
private
|
13
34
|
|
35
|
+
def cache_get(key)
|
36
|
+
if @translation_cache.key?(key)
|
37
|
+
# Aggiorna l'ordine LRU
|
38
|
+
@cache_order.delete(key)
|
39
|
+
@cache_order.push(key)
|
40
|
+
@translation_cache[key]
|
41
|
+
end
|
42
|
+
end
|
43
|
+
|
44
|
+
def cache_set(key, value)
|
45
|
+
if @translation_cache.size >= MAX_CACHE_SIZE
|
46
|
+
# Rimuovi l'elemento meno recentemente usato
|
47
|
+
oldest_key = @cache_order.shift
|
48
|
+
@translation_cache.delete(oldest_key)
|
49
|
+
end
|
50
|
+
|
51
|
+
@translation_cache[key] = value
|
52
|
+
@cache_order.push(key)
|
53
|
+
value
|
54
|
+
end
|
55
|
+
|
56
|
+
|
57
|
+
|
14
58
|
def provider_instance
|
15
59
|
@provider_instance ||= case @provider_name
|
16
60
|
when :chatgpt
|