GeoQuestionRes.php 9.4 KB
<?php
/**
 * @remark :
 * @name   :GeoQuestionResController.php
 * @author :lyh
 * @method :post
 * @time   :2025/7/3 15:13
 */

namespace App\Console\Commands\Geo;

use App\Models\Geo\GeoPlatform;
use App\Models\Geo\GeoQuestion;
use App\Models\Geo\GeoQuestionLog;
use App\Models\Geo\GeoQuestionResult;
use App\Models\Project\Project;
use App\Services\Geo\GeoService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;

class GeoQuestionRes extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'geo_question_result';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'geo设置请求获取结果';


    /**
     * @return bool
     */
    public function handle()
    {
        while (true) {
            $task_id = $this->getTaskId();
            if (empty($task_id)) {
                sleep(300);
                continue;
            }
            echo date('Y-m-d H:i:s').'执行的任务id:'.$task_id.PHP_EOL;
            $geoQuestionModel = new GeoQuestion();
            $taskInfo = $geoQuestionModel->read(['id'=>$task_id]);
            if ($taskInfo === false) {
                $this->output('当前任务详情为空!');
                continue;
            }
            $projectModel = new Project();
            $projectInfo = $projectModel->read(['id' => $taskInfo['project_id']],['geo_status', 'geo_frequency']);
            if ($projectInfo === false) {
                $this->output('未获取到项目详情!');
                $geoQuestionModel->edit(['status'=>$geoQuestionModel::STATUS_CLOSE],['id'=>$task_id]);
                continue;
            }
            if(empty($taskInfo['question']) || empty($taskInfo['keywords']) || empty($taskInfo['url'])){
                $this->output('task id: ' . $task_id . ', error: 任务数据缺失, continue!');
                $geoQuestionModel->edit(['status'=>$geoQuestionModel::STATUS_CLOSE],['id'=>$task_id]);
                continue;
            }
            $geoPlatformModel = new GeoPlatform();
            $platformsArr = $geoPlatformModel->selectField(['status' => GeoPlatform::STATUS_ON],'en_name');
            if (empty($platformsArr)) {
                $this->output('未设置AI模型!');
                continue;
            }
            $geo_service = new GeoService();
            $geoResultModel = new GeoQuestionResult();
            $geoLogModel = new GeoQuestionLog();
            foreach ($taskInfo['question'] as $question) {
                $error_num = 0;
                foreach ($platformsArr as $platform) {
                    // 设置重试, 有的平台不一定能正常获取到数据
                    GET_RESULT:
                    $error_num++;
                    try {
                        if ($error_num >= 5) {
                            continue;
                        }
                        if ($platform == 'Google AI Overview') {
                            continue;
                            // overview 数据结构不确定, 需要单独处理数据
                            $data = $geo_service->getGooglePlatformResult($question);
                            $result = $this->dealGoogleData($data);
                        } else {
                            $result = $geo_service->getAiPlatformResult($question, $platform);
                        }
                        if (empty($result['text'])){
                            goto GET_RESULT;
                        }
                    } catch (\Exception $e) {
                        $this->output('task id:' . $task_id . ', question: ' . $question . ', platform: ' . $question . ', error: ' . $e->getMessage());
                        goto GET_RESULT;
                    }
                    // 命中文案
                    $hit_data[] = $result['text'];
                    if(!empty($result['annotations'])){
                        $url = array_column(array_column($result['annotations'], 'url_citation'), 'url');
                        $title = array_column(array_column($result['annotations'], 'url_citation'), 'title');;
                        $hit_data = array_merge($url, $title, $hit_data);
                    }
                    $hit_string = implode(',', $hit_data);
                    // 命中关键词和路由
                    $hit_keyword = $hit_url = [];
                    $hit = 0;
                    if (!empty($taskInfo['keywords'])) {
                        $pattern = '/(' . implode('|', array_map('preg_quote', $taskInfo['keywords'])) . ')/i';
                        if (preg_match($pattern, $hit_string, $matches)) {
                            $hit_keyword = $matches[0];
                            $hit++;
                        }
                    }
                    if (!empty($taskInfo['url'])) {
                        $pattern = '/(' . implode('|', array_map('preg_quote', $taskInfo['url'])) . ')/i';
                        if (preg_match($pattern, $hit_string, $matches)) {
                            $hit_url = $matches[0];
                            $hit++;
                        }
                    }
                    // 保存数据结果
                    $geo_result = $geoResultModel->read(['project_id' => $taskInfo['project_id'], 'question_id' => $task_id, 'platform' => $platform, 'question' => $question],['id']);
                    $save_data = [
                        'project_id' => $taskInfo['project_id'],
                        'question_id' => $task_id,
                        'type' => $taskInfo['type'] ?? $geoQuestionModel::TYPE_BRAND,
                        'platform' => $platform,
                        'question' => $question,
                        'keywords' => json_encode($hit_keyword,true),//命中的关键词
                        'url' => json_encode($hit_url,true),//命中的网址
                        'text' => json_encode($result,true),
                        'hit' => $hit
                    ];
                    if($geo_result === false){
                        $geoResultModel->addReturnId($save_data);
                    }else{
                        $geoResultModel->edit($save_data, ['id' => $geo_result->id]);
                    }
                    $save_data['text'] = json_encode(FALSE == empty($data) ? $data : $result,true);
                    $geoLogModel->addReturnId($data);
                }
            }
            $next_time = date('Y-m-d', strtotime('+' . ($projectInfo['geo_frequency'] ?? 3) . ' days'));
            $geoQuestionModel->edit(['current_time'=>date('Y-m-d'),'next_time'=>$next_time],['id'=>$task_id]);
        }
        return true;
    }

    /**
     * 整合Google平台数据
     * @param $data
     * @return array
     */
    public function dealGoogleData($data)
    {
        $result = [
            'code' => 200,
            'model' => 'Google AI Overview',
            'text' => '',
        ];
        if (FALSE == empty($data['ai_overview']['texts']) && is_array($data['ai_overview']['texts'])) {
            $texts = [];
            foreach ($data['ai_overview']['texts'] as $item) {
                // 提取链接
                if (FALSE == empty($item['links'])) {
                    foreach ($item['links'] as $link) {
                        if (FALSE == empty($link['text']) && FALSE == empty($link['link'])) {
                            $result['annotations'][] = [
                                'type' => 'url_citation',
                                'url_citation' => [
                                    'url' => $link['link'],
                                    'title' => $link['text']
                                ],
                            ];
                        }
                    }
                }
                // 第一层就有内容
                if (FALSE == empty($item['snippet'])) {
                    // title 放到数组最前面
                    if (FALSE == empty($item['type']) && $item['type'] == 'title')
                        array_unshift($texts, $item['snippet']);
                    else
                        array_push($texts, $item['snippet']);
                }
                // list类型
                if (FALSE == empty($item['type']) && $item['type'] == 'list' && FALSE == empty($item['list']) && is_array($item['list'])) {
                    foreach ($item['list'] as $list) {
                        if (FALSE == empty($list['snippet']))
                            array_push($texts, $list['snippet']);
                    }
                }
            }
            $text = implode(PHP_EOL, $texts);
            $result['text'] = $text;
        }
        return $result;
    }

    /**
     * 获取待执行任务ID
     * @return mixed
     */
    public function getTaskId(){
        $key = 'geo_task_list';
        $task_id = Redis::rpop($key);
        if(empty($task_id)){
            $questionModel = new GeoQuestion();
            $ids = $questionModel->selectField(['status'=>$questionModel::STATUS_OPEN,'next_time'=>['<=',date('Y-m-d')]],'id');
            if(!empty($ids)){
                foreach ($ids as $id) {
                    Redis::lpush($key, $id);
                }
            }
            $task_id = Redis::rpop($key);
        }
        return $task_id;
    }

    /**
     * 输出日志
     * @param $message
     * @return bool
     */
    public function output($message)
    {
        echo date('Y-m-d H:i:s') . ' ' . $message . PHP_EOL;
        return true;
    }
}