UpgradeCompound.php 12 KB

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