Browse Source

Merge pull request #2422 from visuddhinanda/development

Development
visuddhinanda 3 weeks ago
parent
commit
8715d48872

+ 4 - 52
api-v13/app/Console/Commands/ExtractPaliTerm.php

@@ -5,12 +5,11 @@ namespace App\Console\Commands;
 use App\Helpers\LlmResponseParser;
 use App\Http\Api\ChannelApi;
 use App\Http\Resources\AiModelResource;
-use App\Models\DhammaTerm;
 use App\Models\PaliText;
-use App\Models\UserDict;
 use App\Services\AIModelService;
 use App\Services\OpenAIService;
 use App\Services\SentenceService;
+use App\Services\TermService;
 use Illuminate\Console\Command;
 use Illuminate\Support\Facades\Cache;
 use Illuminate\Support\Facades\Log;
@@ -21,14 +20,6 @@ class ExtractPaliTerm extends Command
     // 使命令可重入——中断后重跑自动跳过已完成的 chapter
     private const CURSOR_KEY = 'extract:pali.term:cursor';
 
-    // 术语表额外纳入的 user_dicts 词典 id(其 word 去除连字符与空格后加入)
-    private const USER_DICT_IDS = [
-        'b089de57-f146-4095-b886-057863728c43',
-        '0bfd87ec-f3ac-49a2-985e-28388779078d',
-        '7c7ee287-35ba-4cf3-b87b-30f1fa6e57c9',
-        '4ac8a0d5-9c6f-4b9f-983d-84288d47f993',
-    ];
-
     /**
      * 用 LLM 从巴利文经文中提取术语。
      *
@@ -80,7 +71,8 @@ class ExtractPaliTerm extends Command
     public function __construct(
         protected AIModelService $modelService,
         protected OpenAIService $openAIService,
-        protected SentenceService $sentenceService
+        protected SentenceService $sentenceService,
+        protected TermService $termService
     ) {
         parent::__construct();
     }
@@ -177,27 +169,7 @@ class ExtractPaliTerm extends Command
      */
     private function loadGlossaryJson(): ?string
     {
-        // 1) dhamma_terms 全表 distinct 词条原形(不限 channel),排除 word 含空格的短语条目
-        $dhammaWords = DhammaTerm::query()
-            ->whereNotNull('word')
-            ->where('word', '!=', '')
-            ->where('word', 'not like', '% %')
-            ->distinct()
-            ->pluck('word')
-            ->all();
-
-        // 2) user_dicts 指定词典的词,去除连字符与空格后加入
-        $userWords = UserDict::query()
-            ->whereIn('dict_id', self::USER_DICT_IDS)
-            ->whereNotNull('word')
-            ->where('word', '!=', '')
-            ->pluck('word')
-            ->map(fn ($w) => str_replace(['-', ' '], '', (string) $w))
-            ->all();
-
-        // 合并 + NFC 归一(避免巴利文变音符 NFC/NFD 不一致)+ 去空 + 去重
-        $terms = array_map(fn ($w) => $this->toNfc(trim((string) $w)), array_merge($dhammaWords, $userWords));
-        $terms = array_values(array_unique(array_filter($terms, fn ($w) => $w !== '')));
+        $terms = $this->termService->getGlossary();
 
         if (empty($terms)) {
             $this->error('glossary is empty');
@@ -209,11 +181,6 @@ class ExtractPaliTerm extends Command
         $this->glossarySet = array_fill_keys($terms, true);
 
         $this->info('glossary loaded: '.count($terms).' terms (dhamma_terms + user_dicts)');
-        Log::info('extract:pali.term glossary loaded', [
-            'total' => count($terms),
-            'dhamma_terms' => count($dhammaWords),
-            'user_dicts' => count($userWords),
-        ]);
 
         return json_encode($terms, JSON_UNESCAPED_UNICODE);
     }
@@ -297,21 +264,6 @@ class ExtractPaliTerm extends Command
         return $next ? (int) $next - 1 : $maxParagraph;
     }
 
-    /**
-     * Unicode 规范化为 NFC(巴利文变音符匹配需统一 NFC/NFD)。intl 不可用时原样返回。
-     */
-    private function toNfc(string $s): string
-    {
-        if (class_exists(\Normalizer::class)) {
-            $normalized = \Normalizer::normalize($s, \Normalizer::FORM_C);
-            if ($normalized !== false) {
-                return $normalized;
-            }
-        }
-
-        return $s;
-    }
-
     /**
      * 判断某 chapter 是否在断点游标(含)之前——即已完成、应跳过。
      *

+ 79 - 22
api-v13/app/Console/Commands/UpgradeAITerm.php

@@ -2,25 +2,34 @@
 
 namespace App\Console\Commands;
 
-use Illuminate\Console\Command;
-
-use App\Services\AIModelService;
-use App\Services\TermService;
+use App\Http\Resources\AiModelResource;
 use App\Services\AIAssistant\AITermService;
+use App\Services\AIModelService;
 use App\Services\AuthService;
-
-use App\Http\Resources\AiModelResource;
-
+use App\Services\TermService;
+use Illuminate\Console\Command;
+use Illuminate\Support\Facades\Cache;
 
 class UpgradeAITerm extends Command
 {
+    // 断点缓存键:记录 channel 模式下最后一个已完成的术语游标 ['index'=>int,'word'=>string],
+    // 使命令可重入——中断后重跑自动跳过已完成的术语
+    private const CURSOR_KEY = 'upgrade:ai.term:cursor';
+
     /**
      * The name and signature of the console command.
-     * php artisan upgrade:ai.term  --id=e07bf5b8-bd81-4f0a-9d2c-8e0128b954d7
-     * php artisan upgrade:ai.term
+     * php artisan upgrade:ai.term {model} --id=e07bf5b8-bd81-4f0a-9d2c-8e0128b954d7
+     * php artisan upgrade:ai.term {model} --channel={channelId}
+     *
      * @var string
      */
