UpgradeCompound.php 12 KB

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