UpgradeCompound.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Http\Api\DictApi;
  4. use App\Models\UserDict;
  5. use App\Models\WbwTemplate;
  6. use App\Models\WordIndex;
  7. use App\Tools\Tools;
  8. use App\Tools\TurboSplit;
  9. use Exception;
  10. use GuzzleHttp\Exception\GuzzleException;
  11. use Illuminate\Console\Command;
  12. use Illuminate\Support\Facades\DB;
  13. use Illuminate\Support\Facades\Http;
  14. use Illuminate\Support\Facades\Log;
  15. use Illuminate\Support\Facades\Storage;
  16. class UpgradeCompound extends Command
  17. {
  18. /**
  19. * The name and signature of the console command.
  20. * php -d memory_limit=2024M artisan upgrade:compound --api=https://next.wikipali.org/api --from=0 --to=500000
  21. *
  22. * @var string
  23. */
  24. protected $signature = 'upgrade:compound {word?} {--book=} {--debug} {--test} {--continue} {--api=} {--from=0} {--to=0} {--min=7} {--max=50} {--timeout=600}';
  25. /**
  26. * The console command description.
  27. *
  28. * @var string
  29. */
  30. protected $description = 'auto split compound word';
  31. protected $MaxOneLoopTime = 120;
  32. /**
  33. * Create a new command instance.
  34. *
  35. * @return void
  36. */
  37. public function __construct()
  38. {
  39. parent::__construct();
  40. }
  41. /**
  42. * Execute the console command.
  43. *
  44. * @return int
  45. */
  46. public function handle()
  47. {
  48. if (Tools::isStop()) {
  49. $this->info('.stop exists');
  50. return 0;
  51. }
  52. $confirm = '';
  53. if ($this->option('api')) {
  54. $confirm .= 'api='.$this->option('api').PHP_EOL;
  55. }
  56. $confirm .= 'min='.$this->option('min').PHP_EOL;
  57. $confirm .= 'max='.$this->option('max').PHP_EOL;
  58. $confirm .= 'from='.$this->option('from').PHP_EOL;
  59. $confirm .= 'to='.$this->option('to').PHP_EOL;
  60. if (! $this->confirm($confirm)) {
  61. return 0;
  62. }
  63. $this->info('['.date('Y-m-d H:i:s', time()).'] upgrade:compound start');
  64. $dict_id = DictApi::getSysDict('robot_compound');
  65. if (! $dict_id) {
  66. $this->error('没有找到 robot_compound 字典');
  67. return 1;
  68. }
  69. $start = \microtime(true);
  70. //
  71. if ($this->option('test')) {
  72. // 调试代码
  73. $ts = new TurboSplit(['timeout' => $this->option('timeout')]);
  74. Storage::disk('local')->put('tmp/compound.md', '# Turbo Split');
  75. // 获取需要拆的词
  76. $list = [
  77. [5, 20, 20],
  78. [21, 30, 20],
  79. [31, 40, 10],
  80. [41, 60, 10],
  81. ];
  82. foreach ($list as $take) {
  83. // code...
  84. $words = WordIndex::where('final', 0)
  85. ->whereBetween('len', [$take[0], $take[1]])
  86. ->select('word')
  87. ->take($take[2])->get();
  88. foreach ($words as $word) {
  89. $this->info($word->word);
  90. Storage::disk('local')->append('tmp/compound.md', "## {$word->word}");
  91. $parts = $ts->splitA($word->word);
  92. foreach ($parts as $part) {
  93. // code...
  94. $info = "`{$part['word']}`,{$part['factors']},{$part['confidence']}";
  95. $this->info($info);
  96. Storage::disk('local')->append('tmp/compound.md', "- {$info}");
  97. }
  98. }
  99. }
  100. $this->info('耗时:'.\microtime(true) - $start);
  101. return 0;
  102. }
  103. $_word = $this->argument('word');
  104. if (! empty($_word)) {
  105. $words = [(object) ['real' => $_word, 'id' => 0]];
  106. $total = 1;
  107. } elseif ($this->option('book')) {
  108. $words = WbwTemplate::select('real')
  109. ->where('book', $this->option('book'))
  110. ->where('type', '<>', '.ctl.')
  111. ->where('real', '<>', '')
  112. ->orderBy('real')
  113. ->groupBy('real')->cursor();
  114. $query = DB::select(
  115. 'SELECT count(*) from (
  116. SELECT "real" from wbw_templates where book = ? and type <> ? and real <> ? group by real) T',
  117. [$this->option('book'), '.ctl.', '']
  118. );
  119. $total = $query[0]->count;
  120. } else {
  121. $min = WordIndex::min('id');
  122. $max = WordIndex::max('id');
  123. if ($this->option('from') > 0) {
  124. $from = $min + $this->option('from');
  125. } else {
  126. $from = $min;
  127. }
  128. if ($this->option('to') > 0) {
  129. $to = $min + $this->option('to');
  130. } else {
  131. $to = $max;
  132. }
  133. $table = WordIndex::whereBetween('id', [$from, $to]);
  134. if ($this->option('min') > 0) {
  135. $table = $table->where('len', '>=', $this->option('min'));
  136. }
  137. if ($this->option('max') > 0) {
  138. $table = $table->where('len', '<=', $this->option('max'));
  139. }
  140. $total = $table->count();
  141. $words = $table->orderBy('id')
  142. ->selectRaw('id,word as real')
  143. ->cursor();
  144. }
  145. $wordIndex = [];
  146. $result = [];
  147. $loopTime = 0;
  148. foreach ($words as $key => $word) {
  149. $startAt = microtime(true);
  150. if (Tools::isStop()) {
  151. $this->info('system stop');
  152. return 0;
  153. }
  154. $percent = (int) ($key * 100 / $total);
  155. if (preg_match('/\d/', $word->real)) {
  156. $this->info("[{$percent}%] {$word->real} 数字不处理");
  157. continue;
  158. }
  159. // 判断数据库里面是否有
  160. $exists = UserDict::where('dict_id', $dict_id)
  161. ->where('word', $word->real)
  162. ->exists();
  163. if ($exists) {
  164. $this->info("[{$percent}%]-{$key}-{$word->real}数据库中已经有了");
  165. continue;
  166. }
  167. $now = date('Y-m-d H:i:s');
  168. $this->info("[{$percent}%]-[{$now}]{$word->real} start id={$word->id}");
  169. $wordIndex[] = $word->real;
  170. // 先查询vir数据有没有拆分
  171. $parts = [];
  172. $wbwWords = WbwTemplate::where('real', $word->real)
  173. ->select('word')->groupBy('word')->get();
  174. foreach ($wbwWords as $key => $wbwWord) {
  175. if (strpos($wbwWord->word, '-') !== false) {
  176. $wbwFactors = explode('-', $wbwWord->word);
  177. // 看词尾是否能找到语尾
  178. $endWord = end($wbwFactors);
  179. $endWordInDict = UserDict::where('word', $endWord)->get();
  180. foreach ($endWordInDict as $key => $oneWord) {
  181. if (
  182. ! empty($oneWord->type) &&
  183. strpos($oneWord->type, 'base') === false &&
  184. $oneWord->type !== '.cp.'
  185. ) {
  186. $parts[] = [
  187. 'word' => $oneWord->real,
  188. 'type' => $oneWord->type,
  189. 'grammar' => $oneWord->grammar,
  190. 'parent' => $oneWord->parent,
  191. 'factors' => implode('+', array_slice($wbwFactors, 0, -1)).'+'.$oneWord->factors,
  192. 'confidence' => 100,
  193. ];
  194. }
  195. }
  196. }
  197. }
  198. if (count($parts) === 0) {
  199. $ts = new TurboSplit(['timeout' => $this->option('timeout')]);
  200. if ($this->option('debug')) {
  201. $ts->debug(true);
  202. }
  203. $parts = $ts->splitA($word->real);
  204. } else {
  205. $this->info('找到vri拆分数据:'.count($parts));
  206. }
  207. $resultCount = 0;
  208. foreach ($parts as $part) {
  209. if (isset($part['type']) && $part['type'] === '.v.') {
  210. continue;
  211. }
  212. if (empty($part['word'])) {
  213. continue;
  214. }
  215. $resultCount++;
  216. $new = [];
  217. $new['word'] = $part['word'];
  218. $new['factors'] = $part['factors'];
  219. if (isset($part['type'])) {
  220. $new['type'] = $part['type'];
  221. } else {
  222. $new['type'] = '.cp.';
  223. }
  224. if (isset($part['grammar'])) {
  225. $new['grammar'] = $part['grammar'];
  226. } else {
  227. $new['grammar'] = null;
  228. }
  229. if (isset($part['parent'])) {
  230. $new['parent'] = $part['parent'];
  231. } else {
  232. $new['parent'] = null;
  233. }
  234. $new['confidence'] = 50 * $part['confidence'];
  235. $result[] = $new;
  236. if (! empty($_word)) {
  237. // 指定拆分单词输出结果
  238. $debugOutput = [
  239. $resultCount,
  240. $part['word'],
  241. $part['type'],
  242. $part['grammar'],
  243. $part['parent'],
  244. $part['factors'],
  245. $part['confidence'],
  246. ];
  247. $this->info(implode(',', $debugOutput));
  248. }
  249. }
  250. $time = round(microtime(true) - $startAt, 2);
  251. $loopTime += $time;
  252. $this->info("[{$percent}%][{$key}] {$word->real} {$time}s total{$loopTime}");
  253. if ($loopTime > $this->MaxOneLoopTime) {
  254. // 到时间上传
  255. $ok = $this->upload($wordIndex, $result, $this->option('api'));
  256. if (! $ok) {
  257. Log::error('break on '.$word->id);
  258. return 1;
  259. }
  260. $wordIndex = [];
  261. $result = [];
  262. $loopTime = 0;
  263. }
  264. }
  265. $this->upload($wordIndex, $result, $this->option('api'));
  266. $this->info('['.date('Y-m-d H:i:s', time()).'] upgrade:compound finished');
  267. return 0;
  268. }
  269. private function upload($index, $words, $url = null)
  270. {
  271. if (count($words) === 0) {
  272. return;
  273. }
  274. if (! $url) {
  275. $url = config('app.url').'/api/v2/compound';
  276. } else {
  277. $url = $url.'/v2/compound';
  278. }
  279. $this->info('url = '.$url);
  280. $this->info('uploading size='.strlen(json_encode($words, JSON_UNESCAPED_UNICODE)));
  281. $httpError = false;
  282. $Max_Loop = 10;
  283. try {
  284. $response = Http::retry($Max_Loop, 100, function (Exception $exception) {
  285. Log::error('upload fail.', ['error' => $exception]);
  286. $this->error('upload fail. try again');
  287. return true;
  288. })
  289. ->post(
  290. $url,
  291. [
  292. 'index' => $index,
  293. 'words' => $words,
  294. ]
  295. );
  296. if ($response->ok()) {
  297. $this->info('upload ok');
  298. $httpError = false;
  299. } else {
  300. $this->error('upload fail.');
  301. Log::error('upload fail.'.$response->body());
  302. }
  303. } catch (GuzzleException $e) {
  304. Log::error('send data failed', ['exception' => $e]);
  305. $httpError = true;
  306. }
  307. if ($httpError) {
  308. Log::error('upload fail.try max');
  309. return false;
  310. }
  311. return true;
  312. }
  313. }