-    protected $signature = 'upgrade:ai.term {--id=} {--resume} {--model=} ';
+    protected $signature = 'upgrade:ai.term
+    {model : LLM 模型 id}
+    {--word= : 保留参数}
+    {--channel= : 遍历术语表,逐词生成/更新到该 channel}
+    {--id= : 仅处理该术语 guid}
+    {--thinking= : 开启/关闭 deepseek thinking,true | false}
+    {--fresh : 清除断点缓存,从头开始}';
 
     /**
      * The console command description.
@@ -30,9 +39,15 @@ class UpgradeAITerm extends Command
     protected $description = 'Command description';
 
     protected AiModelResource $model;
+
     protected $modelToken;
+
     protected $workChannel;
+
     protected $accessToken;
+
+    protected ?bool $thinking = null;
+
     /**
      * Create a new command instance.
      *
@@ -54,28 +69,70 @@ class UpgradeAITerm extends Command
      */
     public function handle()
     {
-        if (!$this->option('model')) {
-            $modelId = $this->ask('请输入 llm model id');
-        } else {
-            $modelId = $this->option('model');
-        }
+        $modelId = $this->argument('model');
+
         $this->aiTermService->setModel($modelId);
         $this->model = $this->modelService->getModelById($modelId);
         $this->info("model:{$this->model['model']}");
         $this->modelToken = AuthService::getUserToken($modelId);
 
+        if ($this->option('thinking') !== null) {
+            $this->thinking = $this->option('thinking') === 'true';
+        }
+        $this->aiTermService->setThinking($this->thinking);
+
+        if ($this->option('fresh')) {
+            Cache::forget(self::CURSOR_KEY);
+            $this->info('cleared checkpoint');
+        }
+
         if ($this->option('id')) {
-            $terms = [['guid' => $this->option('id'), 'word' => 'word']];
+            $this->info($this->option('id').' running');
+            $result = $this->aiTermService->update($this->option('id'));
+            $this->info('done content '.substr($result, 0, 30));
+        } elseif ($this->option('channel')) {
+            $this->runChannel($this->option('channel'));
         } else {
-            $terms = $this->termService->getCommunityGlossary('zh-Hans')['items']->toArray();
-        }
+            $this->error('id or channel is request');
 
-        foreach ($terms as $key => $term) {
-            $this->info("[{$term['word']}] running");
-            $result = $this->aiTermService->update($term['guid']);
-            $this->info("[{$term['word']}]content " . substr($result, 0, 30));
+            return 1;
         }
 
         return 0;
     }
+
+    /**
+     * 遍历术语表,逐词生成/更新到指定 channel;逐词写入断点以支持重入。
+     *
+     * 断点游标记录最后一个已完成术语的 word 与 index;重跑时优先按 word 在当前术语表中
+     * 定位续跑位置(术语表尾部新增也能正确接续),找不到则回退到 index。
+     */
+    private function runChannel(string $channelId): void
+    {
+        $terms = $this->termService->getGlossary();
+        $total = count($terms);
+        $this->info("{$total} terms");
+
+        $startIndex = 0;
+        $cursor = Cache::get(self::CURSOR_KEY, []);
+        if (! empty($cursor)) {
+            $pos = array_search($cursor['word'] ?? null, $terms, true);
+            $startIndex = $pos !== false ? (int) $pos + 1 : (int) ($cursor['index'] ?? -1) + 1;
+            $this->info("resume from index {$startIndex} (after word [{$cursor['word']}])");
+        }
+
+        for ($key = $startIndex; $key < $total; $key++) {
+            $term = $terms[$key];
+            $this->info("[{$key}/{$total}][{$term}] running");
+            $result = $this->aiTermService->updateOrCreate($channelId, $term);
+            $this->info("[{$term}]content ".substr($result, 0, 30));
+
+            // 该术语完成后写入断点(中途中断时不会误标记未完成的术语)
+            Cache::put(self::CURSOR_KEY, ['index' => $key, 'word' => $term], now()->addHours(48));
+        }
+
+        // 全部完成,清空断点
+        Cache::forget(self::CURSOR_KEY);
+        $this->info('all terms completed');
+    }
 }

+ 22 - 19
api-v13/app/Console/Commands/UpgradeAITranslation.php

@@ -2,10 +2,6 @@
 
 namespace App\Console\Commands;
 
-use Illuminate\Console\Command;
-use Illuminate\Support\Facades\Cache;
-use Illuminate\Support\Facades\Log;
-
 use App\Helpers\LlmResponseParser;
 use App\Http\Api\ChannelApi;
 use App\Http\Resources\AiModelResource;
@@ -17,8 +13,9 @@ use App\Services\AIModelService;
 use App\Services\AuthService;
 use App\Services\OpenAIService;
 use App\Services\SentenceService;
