Spaces:
Runtime error

celiolr commited on
Commit
78de529
·
verified ·
1 Parent(s): 9eded69

Deploy Docker: scripts\ingest_documents.py

Browse files
Files changed (1) hide show
  1. scripts//ingest_documents.py +174 -0
scripts//ingest_documents.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Script to ingest documents into the vector store, assigning scopes based on subdirectories.
4
+ """
5
+
6
+ import sys
7
+ import argparse
8
+ from pathlib import Path
9
+ import shutil
10
+ import logging
11
+ import os
12
+
13
+ # Add the app directory to the path so we can import app modules
14
+ sys.path.append(str(Path(__file__).parent.parent))
15
+
16
+ from app.services.document_processor import DocumentProcessor
17
+ from app.services.vector_store import VectorStoreManager
18
+ from app.core.config import settings
19
+
20
+ def main():
21
+ """Main ingestion function"""
22
+ # Parse command line arguments
23
+ parser = argparse.ArgumentParser(description="Ingest documents into vector store with scopes")
24
+ parser.add_argument("--directory", "-d",
25
+ default=settings.documents_directory_raw,
26
+ help="Directory containing documents to ingest")
27
+ parser.add_argument("--reset", "-r",
28
+ action="store_true",
29
+ help="Reset vector store before ingestion")
30
+ parser.add_argument("--force", "-y",
31
+ action="store_true",
32
+ help="Force reset without confirmation")
33
+ parser.add_argument("--verbose", "-v",
34
+ action="store_true",
35
+ help="Enable verbose logging")
36
+ args = parser.parse_args()
37
+
38
+ # Configure logging
39
+ log_level = logging.DEBUG if args.verbose else logging.INFO
40
+ logging.basicConfig(
41
+ level=log_level,
42
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
43
+ )
44
+ # Suppress noisy logs from third-party libraries
45
+ logging.getLogger("chromadb.telemetry.product.posthog").setLevel(logging.CRITICAL)
46
+ logger = logging.getLogger(__name__)
47
+
48
+ print("=" * 60)
49
+ print(" Document Ingestion Script (Multi-Scope)")
50
+ print("=" * 60)
51
+
52
+ project_root = Path(__file__).resolve().parent.parent
53
+
54
+ # CRÍTICO: Muda o diretório de trabalho para a raiz do projeto
55
+ # Isso garante que o VectorStoreManager crie o banco em 'project_root/data/chroma_db' e não dentro de 'scripts/'
56
+ os.chdir(project_root)
57
+
58
+ # Handle vector store reset if requested
59
+ if args.reset:
60
+ print("\n⚠️ Resetting vector store...")
61
+ confirm = 'y' if args.force else input("This will delete all documents and clear the DB folder. Continue? (y/N): ")
62
+ if confirm.lower() == 'y':
63
+ # Tenta obter o diretório do banco das configurações ou usa o padrão 'data/chroma_db'
64
+ db_path_setting = getattr(settings, 'persist_directory', 'data/chroma_db')
65
+ db_path = Path(db_path_setting)
66
+ if not db_path.is_absolute():
67
+ db_path = project_root / db_path
68
+
69
+ if db_path.exists():
70
+ try:
71
+ shutil.rmtree(db_path)
72
+ print(f"✅ Diretório do banco removido: {db_path}")
73
+ except Exception as e:
74
+ print(f"❌ Erro ao remover diretório: {e}")
75
+ else:
76
+ print(f"⚠️ Diretório não encontrado: {db_path}")
77
+ else:
78
+ print("❌ Reset cancelled.")
79
+ return
80
+
81
+ # Initialize services
82
+ vector_store = VectorStoreManager()
83
+ processor = DocumentProcessor()
84
+
85
+ # Resolve the documents directory path
86
+ docs_arg = Path(args.directory).expanduser()
87
+ # If path is relative, make it relative to project root
88
+ docs_dir = (project_root / docs_arg if not docs_arg.is_absolute() else docs_arg).resolve(strict=False)
89
+
90
+ if not docs_dir.exists():
91
+ print(f"\n❌ Documents directory not found: {docs_dir}")
92
+ return
93
+
94
+ print(f"\n📂 Processing directory: {docs_dir}")
95
+ print(" (Subdirectories will be used as 'scopes')")
96
+
97
+ # Prepare processed directory early
98
+ processed_dir_setting = Path(settings.documents_directory_processed)
99
+ processed_dir = (project_root / processed_dir_setting if not processed_dir_setting.is_absolute() else processed_dir_setting).resolve(strict=False)
100
+ processed_dir.mkdir(parents=True, exist_ok=True)
101
+ print(f" (Processed files will be moved to: {processed_dir})")
102
+
103
+ # Check for potential duplicates if not resetting
104
+ if not args.reset:
105
+ current_stats = vector_store.get_collection_stats()
106
+ if current_stats.get('total_documents', 0) > 0:
107
+ print("\n⚠️ AVISO: O banco vetorial não está vazio. A ingestão sem --reset pode criar duplicatas e confundir as respostas.")
108
+
109
+ total_chunks_added = 0
110
+ files_processed_count = 0
111
+
112
+ # Iterate over files and process one by one
113
+ for root, dirs, files in os.walk(docs_dir):
114
+ for file in files:
115
+ file_path = Path(root) / file
116
+
117
+ # Skip hidden files
118
+ if file.startswith('.'):
119
+ continue
120
+
121
+ try:
122
+ # Process single file
123
+ chunks = processor.process_file(file_path)
124
+
125
+ if chunks:
126
+ # Calcula o escopo baseado no subdiretório (ex: 'sistemas' em 'data/raw/sistemas/doc.pdf')
127
+ relative_path = file_path.relative_to(docs_dir)
128
+ if len(relative_path.parts) > 1:
129
+ scope = relative_path.parts[0]
130
+ else:
131
+ scope = 'default'
132
+
133
+ # Força a atualização do metadado 'scope' em todos os chunks
134
+ for chunk in chunks:
135
+ chunk.metadata['scope'] = scope
136
+
137
+ logger.info(f"Processing file: {file_path} (Scope: {scope})")
138
+
139
+ # Add to vector store immediately
140
+ vector_store.add_documents(chunks)
141
+ print(f"{len(chunks)} chunks adicionado")
142
+
143
+ total_chunks_added += len(chunks)
144
+ files_processed_count += 1
145
+
146
+ # Move file to processed directory
147
+ relative_path = file_path.relative_to(docs_dir)
148
+ dest_path = processed_dir / relative_path
149
+ dest_path.parent.mkdir(parents=True, exist_ok=True)
150
+
151
+ if dest_path.exists():
152
+ dest_path.unlink()
153
+ shutil.move(str(file_path), str(dest_path))
154
+ else:
155
+ logger.warning(f"No chunks generated for file: {file_path}")
156
+
157
+ except Exception as e:
158
+ logger.error(f"Error processing file {file_path}: {e}")
159
+
160
+ if files_processed_count == 0:
161
+ print(f"\n⚠️ No documents found or processed in {docs_dir}")
162
+ else:
163
+ print(f"\n✅ Ingestion complete! Added {total_chunks_added} chunks from {files_processed_count} files.")
164
+
165
+ # Display statistics
166
+ stats = vector_store.get_collection_stats()
167
+ print(f"\n📊 Collection Statistics:")
168
+ print(f" Total chunks: {stats.get('total_documents', 0)}")
169
+ print(f" Collection name: {stats.get('collection_name', 'N/A')}")
170
+
171
+ print("\n🎉 Done!")
172
+
173
+ if __name__ == "__main__":
174
+ main()