UpgradeCompound.php 12 KB

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