File size: 21,544 Bytes
dbedbf2
a355cd9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8822081
a355cd9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8822081
 
 
a355cd9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8822081
 
 
 
 
a355cd9
 
 
 
 
 
 
 
8822081
a355cd9
 
 
8822081
a355cd9
 
 
 
 
 
 
 
 
8822081
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a355cd9
8822081
 
 
 
a355cd9
 
 
 
 
 
8822081
a355cd9
 
 
 
8822081
a355cd9
8822081
a355cd9
 
8822081
a355cd9
 
 
 
 
 
 
 
 
8822081
a355cd9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8822081
a355cd9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8822081
a355cd9
 
 
 
 
 
 
 
 
 
 
 
20438fb
a355cd9
 
 
 
 
 
 
 
8822081
a355cd9
 
 
8822081
 
 
 
 
 
 
 
 
 
 
 
a355cd9
8822081
a355cd9
8822081
 
a355cd9
 
 
 
 
 
 
8822081
a355cd9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8822081
a355cd9
 
 
8822081
 
 
 
 
 
 
 
 
 
 
 
a355cd9
8822081
a355cd9
8822081
 
a355cd9
 
 
 
 
 
 
8822081
a355cd9
 
 
 
 
 
 
 
 
 
 
 
 
8822081
a355cd9
8822081
 
 
 
 
 
 
 
 
 
 
 
a355cd9
 
8822081
 
 
 
 
 
a355cd9
 
8822081
 
a355cd9
 
 
8822081
a355cd9
8822081
 
 
 
 
 
 
 
 
 
 
a355cd9
 
8822081
 
 
 
 
 
a355cd9
 
8822081
 
a355cd9
 
 
8822081
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a355cd9
 
 
8822081
a355cd9
 
 
 
 
 
8822081
a355cd9
 
 
20438fb
a355cd9
 
 
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
import gradio as gr
import requests
import json
import os
from pathlib import Path
import fitz  # PyMuPDF
import re
from typing import Dict, List, Optional
import tempfile
import unicodedata

def clean_text(text: str) -> str:
    """清理文本,移除多餘空白和特殊字符"""
    if not text:
        return ""
    # 正規化Unicode字符
    text = unicodedata.normalize('NFKC', text)
    # 移除多餘的空白字符
    text = re.sub(r'\s+', ' ', text.strip())
    return text

def extract_title_from_collection(collection_name: str) -> str:
    """從論文集名稱中提取簡潔的標題"""
    # 移除常見的論文集關鍵詞
    keywords_to_remove = ['研究', '論文集', '期刊', '學報', '彙編', '全刊', '下載']
    
    title = collection_name
    for keyword in keywords_to_remove:
        title = title.replace(keyword, '')
    
    # 移除數字和特殊符號,保留核心名稱
    title = re.sub(r'\d+', '', title)
    title = re.sub(r'[^\w\u4e00-\u9fff]', '', title)
    
    return clean_text(title) if title.strip() else collection_name

def download_pdf(url: str) -> Optional[str]:
    """下載PDF文件並返回臨時文件路徑"""
    try:
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
        }
        response = requests.get(url, headers=headers, stream=True, timeout=30)
        response.raise_for_status()
        
        # 創建臨時文件
        temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.pdf')
        temp_file.write(response.content)
        temp_file.close()
        
        return temp_file.name
    except Exception as e:
        print(f"下載PDF失敗: {e}")
        return None

def extract_pdf_content(pdf_path: str) -> Dict[str, str]:
    """從PDF中提取標題、作者和摘要"""
    try:
        doc = fitz.open(pdf_path)
        
        # 提取前幾頁的文本
        full_text = ""
        for page_num in range(min(3, len(doc))):  # 只處理前3頁
            page = doc[page_num]
            text = page.get_text()
            full_text += text + "\n"
        
        doc.close()
        
        # 清理文本
        full_text = clean_text(full_text)
        
        # 提取標題(通常在文檔開頭,字體較大)
        title = extract_title(full_text)
        
        # 提取作者
        author = extract_author(full_text)
        
        # 提取摘要
        abstract = extract_abstract(full_text)
        
        return {
            "title": title,
            "author": author,
            "abstract": abstract
        }
    except Exception as e:
        print(f"提取PDF內容失敗: {e}")
        return {"title": "", "author": "", "abstract": ""}

