|
|
将183万字的论文整理成10万字
简单方法:
from llama_cpp import Llama
import os
from tqdm import tqdm
# ===== 配置 =====
MODEL_PATH = "qwen2-7b-instruct-q4_k_m.gguf"
INPUT_FILE = "input.txt" # 182万字论文
OUTPUT_DIR = "summaries"
FINAL_OUTPUT = "final_100k.txt"
os.makedirs(OUTPUT_DIR, exist_ok=True)
# ===== 加载本地模型(GPU 加速) =====
llm = Llama(
model_path=MODEL_PATH,
n_ctx=4096, # 上下文窗口(可提高至8192)
n_gpu_layers=-1, # 全部层使用 GPU 加速
verbose=False
)
def ask_local_llm(prompt, max_new_tokens=2048):
res = llm(
prompt,
max_tokens=max_new_tokens,
temperature=0.2,
top_p=0.9,
)
return res["choices"][0]["text"]
# ===== 切割大文本 =====
def split_text(text, chunk_size=5000):
return [text[i:i+chunk_size] for i in range(0, len(text), chunk_size)]
print("📘 读取全文...")
with open(INPUT_FILE, "r", encoding="utf-8") as f:
full_text = f.read()
chunks = split_text(full_text)
print(f"✂️ 切割为 {len(chunks)} 段")
# ===== 阶段1:逐段摘要 =====
for i, chunk in enumerate(tqdm(chunks)):
out_file = f"{OUTPUT_DIR}/chunk_{i}.txt"
if os.path.exists(out_file):
continue
prompt = f"""
你是一名高级学术压缩专家。
请对下面文本进行高质量、结构化、忠实的摘要,要求:
1. 不加入新信息
2. 保留关键名词、模型、理论、实验结果
3. 逻辑清晰
4. 压缩到原文的 20–30%
=== 文本段落 {i} ===
{chunk}
"""
summary = ask_local_llm(prompt)
with open(out_file, "w", encoding="utf-8") as f:
f.write(summary)
print("🧩 阶段1:摘要完成")
# ===== 阶段2:合并摘要 =====
print("📚 合并摘要中...")
merged = ""
for f_name in sorted(os.listdir(OUTPUT_DIR)):
with open(os.path.join(OUTPUT_DIR, f_name), "r", encoding="utf-8") as f:
merged += f.read() + "\n\n"
# ===== 阶段3:最终压缩成 10 万字 =====
print("🔧 开始最终压缩为约10万字...")
final_prompt = f"""
请将以下所有摘要文本整合、去重、合并。
目标:压缩至约 100,000 字。
要求:
- 保留核心结论、关键方法、实验数据
- 删除冗余、重复部分
- 保持论文结构(背景、方法、实验、结果、讨论、结论)
- 保持学术性语言
=== 全部摘要 ===
{merged}
"""
final_text = ask_local_llm(final_prompt, max_new_tokens=60000)
with open(FINAL_OUTPUT, "w", encoding="utf-8") as f:
f.write(final_text)
print("🎉 已生成:", FINAL_OUTPUT)
|
|