UpgradeCompound.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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. $words = WordIndex::whereBetween('id', [$from, $to])
  136. ->where('len', '>=', $this->option('min'))
  137. ->where('len', '<=', $this->option('max'))
  138. ->orderBy('id')
  139. ->selectRaw('id,word as real')
  140. ->cursor();
  141. $total = WordIndex::whereBetween('id', [$from, $to])
  142. ->where('len', '>=', $this->option('min'))
  143. ->where('len', '<=', $this->option('max'))
  144. ->count();
  145. }
  146. $wordIndex = array();
  147. $result = array();
  148. /*
  149. $dbHas = array();
  150. $fDbHas = fopen(__DIR__ . '/compound.csv', 'r');
  151. while (! feof($fDbHas)) {
  152. $dbHas[] = trim(fgets($fDbHas));
  153. }
  154. fclose($fDbHas);
  155. $this->info('load db has ' . count($dbHas));
  156. */
  157. $loopTime = 0;
  158. foreach ($words as $key => $word) {
  159. $startAt = microtime(true);
  160. if (\App\Tools\Tools::isStop()) {
  161. $this->info('system stop');
  162. return 0;
  163. }
  164. $percent = (int)($key * 100 / $total);
  165. if (preg_match('/\d/', $word->real)) {
  166. $this->info("[{$percent}%] {$word->real} 数字不处理");
  167. continue;
  168. }
  169. //判断数据库里面是否有
  170. /*
  171. $exists = in_array($word->real, $dbHas)
  172. */
  173. $exists = UserDict::where('dict_id', $dict_id)
  174. ->where('word', $word->real)
  175. ->exists();
  176. if ($exists) {
  177. $this->info("[{$percent}%]-{$key}-{$word->real}数据库中已经有了");
  178. continue;
  179. }
  180. $now = date('Y-m-d H:i:s');
  181. $this->info("[{$percent}%]-[{$now}]{$word->real} start id={$word->id}");
  182. $wordIndex[] = $word->real;
  183. //先查询vir数据有没有拆分
  184. $parts = array();
  185. $wbwWords = WbwTemplate::where('real', $word->real)
  186. ->select('word')->groupBy('word')->get();
  187. foreach ($wbwWords as $key => $wbwWord) {
  188. if (strpos($wbwWord->word, '-') !== false) {
  189. $wbwFactors = explode('-', $wbwWord->word);
  190. //看词尾是否能找到语尾
  191. $endWord = end($wbwFactors);
  192. $endWordInDict = UserDict::where('word', $endWord)->get();
  193. foreach ($endWordInDict as $key => $oneWord) {
  194. if (
  195. !empty($oneWord->type) &&
  196. strpos($oneWord->type, 'base') === false &&
  197. $oneWord->type !== '.cp.'
  198. ) {
  199. $parts[] = [
  200. 'word' => $oneWord->real,
  201. 'type' => $oneWord->type,
  202. 'grammar' => $oneWord->grammar,
  203. 'parent' => $oneWord->parent,
  204. 'factors' => implode('+', array_slice($wbwFactors, 0, -1)) . '+' . $oneWord->factors,
  205. 'confidence' => 100,
  206. ];
  207. }
  208. }
  209. }
  210. }
  211. if (count($parts) === 0) {
  212. $ts = new TurboSplit(['timeout' => $this->option('timeout')]);
  213. if ($this->option('debug')) {
  214. $ts->debug(true);
  215. }
  216. $parts = $ts->splitA($word->real);
  217. } else {
  218. $this->info("找到vri拆分数据:" . count($parts));
  219. }
  220. $resultCount = 0;
  221. foreach ($parts as $part) {
  222. if (isset($part['type']) && $part['type'] === ".v.") {
  223. continue;
  224. }
  225. if (empty($part['word'])) {
  226. continue;
  227. }
  228. $resultCount++;
  229. $new = array();
  230. $new['word'] = $part['word'];
  231. $new['factors'] = $part['factors'];
  232. if (isset($part['type'])) {
  233. $new['type'] = $part['type'];
  234. } else {
  235. $new['type'] = ".cp.";
  236. }
  237. if (isset($part['grammar'])) {
  238. $new['grammar'] = $part['grammar'];
  239. } else {
  240. $new['grammar'] = null;
  241. }
  242. if (isset($part['parent'])) {
  243. $new['parent'] = $part['parent'];
  244. } else {
  245. $new['parent'] = null;
  246. }
  247. $new['confidence'] = 50 * $part['confidence'];
  248. $result[] = $new;
  249. if (!empty($_word)) {
  250. //指定拆分单词输出结果
  251. $debugOutput = [
  252. $resultCount,
  253. $part['word'],
  254. $part['type'],
  255. $part['grammar'],
  256. $part['parent'],
  257. $part['factors'],
  258. $part['confidence']
  259. ];
  260. $this->info(implode(',', $debugOutput));
  261. }
  262. }
  263. $time = round(microtime(true) - $startAt, 2);
  264. $loopTime += $time;
  265. $this->info("[{$percent}%][{$key}] {$word->real} {$time}s total{$loopTime}");
  266. if ($loopTime > $this->MaxOneLoopTime) {
  267. //到时间上传
  268. $ok = $this->upload($wordIndex, $result, $this->option('api'));
  269. if (!$ok) {
  270. Log::error('break on ' . $word->id);
  271. return 1;
  272. }
  273. $wordIndex = array();
  274. $result = array();
  275. $loopTime = 0;
  276. }
  277. }
  278. $this->upload($wordIndex, $result, $this->option('api'));
  279. $this->info('[' . date('Y-m-d H:i:s', time()) . '] upgrade:compound finished');
  280. return 0;
  281. }
  282. private function upload($index, $words, $url = null)
  283. {
  284. if (count($words) === 0) {
  285. return;
  286. }
  287. if (!$url) {
  288. $url = config('app.url') . '/api/v2/compound';
  289. } else {
  290. $url = $url . '/v2/compound';
  291. }
  292. $this->info('url = ' . $url);
  293. $this->info('uploading size=' . strlen(json_encode($words, JSON_UNESCAPED_UNICODE)));
  294. $httpError = false;
  295. $Max_Loop = 10;
  296. try {
  297. $response = Http::retry($Max_Loop, 100, function (Exception $exception) {
  298. Log::error('upload fail.', ['error' => $exception]);
  299. $this->error('upload fail. try again');
  300. return true;
  301. })
  302. ->post(
  303. $url,
  304. [
  305. 'index' => $index,
  306. 'words' => $words,
  307. ]
  308. );
  309. if ($response->ok()) {
  310. $this->info('upload ok');
  311. $httpError = false;
  312. } else {
  313. $this->error('upload fail.');
  314. Log::error('upload fail.' . $response->body());
  315. }
  316. } catch (GuzzleException $e) {
  317. Log::error('send data failed', ['exception' => $e]);
  318. $httpError = true;
  319. }
  320. if ($httpError) {
  321. Log::error('upload fail.try max');
  322. return false;
  323. }
  324. return true;
  325. }
  326. }