WbwLookupController.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Models\UserDict;
  4. use App\Models\DictInfo;
  5. use App\Models\WbwTemplate;
  6. use App\Models\Channel;
  7. use Illuminate\Http\Request;
  8. use App\Tools\CaseMan;
  9. use Illuminate\Support\Facades\Log;
  10. use Illuminate\Support\Facades\Cache;
  11. use App\Tools\RedisClusters;
  12. use App\Http\Api\DictApi;
  13. use App\Http\Api\AuthApi;
  14. class WbwLookupController extends Controller
  15. {
  16. private $dictList = [
  17. '85dcc61c-c9e1-4ae0-9b44-cd6d9d9f0d01',//社区汇总
  18. '4d3a0d92-0adc-4052-80f5-512a2603d0e8',// system irregular
  19. '8359757e-9575-455b-a772-cc6f036caea0',// system sandhi
  20. '61f23efb-b526-4a8e-999e-076965034e60',// pali myanmar grammar
  21. 'eae9fd6f-7bac-4940-b80d-ad6cd6f433bf',// Concise P-E Dict
  22. '2f93d0fe-3d68-46ee-a80b-11fa445a29c6',// unity
  23. 'beb45062-7c20-4047-bcd4-1f636ba443d1',// U Hau Sein
  24. '8833de18-0978-434c-b281-a2e7387f69be',// 巴汉增订
  25. '3acf0c0f-59a7-4d25-a3d9-bf394a266ebd',// 汉译パーリ语辞典-黃秉榮
  26. '9ce6a53b-e28f-4fb7-b69d-b35fd5d76a24',//缅英字典
  27. ];
  28. /**
  29. * Create a new command instance.
  30. *
  31. * @return void
  32. */
  33. private function initSysDict()
  34. {
  35. // system regular
  36. $this->dictList[] = DictApi::getSysDict('system_regular');
  37. $this->dictList[] = DictApi::getSysDict('robot_compound');
  38. $this->dictList[] = DictApi::getSysDict('community');
  39. $this->dictList[] = DictApi::getSysDict('community_extract');
  40. }
  41. /**
  42. * Display a listing of the resource.
  43. * @param \Illuminate\Http\Request $request
  44. *
  45. * @return \Illuminate\Http\Response
  46. */
  47. public function index(Request $request)
  48. {
  49. //
  50. $startAt = microtime(true)*1000;
  51. $this->initSysDict();
  52. $words = \explode(',',$request->get("word"));
  53. $bases = \explode(',',$request->get("base"));
  54. # 查询深度
  55. $deep = $request->get("deep",2);
  56. $result = $this->lookup($words,$bases,$deep);
  57. $endAt = microtime(true)*1000;
  58. return $this->ok(["rows"=>$result,
  59. "count"=>count($result),
  60. "time"=>(int)($endAt-$startAt)]);
  61. }
  62. public function lookup($words,$bases,$deep){
  63. $wordPool = array();
  64. $output = array();
  65. foreach ($words as $word) {
  66. $wordPool[$word] = ['base' => false,'done' => false,'apply' => false];
  67. }
  68. foreach ($bases as $base) {
  69. $wordPool[$base] = ['base' => true,'done' => false,'apply' => false];
  70. }
  71. /**
  72. * 先查询字典名称
  73. */
  74. $dict_info = DictInfo::whereIn('id',$this->dictList)->select('id','shortname')->get();
  75. $dict_name = [];
  76. foreach ($dict_info as $key => $value) {
  77. # code...
  78. $dict_name[$value->id] = $value->shortname;
  79. }
  80. $caseman = new CaseMan();
  81. for ($i=0; $i < $deep; $i++) {
  82. $newBase = array();
  83. $newWords = [];
  84. foreach ($wordPool as $word => $info) {
  85. # code...
  86. if($info['done'] === false){
  87. $newWords[] = $word;
  88. $wordPool[$word]['done'] = true;
  89. }
  90. }
  91. $data = UserDict::whereIn('word',$newWords)
  92. ->whereIn('dict_id',$this->dictList)
  93. ->leftJoin('dict_infos', 'user_dicts.dict_id', '=', 'dict_infos.id')
  94. ->orderBy('confidence','desc')
  95. ->get();
  96. foreach ($data as $row) {
  97. # code...
  98. array_push($output,$row);
  99. if(!empty($row->parent) && !isset($wordPool[$row->parent]) ){
  100. //将parent 插入待查询列表
  101. $wordPool[$row->parent] = ['base' => true,'done' => false,'apply' => false];
  102. }
  103. }
  104. //处理查询结果中的拆分信息
  105. $newWordPart = array();
  106. foreach ($wordPool as $word => $info) {
  107. if(!empty($info['factors'])){
  108. $factors = \explode('+',$info['factors']);
  109. foreach ($factors as $factor) {
  110. # 将没有的拆分放入单词查询列表
  111. if(!isset($wordPool[$factor])){
  112. $wordPool[$factor] = ['base' => true,'done' => false,'apply' => false];
  113. }
  114. }
  115. }
  116. }
  117. }
  118. return $output;
  119. }
  120. /**
  121. *
  122. */
  123. private function langCheck($query,$lang){
  124. if($query===[]){
  125. return true;
  126. }else{
  127. if(in_array(strtolower($lang),$query)){
  128. return true;
  129. }else{
  130. $langFamily = explode('-',$lang)[0];
  131. foreach ($query as $value) {
  132. if(strpos($value,$langFamily) !== false){
  133. return true;
  134. }
  135. }
  136. }
  137. }
  138. return false;
  139. }
  140. private function wbwPreference($word,$field,$userId){
  141. $prefix = 'wbw-preference';
  142. $fieldMap = [
  143. 'type'=>1,
  144. 'grammar'=>2,
  145. 'meaning'=>3,
  146. 'factors'=>4,
  147. 'factorMeaning'=>5,
  148. 'parent'=>6,
  149. 'part'=>7,
  150. 'case'=>8,
  151. ];
  152. $fieldId = $fieldMap[$field];
  153. $myPreference = RedisClusters::get("{$prefix}/{$word}/{$fieldId}/{$userId}");
  154. if(!empty($myPreference)){
  155. Log::debug($word.'命中我的wbw-'.$field,['data'=>$myPreference]);
  156. return ['value'=>$myPreference,'status'=>5];
  157. }else{
  158. $myPreference = RedisClusters::get("{$prefix}/{$word}/3/0");
  159. if(!empty($myPreference)){
  160. Log::debug($word.'命中社区wbw-'.$field,['data'=>$myPreference]);
  161. return ['value'=>$myPreference,'status'=>5];
  162. }
  163. }
  164. //Log::debug($word.'未命中'.$field);
  165. return false;
  166. }
  167. /**
  168. * 自动查词
  169. *
  170. * @param \Illuminate\Http\Request $request
  171. * @return \Illuminate\Http\Response
  172. */
  173. public function store(Request $request)
  174. {
  175. //
  176. $user = AuthApi::current($request);
  177. if(!$user ){
  178. //未登录用户
  179. return $this->error(__('auth.failed'),401,401);
  180. }
  181. $startAt = microtime(true)*1000;
  182. // system regular
  183. $this->initSysDict();
  184. $channel = Channel::find($request->get('channel_id'));
  185. $orgData = $request->get('data');
  186. $lang = [];
  187. foreach ($request->get('lang',[]) as $value) {
  188. $lang[] = strtolower($value);
  189. }
  190. //句子中的单词
  191. $words = [];
  192. foreach ($orgData as $word) {
  193. # code...
  194. if( isset($word['type']) && $word['type']['value'] === '.ctl.'){
  195. continue;
  196. }
  197. if(!empty($word['real']['value'])){
  198. $words[] = $word['real']['value'];
  199. }
  200. }
  201. $result = $this->lookup($words,[],2);
  202. $indexed = $this->toIndexed($result);
  203. foreach ($orgData as $key => $word) {
  204. if( isset($word['type']) && $word['type']['value'] === '.ctl.'){
  205. continue;
  206. }
  207. if(empty($word['real']['value'])){
  208. continue;
  209. }
  210. $data = $word;
  211. $preference = $this->wbwPreference($word['real']['value'],'meaning',$user['user_id']);
  212. if($preference!==false){
  213. $data['meaning'] = $preference;
  214. }
  215. $preference = $this->wbwPreference($word['real']['value'],'factors',$user['user_id']);
  216. if($preference!==false){
  217. $data['factors'] = $preference;
  218. }
  219. $preference = $this->wbwPreference($word['real']['value'],'factorMeaning',$user['user_id']);
  220. if($preference!==false){
  221. $data['factorMeaning'] = $preference;
  222. }
  223. $preference = $this->wbwPreference($word['real']['value'],'case',$user['user_id']);
  224. if($preference!==false){
  225. $data['case'] = $preference;
  226. }
  227. if(isset($indexed[$word['real']['value']])){
  228. //parent
  229. $case = [];
  230. $parent = [];
  231. $factors = [];
  232. $factorMeaning = [];
  233. $meaning = [];
  234. $parent2 = [];
  235. $case2 = [];
  236. foreach ($indexed[$word['real']['value']] as $value) {
  237. //非base优先
  238. if(strstr($value->type,'base') === FALSE){
  239. $increment = 10;
  240. }else{
  241. $increment = 1;
  242. }
  243. //将全部结果加上得分放入数组
  244. if($value->type !== '.cp.'){
  245. $parent = $this->insertValue([$value->parent],$parent,$increment);
  246. }
  247. if(isset($data['case']) && $data['case']['status']<5){
  248. if(!empty($value->type) && $value->type !== ".cp."){
  249. $case = $this->insertValue([$value->type."#".$value->grammar],$case,$increment);
  250. }
  251. }
  252. if($data['factors']['status'] < 50){
  253. $factors = $this->insertValue([$value->factors],$factors,$increment);
  254. }
  255. if(isset($data['factorMeaning']) && $data['factorMeaning']['status'] < 50){
  256. $factorMeaning = $this->insertValue([$value->factormean],$factorMeaning,$increment);
  257. }
  258. if($data['meaning']['status'] < 50){
  259. if($this->langCheck($lang,$value->language)){
  260. $meaning = $this->insertValue(explode('$',$value->mean),$meaning,$increment,false);
  261. }
  262. }
  263. }
  264. if(count($case)>0){
  265. arsort($case);
  266. $first = array_keys($case)[0];
  267. $data['case'] = ['value'=>$first==="_null"?"":$first,'status'=>3];
  268. }
  269. if(count($parent)>0){
  270. arsort($parent);
  271. $first = array_keys($parent)[0];
  272. $data['parent'] = ['value'=>$first==="_null"?"":$first,'status'=>3];
  273. }
  274. if(count($factors)>0 && empty($data['factors']['value'])){
  275. arsort($factors);
  276. $first = array_keys($factors)[0];
  277. $data['factors'] = ['value'=>$first==="_null"?"":$first,'status'=>3];
  278. }
  279. if(isset($data['factorMeaning']['value'])){
  280. $inputFM = str_replace(['-','+'],['',''],$data['factorMeaning']['value']);
  281. }else{
  282. $inputFM = '';
  283. }
  284. if(count($factorMeaning)>0 && empty($inputFM)){
  285. $first = array_keys($factorMeaning)[0];
  286. if($first==="_null"){
  287. $factorMeaning = [];
  288. }
  289. }
  290. //拆分意思
  291. if(count($factorMeaning) === 0){
  292. $autoMeaning = '';
  293. //生成自动的拆分意思
  294. $currFactors = explode('+',$data['factors']['value']) ;
  295. $autoFM = [];
  296. foreach ($currFactors as $factor) {
  297. $subFactors = explode('-',$factor) ;
  298. $autoSubFM = [];
  299. foreach ($subFactors as $subFactor) {
  300. $preference = $this->wbwPreference($subFactor,'meaning',$user['user_id']);
  301. if($preference !== false){
  302. $autoSubFM[] = $preference['value'];
  303. }else{
  304. $autoSubFM[] = '';
  305. }
  306. }
  307. $autoFM[] = implode('-',$autoSubFM);
  308. $autoMeaning .= implode('',$autoSubFM);
  309. }
  310. $autoMeaning .= implode('',$autoFM);
  311. $factorMeaning = [implode('+',$autoFM)=>1];
  312. if(empty($data['meaning']['value']) && !empty($autoMeaning)){
  313. $data['meaning'] = ['value'=>$autoMeaning,'status'=>5];
  314. }
  315. }
  316. if(count($factorMeaning)>0){
  317. arsort($factorMeaning);
  318. $first = array_keys($factorMeaning)[0];
  319. $data['factorMeaning'] = ['value'=>$first==="_null"?"":$first,'status'=>5];
  320. }
  321. if(isset($data['factorMeaning']) && $data['factorMeaning']['status']<5){
  322. $wbwFactorMeaning = [];
  323. if(!empty($data['factors']['value'])){
  324. foreach (explode("+",$data['factors']['value']) as $factor) {
  325. $preference = $this->wbwPreference($factor,'meaning',$user['user_id']);
  326. if($preference!==false){
  327. $wbwFactorMeaning[] = $preference['value'];
  328. }else{
  329. $wbwFactorMeaning[] = $factor;
  330. }
  331. }
  332. }
  333. $data['factorMeaning'] = ['value'=>implode('+',$wbwFactorMeaning),'status'=>3];
  334. }
  335. if(empty($data['meaning']['value']) && !empty($data['parent']['value'])){
  336. if(isset($indexed[$data['parent']['value']])){
  337. foreach ($indexed[$data['parent']['value']] as $value) {
  338. //根据base 查找词意
  339. //非base优先
  340. $increment = 10;
  341. if($this->langCheck($lang,$value->language)){
  342. $meaning = $this->insertValue(explode('$',$value->mean),$meaning,$increment,false);
  343. }
  344. //查找词源
  345. if(!empty($value->parent) && $value->parent !== $value->word && strstr($value->type,"base") !== FALSE ){
  346. $parent2 = $this->insertValue([$value->grammar."$".$value->parent],$parent2,1,false);
  347. }
  348. }
  349. }
  350. }
  351. if(count($meaning)>0){
  352. arsort($meaning);
  353. $first = array_keys($meaning)[0];
  354. $data['meaning'] = ['value'=>$first==="_null"?"":$first,'status'=>3];
  355. }
  356. if(count($parent2)>0){
  357. arsort($parent2);
  358. $first = explode("$",array_keys($parent2)[0]);
  359. $data['parent2'] = ['value'=>$first[1],'status'=>3];
  360. $data['grammar2'] = ['value'=>$first[0],'status'=>3];
  361. }
  362. }
  363. $orgData[$key] = $data;
  364. }
  365. return $this->ok($orgData);
  366. }
  367. /**
  368. * 自动查词
  369. *
  370. * @param string $sentId
  371. * @return \Illuminate\Http\Response
  372. */
  373. public function show(Request $request,string $sentId)
  374. {
  375. $startAt = microtime(true)*1000;
  376. $channel = Channel::find($request->get('channel_id'));
  377. //查询句子中的单词
  378. $sent = \explode('-',$sentId);
  379. $wbw = WbwTemplate::where('book',$sent[0])
  380. ->where('paragraph',$sent[1])
  381. ->whereBetween('wid',[$sent[2],$sent[3]])
  382. ->orderBy('wid')
  383. ->get();
  384. $words = [];
  385. foreach ($wbw as $row) {
  386. if($row->type !== '.ctl.' && !empty($row->real)){
  387. $words[] = $row->real;
  388. }
  389. }
  390. $result = $this->lookup($words,[],2);
  391. $indexed = $this->toIndexed($result);
  392. //生成自动填充结果
  393. $wbwContent = [];
  394. foreach ($wbw as $row) {
  395. $type = $row->type=='?'? '':$row->type;
  396. $grammar = $row->gramma=='?'? '':$row->gramma;
  397. $part = $row->part=='?'? '':$row->part;
  398. if(!empty($type) || !empty($grammar)){
  399. $case = "{$type}#$grammar";
  400. }else{
  401. $case = "";
  402. }
  403. $data = [
  404. 'sn'=>[$row->wid],
  405. 'word'=>['value'=>$row->word,'status'=>3],
  406. 'real'=> ['value'=>$row->real,'status'=>3],
  407. 'meaning'=> ['value'=>[],'status'=>3],
  408. 'type'=> ['value'=>$type,'status'=>3],
  409. 'grammar'=> ['value'=>$grammar,'status'=>3],
  410. 'case'=> ['value'=>$case,'status'=>3],
  411. 'style'=> ['value'=>$row->style,'status'=>3],
  412. 'factors'=> ['value'=>$part,'status'=>3],
  413. 'factorMeaning'=> ['value'=>'','status'=>3],
  414. 'confidence'=> 0.5
  415. ];
  416. if($row->type !== '.ctl.' && !empty($row->real)){
  417. if(isset($indexed[$row->real])){
  418. //parent
  419. $case = [];
  420. $parent = [];
  421. $factors = [];
  422. $factorMeaning = [];
  423. $meaning = [];
  424. $parent2 = [];
  425. $case2 = [];
  426. foreach ($indexed[$row->real] as $value) {
  427. //非base优先
  428. if(strstr($value->type,'base') === FALSE){
  429. $increment = 10;
  430. }else{
  431. $increment = 1;
  432. }
  433. //将全部结果加上得分放入数组
  434. $parent = $this->insertValue([$value->parent],$parent,$increment);
  435. $case = $this->insertValue([$value->type."#".$value->grammar],$case,$increment);
  436. $factors = $this->insertValue([$value->factors],$factors,$increment);
  437. $factorMeaning = $this->insertValue([$value->factormean],$factorMeaning,$increment);
  438. $meaning = $this->insertValue(explode('$',$value->mean),$meaning,$increment,false);
  439. }
  440. if(count($case)>0){
  441. arsort($case);
  442. $first = array_keys($case)[0];
  443. $data['case'] = ['value'=>$first==="_null"?"":$first,'status'=>3];
  444. }
  445. if(count($parent)>0){
  446. arsort($parent);
  447. $first = array_keys($parent)[0];
  448. $data['parent'] = ['value'=>$first==="_null"?"":$first,'status'=>3];
  449. }
  450. if(count($factors)>0){
  451. arsort($factors);
  452. $first = array_keys($factors)[0];
  453. $data['factors'] = ['value'=>$first==="_null"?"":$first,'status'=>3];
  454. }
  455. if(count($factorMeaning)>0){
  456. arsort($factorMeaning);
  457. $first = array_keys($factorMeaning)[0];
  458. $data['factorMeaning'] = ['value'=>$first==="_null"?"":$first,'status'=>3];
  459. }
  460. //根据base 查找词意
  461. if(!empty($data['parent'])){
  462. if(isset($indexed[$data['parent']['value']])){
  463. foreach ($indexed[$data['parent']['value']] as $value) {
  464. //非base优先
  465. $increment = 10;
  466. $meaning = $this->insertValue(explode('$',$value->mean),$meaning,$increment,false);
  467. }
  468. }else{
  469. //Log::error("no set parent".$data['parent']['value']);
  470. }
  471. }
  472. if(count($meaning)>0){
  473. arsort($meaning);
  474. $first = array_keys($meaning)[0];
  475. $data['meaning'] = ['value'=>$first==="_null"?"":$first,'status'=>3];
  476. }
  477. }
  478. }
  479. $wbwContent[] = $data;
  480. }
  481. $endAt = microtime(true)*1000;
  482. return $this->ok(["rows"=>$wbwContent,
  483. "count"=>count($wbwContent),
  484. "time"=>(int)($endAt-$startAt)]);
  485. }
  486. private function toIndexed($words){
  487. //转成索引数组
  488. $indexed = [];
  489. foreach ($words as $key => $value) {
  490. # code...
  491. $indexed[$value->word][] = $value;
  492. }
  493. return $indexed;
  494. }
  495. private function insertValue($value,$container,$increment,$empty=true){
  496. foreach ($value as $one) {
  497. if($empty === false){
  498. if(empty($one)){
  499. break;
  500. }
  501. }
  502. $one=trim($one);
  503. $key = $one;
  504. if(empty($key)){
  505. $key = '_null';
  506. }
  507. if(isset($container[$key])){
  508. $container[$key] += $increment;
  509. }else{
  510. $container[$key] = $increment;
  511. }
  512. }
  513. return $container;
  514. }
  515. /**
  516. * Update the specified resource in storage.
  517. *
  518. * @param \Illuminate\Http\Request $request
  519. * @param \App\Models\UserDict $userDict
  520. * @return \Illuminate\Http\Response
  521. */
  522. public function update(Request $request, UserDict $userDict)
  523. {
  524. //
  525. }
  526. /**
  527. * Remove the specified resource from storage.
  528. *
  529. * @param \App\Models\UserDict $userDict
  530. * @return \Illuminate\Http\Response
  531. */
  532. public function destroy(UserDict $userDict)
  533. {
  534. //
  535. }
  536. }