-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Expand file tree
/
Copy pathprocessor.py
More file actions
2005 lines (1724 loc) · 78.9 KB
/
processor.py
File metadata and controls
2005 lines (1724 loc) · 78.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Document processing functionality for RAGAnything
Contains methods for parsing documents and processing multimodal content
"""
import os
import time
import hashlib
import json
from typing import Dict, List, Any, Tuple, Optional
from pathlib import Path
from raganything.base import DocStatus
from raganything.parser import MineruParser, MineruExecutionError, get_parser
from raganything.utils import (
separate_content,
insert_text_content,
insert_text_content_with_multimodal_content,
get_processor_for_type,
)
import asyncio
from lightrag.utils import compute_mdhash_id
class ProcessorMixin:
"""ProcessorMixin class containing document processing functionality for RAGAnything"""
def _get_file_reference(self, file_path: str) -> str:
"""
Get file reference based on use_full_path configuration.
Args:
file_path: Path to the file (can be absolute or relative)
Returns:
str: Full path if use_full_path is True, otherwise basename
"""
if self.config.use_full_path:
return str(file_path)
else:
return os.path.basename(file_path)
def _generate_cache_key(
self, file_path: Path, parse_method: str = None, **kwargs
) -> str:
"""
Generate cache key based on file path and parsing configuration
Args:
file_path: Path to the file
parse_method: Parse method used
**kwargs: Additional parser parameters
Returns:
str: Cache key for the file and configuration
"""
# Get file modification time
mtime = file_path.stat().st_mtime
# Create configuration dict for cache key
config_dict = {
"file_path": str(file_path.absolute()),
"mtime": mtime,
"parser": self.config.parser,
"parse_method": parse_method or self.config.parse_method,
}
# Add relevant kwargs to config
relevant_kwargs = {
k: v
for k, v in kwargs.items()
if k
in [
"lang",
"device",
"start_page",
"end_page",
"formula",
"table",
"backend",
"source",
]
}
config_dict.update(relevant_kwargs)
# Generate hash from config
config_str = json.dumps(config_dict, sort_keys=True)
cache_key = hashlib.md5(config_str.encode()).hexdigest()
return cache_key
def _generate_content_based_doc_id(self, content_list: List[Dict[str, Any]]) -> str:
"""
Generate doc_id based on document content
Args:
content_list: Parsed content list
Returns:
str: Content-based document ID with doc- prefix
"""
from lightrag.utils import compute_mdhash_id
# Extract key content for ID generation
content_hash_data = []
for item in content_list:
if isinstance(item, dict):
# For text content, use the text
if item.get("type") == "text" and item.get("text"):
content_hash_data.append(item["text"].strip())
# For other content types, use key identifiers
elif item.get("type") == "image" and item.get("img_path"):
content_hash_data.append(f"image:{item['img_path']}")
elif item.get("type") == "table" and item.get("table_body"):
content_hash_data.append(f"table:{item['table_body']}")
elif item.get("type") == "equation" and item.get("text"):
content_hash_data.append(f"equation:{item['text']}")
else:
# For other types, use string representation
content_hash_data.append(str(item))
# Create a content signature
content_signature = "\n".join(content_hash_data)
# Generate doc_id from content
doc_id = compute_mdhash_id(content_signature, prefix="doc-")
return doc_id
async def _get_cached_result(
self, cache_key: str, file_path: Path, parse_method: str = None, **kwargs
) -> tuple[List[Dict[str, Any]], str] | None:
"""
Get cached parsing result if available and valid
Args:
cache_key: Cache key to look up
file_path: Path to the file for mtime check
parse_method: Parse method used
**kwargs: Additional parser parameters
Returns:
tuple[List[Dict[str, Any]], str] | None: (content_list, doc_id) or None if not found/invalid
"""
if not hasattr(self, "parse_cache") or self.parse_cache is None:
return None
try:
cached_data = await self.parse_cache.get_by_id(cache_key)
if not cached_data:
return None
# Check file modification time
current_mtime = file_path.stat().st_mtime
cached_mtime = cached_data.get("mtime", 0)
if current_mtime != cached_mtime:
self.logger.debug(f"Cache invalid - file modified: {cache_key}")
return None
# Check parsing configuration
cached_config = cached_data.get("parse_config", {})
current_config = {
"parser": self.config.parser,
"parse_method": parse_method or self.config.parse_method,
}
# Add relevant kwargs to current config
relevant_kwargs = {
k: v
for k, v in kwargs.items()
if k
in [
"lang",
"device",
"start_page",
"end_page",
"formula",
"table",
"backend",
"source",
]
}
current_config.update(relevant_kwargs)
if cached_config != current_config:
self.logger.debug(f"Cache invalid - config changed: {cache_key}")
return None
content_list = cached_data.get("content_list", [])
doc_id = cached_data.get("doc_id")
if content_list and doc_id:
self.logger.debug(
f"Found valid cached parsing result for key: {cache_key}"
)
return content_list, doc_id
else:
self.logger.debug(
f"Cache incomplete - missing content or doc_id: {cache_key}"
)
return None
except Exception as e:
self.logger.warning(f"Error accessing parse cache: {e}")
return None
async def _store_cached_result(
self,
cache_key: str,
content_list: List[Dict[str, Any]],
doc_id: str,
file_path: Path,
parse_method: str = None,
**kwargs,
) -> None:
"""
Store parsing result in cache
Args:
cache_key: Cache key to store under
content_list: Content list to cache
doc_id: Content-based document ID
file_path: Path to the file for mtime storage
parse_method: Parse method used
**kwargs: Additional parser parameters
"""
if not hasattr(self, "parse_cache") or self.parse_cache is None:
return
try:
# Get file modification time
file_mtime = file_path.stat().st_mtime
# Create parsing configuration
parse_config = {
"parser": self.config.parser,
"parse_method": parse_method or self.config.parse_method,
}
# Add relevant kwargs to config
relevant_kwargs = {
k: v
for k, v in kwargs.items()
if k
in [
"lang",
"device",
"start_page",
"end_page",
"formula",
"table",
"backend",
"source",
]
}
parse_config.update(relevant_kwargs)
cache_data = {
cache_key: {
"content_list": content_list,
"doc_id": doc_id,
"mtime": file_mtime,
"parse_config": parse_config,
"cached_at": time.time(),
"cache_version": "1.0",
}
}
await self.parse_cache.upsert(cache_data)
# Ensure data is persisted to disk
await self.parse_cache.index_done_callback()
self.logger.info(f"Stored parsing result in cache: {cache_key}")
except Exception as e:
self.logger.warning(f"Error storing to parse cache: {e}")
async def parse_document(
self,
file_path: str,
output_dir: str = None,
parse_method: str = None,
display_stats: bool = None,
**kwargs,
) -> tuple[List[Dict[str, Any]], str]:
"""
Parse document with caching support
Args:
file_path: Path to the file to parse
output_dir: Output directory (defaults to config.parser_output_dir)
parse_method: Parse method (defaults to config.parse_method)
display_stats: Whether to display content statistics (defaults to config.display_content_stats)
**kwargs: Additional parameters for parser (e.g., lang, device, start_page, end_page, formula, table, backend, source)
Returns:
tuple[List[Dict[str, Any]], str]: (content_list, doc_id)
"""
# Use config defaults if not provided
if output_dir is None:
output_dir = self.config.parser_output_dir
if parse_method is None:
parse_method = self.config.parse_method
if display_stats is None:
display_stats = self.config.display_content_stats
self.logger.info(f"Starting document parsing: {file_path}")
file_path = Path(file_path)
if not file_path.exists():
raise FileNotFoundError(f"File not found: {file_path}")
callback_file = str(file_path)
callback_manager = getattr(self, "callback_manager", None)
parse_start_time = time.time()
if callback_manager is not None:
callback_manager.dispatch(
"on_parse_start",
file_path=callback_file,
parser=self.config.parser,
)
# Generate cache key based on file and configuration
cache_key = self._generate_cache_key(file_path, parse_method, **kwargs)
# Check cache first
cached_result = await self._get_cached_result(
cache_key, file_path, parse_method, **kwargs
)
if cached_result is not None:
content_list, doc_id = cached_result
self.logger.info(f"Using cached parsing result for: {file_path}")
if display_stats:
self.logger.info(
f"* Total blocks in cached content_list: {len(content_list)}"
)
if callback_manager is not None:
duration = time.time() - parse_start_time
callback_manager.dispatch(
"on_parse_complete",
file_path=callback_file,
content_blocks=len(content_list),
doc_id=doc_id,
duration_seconds=duration,
)
return content_list, doc_id
# Choose appropriate parsing method based on file extension
ext = file_path.suffix.lower()
try:
doc_parser = getattr(self, "doc_parser", None)
if doc_parser is None:
doc_parser = get_parser(self.config.parser)
self.doc_parser = doc_parser
# Log parser and method information
self.logger.info(
f"Using {self.config.parser} parser with method: {parse_method}"
)
if ext in [".pdf"]:
self.logger.info("Detected PDF file, using parser for PDF...")
content_list = await asyncio.to_thread(
doc_parser.parse_pdf,
pdf_path=file_path,
output_dir=output_dir,
method=parse_method,
**kwargs,
)
elif ext in [
".jpg",
".jpeg",
".png",
".bmp",
".tiff",
".tif",
".gif",
".webp",
]:
self.logger.info("Detected image file, using parser for images...")
try:
content_list = await asyncio.to_thread(
doc_parser.parse_image,
image_path=file_path,
output_dir=output_dir,
**kwargs,
)
except NotImplementedError:
# Fallback to MinerU for image parsing if current parser doesn't support it
self.logger.warning(
f"{self.config.parser} parser doesn't support image parsing, falling back to MinerU"
)
content_list = await asyncio.to_thread(
MineruParser().parse_image,
image_path=file_path,
output_dir=output_dir,
**kwargs,
)
elif ext in [
".doc",
".docx",
".ppt",
".pptx",
".xls",
".xlsx",
".html",
".htm",
".xhtml",
]:
self.logger.info(
"Detected Office or HTML document, using parser for Office/HTML..."
)
content_list = await asyncio.to_thread(
doc_parser.parse_office_doc,
doc_path=file_path,
output_dir=output_dir,
**kwargs,
)
else:
# For other or unknown formats, use generic parser
self.logger.info(
f"Using generic parser for {ext} file (method={parse_method})..."
)
content_list = await asyncio.to_thread(
doc_parser.parse_document,
file_path=file_path,
method=parse_method,
output_dir=output_dir,
**kwargs,
)
except MineruExecutionError as e:
self.logger.error(f"Mineru command failed: {e}")
if callback_manager is not None:
callback_manager.dispatch(
"on_parse_error",
file_path=callback_file,
error=e,
parser=self.config.parser,
)
raise
except Exception as e:
self.logger.error(
f"Error during parsing with {self.config.parser} parser: {str(e)}"
)
if callback_manager is not None:
callback_manager.dispatch(
"on_parse_error",
file_path=callback_file,
error=e,
parser=self.config.parser,
)
raise
msg = f"Parsing {file_path} complete! Extracted {len(content_list)} content blocks"
self.logger.info(msg)
if len(content_list) == 0:
raise ValueError("Parsing failed: No content was extracted")
# Generate doc_id based on content
doc_id = self._generate_content_based_doc_id(content_list)
# Store result in cache
await self._store_cached_result(
cache_key, content_list, doc_id, file_path, parse_method, **kwargs
)
# Display content statistics if requested
if display_stats:
self.logger.info("\nContent Information:")
self.logger.info(f"* Total blocks in content_list: {len(content_list)}")
# Count elements by type
block_types: Dict[str, int] = {}
for block in content_list:
if isinstance(block, dict):
block_type = block.get("type", "unknown")
if isinstance(block_type, str):
block_types[block_type] = block_types.get(block_type, 0) + 1
self.logger.info("* Content block types:")
for block_type, count in block_types.items():
self.logger.info(f" - {block_type}: {count}")
if callback_manager is not None:
duration = time.time() - parse_start_time
callback_manager.dispatch(
"on_parse_complete",
file_path=callback_file,
content_blocks=len(content_list),
doc_id=doc_id,
duration_seconds=duration,
)
return content_list, doc_id
async def _process_multimodal_content(
self,
multimodal_items: List[Dict[str, Any]],
file_path: str,
doc_id: str,
pipeline_status: Optional[Any] = None,
pipeline_status_lock: Optional[Any] = None,
):
"""
Process multimodal content (using specialized processors)
Args:
multimodal_items: List of multimodal items
file_path: File path (for reference)
doc_id: Document ID for proper chunk association
pipeline_status: Pipeline status object
pipeline_status_lock: Pipeline status lock
"""
if not multimodal_items:
self.logger.debug("No multimodal content to process")
return
callback_manager = getattr(self, "callback_manager", None)
mm_start_time = time.time()
if callback_manager is not None:
callback_manager.dispatch(
"on_multimodal_start",
file_path=file_path,
item_count=len(multimodal_items),
doc_id=doc_id,
)
# Check multimodal processing status - handle LightRAG's early DocStatus.PROCESSED marking
try:
existing_doc_status = await self.lightrag.doc_status.get_by_id(doc_id)
if existing_doc_status:
# Check if multimodal content is already processed
multimodal_processed = existing_doc_status.get(
"multimodal_processed", False
)
if multimodal_processed:
self.logger.info(
f"Document {doc_id} multimodal content is already processed"
)
return
# Even if status is DocStatus.PROCESSED (text processing done),
# we still need to process multimodal content if not yet done
doc_status = existing_doc_status.get("status", "")
if doc_status == DocStatus.PROCESSED and not multimodal_processed:
self.logger.info(
f"Document {doc_id} text processing is complete, but multimodal content still needs processing"
)
# Continue with multimodal processing
elif doc_status == DocStatus.PROCESSED and multimodal_processed:
self.logger.info(
f"Document {doc_id} is fully processed (text + multimodal)"
)
return
except Exception as e:
self.logger.debug(f"Error checking document status for {doc_id}: {e}")
# Continue with processing if cache check fails
# Use ProcessorMixin's own batch processing that can handle multiple content types
log_message = "Starting multimodal content processing..."
self.logger.info(log_message)
if pipeline_status_lock and pipeline_status:
async with pipeline_status_lock:
pipeline_status["latest_message"] = log_message
pipeline_status["history_messages"].append(log_message)
try:
# Ensure LightRAG is initialized
await self._ensure_lightrag_initialized()
await self._process_multimodal_content_batch_type_aware(
multimodal_items=multimodal_items, file_path=file_path, doc_id=doc_id
)
# Mark multimodal content as processed and update final status
await self._mark_multimodal_processing_complete(doc_id)
log_message = "Multimodal content processing complete"
self.logger.info(log_message)
if pipeline_status_lock and pipeline_status:
async with pipeline_status_lock:
pipeline_status["latest_message"] = log_message
pipeline_status["history_messages"].append(log_message)
if callback_manager is not None:
duration = time.time() - mm_start_time
callback_manager.dispatch(
"on_multimodal_complete",
file_path=file_path,
processed_count=len(multimodal_items),
duration_seconds=duration,
doc_id=doc_id,
)
except Exception as e:
self.logger.error(f"Error in multimodal processing: {e}")
# Fallback to individual processing if batch processing fails
self.logger.warning("Falling back to individual multimodal processing")
await self._process_multimodal_content_individual(
multimodal_items, file_path, doc_id
)
# Mark multimodal content as processed even after fallback
await self._mark_multimodal_processing_complete(doc_id)
async def _process_multimodal_content_individual(
self, multimodal_items: List[Dict[str, Any]], file_path: str, doc_id: str
):
"""
Process multimodal content individually (fallback method)
Args:
multimodal_items: List of multimodal items
file_path: File path (for reference)
doc_id: Document ID for proper chunk association
"""
# Use full path or basename based on config
file_name = self._get_file_reference(file_path)
# Collect all chunk results for batch processing (similar to text content processing)
all_chunk_results = []
multimodal_chunk_ids = []
# Get current text chunks count to set proper order indexes for multimodal chunks
existing_doc_status = await self.lightrag.doc_status.get_by_id(doc_id)
existing_chunks_count = (
existing_doc_status.get("chunks_count", 0) if existing_doc_status else 0
)
for i, item in enumerate(multimodal_items):
try:
content_type = item.get("type", "unknown")
self.logger.info(
f"Processing item {i + 1}/{len(multimodal_items)}: {content_type} content"
)
# Select appropriate processor
processor = get_processor_for_type(self.modal_processors, content_type)
if processor:
# Prepare item info for context extraction
item_info = {
"page_idx": item.get("page_idx", 0),
"index": i,
"type": content_type,
}
# Process content and get chunk results instead of immediately merging
(
enhanced_caption,
entity_info,
chunk_results,
) = await processor.process_multimodal_content(
modal_content=item,
content_type=content_type,
file_path=file_name,
item_info=item_info, # Pass item info for context extraction
batch_mode=True,
doc_id=doc_id, # Pass doc_id for proper association
chunk_order_index=existing_chunks_count
+ i, # Proper order index
)
# Collect chunk results for batch processing
all_chunk_results.extend(chunk_results)
# Extract chunk ID from the entity_info (actual chunk_id created by processor)
if entity_info and "chunk_id" in entity_info:
chunk_id = entity_info["chunk_id"]
multimodal_chunk_ids.append(chunk_id)
self.logger.info(
f"{content_type} processing complete: {entity_info.get('entity_name', 'Unknown')}"
)
else:
self.logger.warning(
f"No suitable processor found for {content_type} type content"
)
except Exception as e:
self.logger.error(f"Error processing multimodal content: {str(e)}")
self.logger.debug("Exception details:", exc_info=True)
continue
# Update doc_status to include multimodal chunks in the standard chunks_list
if multimodal_chunk_ids:
try:
# Get current document status
current_doc_status = await self.lightrag.doc_status.get_by_id(doc_id)
if current_doc_status:
existing_chunks_list = current_doc_status.get("chunks_list", [])
existing_chunks_count = current_doc_status.get("chunks_count", 0)
# Add multimodal chunks to the standard chunks_list
updated_chunks_list = existing_chunks_list + multimodal_chunk_ids
updated_chunks_count = existing_chunks_count + len(
multimodal_chunk_ids
)
# Update document status with integrated chunk list
await self.lightrag.doc_status.upsert(
{
doc_id: {
**current_doc_status, # Keep existing fields
"chunks_list": updated_chunks_list, # Integrated chunks list
"chunks_count": updated_chunks_count, # Updated total count
"updated_at": time.strftime("%Y-%m-%dT%H:%M:%S+00:00"),
}
}
)
# Ensure doc_status update is persisted to disk
await self.lightrag.doc_status.index_done_callback()
self.logger.info(
f"Updated doc_status with {len(multimodal_chunk_ids)} multimodal chunks integrated into chunks_list"
)
except Exception as e:
self.logger.warning(
f"Error updating doc_status with multimodal chunks: {e}"
)
# Batch merge all multimodal content results (similar to text content processing)
if all_chunk_results:
from lightrag.operate import merge_nodes_and_edges
from lightrag.kg.shared_storage import (
get_namespace_data,
get_pipeline_status_lock,
)
# Get pipeline status and lock from shared storage
pipeline_status = await get_namespace_data("pipeline_status")
pipeline_status_lock = get_pipeline_status_lock()
await merge_nodes_and_edges(
chunk_results=all_chunk_results,
knowledge_graph_inst=self.lightrag.chunk_entity_relation_graph,
entity_vdb=self.lightrag.entities_vdb,
relationships_vdb=self.lightrag.relationships_vdb,
global_config=self.lightrag.__dict__,
full_entities_storage=self.lightrag.full_entities,
full_relations_storage=self.lightrag.full_relations,
doc_id=doc_id,
pipeline_status=pipeline_status,
pipeline_status_lock=pipeline_status_lock,
llm_response_cache=self.lightrag.llm_response_cache,
current_file_number=1,
total_files=1,
file_path=file_name,
)
await self.lightrag._insert_done()
self.logger.info("Individual multimodal content processing complete")
# Mark multimodal content as processed
await self._mark_multimodal_processing_complete(doc_id)
async def _process_multimodal_content_batch_type_aware(
self, multimodal_items: List[Dict[str, Any]], file_path: str, doc_id: str
):
"""
Type-aware batch processing that selects correct processors based on content type.
This is the corrected implementation that handles different modality types properly.
Args:
multimodal_items: List of multimodal items with different types
file_path: File path for citation
doc_id: Document ID for proper association
"""
if not multimodal_items:
self.logger.debug("No multimodal content to process")
return
# Get existing chunks count for proper order indexing
try:
existing_doc_status = await self.lightrag.doc_status.get_by_id(doc_id)
existing_chunks_count = (
existing_doc_status.get("chunks_count", 0) if existing_doc_status else 0
)
except Exception:
existing_chunks_count = 0
# Use LightRAG's concurrency control
semaphore = asyncio.Semaphore(getattr(self.lightrag, "max_parallel_insert", 2))
# Progress tracking variables
total_items = len(multimodal_items)
completed_count = 0
progress_lock = asyncio.Lock()
# Log processing start
self.logger.info(f"Starting to process {total_items} multimodal content items")
# Stage 1: Concurrent generation of descriptions using correct processors for each type
async def process_single_item_with_correct_processor(
item: Dict[str, Any], index: int, file_path: str
):
"""Process single item using the correct processor for its type"""
nonlocal completed_count
async with semaphore:
try:
content_type = item.get("type", "unknown")
# Select the correct processor based on content type
processor = get_processor_for_type(
self.modal_processors, content_type
)
if not processor:
self.logger.warning(
f"No processor found for type: {content_type}"
)
return None
item_info = {
"page_idx": item.get("page_idx", 0),
"index": index,
"type": content_type,
}
# Call the correct processor's description generation method
(
description,
entity_info,
) = await processor.generate_description_only(
modal_content=item,
content_type=content_type,
item_info=item_info,
entity_name=None, # Let LLM auto-generate
)
# Update progress (non-blocking)
async with progress_lock:
completed_count += 1
if (
completed_count % max(1, total_items // 10) == 0
or completed_count == total_items
):
progress_percent = (completed_count / total_items) * 100
self.logger.info(
f"Multimodal chunk generation progress: {completed_count}/{total_items} ({progress_percent:.1f}%)"
)
return {
"index": index,
"content_type": content_type,
"description": description,
"entity_info": entity_info,
"original_item": item,
"item_info": item_info,
"chunk_order_index": existing_chunks_count + index,
"processor": processor, # Keep reference to the processor used
"file_path": file_path, # Add file_path to the result
}
except Exception as e:
# Update progress even on error (non-blocking)
async with progress_lock:
completed_count += 1
if (
completed_count % max(1, total_items // 10) == 0
or completed_count == total_items
):
progress_percent = (completed_count / total_items) * 100
self.logger.info(
f"Multimodal chunk generation progress: {completed_count}/{total_items} ({progress_percent:.1f}%)"
)
self.logger.error(
f"Error generating description for {content_type} item {index}: {e}"
)
return None
# Process all items concurrently with correct processors
tasks = [
asyncio.create_task(
process_single_item_with_correct_processor(item, i, file_path)
)
for i, item in enumerate(multimodal_items)
]
results = await asyncio.gather(*tasks, return_exceptions=True)
# Filter successful results
multimodal_data_list = []
for result in results:
if isinstance(result, Exception):
self.logger.error(f"Task failed: {result}")
continue
if result is not None:
multimodal_data_list.append(result)
if not multimodal_data_list:
self.logger.warning("No valid multimodal descriptions generated")
return
self.logger.info(
f"Generated descriptions for {len(multimodal_data_list)}/{len(multimodal_items)} multimodal items using correct processors"
)
# Stage 2: Convert to LightRAG chunks format
lightrag_chunks = self._convert_to_lightrag_chunks_type_aware(
multimodal_data_list, file_path, doc_id
)
# Stage 3: Store chunks to LightRAG storage
await self._store_chunks_to_lightrag_storage_type_aware(lightrag_chunks)
# Stage 3.5: Store multimodal main entities to entities_vdb and full_entities
await self._store_multimodal_main_entities(
multimodal_data_list, lightrag_chunks, file_path, doc_id
)
# Track chunk IDs for doc_status update
chunk_ids = list(lightrag_chunks.keys())
# Stage 4: Use LightRAG's batch entity relation extraction
chunk_results = await self._batch_extract_entities_lightrag_style_type_aware(
lightrag_chunks
)
# Stage 5: Add belongs_to relations (multimodal-specific)
enhanced_chunk_results = await self._batch_add_belongs_to_relations_type_aware(
chunk_results, multimodal_data_list
)
# Stage 6: Use LightRAG's batch merge
await self._batch_merge_lightrag_style_type_aware(
enhanced_chunk_results, file_path, doc_id
)
# Stage 7: Update doc_status with integrated chunks_list
await self._update_doc_status_with_chunks_type_aware(doc_id, chunk_ids)
def _convert_to_lightrag_chunks_type_aware(
self, multimodal_data_list: List[Dict[str, Any]], file_path: str, doc_id: str
) -> Dict[str, Any]:
"""Convert multimodal data to LightRAG standard chunks format"""
chunks = {}
for data in multimodal_data_list:
description = data["description"]
entity_info = data["entity_info"]
chunk_order_index = data["chunk_order_index"]
content_type = data["content_type"]
original_item = data["original_item"]
# Apply the appropriate chunk template based on content type
formatted_chunk_content = self._apply_chunk_template(
content_type, original_item, description
)
# Generate chunk_id
chunk_id = compute_mdhash_id(formatted_chunk_content, prefix="chunk-")
# Calculate tokens
tokens = len(self.lightrag.tokenizer.encode(formatted_chunk_content))
# Use full path or basename based on config
file_ref = self._get_file_reference(file_path)
# Build LightRAG standard chunk format
chunks[chunk_id] = {
"content": formatted_chunk_content, # Now uses the templated content
"tokens": tokens,
"full_doc_id": doc_id,
"chunk_order_index": chunk_order_index,
"file_path": file_ref,
"llm_cache_list": [], # LightRAG will populate this field
# Multimodal-specific metadata
"is_multimodal": True,
"modal_entity_name": entity_info["entity_name"],
"original_type": data["content_type"],
"page_idx": data["item_info"].get("page_idx", 0),
}
self.logger.debug(
f"Converted {len(chunks)} multimodal items to multimodal chunks format"
)
return chunks
def _apply_chunk_template(
self, content_type: str, original_item: Dict[str, Any], description: str
) -> str:
"""
Apply the appropriate chunk template based on content type
Args: