在deepseek中輸入提示詞:
你現(xiàn)在是一個(gè)Python編程專(zhuān)家,要調(diào)用siliconflow平臺(tái)的Qwen2.5-7B-Instruct模型來(lái)總結(jié)文檔,具體步驟如下:
打開(kāi)文件夾:F:\AI自媒體內(nèi)容\AI炒股\已經(jīng)閱讀\已經(jīng)上傳
讀取里面所有的pdf文檔;
用Qwen2.5-7B-Instruct模型總結(jié)pdf文檔;
總結(jié)完后保存為一個(gè)docx文檔,文件名在原pdf文檔名后面加上“_總結(jié)”
siliconflow平臺(tái)的基礎(chǔ)URL: https://api.siliconflow.cn/v1
API密鑰為:XXX
模型為:Qwen/Qwen2.5-7B-Instruct,上下文長(zhǎng)度32K;
提示詞為:總結(jié)下面這篇券商研究報(bào)告的核心內(nèi)容,不需要總結(jié)“投資建議”、“風(fēng)險(xiǎn)提示”、“投資評(píng)級(jí)”、“免責(zé)聲明”這些。輸出部分包括:報(bào)告標(biāo)題、報(bào)告發(fā)布日期、證券分析師姓名、研報(bào)所用的研究方法、數(shù)據(jù)來(lái)源、研報(bào)的核心邏輯和要點(diǎn)(這部分要不少于500字)、具體的股票投資標(biāo)的(股票名稱(chēng)和股票代碼)。
代碼示例:
from openai import OpenAI
client = OpenAI(api_key="YOUR_API_KEY", base_url="https://api.siliconflow.cn/v1")
response = client.chat.completions.create(
model='alibaba/Qwen1.5-110B-Chat',
messages=[
{'role': 'user', 'content': "拋磚引玉是什么意思呀"}
],
stream=True
)
for chunk in response:
print(chunk.choices[0].delta.content, end='')
注意:模型有限速,RPM=1K TPM=50K, 為了解決這個(gè)問(wèn)題,我們可以采取以下措施:增加請(qǐng)求間隔:在每次請(qǐng)求之間增加一定的延遲,以避免短時(shí)間內(nèi)發(fā)送過(guò)多的請(qǐng)求。批量處理:將多個(gè)文檔的總結(jié)任務(wù)分成多個(gè)批次,每個(gè)批次之間增加一定的延遲。錯(cuò)誤重試:在遇到錯(cuò)誤時(shí),等待一段時(shí)間后重試請(qǐng)求。
如果pdf文檔的內(nèi)容超過(guò)模型的上下文長(zhǎng)度(32K 字符),模型將無(wú)法處理整個(gè)文檔。為了解決這個(gè)問(wèn)題,我們可以將文檔分塊處理,確保每個(gè)塊的長(zhǎng)度不超過(guò)模型的上下文長(zhǎng)度限制。
如果分塊處理不當(dāng),可能會(huì)導(dǎo)致某些內(nèi)容在多個(gè)塊中重復(fù)出現(xiàn),從而導(dǎo)致總結(jié)內(nèi)容重復(fù)。
為了解決這個(gè)問(wèn)題,我們可以采取以下措施:優(yōu)化分塊處理:確保每個(gè)塊的內(nèi)容盡可能獨(dú)立,避免重疊。去重處理:在拼接總結(jié)內(nèi)容時(shí),進(jìn)行去重處理,避免重復(fù)內(nèi)容。檢查模型輸出:在調(diào)用模型時(shí),檢查輸出內(nèi)容,確保沒(méi)有重復(fù)。
在把總結(jié)內(nèi)容寫(xiě)入word時(shí),要把### 、**等這些markdown符號(hào)轉(zhuǎn)換成對(duì)應(yīng)的word文檔符號(hào);
每一步都要輸出信息到屏幕上
Deepseek生成的代碼:
# -*- coding: utf-8 -*-
import os
import warnings
import re
from openai import OpenAI
from PyPDF2 import PdfReader
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
# 忽略PyPDF2的警告
warnings.filterwarnings("ignore", category=UserWarning, module="PyPDF2")
# 設(shè)置API密鑰和基礎(chǔ)URL
api_key = XXX
base_url = "https://api.siliconflow.cn/v1"
# 初始化OpenAI客戶端
client = OpenAI(api_key=api_key, base_url=base_url)
# 定義文件夾路徑
folder_path = r"F:\AI自媒體內(nèi)容\AI炒股\已經(jīng)閱讀\已經(jīng)上傳"
# 定義模型的上下文長(zhǎng)度限制
MAX_CONTEXT_LENGTH = 32000 # 32K characters
def split_text_into_chunks(text, max_length):
"""將文本分割成不超過(guò)指定長(zhǎng)度的塊"""
chunks = []
current_chunk = ""
current_length = 0
for line in text.splitlines():
if current_length + len(line) + 1 > max_length:
chunks.append(current_chunk.strip())
current_chunk = line
current_length = len(line)
else:
if current_chunk:
current_chunk += "\n" + line
else:
current_chunk = line
current_length += len(line) + 1
if current_chunk:
chunks.append(current_chunk.strip())
return chunks
def remove_duplicates(text):
"""去除文本中的重復(fù)內(nèi)容"""
lines = text.splitlines()
seen = set()
unique_lines = []
for line in lines:
if line not in seen:
seen.add(line)
unique_lines.append(line)
return "\n".join(unique_lines)
def markdown_to_word(text):
"""將Markdown格式的文本轉(zhuǎn)換成Word文檔格式"""
# 替換標(biāo)題
text = re.sub(r'^### (.*)', r'\1', text, flags=re.MULTILINE)
text = re.sub(r'^## (.*)', r'\1', text, flags=re.MULTILINE)
text = re.sub(r'^# (.*)', r'\1', text, flags=re.MULTILINE)
# 替換加粗
text = re.sub(r'\*\*(.*?)\*\*', r'\1', text)
# 替換列表
text = re.sub(r'^- (.*)', r'\1', text, flags=re.MULTILINE)
return text
# 遍歷文件夾中的所有pdf文件
for filename in os.listdir(folder_path):
if filename.endswith(".pdf"):
# 讀取PDF文檔
pdf_path = os.path.join(folder_path, filename)
print(f"正在讀取PDF文檔: {pdf_path}")
try:
reader = PdfReader(pdf_path)
text = ""
for page in reader.pages:
text += page.extract_text()
except Exception as e:
print(f"讀取PDF文檔時(shí)出錯(cuò): {e}")
continue
# 分塊處理
chunks = split_text_into_chunks(text, MAX_CONTEXT_LENGTH)
# 總結(jié)每個(gè)塊
summary_chunks = []
for i, chunk in enumerate(chunks):
print(f"正在總結(jié)文檔: {filename} 的第 {i+1}/{len(chunks)} 塊")
try:
response = client.chat.completions.create(
model='Qwen/Qwen2.5-7B-Instruct',
messages=[
{'role': 'user', 'content': f"總結(jié)下面這篇券商研究報(bào)告的核心內(nèi)容,不需要總結(jié)“投資建議”、“風(fēng)險(xiǎn)提示”、“投資評(píng)級(jí)”、“免責(zé)聲明”這些。輸出部分包括:報(bào)告標(biāo)題、報(bào)告發(fā)布日期、證券分析師姓名、研報(bào)所用的研究方法、數(shù)據(jù)來(lái)源、研報(bào)的核心邏輯和要點(diǎn)(這部分要不少于500字)、具體的股票投資標(biāo)的(股票名稱(chēng)和股票代碼)。\n{chunk}"}
],
stream=False
)
summary_chunks.append(response.choices[0].message.content)
except Exception as e:
print(f"總結(jié)文檔時(shí)出錯(cuò): {e}")
continue
# 拼接總結(jié)后的內(nèi)容并去除重復(fù)
summary_content = "\n".join(summary_chunks)
summary_content = remove_duplicates(summary_content)
# 將Markdown格式的文本轉(zhuǎn)換成Word文檔格式
summary_content = markdown_to_word(summary_content)
# 創(chuàng)建新的文檔并寫(xiě)入總結(jié)后的內(nèi)容
new_doc = Document()
for line in summary_content.split("\n"):
if line.startswith("報(bào)告標(biāo)題"):
p = new_doc.add_paragraph()
p.add_run(line).bold = True
p.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
elif line.startswith("報(bào)告發(fā)布日期"):
p = new_doc.add_paragraph()
p.add_run(line).bold = True
elif line.startswith("證券分析師"):
p = new_doc.add_paragraph()
p.add_run(line).bold = True
elif line.startswith("研究方法和數(shù)據(jù)來(lái)源"):
p = new_doc.add_paragraph()
p.add_run(line).bold = True
elif line.startswith("核心邏輯和要點(diǎn)"):
p = new_doc.add_paragraph()
p.add_run(line).bold = True
elif line.startswith("具體的股票投資標(biāo)的"):
p = new_doc.add_paragraph()
p.add_run(line).bold = True
else:
new_doc.add_paragraph(line)
# 保存總結(jié)后的文檔
new_filename = filename.replace(".pdf", "_總結(jié).docx")
new_doc_path = os.path.join(folder_path, new_filename)
new_doc.save(new_doc_path)
print(f"總結(jié)完成,保存為: {new_doc_path}")
print("所有文檔總結(jié)完成!")
程序運(yùn)行結(jié)果:
其中一個(gè)總結(jié):
現(xiàn)在在硅基流動(dòng)SiliconCloud網(wǎng)站注冊(cè),不僅可以免費(fèi)使用各種大模型,還可以通過(guò)以下地址注冊(cè)獲得免費(fèi)的2000萬(wàn)Tokens:
https://cloud.siliconflow.cn/i/Do9fPK0j
聯(lián)系客服