UpgradeCompound.php 12 KB

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