diff --git a/common/requirements.txt b/common/requirements.txt index 562c2f6..d5a2d5b 100644 --- a/common/requirements.txt +++ b/common/requirements.txt @@ -110,7 +110,8 @@ packaging==24.2 pandas==2.2.3 #pathtools==0.1.2 pillow==11.2.1 -PyMuPDF==1.26.4 +PyMuPDF==1.26.6 +pymupdf4llm==0.2.0 platformdirs==4.3.8 pluggy==1.6.0 prometheus_client==0.22.1 diff --git a/common/utils/image_data_extractor.py b/common/utils/image_data_extractor.py index bde9c97..bfd07cd 100644 --- a/common/utils/image_data_extractor.py +++ b/common/utils/image_data_extractor.py @@ -1,165 +1,62 @@ import base64 import io import logging -import os -import uuid -import hashlib -from pathlib import Path from langchain_core.messages import HumanMessage, SystemMessage from common.config import get_multimodal_service logger = logging.getLogger(__name__) - - -def describe_image_with_llm(image_input): +def describe_image_with_llm(file_path): """ - Send image (pixmap or PIL image) to LLM vision model and return description. - Uses multimodal_service from config if available, otherwise falls back to completion_service. - Currently supports: OpenAI, Azure OpenAI, Google GenAI, and Google VertexAI + Read image file and convert to base64 to send to LLM. """ try: + from PIL import Image as PILImage + client = get_multimodal_service() if not client: return "[Image: Failed to create multimodal LLM client]" - + + # Read image and convert to base64 + pil_image = PILImage.open(file_path) buffer = io.BytesIO() - # Convert to RGB if needed for better compatibility - if image_input.mode != 'RGB': - image_input = image_input.convert('RGB') - image_input.save(buffer, format="JPEG", quality=95) - b64_img = base64.b64encode(buffer.getvalue()).decode("utf-8") + if pil_image.mode != 'RGB': + pil_image = pil_image.convert('RGB') + pil_image.save(buffer, format="JPEG", quality=95) + image_base64 = base64.b64encode(buffer.getvalue()).decode('utf-8') - # Build messages (system + human) messages = [ - SystemMessage( - content="You are a helpful assistant that describes images concisely for document analysis." - ), - HumanMessage( - content=[ - { - "type": "text", - "text": ( - "Please describe what you see in this image and " - "if the image has scanned text then extract all the text. " - "if the image has any logo, icon, or branding element, try to describe it with text. " - "Focus on any text, diagrams, charts, or other visual elements." - "If the image is purely a logo, icon, or branding element, start your response with 'LOGO:' or 'ICON:'." - ), - }, - { - "type": "image_url", - "image_url": {"url": f"data:image/jpeg;base64,{b64_img}"}, - }, - ] - ), + SystemMessage( + content="You are a helpful assistant that describes images concisely for document analysis." + ), + HumanMessage( + content=[ + { + "type": "text", + "text": ( + "Please describe what you see in this image and " + "if the image has scanned text then extract all the text. " + "If the image has any graph, chart, table, or other diagram, describe it. " + ), + }, + { + "type": "image_url", + "image_url": {"url": f"data:image/jpeg;base64,{image_base64}"}, + }, + ], + ), ] - # Get response from LangChain LLM client - # Access the underlying LangChain client langchain_client = client.llm response = langchain_client.invoke(messages) - return response.content if hasattr(response, 'content') else str(response) + return response.content if hasattr(response, "content") else str(response) except Exception as e: logger.error(f"Failed to describe image with LLM: {str(e)}") return "[Image: Error processing image description]" -def save_image_and_get_markdown(image_input, context_info="", graphname=None): - """ - Save image locally to static/images/ folder and return markdown reference with description. - - LEGACY/OLD APPROACH: Used for backward compatibility with JSONL-based loading. - Images are saved as files and served via /ui/images/ endpoint with img:// protocol. - - For NEW direct loading approach, images are stored in Image vertex as base64 - and served via /ui/image_vertex/ endpoint with image:// protocol. - - Args: - image_input: PIL Image object - context_info: Optional context (e.g., "page 3 of invoice.pdf") - graphname: Graph name to organize images by graph (optional) - - Returns: - dict with: - - 'markdown': Markdown string with img:// reference - - 'image_id': Unique identifier for the saved image - - 'image_path': Path where image was saved to static/images/ - """ - try: - # FIRST: Get description from LLM to check if it's a logo - description = describe_image_with_llm(image_input) - - # Check if the image is a logo, icon, or decorative element BEFORE saving - # These should be filtered out as they're not content-relevant - description_lower = description.lower() - logo_indicators = ['logo', 'icon', 'branding', 'watermark', 'trademark', 'company logo', 'brand logo'] - - if any(indicator in description_lower for indicator in logo_indicators): - logger.info(f"Detected logo/icon in image, skipping: {description[:100]}") - return None - - # If not a logo, proceed with saving the image - # Generate unique image ID using hash of image content - buffer = io.BytesIO() - if image_input.mode != 'RGB': - image_input = image_input.convert('RGB') - image_input.save(buffer, format="JPEG", quality=95) - image_bytes = buffer.getvalue() - - # Create hash-based ID (deterministic for same image) - image_hash = hashlib.sha256(image_bytes).hexdigest()[:16] - image_id = f"{image_hash}.jpg" - - # Save image to local storage directory organized by graphname - project_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) - - # If graphname is provided, organize images by graph - if graphname: - images_dir = os.path.join(project_root, "static", "images", graphname) - # Include graphname in the image reference for URL construction - image_reference = f"{graphname}/{image_id}" - else: - images_dir = os.path.join(project_root, "static", "images") - image_reference = image_id - - os.makedirs(images_dir, exist_ok=True) - - image_path = os.path.join(images_dir, image_id) - - # Save image file (skip if already exists with same hash) - if not os.path.exists(image_path): - with open(image_path, 'wb') as f: - f.write(image_bytes) - logger.info(f"Saved content image to: {image_path}") - else: - logger.debug(f"Image already exists: {image_path}") - - # Generate markdown with custom img:// protocol (will be replaced later) - # Format: ![description](img://graphname/image_id) or ![description](img://image_id) - markdown = f"![{description}](img://{image_reference})" - - logger.info(f"Created image reference: {image_reference} with description") - - return { - 'markdown': markdown, - 'image_id': image_reference, - 'image_path': image_path, - 'description': description - } - - except Exception as e: - logger.error(f"Failed to save image and generate markdown: {str(e)}") - # Fallback to text description only - fallback_desc = f"[Image: {context_info} - processing failed]" - return { - 'markdown': fallback_desc, - 'image_id': None, - 'image_path': None, - 'description': fallback_desc - } diff --git a/common/utils/text_extractors.py b/common/utils/text_extractors.py index da3e22d..a0766ac 100644 --- a/common/utils/text_extractors.py +++ b/common/utils/text_extractors.py @@ -8,6 +8,8 @@ import uuid import base64 import io +import re +import threading from pathlib import Path import shutil import asyncio @@ -15,6 +17,59 @@ logger = logging.getLogger(__name__) +# Global lock for pymupdf4llm calls (not thread-safe) +_pymupdf4llm_lock = threading.Lock() + + +# regex for markdown images: ![alt](path) +_md_pattern = re.compile(r'!\[([^\]]*)\]\(([^)\s]+)\)') + +def extract_images(md_text): + """ + Returns list of {"path": path, "image_id": image_id} + image_id = basename without extension + """ + images = [] + for m in _md_pattern.finditer(md_text): + path = m.group(2) + basename = os.path.basename(path) + image_id = os.path.splitext(basename)[0] + images.append({"path": path, "image_id": image_id}) + return images + + +def insert_description_by_id(md_text, image_id, description): + """ + Replace the description for an image whose basename == image_id. + """ + def repl(m): + old_path = m.group(2) + candidate_id = os.path.splitext(os.path.basename(old_path))[0] + + if candidate_id == image_id: + return f'![{description}]({old_path})' + + return m.group(0) + + return _md_pattern.sub(repl, md_text) + + +def replace_path_with_tg_protocol(md_text, image_id, tg_reference): + """ + Replace the file path for an image whose basename == image_id with tg:// protocol reference. + tg_reference should be like 'Graphs_image_1' + """ + def repl(m): + old_path = m.group(2) + candidate_id = os.path.splitext(os.path.basename(old_path))[0] + + if candidate_id == image_id: + alt_text = m.group(1) + return f'![{alt_text}](tg://{tg_reference})' + + return m.group(0) + + return _md_pattern.sub(repl, md_text) class TextExtractor: """Class for handling text extraction from various file formats and cleanup.""" @@ -38,10 +93,11 @@ def __init__(self): '.jpg': 'image/jpeg' } - async def _process_file_async(self, file_path, folder_path_obj, graphname): + async def _process_file_async(self, file_path, folder_path_obj, graphname, temp_folder, jsonl_file, jsonl_lock): """ Async helper to process a single file. Runs in thread pool to avoid blocking on I/O operations. + Appends documents immediately to JSONL file. """ try: loop = asyncio.get_event_loop() @@ -53,10 +109,21 @@ async def _process_file_async(self, file_path, folder_path_obj, graphname): graphname ) + # Append each document to JSONL file immediately + if doc_entries: + # Use lock to ensure thread-safe writing to JSONL file + async with jsonl_lock: + await loop.run_in_executor( + None, + self._append_to_jsonl, + jsonl_file, + doc_entries + ) + + # Return metadata only, documents already saved to JSONL return { 'success': True, 'file_path': str(file_path), - 'documents': doc_entries, 'num_documents': len(doc_entries) } @@ -67,11 +134,21 @@ async def _process_file_async(self, file_path, folder_path_obj, graphname): except Exception as e: logger.warning(f"Failed to process file {file_path}: {e}") return {'success': False, 'file_path': str(file_path), 'error': str(e)} + + def _append_to_jsonl(self, jsonl_file, doc_entries): + """ + Append document entries to JSONL file. + Each document is written as a separate line. + """ + with open(jsonl_file, 'a', encoding='utf-8') as f: + for doc_data in doc_entries: + json_line = json.dumps(doc_data, ensure_ascii=False) + f.write(json_line + '\n') - async def _process_folder_async(self, folder_path, graphname=None, max_concurrent=10): + async def _process_folder_async(self, folder_path, graphname, temp_folder, max_concurrent=10): """ Async version of process_folder for parallel file processing. - This prevents conflicts when multiple users process folders simultaneously. + Saves all documents immediately to a single JSONL file as they are processed. """ logger.info(f"Processing local folder ASYNC: {folder_path} for graph: {graphname} (max_concurrent={max_concurrent})") @@ -83,6 +160,13 @@ async def _process_folder_async(self, folder_path, graphname=None, max_concurren if not folder_path_obj.is_dir(): raise Exception(f"Path is not a directory: {folder_path}") + # Create temp folder and JSONL file + os.makedirs(temp_folder, exist_ok=True) + jsonl_file = os.path.join(temp_folder, "processed_documents.jsonl") + # Create async lock for thread-safe JSONL writing + jsonl_lock = asyncio.Lock() + logger.info(f"Saving processed documents to: {jsonl_file}") + def safe_walk(path): try: for item in path.iterdir(): @@ -110,13 +194,13 @@ def safe_walk(path): async def process_with_semaphore(file_path): async with semaphore: - return await self._process_file_async(file_path, folder_path_obj, graphname) + return await self._process_file_async(file_path, folder_path_obj, graphname, temp_folder, jsonl_file, jsonl_lock) tasks = [process_with_semaphore(fp) for fp in files_to_process] results = await asyncio.gather(*tasks, return_exceptions=True) - all_documents = [] processed_files_info = [] + total_docs = 0 for result in results: if isinstance(result, Exception): @@ -124,10 +208,12 @@ async def process_with_semaphore(file_path): continue if result.get('success'): - all_documents.extend(result.get('documents', [])) + num_docs = result.get('num_documents', 0) + total_docs += num_docs + processed_files_info.append({ 'file_path': result['file_path'], - 'num_documents': result.get('num_documents', len(result.get('documents', []))), + 'num_documents': num_docs, 'status': 'success' }) else: @@ -137,23 +223,118 @@ async def process_with_semaphore(file_path): 'error': result.get('error', 'Unknown error') }) - logger.info(f"Processed {len(processed_files_info)} files, extracted {len(all_documents)} total documents") + logger.info(f"Processed {len(processed_files_info)} files, extracted {total_docs} total documents") return { 'statusCode': 200, - 'message': f'Processed {len(processed_files_info)} files, {len(all_documents)} documents', - 'documents': all_documents, + 'message': f'Processed {len(processed_files_info)} files, {total_docs} documents', 'files': processed_files_info, - 'num_documents': len(all_documents) + 'num_documents': total_docs, + 'temp_folder': temp_folder, + 'jsonl_file': jsonl_file } - def process_folder(self, folder_path, graphname=None): + def process_folder(self, folder_path, graphname, temp_folder): """ Process local folder with multiple file formats and extract text content. Uses async processing internally for parallel file handling. + Saves all documents to JSONL file immediately as they are processed. + + Args: + folder_path: Path to the folder containing files to process + graphname: Name of the graph (for context) + temp_folder: Path to save processed documents as JSONL file """ logger.info(f"Processing local folder: {folder_path} for graph: {graphname}") - return asyncio.run(self._process_folder_async(folder_path, graphname)) + return asyncio.run(self._process_folder_async(folder_path, graphname, temp_folder)) + + def delete_file_from_jsonl(self, temp_folder, filename): + """ + Delete all documents related to a specific file from the JSONL file. + + Args: + temp_folder: Path to the temp folder containing processed_documents.jsonl + filename: Original filename (e.g., "report.pdf", "stock_gs200.jpg") + + Returns: + dict with status and number of documents removed + """ + jsonl_file = os.path.join(temp_folder, "processed_documents.jsonl") + + if not os.path.exists(jsonl_file): + logger.warning(f"JSONL file not found: {jsonl_file}") + return {'success': False, 'error': 'JSONL file not found'} + + # Get base name without extension to match doc_id + base_name = Path(filename).stem + logger.info(f"Deleting documents for file: {filename} (base_name: '{base_name}')") + + # Read all lines and filter out ones matching this file + remaining_lines = [] + removed_count = 0 + removed_doc_ids = [] + + try: + with open(jsonl_file, 'r', encoding='utf-8') as f: + for line_num, line in enumerate(f, 1): + line = line.strip() + if not line: + continue + + try: + doc_data = json.loads(line) + doc_id = doc_data.get('doc_id', '') + + # Check if doc_id matches the base_name or starts with base_name_ + # Handles: "stock_gs200" == "stock_gs200" or "stock_gs200_image_1".startswith("stock_gs200_") + if doc_id == base_name or doc_id.startswith(f"{base_name}_"): + removed_count += 1 + removed_doc_ids.append(doc_id) + logger.info(f"Removing document: {doc_id}") + else: + remaining_lines.append(line) + except json.JSONDecodeError as e: + logger.warning(f"Skipping invalid JSON at line {line_num}: {e}") + # Keep invalid lines in case they're important + remaining_lines.append(line) + + if removed_count == 0: + logger.warning(f"No documents found matching base_name: '{base_name}'") + return { + 'success': False, + 'error': f'No documents found for {filename}', + 'removed_count': 0 + } + + # If no lines remain, delete the entire temp folder + if not remaining_lines: + logger.info(f"No documents remaining, deleting temp folder: {temp_folder}") + import shutil + shutil.rmtree(temp_folder, ignore_errors=True) + return { + 'success': True, + 'removed_count': removed_count, + 'removed_doc_ids': removed_doc_ids, + 'temp_folder_deleted': True + } + + # Write remaining lines back to JSONL + with open(jsonl_file, 'w', encoding='utf-8') as f: + for line in remaining_lines: + f.write(line + '\n') + + logger.info(f"Removed {removed_count} documents ({', '.join(removed_doc_ids)}), {len(remaining_lines)} remaining") + return { + 'success': True, + 'removed_count': removed_count, + 'removed_doc_ids': removed_doc_ids, + 'remaining_count': len(remaining_lines), + 'temp_folder_deleted': False + } + + except Exception as e: + logger.error(f"Error deleting from JSONL: {e}") + return {'success': False, 'error': str(e)} def extract_text_from_file_with_images_as_docs(file_path, graphname=None): @@ -183,137 +364,166 @@ def extract_text_from_file_with_images_as_docs(file_path, graphname=None): def _extract_pdf_with_images_as_docs(file_path, base_doc_id, graphname=None): """ - Extract PDF as ONE markdown document with inline image references. + Extract PDF as ONE markdown document with inline image references using pymupdf4llm. + Uses unique temporary folder per PDF to allow parallel processing. + After processing, delete the extracted image folder. """ + # Use unique folder per PDF to allow parallel processing without conflicts + unique_folder_id = uuid.uuid4().hex[:12] + image_output_folder = Path(f"tg_temp_{unique_folder_id}") + try: - import fitz # PyMuPDF + import pymupdf4llm from PIL import Image as PILImage + from common.utils.image_data_extractor import describe_image_with_llm - doc = fitz.open(file_path) - markdown_parts = [] - image_entries = [] - image_counter = 0 + # Ensure clean slate - remove folder if it exists from failed previous run + if image_output_folder.exists(): + shutil.rmtree(image_output_folder, ignore_errors=True) - for page_num, page in enumerate(doc, start=1): - if page_num > 1: - markdown_parts.append("\n\n") - markdown_parts.append(f"--- Page {page_num} ---\n") #Avoid to be splitted as a single chunk + # Convert PDF to markdown with extracted image files + # Use lock because pymupdf4llm's table extraction is not thread-safe + # See: https://github.com/pymupdf/PyMuPDF/issues/3241 + with _pymupdf4llm_lock: + try: + markdown_content = pymupdf4llm.to_markdown( + file_path, + write_images=True, + image_path=str(image_output_folder), # unique folder per PDF + margins=0, + image_size_limit=0.08, + ) + except Exception: + # Retry with table_strategy="lines" if first attempt fails + try: + markdown_content = pymupdf4llm.to_markdown( + file_path, + write_images=True, + image_path=str(image_output_folder), # unique folder per PDF + margins=0, + image_size_limit=0.08, + table_strategy="lines", + ) + except Exception as e: + logger.error(f"pymupdf4llm failed for {file_path}: {e}") + # Cleanup folder if it was created + if image_output_folder.exists(): + shutil.rmtree(image_output_folder, ignore_errors=True) + return [{ + "doc_id": base_doc_id, + "doc_type": "markdown", + "content": f"[PDF extraction failed: {e}]", + "position": 0 + }] + + if not markdown_content or not markdown_content.strip(): + logger.warning(f"No content extracted from PDF: {file_path}") + + # Extract image references from markdown + image_refs = extract_images(markdown_content) + + if not image_refs: + # cleanup folder anyway + if image_output_folder.exists(): + shutil.rmtree(image_output_folder, ignore_errors=True) - blocks = page.get_text("blocks", sort=True) - text_blocks_with_pos = [] + return [{ + "doc_id": base_doc_id, + "doc_type": "markdown", + "content": markdown_content, + "position": 0 + }] - for block in blocks: - block_type = block[6] if len(block) > 6 else 0 - if block_type == 0: - text = block[4].strip() - if text: - y_pos = block[1] - text_blocks_with_pos.append({'type': 'text', 'content': text, 'y_pos': y_pos}) + image_entries = [] + image_counter = 0 - image_list = page.get_images(full=True) - images_with_pos = [] + for img_ref in image_refs: + try: + img_path = Path(img_ref["path"]) # convert to Path + image_id = img_ref["image_id"] + + # Image description + description = describe_image_with_llm(str(img_path)) + + markdown_content = insert_description_by_id( + markdown_content, + image_id, + description + ) + + # Convert image to base64 + pil_image = PILImage.open(img_path) + buffer = io.BytesIO() + + if pil_image.mode != "RGB": + pil_image = pil_image.convert("RGB") + + pil_image.save(buffer, format="JPEG", quality=95) + image_base64 = base64.b64encode(buffer.getvalue()).decode("utf-8") + + image_counter += 1 + image_doc_id = f"{base_doc_id}_image_{image_counter}" + + # Replace file path with tg:// protocol reference in markdown + markdown_content = replace_path_with_tg_protocol( + markdown_content, + image_id, + image_doc_id + ) + + image_entries.append({ + "doc_id": image_doc_id, + "doc_type": "image", + "image_description": description, + "image_data": image_base64, + "image_format": "jpg", + "parent_doc": base_doc_id, + "page_number": 0, + "width": pil_image.width, + "height": pil_image.height, + "position": image_counter + }) - if image_list: - for img_index, img_info in enumerate(image_list): - try: - xref = img_info[0] - base_image = doc.extract_image(xref) - image_bytes = base_image["image"] - image_ext = base_image["ext"] - - img_rects = page.get_image_rects(xref) - y_pos = img_rects[0].y0 if img_rects else 999999 - - pil_image = PILImage.open(io.BytesIO(image_bytes)) - if pil_image.width < 100 or pil_image.height < 100: - continue - - from common.utils.image_data_extractor import describe_image_with_llm - description = describe_image_with_llm(pil_image) - description_lower = description.lower() - logo_indicators = [ - 'logo:', 'icon:', 'logo', 'icon', 'branding', - 'watermark', 'trademark', 'stylized letter', - 'stylized text', 'word "', "word '" - ] - if any(indicator in description_lower for indicator in logo_indicators): - continue - - buffer = io.BytesIO() - if pil_image.mode != 'RGB': - pil_image = pil_image.convert('RGB') - pil_image.save(buffer, format="JPEG", quality=95) - image_base64 = base64.b64encode(buffer.getvalue()).decode('utf-8') - - image_counter += 1 - image_doc_id = f"{base_doc_id}_image_{image_counter}" - - images_with_pos.append({ - 'type': 'image', - 'image_doc_id': image_doc_id, - 'description': description, - 'y_pos': y_pos, - 'image_data': image_base64, - 'image_format': image_ext, - 'width': pil_image.width, - 'height': pil_image.height - }) - except Exception as img_error: - logger.warning(f"Failed to extract image on page {page_num}: {img_error}") - - all_elements = text_blocks_with_pos + images_with_pos - all_elements.sort(key=lambda x: x['y_pos']) - - for element in all_elements: - if element['type'] == 'text': - markdown_parts.append(element['content']) - markdown_parts.append("\n\n") - else: - # Add image description as text, then markdown image reference - # Use short alt text in markdown, full description as regular text - markdown_parts.append(f"![{element['description']}](tg://{element['image_doc_id']})\n\n") - - image_entries.append({ - "doc_id": element['image_doc_id'], - "doc_type": "image", - "image_description": element['description'], - "image_data": element['image_data'], - "image_format": element['image_format'], - "parent_doc": base_doc_id, - "page_number": page_num, - "width": element['width'], - "height": element['height'], - "position": int(element['image_doc_id'].split('_')[-1]) - }) - - doc.close() - - markdown_content = "".join(markdown_parts) if markdown_parts else "" #No content extracted from PDF - if not markdown_content: - return [] + except Exception as img_error: + logger.warning(f"Failed to process image {img_ref.get('path')}: {img_error}") + # FINAL CLEANUP — delete folder after processing everything + if image_output_folder.exists() and image_output_folder.is_dir(): + try: + shutil.rmtree(image_output_folder) + logger.debug(f"Deleted image folder: {image_output_folder}") + except Exception as delete_err: + logger.warning(f"Failed to delete folder {image_output_folder}: {delete_err}") + + # Build final result result = [{ "doc_id": base_doc_id, - "doc_type": "", + "doc_type": "markdown", "content": markdown_content, "position": 0 }] result.extend(image_entries) + return result - except ImportError: - logger.error("PyMuPDF not available") + except ImportError as import_err: + logger.error(f"Required library missing: {import_err}") + # Cleanup on import error + if image_output_folder.exists(): + shutil.rmtree(image_output_folder, ignore_errors=True) return [{ "doc_id": base_doc_id, - "doc_type": "", - "content": "[PDF extraction requires PyMuPDF]", + "doc_type": "markdown", + "content": "[PDF extraction requires pymupdf4llm and PyMuPDF]", "position": 0 }] except Exception as e: logger.error(f"Error extracting PDF: {e}") + # Cleanup on any other error + if image_output_folder.exists(): + shutil.rmtree(image_output_folder, ignore_errors=True) raise - def _extract_standalone_image_as_doc(file_path, base_doc_id, graphname=None): """ Extract standalone image file as ONE markdown document with inline image reference. @@ -324,25 +534,15 @@ def _extract_standalone_image_as_doc(file_path, base_doc_id, graphname=None): pil_image = PILImage.open(file_path) if pil_image.width < 100 or pil_image.height < 100: - return [{ - "doc_id": base_doc_id, - "doc_type": "", - "content": f"[Skipped small image: {file_path.name}]", - "position": 0 - }] + pass - description = describe_image_with_llm(pil_image) + description = describe_image_with_llm(str(Path(file_path).absolute())) description_lower = description.lower() logo_indicators = ['logo:', 'icon:', 'logo', 'icon', 'branding', 'watermark', 'trademark', 'stylized letter', 'stylized text', 'word "', "word '"] if any(indicator in description_lower for indicator in logo_indicators): - return [{ - "doc_id": base_doc_id, - "doc_type": "", - "content": f"[Skipped logo/icon: {file_path.name}]", - "position": 0 - }] + return [] buffer = io.BytesIO() if pil_image.mode != 'RGB': @@ -353,7 +553,6 @@ def _extract_standalone_image_as_doc(file_path, base_doc_id, graphname=None): image_id = f"{base_doc_id}_image_1" # Put description as text, then markdown image reference with short alt text content = f"![{description}](tg://{image_id})" - return [ { "doc_id": base_doc_id, @@ -379,7 +578,7 @@ def _extract_standalone_image_as_doc(file_path, base_doc_id, graphname=None): logger.error(f"Error extracting image: {e}") return [{ "doc_id": base_doc_id, - "doc_type": "", + "doc_type": "markdown", "content": f"[Image extraction failed: {str(e)}]", "position": 0 }] @@ -441,12 +640,10 @@ def get_doc_type_from_extension(extension): if extension in ['.html', '.htm']: return 'html' - elif extension in ['.md']: - return 'markdown' elif extension in ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.webp']: return 'image' else: - return '' + return 'markdown' def get_supported_extensions(): @@ -457,4 +654,4 @@ def get_supported_extensions(): def is_supported_file(file_path): """Check if a file is supported for text extraction.""" extension = Path(file_path).suffix.lower() - return extension in get_supported_extensions() + return extension in get_supported_extensions() \ No newline at end of file diff --git a/configs/nginx.conf b/configs/nginx.conf deleted file mode 120000 index cffce04..0000000 --- a/configs/nginx.conf +++ /dev/null @@ -1 +0,0 @@ -../docs/tutorials/configs/nginx.conf \ No newline at end of file diff --git a/configs/nginx.conf b/configs/nginx.conf new file mode 100644 index 0000000..cffce04 --- /dev/null +++ b/configs/nginx.conf @@ -0,0 +1 @@ +../docs/tutorials/configs/nginx.conf \ No newline at end of file diff --git a/configs/server_config.json b/configs/server_config.json deleted file mode 120000 index 04e4259..0000000 --- a/configs/server_config.json +++ /dev/null @@ -1 +0,0 @@ -../docs/tutorials/configs/server_config.json \ No newline at end of file diff --git a/configs/server_config.json b/configs/server_config.json new file mode 100644 index 0000000..04e4259 --- /dev/null +++ b/configs/server_config.json @@ -0,0 +1 @@ +../docs/tutorials/configs/server_config.json \ No newline at end of file diff --git a/ecc/app/common b/ecc/app/common deleted file mode 120000 index dc879ab..0000000 --- a/ecc/app/common +++ /dev/null @@ -1 +0,0 @@ -../../common \ No newline at end of file diff --git a/ecc/app/common b/ecc/app/common new file mode 100644 index 0000000..dc879ab --- /dev/null +++ b/ecc/app/common @@ -0,0 +1 @@ +../../common \ No newline at end of file diff --git a/ecc/app/configs b/ecc/app/configs deleted file mode 120000 index 5992d10..0000000 --- a/ecc/app/configs +++ /dev/null @@ -1 +0,0 @@ -../../configs \ No newline at end of file diff --git a/ecc/app/configs b/ecc/app/configs new file mode 100644 index 0000000..5992d10 --- /dev/null +++ b/ecc/app/configs @@ -0,0 +1 @@ +../../configs \ No newline at end of file diff --git a/graphrag-ui/src/pages/Setup.tsx b/graphrag-ui/src/pages/Setup.tsx index b7d357d..e6f6275 100644 --- a/graphrag-ui/src/pages/Setup.tsx +++ b/graphrag-ui/src/pages/Setup.tsx @@ -2,7 +2,7 @@ import React, { useState, useEffect } from "react"; import { useNavigate } from "react-router-dom"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; -import { Database, Upload, RefreshCw, Loader2, Trash2, FolderUp, Cloud, ArrowLeft, CloudDownload, CloudLightning } from "lucide-react"; +import {Database,Upload,RefreshCw,Loader2,Trash2,FolderUp,Cloud,ArrowLeft,CloudDownload,CloudCog,CloudLightning} from "lucide-react"; import { Dialog, DialogContent, @@ -40,7 +40,7 @@ const Setup = () => { const navigate = useNavigate(); const [confirm, confirmDialog, isConfirmDialogOpen] = useConfirm(); const [availableGraphs, setAvailableGraphs] = useState([]); - + const [initializeGraphOpen, setInitializeGraphOpen] = useState(false); const [graphName, setGraphName] = useState(""); const [isInitializing, setIsInitializing] = useState(false); @@ -56,7 +56,13 @@ const Setup = () => { const [uploadMessage, setUploadMessage] = useState(""); const [isIngesting, setIsIngesting] = useState(false); const [ingestMessage, setIngestMessage] = useState(""); - const [activeTab, setActiveTab] = useState("upload"); + + // Ingestion temp files state + const [tempSessionId, setTempSessionId] = useState(null); + const [tempFiles, setTempFiles] = useState([]); + const [showTempFiles, setShowTempFiles] = useState(false); + const [ingestJobData, setIngestJobData] = useState(null); + const [directIngestion, setDirectIngestion] = useState(false); // Refresh state const [refreshOpen, setRefreshOpen] = useState(false); @@ -65,14 +71,15 @@ const Setup = () => { const [refreshGraphName, setRefreshGraphName] = useState(""); const [isRebuildRunning, setIsRebuildRunning] = useState(false); const [isCheckingStatus, setIsCheckingStatus] = useState(false); - - // S3 state + + // S3 / Bedrock state + const [fileFormat, setFileFormat] = useState<"json" | "multi">("multi"); // default to multi (documents) const [awsAccessKey, setAwsAccessKey] = useState(""); const [awsSecretKey, setAwsSecretKey] = useState(""); + const [dataPath, setDataPath] = useState(""); const [inputBucket, setInputBucket] = useState(""); const [outputBucket, setOutputBucket] = useState(""); const [regionName, setRegionName] = useState(""); - const [skipBDAProcessing, setSkipBDAProcessing] = useState(false); // Cloud Download state const [cloudProvider, setCloudProvider] = useState<"s3" | "gcs" | "azure">("s3"); @@ -93,6 +100,13 @@ const Setup = () => { const [isDownloading, setIsDownloading] = useState(false); const [downloadMessage, setDownloadMessage] = useState(""); + // Active tab state + const [activeTab, setActiveTab] = useState("upload"); + + // ------------------------- + // Networking helpers + // ------------------------- + // Fetch uploaded files const fetchUploadedFiles = async () => { if (!ingestGraphName) return; @@ -109,7 +123,9 @@ const Setup = () => { } }; - // Upload files + // ------------------------- + // Upload handlers + // ------------------------- const handleUploadFiles = async () => { if (!selectedFiles || selectedFiles.length === 0) { setUploadMessage("Please select files to upload"); @@ -122,14 +138,14 @@ const Setup = () => { } const filesArray = Array.from(selectedFiles); - + // Check if any single file exceeds the server limit const oversizedFiles = filesArray.filter((file) => file.size > MAX_UPLOAD_SIZE_BYTES); if (oversizedFiles.length > 0) { const names = oversizedFiles.map((file) => `${file.name} (${formatBytes(file.size)})`).join(", "); setUploadMessage( `❌ ${names} ${oversizedFiles.length === 1 ? "exceeds" : "exceed"} the ${MAX_UPLOAD_SIZE_MB} MB limit per file. ` + - `Please split or compress ${oversizedFiles.length === 1 ? "this file" : "these files"}.` + `Please split or compress ${oversizedFiles.length === 1 ? "this file" : "these files"}.` ); return; } @@ -159,15 +175,23 @@ const Setup = () => { const data = await response.json(); if (data.status === "success") { - setUploadMessage(`✅ ${data.message}`); + setUploadMessage("✅ Successfully uploaded the files. Wait for file processing"); setSelectedFiles(null); await fetchUploadedFiles(); + setIsUploading(false); + + // Step 2: Call create_ingest to process uploaded files in background + console.log("Calling handleCreateIngestAfterUpload from main upload..."); + handleCreateIngestAfterUpload("uploaded").catch((err) => { + console.error("Error in background processing:", err); + }); } else { setUploadMessage(`⚠️ ${data.message}`); + setIsUploading(false); } } catch (error: any) { + console.error("Upload error:", error); setUploadMessage(`❌ Error: ${error.message}`); - } finally { setIsUploading(false); } }; @@ -187,9 +211,9 @@ const Setup = () => { for (let i = 0; i < filesArray.length; i++) { const file = filesArray[i]; const fileNumber = i + 1; - + setUploadMessage(`Uploading file ${fileNumber}/${totalFiles}: ${file.name} (${formatBytes(file.size)})...`); - + const formData = new FormData(); formData.append("files", file); @@ -219,42 +243,63 @@ const Setup = () => { // Show final result if (failedCount === 0) { - setUploadMessage(`✅ Successfully uploaded all ${uploadedCount} files (uploaded individually).`); + setUploadMessage(`✅ Successfully uploaded all ${uploadedCount} files. Processing...`); } else { - setUploadMessage(`⚠️ Uploaded ${uploadedCount} files successfully, ${failedCount} failed.`); + setUploadMessage(`⚠️ Uploaded ${uploadedCount} files successfully, ${failedCount} failed. Processing...`); } - + setSelectedFiles(null); await fetchUploadedFiles(); + + // Step 2: Call create_ingest to process uploaded files + console.log("Calling handleCreateIngestAfterUpload..."); + await handleCreateIngestAfterUpload("uploaded"); + console.log("handleCreateIngestAfterUpload completed"); } catch (error: any) { + console.error("Upload error:", error); setUploadMessage(`❌ Batch upload error: ${error.message}`); } finally { setIsUploading(false); } }; - // Delete a specific file + // ------------------------- + // Delete uploaded / downloaded file handlers + // (these already included session_id logic) + // ------------------------- const handleDeleteFile = async (filename: string) => { if (!ingestGraphName) return; + console.log("Deleting file:", filename); + console.log("tempSessionId:", tempSessionId); + try { const creds = localStorage.getItem("creds"); - const response = await fetch( - `/ui/${ingestGraphName}/uploads?filename=${encodeURIComponent(filename)}`, - { - method: "DELETE", - headers: { Authorization: `Basic ${creds}` }, - } - ); + + // Delete original file (backend will also delete processed content from JSONL if session_id is provided) + const url = tempSessionId + ? `/ui/${ingestGraphName}/uploads?filename=${encodeURIComponent(filename)}&session_id=${tempSessionId}` + : `/ui/${ingestGraphName}/uploads?filename=${encodeURIComponent(filename)}`; + + const response = await fetch(url, { + method: "DELETE", + headers: { Authorization: `Basic ${creds}` }, + }); const data = await response.json(); + setUploadMessage(`✅ ${data.message}`); await fetchUploadedFiles(); + + // Refresh temp files list if session exists + if (tempSessionId) { + await fetchTempFiles(tempSessionId); + } } catch (error: any) { + console.error("Delete error:", error); setUploadMessage(`❌ Error: ${error.message}`); } }; - // Delete all files const handleDeleteAllFiles = async () => { if (!ingestGraphName) return; @@ -268,6 +313,12 @@ const Setup = () => { headers: { Authorization: `Basic ${creds}` }, }); const data = await response.json(); + + // Also clear temp session + if (tempSessionId) { + await handleDeleteAllTempFiles(); + } + setUploadMessage(`✅ ${data.message}`); await fetchUploadedFiles(); } catch (error: any) { @@ -275,7 +326,9 @@ const Setup = () => { } }; - // Fetch downloaded files from cloud + // ------------------------- + // Cloud download handlers + // ------------------------- const fetchDownloadedFiles = async () => { if (!ingestGraphName) return; @@ -291,7 +344,6 @@ const Setup = () => { } }; - // Handle cloud download const handleCloudDownload = async () => { if (!ingestGraphName) { setDownloadMessage("Please select a graph"); @@ -303,7 +355,7 @@ const Setup = () => { try { const creds = localStorage.getItem("creds"); - + // Prepare request body based on provider let requestBody: any = { provider: cloudProvider }; @@ -360,42 +412,56 @@ const Setup = () => { const data = await response.json(); if (data.status === "success") { - setDownloadMessage(`✅ ${data.message}`); + setDownloadMessage("✅ Successfully downloaded the files. Wait for file processing"); await fetchDownloadedFiles(); + setIsDownloading(false); + + // Step 2: Call create_ingest to process downloaded files in background + handleCreateIngestAfterUpload("downloaded").catch((err) => { + console.error("Error in background processing:", err); + }); } else if (data.status === "warning") { setDownloadMessage(`⚠️ ${data.message}`); + setIsDownloading(false); } else { setDownloadMessage(`❌ ${data.message || "Download failed"}`); + setIsDownloading(false); } } catch (error: any) { setDownloadMessage(`❌ Error: ${error.message}`); - } finally { setIsDownloading(false); } }; - // Delete a specific downloaded file const handleDeleteDownloadedFile = async (filename: string) => { if (!ingestGraphName) return; try { const creds = localStorage.getItem("creds"); - const response = await fetch( - `/ui/${ingestGraphName}/cloud/delete?filename=${encodeURIComponent(filename)}`, - { - method: "DELETE", - headers: { Authorization: `Basic ${creds}` }, - } - ); + + // Delete original file (backend will also delete processed content from JSONL if session_id is provided) + const url = tempSessionId + ? `/ui/${ingestGraphName}/cloud/delete?filename=${encodeURIComponent(filename)}&session_id=${tempSessionId}` + : `/ui/${ingestGraphName}/cloud/delete?filename=${encodeURIComponent(filename)}`; + + const response = await fetch(url, { + method: "DELETE", + headers: { Authorization: `Basic ${creds}` }, + }); const data = await response.json(); + setDownloadMessage(`✅ ${data.message}`); await fetchDownloadedFiles(); + + // Refresh temp files list if session exists + if (tempSessionId) { + await fetchTempFiles(tempSessionId); + } } catch (error: any) { setDownloadMessage(`❌ Error: ${error.message}`); } }; - // Delete all downloaded files const handleDeleteAllDownloadedFiles = async () => { if (!ingestGraphName) return; @@ -416,16 +482,193 @@ const Setup = () => { } }; + // ------------------------- + // Temp session helpers (colleague flow) + // ------------------------- + // Fetch temp processed files (server endpoint: GET /ui/{graph}/ingestion_temp/list?session_id=) + const fetchTempFiles = async (sessionId: string) => { + if (!ingestGraphName || !sessionId) return; + + try { + const creds = localStorage.getItem("creds"); + const response = await fetch(`/ui/${ingestGraphName}/ingestion_temp/list?session_id=${sessionId}`, { + headers: { Authorization: `Basic ${creds}` }, + }); + const data = await response.json(); + if (data.status === "success" && data.sessions.length > 0) { + setTempFiles(data.sessions[0].files || []); + setShowTempFiles(true); + } + } catch (error) { + console.error("Error fetching temp files:", error); + } + }; + + // Delete a specific temp file + const handleDeleteTempFile = async (filename: string) => { + if (!ingestGraphName || !tempSessionId) return; + + try { + const creds = localStorage.getItem("creds"); + const response = await fetch( + `/ui/${ingestGraphName}/ingestion_temp/delete?session_id=${tempSessionId}&filename=${encodeURIComponent(filename)}`, + { + method: "DELETE", + headers: { Authorization: `Basic ${creds}` }, + } + ); + const data = await response.json(); + if (data.status === "success") { + setIngestMessage(`✅ ${data.message}`); + // Refresh the temp files list + await fetchTempFiles(tempSessionId); + } + } catch (error: any) { + setIngestMessage(`❌ Error: ${error.message}`); + } + }; + + // Delete all temp files for session + const handleDeleteAllTempFiles = async () => { + if (!ingestGraphName || !tempSessionId) return; + + try { + const creds = localStorage.getItem("creds"); + const response = await fetch( + `/ui/${ingestGraphName}/ingestion_temp/delete?session_id=${tempSessionId}`, + { + method: "DELETE", + headers: { Authorization: `Basic ${creds}` }, + } + ); + const data = await response.json(); + if (data.status === "success") { + setIngestMessage(`✅ ${data.message}`); + setTempFiles([]); + setShowTempFiles(false); + setTempSessionId(null); + } + } catch (error: any) { + setIngestMessage(`❌ Error: ${error.message}`); + } + }; + + // Delete temp files matching original filename (client convenience) + const handleDeleteTempFilesForOriginal = async (originalFilename: string) => { + console.log("handleDeleteTempFilesForOriginal called with:", originalFilename); + + if (!ingestGraphName || !tempSessionId) { + console.log("No graph name or session ID, returning"); + return; + } + + try { + // Extract base name without extension (e.g., "document.pdf" -> "document") + const baseName = originalFilename.replace(/\.[^/.]+$/, ""); + console.log("Base name:", baseName); + + const creds = localStorage.getItem("creds"); + + // Fetch temp files to find matches + const response = await fetch(`/ui/${ingestGraphName}/ingestion_temp/list?session_id=${tempSessionId}`, { + headers: { Authorization: `Basic ${creds}` }, + }); + const data = await response.json(); + console.log("Temp files list response:", data); + + if (data.status === "success" && data.sessions.length > 0) { + const files = data.sessions[0].files || []; + console.log("All temp files:", files.map((f: any) => f.filename)); + + // Find temp files matching pattern: doc_{idx}_{baseName}*.json + const matchingFiles = files.filter((f: any) => f.filename.includes(`_${baseName}`)); + console.log("Matching files to delete:", matchingFiles.map((f: any) => f.filename)); + + // Delete each matching file + for (const file of matchingFiles) { + console.log("Deleting temp file:", file.filename); + const deleteResponse = await fetch( + `/ui/${ingestGraphName}/ingestion_temp/delete?session_id=${tempSessionId}&filename=${encodeURIComponent(file.filename)}`, + { + method: "DELETE", + headers: { Authorization: `Basic ${creds}` }, + } + ); + const deleteData = await deleteResponse.json(); + console.log("Delete response:", deleteData); + } + + console.log(`Successfully deleted ${matchingFiles.length} temp file(s)`); + } else { + console.log("No temp files found or empty sessions"); + } + } catch (error: any) { + console.error("Error deleting temp files:", error); + } + }; + + // ------------------------- + // Ingest flows (create ingest, run ingest) + // ------------------------- + const handleRunIngest = async () => { + if (!ingestJobData) { + setIngestMessage("❌ No ingest job data available"); + return; + } + + setIsIngesting(true); + setIngestMessage("Running final document ingest..."); + + try { + const creds = localStorage.getItem("creds"); + + const loadingInfo = { + load_job_id: ingestJobData.load_job_id, + data_source_id: ingestJobData.data_source_id, + file_path: ingestJobData.data_path, + }; + + const ingestResponse = await fetch(`/ui/${ingestGraphName}/ingest`, { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Basic ${creds}`, + }, + body: JSON.stringify(loadingInfo), + }); + + if (!ingestResponse.ok) { + const errorData = await ingestResponse.json(); + throw new Error(errorData.detail || `Failed to run ingest: ${ingestResponse.statusText}`); + } + + const ingestData = await ingestResponse.json(); + console.log("Ingest response:", ingestData); + + setIngestMessage(`✅ Data ingested successfully! Processed ${tempFiles.length} documents.`); + + // Clear temp state + setTempFiles([]); + setShowTempFiles(false); + setTempSessionId(null); + setIngestJobData(null); + } catch (error: any) { + console.error("Error running ingest:", error); + setIngestMessage(`❌ Error: ${error.message}`); + } finally { + setIsIngesting(false); + } + }; + // Ingest files into knowledge graph (uploaded or downloaded) + // Creates ingest job and either shows temp session or runs ingestion directly const handleIngestDocuments = async (sourceType: "uploaded" | "downloaded" = "uploaded") => { if (!ingestGraphName) { setIngestMessage("Please select a graph"); return; } - const folderPath = sourceType === "uploaded" - ? `uploads/${ingestGraphName}` - : `downloaded_files_cloud/${ingestGraphName}`; + const folderPath = sourceType === "uploaded" ? `uploads/${ingestGraphName}` : `downloaded_files_cloud/${ingestGraphName}`; setIsIngesting(true); setIngestMessage("Step 1/2: Creating ingest job..."); @@ -437,10 +680,10 @@ const Setup = () => { const createIngestConfig = { data_source: "server", data_source_config: { - folder_path: folderPath + data_path: folderPath, }, loader_config: {}, - file_format: "multi" + file_format: "multi", }; const createResponse = await fetch(`/ui/${ingestGraphName}/create_ingest`, { @@ -458,44 +701,144 @@ const Setup = () => { } const createData = await createResponse.json(); - //console.log("Create ingest response:", createData); + console.log("Create ingest response:", createData); - // Step 2: Run ingest - setIngestMessage("Step 2/2: Running document ingest..."); + // Check if temp files were created (for server data source) + const sessionId = createData.data_source_id?.temp_session_id; - const loadingInfo = { - load_job_id: createData.load_job_id, - data_source_id: createData.data_source_id, - file_path: createData.data_path || createData.file_path, // Handle both field names + if (sessionId && !directIngestion) { + // Files are saved to temp storage - show them for review (only if not direct ingestion) + setTempSessionId(sessionId); + setIngestJobData({ + load_job_id: createData.load_job_id, + data_source_id: createData.data_source_id, + data_path: createData.data_path || createData.file_path, + }); + setIngestMessage(`✅ Processed ${createData.data_source_id.file_count} files. Review them below before ingesting.`); + await fetchTempFiles(sessionId); + setIsIngesting(false); + } else { + // No temp files (e.g., S3 Bedrock) OR direct ingestion enabled - proceed directly to ingest + setIngestMessage("Step 2/2: Running document ingest..."); + + const loadingInfo = { + load_job_id: createData.load_job_id, + data_source_id: createData.data_source_id, + file_path: createData.data_path || createData.file_path, + }; + + const ingestResponse = await fetch(`/ui/${ingestGraphName}/ingest`, { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Basic ${creds}`, + }, + body: JSON.stringify(loadingInfo), + }); + + if (!ingestResponse.ok) { + const errorData = await ingestResponse.json(); + throw new Error(errorData.detail || `Failed to run ingest: ${ingestResponse.statusText}`); + } + + const ingestData = await ingestResponse.json(); + console.log("Ingest response:", ingestData); + + setIngestMessage(`✅ Data ingested successfully! Processed documents from ${folderPath}/`); + setIsIngesting(false); + } + } catch (error: any) { + console.error("Error ingesting data:", error); + setIngestMessage(`❌ Error: ${error.message}`); + setIsIngesting(false); + } + }; + + // Called automatically after upload or cloud download finishes. + // Creates an ingest job that processes files into a temp session (JSONL) and stores session id in client. + const handleCreateIngestAfterUpload = async (sourceType: "uploaded" | "downloaded" = "uploaded") => { + console.log("handleCreateIngestAfterUpload called with sourceType:", sourceType); + console.log("ingestGraphName:", ingestGraphName); + + if (!ingestGraphName) { + console.log("No graph name, returning early"); + return; + } + + const folderPath = sourceType === "uploaded" ? `uploads/${ingestGraphName}` : `downloaded_files_cloud/${ingestGraphName}`; + + console.log("folderPath:", folderPath); + + try { + const creds = localStorage.getItem("creds"); + + // Call create_ingest to process files + const createIngestConfig = { + data_source: "server", + data_source_config: { + data_path: folderPath, + }, + loader_config: {}, + file_format: "multi", }; - const ingestResponse = await fetch(`/ui/${ingestGraphName}/ingest`, { + console.log("Calling create_ingest with config:", createIngestConfig); + + const createResponse = await fetch(`/ui/${ingestGraphName}/create_ingest`, { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Basic ${creds}`, }, - body: JSON.stringify(loadingInfo), + body: JSON.stringify(createIngestConfig), }); - if (!ingestResponse.ok) { - const errorData = await ingestResponse.json(); - throw new Error(errorData.detail || `Failed to run ingest: ${ingestResponse.statusText}`); + console.log("create_ingest response status:", createResponse.status); + + if (!createResponse.ok) { + const errorData = await createResponse.json(); + console.error("create_ingest error:", errorData); + throw new Error(errorData.detail || `Failed to create ingest job: ${createResponse.statusText}`); } - const ingestData = await ingestResponse.json(); - //console.log("Ingest response:", ingestData); + const createData = await createResponse.json(); + console.log("create_ingest response data:", createData); + + const sessionId = createData.data_source_id?.temp_session_id; + console.log("Session ID:", sessionId); + + if (sessionId) { + // Save session ID for later ingest + setTempSessionId(sessionId); + setIngestJobData({ + load_job_id: createData.load_job_id, + data_source_id: createData.data_source_id, + data_path: createData.data_path || createData.file_path, + }); + + console.log("Direct ingestion enabled:", directIngestion); - setIngestMessage(`✅ Data ingested successfully! Processed documents from ${folderPath}/`); + if (directIngestion) { + // Direct ingestion - proceed to ingest immediately + setUploadMessage("Running direct ingestion..."); + await handleRunIngest(); + } else { + // Save for later - files ready for ingestion + setUploadMessage(`✅ Successfully processed ${createData.data_source_id.file_count} files. Ready for ingestion.`); + } + } else { + console.warn("No session ID returned from create_ingest"); + } } catch (error: any) { - console.error("Error ingesting data:", error); - setIngestMessage(`❌ Error: ${error.message}`); - } finally { - setIsIngesting(false); + console.error("Error in create_ingest:", error); + setUploadMessage(`❌ Processing error: ${error.message}`); } }; - // Ingest files from S3 with Amazon BDA + // ------------------------- + // S3 / Bedrock ingest + // Replace/merge your AmazonBDA flow with this consolidated handler + // ------------------------- const handleAmazonBDAIngest = async () => { if (!ingestGraphName) { setIngestMessage("Please select a graph"); @@ -508,112 +851,92 @@ const Setup = () => { return; } - if (skipBDAProcessing) { - // When skipping BDA, only output bucket and region are required - if (!outputBucket || !regionName) { - setIngestMessage("❌ Please provide Output Bucket and Region Name"); - return; - } - } else { - // When using BDA, all fields are required + if (fileFormat === "multi") { if (!inputBucket || !outputBucket || !regionName) { setIngestMessage("❌ Please provide Input Bucket, Output Bucket, and Region Name"); return; } - } - // Ask for confirmation - const confirmMessage = skipBDAProcessing - ? `You're skipping Amazon BDA processing and will ingest directly from the output bucket (${outputBucket}). Please confirm to proceed.` - : `You're using Amazon BDA for multimodal document processing. This will trigger Amazon BDA to process your documents from the input bucket (${inputBucket}) and store the results in the output bucket (${outputBucket}) and then ingest them into your knowledge graph. Please confirm to proceed.`; - - const shouldProceed = await confirm(confirmMessage); - if (!shouldProceed) { - setIngestMessage("Operation cancelled by user."); - return; + // Ask for confirmation if using Bedrock (multi format) + const shouldProceed = await confirm( + `You're using AWS Bedrock for multimodal document processing. This will trigger AWS Bedrock BDA to process your documents from the input bucket (${inputBucket}) and store the results in the output bucket (${outputBucket}). Please confirm to proceed.` + ); + if (!shouldProceed) { + setIngestMessage("Operation cancelled by user."); + return; + } + } else if (fileFormat === "json") { + if (!dataPath) { + setIngestMessage("❌ Please provide Data Path (e.g., s3://bucket-name/path/to/data)"); + return; + } } setIsIngesting(true); + setIngestMessage("Step 1/2: Creating ingest job..."); try { const creds = localStorage.getItem("creds"); - let loadingInfo: any = {}; - if (skipBDAProcessing) { - // Skip BDA processing - create ingest job that reads directly from output bucket - const runIngestConfig: any = { - data_source: "bda", + // Step 1: Create ingest job + const createIngestConfig: any = { + data_source: "s3", + data_source_config: { aws_access_key: awsAccessKey, aws_secret_key: awsSecretKey, - output_bucket: outputBucket, - region_name: regionName, - bda_jobs:[], - loader_config: { - doc_id_field: "doc_id", - content_field: "content", - doc_type: "markdown", - }, - file_format: "multi" - }; - - setIngestMessage("Step 1/2: Creating ingest job from output bucket..."); - - // Run ingest directly - loadingInfo = { - load_job_id: "load_documents_content_json", - data_source_id: runIngestConfig, - file_path: outputBucket, - }; - setIngestMessage(`Step 2/2: Running document ingestion for all files in ${outputBucket}...`); - } else { - // Step 1: Create ingest job with BDA processing - const createIngestConfig: any = { - data_source: "bda", - data_source_config: { - aws_access_key: awsAccessKey, - aws_secret_key: awsSecretKey, - input_bucket: inputBucket, - output_bucket: outputBucket, - region_name: regionName, - }, - loader_config: { - doc_id_field: "doc_id", - content_field: "content", - doc_type: "markdown", - }, - file_format: "multi" - }; + }, + loader_config: { + doc_id_field: "doc_id", + content_field: "content", + doc_type: fileFormat === "multi" ? "markdown" : "", + }, + file_format: fileFormat, + }; - setIngestMessage("Step 1/2: Triggering Amazon BDA processing and creating ingest job..."); + // Add format-specific configuration + if (fileFormat === "multi") { + createIngestConfig.data_source_config.input_bucket = inputBucket; + createIngestConfig.data_source_config.output_bucket = outputBucket; + createIngestConfig.data_source_config.region_name = regionName; + setIngestMessage("Step 1/2: Creating ingest job and triggering AWS Bedrock BDA processing..."); + } else if (fileFormat === "json") { + createIngestConfig.loader_config.doc_id_field = "url"; + } - const createResponse = await fetch(`/ui/${ingestGraphName}/create_ingest`, { - method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: `Basic ${creds}`, - }, - body: JSON.stringify(createIngestConfig), - }); + const createResponse = await fetch(`/ui/${ingestGraphName}/create_ingest`, { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Basic ${creds}`, + }, + body: JSON.stringify(createIngestConfig), + }); - if (!createResponse.ok) { - const errorData = await createResponse.json(); - throw new Error(errorData.detail || `Failed to create ingest job: ${createResponse.statusText}`); - } + if (!createResponse.ok) { + const errorData = await createResponse.json(); + throw new Error(errorData.detail || `Failed to create ingest job: ${createResponse.statusText}`); + } - const createData = await createResponse.json(); - //console.log("Create ingest response:", createData); + const createData = await createResponse.json(); + console.log("Create ingest response:", createData); - // Step 2: Run ingest - loadingInfo = { - load_job_id: createData.load_job_id, - data_source_id: createData.data_source_id, - file_path: outputBucket, - }; + // Step 2: Run ingest + setIngestMessage("Step 2/2: Running document ingest..."); - const filesToIngest = createData.data_source_id.bda_jobs.map((job: any) => job.jobId.split("/")[-1]); - setIngestMessage(`Step 2/2: Running document ingest for ${filesToIngest.length} files in ${outputBucket}...`); + // Determine file path based on format + let filePath = ""; + if (fileFormat === "multi") { + filePath = outputBucket; // For multi format, use output bucket + } else if (fileFormat === "json") { + filePath = dataPath; // For json format, use the provided data path } + const loadingInfo = { + load_job_id: createData.load_job_id, + data_source_id: createData.data_source_id, + file_path: filePath, + }; + const ingestResponse = await fetch(`/ui/${ingestGraphName}/ingest`, { method: "POST", headers: { @@ -629,20 +952,26 @@ const Setup = () => { } const ingestData = await ingestResponse.json(); - //console.log("Ingest response:", ingestData); - const filesIngested = ingestData.summary.map((file: any) => file.file_path); - - setIngestMessage(`✅ Document ingestion completed successfully! Ingested ${filesIngested.length} into your knowledge graph.`); + console.log("Ingest response:", ingestData); + if (fileFormat === "multi") { + setIngestMessage( + `✅ Data ingested successfully! AWS Bedrock BDA processed documents from ${inputBucket} and loaded results from ${outputBucket}.` + ); + } else { + setIngestMessage(`✅ Data ingested successfully! Processed documents from ${dataPath}.`); + } } catch (error: any) { - console.error("Error ingesting files:", error); + console.error("Error ingesting S3 data:", error); setIngestMessage(`❌ Error: ${error.message}`); } finally { setIsIngesting(false); } }; - // Check rebuild status + // ------------------------- + // Rebuild / Refresh handlers + // ------------------------- const checkRebuildStatus = async (graphName: string, showLoadingMessage: boolean = false) => { if (!graphName) return; @@ -664,9 +993,9 @@ const Setup = () => { const statusData = await statusResponse.json(); const wasRunning = isRebuildRunning; const isCurrentlyRunning = statusData.is_running || false; - + setIsRebuildRunning(isCurrentlyRunning); - + if (isCurrentlyRunning) { const startTime = statusData.started_at ? new Date(statusData.started_at * 1000).toLocaleString() : "unknown time"; setRefreshMessage(`⚠️ A rebuild is already in progress for "${graphName}" (started at ${startTime}). Please wait for it to complete.`); @@ -695,7 +1024,6 @@ const Setup = () => { } }; - // Handle refresh knowledge graph const handleRefreshGraph = async () => { if (!refreshGraphName) { setRefreshMessage("Please select a graph"); @@ -722,7 +1050,7 @@ const Setup = () => { try { const creds = localStorage.getItem("creds"); - + const response = await fetch(`/ui/${refreshGraphName}/rebuild_graph`, { method: "POST", headers: { @@ -748,22 +1076,9 @@ const Setup = () => { } }; - // Check rebuild status when graph selection or dialog state changes - useEffect(() => { - if (refreshOpen && refreshGraphName) { - // Check status immediately when dialog opens - checkRebuildStatus(refreshGraphName, true); - - // Set up polling to check status every 5 seconds while dialog is open - const intervalId = setInterval(() => { - checkRebuildStatus(refreshGraphName, false); - }, 5000); - - return () => clearInterval(intervalId); - } - }, [refreshOpen, refreshGraphName]); - - // Load available graphs from localStorage on mount + // ------------------------- + // Init effects and helpers + // ------------------------- useEffect(() => { const store = JSON.parse(localStorage.getItem("site") || "{}"); if (store.graphs && Array.isArray(store.graphs)) { @@ -823,9 +1138,7 @@ const Setup = () => { if (createData.status !== "success") { if (createData.message && createData.message.includes("already exists")) { // Ask user to confirm before proceeding with initialization - const shouldInitialize = await confirm( - `Graph "${graphName}" already exists. Do you want to initialize it with GraphRAG schema?` - ); + const shouldInitialize = await confirm(`Graph "${graphName}" already exists. Do you want to initialize it with GraphRAG schema?`); if (!shouldInitialize) { setStatusMessage("Operation cancelled by user."); setStatusType("error"); @@ -858,13 +1171,13 @@ const Setup = () => { setIsInitializing(false); return; } - + setStatusMessage(`✅ Graph "${graphName}" created and initialized successfully! You can now close this dialog.`); setStatusType("success"); - + // Add the new graph to the available graphs list const newGraph = graphName; - setAvailableGraphs(prev => { + setAvailableGraphs((prev) => { if (!prev.includes(newGraph)) { const updated = [...prev, newGraph]; // Update localStorage as well @@ -875,7 +1188,7 @@ const Setup = () => { } return prev; }); - + // Set the newly created graph as selected for ingestion setIngestGraphName(graphName); setRefreshGraphName(graphName); @@ -889,47 +1202,49 @@ const Setup = () => { } }; + // Check rebuild status when graph selection or dialog state changes + useEffect(() => { + if (refreshOpen && refreshGraphName) { + // Check status immediately when dialog opens + checkRebuildStatus(refreshGraphName, true); + + // Set up polling to check status every 5 seconds while dialog is open + const intervalId = setInterval(() => { + checkRebuildStatus(refreshGraphName, false); + }, 5000); + + return () => clearInterval(intervalId); + } + }, [refreshOpen, refreshGraphName]); + + // ------------------------- + // Render + // ------------------------- return (
- -

