Skip to content
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
6 changes: 6 additions & 0 deletions app/services/discourse_translator/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,12 @@ def self.get_text(topic_or_post)
end
end

def self.strip_img_for_detection(detection_text)
html_doc = Nokogiri::HTML::DocumentFragment.parse(detection_text)
html_doc.css("img").remove
html_doc.to_html
Comment on lines +66 to +67
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This needs to be separate lines 😅

end

def self.language_supported?(detected_lang)
raise NotImplementedError unless self.const_defined?(:SUPPORTED_LANG_MAPPING)
supported_lang = const_get(:SUPPORTED_LANG_MAPPING)
Expand Down
4 changes: 3 additions & 1 deletion app/services/discourse_translator/google.rb
Original file line number Diff line number Diff line change
Expand Up @@ -76,9 +76,11 @@ def self.access_token
end

def self.detect(topic_or_post)
detection_text = get_text(topic_or_post).truncate(MAXLENGTH, omission: nil)
detection_text = strip_img_for_detection(detection_text)
topic_or_post.custom_fields[DiscourseTranslator::DETECTED_LANG_CUSTOM_FIELD] ||= result(
DETECT_URI,
q: get_text(topic_or_post).truncate(MAXLENGTH, omission: nil),
q: detection_text,
)[
"detections"
][
Expand Down
30 changes: 29 additions & 1 deletion spec/services/google_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
end

describe ".detect" do
let(:post) { Fabricate(:post) }
fab!(:post)

it "should store the detected language in a custom field" do
detected_lang = "en"
Expand Down Expand Up @@ -74,6 +74,34 @@

expect(described_class.detect(post)).to eq(detected_lang)
end

it "strips img tags from detection text" do
post.cooked = "there are some words <img src='http://example.com/image.jpg'> to be said"
detected_lang = "en"

request_url = "#{DiscourseTranslator::Google::DETECT_URI}"
body = { q: "there are some words to be said", key: api_key }

Excon
.expects(:post)
.with(
request_url,
body: URI.encode_www_form(body),
headers: {
"Content-Type" => "application/x-www-form-urlencoded",
"Referer" => "http://test.localhost",
},
)
.returns(
mock_response.new(
200,
%{ { "data": { "detections": [ [ { "language": "#{detected_lang}", "isReliable": false, "confidence": 0.18397073 } ] ] } } },
),
)
.once

expect(described_class.detect(post)).to eq(detected_lang)
end
end

describe ".translate_supported?" do
Expand Down