-
-use function PHPUnit\Framework\isEmpty;
+use Illuminate\Console\Command;
+use Illuminate\Support\Facades\Cache;
+use Illuminate\Support\Facades\Log;
 
 class UpgradeAITranslation extends Command
 {
@@ -47,7 +44,7 @@ class UpgradeAITranslation extends Command
     {--resume}
     {--model=}
     {--thinking= : 开启和关闭deepseek thinking true | false}
-    {--steps=translate : translation 工作流步骤,逗号分隔,可选 translate,review,revise,evaluate(evaluate 为质量评估,须放最后)}
+    {--steps=translate : translation 工作流步骤,逗号分隔,可选 translate,term,review,revise,evaluate(term 为术语标注,可单独运行;evaluate 为质量评估,须放最后)}
     {--nissaya=translate,review,evaluate : 启用 nissaya 参考资料的步骤,逗号分隔,可选 translate,review,evaluate;传空字符串则全部不注入}
     {--fresh : 清除缓存断点,从头开始}';
 
@@ -98,11 +95,13 @@ class UpgradeAITranslation extends Command
          */
         if (! $this->option('model')) {
             $this->error('model is request');
+
             return 1;
         }
         $this->model = $this->modelService->getModelById($this->option('model'));
         if (empty($this->model)) {
             $this->error('invalid model id ');
+
             return 1;
         }
         $this->info("model:{$this->model['model']}");
@@ -112,21 +111,21 @@ class UpgradeAITranslation extends Command
         $this->workChannel = ChannelApi::getById($this->argument('channel'));
         // 需要判断输入channel 与翻译类型是否一致 nissaya -> nissaya channel
         if ($this->workChannel['type'] !== $this->argument('type')) {
-            $this->error('channel type not match request ' . $this->argument('type') . ' input is ' . $this->workChannel['type']);
+            $this->error('channel type not match request '.$this->argument('type').' input is '.$this->workChannel['type']);
 
             return 1;
         }
 
         if ($this->option('thinking')) {
             $this->thinking = $this->option('thinking') === 'true';
-            $this->line('thinking is ' . $this->option('thinking'));
+            $this->line('thinking is '.$this->option('thinking'));
         }
 
         // translation 工作流步骤校验
         $steps = array_values(array_filter(array_map('trim', explode(',', (string) $this->option('steps')))));
         $invalid = array_diff($steps, PaliTranslateService::STEPS);
         if (! empty($invalid)) {
-            $this->error('invalid steps: ' . implode(',', $invalid) . '. allowed: ' . implode(',', PaliTranslateService::STEPS));
+            $this->error('invalid steps: '.implode(',', $invalid).'. allowed: '.implode(',', PaliTranslateService::STEPS));
 
             return 1;
         }
@@ -135,7 +134,7 @@ class UpgradeAITranslation extends Command
         $nissayaSteps = array_values(array_filter(array_map('trim', explode(',', (string) $this->option('nissaya')))));
         $invalidNissaya = array_diff($nissayaSteps, PaliTranslateService::NISSAYA_STEPS);
         if (! empty($invalidNissaya)) {
-            $this->error('invalid nissaya steps: ' . implode(',', $invalidNissaya) . '. allowed: ' . implode(',', PaliTranslateService::NISSAYA_STEPS));
+            $this->error('invalid nissaya steps: '.implode(',', $invalidNissaya).'. allowed: '.implode(',', PaliTranslateService::NISSAYA_STEPS));
 
             return 1;
         }
@@ -144,7 +143,7 @@ class UpgradeAITranslation extends Command
         $channelId = $this->workChannel['id'] ?? '';
 
         // 缓存键:按 type、channel 区分不同任务的断点
-        $cacheKey = self::CACHE_KEY_PREFIX . ':' . $type . ':' . $channelId;
+        $cacheKey = self::CACHE_KEY_PREFIX.':'.$type.':'.$channelId;
 
         if ($this->option('fresh')) {
             Cache::forget($cacheKey);
@@ -164,7 +163,7 @@ class UpgradeAITranslation extends Command
             // 未指定 book 时,若已有断点缓存,从上次处理到的 book 继续,无需从 1 开始
             $startBook = 1;
             if (! empty($done)) {
-                $doneBooks = array_map(fn($cursor) => (int) explode('|', $cursor)[0], array_keys($done));
+                $doneBooks = array_map(fn ($cursor) => (int) explode('|', $cursor)[0], array_keys($done));
                 $startBook = max($doneBooks);
                 $this->info("resume from book {$startBook}");
             }
@@ -176,9 +175,9 @@ class UpgradeAITranslation extends Command
             if ($this->option('para')) {
                 $paragraphs = [$this->option('para')];
             }
-            foreach ($paragraphs as  $paragraph) {
+            foreach ($paragraphs as $paragraph) {
                 // 稳定游标:缓存键已含 type、channel,此处仅以 book|para 标识处理单元
-                $cursor = $book . '|' . $paragraph;
+                $cursor = $book.'|'.$paragraph;
                 if (isset($done[$cursor])) {
                     $this->info("skip {$cursor}");
 
@@ -207,7 +206,7 @@ class UpgradeAITranslation extends Command
                 }
                 $this->save($data);
                 $time = time() - $start;
-                $this->info($this->argument('type') . " {$book}-{$paragraph} " . count($data) . ' sentences time=' . $time);
+                $this->info($this->argument('type')." {$book}-{$paragraph} ".count($data).' sentences time='.$time);
                 // 该处理单元全部写库完成后再标记游标,确保中途中断不会误跳过
                 $done[$cursor] = true;
                 Cache::put($cacheKey, $done, now()->addHours(24));
@@ -227,7 +226,7 @@ class UpgradeAITranslation extends Command
                 'book' => $book,
                 '--channel' => $this->workChannel['id'],
                 '--summary' => 'off',
-                '--granularity' => 'chapter'
+                '--granularity' => 'chapter',
             ];
             if ($this->option('para')) {
                 $param['--para'] = $this->option('para');
@@ -302,7 +301,7 @@ class UpgradeAITranslation extends Command
             $response = $llm->send("```json\n{$tplText}\n```");
             $complete = time() - $startAt;
             $content = $response['choices'][0]['message']['content'] ?? '[]';
-            Log::debug("ai response in {$complete}s content=" . $content);
+            Log::debug("ai response in {$complete}s content=".$content);
 
             $json = LlmResponseParser::jsonl($content);
 
@@ -347,8 +346,12 @@ class UpgradeAITranslation extends Command
 
     private function save(array $data)
     {
+
         // 写入句子库
         try {
+            // 过滤掉 id 不存在的 item(LLM 输出可能缺失或畸形),避免后续 explode 报错
+            $data = array_filter($data, fn ($n) => ! empty($n['id']));
+
             $sentData = [];
             $sentData = array_map(function ($n) {
                 $sId = explode('-', $n['id']);
@@ -359,7 +362,7 @@ class UpgradeAITranslation extends Command
                     'word_start' => $sId[2],
                     'word_end' => $sId[3],
                     'channel_uid' => $this->workChannel['id'],
-                    'content' => $n['content'],
+                    'content' => $n['content'] ?? '',
                     'content_type' => $n['content_type'] ?? 'markdown',
                     'lang' => $this->workChannel['lang'],
                     'status' => $this->workChannel['status'],

+ 110 - 28
api-v13/app/Services/AIAssistant/AITermService.php

@@ -2,27 +2,26 @@
 
 namespace App\Services\AIAssistant;
 
-use Illuminate\Support\Facades\Log;
-
-use App\Services\OpenSearchService;
-use App\Services\TermService;
-use App\Services\OpenAIService;
+use App\DTO\Search\SearchDataDTO;
+use App\Http\Resources\AiModelResource;
 use App\Services\AIModelService;
 use App\Services\AuthService;
-
-use App\Http\Resources\AiModelResource;
-use App\DTO\Search\SearchDataDTO;
+use App\Services\OpenAIService;
+use App\Services\OpenSearchService;
+use App\Services\TermService;
+use Illuminate\Support\Facades\Log;
 
 class AITermService
 {
     protected $pageSize = 50;
-    protected AiModelResource $model;
 
+    protected AiModelResource $model;
 
     protected $modelToken;
 
+    protected ?bool $thinking = null;
 
-    private $sysPrompt = <<<md
+    private $sysPrompt = <<<'md'
     请根据提供的文献搜素结果,撰写一个巴利术语的简体中文百科词条。
 
     搜素结果是json数组
@@ -41,7 +40,7 @@ class AITermService
     4. 提供完整的参考文献列表
     5. 保持学术中立性和客观性
     6. 请引用我提供的全部内容,不要有任何遗漏
-    7. 请在文档的开头输出一个模板 {{quality|pending}}
+    7. 请在文档的开头输出一个模板 {{quality|pending}}。 这个模板后面不要有空行,直接跟后面的内容。
 
     **观点引用标准格式:**
     《文献中文名》在《章节中文名》中指出/解释/说明:"巴利文原文"(中文翻译及必要说明)。[link]
@@ -142,7 +141,7 @@ class AITermService
     {{category|经典与文献}} {{category|经藏}} {{category|中部}} {{category|义注}}
     md;
 
-    private $sysPromptTags = <<<md
+    private $sysPromptTags = <<<'md'
     你是一个巴利语佛教百科词条分类专家。请根据以下分类体系,为给定的词条打上分类标签。
 
     在分类标签的前面添加一个**词条概述**
@@ -193,6 +192,18 @@ class AITermService
     {{category|经典与文献}} {{category|经藏}} {{category|中部}} {{category|义注}}
     md;
 
+    private $sysPromptMeaning = <<<'md'
+    你是一个巴利语佛教术语翻译专家。我会提供一个巴利术语,以及它的百科词条正文。
+
+    请你阅读百科词条正文,为这个巴利术语提炼出一个最恰当、简洁的简体中文释义。
+
+    **输出规则:**
+    - 只输出释义本身,不要任何解释、标点修饰、引号或模板
+    - 释义应为简短的中文词语或短语,通常不超过 15 个字
+    - 优先采用学界通用的标准译法
+    - 不要重复输出巴利原词
+    md;
+
     /**
      * Create a new command instance.
      *
@@ -203,10 +214,22 @@ class AITermService
         protected OpenAIService $openAIService,
         protected TermService $termService
     ) {}
+
     public function setModel($id)
     {
         $this->model = $this->modelService->getModelById($id);
         $this->modelToken = AuthService::getUserToken($id);
+
+        return $this;
+    }
+
+    /**
+     * 设置 deepseek thinking 开关;null 表示不显式设置,沿用模型默认。
+     */
+    public function setThinking(?bool $thinking): static
+    {
+        $this->thinking = $thinking;
+
         return $this;
     }
 
@@ -215,15 +238,15 @@ class AITermService
         $search = app(OpenSearchService::class);
         // 组装搜索参数
         $params = [
-            'query'        => $word,
+            'query' => $word,
             'resourceType' => 'tipitaka',
             'granularity' => 'paragraph',
-            'pageSize'     => $this->pageSize,
+            'pageSize' => $this->pageSize,
         ];
         $result = $search->search($params);
 
         $dto = SearchDataDTO::fromArray($result);
-        $res = array();
+        $res = [];
         foreach ($dto->hits->items as $key => $item) {
 
             $res[] = [
@@ -231,46 +254,105 @@ class AITermService
                 'content' => $item->content,
                 'path' => $item->path,
                 'pid' => $item->getParaId(),
-                'link' => $item->getParaLink()
+                'link' => $item->getParaLink(),
             ];
         }
-        Log::debug('query ' . count($res));
+        Log::debug('query '.count($res));
+
         return $res;
     }
 
+    /**
+     * 按 word 查找/新建社区词条(_community_translation_zh-hans_),并用 LLM 生成百科正文写入 note。
+     *
+     * @return string LLM 生成的百科词条正文
+     */
+    public function updateOrCreate(string $channelId, string $word): string
+    {
+
+        $term = $this->termService->findOrCreate($channelId, $word);
+
+        return $this->update($term->guid);
+    }
+
     public function update(string $id)
     {
         // 获取术语
         $term = $this->termService->getRaw($id);
+
+        $content = $this->generateNote($term->word);
+        $meaning = $this->generateMeaning($term->word, $content);
+        $this->termService->update($id, ['note' => $content, 'meaning' => $meaning]);
+
+        return $content;
+    }
+
+    /**
+     * 全文搜索 word 命中段落,连同搜索结果发给 LLM 生成巴利术语百科正文,并输出引用自检日志。
+     *
+     * @return string LLM 生成的百科词条正文
+     */
+    private function generateNote(string $word): string
+    {
         // 全文搜索
-        $query = $this->query($term->word);
+        $query = $this->query($word);
 
         $res = json_encode($query, JSON_UNESCAPED_UNICODE);
         $resText = "# 搜索结果\n```json\n{$res}\n```\n";
-        $termText = "# 巴利术语\n\n{$term->word}\n\n";
-        //LLM 生成
-        $response = $this->openAIService->setApiUrl($this->model['url'])
+        $termText = "# 巴利术语\n\n{$word}\n\n";
+        // LLM 生成
+        $llm = $this->openAIService->setApiUrl($this->model['url'])
             ->setModel($this->model['model'])
             ->setApiKey($this->model['key'])
             ->setSystemPrompt($this->sysPrompt)
             ->setTemperature(0.5)
-            ->setStream(false)
-            ->send($resText . $termText);
+            ->setStream(false);
+        if ($this->thinking !== null) {
+            $llm = $llm->setThinking($this->thinking);
+        }
+        $response = $llm->send($resText.$termText);
 
         $content = $response['choices'][0]['message']['content'] ?? '';
-
-        //输出自检报告
+        $content = str_replace("{{quality|pending}}\n", '{{quality|pending}}', $content);
+        // 输出自检报告
         Log::debug('llm response', ['strlen' => $content]);
         $paraIds = $this->extractAllParaIds($content);
         Log::debug('has paragraph ref ', ['total' => count($paraIds), 'id' => $paraIds]);
-        $searchPid = array_map(fn($item) => $item['pid'], $query);
+        $searchPid = array_map(fn ($item) => $item['pid'], $query);
         $diff = array_values(array_diff($paraIds, $searchPid));
         Log::debug('diff', ['total' => count($diff), 'data' => $diff]);
 
-        $this->termService->update($id, ['note' => $content]);
         return $content;
     }
 
+    /**
+     * 根据已生成的百科词条正文,让 LLM 为巴利术语提炼一个简洁的简体中文释义。
+     *
+     * @return string LLM 提炼的简体中文释义;失败时回退为原词
+     */
+    private function generateMeaning(string $word, string $content): string
+    {
+        $termText = "# 巴利术语\n\n{$word}\n\n";
+        $noteText = "# 百科词条正文\n\n{$content}\n";
+
+        $llm = $this->openAIService->setApiUrl($this->model['url'])
+            ->setModel($this->model['model'])
+            ->setApiKey($this->model['key'])
+            ->setSystemPrompt($this->sysPromptMeaning)
+            ->setTemperature(0.3)
+            ->setStream(false);
+        if ($this->thinking !== null) {
+            $llm = $llm->setThinking($this->thinking);
+        }
+        $response = $llm->send($termText.$noteText);
+
+        $meaning = trim($response['choices'][0]['message']['content'] ?? '');
+
+        Log::debug('llm meaning', ['word' => $word, 'meaning' => $meaning]);
+
+        return $meaning !== '' ? $meaning : $word;
+    }
+
     public function create(string $word) {}
 
     /**
@@ -279,7 +361,7 @@ class AITermService
      * Parses a string that may contain multiple "{{para|...}}" templates
      * and returns an array of unique 'id' parameter values found.
      *
-     * @param string $str The input string containing zero or more {{para|...}} templates
+     * @param  string  $str  The input string containing zero or more {{para|...}} templates
      * @return array<int, string> Array of unique extracted ID values (e.g., ['16-1376', 'ABC-123'])
      *                            Returns empty array if no IDs are found
      *

+ 216 - 35
api-v13/app/Services/AIAssistant/PaliTranslateService.php

@@ -10,18 +10,20 @@ use App\Models\PaliText;
 use App\Models\Sentence;
 use App\Services\OpenAIService;
 use App\Services\SearchPaliDataService;
+use App\Services\TermService;
 use Illuminate\Support\Facades\Log;
 
 /**
  * 巴利原文 -> 简体中文 的多步骤翻译工作流。
  *
- * 支持个步骤,可单独运行或按顺序串联:
+ * 支持个步骤,可单独运行或按顺序串联:
  * - translate:根据巴利原文产出译文
+ * - term:术语标注,根据 channel/社区术语表把译文中的中文术语替换为 [[巴利术语]] 标记
  * - review:对已有译文打分并给出问题清单(不修改译文)
  * - revise:根据 review 的问题清单产出改进后的译文
  * - evaluate:质量评估,对照原文找出译文的真实问题,按级别就地用 HTML span 标注译文(颜色=严重程度,title=问题+建议),作为工作流最后一步
  *
- * 单独运行 review / revise / evaluate 时,已有译文从输出 channel 读取。
+ * 单独运行 term / review / revise / evaluate 时,已有译文从输出 channel 读取。
  *
  * 工作流自动提取同段落的 nissaya(巴利逐词缅文释义)注入 translate / review / evaluate
  * 作为参考资料(见 PaliNissayaReferenceService);无 nissaya 数据的段落不受影响。
@@ -31,7 +33,7 @@ class PaliTranslateService
     /**
      * 可用的工作流步骤
      */
-    public const STEPS = ['translate', 'review', 'revise', 'evaluate'];
+    public const STEPS = ['translate', 'term', 'review', 'revise', 'evaluate'];
 
     /**
      * 支持注入 nissaya 参考资料的步骤(revise 基于 review 意见工作,无需 nissaya)
@@ -68,8 +70,6 @@ class PaliTranslateService
 
         若用户额外提供 nissaya(巴利原文的逐词缅文释义,与 pali 通过 id 一一对应,按词列出每个巴利词的语法解析与缅文释义,形如「巴利词= 缅文释义」):它是判断词义、修饰关系、指代关系和句子结构最权威的依据,翻译时应优先参照 nissaya 确定原意,遇到歧义时以 nissaya 为准。
 
-        若用户额外提供 glossary(巴利语术语表,JSON 字符串数组,每个元素是一个巴利语术语原形):翻译时请在巴利原文中查找这些术语。凡巴利原文中出现了术语表中的词(包括其屈折变化、复合等形式),该词在译文相应位置**不要译为中文**,而是原样输出为 `[[术语原形]]`——即用术语表中给出的那个原形,外加双方括号包裹;其余内容照常翻译为中文。例如原文出现 rājagahe 且术语表含 rājagaha,则译文写作「住在[[rājagaha]]」而非「住在王舍城」。术语表中没有、或原文中并未出现的词,一律按正常翻译处理,不要添加双方括号。
-
         翻译要求
         1. 语言风格为现代汉语,**绝对不要**使用古汉语或者半文半白。**不要参考**阿含经和元亨寺语言风格。
         2. 译文严谨,完全贴合巴利原文,不要加入自己的理解
@@ -89,6 +89,36 @@ class PaliTranslateService
         {"id":"2-3-4-5","content":"译文"}
         md;
 
+    /**
+     * term 步骤的提示词:根据术语表把译文中的中文术语替换为 [[巴利术语]] 标记。
+     */
+    protected string $termPrompt = <<<'md'
+        你是一个巴利语佛教术语标注助手。
+        用户会提供:
+        - pali:巴利原文段落,json,每条记录是一个句子,含 id 和 content 两个字段。
+        - translation:已有的简体中文译文,json,与 pali 通过 id 一一对应。
+        - glossary:巴利语术语表,json 数组,每个元素含 word(巴利术语原形)、meaning(该术语的中文释义)、tag(分类标签)三个字段。
+
+        你的任务:在**不改变译文其他内容**的前提下,把 translation 中对应这些术语的中文词语替换为术语标记 `[[巴利术语原形]]`(双方括号包裹 glossary 中给出的 word 原形),其余内容、措辞、标点、黑体等格式**一字不动**地保留。
+
+        判断与替换规则:
+        1. 只有当某个 glossary 术语在该句的巴利原文(pali)中确实出现(包括其屈折变化、变格、复合、连音等形式),且译文中存在与之对应的中文译词时,才进行替换。原文中并未出现的术语,一律不替换。
+        2. **语境判断(最重要)**:必须结合 glossary 中该术语的 meaning,判断它在当前句子语境下是否确实用作该术语义。同一个巴利词在论藏(阿毗达摩)中可能是专门术语,在经藏中却只是普通词汇。若根据 meaning 与上下文判断该词在此处并非用作术语义,则**不要**替换,保持原中文译文。
+        3. 宁缺毋滥:没有十足把握时不要标记。不确定的一律保持原译文,不加双方括号。
+        4. 不要新增术语表中没有的标记,也不要把已经正确翻译的普通词误标为术语。
+        5. 译文中可能已存在 `[[...]]` 术语标记,原样保留即可,不要重复包裹。
+
+        输出格式jsonl,每行对应一个句子,包含两个字段:
+        id:与原文相同的句子id
+        content:标注后的中文译文(无需替换的句子与原译文完全一致)
+
+        直接输出jsonl数据,无需解释
+
+        **输出范例**
+        {"id":"1-2-3-4","content":"住在[[rājagaha]]"}
+        {"id":"2-3-4-5","content":"原样保留的译文"}
+        md;
+
     /**
      * review 步骤的提示词:对已有译文打分并指出问题,不修改译文。
      */
@@ -222,6 +252,7 @@ class PaliTranslateService
         protected OpenAIService $openAIService,
         protected SearchPaliDataService $searchPaliDataService,
         protected PaliNissayaReferenceService $nissayaReference,
+        protected TermService $termService,
     ) {}
 
     /**
@@ -352,10 +383,13 @@ class PaliTranslateService
         foreach ($steps as $step) {
             switch ($step) {
                 case 'translate':
-                    // 加载本段所属 chapter 的巴利术语表;命中术语时译文输出 [[术语]] 而非中文
-                    $glossary = $this->loadGlossary($book, $para);
-                    Log::debug('PaliTranslate: glossary 术语表', ['count' => count($glossary)]);
-                    $translation = $this->translate($pali, $this->nissayaFor('translate', $nissaya), $glossary);
+                    $translation = $this->translate($pali, $this->nissayaFor('translate', $nissaya));
+                    break;
+                case 'term':
+                    // 构造 channel + 社区术语表(经系统术语表过滤、channel 优先),按语境把译文中的中文术语替换为 [[巴利术语]]
+                    $glossary = $this->buildTermGlossary($book, $para);
+                    Log::debug('PaliTranslate: term 术语表', ['count' => count($glossary)]);
+                    $translation = $this->markTerms($pali, $translation, $glossary);
                     break;
                 case 'review':
                     $review = $this->review($pali, $translation, $this->nissayaFor('review', $nissaya));
@@ -370,9 +404,9 @@ class PaliTranslateService
             }
         }
 
-        // 只有产出译文的步骤(translate / revise / evaluate)才返回可写库的数据;
+        // 只有产出译文的步骤(translate / term / revise / evaluate)才返回可写库的数据;
         // evaluate 写库内容为带 HTML 标注的译文;仅 review 时报告已写入日志,无需重新保存原译文
-        $producesTranslation = (bool) array_intersect($steps, ['translate', 'revise', 'evaluate']);
+        $producesTranslation = (bool) array_intersect($steps, ['translate', 'term', 'revise', 'evaluate']);
 
         return $producesTranslation ? $translation : [];
     }
@@ -404,19 +438,38 @@ class PaliTranslateService
      *
      * @param  array<int, array{id: string, content: string}>  $pali
      * @param  array<int, array{id: string, content: string}>  $nissaya  巴利逐词缅文释义参考资料,可空
-     * @param  string[]  $glossary  巴利术语表(术语原形列表),命中时译文输出 [[术语]],可空
      * @return array<int, array{id: string, content: string}>
      */
-    public function translate(array $pali, array $nissaya = [], array $glossary = []): array
+    public function translate(array $pali, array $nissaya = []): array
     {
         $userText = "# pali\n\n".$this->jsonBlock($pali)."\n\n"
-            .$this->nissayaSection($nissaya)
-            .$this->glossarySection($glossary);
+            .$this->nissayaSection($nissaya);
         Log::debug('PaliTranslate: translate', ['input' => $userText]);
 
-        $content = $this->send($this->translatePrompt, $userText);
+        return $this->sendForIds('translate', $this->translatePrompt, $userText, $this->idsOf($pali));
+    }
+
+    /**
+     * term 步骤:根据术语表,把已有译文中对应的中文术语替换为 [[巴利术语]] 标记。
+     * 由大模型结合巴利原文与术语 meaning 做语境判断;译文或术语表为空时原样返回。
+     *
+     * @param  array<int, array{id: string, content: string}>  $pali
+     * @param  array<int, array{id: string, content: string}>  $translation
+     * @param  array<int, array{word: string, meaning: string, tag: string}>  $glossary
+     * @return array<int, array{id: string, content: string}>
+     */
+    public function markTerms(array $pali, array $translation, array $glossary): array
+    {
+        if (empty($translation) || empty($glossary)) {
+            return $translation;
+        }
+
+        $userText = "# pali\n\n".$this->jsonBlock($pali)."\n\n"
+            ."# translation\n\n".$this->jsonBlock($translation)."\n\n"
+            ."# glossary\n\n".$this->jsonBlock($glossary)."\n\n";
+        Log::debug('PaliTranslate: term', ['input' => $userText]);
 
-        return LlmResponseParser::jsonl($content);
+        return $this->sendForIds('term', $this->termPrompt, $userText, $this->idsOf($translation));
     }
 
     /**
@@ -434,10 +487,7 @@ class PaliTranslateService
             .$this->nissayaSection($nissaya);
         Log::debug('PaliTranslate: review', ['input' => $userText]);
 
-        $content = $this->send($this->reviewPrompt, $userText);
-        Log::debug('PaliTranslate: review', ['output' => $content]);
-
-        return LlmResponseParser::jsonl($content);
+        return $this->sendForIds('review', $this->reviewPrompt, $userText, $this->idsOf($translation));
     }
 
     /**
@@ -455,10 +505,7 @@ class PaliTranslateService
             ."# review\n\n".$this->jsonBlock($review)."\n\n";
         Log::debug('PaliTranslate: revise', ['input' => $userText]);
 
-        $content = $this->send($this->revisePrompt, $userText);
-        Log::debug('PaliTranslate: revise', ['output' => $content]);
-
-        return LlmResponseParser::jsonl($content);
+        return $this->sendForIds('revise', $this->revisePrompt, $userText, $this->idsOf($translation));
     }
 
     /**
@@ -477,10 +524,7 @@ class PaliTranslateService
             .$this->nissayaSection($nissaya);
         Log::debug('PaliTranslate: evaluate', ['input' => $userText]);
 
-        $content = $this->send($this->evaluatePrompt, $userText);
-        Log::debug('PaliTranslate: evaluate', ['output' => $content]);
-
-        return LlmResponseParser::jsonl($content);
+        return $this->sendForIds('evaluate', $this->evaluatePrompt, $userText, $this->idsOf($translation));
     }
 
     /**
@@ -535,6 +579,92 @@ class PaliTranslateService
         return is_string($content) ? $content : '[]';
     }
 
+    /**
+     * 调用 LLM 并解析 jsonl;若返回结果缺失部分期望 id(大模型漏句),则整体重试,
+     * 直到全部 id 补齐或达到最大尝试次数;最终仍缺失时返回最后一次(覆盖最全)的结果。
+     *
+     * @param  string  $step  步骤名,仅用于日志
+     * @param  string[]  $expectedIds  期望覆盖的句子 id 列表
+     * @return array<int, array<string, mixed>>
+     */
+    protected function sendForIds(string $step, string $systemPrompt, string $userText, array $expectedIds, int $maxAttempts = 2): array
+    {
+        $best = [];
+        $bestMissing = $expectedIds;
+
+        for ($attempt = 1; $attempt <= $maxAttempts; $attempt++) {
+            $result = LlmResponseParser::jsonl($this->send($systemPrompt, $userText));
+            $missing = $this->missingIds($expectedIds, $result);
+
+            // 保留缺失最少的一次结果,避免重试反而更差
+            if (count($missing) < count($bestMissing)) {
+                $best = $result;
+                $bestMissing = $missing;
+            }
+
+            if (empty($missing)) {
+                return $result;
+            }
+
+            Log::warning('PaliTranslate: LLM 返回缺失 id,重试', [
+                'step' => $step,
+                'attempt' => $attempt,
+                'missing' => $missing,
+            ]);
+        }
+
+        Log::warning('PaliTranslate: 重试后仍缺失 id', [
+            'step' => $step,
+            'missing' => $bestMissing,
+        ]);
+
+        return $best;
+    }
+
+    /**
+     * 提取记录列表中的 id(非空),保持顺序。
+     *
+     * @param  array<int, array<string, mixed>>  $items
+     * @return string[]
+     */
+    protected function idsOf(array $items): array
+    {
+        $ids = [];
+        foreach ($items as $item) {
+            if (isset($item['id']) && $item['id'] !== '') {
+                $ids[] = (string) $item['id'];
+            }
+        }
+
+        return $ids;
+    }
+
+    /**
+     * 返回 expectedIds 中、在 LLM 结果里缺失的 id。
+     *
+     * @param  string[]  $expectedIds
+     * @param  array<int, array<string, mixed>>  $result
+     * @return string[]
+     */
+    protected function missingIds(array $expectedIds, array $result): array
+    {
+        $returned = [];
+        foreach ($result as $item) {
+            if (isset($item['id'])) {
+                $returned[(string) $item['id']] = true;
+            }
+        }
+
+        $missing = [];
+        foreach ($expectedIds as $id) {
+            if (! isset($returned[(string) $id])) {
+                $missing[] = (string) $id;
+            }
+        }
+
+        return $missing;
+    }
+
     /**
      * 按开关返回某步骤应使用的 nissaya;未启用该步骤时返回空数组。
      *
@@ -607,17 +737,68 @@ class PaliTranslateService
     }
 
     /**
-     * 构造 glossary 术语表区块;无数据时返回空串(不污染提示词)。
+     * 构造 term 步骤的术语表:channel 术语表 + 同语言社区术语表,
+     * 经本段所属 chapter 的系统术语表(loadGlossary)过滤——只保留系统术语表里存在的术语,
+     * 再合并去重(channel 优先),每项含 word / meaning / tag 三个字段。
      *
-     * @param  string[]  $glossary
+     * @return array<int, array{word: string, meaning: string, tag: string}>
      */
-    protected function glossarySection(array $glossary): string
+    protected function buildTermGlossary(int $book, int $para): array
     {
-        if (empty($glossary)) {
-            return '';
+        $channelId = $this->workChannel['id'] ?? null;
+        if (! $channelId) {
+            Log::warning('PaliTranslate: term 步骤未设置 channel,跳过术语注入');
+
+            return [];
+        }
+        $lang = $this->workChannel['lang'] ?? 'zh-Hans';
+
+        // 系统术语表(本段所属 chapter 命中的巴利术语原形)作为过滤白名单,算法同 loadGlossary
+        $allowed = $this->loadGlossary($book, $para);
+        if (empty($allowed)) {
+            return [];
+        }
+        $allowedSet = [];
+        foreach ($allowed as $word) {
+            $allowedSet[$this->toNfc($word)] = true;
+        }
+
+        // channel 术语表优先,社区术语表(同语言)补充;只保留系统术语表里有的术语
+        $channelTerms = $this->termService->getChannelGlossary($channelId);
+        $communityTerms = $this->termService->getCommunityGlossary($lang)['items'] ?? [];
+
+        $merged = [];
+        foreach ([$channelTerms, $communityTerms] as $source) {
+            foreach ($source as $term) {
+                $word = $this->toNfc(trim((string) (is_array($term) ? ($term['word'] ?? '') : ($term->word ?? ''))));
+                // 系统术语表里没有、word 为空、或 channel 已提供(优先)则跳过
+                if ($word === '' || ! isset($allowedSet[$word]) || isset($merged[$word])) {
+                    continue;
+                }
+                $merged[$word] = [
+                    'word' => $word,
+                    'meaning' => (string) (is_array($term) ? ($term['meaning'] ?? '') : ($term->meaning ?? '')),
+                    'tag' => (string) (is_array($term) ? ($term['tag'] ?? '') : ($term->tag ?? '')),
+                ];
+            }
+        }
+
+        return array_values($merged);
+    }
+
+    /**
+     * Unicode 规范化为 NFC(巴利文变音符匹配需统一 NFC/NFD)。intl 不可用时原样返回。
+     */
+    protected function toNfc(string $s): string
+    {
+        if (class_exists(\Normalizer::class)) {
+            $normalized = \Normalizer::normalize($s, \Normalizer::FORM_C);
+            if ($normalized !== false) {
+                return $normalized;
+            }
         }
 
-        return "# glossary\n\n```json\n".json_encode(array_values($glossary), JSON_UNESCAPED_UNICODE)."\n```\n\n";
+        return $s;
     }
 
     /**

File diff suppressed because it is too large
+ 234 - 228
api-v13/app/Services/OpenSearchService.php


+ 155 - 45
api-v13/app/Services/TermService.php

@@ -2,17 +2,24 @@
 
 namespace App\Services;
 
-use App\Models\DhammaTerm;
 use App\Http\Api\ChannelApi;
 use App\Http\Resources\TermResource;
-use Illuminate\Http\Request;
-
+use App\Models\DhammaTerm;
+use App\Models\UserDict;
 use App\Tools\Tools;
-
-
+use Illuminate\Http\Request;
+use Illuminate\Support\Str;
 
 class TermService
 {
+    // 术语表额外纳入的 user_dicts 词典 id(其 word 去除连字符与空格后加入)
+    private const USER_DICT_IDS = [
+        'b089de57-f146-4095-b886-057863728c43',
+        '0bfd87ec-f3ac-49a2-985e-28388779078d',
+        '7c7ee287-35ba-4cf3-b87b-30f1fa6e57c9',
+        '4ac8a0d5-9c6f-4b9f-983d-84288d47f993',
+    ];
+
     public function attachLocalName(array $categoryData, string $lang): array
     {
         $allNames = [];
@@ -20,12 +27,12 @@ class TermService
         // 收集所有 name
         foreach ($categoryData as $item) {
 
-            if (!empty($item['category']['name'])) {
+            if (! empty($item['category']['name'])) {
                 $allNames[] = $item['category']['name'];
             }
 
             foreach ($item['children'] as $child) {
-                if (!empty($child['name'])) {
+                if (! empty($child['name'])) {
                     $allNames[] = $child['name'];
                 }
             }
@@ -61,53 +68,119 @@ class TermService
 
         return $categoryData;
     }
+
     public function glossaryByLemma(array $words, string $lang)
     {
         $localTermChannel = ChannelApi::getSysChannel(
-            "_community_term_" . strtolower($lang) . "_"
+            '_community_term_' . strtolower($lang) . '_'
         );
-        if (!$localTermChannel) {
+        if (! $localTermChannel) {
             return null;
         }
         $result = DhammaTerm::select(['guid', 'word', 'tag', 'meaning', 'other_meaning'])
             ->whereIn('word', $words)
             ->where('channal', $localTermChannel)
             ->get();
+
         return $result;
     }
-    public function getCommunityGlossary($lang)
+
+    public function getCommunityGlossary(string $lang)
     {
         $localTermChannel = ChannelApi::getSysChannel(
-            "_community_term_" . strtolower($lang) . "_",
-            "_community_term_en_"
+            '_community_term_' . strtolower($lang) . '_',
+            '_community_term_en_'
         );
-        $result = DhammaTerm::select(['guid', 'word', 'tag', 'meaning', 'other_meaning'])
+        $result = DhammaTerm::select([
+            'guid',
+            'word',
+            'tag',
+            'meaning',
+            'other_meaning'
+        ])
             ->where('channal', $localTermChannel)
             ->get();
+
         return ['items' => $result, 'total' => count($result)];
     }
-    public function getGrammarGlossary($lang)
+
+    public function getChannelGlossary(string $channelId)
+    {
+        $terms = DhammaTerm::whereNotNull('word')
+            ->where('word', '!=', '')
+            ->whereNotNull('word')
+            ->where('channal', $channelId)
+            ->select(['word', 'meaning', 'tag'])
+            ->get();
+        return $terms->toArray();
+    }
+
+    public function getGlossary()
+    {
+        // 1) dhamma_terms 全表 distinct 词条原形(不限 channel),排除 word 含空格的短语条目
+        $dhammaWords = DhammaTerm::query()
+            ->whereNotNull('word')
+            ->where('word', '!=', '')
+            ->where('word', 'not like', '% %')
+            ->distinct()
+            ->pluck('word')
+            ->all();
+
+        // 2) user_dicts 指定词典的词,去除连字符与空格后加入
+        $userWords = UserDict::query()
+            ->whereIn('dict_id', self::USER_DICT_IDS)
+            ->whereNotNull('word')
+            ->where('word', '!=', '')
+            ->pluck('word')
+            ->map(fn($w) => str_replace(['-', ' '], '', (string) $w))
+            ->all();
+
+        // 合并 + NFC 归一(避免巴利文变音符 NFC/NFD 不一致)+ 去空 + 去重
+        $terms = array_map(fn($w) => $this->toNfc(trim((string) $w)), array_merge($dhammaWords, $userWords));
+        $terms = array_values(array_unique(array_filter($terms, fn($w) => $w !== '')));
+
+        return $terms;
+    }
+
+    /**
+     * Unicode 规范化为 NFC(巴利文变音符匹配需统一 NFC/NFD)。intl 不可用时原样返回。
+     */
+    private function toNfc(string $s): string
+    {
+        if (class_exists(\Normalizer::class)) {
+            $normalized = \Normalizer::normalize($s, \Normalizer::FORM_C);
+            if ($normalized !== false) {
+                return $normalized;
+            }
+        }
+
+        return $s;
+    }
+
+    public function getGrammarGlossary(string $lang)
     {
         $localTermChannel = ChannelApi::getSysChannel(
-            "_System_Grammar_Term_" . strtolower($lang) . "_",
-            "_System_Grammar_Term_en_"
+            '_System_Grammar_Term_' . strtolower($lang) . '_',
+            '_System_Grammar_Term_en_'
         );
         $result = DhammaTerm::select(['guid', 'word', 'tag', 'meaning', 'other_meaning'])
             ->where('channal', $localTermChannel)
             ->get();
+
         return ['items' => $result, 'total' => count($result)];
     }
 
     public function getRaw(string $id)
     {
         $result = DhammaTerm::find($id);
+
         return $result;
     }
 
     public function isCommunity(?string $channelId)
     {
         $channel = ChannelApi::getById($channelId);
-        if (!$channel) {
+        if (! $channel) {
             return false;
         }
         if (strpos($channel['name'], '_community_term_') === false) {
@@ -116,10 +189,11 @@ class TermService
             return true;
         }
     }
+
     public function communityTerm(string $word, string $lang, string $format)
     {
         $localTermChannel = ChannelApi::getSysChannel(
-            "_community_term_" . strtolower($lang) . "_"
+            '_community_term_' . strtolower($lang) . '_'
         );
         $result = DhammaTerm::where('word', $word)
             ->where('channal', $localTermChannel)
@@ -128,7 +202,7 @@ class TermService
             $resource = new TermResource($result);
             $urlParam = ['format' => $format];
             $fakeRequest = Request::create('', 'GET', $urlParam);
-            $termArray    = $resource->toArray($fakeRequest);
+            $termArray = $resource->toArray($fakeRequest);
             if ($result) {
                 return $termArray;
             } else {
@@ -142,7 +216,7 @@ class TermService
     public function communityWiki(string $word, string $lang, string $format)
     {
         $localTermChannel = ChannelApi::getSysChannel(
-            "_community_translation_" . strtolower($lang) . "_"
+            '_community_translation_' . strtolower($lang) . '_'
         );
         $result = DhammaTerm::where('word', $word)
             ->where('channal', $localTermChannel)
@@ -151,7 +225,7 @@ class TermService
             $resource = new TermResource($result);
             $urlParam = ['format' => $format];
             $fakeRequest = Request::create('', 'GET', $urlParam);
-            $termArray    = $resource->toArray($fakeRequest);
+            $termArray = $resource->toArray($fakeRequest);
             if ($result) {
                 return $termArray;
             } else {
@@ -165,7 +239,7 @@ class TermService
     public function communityTerms(string $lang)
     {
         $localTermChannel = ChannelApi::getSysChannel(
-            "_community_term_" . strtolower($lang) . "_"
+            '_community_term_' . strtolower($lang) . '_'
         );
         $result = DhammaTerm::where('channal', $localTermChannel)
             ->whereNotNull('note')
@@ -173,9 +247,10 @@ class TermService
             ->take(10)
             ->orderBy('updated_at', 'desc')
             ->get();
+
         return [
-            "data" => TermResource::collection($result),
-            "count" => 10
+            'data' => TermResource::collection($result),
+            'count' => 10,
         ];
     }
 
@@ -185,7 +260,7 @@ class TermService
         $resource = new TermResource($result);
         $urlParam = ['format' => $format];
         $fakeRequest = Request::create('', 'GET', $urlParam);
-        $termArray    = $resource->toArray($fakeRequest);
+        $termArray = $resource->toArray($fakeRequest);
         if ($result) {
             return $termArray;
         } else {
@@ -225,34 +300,69 @@ class TermService
         if ($term) {
             // 已存在,直接更新
             $term->update([
-                'meaning'       => $data['meaning'],
+                'meaning' => $data['meaning'],
                 'other_meaning' => $data['other_meaning'] ?? null,
-                'note'          => $data['note'] ?? null,
-                'redirect'      => $data['redirect'] ?? null,
-                'editor_id'     => $data['editor_id'],
-                'modify_time'   => $now,
+                'note' => $data['note'] ?? null,
+                'redirect' => $data['redirect'] ?? null,
+                'editor_id' => $data['editor_id'],
+                'modify_time' => $now,
             ]);
         } else {
             // 不存在,新建(一次性写入所有字段)
-            $term = new DhammaTerm();
-            $term->id           = app('snowflake')->id();
-            $term->guid         = (string) \Illuminate\Support\Str::uuid();
-            $term->word         = $data['word'];
-            $term->tag          = $data['tag'] ?? null;
-            $term->channal      = $data['channel_id'];
-            $term->meaning      = $data['meaning'];
+            $term = new DhammaTerm;
+            $term->id = app('snowflake')->id();
+            $term->guid = (string) Str::uuid();
+            $term->word = $data['word'];
+            $term->tag = $data['tag'] ?? null;
+            $term->channal = $data['channel_id'];
+            $term->meaning = $data['meaning'];
             $term->other_meaning = $data['other_meaning'] ?? null;
-            $term->note         = $data['note'] ?? null;
-            $term->redirect     = $data['redirect'] ?? null;
-            $term->editor_id    = $data['editor_id'];  // 注意:需传入 int 类型的 editor id
-            $term->owner        = $channelInfo['studio_id'];
-            $term->word_en      = Tools::getWordEn($data['word']);
-            $term->language     = $channelInfo['lang'] ?? 'zh-Hans';
-            $term->create_time  = $now;
-            $term->modify_time  = $now;
+            $term->note = $data['note'] ?? null;
+            $term->redirect = $data['redirect'] ?? null;
+            $term->editor_id = $data['editor_id'];  // 注意:需传入 int 类型的 editor id
+            $term->owner = $channelInfo['studio_id'];
+            $term->word_en = Tools::getWordEn($data['word']);
+            $term->language = $channelInfo['lang'] ?? 'zh-Hans';
+            $term->create_time = $now;
+            $term->modify_time = $now;
             $term->save();
         }
 
         return $term->guid;
     }
+
+    /**
+     * 按 channel + word 查找术语;不存在则新建一条空白词条(释义留待后续填充)。
+     *
+     * @return DhammaTerm 既有或新建的术语记录
+     */
+    public function findOrCreate(string $channelId, string $word): DhammaTerm
+    {
+        $term = DhammaTerm::where('word', $word)
+            ->where('channal', $channelId)
+            ->first();
+
+        if ($term) {
+            return $term;
+        }
+
+        $channelInfo = ChannelApi::getById($channelId);
+        $now = time();
+
+        $term = new DhammaTerm;
+        $term->id = app('snowflake')->id();
+        $term->guid = (string) Str::uuid();
+        $term->word = $word;
+        $term->meaning = $word;
+        $term->channal = $channelId;
+        $term->word_en = Tools::getWordEn($word);
+        $term->owner = $channelInfo['studio_id'] ?? null;
+        $term->language = $channelInfo['lang'] ?? 'en';
+        $term->editor_id = 0;
+        $term->create_time = $now;
+        $term->modify_time = $now;
+        $term->save();
+
+        return $term;
+    }
 }

Some files were not shown because too many files changed in this diff