File size: 14,383 Bytes
a97d040
 
 
 
92d8c87
 
 
a97d040
92d8c87
a97d040
92d8c87
 
a97d040
 
 
 
 
 
 
 
 
 
 
 
c320a1b
a97d040
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c320a1b
a97d040
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92d8c87
 
a97d040
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92d8c87
 
a97d040
 
 
 
70cc6ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a97d040
92d8c87
70cc6ab
 
92d8c87
a97d040
92d8c87
 
70cc6ab
 
 
 
 
 
92d8c87
 
 
 
 
 
 
 
 
70cc6ab
 
 
 
92d8c87
 
 
 
 
 
 
 
a97d040
92d8c87
a97d040
92d8c87
 
 
a97d040
92d8c87
 
 
 
 
 
 
 
 
a97d040
 
92d8c87
a97d040
92d8c87
 
 
 
a97d040
 
92d8c87
 
 
 
a97d040
92d8c87
 
a97d040
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92d8c87
 
 
 
a97d040
 
 
92d8c87
 
 
 
 
 
 
 
 
 
 
a97d040
92d8c87
a97d040
 
 
92d8c87
 
 
 
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
import os
import re
import json
import subprocess
import glob
from pathlib import Path
from concurrent.futures import ProcessPoolExecutor
from langchain_community.document_loaders import UnstructuredMarkdownLoader
from langchain.schema import Document
import shutil
import tempfile
from .path_utils import get_path

