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

Improve recognition of untranslated text #477

Merged
merged 6 commits into from
Aug 8, 2024
Merged
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
16 changes: 13 additions & 3 deletions src/main/java/net/wurstclient/util/GoogleTranslate.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,16 @@ public enum GoogleTranslate
{
;

private static final Pattern ALL_WHITESPACE = Pattern.compile("\\s+");

public static String translate(String text, String langFrom, String langTo)
{
String html = getHTML(text, langFrom, langTo);
String translated = parseHTML(html);

if(text.equalsIgnoreCase(translated))
// Detect if Google translate returned the original text, maybe with
// some whitespace or capitalization changes, and return null if so
if(simplify(text).equals(simplify(translated)))
return null;

return translated;
Expand Down Expand Up @@ -96,14 +100,20 @@ private static String parseHTML(String html)
Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);

Matcher matcher = pattern.matcher(html);
matcher.find();
String match = matcher.group(1);
if(!matcher.find())
return null;

String match = matcher.group(1);
if(match == null || match.isEmpty())
return null;

// deprecated in favor of org.apache.commons.text.StringEscapeUtils,
// which isn't bundled with Minecraft
return org.apache.commons.lang3.StringEscapeUtils.unescapeHtml4(match);
}

private static String simplify(String text)
{
return ALL_WHITESPACE.matcher(text).replaceAll("").toLowerCase();
}
}