SchoolPhysicalExamination/application/test/controller/Baidufanyi.php

354 lines
14 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace app\test\controller;
use think\Controller;
use think\facade\Log;
use PhpOffice\PhpSpreadsheet\IOFactory;
class Baidufanyi extends Controller
{
// API Key - 按你说的放在控制器属性中
// protected $api_key = 'hMo4_d4p9d29a9802e5gscdf0';//自己的
// protected $app_id = '20251205002512839';//自己的
// protected $api_key = 'N0i8_d572v1iio4kk2k6v91kg';//公司
// protected $app_id = '20251218002521924';//公司
// protected $api_key = 'k185_d5759udrfk5qno0pjmdg';//邱总
// protected $app_id = '20251226002527798';//邱总
// protected $api_key = 'bT16_d57oa0lrfk5qno0pprj0';//同事
// protected $app_id = '20251227002528232';//同事
protected $api_key = '93PX_d58tcq538bmaitasivrg';//段莹
protected $app_id = '20251229002529158';//段莹
// 百度翻译API地址
protected $api_url = 'https://fanyi-api.baidu.com/ait/api/aiTextTranslate';
/**
* 百度翻译函数
* @param string $q 待翻译文本
* @param string $from 源语言(默认中文)
* @param string $to 目标语言(默认英文)
* @param array $options 可选参数
* - needIntervene: 是否使用自定义术语干预
* - model_type: 翻译模型 'llm'或'nmt'
* - reference: 自定义翻译指令
* - tag_handling: 标签保持功能
* - ignore_tags: 自定义标签
* @return array
*/
public function baiduTranslate($q, $from = 'zh', $to = 'en', $options = [])
{
try {
// 构建请求数据
$data = [
'q' => $q,
'from' => $from,
'to' => $to,
];
// 合并可选参数
$optional_params = ['needIntervene', 'model_type', 'reference', 'tag_handling', 'ignore_tags'];
foreach ($optional_params as $param) {
if (isset($options[$param]) && $options[$param] !== '') {
$data[$param] = $options[$param];
}
}
// 发送请求
$result = $this->httpPost($data);
// 解析结果
$result_array = json_decode($result, true);
if (isset($result_array['error_code'])) {
// 翻译失败
// Log::error('百度翻译API错误' . json_encode($result_array, JSON_UNESCAPED_UNICODE));
return [
'success' => false,
'error_code' => $result_array['error_code'],
'error_msg' => $result_array['error_msg'] ?? '翻译失败',
'data' => null
];
} else {
// 翻译成功
return [
'success' => true,
'error_code' => 0,
'error_msg' => '',
'data' => $result_array
];
}
} catch (\Exception $e) {
// Log::error('百度翻译异常:' . $e->getMessage());
return [
'success' => false,
'error_code' => '500',
'error_msg' => '系统异常:' . $e->getMessage(),
'data' => null
];
}
}
/**
* 发送HTTP POST请求
* @param array $data 请求数据
* @return string
*/
private function httpPost($data)
{
$ch = curl_init();
$data['appid'] = $this->app_id;
// 设置cURL选项
curl_setopt($ch, CURLOPT_URL, $this->api_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data, JSON_UNESCAPED_UNICODE));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $this->api_key
]);
curl_setopt($ch, CURLOPT_TIMEOUT, 10); // 10秒超时
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$response = curl_exec($ch);
$error = curl_error($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($error) {
throw new \Exception('cURL错误' . $error);
}
if ($httpCode != 200) {
throw new \Exception('HTTP请求失败状态码' . $httpCode);
}
return $response;
}
/**
* 使用示例
*/
public function translateDemo()
{
// 英语:en,德语:de,日语:jp,韩语:kor,阿拉伯语:ara,葡萄牙:pt,西班牙:spa,俄语:ru,法语:fra
// 示例1基本翻译
$result1 = $this->baiduTranslate('Beans, Dry, Dark Red Kidney (0% moisture)', 'en', 'zh');
// $result1 = $this->baiduTranslate('HUNTS ', 'en', 'zh');
dump($result1);
// // 示例2带可选参数的翻译
// $result2 = $this->baiduTranslate('Apples, gala, with skin, raw', 'en', 'zh', [
// 'model_type' => 'nmt',
// 'reference' => '使用学术风格翻译'
// ]);
// dump($result2);
// $result3 = $this->baiduTranslate('Tomatoes, diced, canned, HUNTS (CA) - NFY120AB9', 'en', 'zh');
// dump($result3);
// 示例3获取翻译结果
if ($result1['success']) {
$translated_text = '';
if (isset($result1['data']['trans_result'][0]['dst'])) {
$translated_text = $result1['data']['trans_result'][0]['dst'];
}
echo "翻译结果:" . $translated_text;
} else {
echo "翻译失败:" . $result1['error_msg'];
}
}
public function fanyi_action($data,$from,$to)
{
$result = $this->baiduTranslate($data, $from, $to);
return $result;
}
public function congli_fanyi(){
$congli = '{
"tips": {
"msgTitle": "友情提示",
"msgUpgradeFail": "升级失败",
"msgDownloading": "正在下载",
"msgLatestVersion": "已经是最新版本了!",
"msgCancel": "您已取消操作!",
"msgLoginSuccess": "登录成功!",
"msgDelete": "删除成功",
"msgSetSuccess": "设置成功",
"msgBottom": "到底了,看看别的吧",
"msgNoMoreData": "没有更多数据了!",
"msgSetPasswordSuccess": "密码设置成功,进入程序中!",
"msgAddUser": "暂无成员,请先添加",
"verifyNickName": "请输入昵称",
"verifyNotOptional": "未来日期不可选",
"verifyDate": "请选择测量日期",
"verifyBirthday": "请选择出生日期",
"verifyHeight": "请输入身高",
"verifyWeight": "请输入体重",
"verifyGender": "请选择性别",
"verifyBontrast": "请选择数据",
"verifyBodyDate": "请选择正确的时间",
"verifyRecord": "请输入",
"verifyPicker": "请选择",
"verifyAccount": "请输入正确的手机号或邮箱",
"verifyEmail": "请输入邮箱",
"verifyEmailCorrect": "请输入正确的邮箱",
"verifyMobile": "请输入手机号",
"verifyMobileCorrect": "请输入正确的手机号",
"verifyCode": "请输入验证码",
"verifyPassword": "请输入密码",
"verifyPasswordTwo": "请输入确认密码",
"verifyPasswordCorrect": "请确认两次密码填写一致",
"verifyAgreement": "请先确认并勾选协议",
"verifyOutLogin": "是否退出登录?",
"verifyDeleteUser": "是否删除该成员?",
"verifyDeleteHistory": "是否删除当前测量记录?",
"verifyDeleteAccount": "删除成功后,该账号的所有关联信息将被清空且无法找回,是否删除?",
"btnConfirm": "确认",
"btnSubmit": "提交",
"btnSancellation": "取消",
"btnContinue": "继续",
"btnBack": "返回",
"btnDelete": "删除"
},
"linkBluetooth": {
"ConnectionTimeout": "连接超时,点击重新连接",
"Measuring": "测量中,请将食物放到秤上",
"Weight": "重量",
"RecordWeight": "请输入食物重量",
"Search": "蓝牙搜索中",
"Remeasure": "数据异常,请重新测量!",
"reset": "数据异常,请清零后重新测量!",
"Disconnect": "断开连接",
"remeasure": "重新测量",
"resetBtn": "清零",
"UnitBtn": "单位",
"SaveResult": "保存"
},
"common": {
"titleHome": "首页",
"titleMenu": "菜谱",
"titleMenuAdd": "添加食谱",
"titleMenuSearch": "搜索菜谱",
"titleCount": "计食",
"titleCountList": "食材库",
"titleCustomKcal": "自定义卡路里",
"titleEveryMeal": "餐食详情",
"titleCountSearch": "食材搜索",
"titleeveryDay": "营养分析",
"titleMe": "我的",
"titleDetail": "详情",
"titleBody": "目标",
"titleHistory": "饮食记录",
"titlePhone": "绑定手机号",
"titleEmail": "绑定邮箱",
"titlePasswordEdit": "修改密码",
"titleSet": "设置",
"titleDate": "日期",
"titleMember": "资料",
"titleManage": "成员管理",
"titleManageAdd": "添加成员",
"titleAboutUs": "关于我们",
"titleSetPassword": "设置密码",
"titlePassword": "密码",
"titleConfirmPassword": "确认密码",
"titleForgotPassword": "忘记密码",
"titleCode": "验证码",
"titleLanguage": "语言设置",
"titleSendCode": "获取验证码",
"titleSendCodeRetry": "S后重发",
"titleLogin": "登录",
"titleRegister": "注册",
"titleToggleLogin": "切换登录",
"titleAccountText": "手机号/邮箱",
"titleAgreementText": "阅读并同意",
"titleAgreementContntText": "隐私协议",
"titleVersionUpdate": "版本更新",
"titleNewVersion": "新版本",
"infoActivityCoefficient": "活动系数",
"infoPersonalProfile": "个人资料",
"infoMyRecipes": "我的菜谱",
"infoMyCollection": "我的收藏",
"infoAvatar": "头像",
"infoNickname": "昵称",
"infoMobile": "手机号",
"infoEmail": "邮箱",
"infoAge": "年龄",
"infoAgeunit": "岁",
"infoGender": "性别",
"infoMan": "男",
"infoWoman": "女",
"infoUnknown": "未知",
"infoBirthday": "出生日期",
"infoHeight": "身高",
"infoWeight": "体重",
"btnEdit": "编辑",
"btnDelete": "删除",
"btnAdd": "添加",
"btnDetail": "查看详情",
"btnDeleteAccount": "删除账号",
"btnLogOut": "退出登录"
},
"countIntake": "摄入",
"countCalorieIntake": "热量摄入",
"countMealdetails": "餐食详情",
"countAddFood": "添加食物",
"countNutritionalProportion": "营养占比",
"countComponentStatistics": "成分统计",
"countCalorieAnalysis": "卡路里分析",
"countNutrientElementEnergyProportion": "营养元素能量占比",
"countNutritionClassification": "营养分类",
"countNutritionElementRankingList": "营养元素排行榜",
"countFoodTypes": "食物类型"
}';
$congli_arr = json_decode($congli,true);
// foreach ($congli_arr as $key => $value) {
// if(is_array($value)){
// foreach ($value as $k => $v) {
// $congli_arr[$key][$k] = $this->baiduTranslate($v, 'zh', 'en');
// }
// }else{
// $congli_arr[$key] = $this->baiduTranslate($value, 'zh', 'en');
// }
// }
// foreach ($congli_arr as $key => $value) {
// if(!is_array($value)){
// $congli_arr[$key] = $this->baiduTranslate($value, 'zh', 'en')['data']['trans_result'][0]['dst'];
// }
foreach ($congli_arr['tips'] as $key => $value) {
$congli_arr['tips'][$key] = $this->baiduTranslate($value, 'zh', 'en')['data']['trans_result'][0]['dst'];
}
return $this->msg(0,'成功',$congli_arr);
}
public function msg($code,$str,$data){
return json(['code'=>$code,'msg'=>$str,'data'=>$data]);
}
}