UpgradeCompound.php 10 KB

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