ai_parse_sync.php 13 KB

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