ExportPaliSynonyms.php 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Models\DhammaTerm;
  4. use App\Models\UserDict;
  5. use Illuminate\Console\Command;
  6. use Illuminate\Support\Facades\File;
  7. use Illuminate\Support\Facades\Storage;
  8. class ExportPaliSynonyms extends Command
  9. {
  10. /**
  11. * The name and signature of the console command.
  12. * php artisan export:pali.synonyms --output=pali-synonyms.txt [--test]
  13. *
  14. * 只负责导出,文件写到 local disk(storage/app/private)。
  15. * 由 ops 脚本把文件分发到 OpenSearch 节点后,
  16. * 再用 export:pali.synonyms.set-path 切换索引的同义词文件。
  17. *
  18. * @var string
  19. */
  20. protected $signature = 'export:pali.synonyms {--output=} {--test : 只导出一行,用于快速检查输出格式}';
  21. /**
  22. * The console command description.
  23. *
  24. * @var string
  25. */
  26. protected $description = '导出openSearch用的巴利语变格表';
  27. /**
  28. * Create a new command instance.
  29. *
  30. * @return void
  31. */
  32. public function __construct()
  33. {
  34. parent::__construct();
  35. }
  36. /**
  37. * Execute the console command.
  38. *
  39. * @return int
  40. */
  41. public function handle()
  42. {
  43. if (! $this->option('output')) {
  44. $this->error('please set output file option --output=file');
  45. return 1;
  46. }
  47. /*
  48. //irregular
  49. $dictId = ['4d3a0d92-0adc-4052-80f5-512a2603d0e8'];
  50. //regular
  51. $dictId[] = DictApi::getSysDict('system_regular');
  52. $dictId[] = DictApi::getSysDict('robot_compound');
  53. */
  54. $filename = $this->option('output');
  55. if (preg_match(self::FILENAME_PATTERN, $filename) !== 1) {
  56. $this->error('--output must be a plain file name matching '.self::FILENAME_PATTERN);
  57. return 1;
  58. }
  59. $outputPath = Storage::disk('local')->path($filename);
  60. File::ensureDirectoryExists(dirname($outputPath));
  61. $fp = fopen($outputPath, 'w');
  62. if ($fp === false) {
  63. $this->error("Unable to open file [{$outputPath}]");
  64. return 1;
  65. }
  66. $parents = UserDict::select('parent')
  67. ->whereNotNull('parent')
  68. ->where('parent', '<>', '')
  69. ->groupBy('parent')->cursor();
  70. $droppedTerms = 0;
  71. $droppedLines = 0;
  72. foreach ($parents as $parent) {
  73. if (str_contains($parent->parent, ' ')) {
  74. continue;
  75. }
  76. $words = UserDict::where('parent', $parent->parent)
  77. ->select('word')
  78. ->groupBy('word')->get();
  79. $wordsList = [];
  80. foreach ($words as $word) {
  81. $wordsList[$word->word] = 1;
  82. }
  83. $teams = DhammaTerm::where('word', $parent->parent)
  84. ->select(['meaning'])->get();
  85. foreach ($teams as $term) {
  86. $wordsList[$term->meaning] = 1;
  87. }
  88. $this->info("[{$parent->parent}] ".count($words).' team='.count($teams));
  89. // 合并 $parent->parent, $words->word, $team->meaning 为一个字符串数组
  90. $combinedArray = [];
  91. $combinedArray[] = $parent->parent;
  92. foreach ($wordsList as $word => $value) {
  93. $combinedArray[] = $word;
  94. }
  95. // 过滤掉会被 analyzer 完全消除的 term,否则建索引时会失败
  96. $termCount = count($combinedArray);
  97. $combinedArray = $this->filterSynonymTerms($combinedArray);
  98. $droppedTerms += $termCount - count($combinedArray);
  99. // 同义词行至少要有两个 term 才有意义
  100. if (count($combinedArray) < 2) {
  101. $droppedLines++;
  102. continue;
  103. }
  104. // 将 $combinedArray 写入 CSV 文件
  105. fputcsv($fp, $combinedArray);
  106. if ($this->option('test')) {
  107. $this->warn('--test 已开启,只导出一行。');
  108. break;
  109. }
  110. }
  111. // 关闭文件
  112. fclose($fp);
  113. $this->info("过滤掉非法 term {$droppedTerms} 个,整行丢弃 {$droppedLines} 行。");
  114. $this->info("done: {$outputPath}");
  115. return 0;
  116. }
  117. /**
  118. * 输出文件名,只允许纯文件名,不能带路径
  119. */
  120. public const FILENAME_PATTERN = '/^[A-Za-z0-9][A-Za-z0-9._-]*$/';
  121. /**
  122. * 词典源码标记,这类 term 不是真正的词条
  123. *
  124. * 1. 含 # ‹ › 的:如 "#=cetayati)"、"(#=)(‹paññāpeti)"。
  125. * 其中以 # 开头的 term 若落在行首,整行会被 OpenSearch 当成注释静默忽略。
  126. * 2. 以 ( [ < 开头的:如 "(ku的离格)"、"[ava-hīḷanā<hīḍ]",是词源/变格标注。
  127. * 只匹配开头,保证 "阿拉汉[果]"、"bhesajja[ṃ]" 这类正常释义不受影响。
  128. */
  129. private const DIRTY_TERM_PATTERN = '/[#‹›]|^[(\[<<]/u';
  130. /**
  131. * 过滤掉不能用作同义词的 term,并按原顺序去重
  132. *
  133. * 丢弃两类 term:
  134. * 1. 不含任何字母或数字的(例如 "②"、"——"、"?)")。OpenSearch 的 synonym_graph
  135. * filter 会用 analyzer 分析每一个 term,这类 term 分析后被完全消除,
  136. * 建索引时会抛出 illegal_argument_exception: Failed to build synonyms。
  137. * 2. 带词典源码标记的脏词条,见 self::DIRTY_TERM_PATTERN。
  138. *
  139. * @param array<int, string> $terms
  140. * @return array<int, string>
  141. */
  142. private function filterSynonymTerms(array $terms): array
  143. {
  144. $seen = [];
  145. $filtered = [];
  146. foreach ($terms as $term) {
  147. $term = trim((string) $term);
  148. if ($term === '' || preg_match('/[\p{L}\p{Nd}]/u', $term) !== 1) {
  149. continue;
  150. }
  151. if (preg_match(self::DIRTY_TERM_PATTERN, $term) === 1) {
  152. continue;
  153. }
  154. if (isset($seen[$term])) {
  155. continue;
  156. }
  157. $seen[$term] = true;
  158. $filtered[] = $term;
  159. }
  160. return $filtered;
  161. }
  162. /**
  163. * 将给定文件路径的扩展名替换为 .json
  164. *
  165. * @param string $filePath 完整的文件路径
  166. * @return string 新的文件路径
  167. */
  168. private function changeExtensionToJson(string $filePath): string
  169. {
  170. // 获取路径信息
  171. $pathInfo = pathinfo($filePath);
  172. // 提取目录、文件名(不含扩展名)
  173. $dirname = $pathInfo['dirname'] ?? '';
  174. $filename = $pathInfo['filename'] ?? '';
  175. // 如果目录不是根目录,则添加目录分隔符
  176. $dirname = rtrim($dirname, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
  177. // 构建新路径
  178. return $dirname.$filename.'.json';
  179. }
  180. }