def extract_title(text: str) -> str:
    """提取標題"""
    lines = text.split('\n')
    
    # 尋找可能的標題(通常在前幾行,不包含常見的頁眉頁腳詞彙)
    skip_keywords = ['頁', 'page', '目錄', '內容', '摘要', 'abstract', '關鍵詞']
    
    for line in lines[:20]:  # 檢查前20行
        line = line.strip()
        if len(line) > 5 and len(line) < 100:  # 標題長度合理
            if not any(keyword in line.lower() for keyword in skip_keywords):
                if not re.match(r'^\d+\.?\d*$', line):  # 不是純數字
                    return line
    
    # 如果沒找到合適標題,返回第一行非空內容
    for line in lines:
        line = line.strip()
        if line and len(line) > 3:
            return line[:80]  # 限制長度
    
    return "未知標題"

def extract_author(text: str) -> str:
    """提取作者"""
    # 常見的作者指示詞
    author_patterns = [
        r'作者[::]\s*([^\n]+)',
        r'著者[::]\s*([^\n]+)',
        r'by\s+([^\n]+)',
        r'撰稿[::]\s*([^\n]+)',
    ]
    
    for pattern in author_patterns:
        match = re.search(pattern, text, re.IGNORECASE)
        if match:
            author = clean_text(match.group(1))
            return author[:50]  # 限制長度
    
    # 如果沒找到明確的作者標識,尋找人名模式
    # 中文人名模式(2-4個中文字符)
    chinese_name_pattern = r'[\u4e00-\u9fff]{2,4}(?:\s*、\s*[\u4e00-\u9fff]{2,4})*'
    
    lines = text.split('\n')
    for line in lines[:30]:  # 檢查前30行
        line = line.strip()
        if len(line) < 100:  # 作者行通常不會太長
            matches = re.findall(chinese_name_pattern, line)
            if matches and len(line) < 50:
                return line
    
    return "未知作者"

def extract_abstract(text: str) -> str:
    """提取摘要"""
    # 摘要關鍵詞
    abstract_keywords = ['摘要', 'abstract', '內容摘要', '研究摘要']
    
    text_lines = text.split('\n')
    abstract_start = -1
    
    # 尋找摘要開始位置
    for i, line in enumerate(text_lines):
        line_lower = line.lower().strip()
        if any(keyword in line_lower for keyword in abstract_keywords):
            abstract_start = i
            break
    
    if abstract_start == -1:
        # 如果沒找到明確的摘要標識,取文檔開頭部分作為摘要
        abstract_text = ' '.join(text_lines[5:15])  # 取中間部分
    else:
        # 從摘要標識處開始提取
        abstract_lines = text_lines[abstract_start+1:abstract_start+15]  # 取摘要後的內容
        abstract_text = ' '.join(abstract_lines)
    
    # 清理和限制摘要長度
    abstract_text = clean_text(abstract_text)
    if len(abstract_text) > 500:
        abstract_text = abstract_text[:500] + "..."
    
    return abstract_text if abstract_text else "無摘要資訊"

