|
| 1 | +import json |
| 2 | +import os |
| 3 | +import requests |
| 4 | +import tempfile |
| 5 | +import time |
| 6 | +from pathlib import Path |
| 7 | +from typing import Any, List, Optional |
| 8 | +from llama_parse import LlamaParse |
| 9 | +from server.rag.index.parser.file_parser.llamaparse.file_handler import FileHandler |
| 10 | +from server.logger.logger_config import my_logger as logger |
| 11 | + |
| 12 | +all_elements_output_file = "all_elements.json" |
| 13 | +chunks_output_file = "chunks.json" |
| 14 | + |
| 15 | + |
| 16 | +class DocParser: |
| 17 | + def __init__(self, |
| 18 | + file_handler: FileHandler, |
| 19 | + language: str = "en", |
| 20 | + is_download_image: bool = True) -> None: |
| 21 | + self.file_handler = file_handler |
| 22 | + self.is_download_image = is_download_image |
| 23 | + USE_GPT4O = int(os.getenv('USE_GPT4O')) |
| 24 | + if USE_GPT4O: |
| 25 | + self.llamaparse = LlamaParse( |
| 26 | + api_key=os.getenv('LLAMA_CLOUD_API_KEY'), |
| 27 | + gpt4o_mode=True, |
| 28 | + gpt4o_api_key=os.getenv('OPENAI_API_KEY'), |
| 29 | + result_type="json", |
| 30 | + language=language, |
| 31 | + verbose=True) |
| 32 | + else: |
| 33 | + self.llamaparse = LlamaParse( |
| 34 | + api_key=os.getenv('LLAMA_CLOUD_API_KEY'), |
| 35 | + result_type="json", |
| 36 | + language=language, |
| 37 | + verbose=True) |
| 38 | + logger.info( |
| 39 | + f"Init DocParser of llamaparse, language: '{language}', is_download_image: {is_download_image}, USE_GPT4O: {USE_GPT4O}" |
| 40 | + ) |
| 41 | + |
| 42 | + def parse_file( |
| 43 | + self, |
| 44 | + filepath: Path, |
| 45 | + destination_folder: Path, |
| 46 | + include_chunking: bool = True) -> tuple[list[Any], list[Any]]: |
| 47 | + with tempfile.TemporaryDirectory() as temp_dir: |
| 48 | + temp_file = Path(temp_dir) / filepath.name |
| 49 | + self.file_handler.download_file(filepath.as_posix(), |
| 50 | + temp_file.as_posix()) |
| 51 | + |
| 52 | + elements_file = f"{temp_dir}/{all_elements_output_file}" |
| 53 | + |
| 54 | + elements, chunks = self.partition_doc_to_folder( |
| 55 | + temp_file, |
| 56 | + Path(temp_dir), |
| 57 | + include_chunking=include_chunking, |
| 58 | + all_elements_output_file=elements_file) |
| 59 | + |
| 60 | + self.file_handler.sync_foler(temp_dir, |
| 61 | + destination_folder.as_posix()) |
| 62 | + |
| 63 | + return elements, chunks |
| 64 | + |
| 65 | + def partition_doc( |
| 66 | + self, |
| 67 | + input_file: Path, |
| 68 | + output_dir: Path, |
| 69 | + include_chunking: bool = True, |
| 70 | + ) -> tuple[list[Any], list[Any]]: |
| 71 | + elements = [] |
| 72 | + chunks = [] |
| 73 | + try: |
| 74 | + import nest_asyncio |
| 75 | + nest_asyncio.apply() |
| 76 | + |
| 77 | + json_objs = self.llamaparse.get_json_result(str(input_file)) |
| 78 | + job_id = json_objs[0]["job_id"] |
| 79 | + elements = json_objs[0]["pages"] |
| 80 | + job_metadata = json_objs[0]["job_metadata"] |
| 81 | + logger.info( |
| 82 | + f"For inpput_file: '{input_file}', job_id is'{job_id}', job_metatdata is {job_metadata}" |
| 83 | + ) |
| 84 | + |
| 85 | + if self.is_download_image: |
| 86 | + """ |
| 87 | + TODO: |
| 88 | + To enhance the efficiency of image downloading, the following optimizations could be considered: |
| 89 | + 1. Handle image downloads through asynchronous tasks to improve response times. |
| 90 | + 2. Implement concurrent downloads to make effective use of resources and accelerate the download process. |
| 91 | + """ |
| 92 | + for page_item in elements: |
| 93 | + images = page_item["images"] |
| 94 | + for image_item in images: |
| 95 | + image_name = image_item["name"] |
| 96 | + logger.info( |
| 97 | + f"For inpput_file: '{input_file}', downloading image: '{image_name}'" |
| 98 | + ) |
| 99 | + download_image(job_id, image_name, |
| 100 | + output_dir.as_posix()) |
| 101 | + |
| 102 | + if include_chunking: |
| 103 | + """ |
| 104 | + TODO: |
| 105 | + The current chunking strategy treats each page as a separate chunk. Future optimizations might include: |
| 106 | + 1. Evaluating whether adjacent pages can be merged into a single chunk. |
| 107 | + 2. Considering whether it's necessary to split a single page into multiple chunks. |
| 108 | + """ |
| 109 | + filename = input_file.name |
| 110 | + file_extension = input_file.suffix |
| 111 | + for page_item in elements: |
| 112 | + page_number = page_item["page"] |
| 113 | + chunk_item = { |
| 114 | + "chunk_text": page_item["md"], |
| 115 | + "metadata": { |
| 116 | + "filename": filename, |
| 117 | + "filetype": f"application/{file_extension[1:]}", |
| 118 | + "last_modified_timestamp": int(time.time()), |
| 119 | + "beginning_page": page_number, |
| 120 | + "ending_page": page_number |
| 121 | + } |
| 122 | + } |
| 123 | + chunks.append(chunk_item) |
| 124 | + except Exception as e: |
| 125 | + logger.error( |
| 126 | + f"Parsing file: '{input_file}' is failed, exception: {e}") |
| 127 | + |
| 128 | + return elements, chunks |
| 129 | + |
| 130 | + def partition_doc_to_folder( |
| 131 | + self, |
| 132 | + input_file: Path, |
| 133 | + output_dir: Path, |
| 134 | + all_elements_output_file: str, |
| 135 | + include_chunking: bool = True, |
| 136 | + ) -> tuple[list[Any], list[Any]]: |
| 137 | + elements, chunks = self.partition_doc(input_file, output_dir, |
| 138 | + include_chunking) |
| 139 | + |
| 140 | + elements_output_file = output_dir / all_elements_output_file |
| 141 | + elements_to_json(elements, elements_output_file.as_posix()) |
| 142 | + elements_to_json(chunks, (output_dir / chunks_output_file).as_posix()) |
| 143 | + |
| 144 | + return elements, chunks |
| 145 | + |
| 146 | + |
| 147 | +def elements_to_json( |
| 148 | + elements: List[Any], |
| 149 | + filename: Optional[str] = None, |
| 150 | + indent: int = 4, |
| 151 | + encoding: str = "utf-8", |
| 152 | +) -> Optional[str]: |
| 153 | + """ |
| 154 | + Saves a list of elements to a JSON file if filename is specified. |
| 155 | + Otherwise, return the list of elements as a string. |
| 156 | + """ |
| 157 | + # -- serialize `elements` as a JSON array (str) -- |
| 158 | + json_str = json.dumps(elements, indent=indent, sort_keys=False) |
| 159 | + if filename is not None: |
| 160 | + with open(filename, "w", encoding=encoding) as f: |
| 161 | + f.write(json_str) |
| 162 | + return None |
| 163 | + return json_str |
| 164 | + |
| 165 | + |
| 166 | +def download_image(job_id: str, image_name: str, output_dir: str) -> None: |
| 167 | + url = f"https://api.cloud.llamaindex.ai/api/parsing/job/{job_id}/result/image/{image_name}" |
| 168 | + headers = { |
| 169 | + 'Authorization': f'Bearer {os.getenv("LLAMA_CLOUD_API_KEY")}', |
| 170 | + 'Accept': 'application/json', |
| 171 | + 'Content-Type': 'multipart/form-data' |
| 172 | + } |
| 173 | + try: |
| 174 | + response = requests.get(url, headers=headers) |
| 175 | + if response.status_code == 200: |
| 176 | + with open(f'{output_dir}/{image_name}', 'wb') as f: |
| 177 | + f.write(response.content) |
| 178 | + else: |
| 179 | + logger.error( |
| 180 | + f"Failed to retrieve '{image_name}', status_code: {response.status_code}, text: {response.text}" |
| 181 | + ) |
| 182 | + except Exception as e: |
| 183 | + logger.error(f"Download '{image_name}' failed, error: {e}") |
0 commit comments