File parsing function, supports progress callback :param hparams: Hyperparameters :param progress_callback: Progress callback function :return: Path of the parsed file
(hparams: HyperParams, progress_callback=None)
| 110 | |
| 111 | |
| 112 | def parse(hparams: HyperParams, progress_callback=None): |
| 113 | """ |
| 114 | File parsing function, supports progress callback |
| 115 | :param hparams: Hyperparameters |
| 116 | :param progress_callback: Progress callback function |
| 117 | :return: Path of the parsed file |
| 118 | """ |
| 119 | assert os.path.exists(hparams.file_path), "File does not exist." |
| 120 | file_type = hparams.file_path.split('.')[-1].lower() |
| 121 | save_path = os.path.join(hparams.save_path, 'parsed_file') |
| 122 | os.makedirs(save_path, exist_ok=True) |
| 123 | |
| 124 | if file_type in {'tex', 'txt', 'json'}: |
| 125 | # Use file size instead of line count to estimate progress |
| 126 | CHUNK_SIZE = 1024 * 1024 # 1MB |
| 127 | file_size = os.path.getsize(hparams.file_path) |
| 128 | read_bytes = 0 |
| 129 | content = [] |
| 130 | |
| 131 | with open(hparams.file_path, 'r', encoding='utf-8') as f: |
| 132 | while chunk := f.read(CHUNK_SIZE): |
| 133 | content.append(chunk) |
| 134 | read_bytes += len(chunk.encode('utf-8')) |
| 135 | if progress_callback: |
| 136 | progress = int((read_bytes/file_size) * 70) |
| 137 | progress_callback(min(progress, 70)) # Ensure it doesn't exceed 70% |
| 138 | |
| 139 | # Save processed content |
| 140 | save_file_path = os.path.join( |
| 141 | save_path, |
| 142 | f"{os.path.splitext(os.path.basename(hparams.file_path))[0]}.txt" |
| 143 | ) |
| 144 | |
| 145 | with open(save_file_path, 'w', encoding='utf-8') as f: |
| 146 | f.writelines(content) |
| 147 | |
| 148 | if progress_callback: |
| 149 | progress_callback(100) |
| 150 | return save_file_path |
| 151 | |
| 152 | elif file_type == 'pdf': |
| 153 | return pdf_parse(hparams.file_path, save_path, progress_callback) |
| 154 | else: |
| 155 | raise ValueError(f"Unsupported file type: {file_type}") |
| 156 | |
| 157 |