def process_json_data(json_input: str, manual_abstract: str = "") -> str:
    """處理JSON數據,補充缺失欄位"""
    try:
        # 解析輸入的JSON
        data = json.loads(json_input)
        
        if not isinstance(data, list):
            data = [data]
        
        processed_data = []
        
        for item in data:
            # 獲取現有資料
            collection_name = item.get("論文集名稱", "")
            author = item.get("作者", "")
            download_url = item.get("下載位置", "")
            
            # 初始化處理後的項目
            processed_item = {
                "論文集名稱": collection_name,
                "作者": author,
                "下載位置": download_url,
                "名稱": "",
                "摘要": ""
            }
            
            # 如果有手動輸入的摘要,優先使用
            use_manual_abstract = manual_abstract.strip()
            
            # 如果有下載位置,嘗試下載並提取資訊
            if download_url:
                print(f"正在處理: {collection_name}")
                pdf_path = download_pdf(download_url)
                
                if pdf_path:
                    try:
                        # 從PDF提取資訊
                        extracted_info = extract_pdf_content(pdf_path)
                        
                        # 設定名稱(避免與論文集名稱重複)
                        pdf_title = extracted_info.get("title", "")
                        if pdf_title and pdf_title != "未知標題":
                            # 確保名稱與論文集名稱不重複
                            collection_base = extract_title_from_collection(collection_name)
                            if collection_base not in pdf_title:
                                processed_item["名稱"] = pdf_title
                            else:
                                # 如果重複,使用更簡潔的版本
                                processed_item["名稱"] = pdf_title.replace(collection_base, "").strip()
                        else:
                            processed_item["名稱"] = extract_title_from_collection(collection_name)
                        
                        # 更新作者(如果原來沒有或PDF中有更詳細的資訊)
                        pdf_author = extracted_info.get("author", "")
                        if pdf_author and pdf_author != "未知作者":
                            if not author or author == "犯罪防治研究中心彙編":
                                processed_item["作者"] = pdf_author
                        
                        # 設定摘要:優先使用手動輸入,否則使用PDF提取的
                        if use_manual_abstract:
                            processed_item["摘要"] = use_manual_abstract
                        else:
                            processed_item["摘要"] = extracted_info.get("abstract", "無摘要資訊")
                        
                    finally:
                        # 清理臨時文件
                        if os.path.exists(pdf_path):
                            os.unlink(pdf_path)
                else:
                    # 如果無法下載PDF,使用現有資訊
                    processed_item["名稱"] = extract_title_from_collection(collection_name)
                    processed_item["摘要"] = use_manual_abstract if use_manual_abstract else "無法獲取摘要資訊"
            else:
                # 如果沒有下載位置,使用現有資訊
                processed_item["名稱"] = extract_title_from_collection(collection_name)
                processed_item["摘要"] = use_manual_abstract if use_manual_abstract else "無下載位置,無法提取摘要"
            
            processed_data.append(processed_item)
        
        # 返回格式化的JSON
        return json.dumps(processed_data, ensure_ascii=False, indent=2)
        
    except Exception as e:
        return f"處理錯誤: {str(e)}"

def generate_filename_from_collection(collection_name: str) -> str:
    """根據論文集名稱生成安全的文件名"""
    if not collection_name:
        return "processed_data.json"
    
    # 移除特殊字符,保留中英文、數字、連字符
    safe_name = re.sub(r'[^\w\u4e00-\u9fff\-]', '_', collection_name)
    
    # 移除多餘的下劃線
    safe_name = re.sub(r'_+', '_', safe_name).strip('_')
    
    # 限制長度
    if len(safe_name) > 50:
        safe_name = safe_name[:50]
    
    # 確保有副檔名
    if not safe_name.endswith('.json'):
        safe_name += '.json'
    
    return safe_name

def save_json_file(json_data: str, filename: str = None, auto_filename: bool = False, collection_name: str = None) -> tuple:
    """保存JSON文件,支持自動文件名生成"""
    try:
        # 如果啟用自動文件名且有論文集名稱,使用論文集名稱
        if auto_filename and collection_name:
            filename = generate_filename_from_collection(collection_name)
        elif not filename:
            filename = "processed_data.json"
        
        if not filename.endswith('.json'):
            filename += '.json'
        
        # 確保文件名安全
        filename = re.sub(r'[^\w\u4e00-\u9fff\-_\.]', '_', filename)
        
        with open(filename, 'w', encoding='utf-8') as f:
            f.write(json_data)
        
        return f"文件已保存: {filename}", filename
    except Exception as e:
        return f"保存失敗: {str(e)}", None