- Knowledge Graph Administration -

-

- Configure and manage your knowledge graphs -

+

Knowledge Graph Administration

+

Configure and manage your knowledge graphs

{/* Three cards displayed horizontally */}
- {/* Section 1: Initialize Knowledge Graph */}
-

- Initialize Knowledge Graph -

-

- Create the knowledge graph schema and queries for future document ingestion. -

+

Initialize Knowledge Graph

+

Create the knowledge graph schema and queries for future document ingestion.

- @@ -942,18 +1257,11 @@ const Setup = () => {
-

- Ingest to Knowledge Graph -

-

- Upload and ingest documents into your knowledge graph for future content processing. -

+

Ingest to Knowledge Graph

+

Upload and ingest documents into your knowledge graph for future content processing.

- @@ -966,28 +1274,20 @@ const Setup = () => {
-

- Refresh Knowledge Graph -

-

- Process new documents in your knowledge graph to refresh its content. -

+

Refresh Knowledge Graph

+

Process new documents in your knowledge graph to refresh its content.

-
-
{/* Initialize Graph Dialog */} - { // Prevent closing if confirm dialog is open @@ -997,22 +1297,17 @@ const Setup = () => { setInitializeGraphOpen(open); }} > - e.preventDefault()} - > + e.preventDefault()}> Initialize Knowledge Graph Enter the name of your knowledge graph. The system will create it if necessary and initialize it with the GraphRAG schema. - +
- + { > Cancel -
{/* Data Ingest Dialog */} - { // Prevent closing if confirm dialog is open if (!open && isConfirmDialogOpen) { @@ -1105,10 +1396,7 @@ const Setup = () => { setIngestOpen(open); }} > - e.preventDefault()} - > + e.preventDefault()}> Document Ingestion for Knowledge Graph @@ -1118,9 +1406,7 @@ const Setup = () => { {/* Graph Name Selection */}
- + setSelectedFiles(e.target.files)} - disabled={isUploading} - className="dark:border-[#3D3D3D] dark:bg-shadeA" + + setSelectedFiles(e.target.files)} disabled={isUploading} className="dark:border-[#3D3D3D] dark:bg-shadeA" /> +

Maximum upload per request: {MAX_UPLOAD_SIZE_MB} MB. {ingestGraphName ? `Upload destination: uploads/${ingestGraphName}/` : ""}

+
+ + {/* Direct Ingestion Checkbox */} +
+ setDirectIngestion(e.target.checked)} + className="mr-2 h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500" /> -

- Maximum upload per request: {MAX_UPLOAD_SIZE_MB} MB. {ingestGraphName ? `Upload destination: uploads/${ingestGraphName}/` : ""} -

+
- {uploadedFiles.length > 0 && ( - )}
- {uploadMessage && ( -
- {uploadMessage} -
- )} + {uploadMessage &&
{uploadMessage}
} {/* Ingest Data Section */} {uploadedFiles.length > 0 && (
-

- Ingest Documents into Knowledge Graph -

-

- Process uploaded files and add them to the knowledge graph -

-
+ }`}>{ingestMessage}
)}
)} @@ -1264,24 +1529,12 @@ const Setup = () => { {/* Uploaded Files List */} {uploadedFiles.length > 0 && (
-

- Uploaded Files ({uploadedFiles.length}) -

+

Uploaded Files ({uploadedFiles.length})

{uploadedFiles.map((file, index) => ( -
- - {file.filename} - -
@@ -1295,13 +1548,9 @@ const Setup = () => { {/* Download from Cloud Storage Tab */}
-

- Download files from cloud storage and ingest them into your knowledge graph. -

+

Download files from cloud storage and ingest them into your knowledge graph.

- + setCloudAccessKey(e.target.value)} - placeholder="Enter AWS access key" - className="dark:border-[#3D3D3D] dark:bg-shadeA" - /> + + setCloudAccessKey(e.target.value)} placeholder="Enter AWS access key" className="dark:border-[#3D3D3D] dark:bg-shadeA" />
- - setCloudSecretKey(e.target.value)} - placeholder="Enter AWS secret key" - className="dark:border-[#3D3D3D] dark:bg-shadeA" - /> + + setCloudSecretKey(e.target.value)} placeholder="Enter AWS secret key" className="dark:border-[#3D3D3D] dark:bg-shadeA" />
- - setCloudBucket(e.target.value)} - placeholder="my-bucket-name" - className="dark:border-[#3D3D3D] dark:bg-shadeA" - /> + + setCloudBucket(e.target.value)} placeholder="my-bucket-name" className="dark:border-[#3D3D3D] dark:bg-shadeA" />
- - setCloudRegion(e.target.value)} - placeholder="us-east-1" - className="dark:border-[#3D3D3D] dark:bg-shadeA" - /> + + setCloudRegion(e.target.value)} placeholder="us-east-1" className="dark:border-[#3D3D3D] dark:bg-shadeA" />
- - setCloudPrefix(e.target.value)} - placeholder="folder/subfolder/" - className="dark:border-[#3D3D3D] dark:bg-shadeA" - /> + + setCloudPrefix(e.target.value)} placeholder="folder/subfolder/" className="dark:border-[#3D3D3D] dark:bg-shadeA" />
)} @@ -1384,52 +1593,20 @@ const Setup = () => { {cloudProvider === "gcs" && ( <>
- - setGcsProjectId(e.target.value)} - placeholder="my-project-id" - className="dark:border-[#3D3D3D] dark:bg-shadeA" - /> + + setGcsProjectId(e.target.value)} placeholder="my-project-id" className="dark:border-[#3D3D3D] dark:bg-shadeA" />
- -