Merge branch 'dev/dev_xp' into dev/dev
This commit is contained in:
@@ -3168,4 +3168,59 @@ public class PythonService {
|
||||
return Boolean.TRUE;
|
||||
}
|
||||
|
||||
public String promptTranslate(String text) throws BusinessException {
|
||||
OkHttpClient client = new OkHttpClient().newBuilder()
|
||||
.connectTimeout(30, TimeUnit.SECONDS)
|
||||
.pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒)
|
||||
.readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒)
|
||||
.writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒)
|
||||
.build();
|
||||
MediaType mediaType = MediaType.parse("application/json");
|
||||
|
||||
HashMap<String, String> content = new HashMap<>();
|
||||
content.put("text", text);
|
||||
|
||||
String jsonString = JSON.toJSONString(content, SerializerFeature.WriteNullStringAsEmpty);
|
||||
RequestBody body = RequestBody.create(mediaType, jsonString);
|
||||
Request request = new Request.Builder()
|
||||
.url(accessPythonIp + ":" + accessPythonPort + "/api/translateToEN")
|
||||
.method("POST", body)
|
||||
.addHeader("Content-Type", "application/json")
|
||||
.build();
|
||||
Response response = null;
|
||||
try {
|
||||
log.info("promptTranslation请求入参content###{}", jsonString);
|
||||
response = client.newCall(request).execute();
|
||||
} catch (IOException ioException) {
|
||||
log.error("PythonService##promptTranslation异常###{}", ExceptionUtil.getThrowableList(ioException));
|
||||
return text;
|
||||
}
|
||||
int responseCode = response.code();
|
||||
String bodyString;
|
||||
try {
|
||||
bodyString = response.body().string();
|
||||
if (responseCode != HttpURLConnection.HTTP_OK) {
|
||||
// 基本不会有除200以外的code
|
||||
log.info("promptTranslation 用户输入翻译失败。 Response code " + responseCode);
|
||||
throw new BusinessException("promptTranslation 用户输入翻译失败。 Response code " + responseCode);
|
||||
}
|
||||
JSONObject jsonObject = JSON.parseObject(bodyString);
|
||||
Boolean result = JSON.parseObject(JSON.toJSONString(response)).getBoolean("successful");
|
||||
if (result && jsonObject.get("msg").equals("OK!")) {
|
||||
String translated = jsonObject.get("data").toString();
|
||||
log.info("翻译或处理后的文本 : {}", translated);
|
||||
return translated;
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.error("promptTranslation 用户输入翻译失败; error message => " + e.getMessage());
|
||||
throw new RuntimeException(e);
|
||||
|
||||
} finally {
|
||||
response.close();
|
||||
}
|
||||
|
||||
log.info("promptTranslation 用户输入翻译失败,返回用户输入");
|
||||
return text;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user