class DocumentLoading:
    def convert_pdf_to_md(self, pdf_file, output_dir="output", method="auto"):
        base_name = os.path.splitext(os.path.basename(pdf_file))[0]
        target_dir = os.path.join(output_dir, base_name)
        md_file_path = os.path.join(target_dir, method, f"{base_name}.md")
        print("The md file path is: ", md_file_path)

        if os.path.exists(md_file_path):
            print(f"Markdown file for {pdf_file} already exists at {md_file_path}. Skipping conversion.", flush=True)
            return
            
        command = ["mineru", "-p", pdf_file, "-o", output_dir, "-m", method]
        try:
            subprocess.run(command, check=True)
            # 检查是否生成了 Markdown 文件
            if not os.path.exists(md_file_path):
                print(f"Conversion failed: Markdown file not found at {md_file_path}. Cleaning up folder...")
                shutil.rmtree(target_dir)  # 删除生成的文件夹
            else:
                print(f"Successfully converted {pdf_file} to markdown format in {target_dir}.")
        except subprocess.CalledProcessError as e:
            print(f"An error occurred during conversion: {e}")
            # 如果发生错误且文件夹已生成,则删除文件夹
            if os.path.exists(target_dir):
                print(f"Cleaning up incomplete folder: {target_dir}")
                shutil.rmtree(target_dir)
    # new
    def convert_pdf_to_md_new(self, pdf_dir, output_dir="output", method="auto"):
        pdf_files = glob.glob(os.path.join(pdf_dir, "*.pdf"))

        for pdf_file in pdf_files:
            base_name = os.path.splitext(os.path.basename(pdf_file))[0]
            target_dir = os.path.join(output_dir, base_name)

            if os.path.exists(target_dir):
                print(f"Folder for {pdf_file} already exists in {output_dir}. Skipping conversion.")
            else:
                command = ["mineru", "-p", pdf_file, "-o", output_dir, "-m", method]
                try:
                    subprocess.run(command, check=True)
                    print(f"Successfully converted {pdf_file} to markdown format in {target_dir}.")
                except subprocess.CalledProcessError as e:
                    print(f"An error occurred: {e}")

    def batch_convert_pdfs(pdf_files, output_dir="output", method="auto", max_workers=None):
        # Create a process pool to run the conversion in parallel
        with ProcessPoolExecutor(max_workers=max_workers) as executor:
            # Submit each PDF file to the process pool for conversion
            futures = [executor.submit(convert_pdf_to_md, pdf, output_dir, method) for pdf in pdf_files]

            # Optionally, you can monitor the status of each future as they complete
            for future in futures:
                try:
                    future.result()  # This will raise any exceptions that occurred during the processing
                except Exception as exc:
                    print(f"An error occurred during processing: {exc}")

    def extract_information_from_md(self, md_text):
        title_match = re.search(r'^(.*?)(\n\n|\Z)', md_text, re.DOTALL)
        title = title_match.group(1).strip() if title_match else "N/A"

        authors_match = re.search(
            r'\n\n(.*?)(\n\n[aA][\s]*[bB][\s]*[sS][\s]*[tT][\s]*[rR][\s]*[aA][\s]*[cC][\s]*[tT][^\n]*\n\n)', 
            md_text, 
            re.DOTALL
        )
        authors = authors_match.group(1).strip() if authors_match else "N/A"

        abstract_match = re.search(
            r'(\n\n[aA][\s]*[bB][\s]*[sS][\s]*[tT][\s]*[rR][\s]*[aA][\s]*[cC][\s]*[tT][^\n]*\n\n)(.*?)(\n\n|\Z)', 
            md_text, 
            re.DOTALL
        )
        abstract = abstract_match.group(0).strip() if abstract_match else "N/A"
        abstract = re.sub(r'^[aA]\s*[bB]\s*[sS]\s*[tT]\s*[rR]\s*[aA]\s*[cC]\s*[tT][^\w]*', '', abstract)
        abstract = re.sub(r'^[^a-zA-Z]*', '', abstract)

        introduction_match = re.search(
            r'\n\n([1I][\.\- ]?\s*)?[Ii]\s*[nN]\s*[tT]\s*[rR]\s*[oO]\s*[dD]\s*[uU]\s*[cC]\s*[tT]\s*[iI]\s*[oO]\s*[nN][\.\- ]?\s*\n\n(.*?)'
            r'(?=\n\n(?:([2I][I]|\s*2)[^\n]*?\n\n|\n\n(?:[2I][I][^\n]*?\n\n)))',
            md_text, 
            re.DOTALL
        )
        introduction = introduction_match.group(2).strip() if introduction_match else "N/A"

        main_content_match = re.search(
            r'(.*?)(\n\n([3I][\.\- ]?\s*)?[Rr][Ee][Ff][Ee][Rr][Ee][Nn][Cc][Ee][Ss][^\n]*\n\n|\Z)', 
            md_text, 
            re.DOTALL
        )
        
        if main_content_match:
            main_content = main_content_match.group(1).strip()
        else:
            main_content = "N/A"

        extracted_data = {
            "title": title,
            "authors": authors,
            "abstract": abstract,
            "introduction": introduction,
            "main_content": main_content
        }
        return extracted_data
    
    def process_md_file(self, md_file_path, survey_id):
        loader = UnstructuredMarkdownLoader(md_file_path)
        data = loader.load()
        assert len(data) == 1, "Expected exactly one document in the markdown file."
        assert isinstance(data[0], Document), "The loaded data is not of type Document."
        extracted_text = data[0].page_content
        
        extracted_data = self.extract_information_from_md(extracted_text)
        if len(extracted_data["abstract"]) < 10:
            extracted_data["abstract"] = extracted_data['title']

        title = os.path.splitext(os.path.basename(md_file_path))[0]
        title_new = title.strip()
        invalid_chars = ['<', '>', ':', '"', '/', '\\', '|', '?', '*', '_']
        for char in invalid_chars:
            title_new = title_new.replace(char, ' ')

        os.makedirs(get_path('txt', survey_id), exist_ok=True)
        with open(get_path('txt', survey_id, f'{title_new}.json'), 'w', encoding='utf-8') as f:
            json.dump(extracted_data, f, ensure_ascii=False, indent=4)
        return extracted_data['introduction']
    
    def process_md_file_full(self, md_file_path, survey_id):
        loader = UnstructuredMarkdownLoader(md_file_path)
        data = loader.load()
        assert len(data) == 1, "Expected exactly one document in the markdown file."
        assert isinstance(data[0], Document), "The loaded data is not of type Document."
        extracted_text = data[0].page_content
        
        extracted_data = self.extract_information_from_md(extracted_text)
        if len(extracted_data["abstract"]) < 10:
            extracted_data["abstract"] = extracted_data['title']

        title = os.path.splitext(os.path.basename(md_file_path))[0]
        title_new = title.strip()
        invalid_chars = ['<', '>', ':', '"', '/', '\\', '|', '?', '*', '_']
        for char in invalid_chars:
            title_new = title_new.replace(char, ' ')
 
        os.makedirs(get_path('txt', survey_id), exist_ok=True)
        with open(get_path('txt', survey_id, f'{title_new}.json'), 'w', encoding='utf-8') as f:
            json.dump(extracted_data, f, ensure_ascii=False, indent=4)
        return extracted_data['abstract'] + extracted_data['introduction'] + extracted_data['main_content']

    def load_pdf(self, pdf_file, survey_id, mode):
        """ 
        Parameters
        ----------
        pdf_file : str
            绝对路径 PDF 文件
        survey_id : str
            当前 survey ID,用于组织输出目录
        mode : str
            前端传递的模式,用于控制提取 intro 还是全文,
            可能为 intro / full / auto / txt / ocr。

        设计:
        • mineru 只支持 auto / txt / ocr,这里统一用 'auto'(或保留传入的合法值),
          与前端 intro/full 概念解耦。
        • read_type 控制返回介绍还是全文:
              - mode == 'intro'  →  只返回 introduction
              - 其它             →  返回全文(abstract+intro+main)
        """

        valid_mineru_methods = ['auto', 'txt', 'ocr']
        if mode in valid_mineru_methods:
            mineru_method = mode
            read_type = 'full'
        else:
            mineru_method = 'auto'  # 默认的 mineru 解析方式
            read_type = 'intro' if mode == 'intro' else 'full'

        base_name = os.path.splitext(os.path.basename(pdf_file))[0]
        target_dir = os.path.join(get_path('md', survey_id), base_name)
        # mineru 会把 md 文件放到  <target_dir>/<mineru_method>/<name>.md
        md_file_path = os.path.join(target_dir, mineru_method, f"{base_name}.md")
        print("The md file path is: ", md_file_path)

        if os.path.exists(md_file_path):
            print(f"Markdown file for {pdf_file} already exists at {md_file_path}. Skipping conversion.", flush=True)
            if read_type == 'intro':
                return self.process_md_file(md_file_path, survey_id)
            else:
                return self.process_md_file_full(md_file_path, survey_id)

        command = ["mineru", "-p", pdf_file, "-o", get_path('md', survey_id), "-m", mineru_method]
        try:
            subprocess.run(command, check=True)
            # 检查是否生成了 Markdown 文件
            if not os.path.exists(md_file_path):
                print(f"Conversion failed: Markdown file not found at {md_file_path}. Cleaning up folder...")
                shutil.rmtree(target_dir)  # 删除生成的文件夹
                return None
            else:
                print(f"Successfully converted {pdf_file} to markdown format in {target_dir}.")
                if read_type == 'intro':
                    return self.process_md_file(md_file_path, survey_id)
                else:
                    return self.process_md_file_full(md_file_path, survey_id)
        except subprocess.CalledProcessError as e:
            print(f"An error occurred during conversion: {e}")
            # 如果发生错误且文件夹已生成,则删除文件夹
            if os.path.exists(target_dir):
                print(f"Cleaning up incomplete folder: {target_dir}")
                shutil.rmtree(target_dir)
            return None
    
    def load_pdf_new(self, pdf_dir, survey_id):
        pdf_files = glob.glob(os.path.join(pdf_dir, "*.pdf"))

        for pdf_file in pdf_files:
            base_name = os.path.splitext(os.path.basename(pdf_file))[0]
            target_dir = os.path.join(get_path('md', survey_id), base_name)

            if os.path.exists(target_dir):
                print(f"Folder for {pdf_file} already exists in {get_path('md', survey_id)}. Skipping conversion.")
            else:
                command = ["mineru", "-p", pdf_file, "-o", get_path('md', survey_id), "-m", "auto"]
                try:
                    subprocess.run(command, check=True)
                    print(f"Successfully converted {pdf_file} to markdown format in {target_dir}.")
                except subprocess.CalledProcessError as e:
                    print(f"An error occurred: {e}")

    def parallel_load_pdfs(self, pdf_files, survey_id, max_workers=4):
        # Create a process pool to run the conversion in parallel
        with ProcessPoolExecutor(max_workers=max_workers) as executor:
            # Submit each PDF file to the process pool for conversion
            futures = [executor.submit(self.load_pdf, pdf, survey_id, "auto") for pdf in pdf_files]

            # Optionally, you can monitor the status of each future as they complete
            for future in futures:
                try:
                    future.result()  # This will raise any exceptions that occurred during the processing
                except Exception as exc:
                    print(f"An error occurred during processing: {exc}")

    def ensure_non_empty_introduction(self, introduction, full_text):
        if len(introduction) < 50:
            return full_text[:1000]
        return introduction

    def extract_information_from_md_new(self, md_text):
        # Title extraction
        title_match = re.search(r'^(.*?)(\n\n|\Z)', md_text, re.DOTALL)
        title = title_match.group(1).strip() if title_match else "N/A"

        # Authors extraction
        authors_match = re.search(
            r'\n\n(.*?)(\n\n[aA][\s]*[bB][\s]*[sS][\s]*[tT][\s]*[rR][\s]*[aA][\s]*[cC][\s]*[tT][^\n]*\n\n)', 
            md_text, 
            re.DOTALL
        )
        authors = authors_match.group(1).strip() if authors_match else "N/A"

        # Abstract extraction
        abstract_match = re.search(
            r'(\n\n[aA][\s]*[bB][\s]*[sS][\s]*[tT][\s]*[rR][\s]*[aA][\s]*[cC][\s]*[tT][^\n]*\n\n)(.*?)(\n\n|\Z)', 
            md_text, 
            re.DOTALL
        )
        abstract = abstract_match.group(0).strip() if abstract_match else "N/A"
        abstract = re.sub(r'^[aA]\s*[bB]\s*[sS]\s*[tT]\s*[rR]\s*[aA]\s*[cC]\s*[tT][^\w]*', '', abstract)
        abstract = re.sub(r'^[^a-zA-Z]*', '', abstract)

        # Introduction extraction
        introduction_match = re.search(
            r'\n\n([1I][\.\- ]?\s*)?[Ii]\s*[nN]\s*[tT]\s*[rR]\s*[oO]\s*[dD]\s*[uU]\s*[cC]\s*[tT]\s*[iI]\s*[oO]\s*[nN][\.\- ]?\s*\n\n(.*?)'
            r'(?=\n\n(?:([2I][I]|\s*2)[^\n]*?\n\n|\n\n(?:[2I][I][^\n]*?\n\n)))',
            md_text, 
            re.DOTALL
        )
        introduction = introduction_match.group(2).strip() if introduction_match else "N/A"

        # Main content extraction
        main_content_match = re.search(
            r'(.*?)(\n\n([3I][\.\- ]?\s*)?[Rr][Ee][Ff][Ee][Rr][Ee][Nn][Cc][Ee][Ss][^\n]*\n\n|\Z)', 
            md_text, 
            re.DOTALL
        )
        
        if main_content_match:
            main_content = main_content_match.group(1).strip()
        else:
            main_content = "N/A"

        extracted_data = {
            "title": title,
            "authors": authors,
            "abstract": abstract,
            "introduction": introduction,
            "main_content": main_content
        }
        return extracted_data