| 333 | } |
| 334 | |
| 335 | std::vector<DocumentChunk> DocumentProcessor::process_directory(const std::string& dir_path) { |
| 336 | std::vector<DocumentChunk> all_chunks; |
| 337 | |
| 338 | if (!fs::exists(dir_path) || !fs::is_directory(dir_path)) { |
| 339 | fprintf(stderr, "[DOC] Directory not found: %s\n", dir_path.c_str()); |
| 340 | return {}; |
| 341 | } |
| 342 | |
| 343 | // Collect document files sorted by name |
| 344 | std::vector<std::string> pdf_files; |
| 345 | std::vector<std::string> docx_files; |
| 346 | std::vector<std::string> txt_files; |
| 347 | static const std::vector<std::string> text_exts = { |
| 348 | ".txt", ".md", ".json", ".jsonl", ".csv", ".log", |
| 349 | ".html", ".htm", ".xml", ".yaml", ".yml", ".ini", |
| 350 | ".cfg", ".conf", ".rst", ".rtf", |
| 351 | }; |
| 352 | for (const auto& entry : fs::recursive_directory_iterator(dir_path)) { |
| 353 | if (entry.is_regular_file()) { |
| 354 | std::string ext = entry.path().extension().string(); |
| 355 | std::transform(ext.begin(), ext.end(), ext.begin(), |
| 356 | [](unsigned char c) { return std::tolower(c); }); |
| 357 | if (ext == ".pdf") { |
| 358 | pdf_files.push_back(entry.path().string()); |
| 359 | } else if (ext == ".docx") { |
| 360 | docx_files.push_back(entry.path().string()); |
| 361 | } else if (std::find(text_exts.begin(), text_exts.end(), ext) != text_exts.end()) { |
| 362 | txt_files.push_back(entry.path().string()); |
| 363 | } |
| 364 | } |
| 365 | } |
| 366 | std::sort(pdf_files.begin(), pdf_files.end()); |
| 367 | std::sort(docx_files.begin(), docx_files.end()); |
| 368 | std::sort(txt_files.begin(), txt_files.end()); |
| 369 | |
| 370 | fprintf(stderr, "[DOC] Found %zu PDF, %zu DOCX, %zu text files in %s\n", |
| 371 | pdf_files.size(), docx_files.size(), txt_files.size(), dir_path.c_str()); |
| 372 | |
| 373 | for (const auto& pdf : pdf_files) { |
| 374 | auto chunks = process_pdf(pdf); |
| 375 | all_chunks.insert(all_chunks.end(), |
| 376 | std::make_move_iterator(chunks.begin()), |
| 377 | std::make_move_iterator(chunks.end())); |
| 378 | } |
| 379 | |
| 380 | for (const auto& docx : docx_files) { |
| 381 | auto chunks = process_docx(docx); |
| 382 | all_chunks.insert(all_chunks.end(), |
| 383 | std::make_move_iterator(chunks.begin()), |
| 384 | std::make_move_iterator(chunks.end())); |
| 385 | } |
| 386 | |
| 387 | // Process text files |
| 388 | for (const auto& txt : txt_files) { |
| 389 | fprintf(stderr, "[DOC] Processing TXT: %s\n", txt.c_str()); |
| 390 | std::ifstream ifs(txt); |
| 391 | if (!ifs) { |
| 392 | fprintf(stderr, "[DOC] Failed to read %s\n", txt.c_str()); |