TaskSystem/app/api/controller/XunFeiController.php

452 lines
17 KiB
PHP
Raw Normal View History

2023-09-12 12:36:32 +08:00
<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台PHP版
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码,建议反馈是我们前进的动力
// | 开源版本可自由商用可去除界面版权logo
// | gitee下载https://gitee.com/likeshop_gitee/likeadmin
// | github下载https://github.com/likeshop-github/likeadmin
// | 访问官网https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------
namespace app\api\controller;
2023-09-12 15:20:31 +08:00
use IFlytek\Xfyun\Speech\ChatClient;
2023-10-09 22:39:21 +08:00
use IFlytek\Xfyun\Speech\IatClient;
2023-10-10 13:40:27 +08:00
use IFlytek\Xfyun\Speech\TtsClient;
2023-10-10 17:52:37 +08:00
use IFlytek\Xfyun\Speech\OcrClient;
2023-10-14 15:32:48 +08:00
use think\facade\Db;
2023-09-12 15:20:31 +08:00
use WebSocket\Client;
2023-10-10 17:52:37 +08:00
use GuzzleHttp\Client as GzClient;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Exception\GuzzleException;
use Guzzle\Http\Exception\RequestException;
2023-09-12 12:36:32 +08:00
/**
* 讯飞
* Class WechatController
*/
class XunFeiController extends BaseApiController
{
2023-10-14 15:32:48 +08:00
public array $notNeedLogin = ['chat', 'iat', 'tts', 'ocr', 'iatWss', 'analyse'];
2023-09-12 12:36:32 +08:00
private $app_id='2eda6c2e';
2023-09-12 15:20:31 +08:00
private $api_key='12ec1f9d113932575fc4b114a2f60ffd';
private $api_secret='MDEyMzE5YTc5YmQ5NjMwOTU1MWY4N2Y2';
2023-09-12 12:36:32 +08:00
2023-10-14 15:32:48 +08:00
//星火认知chat
2023-09-12 15:20:31 +08:00
public function chat()
2023-09-12 12:36:32 +08:00
{
2023-09-12 16:44:15 +08:00
header('X-Accel-Buffering: no');
2023-10-14 11:56:12 +08:00
$content = $this->request->param('content');
if(empty($content)){
return $this->data(['answer' => '']);
2023-09-12 15:22:32 +08:00
}
2023-09-12 15:20:31 +08:00
$chat=new ChatClient($this->app_id,$this->api_key,$this->api_secret);
$client = new Client($chat->assembleAuthUrl('wss://spark-api.xf-yun.com/v2.1/chat'));
// 连接到 WebSocket 服务器
if ($client) {
2023-10-14 11:56:12 +08:00
$header = [
"app_id" => $this->app_id,
"uid" => "1"
];
$parameter = [
"chat" => [
"domain" => "generalv2",
"temperature" => 0.5,
"max_tokens" => 1024
]
];
$payload = [
"message" => [
"text" => [
["role" => "user", "content" => $content]
]
]
];
$data = json_encode([
"header" => $header,
"parameter" => $parameter,
"payload" => $payload
]);
2023-09-12 15:20:31 +08:00
$client->send($data);
$answer = "";
while(true){
$response = $client->receive();
2023-10-14 11:56:12 +08:00
$resp = json_decode($response, true);
$code = $resp["header"]["code"] ?? 0;
2023-09-12 15:20:31 +08:00
if(0 == $code){
$status = $resp["header"]["status"];
if($status != 2){
$content = $resp['payload']['choices']['text'][0]['content'];
$answer .= $content;
}else{
$content = $resp['payload']['choices']['text'][0]['content'];
$answer .= $content;
break;
}
}else{
2023-10-14 11:56:12 +08:00
return $this->fail( "服务返回报错 " . $response);
2023-09-12 15:20:31 +08:00
break;
}
}
2023-10-14 11:56:12 +08:00
return $this->data(['answer' => $answer]);
2023-09-12 15:20:31 +08:00
} else {
2023-09-12 16:44:15 +08:00
return $this->fail('无法连接到 WebSocket 服务器');
2023-09-12 15:20:31 +08:00
}
2023-09-12 12:36:32 +08:00
}
2023-09-12 15:20:31 +08:00
2023-10-14 15:32:48 +08:00
//AI分析信息
public function analyse()
{
$informationg_demand_id = $this->request->param('informationg_demand_id');
if(empty($informationg_demand_id)){
return $this->fail('信息参数错误');
}
$informationg = Db::name('user_informationg_demand')->where('id', $informationg_demand_id)->where('status', 1)->find();
$type_name = Db::name('category_business')->where('id', $informationg['category_child'])->value('name');
$data_field = json_decode($informationg['data_field'], true);
$demand = '';
foreach($data_field as $k=>$v) {
$demand .= $k . '' . $v . '';
}
2023-10-20 17:23:13 +08:00
$question = "根据以下{$type_name}信息【{$demand}】请问有那些商机?";
2023-10-14 15:32:48 +08:00
$chat=new ChatClient($this->app_id,$this->api_key,$this->api_secret);
$client = new Client($chat->assembleAuthUrl('wss://spark-api.xf-yun.com/v2.1/chat'));
// 连接到 WebSocket 服务器
if ($client) {
$header = [
"app_id" => $this->app_id,
"uid" => "1"
];
$parameter = [
"chat" => [
"domain" => "generalv2",
"temperature" => 0.5,
"max_tokens" => 1024
]
];
$payload = [
"message" => [
"text" => [
["role" => "user", "content" => $question]
]
]
];
$data = json_encode([
"header" => $header,
"parameter" => $parameter,
"payload" => $payload
]);
$client->send($data);
$answer = '';
while(true){
$response = $client->receive();
$resp = json_decode($response, true);
$code = $resp["header"]["code"] ?? 0;
if($code == 0){
$status = $resp["header"]["status"];
$content = $resp['payload']['choices']['text'][0]['content'] ?? '';
2023-10-14 15:55:48 +08:00
$answer .= $content;
2023-10-14 15:32:48 +08:00
if($status == 2){
break;
}
}else{
return $this->fail( "服务返回报错 " . $response);
break;
}
}
$data = [
2023-10-14 15:55:48 +08:00
'ai_aianalyse' => $answer,
2023-10-14 15:32:48 +08:00
'update_time' => time(),
];
2023-10-14 15:55:48 +08:00
$res = Db::name('user_informationg_demand')->where('id', $informationg_demand_id)->update($data);
2023-10-14 15:32:48 +08:00
if (!$res) {
return $this->fail('AI分析信息失败');
}
} else {
return $this->fail('无法连接到 WebSocket 服务器');
}
return $this->data(['question'=>$question, 'answer' => $answer]);
}
2023-10-10 13:40:27 +08:00
//语音听写(流式版)
2023-10-09 20:00:58 +08:00
public function iat()
{
2023-10-09 22:39:21 +08:00
header('X-Accel-Buffering: no');
2023-10-10 10:34:45 +08:00
$file = request()->file('audio');
2023-10-10 17:52:37 +08:00
if (empty($file)) {
2023-10-10 15:02:01 +08:00
return $this->fail('未上传音频文件');
2023-10-10 10:34:45 +08:00
}
2023-10-10 10:50:52 +08:00
// 上传音频临时文件
2023-10-10 10:34:45 +08:00
$savename = \think\facade\Filesystem::putFile('audio', $file);
2023-10-11 17:25:36 +08:00
2023-10-10 10:50:52 +08:00
$file = app()->getRootPath() . '/runtime/storage/' . $savename;
if (!file_exists($file)) {
2023-10-10 15:02:01 +08:00
return $this->fail('未上传音频文件');
2023-10-10 10:50:52 +08:00
}
2023-10-11 10:58:36 +08:00
$filesize = filesize($file);
if ($filesize > 1 * 1024 * 1024) {
return $this->fail('录音文件太长');
}
2023-10-11 17:37:13 +08:00
$last_file = substr($savename, -36);
2023-10-11 17:25:36 +08:00
$copyFile = app()->getRootPath() . '/public/uploads/iat/' . $last_file;
2023-10-11 18:42:09 +08:00
2023-10-14 11:56:12 +08:00
// ********** 临时方案 ********** //
2023-10-11 17:25:36 +08:00
copy($file, $copyFile);
2023-10-11 18:43:01 +08:00
// $last_file = 'a1fcdd96c7967b48add17b52ab456368.mp3';
2023-10-11 18:31:08 +08:00
$curl_url = "https://dev.app.tword.cn/ffmpeg.php?file={$last_file}";
$ch = curl_init();
2023-10-11 18:42:09 +08:00
curl_setopt($ch, CURLOPT_URL, $curl_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
2023-10-11 18:31:08 +08:00
curl_exec($ch);
curl_close($ch);
2023-10-11 18:21:52 +08:00
$file = "https://dev.app.tword.cn/iat/" . $last_file . ".pcm";
// $ext = pathinfo($file, PATHINFO_EXTENSION);
$ext = "pcm";
2023-10-11 11:26:30 +08:00
$extArray = ['mp3', 'pcm'];
if (!in_array($ext, $extArray)) {
2023-10-11 10:58:36 +08:00
return $this->fail('录音格式错误');
}
2023-11-03 14:30:57 +08:00
// ********** 临时方案 ********** //
2023-10-11 11:26:30 +08:00
$encoding = 'raw';
if ($ext == 'mp3') {
$encoding = 'lame';
}
if ($ext == 'pcm') {
$encoding = 'raw';
}
2023-10-10 10:34:45 +08:00
$audioFile = fopen($file, 'rb');
if ($audioFile === false) {
return $this->fail('音频文件异常');
}
2023-10-11 10:58:36 +08:00
try {
$words = '';
$iatHostUrl = "wss://iat-api.xfyun.cn/v2/iat";
$iat = new IatClient($this->app_id, $this->api_key, $this->api_secret);
$client = new Client($iat->assembleAuthUrl($iatHostUrl));
2023-10-11 15:04:34 +08:00
$frameSize = 1280; //每一帧的音频大小
$intervel = 20 * 1000; //发送音频间隔
$status = 0;
while (true) {
$len = fread($audioFile, $frameSize);
if ($len === false) {
break;
}
if ($len === '') { //文件读取完了
$status = 2;
2023-10-09 23:40:07 +08:00
}
2023-10-11 15:04:34 +08:00
switch ($status) {
case 0: //发送第一帧音频带business 参数
$frameData = array(
'common' => array(
'app_id' => $this->app_id //appid 必须带上,只需第一帧发送
),
'business' => array( //business 参数,只需一帧发送
'language' => 'zh_cn',
'domain' => 'iat',
'accent' => 'mandarin'
),
'data' => array(
'status' => 0,
'format' => 'audio/L16;rate=16000',
'audio' => base64_encode($len),
'encoding' => $encoding
)
);
$client->send(json_encode($frameData));
$status = 1;
2023-10-09 23:40:07 +08:00
break;
2023-10-11 15:04:34 +08:00
case 1:
$frameData = array(
'data' => array(
'status' => 1,
'format' => 'audio/L16;rate=16000',
'audio' => base64_encode($len),
'encoding' => $encoding
)
);
$client->send(json_encode($frameData));
2023-10-11 11:48:38 +08:00
break;
2023-10-11 15:04:34 +08:00
case 2:
$frameData = array(
'data' => array(
'status' => 2,
'format' => 'audio/L16;rate=16000',
'audio' => base64_encode($len),
'encoding' => $encoding
)
);
$client->send(json_encode($frameData));
break 2;
2023-10-10 10:34:45 +08:00
}
2023-10-11 15:04:34 +08:00
//模拟音频采样间隔
usleep($intervel);
}
while (true) {
$response = $client->receive();
if ($response === null) {
break;
}
$resp = json_decode($response, true);
$code = $resp['code'];
if ($code != 0) {
break;
}
$message = $resp['message'];
$data = $resp['data'];
$result = $data['result'];
$status = $data['status'];
foreach($result['ws'] as $v) {
$words .= $v['cw'][0]['w'] ?? '';
}
if ($status === 2) {
break;
2023-10-09 23:40:07 +08:00
}
}
2023-10-11 10:58:36 +08:00
fclose($audioFile);
2023-10-10 18:40:45 +08:00
// 删除临时音频文件
if (file_exists($file)) {
2023-10-11 15:04:34 +08:00
unlink($file);
2023-10-10 18:40:45 +08:00
}
2023-10-11 10:58:36 +08:00
} catch (\Exception $e) {
if (file_exists($file)) {
// 删除临时文件
unlink($file);
}
return $this->fail($e->getMessage());
2023-10-10 10:34:45 +08:00
}
return $this->data(['words' => $words]);
2023-10-09 20:00:58 +08:00
}
2023-10-14 15:32:48 +08:00
//获取语音听写流式版websocket地址
2023-10-11 14:10:00 +08:00
public function iatWss()
{
header('X-Accel-Buffering: no');
$iatHostUrl = "wss://iat-api.xfyun.cn/v2/iat";
$iat = new IatClient($this->app_id, $this->api_key, $this->api_secret);
$iat_wss = $iat->assembleAuthUrl($iatHostUrl);
//后期添加鉴权
return $this->data(['iat_wss' => $iat_wss]);
}
2023-10-10 13:40:27 +08:00
//语音合成(流式版)
public function tts()
2023-10-10 09:25:42 +08:00
{
header('X-Accel-Buffering: no');
2023-10-10 13:40:27 +08:00
$ttsHostUrl = "wss://tts-api.xfyun.cn/v2/tts";
2023-10-10 14:13:24 +08:00
$text = request()->param('text');
2023-10-10 17:52:37 +08:00
if (empty($text)) {
2023-10-10 14:00:57 +08:00
return $this->fail('未上传文本参数');
}
2023-10-10 15:23:52 +08:00
$file_name = date('YmdHis', time()) . mt_rand(1000, 9999) . '.mp3';
$date_path = date('Ymd');
$dir = app()->getRootPath() . '/public/uploads/audio/' . $date_path;
2023-10-10 14:23:19 +08:00
if (!is_dir($dir)) {
mkdir($dir, 0755, true);
}
$audioFile = $dir . '/' . $file_name;
2023-10-10 14:13:24 +08:00
$business = [
2023-10-10 15:23:52 +08:00
'aue' => 'lame', //mp3格式
2023-10-31 16:02:28 +08:00
'vcn' => 'aisjinger', //发音人
2023-10-10 15:23:52 +08:00
'auf' => 'audio/L16;rate=16000', //音频采样率
'speed' => 50, //语速
'volume' => 100, //音量
'pitch' => 50, //音高
'tte' => 'UTF8'
2023-10-10 14:13:24 +08:00
];
try {
$tts = new TtsClient($this->app_id, $this->api_key, $this->api_secret, $business);
file_put_contents($audioFile, $tts->request($text)->getBody()->getContents());
2023-10-11 09:53:18 +08:00
//生成语音文件需要定时清理
2023-10-10 14:13:24 +08:00
} catch (\Exception $e) {
2023-10-10 17:52:37 +08:00
return $this->fail($e->getMessage());
2023-10-10 14:13:24 +08:00
}
2023-10-10 15:23:52 +08:00
return $this->data(['audio_file' => request()->domain() . '/uploads/audio/' . $date_path . '/' . $file_name]);
2023-10-10 09:25:42 +08:00
}
2023-10-10 17:52:37 +08:00
//通用文字识别
public function ocr()
{
$ocrHostUrl = "https://api.xf-yun.com/v1/private/sf8e6aca1";
2023-10-19 17:36:22 +08:00
$file = request()->param('image');
2023-10-10 17:52:37 +08:00
if (empty($file)) {
return $this->fail('未上传图片文件');
}
2023-10-19 17:36:22 +08:00
/*
2023-10-10 17:52:37 +08:00
// 上传图片临时文件
$savename = \think\facade\Filesystem::putFile('ocr', $file);
$file = app()->getRootPath() . '/runtime/storage/' . $savename;
if (!file_exists($file)) {
return $this->fail('未上传图片文件');
}
$filesize = filesize($file);
if ($filesize > 4 * 1024 * 1024) {
return $this->fail('图片文件不能超过4M');
}
2023-10-19 17:36:22 +08:00
*/
2023-10-19 18:08:14 +08:00
$ext = pathinfo($file, PATHINFO_EXTENSION);
2023-10-10 17:52:37 +08:00
$base64_image = base64_encode(file_get_contents($file));
$ocr = new OcrClient($this->app_id, $this->api_key, $this->api_secret);
2023-10-11 09:53:18 +08:00
$ocrHostUrl = $ocr->assembleAuthUrl($ocrHostUrl);
2023-10-10 18:40:45 +08:00
$requestBody = [
'header' => [
'app_id' => $this->app_id,
'status' => 3
],
'parameter' => [
'sf8e6aca1' => [
'category' => 'ch_en_public_cloud',
'result' => [
'encoding' => 'utf8',
'compress' => 'raw',
'format' => 'json'
]
]
],
'payload' => [
'sf8e6aca1_data_1' => [
'encoding' => $ext,
'status' => 3,
'image' => $base64_image
]
]
];
2023-10-11 15:04:34 +08:00
$text = [];
2023-10-10 17:52:37 +08:00
try {
2023-10-19 18:16:11 +08:00
$client = new GzClient(['timeout' => 5]);
2023-10-10 17:52:37 +08:00
$response = $client->request('POST', $ocrHostUrl, [
2023-10-10 18:40:45 +08:00
'json' => $requestBody,
2023-10-10 17:52:37 +08:00
'verify' => false
]);
$responseData = $response->getBody()->getContents();
2023-10-11 15:04:34 +08:00
$responseArray = json_decode($responseData, true);
if (empty($responseArray['payload']['result']['text'])) {
return $this->fail('json解析错误');
2023-10-10 18:40:45 +08:00
}
2023-10-11 15:04:34 +08:00
$encodeText = $responseArray['payload']['result']['text'];
$textArray = json_decode(base64_decode($encodeText), true);
$lineArray = $textArray['pages'][0]['lines'] ?? [];
foreach($lineArray as $item) {
2023-10-21 09:28:35 +08:00
$content = $item['words'][0]['content'] ?? '';
if ($content) {
$text[] = $content;
}
2023-10-10 18:40:45 +08:00
}
2023-10-11 15:04:34 +08:00
} catch (GuzzleException $e) {
2023-10-10 17:52:37 +08:00
return $this->fail($e->getMessage());
}
2023-10-11 15:04:34 +08:00
return $this->data(['words' => $text]);
2023-10-10 17:52:37 +08:00
}
2023-09-12 12:36:32 +08:00
}