# PDF網址處理函數
def process_pdf_urls(urls_text: str, manual_abstract: str = "") -> str:
    """處理PDF網址列表,直接提取資訊"""
    try:
        # 解析網址
        urls = [url.strip() for url in urls_text.strip().split('\n') if url.strip()]
        
        if not urls:
            return "請輸入至少一個PDF網址"
        
        processed_data = []
        use_manual_abstract = manual_abstract.strip()
        
        for i, url in enumerate(urls, 1):
            print(f"正在處理第 {i}/{len(urls)} 個PDF: {url}")
            
            # 下載PDF
            pdf_path = download_pdf(url)
            
            if pdf_path:
                try:
                    # 從PDF提取資訊
                    extracted_info = extract_pdf_content(pdf_path)
                    
                    # 構建資料項目
                    item = {
                        "名稱": extracted_info.get("title", f"PDF文件 {i}"),
                        "作者": extracted_info.get("author", "未知作者"),
                        "摘要": use_manual_abstract if use_manual_abstract else extracted_info.get("abstract", "無摘要資訊"),
                        "下載位置": url,
                        "論文集名稱": f"直接處理PDF {i}"
                    }
                    
                    processed_data.append(item)
                    
                finally:
                    # 清理臨時文件
                    if os.path.exists(pdf_path):
                        os.unlink(pdf_path)
            else:
                # PDF下載失敗時的處理
                item = {
                    "名稱": f"無法下載的PDF {i}",
                    "作者": "未知作者",
                    "摘要": use_manual_abstract if use_manual_abstract else "PDF下載失敗,無法提取摘要",
                    "下載位置": url,
                    "論文集名稱": f"處理失敗 {i}"
                }
                processed_data.append(item)
        
        # 返回格式化的JSON
        return json.dumps(processed_data, ensure_ascii=False, indent=2)
        
    except Exception as e:
        return f"處理錯誤: {str(e)}"

