用deepseek写了一个对联识别上下联功能

167 阅读1分钟

以下是一个基于ThinkPHP6.1和DeepSeek API实现对联上下联识别的示例代码。该方案结合传统平仄规则和AI模型判断,提高准确率。

php

复制

// 应用目录结构
app/
├─ controller/
│  └─ Couplet.php
├─ service/
│  └─ CoupletService.php
config/
├─ deepseek.php
view/
└─ couplet/
   └─ index.html

// 步骤1:配置DeepSeek API信息
// config/deepseek.php
<?php
return [
    'api_key' => 'your_deepseek_api_key',
    'base_url' => 'https://api.deepseek.com/v1/chat/completions'
];

php

复制

// 步骤2:服务类处理核心逻辑
// app/service/CoupletService.php
<?php
namespace app\service;

use think\facade\Config;

class CoupletService
{
    private $apiKey;
    private $baseUrl;

    public function __construct()
    {
        $config = Config::get('deepseek');
        $this->apiKey = $config['api_key'];
        $this->baseUrl = $config['base_url'];
    }

    public function identifyCouplet($sentence1, $sentence2)
    {
        // 先检查平仄规则
        $resultByTone = $this->checkByTone($sentence1, $sentence2);
        if ($resultByTone) return $resultByTone;

        // 平仄无法判断时调用AI模型
        return $this->checkByAI($sentence1, $sentence2);
    }

    private function checkByTone($s1, $s2)
    {
        require_once 'Pinyin.php'; // 引入拼音转换库
        
        $s1LastChar = mb_substr($s1, -1);
        $s2LastChar = mb_substr($s2, -1);
        
        $tone1 = $this->getTone($s1LastChar);
        $tone2 = $this->getTone($s2LastChar);

        if ($tone1 === '仄' && $tone2 === '平') {
            return ['上联' => $s1, '下联' => $s2];
        }

        if ($tone1 === '平' && $tone2 === '仄') {
            return ['上联' => $s2, '下联' => $s1];
        }

        return null;
    }

    private function getTone($char)
    {
        // 使用拼音库获取声调(示例实现)
        $pinyin = \Overtrue\Pinyin\Pinyin::sentence($char);
        $tone = substr($pinyin, -1);
        
        // 判断平仄(简化为:一声二声为平,三声四声为仄)
        return in_array($tone, [1, 2]) ? '平' : '仄';
    }

    private function checkByAI($s1, $s2)
    {
        $client = new Client();

        $prompt = "请严格按json格式返回结果。判断以下哪个是上联,示例格式:{'上联' : '...', '下联' : '...'}\n对联A:$s1\n对联B:$s2";

        $response = $client->post($this->baseUrl, [
            'headers' => [
                'Authorization' => 'Bearer ' . $this->apiKey,
                'Content-Type' => 'application/json'
            ],
            'json' => [
                'model' => 'deepseek-chat',
                'messages' => [
                    ['role' => 'user', 'content' => $prompt]
                ],
                'temperature' => 0.3
            ]
        ]);

        $result = json_decode($response->getBody(), true);
        $cleanedString = str_replace('```', '', $result['choices'][0]['message']['content']);
        $str = str_replace('json','',$cleanedString);
        $aiResponse = json_decode($str, true);
        return [
            '上联' => $aiResponse['上联'],
            '下联' => $aiResponse['下联'],
        ];
    }

php

复制

// 步骤3:控制器处理请求
// app/controller/Couplet.php
<?php
namespace app\controller;

use app\BaseController;
use app\service\CoupletService;
use think\facade\Request;
use think\facade\View;

class Couplet extends BaseController
{
    public function index()
    {
        return View::fetch('index');
    }

    public function identify()
    {
        $sentence1 = Request::param('sentence1');
        $sentence2 = Request::param('sentence2');

        try {
            $service = new CoupletService();
            $result = $service->identifyCouplet($sentence1, $sentence2);
            
            return json([
                'code' => 200,
                'data' => $result
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }
}

html

复制

<!-- 步骤4:前端视图 -->
<!-- view/couplet/index.html -->
<!DOCTYPE html>
<html>
<head>
    <title>对联识别</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
    <div style="max-width: 600px; margin: 50px auto;">
        <h1>对联上下联识别</h1>
        <form id="coupletForm">
            <div>
                <label>输入1:</label>
                <input type="text" name="sentence1" style="width: 300px;">
            </div>
            <div style="margin: 15px 0;">
                <label>输入2:</label>
                <input type="text" name="sentence2" style="width: 300px;">
            </div>
            <button type="button" onclick="identify()">识别</button>
        </form>
        
        <div id="result" style="margin-top: 30px; padding: 20px; border: 1px solid #ccc;">
            <p>识别结果:</p>
            <div id="output"></div>
        </div>
    </div>

    <script>
    function identify() {
        $.post('/couplet/identify', $('#coupletForm').serialize(), function(res){
            if(res.code === 200) {
                const data = res.data;
                let html = `<p>上联:${data.上联}</p>
                          <p>下联:${data.下联}</p>
                          <p>识别方式:${data.method || '平仄规则判断'}</p>`;
                $('#output').html(html);
            } else {
                alert('识别失败:' + res.msg);
            }
        });
    }
    </script>
</body>
</html>