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+ !pip install --no-deps unsloth_zoo
11
+ !pip install --no-deps unsloth
12
+ !pip install trl
13
+ !pip install -U bitsandbytes
14
+ !pip install pymupdf
15
+
16
+ import os
17
+ os.kill(os.getpid(), 9)
18
+
19
+ from huggingface_hub import login
20
+ login() # 或设置环境变量 HF_TOKEN
21
+
22
+ from transformers import pipeline
23
+ from unsloth import FastLanguageModel
24
+
25
+ # 2. 导入必要包
26
+ import gradio as gr
27
+ from transformers import pipeline
28
+ from unsloth import FastLanguageModel # ✅ 插入这里
29
+
30
+ import torch
31
+ import torch
32
+ from transformers import AutoTokenizer, pipeline
33
+ from unsloth import FastLanguageModel
34
+
35
+ model_name = "unsloth/Meta-Llama-3.1-8B-Instruct-bnb-4bit"
36
+
37
+ # 全局模型与tokenizer(只加载一次)
38
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
39
+
40
+ model = None
41
+ generator = None
42
+
43
+ def load_model_dynamic_maxlen(example_text):
44
+ global model, generator
45
+ tokenized_len = len(tokenizer.encode(example_text))
46
+ buffer_len = 512
47
+ max_limit = 4096
48
+ max_seq_length = min(tokenized_len + buffer_len, max_limit)
49
+
50
+ print(f"[✓] 动态设置 max_seq_length 为: {max_seq_length}")
51
+
52
+ model, _ = FastLanguageModel.from_pretrained(
53
+ model_name=model_name,
54
+ max_seq_length=max_seq_length,
55
+ dtype=torch.float16,
56
+ load_in_4bit=True
57
+ )
58
+
59
+ generator = pipeline("text-generation", model=model, tokenizer=tokenizer, device_map="auto")
60
+ return generator
61
+
62
+ # 全局模型与tokenizer(只加载一次)
63
+ model_name = "unsloth/Meta-Llama-3.1-8B-Instruct-bnb-4bit"
64
+
65
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
66
+
67
+ # 设置最大长度一次性加载
68
+ max_seq_length = 4096
69
+
70
+ model, _ = FastLanguageModel.from_pretrained(
71
+ model_name=model_name,
72
+ max_seq_length=max_seq_length,
73
+ dtype=torch.float16,
74
+ load_in_4bit=True
75
+ )
76
+
77
+ generator = pipeline("text-generation", model=model, tokenizer=tokenizer, device_map="auto")
78
+
79
+ def generate_suggestion_llama(prompt_text):
80
+ inputs = tokenizer(prompt_text, return_tensors="pt").to(model.device)
81
+ generation_output = model.generate(
82
+ **inputs,
83
+ max_new_tokens=512,
84
+ do_sample=True,
85
+ temperature=0.7,
86
+ top_p=0.9,
87
+ eos_token_id=tokenizer.eos_token_id
88
+ )
89
+ output_text = tokenizer.decode(generation_output[0], skip_special_tokens=True)
90
+ # 通常模型会把prompt也返回,切掉prompt部分,只保留生成
91
+ return output_text[len(prompt_text):].strip()
92
+
93
+ # 1. 安装依赖
94
+ !pip install gradio transformers accelerate
95
+
96
+ # 2. 导入必要包
97
+ import gradio as gr
98
+ from transformers import pipeline
99
+
100
+ # 先写个PDF转文本的简单函数
101
+ def pdf_to_text(pdf_file):
102
+ try:
103
+ # 这里写你的PDF解析代码,比如用 PyMuPDF / pdfplumber / PyPDF2 等
104
+ # demo示例:
105
+ import fitz # PyMuPDF
106
+ doc = fitz.open(pdf_file.name)
107
+ text = ""
108
+ for page in doc:
109
+ text += page.get_text()
110
+ return text
111
+ except Exception as e:
112
+ print(f"PDF解析错误: {e}")
113
+ return "" # 或者返回提示文本
114
+
115
+
116
+ # 先写个PDF转文本的简单函数
117
+ def extract_title_author_from_pdf(pdf_file):
118
+ import fitz # PyMuPDF
119
+ try:
120
+ doc = fitz.open(pdf_file.name)
121
+
122
+ # 先尝试读取PDF元数据
123
+ metadata = doc.metadata
124
+ title = metadata.get('title', '').strip()
125
+ author = metadata.get('author', '').strip()
126
+
127
+ # 如果元数据里没有,尝试从第一页内容提取
128
+ if not title or not author:
129
+ first_page_text = doc[0].get_text("text")
130
+ lines = [line.strip() for line in first_page_text.split('\n') if line.strip()]
131
+ if not title and len(lines) > 0:
132
+ title = lines[0] # 假设第一页第一行是标题
133
+ if not author and len(lines) > 1:
134
+ author = lines[1] # 假设第二行是作者信息
135
+
136
+ # 返回标题、作者和全文文本
137
+ full_text = ""
138
+ for page in doc:
139
+ full_text += page.get_text("text") + "\n"
140
+
141
+ return title, author, full_text
142
+ except Exception as e:
143
+ print(f"PDF解析错误: {e}")
144
+ return "", "", ""
145
+
146
+ # 在import部分新增
147
+ from typing import List, Dict, Tuple
148
+ import re
149
+
150
+ # 新增高亮处理函数
151
+ def highlight_severity(text, suggestions):
152
+ severity_colors = {
153
+ "High": "red",
154
+ "Medium": "orange",
155
+ "Low": "blue"
156
+ }
157
+
158
+ color_map = {}
159
+ marked_text = text
160
+
161
+ # Handle both string (single suggestion) and list (multiple suggestions) inputs
162
+ suggestions_iter = [suggestions] if isinstance(suggestions, dict) else suggestions
163
+
164
+ for suggestion in suggestions_iter:
165
+ excerpt = suggestion.get("excerpt", "")
166
+ severity = suggestion.get("severity", "Low")
167
+ color = severity_colors.get(severity, "black")
168
+ if excerpt in marked_text and excerpt not in color_map:
169
+ span = f"<span style='background-color:{color};'>{excerpt}</span>"
170
+ marked_text = marked_text.replace(excerpt, span, 1)
171
+ color_map[excerpt] = color
172
+
173
+ if not color_map:
174
+ marked_text = f"<div style='padding:10px;'>{text}</div>"
175
+
176
+ return marked_text, color_map
177
+
178
+ from google.colab import drive
179
+ drive.mount('/content/drive')
180
+
181
+ import os
182
+ base_path = "/content/drive/MyDrive/Colab Notebooks"
183
+ print(os.listdir(base_path))
184
+
185
+ import os
186
+ model_path = "/content/drive/MyDrive/Colab Notebooks/longformer_dmp_final_model"
187
+ print("目录是否存在:", os.path.exists(model_path))
188
+
189
+ import os
190
+ model_path = "/content/drive/MyDrive/Colab Notebooks/longformer_dmp_final_model"
191
+
192
+ print("目录是否存在:", os.path.exists(model_path))
193
+ print("目录内容:", os.listdir(model_path))
194
+
195
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
196
+
197
+ tokenizer = AutoTokenizer.from_pretrained(model_path)
198
+ model = AutoModelForSequenceClassification.from_pretrained(model_path)
199
+
200
+ print("模型和分词器加载成功!")
201
+
202
+ !ls /content/drive/MyDrive/Colab\ Notebooks/
203
+
204
+ # 2. 导入必要包
205
+ import gradio as gr
206
+ from transformers import pipeline
207
+
208
+ # 先写个PDF转文本的简单函数
209
+ def pdf_to_text(pdf_file):
210
+ try:
211
+ # 这里写你的PDF解析代码,比如用 PyMuPDF / pdfplumber / PyPDF2 等
212
+ # demo示例:
213
+ import fitz # PyMuPDF
214
+ doc = fitz.open(pdf_file.name)
215
+ text = ""
216
+ for page in doc:
217
+ text += page.get_text()
218
+ return text
219
+ except Exception as e:
220
+ print(f"PDF解析错误: {e}")
221
+ return "" # 或者返回提示文本
222
+
223
+ # 定义统一的标签映射,分类名称 <-> 数字标签
224
+ num_to_category = {
225
+ 0: "Good",
226
+ 1: "Not Good",
227
+ 2: "Intermediate DMP Needed",
228
+ 3: "Good with Suggestions"
229
+ }
230
+
231
+ category_map = {
232
+ "Good": 0,
233
+ "Not Good": 1,
234
+ "Intermediate DMP Needed": 2,
235
+ "Good with Suggestions": 3,
236
+ "Other": 1, # 仍然可以保留“其他”映射到1,即 Not Good
237
+ }
238
+
239
+ # === 新增:Longformer 分类模型 ===
240
+ from transformers import AutoModelForSequenceClassification, AutoTokenizer
241
+
242
+ longformer_model_name = "allenai/longformer-base-4096" # 你的模型路径
243
+ longformer_tokenizer = AutoTokenizer.from_pretrained(longformer_model_name)
244
+ longformer_model = AutoModelForSequenceClassification.from_pretrained(longformer_model_name)
245
+
246
+ from transformers import pipeline
247
+ longformer_classifier = pipeline(
248
+ "text-classification",
249
+ model=longformer_model,
250
+ tokenizer=longformer_tokenizer,
251
+ device_map="auto",
252
+ truncation=True,
253
+ max_length=4096
254
+ )
255
+
256
+ # 3. 模拟分类模型(用现成pipeline替代,后续换你的Longformer)
257
+ # === 修改:用Longformer替代关键词判断 ===
258
+ def classify_text(text):
259
+ # 将长文本切成大约 3500 tokens 的块
260
+ tokens = longformer_tokenizer.encode(text, truncation=False)
261
+ chunk_size = 3500 # 预留余量,避免超出 max_length=4096
262
+ chunks = [tokens[i:i + chunk_size] for i in range(0, len(tokens), chunk_size)]
263
+
264
+ # 初始化分数字典
265
+ label_scores = {0: 0, 1: 0, 2: 0, 3: 0}
266
+
267
+ # 标签映射:将模型输出的 label 转为对应的数字分类
268
+ label_map = {
269
+ "good": 0,
270
+ "not good": 1,
271
+ "intermediate dmp needed": 2,
272
+ "good with suggestions": 3,
273
+ }
274
+
275
+ for chunk in chunks:
276
+ chunk_text = longformer_tokenizer.decode(chunk)
277
+ result = longformer_classifier(chunk_text, top_k=None)[0]
278
+
279
+ label = result["label"].lower().strip() # 转小写并去除可能的空格
280
+ score = result["score"]
281
+
282
+ # 如果标签未被识别,则默认归为“not good”(1)
283
+ label_idx = label_map.get(label, 1)
284
+ label_scores[label_idx] += score
285
+
286
+ # 返回得分最高的标签编号
287
+ final_label = max(label_scores, key=label_scores.get)
288
+ return final_label
289
+
290
+ # 4. 模拟结构化建议生成(用Meta-Llama调用示范)
291
+ def generate_suggestion(text, category_label):
292
+ prompt = f"""
293
+ I want you to act as a Research Data Management expert.
294
+ You will be provided with:
295
+
296
+ 1. An excerpt from a Data Management Plan (DMP) document:
297
+ {text}
298
+
299
+ 2. A quality label for the DMP:
300
+ {category_label} # 这里是数字标签,确保和分类模型一致
301
+
302
+ Your task is to analyze the given DMP excerpt and explain the reasons behind the provided quality label. Provide clear, constructive, and actionable feedback to help improve the DMP where needed.
303
+
304
+ Please organize your output in the following format:
305
+
306
+ # Summary Diagnosis
307
+ - Briefly interpret the overall quality based on the given label, naming the main strengths and/or weaknesses regardless of label value.
308
+ - Highlight the top 2–3 aspects that most influenced the categorization.
309
+
310
+ # Structured Analysis by Dimension
311
+ Analyze the DMP excerpt along these dimensions, presented in descending order of importance:
312
+ - Data Description
313
+ - Metadata and Documentation
314
+ - Ethics and Privacy
315
+ - Storage and Backup
316
+ - Legal and Security
317
+ - Data Sharing
318
+ - Preservation
319
+ - Responsibilities
320
+
321
+ For **each dimension where relevant issues or observations exist**, provide:
322
+ - **Severity Level:** (e.g., Low, Medium, High) — the importance or urgency of addressing this point.
323
+ - **Core Keywords:** 3 to 5 keywords that summarize the main focus of the issue or strength.
324
+ - **Core Issue Summary:** A concise explanation of the strengths or weaknesses seen in this area.
325
+ - **Supporting Excerpts:** Relevant quotes or sentences taken directly from the *DMP text itself* (not reviewer comments), which illustrate your point.
326
+ - **Improvement Suggestions:** Specific, practical, and encouraging recommendations for enhancement.
327
+
328
+ # Other Notes (if applicable)
329
+ If there are supplementary comments, minor issues, or helpful suggestions that do not fit neatly into the above dimensions, briefly list them here.
330
+
331
+ ---
332
+
333
+ **Important:** Please maintain a positive and encouraging tone throughout your feedback to motivate and guide improvement.
334
+ **Note:** Do not explicitly mention or describe your tone or style in the output. Just apply a constructive and supportive wording naturally.
335
+ **Note:** Do NOT repeat disclaimers or polite closings. Only provide concise, actionable feedback.
336
+ ---
337
+
338
+ Please treat each DMP and label you receive individually, applying this structured approach consistently.
339
+ """
340
+
341
+ # 这里调用你模型接口或transformers pipeline的代码,传入prompt,获得生成结果
342
+ # 例如:
343
+ # response = llama_model.generate(prompt)
344
+ # return response
345
+
346
+ outputs = generator(prompt, max_new_tokens=2000, do_sample=True, temperature=0.7, top_p=0.9)
347
+ result = outputs[0]['generated_text']
348
+ if result.startswith(prompt):
349
+ result = result[len(prompt):].strip()
350
+ elif prompt.strip() in result:
351
+ result = result.split(prompt.strip(), 1)[-1].strip()
352
+ return result
353
+
354
+ # 在import后,紧接着加入:
355
+ reviewed_docs = [] # 存放已审核结果的列表
356
+ docs_to_review = [] # 批量待审核的文档列表
357
+ current_index = 0 # 当前审核文档索引
358
+
359
+ # 主处理函数,输入PDF文件或文本,输出分类和建议
360
+
361
+ # 修改process_document函数,添加高亮处理
362
+
363
+ # Modify the process_document function to return proper results
364
+ def process_document(pdf_file, text_input, selected_category):
365
+ if pdf_file is not None:
366
+ title, author, text = extract_title_author_from_pdf(pdf_file)
367
+ if not text.strip():
368
+ return "❌ PDF解析失败或内容为空", "", "", "请上传有效的PDF文件或输入文本。", ""
369
+ else:
370
+ title, author = "", ""
371
+ text = text_input
372
+ if not text.strip():
373
+ return "❌ 无输入文本", "", "", "请输入文本或上传PDF文件。", ""
374
+
375
+ # Classification
376
+ if selected_category == "Auto Classification":
377
+ category_num = classify_text(text)
378
+ else:
379
+ category_num = category_map.get(selected_category, 1)
380
+
381
+ category_str = num_to_category.get(category_num, str(category_num))
382
+
383
+ # Generate suggestions with proper highlighting
384
+ try:
385
+ # GPT 生成建议
386
+ suggestion = generate_suggestion(text, category_num) # 返回的是字符串,真实建议文本
387
+
388
+ # 解析建议(可以不改)
389
+ # ...
390
+
391
+ # 生成带高亮的文本
392
+ highlighted_text, _ = highlight_severity(text, suggestions_list)
393
+ except Exception as e:
394
+ suggestion = f"❌ 生成建议时出错: {e}"
395
+ highlighted_text = text
396
+
397
+ # 返回给前端:分类标签, 建议文本, 原文, 文档信息, 高亮文本
398
+ # 其中 category_str 是类似 "Good" 的标签
399
+ return category_str, suggestion, text, f"标题: {title}\n作者: {author}", highlighted_text
400
+
401
+ # 2.1 新增批量加载文档函数,替换你主函数里对文件和文本读取逻辑:
402
+ # 改进PDF元数据提取
403
+ def load_documents(pdf_files):
404
+ """Load all PDF files and extract text with better metadata handling"""
405
+ import fitz
406
+ texts = []
407
+ doc_infos = []
408
+
409
+ for pdf_file in pdf_files:
410
+ try:
411
+ doc = fitz.open(pdf_file.name)
412
+ text = ""
413
+ for page in doc:
414
+ text += page.get_text() + "\n"
415
+
416
+ # 改进的元数据提取
417
+ metadata = doc.metadata
418
+ title = metadata.get("title", "").strip() or pdf_file.name.split('/')[-1]
419
+ author = metadata.get("author", "").strip() or "Unknown"
420
+
421
+ # 尝试从第一页提取标题
422
+ if not title or title == pdf_file.name:
423
+ first_page = doc[0].get_text("text")
424
+ possible_title = first_page.split('\n')[0].strip()
425
+ if len(possible_title) > 3 and len(possible_title) < 100:
426
+ title = possible_title
427
+
428
+ doc_infos.append({
429
+ "title": title,
430
+ "author": author,
431
+ "text": text
432
+ })
433
+ doc.close()
434
+ except Exception as e:
435
+ print(f"Error processing {pdf_file.name}: {str(e)}")
436
+
437
+ return doc_infos
438
+
439
+ # 单条文档分类+生成建议(调整了参数,不再传selected_category):
440
+
441
+ def classify_and_suggest(doc):
442
+ category_num = classify_text(doc["text"])
443
+ category_str = num_to_category.get(category_num, "Unknown")
444
+
445
+ suggestion = generate_suggestion(doc["text"], category_num)
446
+
447
+ return category_str, suggestion
448
+
449
+ # 2.3 保存当前审核结果:
450
+ def save_review(doc, manual_label_value, edited_suggestion):
451
+ reviewed_docs.append({
452
+ "title": doc.get("title", "Untitled"),
453
+ "author": doc.get("author", "Unknown"),
454
+ "text": doc["text"],
455
+ "final_label": manual_label_value,
456
+ "suggestion": edited_suggestion
457
+ })
458
+ return f"Document '{doc.get('title', 'Untitled')}' saved"
459
+
460
+ # ===== 新增全局变量和导入 =====
461
+ import json
462
+ import pandas as pd
463
+ from datetime import datetime
464
+
465
+ saved_data = [] # 存储所有保存的文档数据
466
+ export_format = gr.Radio( # 导出格式选择器
467
+ choices=["CSV", "JSON", "Excel"],
468
+ value="CSV",
469
+ label="Export Format"
470
+ )
471
+
472
+ # # 6. Gradio界面搭建
473
+
474
+ # 额外:保存结果按钮,导出JSON示范(简易)
475
+ # 导出JSON
476
+ # Export JSON
477
+ def export_json(text, category, suggestion):
478
+ import json
479
+ result = {
480
+ "text": text,
481
+ "category": category,
482
+ "suggestion": suggestion
483
+ }
484
+ return json.dumps(result, ensure_ascii=False, indent=2)
485
+
486
+ # 替换当前文档来源为 Title & Author
487
+ # 启动批量审查
488
+ # 修改start_review函数,添加高亮处理
489
+ def start_review(pdf_files):
490
+ if not pdf_files:
491
+ return [gr.update()] * 10 # 匹配10个output
492
+
493
+ import fitz
494
+ docs = []
495
+ titles = []
496
+ title_author_list = []
497
+
498
+ for pdf_file in pdf_files:
499
+ doc = fitz.open(pdf_file.name)
500
+ text = "\n".join(page.get_text() for page in doc)
501
+
502
+ # 改进标题/作者提取
503
+ metadata = doc.metadata
504
+ title = metadata.get("title", "").strip()
505
+ author = metadata.get("author", "").strip()
506
+ first_page = doc[0].get_text("text")
507
+ lines = [line.strip() for line in first_page.split('\n') if line.strip()]
508
+ if not title and lines:
509
+ title = lines[0]
510
+ if not author and len(lines) > 1:
511
+ author = lines[1]
512
+
513
+ title = title or pdf_file.name.split("/")[-1]
514
+ author = author or "Unknown"
515
+ full_title_author = f"{title} - {author}"
516
+
517
+ docs.append(text)
518
+ titles.append(full_title_author)
519
+ title_author_list.append(full_title_author)
520
+
521
+ # 处理第一个文档
522
+ doc_text = docs[0]
523
+ category_num = classify_text(doc_text)
524
+ category_str = num_to_category.get(category_num, "Unknown")
525
+ suggestion = generate_suggestion(doc_text, category_num)
526
+
527
+ # 解析高亮建议
528
+ suggestions_list = []
529
+ severity_pattern = r"\*\*Severity Level:\*\* (High|Medium|Low)"
530
+ excerpt_pattern = r"\*\*Supporting Excerpts:\*\* (.*?)(?=\n\*\*|\n\n|$)"
531
+ severities = re.findall(severity_pattern, suggestion)
532
+ excerpts = re.findall(excerpt_pattern, suggestion, re.DOTALL)
533
+
534
+ for sev, exc in zip(severities, excerpts):
535
+ suggestions_list.append({
536
+ "excerpt": exc.strip(),
537
+ "severity": sev
538
+ })
539
+
540
+ highlighted_text, _ = highlight_severity(doc_text, suggestions_list)
541
+
542
+ page_info_str = f"Document 1/{len(docs)}"
543
+
544
+ return [
545
+ titles[0], # Title & Author
546
+ category_str, # Auto category
547
+ suggestion, # Suggestion text
548
+ category_str, # Manual label default
549
+ page_info_str, # Page info
550
+ highlighted_text, # Left side content
551
+ docs, # all texts
552
+ titles, # titles
553
+ 0, # current index
554
+ 1 # page num (placeholder)
555
+ ]
556
+
557
+ # 保存并切换到下一个
558
+
559
+ # 修改save_and_next函数,添加高亮处理
560
+ def save_and_next(manual_label_value, edited_suggestion):
561
+ global current_index
562
+
563
+ if current_index >= len(docs_to_review):
564
+ return gr.update(), gr.update(), gr.update(), gr.update(), "No more documents", gr.update()
565
+
566
+ # Save current
567
+ doc = docs_to_review[current_index]
568
+ save_msg = save_review(doc, manual_label_value, edited_suggestion)
569
+ current_index += 1
570
+
571
+ if current_index >= len(docs_to_review):
572
+ return gr.update(), gr.update(), gr.update(), gr.update(), "All documents reviewed", gr.update()
573
+
574
+ # Process next
575
+ doc = docs_to_review[current_index]
576
+ category_num = classify_text(doc["text"])
577
+ category_str = num_to_category.get(category_num, "Unknown")
578
+ suggestion = generate_suggestion(doc["text"], category_num)
579
+
580
+ # Highlight
581
+ suggestions_list = []
582
+ severity_pattern = r"\*\*Severity Level:\*\* (High|Medium|Low)"
583
+ excerpt_pattern = r"\*\*Supporting Excerpts:\*\* (.*?)(?=\n\*\*|\n\n|$)"
584
+ severities = re.findall(severity_pattern, suggestion)
585
+ excerpts = re.findall(excerpt_pattern, suggestion, re.DOTALL)
586
+
587
+ for sev, exc in zip(severities, excerpts):
588
+ suggestions_list.append({
589
+ "excerpt": exc.strip(),
590
+ "severity": sev
591
+ })
592
+
593
+ highlighted_text, _ = highlight_severity(doc["text"], suggestions_list)
594
+
595
+ return (
596
+ f"{doc.get('title','Untitled')} - {doc.get('author','Unknown')}",
597
+ category_str,
598
+ suggestion,
599
+ category_str,
600
+ f"Document {current_index+1} of {len(docs_to_review)}",
601
+ highlighted_text
602
+ )
603
+
604
+ def save_current_document(label, suggestion, current_doc_idx, full_texts):
605
+ """保存当前文档的评审结果"""
606
+ if not full_texts or current_doc_idx >= len(full_texts):
607
+ return "No document to save"
608
+
609
+ doc_info = {
610
+ "document_index": current_doc_idx,
611
+ "label": label,
612
+ "suggestion": suggestion,
613
+ "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
614
+ }
615
+
616
+ global saved_data
617
+ saved_data.append(doc_info)
618
+ return f"Document {current_doc_idx + 1} saved!"
619
+
620
+ # 导出所有评审结果
621
+
622
+ def export_report(format_type):
623
+ """导出所有保存的评审结果"""
624
+ if not saved_data:
625
+ raise gr.Error("No data to export. Please save some documents first.")
626
+
627
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
628
+ filename = f"DMP_Report_{timestamp}"
629
+
630
+ if format_type == "CSV":
631
+ df = pd.DataFrame(saved_data)
632
+ output = df.to_csv(index=False)
633
+ return gr.File(value=output, visible=True, filename=f"{filename}.csv")
634
+ elif format_type == "JSON":
635
+ output = json.dumps(saved_data, indent=2)
636
+ return gr.File(value=output, visible=True, filename=f"{filename}.json")
637
+ elif format_type == "Excel":
638
+ df = pd.DataFrame(saved_data)
639
+ output = df.to_excel(f"{filename}.xlsx", index=False)
640
+ return gr.File(value=f"{filename}.xlsx", visible=True, filename=f"{filename}.xlsx")
641
+ else:
642
+ raise gr.Error("Unsupported export format")
643
+
644
+ pdf_files = gr.File(file_types=[".pdf"], file_count="multiple")
645
+
646
+ # ===== Gradio界面搭建 =====
647
+
648
+ with gr.Blocks(title="DMP Document Review System", theme="soft") as demo:
649
+ gr.Markdown("## DMP Document Classification and Recommendation System")
650
+ gr.Markdown("Supports batch PDF upload, auto classification, manual review, and exporting results.")
651
+
652
+ gr.Markdown("""
653
+ <style>
654
+ /* 让左右两栏对齐 */
655
+ .gr-box .gr-column {
656
+ display: flex;
657
+ flex-direction: column;
658
+ height: 100%;
659
+ }
660
+
661
+ /* 左侧高亮显示区域高度拉满 */
662
+ .scrollable-html-box {
663
+ height: 640px !important;
664
+ overflow-y: auto;
665
+ padding: 10px;
666
+ border: 1px solid #ccc;
667
+ font-size: 14px;
668
+ line-height: 1.6;
669
+ }
670
+
671
+ /* 右侧建议输入框高度 */
672
+ .scrollable-textbox textarea {
673
+ height: 640px !important;
674
+ overflow-y: auto;
675
+ font-size: 14px;
676
+ line-height: 1.6;
677
+ }
678
+ </style>
679
+ """)
680
+
681
+ current_doc_index = gr.State(0)
682
+ current_page_num = gr.State(1)
683
+ full_texts = gr.State([])
684
+ titles_list = gr.State([])
685
+
686
+ with gr.Row():
687
+ pdf_input = gr.File(
688
+ label="Upload PDF Files",
689
+ file_types=[".pdf"],
690
+ file_count="multiple",
691
+ height="50px"
692
+ )
693
+
694
+ with gr.Row():
695
+ with gr.Column(scale=2):
696
+ highlighted_display = gr.HTML(
697
+ label="Document Content with Highlighted Issues",
698
+ value="<div>Waiting...</div>",
699
+ elem_classes=["scrollable-html-box"]
700
+ )
701
+ with gr.Row():
702
+ prev_page_btn = gr.Button("← Previous Page", variant="secondary", min_width=120)
703
+ page_info = gr.Textbox(
704
+ value="Page 1/1",
705
+ interactive=False,
706
+ show_label=False,
707
+ lines=1,
708
+ elem_classes=["no-border"],
709
+ min_width=100,
710
+ scale=1
711
+ )
712
+ next_page_btn = gr.Button("Next Page →", variant="secondary", min_width=120)
713
+ with gr.Row():
714
+ next_doc_btn = gr.Button("Next Document →", variant="primary", min_width=360)
715
+
716
+ with gr.Column(scale=1):
717
+ process_btn = gr.Button("Auto Classify and Generate Suggestions", variant="primary")
718
+
719
+ with gr.Group():
720
+ title_author_output = gr.Textbox(label="Title & Author", lines=1, interactive=False)
721
+ auto_category = gr.Textbox(label="Model Auto Classification", interactive=False)
722
+ suggestion_box = gr.Textbox(
723
+ label="Suggestions (editable)",
724
+ lines=25, # 增加高度
725
+ max_lines=35, # 可选:允许更长的建议
726
+ interactive=True,
727
+ elem_classes=["scrollable-textbox"],
728
+ show_copy_button=True # 可选:增加复制按钮
729
+ )
730
+
731
+ manual_label = gr.Dropdown(
732
+ choices=["Good", "Not Good", "Intermediate DMP Needed", "Good with Suggestions", "Other"],
733
+ label="Final Reviewed Label",
734
+ value="Good",
735
+ allow_custom_value=True
736
+ )
737
+ with gr.Row():
738
+ save_btn = gr.Button("Save Current", variant="primary")
739
+ export_btn = gr.Button("Download Report", variant="secondary")
740
+ export_file = gr.File(label="Exported File", visible=False)
741
+
742
+ def get_current_page_text(full_text, page_num):
743
+ lines = full_text.split('\n')
744
+ lines_per_page = 50
745
+ max_page = max(1, (len(lines) + lines_per_page - 1) // lines_per_page)
746
+ page_num = max(1, min(page_num, max_page))
747
+ start = (page_num - 1) * lines_per_page
748
+ end = min(start + lines_per_page, len(lines))
749
+ return "\n".join(lines[start:end]), page_num, max_page
750
+
751
+ def start_review(pdf_files):
752
+ if not pdf_files:
753
+ return [gr.update()]*6 + [[], [], 0, 1, "No files"]
754
+
755
+ import fitz
756
+ docs = []
757
+ titles = []
758
+ for pdf_file in pdf_files:
759
+ doc = fitz.open(pdf_file.name)
760
+ text = "\n".join(page.get_text() for page in doc)
761
+ metadata = doc.metadata
762
+ title = metadata.get("title", "").strip()
763
+ author = metadata.get("author", "").strip()
764
+
765
+ # 尝试从第一页提取标题
766
+ if not title:
767
+ first_page = doc[0].get_text("text")
768
+ lines = [line.strip() for line in first_page.split('\n') if line.strip()]
769
+ if lines:
770
+ title = lines[0] # 第一行为标题
771
+ if not author:
772
+ if len(lines) > 1:
773
+ author = lines[1] # 第二行为作者
774
+
775
+ title_author = f"{title} - {author}" if author else title
776
+
777
+ docs.append(text)
778
+ titles.append(title)
779
+
780
+ category_num = classify_text(docs[0])
781
+ category_str = num_to_category.get(category_num, "Unknown")
782
+ suggestion = generate_suggestion(docs[0], category_num)
783
+
784
+ page_text, page_num, max_page = get_current_page_text(docs[0], 1)
785
+ page_info_str = f"Document 1/{len(docs)} | Page {page_num}/{max_page}"
786
+
787
+ return [
788
+ title_author,
789
+ category_str,
790
+ suggestion,
791
+ category_str,
792
+ page_info_str,
793
+ page_text,
794
+ docs,
795
+ titles,
796
+ 0,
797
+ 1
798
+ ]
799
+
800
+ def navigate_page(direction, current_doc_idx, current_page, full_texts):
801
+ if not full_texts:
802
+ return current_page, gr.update(), gr.update()
803
+ page_text, new_page, max_page = get_current_page_text(full_texts[current_doc_idx], current_page + direction)
804
+ page_info = f"Document {current_doc_idx+1}/{len(full_texts)} | Page {new_page}/{max_page}"
805
+ return new_page, page_info, page_text
806
+
807
+ def next_document(current_doc_idx, current_page, full_texts, titles):
808
+ if not full_texts or current_doc_idx >= len(full_texts) - 1:
809
+ return [gr.update()] * 9
810
+
811
+ new_idx = current_doc_idx + 1
812
+ category_num = classify_text(full_texts[new_idx])
813
+ category_str = num_to_category.get(category_num, "Unknown")
814
+ suggestion = generate_suggestion(full_texts[new_idx], category_num)
815
+
816
+ page_text, page_num, max_page = get_current_page_text(full_texts[new_idx], 1)
817
+ page_info = f"Document {new_idx+1}/{len(full_texts)} | Page {page_num}/{max_page}"
818
+
819
+ return [
820
+ f"{titles[new_idx]}",
821
+ category_str,
822
+ suggestion,
823
+ category_str,
824
+ page_info,
825
+ page_text,
826
+ new_idx,
827
+ 1
828
+ ]
829
+
830
+ def save_current_document(manual_label, suggestion, current_doc_idx, full_texts):
831
+ if not full_texts:
832
+ return gr.Info("Nothing to save")
833
+ doc_info = {
834
+ "index": current_doc_idx,
835
+ "label": manual_label,
836
+ "suggestion": suggestion,
837
+ "text": full_texts[current_doc_idx]
838
+ }
839
+ saved_data.append(doc_info)
840
+ return gr.Info("Saved successfully!")
841
+
842
+ def export_report():
843
+ import pandas as pd, tempfile
844
+ from datetime import datetime
845
+ if not saved_data:
846
+ raise gr.Error("No data to export")
847
+
848
+ df = pd.DataFrame(saved_data)
849
+ now = datetime.now().strftime("%Y%m%d_%H%M%S")
850
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx") as tmp:
851
+ df.to_excel(tmp.name, index=False)
852
+ return tmp.name
853
+
854
+ process_btn.click(
855
+ fn=start_review,
856
+ inputs=[pdf_input],
857
+ outputs=[
858
+ title_author_output, auto_category, suggestion_box, manual_label,
859
+ page_info, highlighted_display,
860
+ full_texts, titles_list, current_doc_index, current_page_num
861
+ ]
862
+ )
863
+
864
+ prev_page_btn.click(
865
+ fn=navigate_page,
866
+ inputs=[gr.State(-1), current_doc_index, current_page_num, full_texts],
867
+ outputs=[current_page_num, page_info, highlighted_display]
868
+ )
869
+
870
+ next_page_btn.click(
871
+ fn=navigate_page,
872
+ inputs=[gr.State(1), current_doc_index, current_page_num, full_texts],
873
+ outputs=[current_page_num, page_info, highlighted_display]
874
+ )
875
+
876
+ next_doc_btn.click(
877
+ fn=next_document,
878
+ inputs=[current_doc_index, current_page_num, full_texts, titles_list],
879
+ outputs=[title_author_output, auto_category, suggestion_box, manual_label, page_info, highlighted_display, current_doc_index, current_page_num]
880
+ )
881
+
882
+ save_btn.click(
883
+ fn=save_current_document,
884
+ inputs=[manual_label, suggestion_box, current_doc_index, full_texts],
885
+ outputs=[]
886
+ )
887
+
888
+ # 替换原来 export_btn.click(...) 这一段
889
+ export_btn.click(
890
+ fn=lambda: export_report(export_format.value),
891
+ inputs=[],
892
+ outputs=[export_file]
893
+ )
894
+
895
+ # ===== 启动 =====
896
+ demo.launch(debug=True)
897
+
898
+ pip install pandas openpyxl
requirements.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ torch>=2.0.0
2
+ transformers>=4.40.0
3
+ gradio>=4.0.0
4
+ unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git
5
+ accelerate>=0.27.0
6
+ bitsandbytes>=0.42.0
7
+ pymupdf>=1.23.0
8
+ pandas>=2.0.0
9
+ openpyxl>=3.1.0
10
+ trl>=0.7.0