UpdateCorpus.php 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Services\SentenceService;
  4. use Illuminate\Console\Attributes\Description;
  5. use Illuminate\Console\Attributes\Signature;
  6. use Illuminate\Console\Command;
  7. use Illuminate\Support\Facades\DB;
  8. use App\Models\Channel;
  9. #[Signature('app:update-corpus')]
  10. #[Description('Update corpus from JSONL files in corpus directory')]
  11. class UpdateCorpus extends Command
  12. {
  13. /**
  14. * The SentenceService instance.
  15. *
  16. * @var SentenceService
  17. */
  18. protected SentenceService $sentenceService;
  19. /**
  20. * Create a new command instance.
  21. *
  22. * @param SentenceService $sentenceService
  23. */
  24. public function __construct(SentenceService $sentenceService)
  25. {
  26. parent::__construct();
  27. $this->sentenceService = $sentenceService;
  28. }
  29. /**
  30. * Execute the console command.
  31. *
  32. * @return int
  33. */
  34. public function handle(): int
  35. {
  36. $this->info('Starting corpus update process...');
  37. // Get the corpus base path from config
  38. $corpusBasePath = config('mint.path.corpus');
  39. if (!is_dir($corpusBasePath)) {
  40. $this->error("Corpus directory not found: {$corpusBasePath}");
  41. return self::FAILURE;
  42. }
  43. // Scan subdirectories of the corpus path
  44. $subdirectories = $this->getSubdirectories($corpusBasePath);
  45. if (empty($subdirectories)) {
  46. $this->warn('No subdirectories found in corpus path.');
  47. return self::SUCCESS;
  48. }
  49. $this->info("Found " . count($subdirectories) . " subdirectories to process.");
  50. $totalProcessed = 0;
  51. $totalErrors = 0;
  52. foreach ($subdirectories as $subdir) {
  53. $this->info("Processing directory: {$subdir}");
  54. try {
  55. $stats = $this->processCorpusDirectory($subdir);
  56. $totalProcessed += $stats['processed'];
  57. $totalErrors += $stats['errors'];
  58. $this->info("Directory processed: {$stats['processed']} records saved, {$stats['errors']} errors");
  59. } catch (\Exception $e) {
  60. $this->error("Failed to process directory {$subdir}: {$e->getMessage()}");
  61. $totalErrors++;
  62. }
  63. }
  64. $this->info("Corpus update completed. Total processed: {$totalProcessed}, Total errors: {$totalErrors}");
  65. return $totalErrors > 0 ? self::FAILURE : self::SUCCESS;
  66. }
  67. /**
  68. * Get all subdirectories of a given directory.
  69. *
  70. * @param string $path
  71. * @return array
  72. */
  73. protected function getSubdirectories(string $path): array
  74. {
  75. $directories = [];
  76. $items = scandir($path);
  77. foreach ($items as $item) {
  78. if ($item === '.' || $item === '..') {
  79. continue;
  80. }
  81. $fullPath = $path . DIRECTORY_SEPARATOR . $item;
  82. if (is_dir($fullPath)) {
  83. $directories[] = $fullPath;
  84. }
  85. }
  86. return $directories;
  87. }
  88. /**
  89. * Process a single corpus directory.
  90. *
  91. * @param string $directoryPath
  92. * @return array
  93. * @throws \Exception
  94. */
  95. protected function processCorpusDirectory(string $directoryPath): array
  96. {
  97. $stats = [
  98. 'processed' => 0,
  99. 'errors' => 0,
  100. ];
  101. // Read meta.json file
  102. $metaFile = $directoryPath . DIRECTORY_SEPARATOR . 'meta.json';
  103. if (!file_exists($metaFile)) {
  104. $this->warn("meta.json not found in directory: {$directoryPath}");
  105. return $stats;
  106. }
  107. $metaData = json_decode(file_get_contents($metaFile), true);
  108. if (!isset($metaData['id'])) {
  109. $this->error("Invalid meta.json: missing 'id' field in {$directoryPath}");
  110. return $stats;
  111. }
  112. $sourceId = $metaData['id'];
  113. $this->info("Processing {$directoryPath} source ID: {$sourceId}");
  114. // Find all channel records with matching source_id
  115. $channels = Channel::where('source_id', $sourceId)->get();
  116. if ($channels->isEmpty()) {
  117. $this->warn("No channels found with source_id: {$sourceId}");
  118. return $stats;
  119. }
  120. $this->info("Found {$channels->count()} channel(s) for source ID: {$sourceId}");
  121. // Scan subdirectories of the current directory for JSONL files
  122. $childDirectories = $this->getSubdirectories($directoryPath);
  123. foreach ($childDirectories as $childDir) {
  124. $this->info("Scanning directory for JSONL files: {$childDir}");
  125. $jsonlFiles = glob($childDir . DIRECTORY_SEPARATOR . '*.jsonl');
  126. foreach ($jsonlFiles as $jsonlFile) {
  127. $this->line("Processing file: {$jsonlFile}");
  128. $fileStats = $this->processJsonlFile($jsonlFile, $channels);
  129. $stats['processed'] += $fileStats['processed'];
  130. $stats['errors'] += $fileStats['errors'];
  131. }
  132. }
  133. return $stats;
  134. }
  135. /**
  136. * Process a single JSONL file and save records for each channel.
  137. *
  138. * @param string $filePath
  139. * @param \Illuminate\Database\Eloquent\Collection $channels
  140. * @return array
  141. */
  142. protected function processJsonlFile(string $filePath, $channels): array
  143. {
  144. $stats = [
  145. 'processed' => 0,
  146. 'errors' => 0,
  147. ];
  148. $handle = fopen($filePath, 'r');
  149. if (!$handle) {
  150. $this->error("Failed to open file: {$filePath}");
  151. return $stats;
  152. }
  153. $lineNumber = 0;
  154. $robotUid = config('mint.admin.robot_uuid');
  155. if (!$robotUid) {
  156. $this->error('robot_uuid not configured in mint.admin.robot_uuid');
  157. fclose($handle);
  158. return $stats;
  159. }
  160. while (($line = fgets($handle)) !== false) {
  161. $lineNumber++;
  162. $line = trim($line);
  163. if (empty($line)) {
  164. continue;
  165. }
  166. // Parse JSON line
  167. $data = json_decode($line, true);
  168. if ($data === null) {
  169. $this->error("Failed to parse JSON at line {$lineNumber} in file: {$filePath}");
  170. $stats['errors']++;
  171. continue;
  172. }
  173. // Save for each channel
  174. foreach ($channels as $channel) {
  175. try {
  176. $saveData = [
  177. 'book_id' => $data['book'],
  178. 'paragraph' => $data['paragraph'],
  179. 'word_start' => $data['start'],
  180. 'word_end' => $data['end'],
  181. 'content' => $data['content'],
  182. 'channel_uid' => $channel->uid,
  183. 'editor_uid' => $robotUid,
  184. ];
  185. DB::transaction(function () use ($saveData) {
  186. $this->sentenceService->save($saveData);
  187. });
  188. $stats['processed']++;
  189. //$this->line("Saved record for channel: {$channel->uid}");
  190. } catch (\Exception $e) {
  191. $this->error("Failed to save record for channel {$channel->uid} at line {$lineNumber}: {$e->getMessage()}");
  192. $stats['errors']++;
  193. }
  194. }
  195. }
  196. fclose($handle);
  197. $this->line("$lineNumber lines write");
  198. return $stats;
  199. }
  200. }