# Gradio界面
with gr.Blocks(title="PDF資料處理器", theme=gr.themes.Soft()) as demo:
    with gr.Tabs():
        # JSON處理標籤頁
        with gr.TabItem("JSON資料處理"):
            with gr.Row():
                with gr.Column(scale=1):
                    json_input = gr.Textbox(
                        label="輸入JSON資料",
                        placeholder="請貼上您的JSON資料...",
                        lines=8,
                        value='[\n    {\n        "論文集名稱": "刑事政策與犯罪防治研究36",\n        "作者": "犯罪防治研究中心彙編",\n        "下載位置": "https://www.cprc.moj.gov.tw/media/20213330/3_36%E6%9C%9F%E5%85%A8%E5%88%8A%E4%B8%8B%E8%BC%89.pdf?mediaDL=true"\n    }\n]'
                    )
                    
                    manual_abstract1 = gr.Textbox(
                        label="手動輸入摘要 (選填)",
                        placeholder="如果有摘要,請在此輸入。留空則自動從PDF中提取。",
                        lines=4
                    )
                    
                    with gr.Row():
                        auto_filename1 = gr.Checkbox(
                            label="自動使用論文集名稱作為檔名",
                            value=True
                        )
                    
                    filename_input1 = gr.Textbox(
                        label="自訂文件名 (僅在未勾選自動檔名時使用)",
                        placeholder="例: processed_papers.json",
                        value="processed_papers.json",
                        visible=False
                    )
                    
                    process_json_btn = gr.Button("處理JSON資料", variant="primary", size="lg")
                
                with gr.Column(scale=2):
                    output_json1 = gr.Textbox(
                        label="處理結果",
                        lines=18,
                        show_copy_button=True
                    )
                    
                    save_status1 = gr.Textbox(
                        label="保存狀態",
                        lines=2
                    )
                    
                    download_file1 = gr.File(
                        label="下載處理後的文件",
                        visible=False
                    )
        
        # PDF網址處理標籤頁
        with gr.TabItem("PDF網址直接處理"):
            with gr.Row():
                with gr.Column(scale=1):
                    pdf_urls_input = gr.Textbox(
                        label="輸入PDF網址",
                        placeholder="請輸入PDF網址,每行一個...\n\n例如:\nhttps://example.com/paper1.pdf\nhttps://example.com/paper2.pdf\nhttps://example.com/paper3.pdf",
                        lines=8,
                        value="https://www.cprc.moj.gov.tw/media/20213330/3_36%E6%9C%9F%E5%85%A8%E5%88%8A%E4%B8%8B%E8%BC%89.pdf?mediaDL=true"
                    )
                    
                    manual_abstract2 = gr.Textbox(
                        label="手動輸入摘要 (選填)",
                        placeholder="如果有摘要,請在此輸入。留空則自動從PDF中提取。",
                        lines=4
                    )
                    
                    with gr.Row():
                        auto_filename2 = gr.Checkbox(
                            label="自動使用第一個PDF標題作為檔名",
                            value=True
                        )
                    
                    filename_input2 = gr.Textbox(
                        label="自訂文件名 (僅在未勾選自動檔名時使用)",
                        placeholder="例: pdf_extracted_data.json",
                        value="pdf_extracted_data.json",
                        visible=False
                    )
                    
                    process_urls_btn = gr.Button("處理PDF網址", variant="primary", size="lg")
                
                with gr.Column(scale=2):
                    output_json2 = gr.Textbox(
                        label="處理結果",
                        lines=18,
                        show_copy_button=True
                    )
                    
                    save_status2 = gr.Textbox(
                        label="保存狀態",
                        lines=2
                    )
                    
                    download_file2 = gr.File(
                        label="下載處理後的文件",
                        visible=False
                    )
    
    def process_and_save_json(json_input, manual_abstract, auto_filename, custom_filename):
        # 處理JSON資料
        result = process_json_data(json_input, manual_abstract)
        
        # 獲取論文集名稱用於自動檔名
        collection_name = ""
        try:
            data = json.loads(json_input)
            if isinstance(data, list) and len(data) > 0:
                collection_name = data[0].get("論文集名稱", "")
            elif isinstance(data, dict):
                collection_name = data.get("論文集名稱", "")
        except:
            pass
        
        # 保存文件
        save_msg, actual_filename = save_json_file(
            result, 
            custom_filename if not auto_filename else None,
            auto_filename,
            collection_name
        )
        
        # 如果保存成功,提供下載
        if actual_filename and "已保存" in save_msg:
            return result, save_msg, gr.update(visible=True, value=actual_filename)
        else:
            return result, save_msg, gr.update(visible=False)
    
    def process_and_save_urls(urls_input, manual_abstract, auto_filename, custom_filename):
        # 處理PDF網址
        result = process_pdf_urls(urls_input, manual_abstract)
        
        # 獲取第一個PDF的標題用於自動檔名
        title_for_filename = ""
        if auto_filename:
            try:
                data = json.loads(result)
                if isinstance(data, list) and len(data) > 0:
                    title_for_filename = data[0].get("名稱", "")
            except:
                pass
        
        # 保存文件
        save_msg, actual_filename = save_json_file(
            result,
            custom_filename if not auto_filename else None,
            auto_filename,
            title_for_filename
        )
        
        # 如果保存成功,提供下載
        if actual_filename and "已保存" in save_msg:
            return result, save_msg, gr.update(visible=True, value=actual_filename)
        else:
            return result, save_msg, gr.update(visible=False)
    
    # 控制文件名輸入框的顯示/隱藏
    def toggle_filename_input1(auto_filename):
        return gr.update(visible=not auto_filename)
    
    def toggle_filename_input2(auto_filename):
        return gr.update(visible=not auto_filename)
    
    # 綁定checkbox事件
    auto_filename1.change(
        toggle_filename_input1,
        inputs=[auto_filename1],
        outputs=[filename_input1]
    )
    
    auto_filename2.change(
        toggle_filename_input2,
        inputs=[auto_filename2],
        outputs=[filename_input2]
    )
    
    # JSON處理按鈕事件
    process_json_btn.click(
        process_and_save_json,
        inputs=[json_input, manual_abstract1, auto_filename1, filename_input1],
        outputs=[output_json1, save_status1, download_file1]
    )
    
    # PDF網址處理按鈕事件
    process_urls_btn.click(
        process_and_save_urls,
        inputs=[pdf_urls_input, manual_abstract2, auto_filename2, filename_input2],
        outputs=[output_json2, save_status2, download_file2]
    )
    
    gr.Markdown("## 基本功能:JSON處理 | PDF網址處理 | 自動檔名 | 手動摘要")

if __name__ == "__main__":
    demo.launch()