better_translate 0.3.0 → 0.4.0

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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 1110968d8e49f85d5231775f9c05fcbca610021a33723999c75246b687f56b77
4
- data.tar.gz: 255e51ff5e5105ebf314b703d9aa841c66eaa6b0ffb5ca1f631ea2cbe81ab6db
3
+ metadata.gz: 6941ef1c334c2ddbbb7141c8257f8906957fd0b60eadeee867d9a11b83788ae6
4
+ data.tar.gz: 8678aa23790a06d905592efc1571a91408e58a9f1359e70ee90174d5d2ee8975
5
5
  SHA512:
6
- metadata.gz: b971940521bce1ad359990e13fe7d17a339f9d5e62fe5ea9b565fe1ffbd51fe2c2dd24789cd02b7e838a20a3ae88de919ed529adf325b3c11d7377c6bced68e5
7
- data.tar.gz: 1d8d785607ba4439df35ceb70b0c302ba1944bfdd74e197d2686cbe7781cfab55bfc93ed7a2affa9ef50b5fc1a459034b1d3cdf6f60420cb2df1b0252d5e3ac5
6
+ metadata.gz: 548433e5223f37320a42c7ba35644b46470dc89baf42581612753d0542d039e2729cad8dd8bf4fbde1cd962ac970f397fdd1a3d98374f83fbc0380805771daae
7
+ data.tar.gz: 704eaeb04b49d7f165631443567e89afdff27a30c42893d0d04e424fe340fb113a9a4553ded29c1b4f8e9af36d75eccea0e138d0056c72442f75570340b9fa97
data/CHANGELOG.md ADDED
@@ -0,0 +1,87 @@
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.4.0] - 2025-03-11
9
+
10
+ ### Added
11
+ - New Translation Similarity Analyzer:
12
+ - Identifies similar translations across language files
13
+ - Generates detailed JSON reports and human-readable summaries
14
+ - Uses Levenshtein distance for similarity calculation
15
+ - Configurable similarity threshold
16
+ - New Rails generator: `rails generate better_translate:analyze`
17
+ - Analyzes all YAML files in the locales directory
18
+ - Provides immediate feedback in the console
19
+ - Generates comprehensive similarity reports
20
+
21
+ ## [0.3.1] - 2025-03-11
22
+
23
+ ### Added
24
+ - Comprehensive RSpec test suite covering:
25
+ - Core translation functionality
26
+ - LRU cache implementation
27
+ - Provider selection and initialization
28
+ - Error handling
29
+ - Configuration management
30
+ - Improved documentation with badges and testing information
31
+
32
+ ### Changed
33
+ - Made `translate` method public in `Service` class for better testability
34
+ - Reorganized README.md with better structure and modern layout
35
+
36
+ ## [0.3.0] - 2025-03-11
37
+
38
+ ### Added
39
+ - New translation helper methods:
40
+ - `translate_text_to_languages`: Translate single text to multiple languages
41
+ - `translate_texts_to_languages`: Translate multiple texts to multiple languages
42
+ - LRU caching for improved performance
43
+
44
+ ### Changed
45
+ - Enhanced error handling in translation providers
46
+ - Improved method documentation
47
+
48
+ ## [0.2.0] - 2025-03-11
49
+
50
+ ### Added
51
+ - Two-step filtering process:
52
+ - Global exclusions using `global_exclusions`
53
+ - Language-specific exclusions using `exclusions_per_language`
54
+
55
+ ### Changed
56
+ - Improved filtering logic to handle language-specific exclusions independently
57
+ - Enhanced documentation for exclusion configuration
58
+
59
+ ### Fixed
60
+ - Issue with language-specific exclusions affecting global filtering
61
+
62
+ ## [0.1.1] - 2025-03-10
63
+
64
+ ### Added
65
+ - New Rails generator: `rails generate better_translate:translate`
66
+ - Triggers translation process
67
+ - Displays progress messages
68
+ - Integrates with existing configuration
69
+
70
+ ## [0.1.0] - 2025-03-10
71
+
72
+ ### Added
73
+ - Initial release with core features:
74
+ - YAML file translation from source to multiple target languages
75
+ - Multiple provider support (ChatGPT and Google Gemini)
76
+ - Progress tracking with ruby-progressbar
77
+ - Centralized configuration via initializer
78
+ - Two translation modes: override and incremental
79
+ - Key exclusion system
80
+ - Rails integration
81
+
82
+ ### Configuration
83
+ - API key management for providers
84
+ - Source and target language settings
85
+ - Output folder configuration
86
+ - Translation mode selection
87
+ - Exclusion patterns support
@@ -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,30 +1,44 @@
1
- # BetterTranslate
2
-
3
- BetterTranslate is a Ruby gem that enables you to translate YAML files from a source language into one or more target languages using translation providers such as ChatGPT (OpenAI) and Google Gemini. The gem supports two translation modes:
4
-
5
- - **Override**: Completely rewrites the translated file.
6
- - **Incremental**: Updates the translated file only with new or modified keys while keeping the existing ones.
7
-
8
- Configuration is centralized via an initializer (for example, in a Rails app), where you can set API keys, the source language, target languages, key exclusions, the output folder, and the translation mode. Additionally, BetterTranslate integrates progress tracking using the [ruby-progressbar](https://github.com/jfelchner/ruby-progressbar) gem.
9
-
10
- ## Features
11
-
12
- - **Multi-language YAML Translation**: Translates YAML files from a source language into one or more target languages.
13
- - **Multiple Providers**: Supports ChatGPT (OpenAI) and Google Gemini (with potential for extension to other providers in the future).
14
- - **Translation Modes**:
15
- - **Override**: Rewrites the file from scratch.
16
- - **Incremental**: Updates only missing or modified keys.
17
- - **Centralized Configuration**: Configured via an initializer with settings for API keys, source language, target languages, exclusions (using dot notation), and the output folder.
18
- - **Two-Step Exclusion Filtering**:
19
- - **Global Exclusions**: Removes keys defined in `global_exclusions` from the entire YAML structure.
20
- - **Language-Specific Exclusions**: Applies additional filtering using the `exclusions_per_language` map for each target language.
21
- - **Progress Bar**: Displays translation progress using ruby-progressbar.
22
- - **Rails Generators**:
23
- - `rails generate better_translate:install` to generate the initializer.
24
- - `rails generate better_translate:translate` to trigger the translation process directly from your Rails app.
25
- - **Translation Helpers**:
26
- - `translate_text_to_languages` for translating a single text into multiple target languages.
27
- - `translate_texts_to_languages` for translating an array of texts into multiple target languages.
1
+ # BetterTranslate 🌍
2
+
3
+ [![Gem Version](https://badge.fury.io/rb/better_translate.svg)](https://badge.fury.io/rb/better_translate)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
5
+ [![Ruby Style Guide](https://img.shields.io/badge/code_style-rubocop-brightgreen.svg)](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
+ - 🔍 Translation similarity analysis
18
+
19
+ ## Why BetterTranslate? 🤔
20
+
21
+ - 🌐 **AI-Powered Translation**: Leverage ChatGPT and Google Gemini for high-quality translations
22
+ - 🔄 **Smart Translation Modes**:
23
+ - `Override`: Full file rewrite
24
+ - `Incremental`: Update only new/modified keys
25
+ - 🎯 **Precise Control**:
26
+ - Global key exclusions
27
+ - Language-specific exclusions
28
+ - Dot notation support
29
+ - 🛠 **Developer-Friendly**:
30
+ - Rails generators included
31
+ - Comprehensive test suite
32
+ - LRU caching for performance
33
+ - Progress tracking
34
+ - 🔍 **Translation Analysis**:
35
+ - Similarity detection
36
+ - Detailed reports
37
+ - Optimization suggestions
38
+ - 🔧 **Flexible Helpers**:
39
+ - Single text translation
40
+ - Bulk text translation
41
+ - Multiple target languages support
28
42
 
29
43
  ## Installation
30
44
 
@@ -137,6 +151,25 @@ The gem includes generators to simplify tasks:
137
151
 
138
152
  The `better_translate:translate` generator will trigger the translation process (via `BetterTranslate.magic`) and display progress in the terminal.
139
153
 
154
+ - **Analyze Translations:**
155
+
156
+ ```bash
157
+ rails generate better_translate:analyze
158
+ ```
159
+
160
+ The `better_translate:analyze` generator will:
161
+ - Scan all YAML files in your locales directory
162
+ - Find similar translations using Levenshtein distance
163
+ - Generate two reports:
164
+ - `translation_similarities.json`: Detailed JSON report
165
+ - `translation_similarities_summary.txt`: Human-readable summary
166
+
167
+ This helps you:
168
+ - Identify potentially redundant translations
169
+ - Maintain consistency across your translations
170
+ - Optimize your translation files
171
+ - Reduce translation costs
172
+
140
173
  ### Translation Helpers
141
174
 
142
175
  BetterTranslate provides helper methods to simplify translation tasks.
@@ -194,11 +227,38 @@ puts translated_texts
194
227
  # }
195
228
  ```
196
229
 
197
- ## Contact & Feature Requests
230
+ ## Testing 🧪
231
+
232
+ BetterTranslate comes with a comprehensive test suite using RSpec. To run the tests:
233
+
234
+ ```bash
235
+ bundle exec rspec
236
+ ```
237
+
238
+ The test suite covers:
239
+ - Core translation functionality
240
+ - Cache implementation (LRU)
241
+ - Provider selection and initialization
242
+ - Error handling
243
+ - Configuration management
244
+
245
+ ## Contributing 🤝
246
+
247
+ 1. Fork the repository
248
+ 2. Create your feature branch (`git checkout -b feature/amazing-feature`)
249
+ 3. Commit your changes (`git commit -m 'Add amazing feature'`)
250
+ 4. Push to the branch (`git push origin feature/amazing-feature`)
251
+ 5. Open a Pull Request
252
+
253
+ ## Contact & Support 📬
254
+
255
+ - **Email**: alessio.bussolari@pandev.it
256
+ - **Issues**: [GitHub Issues](https://github.com/alessiobussolari/better_translate/issues)
257
+ - **Discussions**: [GitHub Discussions](https://github.com/alessiobussolari/better_translate/discussions)
198
258
 
199
- For suggestions, bug reports, or to request new features, please reach out via email at: **alessio.bussolari@pandev.it**.
259
+ ## License 📄
200
260
 
201
- ## Conclusions
261
+ This project is licensed under the MIT License - see the [LICENSE.txt](LICENSE.txt) file for details.
202
262
 
203
263
  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.
204
264
 
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
@@ -68,8 +68,4 @@ module BetterTranslate
68
68
  end
69
69
  end
70
70
  end
71
- end
72
-
73
- __END__
74
-
75
- translated = BetterTranslate::Helper.translate_text_to_languages("Hello world!",[{ short_name: "it", name: "Italian" }, { short_name: "fr", name: "French" }],"en",:chatgpt)
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
- # Metodo da implementare nelle classi derivate.
9
- # @param text [String] testo da tradurre.
10
- # @param target_lang_code [String] codice della lingua di destinazione (es. "en").
11
- # @param target_lang_name [String] nome della lingua di destinazione (es. "English").
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
- raise NotImplementedError, "Il provider #{self.class} deve implementare il metodo translate"
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
- # Utilizza l'API di OpenAI per tradurre il testo.
5
- def translate(text, target_lang_code, target_lang_name)
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
- # Costruiamo il prompt per tradurre il testo.
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: "Sei un traduttore professionale. Traduci esattamente il seguente testo da #{BetterTranslate.configuration.source_language} a #{target_lang_name} senza aggiungere commenti, spiegazioni o alternative. Fornisci solamente la traduzione diretta:" },
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 "Errore durante la traduzione con ChatGPT: #{response.body}"
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 translate(text, target_lang_code, target_lang_name)
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
- # Metodo per tradurre un testo utilizzando il provider selezionato.
11
+ # Method to translate a text using the selected provider.
8
12
  def translate(text, target_lang_code, target_lang_name)
9
- provider_instance.translate(text, target_lang_code, target_lang_name)
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