Phi-3-mini-4k-instruct-gguf代码实例:Python调用API实现批量摘要生成脚本
Phi-3-mini-4k-instruct-gguf代码实例Python调用API实现批量摘要生成脚本1. 环境准备与快速部署在开始编写批量摘要生成脚本之前我们需要先准备好Python环境并安装必要的依赖库。Phi-3-mini-4k-instruct-gguf模型已经预装在镜像中我们可以直接通过API进行调用。1.1 安装必要依赖首先创建一个新的Python虚拟环境并安装核心依赖python -m venv phi3-env source phi3-env/bin/activate # Linux/Mac # phi3-env\Scripts\activate # Windows pip install requests tqdm1.2 验证API可用性在编写脚本前我们先简单测试下API是否正常工作import requests API_URL https://gpu-3sbnmfumnj-7860.web.gpu.csdn.net/generate headers {Content-Type: application/json} data { prompt: 请用中文一句话介绍你自己, max_length: 128, temperature: 0.2 } response requests.post(API_URL, jsondata, headersheaders) print(response.json())如果看到类似下面的输出说明API连接正常{response: 我是Phi-3-mini-4k-instruct模型擅长处理各种文本生成任务。}2. 批量摘要生成脚本实现现在我们来编写完整的批量摘要生成脚本这个脚本可以读取一个包含多篇文章的文本文件为每篇文章生成简洁的摘要。2.1 脚本核心功能设计我们的脚本需要实现以下功能从文本文件中读取多篇文章每篇文章用空行分隔为每篇文章生成摘要保存摘要结果到新文件显示处理进度2.2 完整代码实现以下是完整的Python脚本代码import requests import time from tqdm import tqdm class Phi3SummaryGenerator: def __init__(self, api_url): self.api_url api_url self.headers {Content-Type: application/json} def generate_summary(self, text, max_length256, temperature0.2): 生成单篇文章摘要 prompt f请为以下文章生成一个简洁的摘要不超过3句话\n\n{text} data { prompt: prompt, max_length: max_length, temperature: temperature } try: response requests.post(self.api_url, jsondata, headersself.headers) if response.status_code 200: return response.json().get(response, 摘要生成失败) else: return fAPI错误: {response.status_code} except Exception as e: return f请求异常: {str(e)} def batch_summarize(self, input_file, output_file): 批量处理文章并生成摘要 with open(input_file, r, encodingutf-8) as f: articles f.read().split(\n\n) # 假设文章间用空行分隔 summaries [] print(f开始处理{len(articles)}篇文章...) for article in tqdm(articles): if not article.strip(): continue summary self.generate_summary(article) summaries.append({ original: article, summary: summary }) time.sleep(0.5) # 避免请求过于频繁 # 保存结果 with open(output_file, w, encodingutf-8) as f: for item in summaries: f.write(f原文:\n{item[original]}\n\n) f.write(f摘要:\n{item[summary]}\n\n) f.write(*50 \n\n) print(f处理完成结果已保存到 {output_file}) if __name__ __main__: API_URL https://gpu-3sbnmfumnj-7860.web.gpu.csdn.net/generate generator Phi3SummaryGenerator(API_URL) # 使用示例 generator.batch_summarize(input_articles.txt, output_summaries.txt)3. 脚本使用指南3.1 准备输入文件创建一个名为input_articles.txt的文本文件每篇文章用空行分隔。例如人工智能是模拟人类智能的计算机系统。它能够执行通常需要人类智能的任务如视觉感知、语音识别、决策制定和语言翻译。 机器学习是人工智能的一个分支它使用统计技术使计算机系统能够从数据中学习而无需明确编程。常见的机器学习方法包括监督学习、无监督学习和强化学习。3.2 运行脚本在命令行中执行脚本python batch_summary.py脚本会自动处理输入文件中的所有文章并在当前目录下生成output_summaries.txt文件。3.3 结果示例输出文件内容示例原文: 人工智能是模拟人类智能的计算机系统。它能够执行通常需要人类智能的任务如视觉感知、语音识别、决策制定和语言翻译。 摘要: 人工智能是模拟人类智能的计算机系统。它能执行需要人类智能的任务如感知、识别和决策。AI技术正在改变我们的生活和工作方式。 原文: 机器学习是人工智能的一个分支它使用统计技术使计算机系统能够从数据中学习而无需明确编程。常见的机器学习方法包括监督学习、无监督学习和强化学习。 摘要: 机器学习是AI的分支通过统计技术让计算机从数据中学习。它包括监督学习、无监督学习和强化学习等方法。机器学习使系统能自动改进而不需显式编程。 4. 高级功能扩展4.1 自定义提示模板如果你想调整摘要的风格或长度可以修改generate_summary方法中的提示词模板。例如def generate_summary(self, text, style学术): 根据指定风格生成摘要 if style 学术: prompt f请为以下学术文章生成一个严谨的摘要不超过100字\n\n{text} elif style 新闻: prompt f请为以下新闻报道生成一个简洁的摘要包含5W1H要素\n\n{text} else: prompt f请为以下内容生成一个通俗易懂的摘要\n\n{text} # 其余代码保持不变4.2 处理大文件对于非常大的文本文件可以使用生成器逐行读取避免内存不足def read_large_file(self, file_path): 生成器方式读取大文件 current_article [] with open(file_path, r, encodingutf-8) as f: for line in f: if line.strip() and current_article: yield \n.join(current_article) current_article [] else: current_article.append(line.strip()) if current_article: yield \n.join(current_article)4.3 错误处理与重试增强脚本的健壮性添加重试机制def generate_summary(self, text, max_retries3): 带重试机制的摘要生成 for attempt in range(max_retries): try: # 原有生成代码 return response.json().get(response) except Exception as e: if attempt max_retries - 1: return f生成失败: {str(e)} time.sleep(1 * (attempt 1)) # 指数退避5. 性能优化建议5.1 并行处理对于大量文章可以使用多线程加速处理from concurrent.futures import ThreadPoolExecutor def batch_summarize_parallel(self, input_file, output_file, workers4): 多线程批量处理 with open(input_file, r, encodingutf-8) as f: articles [a for a in f.read().split(\n\n) if a.strip()] with ThreadPoolExecutor(max_workersworkers) as executor: summaries list(tqdm( executor.map(self.generate_summary, articles), totallen(articles) )) # 保存结果...5.2 结果缓存避免重复处理相同内容可以添加简单的缓存机制import hashlib import json import os class Phi3SummaryGenerator: def __init__(self, api_url, cache_filesummary_cache.json): self.cache_file cache_file self.cache self._load_cache() def _load_cache(self): if os.path.exists(self.cache_file): with open(self.cache_file, r) as f: return json.load(f) return {} def _save_cache(self): with open(self.cache_file, w) as f: json.dump(self.cache, f) def _get_cache_key(self, text): return hashlib.md5(text.encode()).hexdigest() def generate_summary(self, text): cache_key self._get_cache_key(text) if cache_key in self.cache: return self.cache[cache_key] # 正常生成摘要 summary ... # 原有生成逻辑 # 更新缓存 self.cache[cache_key] summary self._save_cache() return summary6. 总结通过本文介绍的Python脚本你可以轻松实现以下功能批量处理大量文本文件自动为每篇文章生成摘要自定义摘要风格和长度满足不同场景需求通过并行处理和缓存机制提升性能灵活调整API参数获得最佳生成效果Phi-3-mini-4k-instruct-gguf模型虽然体积小巧但在摘要生成这类任务上表现优异特别适合处理中文内容。你可以基于这个脚本框架进一步开发更复杂的文本处理流水线。获取更多AI镜像想探索更多AI镜像和应用场景访问 CSDN星图镜像广场提供丰富的预置镜像覆盖大模型推理、图像生成、视频生成、模型微调等多个领域支持一键部署。