UpgradeCompound.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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 Illuminate\Support\Facades\DB;
  16. use Illuminate\Support\Facades\Http;
  17. use Symfony\Component\Process\Exception\RuntimeException;
  18. class UpgradeCompound extends Command
  19. {
  20. /**
  21. * The name and signature of the console command.
  22. * php -d memory_limit=2024M artisan upgrade:compound --api=https://next.wikipali.org/api --from=0 --to=500000
  23. * @var string
  24. */
  25. protected $signature = 'upgrade:compound {word?} {--book=} {--debug} {--test} {--continue} {--api=} {--from=0} {--to=0} {--min=7} {--max=50}';
  26. /**
  27. * The console command description.
  28. *
  29. * @var string
  30. */
  31. protected $description = 'auto split compound word';
  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 (\App\Tools\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();
  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 = array((object)array('real' => $_word, 'id' => 0));
  106. $count = 1;
  107. } else if ($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. $count = $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. $words = WordIndex::whereBetween('id', [$from, $to])
  134. ->where('len', '>', $this->option('min'))
  135. ->orderBy('id')
  136. ->selectRaw('id,word as real')
  137. ->cursor();
  138. $count = $to - $from + 1;
  139. }
  140. $sn = 0;
  141. $wordIndex = array();
  142. $result = array();
  143. /*
  144. $dbHas = array();
  145. $fDbHas = fopen(__DIR__ . '/compound.csv', 'r');
  146. while (! feof($fDbHas)) {
  147. $dbHas[] = trim(fgets($fDbHas));
  148. }
  149. fclose($fDbHas);
  150. $this->info('load db has ' . count($dbHas));
  151. */
  152. foreach ($words as $key => $word) {
  153. if (\App\Tools\Tools::isStop()) {
  154. return 0;
  155. }
  156. //判断数据库里面是否有
  157. /*
  158. $exists = in_array($word->real, $dbHas)
  159. */
  160. $exists = UserDict::where('dict_id', $dict_id)
  161. ->where('word', $word->real)
  162. ->exists();
  163. if ($exists) {
  164. $this->info("[{$key}]{$word->real}数据库中已经有了");
  165. continue;
  166. }
  167. $sn++;
  168. $startAt = microtime(true);
  169. $now = date('Y-m-d H:i:s');
  170. $this->info("[{$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. if (mb_strlen($word->real, 'UTF-8') > $this->option('max')) {
  202. Log::error('超长,give up' . $word->real);
  203. continue;
  204. }
  205. $ts = new TurboSplit();
  206. if ($this->option('debug')) {
  207. $ts->debug(true);
  208. }
  209. $parts = $ts->splitA($word->real);
  210. } else {
  211. $this->info("找到vri拆分数据:" . count($parts));
  212. }
  213. $time = round(microtime(true) - $startAt, 2);
  214. $percent = (int)($sn * 100 / $count);
  215. $this->info("[{$percent}%][{$sn}] {$word->real} {$time}s");
  216. $resultCount = 0;
  217. foreach ($parts as $part) {
  218. if (isset($part['type']) && $part['type'] === ".v.") {
  219. continue;
  220. }
  221. $resultCount++;
  222. $new = array();
  223. $new['word'] = $part['word'];
  224. $new['factors'] = $part['factors'];
  225. if (isset($part['type'])) {
  226. $new['type'] = $part['type'];
  227. } else {
  228. $new['type'] = ".cp.";
  229. }
  230. if (isset($part['grammar'])) {
  231. $new['grammar'] = $part['grammar'];
  232. } else {
  233. $new['grammar'] = null;
  234. }
  235. if (isset($part['parent'])) {
  236. $new['parent'] = $part['parent'];
  237. } else {
  238. $new['parent'] = null;
  239. }
  240. $new['confidence'] = 50 * $part['confidence'];
  241. $result[] = $new;
  242. if (!empty($_word)) {
  243. //指定拆分单词输出结果
  244. $debugOutput = [
  245. $resultCount,
  246. $part['word'],
  247. $part['type'],
  248. $part['grammar'],
  249. $part['parent'],
  250. $part['factors'],
  251. $part['confidence']
  252. ];
  253. $this->info(implode(',', $debugOutput));
  254. }
  255. }
  256. if (count($wordIndex) % 100 === 0) {
  257. //每100个单词上传一次
  258. $ok = $this->upload($wordIndex, $result, $this->option('api'));
  259. if (!$ok) {
  260. Log::error('break on ' . $word->id);
  261. return 1;
  262. }
  263. $wordIndex = array();
  264. $result = array();
  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.');
  304. }
  305. } catch (\Throwable $throwable) {
  306. Log::error('send notification failed', ['exception' => $throwable]);
  307. $httpError = true;
  308. }
  309. if ($httpError) {
  310. Log::error('upload fail.try max');
  311. return false;
  312. }
  313. return true;
  314. }
  315. }