Class: AiRedactor::TextRedactor
- Inherits:
-
Object
- Object
- AiRedactor::TextRedactor
- Defined in:
- lib/ai_redactor/text_redactor.rb
Constant Summary collapse
- DEFAULT_MASK_CHAR =
"*"- DEFAULT_MASK_LENGTH =
8
Instance Method Summary collapse
- #analyze(text) ⇒ Object
-
#initialize(options = {}) ⇒ TextRedactor
constructor
A new instance of TextRedactor.
- #mask(text) ⇒ Object
Constructor Details
#initialize(options = {}) ⇒ TextRedactor
Returns a new instance of TextRedactor.
12 13 14 15 16 17 18 |
# File 'lib/ai_redactor/text_redactor.rb', line 12 def initialize( = {}) @mask_char = [:mask_char] || DEFAULT_MASK_CHAR @mask_length = [:mask_length] || DEFAULT_MASK_LENGTH @preserve_format = [:preserve_format] || false @patterns = [:patterns] || Patterns::ALL_PATTERNS.keys @case_sensitive = [:case_sensitive] || false end |
Instance Method Details
#analyze(text) ⇒ Object
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 |
# File 'lib/ai_redactor/text_redactor.rb', line 52 def analyze(text) return Report.new(text, [], text) if text.nil? || text.empty? detections = [] masked_text = text.dup @patterns.each do |pattern_name| pattern = Patterns.get_pattern(pattern_name) next unless pattern flags = @case_sensitive ? 0 : Regexp::IGNORECASE regex = Regexp.new(pattern.source, flags) text.scan(regex) do match = Regexp.last_match start_pos = match.begin(0) end_pos = match.end(0) matched_text = match[0] detections << { type: pattern_name.to_s, original: matched_text, start_position: start_pos, end_position: end_pos, confidence: calculate_confidence(matched_text, pattern_name), masked_value: generate_mask(matched_text, pattern_name) } end end # Apply masking to create masked text detections.sort_by { |d| -d[:start_position] }.each do |detection| start_pos = detection[:start_position] end_pos = detection[:end_position] masked_text[start_pos...end_pos] = detection[:masked_value] end Report.new(text, detections, masked_text) end |
#mask(text) ⇒ Object
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 |
# File 'lib/ai_redactor/text_redactor.rb', line 20 def mask(text) return "" if text.nil? || text.empty? masked_text = text.dup detections = [] @patterns.each do |pattern_name| pattern = Patterns.get_pattern(pattern_name) next unless pattern flags = @case_sensitive ? 0 : Regexp::IGNORECASE regex = Regexp.new(pattern.source, flags) masked_text.gsub!(regex) do |match| start_pos = Regexp.last_match.begin(0) end_pos = Regexp.last_match.end(0) detections << { type: pattern_name.to_s, original: match, start_position: start_pos, end_position: end_pos, confidence: 1.0 } generate_mask(match, pattern_name) end end masked_text end |