同步完整源码 - 2026-05-25
This commit is contained in:
@@ -0,0 +1,241 @@
|
||||
# 文档分类器应用示例
|
||||
|
||||
本示例展示了如何使用agentUniverse框架的文档分类器功能,支持多种分类策略和中文文档处理。
|
||||
|
||||
## 功能特性
|
||||
|
||||
### 基础文档分类器 (DocumentClassifier)
|
||||
- **多种分类策略**:关键词匹配、正则表达式、LLM分类、混合策略
|
||||
- **灵活配置**:支持自定义分类规则和类别
|
||||
- **批量处理**:高效处理大量文档
|
||||
- **分类统计**:提供详细的分类结果统计
|
||||
|
||||
### 中文文档分类器 (ChineseDocumentClassifier)
|
||||
- **中文优化**:专门针对中文文档优化
|
||||
- **jieba分词**:支持中文分词和关键词提取
|
||||
- **停用词过滤**:自动过滤中文停用词
|
||||
- **模糊匹配**:支持中文关键词模糊匹配
|
||||
- **内容类型识别**:自动识别文档内容类型
|
||||
|
||||
## 安装依赖
|
||||
|
||||
```bash
|
||||
pip install agentuniverse jieba
|
||||
```
|
||||
|
||||
## 快速开始
|
||||
|
||||
### 1. 运行演示程序
|
||||
|
||||
```bash
|
||||
python document_classifier_demo.py
|
||||
```
|
||||
|
||||
### 2. 运行测试
|
||||
|
||||
```bash
|
||||
python test_classifier.py
|
||||
```
|
||||
|
||||
## 使用示例
|
||||
|
||||
### 基础分类器使用
|
||||
|
||||
```python
|
||||
from agentuniverse.agent.action.knowledge.store.document import Document
|
||||
from examples.third_party_examples.tools.document_classifier_tool.document_classifier import DocumentClassifier
|
||||
|
||||
# 创建分类器
|
||||
classifier = DocumentClassifier()
|
||||
|
||||
# 设置分类类别
|
||||
classifier.set_categories(['技术文档', '学术论文', '新闻资讯', '其他'])
|
||||
|
||||
# 添加关键词规则
|
||||
classifier.add_keyword_rule('技术文档', ['代码', '编程', 'API', '函数'])
|
||||
classifier.add_keyword_rule('学术论文', ['研究', '实验', '分析', '论文'])
|
||||
|
||||
# 创建文档
|
||||
doc = Document(text="这是一个Python编程教程,介绍了如何使用API和函数。")
|
||||
|
||||
# 分类文档
|
||||
classified_doc = classifier._classify_document(doc)
|
||||
print(f"分类结果: {classified_doc.metadata['classification']}")
|
||||
print(f"置信度: {classified_doc.metadata['classification_confidence']}")
|
||||
```
|
||||
|
||||
### 中文分类器使用
|
||||
|
||||
```python
|
||||
from examples.third_party_examples.tools.document_classifier_tool.chinese_document_classifier import
|
||||
ChineseDocumentClassifier
|
||||
|
||||
# 创建中文分类器
|
||||
classifier = ChineseDocumentClassifier()
|
||||
|
||||
# 设置分类类别
|
||||
classifier.set_categories(['技术文档', '学术论文', '新闻资讯', '其他'])
|
||||
|
||||
# 添加中文关键词规则
|
||||
classifier.add_chinese_keyword_rule('技术文档', ['代码', '编程', 'API', '函数', '技术'])
|
||||
|
||||
# 分类中文文档
|
||||
doc = Document(text="这是一个Python编程教程,介绍了如何使用API和函数进行技术开发。")
|
||||
classified_doc = classifier._classify_document(doc)
|
||||
print(f"分类结果: {classified_doc.metadata['classification']}")
|
||||
```
|
||||
|
||||
### 批量文档处理
|
||||
|
||||
```python
|
||||
# 处理多个文档
|
||||
documents = [
|
||||
Document(text="Python编程教程"),
|
||||
Document(text="机器学习研究论文"),
|
||||
Document(text="科技新闻资讯")
|
||||
]
|
||||
|
||||
classified_docs = classifier.process_docs(documents)
|
||||
|
||||
# 获取分类统计
|
||||
summary = classifier.get_classification_summary(classified_docs)
|
||||
print(f"总文档数: {summary['total_documents']}")
|
||||
print(f"分类统计: {summary['category_counts']}")
|
||||
```
|
||||
|
||||
## 配置说明
|
||||
|
||||
### 基础分类器配置 (document_classifier.yaml)
|
||||
|
||||
```yaml
|
||||
name: 'document_classifier'
|
||||
description: '智能文档分类器,支持多种分类策略'
|
||||
strategy: 'keyword_matching' # 分类策略
|
||||
confidence_threshold: 0.7 # 置信度阈值
|
||||
default_category: '未分类' # 默认分类
|
||||
categories: # 分类类别列表
|
||||
- '技术文档'
|
||||
- '学术论文'
|
||||
- '新闻资讯'
|
||||
- '其他'
|
||||
keyword_rules: # 关键词规则
|
||||
技术文档:
|
||||
- '代码'
|
||||
- '编程'
|
||||
- 'API'
|
||||
- '函数'
|
||||
```
|
||||
|
||||
### 中文分类器配置 (chinese_document_classifier.yaml)
|
||||
|
||||
```yaml
|
||||
name: 'chinese_document_classifier'
|
||||
description: '中文文档智能分类器'
|
||||
use_jieba: true # 使用jieba分词
|
||||
min_word_length: 2 # 最小词长度
|
||||
similarity_threshold: 0.6 # 相似度阈值
|
||||
stop_words: # 停用词列表
|
||||
- '的'
|
||||
- '了'
|
||||
- '在'
|
||||
- '是'
|
||||
```
|
||||
|
||||
## 分类策略
|
||||
|
||||
### 1. 关键词匹配 (keyword_matching)
|
||||
- 基于预定义关键词进行匹配
|
||||
- 支持模糊匹配和权重计算
|
||||
- 适合规则明确的分类场景
|
||||
|
||||
### 2. 正则表达式 (regex_pattern)
|
||||
- 使用正则表达式进行模式匹配
|
||||
- 支持复杂的文本模式识别
|
||||
- 适合结构化文档分类
|
||||
|
||||
### 3. LLM分类 (llm_classification)
|
||||
- 使用大语言模型进行智能分类
|
||||
- 支持自然语言理解
|
||||
- 适合复杂语义分类场景
|
||||
|
||||
### 4. 混合策略 (hybrid)
|
||||
- 结合多种分类策略
|
||||
- 提高分类准确性和鲁棒性
|
||||
- 适合复杂分类需求
|
||||
|
||||
## 高级功能
|
||||
|
||||
### 文本统计
|
||||
```python
|
||||
# 获取文本统计信息
|
||||
stats = classifier.get_text_statistics(text)
|
||||
print(f"总字符数: {stats['total_chars']}")
|
||||
print(f"总词数: {stats['total_words']}")
|
||||
print(f"高频词: {stats['most_common_words']}")
|
||||
```
|
||||
|
||||
### 内容类型识别
|
||||
```python
|
||||
# 自动识别内容类型
|
||||
content_type = classifier.classify_by_content_type(text)
|
||||
print(f"内容类型: {content_type}")
|
||||
```
|
||||
|
||||
### 自定义停用词
|
||||
```python
|
||||
# 添加自定义停用词
|
||||
classifier.stop_words.extend(['自定义', '停用词'])
|
||||
```
|
||||
|
||||
## 性能优化
|
||||
|
||||
1. **批量处理**:使用`process_docs`方法批量处理文档
|
||||
2. **缓存结果**:分类结果会存储在文档metadata中
|
||||
3. **分词优化**:中文分类器使用jieba分词提高效率
|
||||
4. **规则优化**:合理设置关键词规则和正则表达式
|
||||
|
||||
## 扩展开发
|
||||
|
||||
### 自定义分类器
|
||||
```python
|
||||
class CustomClassifier(DocumentClassifier):
|
||||
def _classify_document(self, document: Document) -> Document:
|
||||
# 实现自定义分类逻辑
|
||||
pass
|
||||
```
|
||||
|
||||
### 添加新的分类策略
|
||||
```python
|
||||
class CustomStrategy(ClassificationStrategy):
|
||||
CUSTOM_STRATEGY = "custom_strategy"
|
||||
```
|
||||
|
||||
## 常见问题
|
||||
|
||||
### Q: 如何提高分类准确性?
|
||||
A:
|
||||
1. 优化关键词规则
|
||||
2. 调整置信度阈值
|
||||
3. 使用混合策略
|
||||
4. 增加训练数据
|
||||
|
||||
### Q: 如何处理新领域文档?
|
||||
A:
|
||||
1. 添加领域特定关键词
|
||||
2. 训练领域特定模型
|
||||
3. 使用LLM分类策略
|
||||
|
||||
### Q: 分类速度慢怎么办?
|
||||
A:
|
||||
1. 减少关键词数量
|
||||
2. 使用更简单的策略
|
||||
3. 批量处理文档
|
||||
4. 优化正则表达式
|
||||
|
||||
## 贡献指南
|
||||
|
||||
欢迎提交Issue和Pull Request来改进文档分类器功能!
|
||||
|
||||
## 许可证
|
||||
|
||||
本项目采用Apache 2.0许可证。
|
||||
@@ -0,0 +1 @@
|
||||
# Document Classifier App
|
||||
+278
@@ -0,0 +1,278 @@
|
||||
# !/usr/bin/env python3
|
||||
# -*- coding:utf-8 -*-
|
||||
|
||||
# @Time : 2024/12/19 10:30
|
||||
# @Author : AI Assistant
|
||||
# @Email : assistant@agentuniverse.ai
|
||||
# @FileName: chinese_document_classifier.py
|
||||
|
||||
import jieba
|
||||
import re
|
||||
from typing import List, Dict, Any
|
||||
from collections import Counter
|
||||
|
||||
from examples.third_party_examples.tools.document_classifier_tool.document_classifier import (
|
||||
DocumentClassifier
|
||||
)
|
||||
|
||||
|
||||
class ChineseDocumentClassifier(DocumentClassifier):
|
||||
"""中文文档分类器
|
||||
|
||||
专门针对中文文档优化的分类器,支持:
|
||||
- 中文关键词匹配
|
||||
- 中文正则表达式匹配
|
||||
- 基于jieba分词的关键词提取
|
||||
- 中文语义相似度计算
|
||||
- 中文LLM分类
|
||||
|
||||
Attributes:
|
||||
use_jieba: 是否使用jieba分词
|
||||
min_word_length: 最小词长度
|
||||
stop_words: 停用词列表
|
||||
similarity_threshold: 语义相似度阈值
|
||||
"""
|
||||
|
||||
name: str = "chinese_document_classifier"
|
||||
description: str = "中文文档智能分类器,支持多种中文分类策略"
|
||||
|
||||
# 中文特定配置
|
||||
use_jieba: bool = True
|
||||
min_word_length: int = 2
|
||||
stop_words: List[str] = []
|
||||
similarity_threshold: float = 0.6
|
||||
|
||||
# 中文停用词(常用)
|
||||
DEFAULT_STOP_WORDS = [
|
||||
'的', '了', '在', '是', '我', '有', '和', '就', '不', '人', '都', '一', '一个', '上', '也', '很', '到', '说', '要', '去', '你', '会', '着', '没有', '看', '好', '自己', '这', '那', '里', '来', '下', '过', '他', '她', '它', '们', '我们', '你们', '他们', '这个', '那个', '这些', '那些', '什么', '怎么', '为什么', '哪里', '什么时候', '多少', '几个', '一些', '很多', '非常', '特别', '比较', '更', '最', '还', '又', '再', '已经', '正在', '将要', '可以', '能够', '应该', '必须', '需要', '想要', '希望', '觉得', '认为', '知道', '了解', '明白', '清楚', '记得', '忘记', '学习', '工作', '生活', '时间', '地方', '事情', '问题', '方法', '结果', '原因', '条件', '情况', '时候', '地方', '方面', '部分', '内容', '形式', '方式', '过程', '阶段', '步骤', '环节', '因素', '影响', '作用', '意义', '价值', '目的', '目标', '计划', '安排', '组织', '管理', '控制', '监督', '检查', '评估', '分析', '研究', '调查', '统计', '数据', '信息', '资料', '材料', '文件', '报告', '总结', '结论', '建议', '意见', '看法', '观点', '态度', '立场', '角度', '层面', '水平', '程度', '范围', '规模', '大小', '多少', '长短', '高低', '深浅', '粗细', '厚薄', '宽窄', '远近', '新旧', '好坏', '对错', '真假', '美丑', '善恶', '正邪', '是非', '黑白', '红绿', '蓝黄', '紫粉', '灰棕', '金银', '铜铁', '木石', '水火', '土气', '风雷', '雨雪', '冰霜', '云雾', '阳光', '月光', '星光', '灯光', '火光', '电光', '声音', '音乐', '歌曲', '舞蹈', '绘画', '书法', '雕塑', '建筑', '设计', '艺术', '文化', '历史', '传统', '现代', '未来', '过去', '现在', '今天', '明天', '昨天', '今年', '明年', '去年', '春天', '夏天', '秋天', '冬天', '一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日', '上午', '下午', '晚上', '夜里', '凌晨', '早晨', '中午', '傍晚', '深夜', '半夜', '整天', '全天', '部分', '全部', '一半', '三分之一', '四分之一', '五分之一', '十分之一', '百分之一', '千分之一', '万分之一', '亿分之一', '无限', '有限', '有限制', '无限制', '有条件', '无条件', '有可能', '不可能', '有希望', '无希望', '有前途', '无前途', '有发展', '无发展', '有进步', '无进步', '有改善', '无改善', '有提高', '无提高', '有提升', '无提升', '有增长', '无增长', '有减少', '无减少', '有下降', '无下降', '有上升', '无上升', '有增加', '无增加', '有减少', '无减少', '有变化', '无变化', '有改变', '无改变', '有改善', '无改善', '有提高', '无提高', '有提升', '无提升', '有增长', '无增长', '有减少', '无减少', '有下降', '无下降', '有上升', '无上升', '有增加', '无增加', '有减少', '无减少', '有变化', '无变化', '有改变', '无改变'
|
||||
]
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
# 初始化停用词
|
||||
if not self.stop_words:
|
||||
self.stop_words = self.DEFAULT_STOP_WORDS.copy()
|
||||
|
||||
# 初始化jieba
|
||||
if self.use_jieba:
|
||||
jieba.initialize()
|
||||
|
||||
def _classify_by_keywords(self, text: str) -> tuple[str, float]:
|
||||
"""基于中文关键词匹配进行分类
|
||||
|
||||
Args:
|
||||
text: 文档文本
|
||||
|
||||
Returns:
|
||||
tuple: (分类结果, 置信度)
|
||||
"""
|
||||
if not self.keyword_rules:
|
||||
return self.default_category, 0.0
|
||||
|
||||
# 对文本进行分词处理
|
||||
if self.use_jieba:
|
||||
words = self._extract_keywords(text)
|
||||
text_processed = " ".join(words)
|
||||
else:
|
||||
text_processed = text
|
||||
|
||||
category_scores = {}
|
||||
|
||||
for category, keywords in self.keyword_rules.items():
|
||||
score = 0
|
||||
total_keywords = len(keywords)
|
||||
|
||||
for keyword in keywords:
|
||||
# 支持模糊匹配
|
||||
if self._fuzzy_match(keyword, text_processed):
|
||||
score += 1
|
||||
|
||||
if total_keywords > 0:
|
||||
confidence = score / total_keywords
|
||||
category_scores[category] = confidence
|
||||
|
||||
if category_scores:
|
||||
best_category = max(category_scores, key=category_scores.get)
|
||||
best_confidence = category_scores[best_category]
|
||||
|
||||
if best_confidence >= self.confidence_threshold:
|
||||
return best_category, best_confidence
|
||||
|
||||
return self.default_category, 0.0
|
||||
|
||||
def _extract_keywords(self, text: str) -> List[str]:
|
||||
"""使用jieba提取关键词
|
||||
|
||||
Args:
|
||||
text: 输入文本
|
||||
|
||||
Returns:
|
||||
List[str]: 关键词列表
|
||||
"""
|
||||
if not self.use_jieba:
|
||||
return [text]
|
||||
|
||||
# 分词
|
||||
words = jieba.lcut(text)
|
||||
|
||||
# 过滤停用词和短词
|
||||
filtered_words = []
|
||||
for word in words:
|
||||
word = word.strip()
|
||||
if (len(word) >= self.min_word_length and
|
||||
word not in self.stop_words and
|
||||
not re.match(r'^[0-9\s\W]+$', word)): # 过滤纯数字和特殊字符
|
||||
filtered_words.append(word)
|
||||
|
||||
return filtered_words
|
||||
|
||||
def _fuzzy_match(self, keyword: str, text: str) -> bool:
|
||||
"""模糊匹配关键词
|
||||
|
||||
Args:
|
||||
keyword: 关键词
|
||||
text: 文本
|
||||
|
||||
Returns:
|
||||
bool: 是否匹配
|
||||
"""
|
||||
# 精确匹配
|
||||
if keyword in text:
|
||||
return True
|
||||
|
||||
# 分词后匹配
|
||||
if self.use_jieba:
|
||||
keyword_words = jieba.lcut(keyword)
|
||||
text_words = jieba.lcut(text)
|
||||
|
||||
# 检查关键词的所有词是否都在文本中
|
||||
keyword_set = set(keyword_words)
|
||||
text_set = set(text_words)
|
||||
|
||||
if keyword_set.issubset(text_set):
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
def _build_classification_prompt(self, text: str) -> str:
|
||||
"""构建中文LLM分类提示
|
||||
|
||||
Args:
|
||||
text: 文档文本
|
||||
|
||||
Returns:
|
||||
str: 分类提示
|
||||
"""
|
||||
categories_str = "、".join(self.categories)
|
||||
|
||||
prompt = f"""请对以下中文文档进行分类。
|
||||
|
||||
可选分类类别:{categories_str}
|
||||
|
||||
文档内容:
|
||||
{text[:2000]}
|
||||
|
||||
请仔细分析文档内容,选择最合适的分类。请按照以下JSON格式返回分类结果:
|
||||
{{
|
||||
"category": "分类结果",
|
||||
"confidence": 0.95,
|
||||
"reason": "分类理由(简要说明为什么选择这个分类)"
|
||||
}}
|
||||
|
||||
如果文档内容无法明确分类,请选择"{self.default_category}"。
|
||||
请确保分类结果准确,置信度要合理。
|
||||
"""
|
||||
return prompt
|
||||
|
||||
def add_chinese_keyword_rule(self, category: str, keywords: List[str]) -> None:
|
||||
"""添加中文关键词分类规则
|
||||
|
||||
Args:
|
||||
category: 分类类别
|
||||
keywords: 中文关键词列表
|
||||
"""
|
||||
# 对关键词进行预处理
|
||||
processed_keywords = []
|
||||
for keyword in keywords:
|
||||
if self.use_jieba:
|
||||
# 使用jieba分词处理关键词
|
||||
words = jieba.lcut(keyword)
|
||||
processed_keywords.extend([w for w in words if len(w) >= self.min_word_length])
|
||||
else:
|
||||
processed_keywords.append(keyword)
|
||||
|
||||
self.add_keyword_rule(category, processed_keywords)
|
||||
|
||||
def add_chinese_regex_rule(self, category: str, pattern: str) -> None:
|
||||
"""添加中文正则表达式分类规则
|
||||
|
||||
Args:
|
||||
category: 分类类别
|
||||
pattern: 中文正则表达式模式
|
||||
"""
|
||||
self.add_regex_rule(category, pattern)
|
||||
|
||||
def get_text_statistics(self, text: str) -> Dict[str, Any]:
|
||||
"""获取文本统计信息
|
||||
|
||||
Args:
|
||||
text: 输入文本
|
||||
|
||||
Returns:
|
||||
Dict: 文本统计信息
|
||||
"""
|
||||
if self.use_jieba:
|
||||
words = self._extract_keywords(text)
|
||||
word_count = Counter(words)
|
||||
|
||||
return {
|
||||
"total_chars": len(text),
|
||||
"total_words": len(words),
|
||||
"unique_words": len(word_count),
|
||||
"most_common_words": word_count.most_common(10),
|
||||
"avg_word_length": sum(len(w) for w in words) / len(words) if words else 0
|
||||
}
|
||||
else:
|
||||
return {
|
||||
"total_chars": len(text),
|
||||
"total_words": len(text.split()),
|
||||
"unique_words": len(set(text.split())),
|
||||
"most_common_words": Counter(text.split()).most_common(10),
|
||||
"avg_word_length": len(text) / len(text.split()) if text.split() else 0
|
||||
}
|
||||
|
||||
def classify_by_content_type(self, text: str) -> str:
|
||||
"""根据内容类型进行基础分类
|
||||
|
||||
Args:
|
||||
text: 输入文本
|
||||
|
||||
Returns:
|
||||
str: 内容类型分类
|
||||
"""
|
||||
# 检测文档类型的关键词
|
||||
type_keywords = {
|
||||
"技术文档": ["代码", "API", "接口", "函数", "方法", "类", "模块", "配置", "安装", "部署", "调试", "错误", "异常", "日志"],
|
||||
"学术论文": ["摘要", "引言", "方法", "实验", "结果", "讨论", "结论", "参考文献", "引用", "研究", "分析", "数据"],
|
||||
"新闻资讯": ["报道", "消息", "新闻", "事件", "发生", "时间", "地点", "人物", "原因", "影响", "结果"],
|
||||
"商业报告": ["报告", "分析", "数据", "统计", "趋势", "预测", "建议", "策略", "市场", "销售", "收入", "利润"],
|
||||
"法律文档": ["法律", "法规", "条例", "条款", "权利", "义务", "责任", "合同", "协议", "争议", "诉讼"],
|
||||
"教育材料": ["学习", "教学", "课程", "教材", "练习", "考试", "作业", "知识点", "概念", "原理", "方法"],
|
||||
"医疗文档": ["疾病", "症状", "诊断", "治疗", "药物", "手术", "检查", "化验", "病历", "处方", "康复"],
|
||||
"其他": []
|
||||
}
|
||||
|
||||
text_lower = text.lower()
|
||||
max_score = 0
|
||||
best_type = "其他"
|
||||
|
||||
for doc_type, keywords in type_keywords.items():
|
||||
if doc_type == "其他":
|
||||
continue
|
||||
|
||||
score = sum(1 for keyword in keywords if keyword in text_lower)
|
||||
if score > max_score:
|
||||
max_score = score
|
||||
best_type = doc_type
|
||||
|
||||
return best_type
|
||||
+257
@@ -0,0 +1,257 @@
|
||||
name: 'chinese_document_classifier'
|
||||
description: '中文文档智能分类器,支持多种中文分类策略'
|
||||
strategy: 'keyword_matching'
|
||||
confidence_threshold: 0.7
|
||||
default_category: '未分类'
|
||||
llm_name: null
|
||||
use_jieba: true
|
||||
min_word_length: 2
|
||||
similarity_threshold: 0.6
|
||||
|
||||
categories:
|
||||
- '技术文档'
|
||||
- '学术论文'
|
||||
- '新闻资讯'
|
||||
- '商业报告'
|
||||
- '法律文档'
|
||||
- '教育材料'
|
||||
- '医疗文档'
|
||||
- '其他'
|
||||
|
||||
# 中文关键词分类规则
|
||||
keyword_rules:
|
||||
技术文档:
|
||||
- '代码'
|
||||
- 'API'
|
||||
- '接口'
|
||||
- '函数'
|
||||
- '方法'
|
||||
- '类'
|
||||
- '模块'
|
||||
- '配置'
|
||||
- '安装'
|
||||
- '部署'
|
||||
- '调试'
|
||||
- '错误'
|
||||
- '异常'
|
||||
- '日志'
|
||||
- '编程'
|
||||
- '开发'
|
||||
- '软件'
|
||||
- '系统'
|
||||
- '数据库'
|
||||
- '算法'
|
||||
- '程序'
|
||||
- '技术'
|
||||
- '实现'
|
||||
- '架构'
|
||||
- '框架'
|
||||
|
||||
学术论文:
|
||||
- '摘要'
|
||||
- '引言'
|
||||
- '方法'
|
||||
- '实验'
|
||||
- '结果'
|
||||
- '讨论'
|
||||
- '结论'
|
||||
- '参考文献'
|
||||
- '引用'
|
||||
- '研究'
|
||||
- '分析'
|
||||
- '数据'
|
||||
- '论文'
|
||||
- '学术'
|
||||
- '理论'
|
||||
- '模型'
|
||||
- '假设'
|
||||
- '验证'
|
||||
- '统计'
|
||||
- '显著性'
|
||||
- '科学'
|
||||
- '实验'
|
||||
- '观察'
|
||||
- '测量'
|
||||
|
||||
新闻资讯:
|
||||
- '报道'
|
||||
- '消息'
|
||||
- '新闻'
|
||||
- '事件'
|
||||
- '发生'
|
||||
- '时间'
|
||||
- '地点'
|
||||
- '人物'
|
||||
- '原因'
|
||||
- '影响'
|
||||
- '结果'
|
||||
- '记者'
|
||||
- '采访'
|
||||
- '现场'
|
||||
- '突发'
|
||||
- '最新'
|
||||
- '今日'
|
||||
- '昨日'
|
||||
- '明天'
|
||||
- '发布'
|
||||
- '宣布'
|
||||
- '透露'
|
||||
- '透露'
|
||||
|
||||
商业报告:
|
||||
- '报告'
|
||||
- '分析'
|
||||
- '数据'
|
||||
- '统计'
|
||||
- '趋势'
|
||||
- '预测'
|
||||
- '建议'
|
||||
- '策略'
|
||||
- '市场'
|
||||
- '销售'
|
||||
- '收入'
|
||||
- '利润'
|
||||
- '财务'
|
||||
- '预算'
|
||||
- '投资'
|
||||
- '收益'
|
||||
- '成本'
|
||||
- '风险'
|
||||
- '机会'
|
||||
- '业务'
|
||||
- '经营'
|
||||
- '管理'
|
||||
- '决策'
|
||||
|
||||
法律文档:
|
||||
- '法律'
|
||||
- '法规'
|
||||
- '条例'
|
||||
- '条款'
|
||||
- '权利'
|
||||
- '义务'
|
||||
- '责任'
|
||||
- '合同'
|
||||
- '协议'
|
||||
- '争议'
|
||||
- '诉讼'
|
||||
- '法院'
|
||||
- '判决'
|
||||
- '律师'
|
||||
- '当事人'
|
||||
- '证据'
|
||||
- '证人'
|
||||
- '辩护'
|
||||
- '上诉'
|
||||
- '司法'
|
||||
- '审判'
|
||||
- '裁决'
|
||||
- '执行'
|
||||
|
||||
教育材料:
|
||||
- '学习'
|
||||
- '教学'
|
||||
- '课程'
|
||||
- '教材'
|
||||
- '练习'
|
||||
- '考试'
|
||||
- '作业'
|
||||
- '知识点'
|
||||
- '概念'
|
||||
- '原理'
|
||||
- '方法'
|
||||
- '教育'
|
||||
- '培训'
|
||||
- '指导'
|
||||
- '说明'
|
||||
- '步骤'
|
||||
- '示例'
|
||||
- '习题'
|
||||
- '答案'
|
||||
- '学生'
|
||||
- '老师'
|
||||
- '课堂'
|
||||
- '课程'
|
||||
|
||||
医疗文档:
|
||||
- '疾病'
|
||||
- '症状'
|
||||
- '诊断'
|
||||
- '治疗'
|
||||
- '药物'
|
||||
- '手术'
|
||||
- '检查'
|
||||
- '化验'
|
||||
- '病历'
|
||||
- '处方'
|
||||
- '康复'
|
||||
- '患者'
|
||||
- '医生'
|
||||
- '医院'
|
||||
- '护理'
|
||||
- '健康'
|
||||
- '医疗'
|
||||
- '临床'
|
||||
- '病理'
|
||||
- '医学'
|
||||
- '生理'
|
||||
- '心理'
|
||||
- '康复'
|
||||
|
||||
# 中文正则表达式分类规则
|
||||
regex_rules:
|
||||
技术文档: '(代码|API|接口|函数|方法|类|模块|配置|安装|部署|调试|错误|异常|日志|编程|开发|软件|系统|数据库|算法|程序|技术|实现|架构|框架)'
|
||||
学术论文: '(摘要|引言|方法|实验|结果|讨论|结论|参考文献|引用|研究|分析|数据|论文|学术|理论|模型|假设|验证|统计|显著性|科学|实验|观察|测量)'
|
||||
新闻资讯: '(报道|消息|新闻|事件|发生|时间|地点|人物|原因|影响|结果|记者|采访|现场|突发|最新|今日|昨日|明天|发布|宣布|透露)'
|
||||
商业报告: '(报告|分析|数据|统计|趋势|预测|建议|策略|市场|销售|收入|利润|财务|预算|投资|收益|成本|风险|机会|业务|经营|管理|决策)'
|
||||
法律文档: '(法律|法规|条例|条款|权利|义务|责任|合同|协议|争议|诉讼|法院|判决|律师|当事人|证据|证人|辩护|上诉|司法|审判|裁决|执行)'
|
||||
教育材料: '(学习|教学|课程|教材|练习|考试|作业|知识点|概念|原理|方法|教育|培训|指导|说明|步骤|示例|习题|答案|学生|老师|课堂|课程)'
|
||||
医疗文档: '(疾病|症状|诊断|治疗|药物|手术|检查|化验|病历|处方|康复|患者|医生|医院|护理|健康|医疗|临床|病理|医学|生理|心理|康复)'
|
||||
|
||||
# 停用词列表(部分)
|
||||
stop_words:
|
||||
- '的'
|
||||
- '了'
|
||||
- '在'
|
||||
- '是'
|
||||
- '我'
|
||||
- '有'
|
||||
- '和'
|
||||
- '就'
|
||||
- '不'
|
||||
- '人'
|
||||
- '都'
|
||||
- '一'
|
||||
- '一个'
|
||||
- '上'
|
||||
- '也'
|
||||
- '很'
|
||||
- '到'
|
||||
- '说'
|
||||
- '要'
|
||||
- '去'
|
||||
- '你'
|
||||
- '会'
|
||||
- '着'
|
||||
- '没有'
|
||||
- '看'
|
||||
- '好'
|
||||
- '自己'
|
||||
- '这'
|
||||
- '那'
|
||||
- '里'
|
||||
- '来'
|
||||
- '下'
|
||||
- '过'
|
||||
- '他'
|
||||
- '她'
|
||||
- '它'
|
||||
- '们'
|
||||
|
||||
classification_key: 'classification'
|
||||
confidence_key: 'classification_confidence'
|
||||
|
||||
metadata:
|
||||
type: 'DOC_PROCESSOR'
|
||||
module: 'agentuniverse.agent.action.knowledge.doc_processor.chinese_document_classifier'
|
||||
class: 'ChineseDocumentClassifier'
|
||||
@@ -0,0 +1,35 @@
|
||||
# Document Classifier App Configuration
|
||||
|
||||
[APP]
|
||||
name = "document_classifier_app"
|
||||
version = "1.0.0"
|
||||
description = "文档分类器应用示例"
|
||||
|
||||
[CORE_PACKAGE]
|
||||
doc_processor = ['agentuniverse.agent.action.knowledge.doc_processor']
|
||||
|
||||
[LLM]
|
||||
default_llm = "openai"
|
||||
llm_list = ["openai", "claude", "qwen"]
|
||||
|
||||
[LLM.openai]
|
||||
api_key = "your_openai_api_key_here"
|
||||
model_name = "gpt-4"
|
||||
temperature = 0.1
|
||||
max_tokens = 2000
|
||||
|
||||
[LLM.claude]
|
||||
api_key = "your_claude_api_key_here"
|
||||
model_name = "claude-3-sonnet-20240229"
|
||||
temperature = 0.1
|
||||
max_tokens = 2000
|
||||
|
||||
[LLM.qwen]
|
||||
api_key = "your_qwen_api_key_here"
|
||||
model_name = "qwen-max"
|
||||
temperature = 0.1
|
||||
max_tokens = 2000
|
||||
|
||||
[LOG]
|
||||
level = "INFO"
|
||||
format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
# DocumentClassifier 文档分类器
|
||||
|
||||
DocumentClassifier是agentUniverse框架中的文档分类组件,提供智能文档分类功能,支持多种分类策略和中文文档处理。
|
||||
|
||||
## 功能特性
|
||||
|
||||
### 基础功能
|
||||
- **多种分类策略**:关键词匹配、正则表达式、LLM分类、混合策略
|
||||
- **灵活配置**:支持自定义分类规则和类别
|
||||
- **批量处理**:高效处理大量文档
|
||||
- **分类统计**:提供详细的分类结果统计
|
||||
|
||||
### 中文优化
|
||||
- **jieba分词**:支持中文分词和关键词提取
|
||||
- **停用词过滤**:自动过滤中文停用词
|
||||
- **模糊匹配**:支持中文关键词模糊匹配
|
||||
- **内容类型识别**:自动识别文档内容类型
|
||||
|
||||
## 使用方法
|
||||
|
||||
### 基础分类器
|
||||
|
||||
```python
|
||||
from agentuniverse.agent.action.knowledge.store.document import Document
|
||||
from examples.third_party_examples.tools.document_classifier_tool.document_classifier import DocumentClassifier
|
||||
|
||||
# 创建分类器
|
||||
classifier = DocumentClassifier()
|
||||
|
||||
# 设置分类类别
|
||||
classifier.set_categories(['技术文档', '学术论文', '新闻资讯', '其他'])
|
||||
|
||||
# 添加关键词规则
|
||||
classifier.add_keyword_rule('技术文档', ['代码', '编程', 'API', '函数'])
|
||||
|
||||
# 分类文档
|
||||
doc = Document(text="这是一个Python编程教程")
|
||||
classified_doc = classifier._classify_document(doc)
|
||||
```
|
||||
|
||||
### 中文分类器
|
||||
|
||||
```python
|
||||
from examples.third_party_examples.tools.document_classifier_tool.chinese_document_classifier import
|
||||
ChineseDocumentClassifier
|
||||
|
||||
# 创建中文分类器
|
||||
classifier = ChineseDocumentClassifier()
|
||||
|
||||
# 添加中文关键词规则
|
||||
classifier.add_chinese_keyword_rule('技术文档', ['代码', '编程', 'API', '函数', '技术'])
|
||||
```
|
||||
|
||||
## 配置说明
|
||||
|
||||
### 基础配置
|
||||
|
||||
```yaml
|
||||
name: 'document_classifier'
|
||||
strategy: 'keyword_matching'
|
||||
confidence_threshold: 0.7
|
||||
default_category: '未分类'
|
||||
categories:
|
||||
- '技术文档'
|
||||
- '学术论文'
|
||||
- '新闻资讯'
|
||||
keyword_rules:
|
||||
技术文档:
|
||||
- '代码'
|
||||
- '编程'
|
||||
- 'API'
|
||||
```
|
||||
|
||||
### 中文配置
|
||||
|
||||
```yaml
|
||||
name: 'chinese_document_classifier'
|
||||
use_jieba: true
|
||||
min_word_length: 2
|
||||
similarity_threshold: 0.6
|
||||
```
|
||||
|
||||
## 分类策略
|
||||
|
||||
1. **关键词匹配**:基于预定义关键词进行匹配
|
||||
2. **正则表达式**:使用正则表达式进行模式匹配
|
||||
3. **LLM分类**:使用大语言模型进行智能分类
|
||||
4. **混合策略**:结合多种分类策略
|
||||
|
||||
## 高级功能
|
||||
|
||||
- 文本统计信息获取
|
||||
- 内容类型自动识别
|
||||
- 分类结果统计摘要
|
||||
- 自定义停用词配置
|
||||
|
||||
更多详细信息请参考示例应用:`examples/sample_apps/document_classifier_app/`
|
||||
@@ -0,0 +1,396 @@
|
||||
# !/usr/bin/env python3
|
||||
# -*- coding:utf-8 -*-
|
||||
|
||||
# @Time : 2024/12/19 10:00
|
||||
# @Author : AI Assistant
|
||||
# @Email : assistant@agentuniverse.ai
|
||||
# @FileName: document_classifier.py
|
||||
|
||||
import re
|
||||
import json
|
||||
from abc import abstractmethod
|
||||
from typing import List, Optional, Dict, Any, Set, Union
|
||||
from enum import Enum
|
||||
|
||||
from agentuniverse.agent.action.knowledge.store.query import Query
|
||||
from agentuniverse.agent.action.knowledge.store.document import Document
|
||||
from agentuniverse.agent.action.knowledge.doc_processor.doc_processor import DocProcessor
|
||||
from agentuniverse.llm.llm_manager import LLMManager
|
||||
|
||||
|
||||
class ClassificationStrategy(Enum):
|
||||
"""文档分类策略枚举"""
|
||||
KEYWORD_MATCHING = "keyword_matching" # 关键词匹配
|
||||
REGEX_PATTERN = "regex_pattern" # 正则表达式匹配
|
||||
LLM_CLASSIFICATION = "llm_classification" # 大语言模型分类
|
||||
HYBRID = "hybrid" # 混合策略
|
||||
|
||||
|
||||
class DocumentClassifier(DocProcessor):
|
||||
"""文档分类器基类
|
||||
|
||||
提供多种文档分类策略,支持基于关键词、正则表达式、LLM等方法的文档自动分类。
|
||||
分类结果将存储在文档的metadata中,便于后续检索和处理。
|
||||
|
||||
Attributes:
|
||||
categories: 分类类别列表
|
||||
strategy: 分类策略
|
||||
confidence_threshold: 置信度阈值
|
||||
default_category: 默认分类
|
||||
llm_name: 用于LLM分类的模型名称
|
||||
"""
|
||||
|
||||
component_type = DocProcessor.component_type
|
||||
name: Optional[str] = "document_classifier"
|
||||
description: Optional[str] = "智能文档分类器,支持多种分类策略"
|
||||
|
||||
# 分类配置
|
||||
categories: List[str] = []
|
||||
strategy: ClassificationStrategy = ClassificationStrategy.KEYWORD_MATCHING
|
||||
confidence_threshold: float = 0.7
|
||||
default_category: str = "未分类"
|
||||
llm_name: Optional[str] = None
|
||||
|
||||
# 关键词分类规则
|
||||
keyword_rules: Dict[str, List[str]] = {}
|
||||
|
||||
# 正则表达式分类规则
|
||||
regex_rules: Dict[str, str] = {}
|
||||
|
||||
# 分类结果存储键名
|
||||
classification_key: str = "classification"
|
||||
confidence_key: str = "classification_confidence"
|
||||
|
||||
class Config:
|
||||
arbitrary_types_allowed = True
|
||||
|
||||
def _process_docs(self, origin_docs: List[Document], query: Query = None) -> List[Document]:
|
||||
"""处理文档列表,为每个文档添加分类信息
|
||||
|
||||
Args:
|
||||
origin_docs: 原始文档列表
|
||||
query: 查询对象(可选)
|
||||
|
||||
Returns:
|
||||
List[Document]: 处理后的文档列表,包含分类信息
|
||||
"""
|
||||
processed_docs = []
|
||||
|
||||
for doc in origin_docs:
|
||||
# 对单个文档进行分类
|
||||
classified_doc = self._classify_document(doc)
|
||||
processed_docs.append(classified_doc)
|
||||
|
||||
return processed_docs
|
||||
|
||||
def _classify_document(self, document: Document) -> Document:
|
||||
"""对单个文档进行分类
|
||||
|
||||
Args:
|
||||
document: 待分类的文档
|
||||
|
||||
Returns:
|
||||
Document: 包含分类信息的文档
|
||||
"""
|
||||
# 确保metadata存在
|
||||
if document.metadata is None:
|
||||
document.metadata = {}
|
||||
|
||||
# 获取文档文本
|
||||
text = document.text or ""
|
||||
|
||||
# 根据策略进行分类
|
||||
if self.strategy == ClassificationStrategy.KEYWORD_MATCHING:
|
||||
category, confidence = self._classify_by_keywords(text)
|
||||
elif self.strategy == ClassificationStrategy.REGEX_PATTERN:
|
||||
category, confidence = self._classify_by_regex(text)
|
||||
elif self.strategy == ClassificationStrategy.LLM_CLASSIFICATION:
|
||||
category, confidence = self._classify_by_llm(text)
|
||||
elif self.strategy == ClassificationStrategy.HYBRID:
|
||||
category, confidence = self._classify_by_hybrid(text)
|
||||
else:
|
||||
category, confidence = self.default_category, 0.0
|
||||
|
||||
# 存储分类结果
|
||||
document.metadata[self.classification_key] = category
|
||||
document.metadata[self.confidence_key] = confidence
|
||||
|
||||
# 将分类结果添加到keywords中
|
||||
if category != self.default_category:
|
||||
document.keywords.add(f"分类:{category}")
|
||||
|
||||
return document
|
||||
|
||||
def _classify_by_keywords(self, text: str) -> tuple[str, float]:
|
||||
"""基于关键词匹配进行分类
|
||||
|
||||
Args:
|
||||
text: 文档文本
|
||||
|
||||
Returns:
|
||||
tuple: (分类结果, 置信度)
|
||||
"""
|
||||
if not self.keyword_rules:
|
||||
return self.default_category, 0.0
|
||||
|
||||
text_lower = text.lower()
|
||||
category_scores = {}
|
||||
|
||||
for category, keywords in self.keyword_rules.items():
|
||||
score = 0
|
||||
total_keywords = len(keywords)
|
||||
|
||||
for keyword in keywords:
|
||||
if keyword.lower() in text_lower:
|
||||
score += 1
|
||||
|
||||
if total_keywords > 0:
|
||||
confidence = score / total_keywords
|
||||
category_scores[category] = confidence
|
||||
|
||||
if category_scores:
|
||||
best_category = max(category_scores, key=category_scores.get)
|
||||
best_confidence = category_scores[best_category]
|
||||
|
||||
if best_confidence >= self.confidence_threshold:
|
||||
return best_category, best_confidence
|
||||
|
||||
return self.default_category, 0.0
|
||||
|
||||
def _classify_by_regex(self, text: str) -> tuple[str, float]:
|
||||
"""基于正则表达式进行分类
|
||||
|
||||
Args:
|
||||
text: 文档文本
|
||||
|
||||
Returns:
|
||||
tuple: (分类结果, 置信度)
|
||||
"""
|
||||
if not self.regex_rules:
|
||||
return self.default_category, 0.0
|
||||
|
||||
for category, pattern in self.regex_rules.items():
|
||||
if re.search(pattern, text, re.IGNORECASE | re.MULTILINE):
|
||||
return category, 1.0
|
||||
|
||||
return self.default_category, 0.0
|
||||
|
||||
def _classify_by_llm(self, text: str) -> tuple[str, float]:
|
||||
"""基于大语言模型进行分类
|
||||
|
||||
Args:
|
||||
text: 文档文本
|
||||
|
||||
Returns:
|
||||
tuple: (分类结果, 置信度)
|
||||
"""
|
||||
if not self.llm_name or not self.categories:
|
||||
return self.default_category, 0.0
|
||||
|
||||
try:
|
||||
# 构建分类提示
|
||||
prompt = self._build_classification_prompt(text)
|
||||
|
||||
# 获取LLM实例
|
||||
llm_manager = LLMManager()
|
||||
llm = llm_manager.get_instance_by_name(self.llm_name)
|
||||
|
||||
if not llm:
|
||||
return self.default_category, 0.0
|
||||
|
||||
# 调用LLM进行分类
|
||||
response = llm.run(prompt)
|
||||
|
||||
# 解析LLM响应
|
||||
category, confidence = self._parse_llm_response(response)
|
||||
|
||||
return category, confidence
|
||||
|
||||
except Exception as e:
|
||||
print(f"LLM分类出错: {e}")
|
||||
return self.default_category, 0.0
|
||||
|
||||
def _classify_by_hybrid(self, text: str) -> tuple[str, float]:
|
||||
"""混合策略分类
|
||||
|
||||
Args:
|
||||
text: 文档文本
|
||||
|
||||
Returns:
|
||||
tuple: (分类结果, 置信度)
|
||||
"""
|
||||
# 先尝试关键词匹配
|
||||
keyword_category, keyword_confidence = self._classify_by_keywords(text)
|
||||
|
||||
# 如果关键词匹配置信度足够高,直接返回
|
||||
if keyword_confidence >= self.confidence_threshold:
|
||||
return keyword_category, keyword_confidence
|
||||
|
||||
# 尝试正则表达式匹配
|
||||
regex_category, regex_confidence = self._classify_by_regex(text)
|
||||
|
||||
# 如果正则表达式匹配成功,返回结果
|
||||
if regex_confidence > 0:
|
||||
return regex_category, regex_confidence
|
||||
|
||||
# 最后尝试LLM分类
|
||||
if self.llm_name:
|
||||
llm_category, llm_confidence = self._classify_by_llm(text)
|
||||
if llm_confidence >= self.confidence_threshold:
|
||||
return llm_category, llm_confidence
|
||||
|
||||
# 如果所有策略都失败,返回关键词匹配结果(即使置信度较低)
|
||||
return keyword_category, keyword_confidence
|
||||
|
||||
def _build_classification_prompt(self, text: str) -> str:
|
||||
"""构建LLM分类提示
|
||||
|
||||
Args:
|
||||
text: 文档文本
|
||||
|
||||
Returns:
|
||||
str: 分类提示
|
||||
"""
|
||||
categories_str = "、".join(self.categories)
|
||||
|
||||
prompt = f"""请对以下文档进行分类。
|
||||
|
||||
可选分类类别:{categories_str}
|
||||
|
||||
文档内容:
|
||||
{text[:2000]} # 限制文本长度避免token过多
|
||||
|
||||
请按照以下JSON格式返回分类结果:
|
||||
{{
|
||||
"category": "分类结果",
|
||||
"confidence": 0.95,
|
||||
"reason": "分类理由"
|
||||
}}
|
||||
|
||||
如果文档内容无法明确分类,请选择"{self.default_category}"。
|
||||
"""
|
||||
return prompt
|
||||
|
||||
def _parse_llm_response(self, response: str) -> tuple[str, float]:
|
||||
"""解析LLM响应
|
||||
|
||||
Args:
|
||||
response: LLM响应文本
|
||||
|
||||
Returns:
|
||||
tuple: (分类结果, 置信度)
|
||||
"""
|
||||
try:
|
||||
# 尝试解析JSON响应
|
||||
if "{" in response and "}" in response:
|
||||
json_start = response.find("{")
|
||||
json_end = response.rfind("}") + 1
|
||||
json_str = response[json_start:json_end]
|
||||
|
||||
result = json.loads(json_str)
|
||||
category = result.get("category", self.default_category)
|
||||
confidence = float(result.get("confidence", 0.0))
|
||||
|
||||
# 验证分类结果是否在有效类别中
|
||||
if category not in self.categories and category != self.default_category:
|
||||
category = self.default_category
|
||||
confidence = 0.0
|
||||
|
||||
return category, confidence
|
||||
|
||||
except (json.JSONDecodeError, ValueError, KeyError) as e:
|
||||
print(f"解析LLM响应失败: {e}")
|
||||
|
||||
# 如果JSON解析失败,尝试简单的文本匹配
|
||||
response_lower = response.lower()
|
||||
for category in self.categories:
|
||||
if category.lower() in response_lower:
|
||||
return category, 0.8 # 给予中等置信度
|
||||
|
||||
return self.default_category, 0.0
|
||||
|
||||
def add_keyword_rule(self, category: str, keywords: List[str]) -> None:
|
||||
"""添加关键词分类规则
|
||||
|
||||
Args:
|
||||
category: 分类类别
|
||||
keywords: 关键词列表
|
||||
"""
|
||||
if category not in self.keyword_rules:
|
||||
self.keyword_rules[category] = []
|
||||
self.keyword_rules[category].extend(keywords)
|
||||
|
||||
# 确保类别在分类列表中
|
||||
if category not in self.categories:
|
||||
self.categories.append(category)
|
||||
|
||||
def add_regex_rule(self, category: str, pattern: str) -> None:
|
||||
"""添加正则表达式分类规则
|
||||
|
||||
Args:
|
||||
category: 分类类别
|
||||
pattern: 正则表达式模式
|
||||
"""
|
||||
self.regex_rules[category] = pattern
|
||||
|
||||
# 确保类别在分类列表中
|
||||
if category not in self.categories:
|
||||
self.categories.append(category)
|
||||
|
||||
def set_categories(self, categories: List[str]) -> None:
|
||||
"""设置分类类别列表
|
||||
|
||||
Args:
|
||||
categories: 分类类别列表
|
||||
"""
|
||||
self.categories = categories
|
||||
|
||||
def get_classification_summary(self, documents: List[Document]) -> Dict[str, Any]:
|
||||
"""获取分类结果统计摘要
|
||||
|
||||
Args:
|
||||
documents: 已分类的文档列表
|
||||
|
||||
Returns:
|
||||
Dict: 分类统计摘要
|
||||
"""
|
||||
summary = {
|
||||
"total_documents": len(documents),
|
||||
"category_counts": {},
|
||||
"confidence_stats": {
|
||||
"average": 0.0,
|
||||
"min": 1.0,
|
||||
"max": 0.0
|
||||
},
|
||||
"unclassified_count": 0
|
||||
}
|
||||
|
||||
total_confidence = 0.0
|
||||
confidence_count = 0
|
||||
|
||||
for doc in documents:
|
||||
if doc.metadata:
|
||||
category = doc.metadata.get(self.classification_key, self.default_category)
|
||||
confidence = doc.metadata.get(self.confidence_key, 0.0)
|
||||
|
||||
# 统计分类数量
|
||||
if category not in summary["category_counts"]:
|
||||
summary["category_counts"][category] = 0
|
||||
summary["category_counts"][category] += 1
|
||||
|
||||
# 统计置信度
|
||||
if confidence > 0:
|
||||
total_confidence += confidence
|
||||
confidence_count += 1
|
||||
summary["confidence_stats"]["min"] = min(summary["confidence_stats"]["min"], confidence)
|
||||
summary["confidence_stats"]["max"] = max(summary["confidence_stats"]["max"], confidence)
|
||||
|
||||
# 统计未分类文档
|
||||
if category == self.default_category:
|
||||
summary["unclassified_count"] += 1
|
||||
|
||||
# 计算平均置信度
|
||||
if confidence_count > 0:
|
||||
summary["confidence_stats"]["average"] = total_confidence / confidence_count
|
||||
|
||||
return summary
|
||||
+185
@@ -0,0 +1,185 @@
|
||||
name: 'document_classifier'
|
||||
description: '智能文档分类器,支持多种分类策略'
|
||||
strategy: 'keyword_matching' # keyword_matching, regex_pattern, llm_classification, hybrid
|
||||
confidence_threshold: 0.7
|
||||
default_category: '未分类'
|
||||
llm_name: null # 用于LLM分类的模型名称,如 'gpt-4', 'claude-3' 等
|
||||
categories:
|
||||
- '技术文档'
|
||||
- '学术论文'
|
||||
- '新闻资讯'
|
||||
- '商业报告'
|
||||
- '法律文档'
|
||||
- '教育材料'
|
||||
- '医疗文档'
|
||||
- '其他'
|
||||
|
||||
# 关键词分类规则
|
||||
keyword_rules:
|
||||
技术文档:
|
||||
- '代码'
|
||||
- 'API'
|
||||
- '接口'
|
||||
- '函数'
|
||||
- '方法'
|
||||
- '类'
|
||||
- '模块'
|
||||
- '配置'
|
||||
- '安装'
|
||||
- '部署'
|
||||
- '调试'
|
||||
- '错误'
|
||||
- '异常'
|
||||
- '日志'
|
||||
- '编程'
|
||||
- '开发'
|
||||
- '软件'
|
||||
- '系统'
|
||||
- '数据库'
|
||||
- '算法'
|
||||
|
||||
学术论文:
|
||||
- '摘要'
|
||||
- '引言'
|
||||
- '方法'
|
||||
- '实验'
|
||||
- '结果'
|
||||
- '讨论'
|
||||
- '结论'
|
||||
- '参考文献'
|
||||
- '引用'
|
||||
- '研究'
|
||||
- '分析'
|
||||
- '数据'
|
||||
- '论文'
|
||||
- '学术'
|
||||
- '理论'
|
||||
- '模型'
|
||||
- '假设'
|
||||
- '验证'
|
||||
- '统计'
|
||||
- '显著性'
|
||||
|
||||
新闻资讯:
|
||||
- '报道'
|
||||
- '消息'
|
||||
- '新闻'
|
||||
- '事件'
|
||||
- '发生'
|
||||
- '时间'
|
||||
- '地点'
|
||||
- '人物'
|
||||
- '原因'
|
||||
- '影响'
|
||||
- '结果'
|
||||
- '记者'
|
||||
- '采访'
|
||||
- '现场'
|
||||
- '突发'
|
||||
- '最新'
|
||||
- '今日'
|
||||
- '昨日'
|
||||
- '明天'
|
||||
|
||||
商业报告:
|
||||
- '报告'
|
||||
- '分析'
|
||||
- '数据'
|
||||
- '统计'
|
||||
- '趋势'
|
||||
- '预测'
|
||||
- '建议'
|
||||
- '策略'
|
||||
- '市场'
|
||||
- '销售'
|
||||
- '收入'
|
||||
- '利润'
|
||||
- '财务'
|
||||
- '预算'
|
||||
- '投资'
|
||||
- '收益'
|
||||
- '成本'
|
||||
- '风险'
|
||||
- '机会'
|
||||
|
||||
法律文档:
|
||||
- '法律'
|
||||
- '法规'
|
||||
- '条例'
|
||||
- '条款'
|
||||
- '权利'
|
||||
- '义务'
|
||||
- '责任'
|
||||
- '合同'
|
||||
- '协议'
|
||||
- '争议'
|
||||
- '诉讼'
|
||||
- '法院'
|
||||
- '判决'
|
||||
- '律师'
|
||||
- '当事人'
|
||||
- '证据'
|
||||
- '证人'
|
||||
- '辩护'
|
||||
- '上诉'
|
||||
|
||||
教育材料:
|
||||
- '学习'
|
||||
- '教学'
|
||||
- '课程'
|
||||
- '教材'
|
||||
- '练习'
|
||||
- '考试'
|
||||
- '作业'
|
||||
- '知识点'
|
||||
- '概念'
|
||||
- '原理'
|
||||
- '方法'
|
||||
- '教育'
|
||||
- '培训'
|
||||
- '指导'
|
||||
- '说明'
|
||||
- '步骤'
|
||||
- '示例'
|
||||
- '习题'
|
||||
- '答案'
|
||||
|
||||
医疗文档:
|
||||
- '疾病'
|
||||
- '症状'
|
||||
- '诊断'
|
||||
- '治疗'
|
||||
- '药物'
|
||||
- '手术'
|
||||
- '检查'
|
||||
- '化验'
|
||||
- '病历'
|
||||
- '处方'
|
||||
- '康复'
|
||||
- '患者'
|
||||
- '医生'
|
||||
- '医院'
|
||||
- '护理'
|
||||
- '健康'
|
||||
- '医疗'
|
||||
- '临床'
|
||||
- '病理'
|
||||
|
||||
# 正则表达式分类规则
|
||||
regex_rules:
|
||||
技术文档: '(?i)(代码|API|接口|函数|方法|类|模块|配置|安装|部署|调试|错误|异常|日志|编程|开发|软件|系统|数据库|算法)'
|
||||
学术论文: '(?i)(摘要|引言|方法|实验|结果|讨论|结论|参考文献|引用|研究|分析|数据|论文|学术|理论|模型|假设|验证|统计|显著性)'
|
||||
新闻资讯: '(?i)(报道|消息|新闻|事件|发生|时间|地点|人物|原因|影响|结果|记者|采访|现场|突发|最新|今日|昨日|明天)'
|
||||
商业报告: '(?i)(报告|分析|数据|统计|趋势|预测|建议|策略|市场|销售|收入|利润|财务|预算|投资|收益|成本|风险|机会)'
|
||||
法律文档: '(?i)(法律|法规|条例|条款|权利|义务|责任|合同|协议|争议|诉讼|法院|判决|律师|当事人|证据|证人|辩护|上诉)'
|
||||
教育材料: '(?i)(学习|教学|课程|教材|练习|考试|作业|知识点|概念|原理|方法|教育|培训|指导|说明|步骤|示例|习题|答案)'
|
||||
医疗文档: '(?i)(疾病|症状|诊断|治疗|药物|手术|检查|化验|病历|处方|康复|患者|医生|医院|护理|健康|医疗|临床|病理)'
|
||||
|
||||
# 分类结果存储键名
|
||||
classification_key: 'classification'
|
||||
confidence_key: 'classification_confidence'
|
||||
|
||||
metadata:
|
||||
type: 'DOC_PROCESSOR'
|
||||
module: 'agentuniverse.agent.action.knowledge.doc_processor.document_classifier'
|
||||
class: 'DocumentClassifier'
|
||||
+322
@@ -0,0 +1,322 @@
|
||||
# !/usr/bin/env python3
|
||||
# -*- coding:utf-8 -*-
|
||||
|
||||
# @Time : 2024/12/19 11:00
|
||||
# @Author : AI Assistant
|
||||
# @Email : assistant@agentuniverse.ai
|
||||
# @FileName: document_classifier_demo.py
|
||||
|
||||
"""
|
||||
文档分类器使用示例
|
||||
|
||||
本示例展示了如何使用agentUniverse的文档分类器功能:
|
||||
1. 基础文档分类
|
||||
2. 中文文档分类
|
||||
3. 批量文档处理
|
||||
4. 分类结果统计
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
from typing import List
|
||||
|
||||
# 添加项目根目录到Python路径
|
||||
sys.path.append(os.path.join(os.path.dirname(__file__), '../../../..'))
|
||||
|
||||
from agentuniverse.agent.action.knowledge.store.document import Document
|
||||
from examples.third_party_examples.tools.document_classifier_tool.document_classifier import DocumentClassifier
|
||||
from examples.third_party_examples.tools.document_classifier_tool.chinese_document_classifier import ChineseDocumentClassifier
|
||||
|
||||
|
||||
def create_sample_documents() -> List[Document]:
|
||||
"""创建示例文档"""
|
||||
documents = [
|
||||
Document(
|
||||
text="""
|
||||
Python是一种高级编程语言,具有简洁的语法和强大的功能。
|
||||
它广泛应用于Web开发、数据分析、人工智能等领域。
|
||||
本文档介绍了Python的基本语法、数据类型、控制结构等核心概念。
|
||||
""",
|
||||
metadata={"source": "python_tutorial.txt", "author": "技术团队"}
|
||||
),
|
||||
Document(
|
||||
text="""
|
||||
本研究通过实验方法分析了机器学习算法在文本分类任务中的性能表现。
|
||||
实验结果表明,基于深度学习的模型在准确率方面显著优于传统方法。
|
||||
论文提出了新的注意力机制,有效提升了模型的分类效果。
|
||||
""",
|
||||
metadata={"source": "ml_research.pdf", "author": "研究团队"}
|
||||
),
|
||||
Document(
|
||||
text="""
|
||||
据最新消息,某科技公司今日宣布完成新一轮融资,融资金额达到1亿美元。
|
||||
该轮融资将主要用于产品研发和市场拓展。公司CEO表示,这将有助于
|
||||
加速公司在人工智能领域的布局,提升市场竞争力。
|
||||
""",
|
||||
metadata={"source": "tech_news.txt", "author": "新闻部"}
|
||||
),
|
||||
Document(
|
||||
text="""
|
||||
本季度财务报告显示,公司营业收入同比增长15%,净利润增长20%。
|
||||
主要增长动力来自于新产品的成功推出和市场份额的扩大。
|
||||
预计下季度将继续保持增长态势,全年目标有望超额完成。
|
||||
""",
|
||||
metadata={"source": "q3_report.pdf", "author": "财务部"}
|
||||
),
|
||||
Document(
|
||||
text="""
|
||||
根据《中华人民共和国合同法》相关规定,甲乙双方就软件开发项目
|
||||
达成如下协议:项目周期为6个月,总金额为100万元。
|
||||
甲方负责提供需求文档,乙方负责系统设计和开发实现。
|
||||
""",
|
||||
metadata={"source": "contract.docx", "author": "法务部"}
|
||||
),
|
||||
Document(
|
||||
text="""
|
||||
本课程将系统介绍数据结构与算法的基本概念和实现方法。
|
||||
内容包括:线性表、栈、队列、树、图等数据结构,
|
||||
以及排序、查找、动态规划等经典算法。
|
||||
通过理论学习和编程实践,帮助学生掌握算法设计思想。
|
||||
""",
|
||||
metadata={"source": "algorithm_course.md", "author": "教学部"}
|
||||
),
|
||||
Document(
|
||||
text="""
|
||||
患者主诉:头痛、发热、乏力3天。体格检查:体温38.5℃,血压正常,
|
||||
心肺听诊无异常。实验室检查:白细胞计数升高,中性粒细胞比例增加。
|
||||
初步诊断:上呼吸道感染。建议:多休息,多饮水,口服解热镇痛药。
|
||||
""",
|
||||
metadata={"source": "patient_record.txt", "author": "医生"}
|
||||
)
|
||||
]
|
||||
return documents
|
||||
|
||||
|
||||
def demo_basic_classifier():
|
||||
"""演示基础文档分类器"""
|
||||
print("=" * 60)
|
||||
print("基础文档分类器演示")
|
||||
print("=" * 60)
|
||||
|
||||
# 创建分类器实例
|
||||
classifier = DocumentClassifier()
|
||||
|
||||
# 设置分类类别
|
||||
classifier.set_categories([
|
||||
'技术文档', '学术论文', '新闻资讯', '商业报告',
|
||||
'法律文档', '教育材料', '医疗文档', '其他'
|
||||
])
|
||||
|
||||
# 添加关键词规则
|
||||
classifier.add_keyword_rule('技术文档', [
|
||||
'Python', '编程', '代码', 'API', '接口', '函数', '方法', '类', '模块', '开发'
|
||||
])
|
||||
classifier.add_keyword_rule('学术论文', [
|
||||
'研究', '实验', '分析', '论文', '学术', '理论', '模型', '假设', '验证', '数据'
|
||||
])
|
||||
classifier.add_keyword_rule('新闻资讯', [
|
||||
'消息', '新闻', '事件', '发生', '宣布', '融资', '公司', 'CEO', '市场'
|
||||
])
|
||||
classifier.add_keyword_rule('商业报告', [
|
||||
'报告', '财务', '收入', '利润', '增长', '季度', '预算', '投资', '收益'
|
||||
])
|
||||
classifier.add_keyword_rule('法律文档', [
|
||||
'法律', '法规', '合同', '协议', '权利', '义务', '责任', '争议', '诉讼'
|
||||
])
|
||||
classifier.add_keyword_rule('教育材料', [
|
||||
'课程', '学习', '教学', '教材', '练习', '考试', '学生', '老师', '知识点'
|
||||
])
|
||||
classifier.add_keyword_rule('医疗文档', [
|
||||
'患者', '疾病', '症状', '诊断', '治疗', '药物', '医生', '医院', '健康'
|
||||
])
|
||||
|
||||
# 获取示例文档
|
||||
documents = create_sample_documents()
|
||||
|
||||
# 对文档进行分类
|
||||
classified_docs = classifier.process_docs(documents)
|
||||
|
||||
# 显示分类结果
|
||||
print("\n分类结果:")
|
||||
print("-" * 60)
|
||||
for i, doc in enumerate(classified_docs, 1):
|
||||
classification = doc.metadata.get('classification', '未分类')
|
||||
confidence = doc.metadata.get('classification_confidence', 0.0)
|
||||
source = doc.metadata.get('source', '未知')
|
||||
|
||||
print(f"{i}. 文档: {source}")
|
||||
print(f" 分类: {classification}")
|
||||
print(f" 置信度: {confidence:.2f}")
|
||||
print(f" 内容预览: {doc.text[:50]}...")
|
||||
print()
|
||||
|
||||
# 获取分类统计
|
||||
summary = classifier.get_classification_summary(classified_docs)
|
||||
print("分类统计摘要:")
|
||||
print("-" * 60)
|
||||
print(f"总文档数: {summary['total_documents']}")
|
||||
print(f"未分类文档数: {summary['unclassified_count']}")
|
||||
print(f"平均置信度: {summary['confidence_stats']['average']:.2f}")
|
||||
print(f"最高置信度: {summary['confidence_stats']['max']:.2f}")
|
||||
print(f"最低置信度: {summary['confidence_stats']['min']:.2f}")
|
||||
print("\n各类别文档数量:")
|
||||
for category, count in summary['category_counts'].items():
|
||||
print(f" {category}: {count}")
|
||||
|
||||
|
||||
def demo_chinese_classifier():
|
||||
"""演示中文文档分类器"""
|
||||
print("\n" + "=" * 60)
|
||||
print("中文文档分类器演示")
|
||||
print("=" * 60)
|
||||
|
||||
# 创建中文分类器实例
|
||||
classifier = ChineseDocumentClassifier()
|
||||
|
||||
# 设置分类类别
|
||||
classifier.set_categories([
|
||||
'技术文档', '学术论文', '新闻资讯', '商业报告',
|
||||
'法律文档', '教育材料', '医疗文档', '其他'
|
||||
])
|
||||
|
||||
# 添加中文关键词规则
|
||||
classifier.add_chinese_keyword_rule('技术文档', [
|
||||
'Python', '编程', '代码', 'API', '接口', '函数', '方法', '类', '模块', '开发', '技术', '系统'
|
||||
])
|
||||
classifier.add_chinese_keyword_rule('学术论文', [
|
||||
'研究', '实验', '分析', '论文', '学术', '理论', '模型', '假设', '验证', '数据', '科学', '观察'
|
||||
])
|
||||
classifier.add_chinese_keyword_rule('新闻资讯', [
|
||||
'消息', '新闻', '事件', '发生', '宣布', '融资', '公司', 'CEO', '市场', '报道', '记者'
|
||||
])
|
||||
classifier.add_chinese_keyword_rule('商业报告', [
|
||||
'报告', '财务', '收入', '利润', '增长', '季度', '预算', '投资', '收益', '业务', '经营'
|
||||
])
|
||||
classifier.add_chinese_keyword_rule('法律文档', [
|
||||
'法律', '法规', '合同', '协议', '权利', '义务', '责任', '争议', '诉讼', '法院', '律师'
|
||||
])
|
||||
classifier.add_chinese_keyword_rule('教育材料', [
|
||||
'课程', '学习', '教学', '教材', '练习', '考试', '学生', '老师', '知识点', '教育', '培训'
|
||||
])
|
||||
classifier.add_chinese_keyword_rule('医疗文档', [
|
||||
'患者', '疾病', '症状', '诊断', '治疗', '药物', '医生', '医院', '健康', '医疗', '临床'
|
||||
])
|
||||
|
||||
# 创建中文示例文档
|
||||
chinese_documents = [
|
||||
Document(
|
||||
text="Python是一种高级编程语言,具有简洁的语法和强大的功能。它广泛应用于Web开发、数据分析、人工智能等领域。",
|
||||
metadata={"source": "python教程.txt"}
|
||||
),
|
||||
Document(
|
||||
text="本研究通过实验方法分析了机器学习算法在文本分类任务中的性能表现。实验结果表明,基于深度学习的模型在准确率方面显著优于传统方法。",
|
||||
metadata={"source": "机器学习论文.pdf"}
|
||||
),
|
||||
Document(
|
||||
text="据最新消息,某科技公司今日宣布完成新一轮融资,融资金额达到1亿美元。该轮融资将主要用于产品研发和市场拓展。",
|
||||
metadata={"source": "科技新闻.txt"}
|
||||
),
|
||||
Document(
|
||||
text="本季度财务报告显示,公司营业收入同比增长15%,净利润增长20%。主要增长动力来自于新产品的成功推出。",
|
||||
metadata={"source": "财务报告.pdf"}
|
||||
),
|
||||
Document(
|
||||
text="根据《中华人民共和国合同法》相关规定,甲乙双方就软件开发项目达成如下协议:项目周期为6个月,总金额为100万元。",
|
||||
metadata={"source": "软件开发合同.docx"}
|
||||
),
|
||||
Document(
|
||||
text="本课程将系统介绍数据结构与算法的基本概念和实现方法。内容包括:线性表、栈、队列、树、图等数据结构。",
|
||||
metadata={"source": "算法课程.md"}
|
||||
),
|
||||
Document(
|
||||
text="患者主诉:头痛、发热、乏力3天。体格检查:体温38.5℃,血压正常。初步诊断:上呼吸道感染。",
|
||||
metadata={"source": "病历记录.txt"}
|
||||
)
|
||||
]
|
||||
|
||||
# 对文档进行分类
|
||||
classified_docs = classifier.process_docs(chinese_documents)
|
||||
|
||||
# 显示分类结果
|
||||
print("\n中文文档分类结果:")
|
||||
print("-" * 60)
|
||||
for i, doc in enumerate(classified_docs, 1):
|
||||
classification = doc.metadata.get('classification', '未分类')
|
||||
confidence = doc.metadata.get('classification_confidence', 0.0)
|
||||
source = doc.metadata.get('source', '未知')
|
||||
|
||||
print(f"{i}. 文档: {source}")
|
||||
print(f" 分类: {classification}")
|
||||
print(f" 置信度: {confidence:.2f}")
|
||||
print(f" 内容预览: {doc.text[:50]}...")
|
||||
print()
|
||||
|
||||
# 获取文本统计信息
|
||||
print("文本统计信息:")
|
||||
print("-" * 60)
|
||||
for i, doc in enumerate(classified_docs, 1):
|
||||
stats = classifier.get_text_statistics(doc.text)
|
||||
print(f"文档 {i} ({doc.metadata.get('source', '未知')}):")
|
||||
print(f" 总字符数: {stats['total_chars']}")
|
||||
print(f" 总词数: {stats['total_words']}")
|
||||
print(f" 唯一词数: {stats['unique_words']}")
|
||||
print(f" 平均词长: {stats['avg_word_length']:.2f}")
|
||||
print(f" 高频词: {[word for word, count in stats['most_common_words'][:5]]}")
|
||||
print()
|
||||
|
||||
|
||||
def demo_content_type_classification():
|
||||
"""演示内容类型分类"""
|
||||
print("\n" + "=" * 60)
|
||||
print("内容类型自动分类演示")
|
||||
print("=" * 60)
|
||||
|
||||
classifier = ChineseDocumentClassifier()
|
||||
|
||||
# 测试不同类型的文档
|
||||
test_texts = [
|
||||
"这是一个Python编程教程,介绍了如何使用Python进行Web开发。",
|
||||
"本研究分析了深度学习在自然语言处理中的应用效果。",
|
||||
"今日股市收盘,上证指数上涨2.5%,成交量放大。",
|
||||
"公司第三季度财报显示,净利润同比增长30%。",
|
||||
"根据《民法典》规定,合同双方应当履行各自义务。",
|
||||
"本节课我们将学习数据结构中的二叉树遍历算法。",
|
||||
"患者出现发热、咳嗽等症状,建议进行血常规检查。"
|
||||
]
|
||||
|
||||
print("内容类型自动分类结果:")
|
||||
print("-" * 60)
|
||||
for i, text in enumerate(test_texts, 1):
|
||||
content_type = classifier.classify_by_content_type(text)
|
||||
print(f"{i}. 文本: {text[:30]}...")
|
||||
print(f" 内容类型: {content_type}")
|
||||
print()
|
||||
|
||||
|
||||
def main():
|
||||
"""主函数"""
|
||||
print("agentUniverse 文档分类器演示")
|
||||
print("=" * 60)
|
||||
|
||||
try:
|
||||
# 基础分类器演示
|
||||
demo_basic_classifier()
|
||||
|
||||
# 中文分类器演示
|
||||
demo_chinese_classifier()
|
||||
|
||||
# 内容类型分类演示
|
||||
demo_content_type_classification()
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("演示完成!")
|
||||
print("=" * 60)
|
||||
|
||||
except Exception as e:
|
||||
print(f"演示过程中出现错误: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,4 @@
|
||||
agentuniverse>=0.0.18
|
||||
jieba>=0.42.1
|
||||
pydantic>=2.0.0
|
||||
langchain>=0.1.0
|
||||
@@ -0,0 +1,16 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding:utf-8 -*-
|
||||
|
||||
"""
|
||||
文档分类器演示启动脚本
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
|
||||
# 添加项目根目录到Python路径
|
||||
sys.path.append(os.path.join(os.path.dirname(__file__), '../../../..'))
|
||||
|
||||
if __name__ == "__main__":
|
||||
from document_classifier_demo import main
|
||||
main()
|
||||
@@ -0,0 +1,354 @@
|
||||
# !/usr/bin/env python3
|
||||
# -*- coding:utf-8 -*-
|
||||
|
||||
# @Time : 2024/12/19 11:30
|
||||
# @Author : AI Assistant
|
||||
# @Email : assistant@agentuniverse.ai
|
||||
# @FileName: test_classifier.py
|
||||
|
||||
"""
|
||||
文档分类器测试文件
|
||||
|
||||
测试文档分类器的各种功能:
|
||||
1. 基础分类功能
|
||||
2. 中文分类功能
|
||||
3. 不同策略分类
|
||||
4. 边界情况处理
|
||||
"""
|
||||
|
||||
import unittest
|
||||
import sys
|
||||
import os
|
||||
|
||||
# 添加项目根目录到Python路径
|
||||
sys.path.append(os.path.join(os.path.dirname(__file__), '../../../..'))
|
||||
|
||||
from agentuniverse.agent.action.knowledge.store.document import Document
|
||||
from examples.third_party_examples.tools.document_classifier_tool.document_classifier import (
|
||||
DocumentClassifier,
|
||||
ClassificationStrategy
|
||||
)
|
||||
from examples.third_party_examples.tools.document_classifier_tool.chinese_document_classifier import ChineseDocumentClassifier
|
||||
|
||||
|
||||
class TestDocumentClassifier(unittest.TestCase):
|
||||
"""文档分类器测试类"""
|
||||
|
||||
def setUp(self):
|
||||
"""测试前准备"""
|
||||
self.classifier = DocumentClassifier()
|
||||
self.classifier.set_categories(['技术文档', '学术论文', '新闻资讯', '其他'])
|
||||
|
||||
# 添加测试规则
|
||||
self.classifier.add_keyword_rule('技术文档', ['代码', '编程', 'API', '函数'])
|
||||
self.classifier.add_keyword_rule('学术论文', ['研究', '实验', '分析', '论文'])
|
||||
self.classifier.add_keyword_rule('新闻资讯', ['消息', '新闻', '事件', '报道'])
|
||||
|
||||
self.test_documents = [
|
||||
Document(text="这是一个Python编程教程,介绍了如何使用API和函数。"),
|
||||
Document(text="本研究通过实验分析了机器学习算法的性能。"),
|
||||
Document(text="据最新消息,某公司今日宣布重大事件。"),
|
||||
Document(text="今天天气很好,适合出门散步。") # 应该分类为"其他"
|
||||
]
|
||||
|
||||
def test_keyword_classification(self):
|
||||
"""测试关键词分类"""
|
||||
self.classifier.strategy = ClassificationStrategy.KEYWORD_MATCHING
|
||||
|
||||
classified_docs = self.classifier.process_docs(self.test_documents)
|
||||
|
||||
# 检查第一个文档(技术文档)
|
||||
self.assertEqual(
|
||||
classified_docs[0].metadata['classification'],
|
||||
'技术文档'
|
||||
)
|
||||
self.assertGreater(
|
||||
classified_docs[0].metadata['classification_confidence'],
|
||||
0.5
|
||||
)
|
||||
|
||||
# 检查第二个文档(学术论文)
|
||||
self.assertEqual(
|
||||
classified_docs[1].metadata['classification'],
|
||||
'学术论文'
|
||||
)
|
||||
|
||||
# 检查第三个文档(新闻资讯)
|
||||
self.assertEqual(
|
||||
classified_docs[2].metadata['classification'],
|
||||
'新闻资讯'
|
||||
)
|
||||
|
||||
# 检查第四个文档(其他)
|
||||
self.assertEqual(
|
||||
classified_docs[3].metadata['classification'],
|
||||
'其他'
|
||||
)
|
||||
|
||||
def test_regex_classification(self):
|
||||
"""测试正则表达式分类"""
|
||||
self.classifier.strategy = ClassificationStrategy.REGEX_PATTERN
|
||||
|
||||
# 添加正则表达式规则
|
||||
self.classifier.add_regex_rule('技术文档', r'(代码|编程|API|函数)')
|
||||
self.classifier.add_regex_rule('学术论文', r'(研究|实验|分析|论文)')
|
||||
self.classifier.add_regex_rule('新闻资讯', r'(消息|新闻|事件|报道)')
|
||||
|
||||
classified_docs = self.classifier.process_docs(self.test_documents)
|
||||
|
||||
# 检查分类结果
|
||||
self.assertEqual(
|
||||
classified_docs[0].metadata['classification'],
|
||||
'技术文档'
|
||||
)
|
||||
self.assertEqual(
|
||||
classified_docs[1].metadata['classification'],
|
||||
'学术论文'
|
||||
)
|
||||
self.assertEqual(
|
||||
classified_docs[2].metadata['classification'],
|
||||
'新闻资讯'
|
||||
)
|
||||
|
||||
def test_empty_document(self):
|
||||
"""测试空文档处理"""
|
||||
empty_doc = Document(text="")
|
||||
classified_doc = self.classifier._classify_document(empty_doc)
|
||||
|
||||
self.assertEqual(
|
||||
classified_doc.metadata['classification'],
|
||||
'其他'
|
||||
)
|
||||
self.assertEqual(
|
||||
classified_doc.metadata['classification_confidence'],
|
||||
0.0
|
||||
)
|
||||
|
||||
def test_none_text_document(self):
|
||||
"""测试None文本文档处理"""
|
||||
none_doc = Document(text=None)
|
||||
classified_doc = self.classifier._classify_document(none_doc)
|
||||
|
||||
self.assertEqual(
|
||||
classified_doc.metadata['classification'],
|
||||
'其他'
|
||||
)
|
||||
|
||||
def test_classification_summary(self):
|
||||
"""测试分类统计摘要"""
|
||||
classified_docs = self.classifier.process_docs(self.test_documents)
|
||||
summary = self.classifier.get_classification_summary(classified_docs)
|
||||
|
||||
self.assertEqual(summary['total_documents'], 4)
|
||||
self.assertIn('技术文档', summary['category_counts'])
|
||||
self.assertIn('学术论文', summary['category_counts'])
|
||||
self.assertIn('新闻资讯', summary['category_counts'])
|
||||
self.assertIn('其他', summary['category_counts'])
|
||||
|
||||
def test_add_keyword_rule(self):
|
||||
"""测试添加关键词规则"""
|
||||
initial_count = len(self.classifier.keyword_rules)
|
||||
|
||||
self.classifier.add_keyword_rule('新类别', ['新关键词'])
|
||||
|
||||
self.assertEqual(len(self.classifier.keyword_rules), initial_count + 1)
|
||||
self.assertIn('新类别', self.classifier.keyword_rules)
|
||||
self.assertIn('新类别', self.classifier.categories)
|
||||
|
||||
def test_add_regex_rule(self):
|
||||
"""测试添加正则表达式规则"""
|
||||
initial_count = len(self.classifier.regex_rules)
|
||||
|
||||
self.classifier.add_regex_rule('新类别', r'新正则')
|
||||
|
||||
self.assertEqual(len(self.classifier.regex_rules), initial_count + 1)
|
||||
self.assertIn('新类别', self.classifier.regex_rules)
|
||||
self.assertIn('新类别', self.classifier.categories)
|
||||
|
||||
|
||||
class TestChineseDocumentClassifier(unittest.TestCase):
|
||||
"""中文文档分类器测试类"""
|
||||
|
||||
def setUp(self):
|
||||
"""测试前准备"""
|
||||
self.classifier = ChineseDocumentClassifier()
|
||||
self.classifier.set_categories(['技术文档', '学术论文', '新闻资讯', '其他'])
|
||||
|
||||
# 添加中文关键词规则
|
||||
self.classifier.add_chinese_keyword_rule('技术文档', ['代码', '编程', 'API', '函数', '技术'])
|
||||
self.classifier.add_chinese_keyword_rule('学术论文', ['研究', '实验', '分析', '论文', '学术'])
|
||||
self.classifier.add_chinese_keyword_rule('新闻资讯', ['消息', '新闻', '事件', '报道', '记者'])
|
||||
|
||||
self.chinese_documents = [
|
||||
Document(text="这是一个Python编程教程,介绍了如何使用API和函数进行技术开发。"),
|
||||
Document(text="本研究通过实验分析了机器学习算法的性能,这是一篇学术论文。"),
|
||||
Document(text="据最新消息,某公司今日宣布重大事件,记者现场报道。"),
|
||||
Document(text="今天天气很好,适合出门散步。") # 应该分类为"其他"
|
||||
]
|
||||
|
||||
def test_chinese_keyword_classification(self):
|
||||
"""测试中文关键词分类"""
|
||||
classified_docs = self.classifier.process_docs(self.chinese_documents)
|
||||
|
||||
# 检查第一个文档(技术文档)
|
||||
self.assertEqual(
|
||||
classified_docs[0].metadata['classification'],
|
||||
'技术文档'
|
||||
)
|
||||
|
||||
# 检查第二个文档(学术论文)
|
||||
self.assertEqual(
|
||||
classified_docs[1].metadata['classification'],
|
||||
'学术论文'
|
||||
)
|
||||
|
||||
# 检查第三个文档(新闻资讯)
|
||||
self.assertEqual(
|
||||
classified_docs[2].metadata['classification'],
|
||||
'新闻资讯'
|
||||
)
|
||||
|
||||
# 检查第四个文档(其他)
|
||||
self.assertEqual(
|
||||
classified_docs[3].metadata['classification'],
|
||||
'其他'
|
||||
)
|
||||
|
||||
def test_jieba_keyword_extraction(self):
|
||||
"""测试jieba关键词提取"""
|
||||
text = "这是一个Python编程教程,介绍了如何使用API和函数。"
|
||||
keywords = self.classifier._extract_keywords(text)
|
||||
|
||||
self.assertIsInstance(keywords, list)
|
||||
self.assertGreater(len(keywords), 0)
|
||||
# 检查是否过滤了停用词
|
||||
self.assertNotIn('的', keywords)
|
||||
self.assertNotIn('是', keywords)
|
||||
|
||||
def test_fuzzy_match(self):
|
||||
"""测试模糊匹配"""
|
||||
# 精确匹配
|
||||
self.assertTrue(self.classifier._fuzzy_match('编程', '这是一个编程教程'))
|
||||
|
||||
# 分词匹配
|
||||
self.assertTrue(self.classifier._fuzzy_match('Python编程', '这是一个Python编程教程'))
|
||||
|
||||
# 不匹配
|
||||
self.assertFalse(self.classifier._fuzzy_match('Java', '这是一个Python教程'))
|
||||
|
||||
def test_text_statistics(self):
|
||||
"""测试文本统计"""
|
||||
text = "这是一个Python编程教程,介绍了如何使用API和函数。"
|
||||
stats = self.classifier.get_text_statistics(text)
|
||||
|
||||
self.assertIn('total_chars', stats)
|
||||
self.assertIn('total_words', stats)
|
||||
self.assertIn('unique_words', stats)
|
||||
self.assertIn('most_common_words', stats)
|
||||
self.assertIn('avg_word_length', stats)
|
||||
|
||||
self.assertGreater(stats['total_chars'], 0)
|
||||
self.assertGreater(stats['total_words'], 0)
|
||||
|
||||
def test_content_type_classification(self):
|
||||
"""测试内容类型分类"""
|
||||
# 技术文档
|
||||
tech_text = "这是一个Python编程教程,介绍了如何使用API和函数。"
|
||||
self.assertEqual(
|
||||
self.classifier.classify_by_content_type(tech_text),
|
||||
'技术文档'
|
||||
)
|
||||
|
||||
# 学术论文
|
||||
academic_text = "本研究通过实验分析了机器学习算法的性能。"
|
||||
self.assertEqual(
|
||||
self.classifier.classify_by_content_type(academic_text),
|
||||
'学术论文'
|
||||
)
|
||||
|
||||
# 新闻资讯
|
||||
news_text = "据最新消息,某公司今日宣布重大事件。"
|
||||
self.assertEqual(
|
||||
self.classifier.classify_by_content_type(news_text),
|
||||
'新闻资讯'
|
||||
)
|
||||
|
||||
def test_chinese_regex_classification(self):
|
||||
"""测试中文正则表达式分类"""
|
||||
self.classifier.add_chinese_regex_rule('技术文档', r'(代码|编程|API|函数|技术)')
|
||||
self.classifier.add_chinese_regex_rule('学术论文', r'(研究|实验|分析|论文|学术)')
|
||||
self.classifier.add_chinese_regex_rule('新闻资讯', r'(消息|新闻|事件|报道|记者)')
|
||||
|
||||
self.classifier.strategy = ClassificationStrategy.REGEX_PATTERN
|
||||
|
||||
classified_docs = self.classifier.process_docs(self.chinese_documents)
|
||||
|
||||
# 检查分类结果
|
||||
self.assertEqual(
|
||||
classified_docs[0].metadata['classification'],
|
||||
'技术文档'
|
||||
)
|
||||
self.assertEqual(
|
||||
classified_docs[1].metadata['classification'],
|
||||
'学术论文'
|
||||
)
|
||||
self.assertEqual(
|
||||
classified_docs[2].metadata['classification'],
|
||||
'新闻资讯'
|
||||
)
|
||||
|
||||
|
||||
class TestEdgeCases(unittest.TestCase):
|
||||
"""边界情况测试"""
|
||||
|
||||
def setUp(self):
|
||||
"""测试前准备"""
|
||||
self.classifier = DocumentClassifier()
|
||||
self.classifier.set_categories(['类别1', '类别2'])
|
||||
|
||||
def test_no_categories(self):
|
||||
"""测试无分类类别"""
|
||||
classifier = DocumentClassifier()
|
||||
doc = Document(text="测试文档")
|
||||
classified_doc = classifier._classify_document(doc)
|
||||
|
||||
self.assertEqual(
|
||||
classified_doc.metadata['classification'],
|
||||
'未分类'
|
||||
)
|
||||
|
||||
def test_no_keyword_rules(self):
|
||||
"""测试无关键词规则"""
|
||||
classifier = DocumentClassifier()
|
||||
classifier.set_categories(['类别1', '类别2'])
|
||||
|
||||
doc = Document(text="测试文档")
|
||||
classified_doc = classifier._classify_document(doc)
|
||||
|
||||
self.assertEqual(
|
||||
classified_doc.metadata['classification'],
|
||||
'未分类'
|
||||
)
|
||||
|
||||
def test_very_long_text(self):
|
||||
"""测试超长文本"""
|
||||
long_text = "测试" * 10000 # 20000个字符
|
||||
doc = Document(text=long_text)
|
||||
classified_doc = self.classifier._classify_document(doc)
|
||||
|
||||
# 应该能正常处理,不会出错
|
||||
self.assertIn('classification', classified_doc.metadata)
|
||||
|
||||
def test_special_characters(self):
|
||||
"""测试特殊字符"""
|
||||
special_text = "!@#$%^&*()_+-=[]{}|;':\",./<>?`~"
|
||||
doc = Document(text=special_text)
|
||||
classified_doc = self.classifier._classify_document(doc)
|
||||
|
||||
# 应该能正常处理特殊字符
|
||||
self.assertIn('classification', classified_doc.metadata)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
# 运行测试
|
||||
unittest.main(verbosity=2)
|
||||
Reference in New Issue
Block a user