ai_parse_sync.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. #!/usr/bin/env php
  2. <?php
  3. // 检查是否支持多进程
  4. if (!function_exists('pcntl_fork')) {
  5. echo "\n❌ 错误:PHP pcntl 扩展未安装,无法使用并发模式。\n";
  6. echo "请安装 pcntl 扩展或使用单进程模式。\n\n";
  7. exit(1);
  8. }
  9. require __DIR__ . '/vendor/autoload.php';
  10. $app = require_once __DIR__ . '/bootstrap/app.php';
  11. $kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
  12. $kernel->bootstrap();
  13. use App\Models\MarkdownImport;
  14. use App\Models\PreQuestionCandidate;
  15. use App\Services\MarkdownQuestionParser;
  16. use Illuminate\Support\Facades\DB;
  17. use Illuminate\Support\Facades\Facade;
  18. echo "\n=== AI 解析同步执行脚本 (并发版) ===\n\n";
  19. // 查找所有导入记录
  20. $allImports = MarkdownImport::orderBy('created_at', 'desc')->get();
  21. if ($allImports->isEmpty()) {
  22. echo "❌ 没有找到导入记录。\n\n";
  23. exit(0);
  24. }
  25. echo "📋 找到 {$allImports->count()} 个导入记录:\n\n";
  26. foreach ($allImports as $index => $import) {
  27. $candidateCount = PreQuestionCandidate::where('import_id', $import->id)
  28. ->where('status', '!=', 'superseded')
  29. ->count();
  30. echo sprintf(
  31. "%d. ID %d: %s (%d 个候选题)\n",
  32. $index + 1,
  33. $import->id,
  34. $import->file_name,
  35. $candidateCount
  36. );
  37. }
  38. echo "\n选择要解析的导入ID (输入数字,多个用逗号分隔,输入 'all' 全部执行): ";
  39. $input = trim(fgets(STDIN));
  40. $selectedImports = [];
  41. if ($input === 'all') {
  42. $selectedImports = $allImports;
  43. } else {
  44. $indices = array_map('intval', explode(',', $input));
  45. foreach ($indices as $index) {
  46. if ($index >= 1 && $index <= $allImports->count()) {
  47. $selectedImports[] = $allImports[$index - 1];
  48. }
  49. }
  50. }
  51. if (empty($selectedImports)) {
  52. echo "❌ 没有选择有效的导入记录。\n";
  53. exit(1);
  54. }
  55. echo "\n设置并发参数:\n";
  56. echo "并发进程数 (建议 4-8,默认为 4): ";
  57. $workers = (int)trim(fgets(STDIN));
  58. if ($workers <= 0) {
  59. $workers = 4;
  60. }
  61. echo "每个进程的批次大小 (默认 10): ";
  62. $batchSize = (int)trim(fgets(STDIN));
  63. if ($batchSize <= 0) {
  64. $batchSize = 10;
  65. }
  66. echo "\n=== 开始执行 AI 解析 (并发模式: {$workers} 进程) ===\n\n";
  67. foreach ($selectedImports as $import) {
  68. echo "🔄 处理 ID {$import->id}: {$import->file_name}\n";
  69. $candidateCount = PreQuestionCandidate::where('import_id', $import->id)
  70. ->where('status', '!=', 'superseded')
  71. ->count();
  72. if ($candidateCount === 0) {
  73. echo " ⚠️ 没有候选题,跳过\n\n";
  74. continue;
  75. }
  76. // 更新导入状态
  77. $import->update([
  78. 'status' => 'processing',
  79. 'progress_stage' => MarkdownImport::STAGE_AI_PARSING,
  80. 'progress_message' => "开始 AI 解析(本地脚本)...",
  81. 'progress_current' => 0,
  82. 'progress_total' => $candidateCount,
  83. 'progress_updated_at' => now(),
  84. 'processing_started_at' => $import->processing_started_at ?: now(),
  85. 'processing_finished_at' => null,
  86. 'error_message' => null,
  87. ]);
  88. echo " 📊 总计 {$candidateCount} 个候选题,使用 {$workers} 个进程并发处理\n";
  89. // 将候选题分成批次
  90. $candidateIds = PreQuestionCandidate::where('import_id', $import->id)
  91. ->where('status', '!=', 'superseded')
  92. ->orderBy('id')
  93. ->pluck('id')
  94. ->toArray();
  95. $batches = array_chunk($candidateIds, $batchSize);
  96. $batchCount = count($batches);
  97. $batchSizes = array_map('count', $batches);
  98. $activeWorkers = [];
  99. // 创建临时目录存储子进程结果
  100. $tmpDir = sys_get_temp_dir() . '/ai_parse_' . $import->id;
  101. if (!is_dir($tmpDir)) {
  102. mkdir($tmpDir, 0777, true);
  103. }
  104. $batchIndex = 0;
  105. $processedTotal = 0;
  106. $failedTotal = 0;
  107. $batchDurations = [];
  108. // 主进程循环
  109. while ($batchIndex < $batchCount || !empty($activeWorkers)) {
  110. // 启动新的工作进程
  111. while ($batchIndex < $batchCount && count($activeWorkers) < $workers) {
  112. $batch = $batches[$batchIndex];
  113. $pid = pcntl_fork();
  114. if ($pid == -1) {
  115. die("无法创建子进程\n");
  116. } elseif ($pid == 0) {
  117. // 子进程
  118. $start = microtime(true);
  119. $result = [
  120. 'processed' => 0,
  121. 'failed' => count($batch),
  122. 'error' => 'child terminated unexpectedly',
  123. 'duration_sec' => 0,
  124. ];
  125. try {
  126. $result = processBatch($import->id, $batch);
  127. } catch (Throwable $e) {
  128. $result = [
  129. 'processed' => 0,
  130. 'failed' => count($batch),
  131. 'error' => $e->getMessage(),
  132. 'duration_sec' => 0,
  133. ];
  134. }
  135. $result['duration_sec'] = round(microtime(true) - $start, 3);
  136. $resultFile = $tmpDir . '/batch_' . $batchIndex . '.json';
  137. $tmpFile = $resultFile . '.tmp';
  138. file_put_contents($tmpFile, json_encode($result), LOCK_EX);
  139. rename($tmpFile, $resultFile);
  140. exit(($result['failed'] ?? 0) > 0 ? 1 : 0);
  141. } else {
  142. // 父进程
  143. $activeWorkers[$pid] = $batchIndex;
  144. $batchIndex++;
  145. }
  146. }
  147. // 检查子进程状态
  148. foreach ($activeWorkers as $pid => $batchIdx) {
  149. $res = pcntl_waitpid($pid, $status, WNOHANG);
  150. if ($res == $pid) {
  151. // 子进程完成
  152. unset($activeWorkers[$pid]);
  153. // 读取结果
  154. $resultFile = $tmpDir . '/batch_' . $batchIdx . '.json';
  155. if (file_exists($resultFile)) {
  156. $raw = file_get_contents($resultFile);
  157. $result = json_decode($raw, true);
  158. $expected = $batchSizes[$batchIdx] ?? 0;
  159. if (!is_array($result)) {
  160. $result = [
  161. 'processed' => 0,
  162. 'failed' => $expected,
  163. 'error' => 'invalid result file: ' . ($raw === '' ? 'empty' : 'malformed json'),
  164. ];
  165. }
  166. $processed = $result['processed'] ?? 0;
  167. $failed = $result['failed'] ?? $expected;
  168. $accounted = $processed + $failed;
  169. if ($expected > 0 && $accounted < $expected) {
  170. $failed += ($expected - $accounted);
  171. }
  172. $processedTotal += $processed;
  173. $failedTotal += $failed;
  174. if (!empty($result['error'])) {
  175. echo " ⚠️ 批次 {$batchIdx} 错误: {$result['error']}\n";
  176. }
  177. if (isset($result['duration_sec'])) {
  178. $duration = (float) $result['duration_sec'];
  179. $batchDurations[] = $duration;
  180. $count = count($batchDurations);
  181. echo sprintf(" ⏱️ 批次 %d 用时: %.2fs\n", $batchIdx, $duration);
  182. if ($count % 10 === 0) {
  183. $recent = array_slice($batchDurations, -10);
  184. $avg = array_sum($recent) / max(count($recent), 1);
  185. echo sprintf(" 📈 最近 10 批次平均用时: %.2fs (估算 10 批次)\n", $avg);
  186. }
  187. }
  188. $percent = round(($processedTotal / $candidateCount) * 100, 1);
  189. echo " ⏳ 进度: {$processedTotal}/{$candidateCount} ({$percent}%)\n";
  190. } else {
  191. $failedTotal += $batchSizes[$batchIdx] ?? 0;
  192. echo " ⚠️ 批次 {$batchIdx} 未找到结果文件,已计为失败\n";
  193. }
  194. }
  195. }
  196. // 短暂休眠避免CPU占用过高
  197. usleep(100000); // 0.1秒
  198. }
  199. // 清理临时文件
  200. array_map('unlink', glob($tmpDir . '/*'));
  201. rmdir($tmpDir);
  202. // 更新最终状态
  203. $import->update([
  204. 'status' => 'parsed',
  205. 'progress_stage' => MarkdownImport::STAGE_PARSED,
  206. 'progress_message' => "解析完成,成功 {$processedTotal},失败 {$failedTotal}",
  207. 'progress_current' => $processedTotal,
  208. 'progress_total' => $candidateCount,
  209. 'progress_updated_at' => now(),
  210. 'processing_finished_at' => now(),
  211. ]);
  212. echo " ✅ 完成: 成功 {$processedTotal} 题,失败 {$failedTotal} 题\n\n";
  213. }
  214. echo "=== 所有任务完成 ===\n\n";
  215. // 子进程处理函数
  216. function processBatch($importId, $candidateIds) {
  217. // 确保自动加载器已加载
  218. if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
  219. return [
  220. 'processed' => 0,
  221. 'failed' => count($candidateIds),
  222. 'error' => 'Composer autoload not found',
  223. ];
  224. }
  225. require_once __DIR__ . '/vendor/autoload.php';
  226. // 在子进程中重新初始化 Laravel 应用
  227. $app = require __DIR__ . '/bootstrap/app.php';
  228. // 先检查应用实例是否正确
  229. if (!$app instanceof Illuminate\Foundation\Application) {
  230. return [
  231. 'processed' => 0,
  232. 'failed' => count($candidateIds),
  233. 'error' => 'Laravel app initialization failed in child process',
  234. ];
  235. }
  236. try {
  237. Facade::clearResolvedInstances();
  238. Facade::setFacadeApplication($app);
  239. $kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
  240. $kernel->bootstrap();
  241. } catch (Throwable $e) {
  242. return [
  243. 'processed' => 0,
  244. 'failed' => count($candidateIds),
  245. 'error' => 'Failed to bootstrap kernel: ' . $e->getMessage(),
  246. ];
  247. }
  248. try {
  249. DB::disconnect();
  250. DB::reconnect();
  251. DB::disableQueryLog();
  252. } catch (Throwable $e) {
  253. return [
  254. 'processed' => 0,
  255. 'failed' => count($candidateIds),
  256. 'error' => 'Failed to reconnect DB: ' . $e->getMessage(),
  257. ];
  258. }
  259. // 直接从容器获取服务
  260. try {
  261. $parser = $app->make(App\Services\MarkdownQuestionParser::class);
  262. } catch (Throwable $e) {
  263. return [
  264. 'processed' => 0,
  265. 'failed' => count($candidateIds),
  266. 'error' => 'Failed to resolve services: ' . $e->getMessage(),
  267. ];
  268. }
  269. $processed = 0;
  270. $failed = 0;
  271. foreach ($candidateIds as $candidateId) {
  272. try {
  273. // 在子进程中也需要重新连接数据库
  274. $candidate = App\Models\PreQuestionCandidate::find($candidateId);
  275. if (!$candidate) {
  276. $failed++;
  277. continue;
  278. }
  279. // 如果已经解析过,跳过
  280. $meta = $candidate->meta ?? [];
  281. if (!empty($meta['ai_parsed'])) {
  282. $processed++;
  283. continue;
  284. }
  285. // 执行 AI 解析
  286. $parsed = $parser->parseRawMarkdown((string) $candidate->raw_markdown, (int) $candidate->index);
  287. $meta = $candidate->meta ?? [];
  288. $meta['ai_parsed'] = true;
  289. $meta['ai_parsed_at'] = now()->toDateTimeString();
  290. $candidate->update([
  291. 'stem' => $parsed['stem'] ?? null,
  292. 'options' => $parsed['options'] ?? null,
  293. 'images' => $parsed['images'] ?? [],
  294. 'tables' => $parsed['tables'] ?? [],
  295. 'is_question_candidate' => (bool) ($parsed['is_question_candidate'] ?? false),
  296. 'ai_confidence' => $parsed['ai_confidence'] ?? null,
  297. 'status' => 'pending',
  298. 'meta' => $meta,
  299. ]);
  300. $processed++;
  301. } catch (\Throwable $e) {
  302. $failed++;
  303. // 记录详细错误信息到子进程stderr
  304. fwrite(STDERR, sprintf(
  305. "[Child PID %d] Candidate %d failed: %s in %s:%d\n%s\n",
  306. getmypid(),
  307. $candidateId,
  308. $e->getMessage(),
  309. basename($e->getFile()),
  310. $e->getLine(),
  311. $e->getTraceAsString()
  312. ));
  313. }
  314. }
  315. return [
  316. 'processed' => $processed,
  317. 'failed' => $failed,
  318. ];
  319. }