feat: 项目

This commit is contained in:
李如威 2025-08-08 15:23:53 +08:00
parent 34d4fe61d9
commit af0ac9605b
26 changed files with 274 additions and 872 deletions

View File

@ -1,81 +0,0 @@
# 项目清理完成总结
## 🧹 清理工作完成
已成功删除多余文件,保留必要示例,并更新了文档。
## 📁 当前项目结构
```
base_rag/
├── src/
│ └── base_rag/
│ ├── __init__.py # 包入口
│ └── core.py # 核心BaseRAG类异步版本
├── examples/
│ └── simple_test.py # 基础使用示例
├── FILE_PROCESSING_GUIDE.md # 文件处理功能说明
├── RERANK_GUIDE.md # 重排功能详细说明
├── README.md # 项目说明(已更新)
├── requirements.txt # 依赖列表
├── pyproject.toml # 包配置
└── LICENSE # 许可证
```
## ❌ 已删除的文件
### 文档文件
- `ASYNC_GUIDE.md` - 异步功能使用指南
- `MIGRATION_GUIDE.md` - 迁移指南
### 示例文件
- `examples/async_example.py` - 异步示例和FastAPI集成
- `examples/performance_test.py` - 性能测试脚本
## ✅ 保留的文件
### 核心文件
- `src/base_rag/core.py` - 保留异步版本的核心实现
- `examples/simple_test.py` - 更新为异步版本的基础示例
### 文档文件
- `README.md` - 删除了异步相关说明,保留核心功能介绍
- `FILE_PROCESSING_GUIDE.md` - 更新为异步版本的使用说明
- `RERANK_GUIDE.md` - 重排功能说明(保持不变)
## 📝 主要更新
### README.md
- ❌ 删除了所有异步特性的详细说明
- ❌ 删除了FastAPI集成示例
- ❌ 删除了性能测试结果
- ❌ 删除了迁移指南链接
- ✅ 保留了核心功能介绍
- ✅ 保留了基本配置和使用示例
- ✅ 简化了项目结构说明
### FILE_PROCESSING_GUIDE.md
- ✅ 更新方法签名为async/await形式
- ✅ 更新示例代码使用asyncio
- ✅ 修正了示例文件引用
### examples/simple_test.py
- ✅ 更新为async/await版本
- ✅ 保持简洁的功能演示
- ✅ 测试验证正常工作
## 🎯 当前状态
项目现在保持了异步功能的核心实现,但删除了:
- 复杂的异步使用指南
- 迁移相关的文档
- 性能测试和对比
- FastAPI集成示例
保留了:
- 核心异步RAG功能
- 简单明了的使用示例
- 基础文档说明
- 重排功能指南
项目现在更加精简,专注于核心功能,适合直接使用和学习。

117
DIRECTORY_CLEANUP.md Normal file
View File

@ -0,0 +1,117 @@
# 项目目录整理总结
## 🗂️ 整理前的问题
- 存在多个重复的测试目录:`test_files/`, `test_docs/`, `documents/`
- 测试文件分散在不同位置,管理混乱
- 大量临时测试脚本和数据库文件
- 重复的测试文件和配置
## 🧹 清理操作
### 删除的目录和文件
1. **重复目录**:
- `test_docs/` - 删除
- `documents/` - 删除
2. **临时测试脚本**:
- `create_docx.py`
- `test_docx.py`
- `test_file_formats.py`
- `comprehensive_test.py`
- `final_test.py`
3. **多余数据库文件**:
- `demo_file_status.db`
- `file_status.db`
- `test_status.db`
- `final_test.db`
4. **临时文档**:
- `CLEANUP_SUMMARY.md`
- `TEST_REPORT.md`
5. **重复测试文件**:
- `test_files/test_document.txt`
- `test_files/test_markdown.md`
## 📁 整理后的目录结构
```
base_rag/
├── src/ # 源代码
│ └── base_rag/
│ ├── __init__.py
│ └── core.py
├── examples/ # 示例代码
│ ├── simple_test.py # 基础功能测试
│ └── multi_format_test.py # 多格式文件测试
├── test_files/ # 统一的测试文件目录
│ ├── knowledge.txt # TXT格式测试文件
│ ├── python_basics.txt # Python基础知识
│ ├── web_frameworks.txt # Web框架知识
│ ├── data_science.txt # 数据科学知识
│ ├── python_guide.md # Python指南(MD格式)
│ ├── machine_learning.md # 机器学习(MD格式)
│ └── deep_learning_guide.docx # 深度学习(DOCX格式)
├── chroma_db/ # 向量数据库
├── scripts/ # 构建脚本
├── venv/ # Python虚拟环境
├── README.md # 项目说明
├── requirements.txt # 依赖包
└── pyproject.toml # 项目配置
```
## 🎯 统一的测试配置
### 测试目录统一为 `test_files/`
- 所有测试文件集中在 `test_files/` 目录
- 包含 TXT、MD、DOCX 三种格式的测试文件
- 涵盖不同主题Python、机器学习、深度学习、数据科学
### 数据库统一为 `status.db`
- 使用单一的状态数据库文件
- 避免多个测试脚本创建重复的数据库
### 示例脚本优化
1. **`simple_test.py`** - 基础功能测试
- 测试基本的文件处理和查询功能
- 使用 TXT 格式文件进行测试
2. **`multi_format_test.py`** - 多格式文件测试
- 测试 TXT、MD、DOCX 三种格式
- 验证跨格式查询功能
- 展示异步处理能力
## ✅ 整理效果
1. **目录结构清晰**: 消除了重复目录,统一了测试文件位置
2. **文件管理规范**: 删除了临时和重复文件
3. **测试配置统一**: 所有测试使用相同的目录和数据库配置
4. **代码组织优化**: 保留了两个核心的测试示例
## 🚀 后续测试指南
### 运行基础测试
```bash
cd /Users/liruwei/Documents/code/project/demo/base_rag
python examples/simple_test.py
```
### 运行多格式测试
```bash
cd /Users/liruwei/Documents/code/project/demo/base_rag
python examples/multi_format_test.py
```
### 添加新测试文件
将新的测试文件直接放入 `test_files/` 目录即可,支持的格式:
- `.txt` - 纯文本文件
- `.md` - Markdown文件
- `.docx` - Word文档
现在项目结构更加清晰,便于后续的开发和测试!

View File

@ -1,148 +0,0 @@
# 文件格式支持测试报告
## 测试概述
本次测试验证了 Base RAG 异步库对多种文件格式的支持能力,包括:
- **TXT** - 纯文本文件
- **MD** - Markdown 文件
- **DOCX** - Microsoft Word 文档
## 测试环境
- **Python 版本**: 3.13.0
- **异步框架**: asyncio
- **向量数据库**: ChromaDB
- **嵌入模型**: BAAI/bge-small-zh-v1.5
## 测试结果
### ✅ Markdown 文件 (.md)
**测试文件**:
- `python_guide.md` - Python编程指南
- `machine_learning.md` - 机器学习入门
**测试结果**:
- ✅ 文件解析成功
- ✅ 内容切分正常 (2个文档片段)
- ✅ 向量化存储成功
- ✅ 查询检索正常
**特点**:
- 支持 Markdown 语法解析
- 保留文档结构信息
- 支持代码块、列表、标题等格式
### ✅ Word 文档 (.docx)
**测试文件**:
- `deep_learning_guide.docx` - 深度学习技术指南
**测试结果**:
- ✅ 文件解析成功 (需要 `unstructured` 库)
- ✅ 内容提取正常 (1个文档片段)
- ✅ 向量化存储成功
- ✅ 查询检索正常
**依赖要求**:
```bash
pip install unstructured python-docx
```
**特点**:
- 支持复杂文档格式
- 提取文本内容和基本结构
- 保留标题层次信息
## 异步处理能力
### 🚀 性能优势
1. **非阻塞 I/O**:
- 使用 `aiofiles` 进行异步文件读取
- 使用 `aiosqlite` 进行异步数据库操作
2. **并发处理**:
- 支持同时处理多个文件
- 模型加载使用线程池避免阻塞
3. **内存优化**:
- 流式处理大文件
- 智能缓存管理
### 📊 测试数据
| 文件格式 | 文件大小 | 处理时间 | 文档片段 | 状态 |
|---------|---------|---------|---------|------|
| .md | ~2KB | <1s | 2个 | |
| .md | ~1.5KB | <1s | 2个 | |
| .docx | ~12KB | <2s | 1个 | |
## 查询功能测试
### 跨格式查询
测试了跨不同文件格式的知识检索:
1. **Python语法查询** → 从 Markdown 文件检索
2. **机器学习概念** → 从 Markdown 文件检索
3. **深度学习应用** → 从 Word 文档检索
### 检索质量
- ✅ 语义相似度匹配准确
- ✅ 支持中文查询
- ✅ 返回相关文档来源信息
- ✅ 上下文信息完整
## FastAPI 兼容性
### 异步特性
```python
# 完全兼容 FastAPI 异步路由
@app.post("/query")
async def query_documents(query: str):
result = await rag.query(query)
return {"answer": result}
@app.post("/upload")
async def upload_file(file: UploadFile):
result = await rag.process_file_to_vector_store(file.filename)
return {"status": result}
```
### 并发支持
- ✅ 支持多用户并发查询
- ✅ 异步文件上传处理
- ✅ 无阻塞的文档处理流水线
## 技术总结
### 已实现功能
1. **完全异步化**: 所有 I/O 操作都是异步的
2. **多格式支持**: TXT, MD, DOCX 全支持
3. **智能文档处理**: 自动检测文件类型并选择合适的加载器
4. **向量化存储**: 使用 ChromaDB 进行高效存储
5. **语义检索**: 基于嵌入模型的相似度搜索
### 架构优势
- **模块化设计**: FileManager, ModelManager, BaseRAG 分离关注点
- **配置灵活**: 支持本地模型和 API 模式
- **扩展性强**: 易于添加新的文件格式支持
- **生产就绪**: 适合 FastAPI 等异步 Web 框架
## 结论
🎉 **Base RAG 异步库已成功支持多种文件格式的处理和查询**
- ✅ **文件格式支持**: TXT, MD, DOCX
- ✅ **异步处理**: 完全异步化,适合生产环境
- ✅ **FastAPI 兼容**: 可直接集成到异步 Web 框架
- ✅ **查询质量**: 语义检索准确,支持跨格式查询
- ✅ **性能优化**: 非阻塞 I/O支持高并发
该库现在可以高效地运行在 FastAPI 等异步框架中,为用户提供强大的文档检索和问答能力。

View File

@ -1,174 +0,0 @@
#!/usr/bin/env python3
"""
文件格式支持综合测试 - 测试 txtmddocx 文件
"""
import asyncio
import sys
import os
from pathlib import Path
# 添加项目路径
sys.path.append('/Users/liruwei/Documents/code/project/demo/base_rag/src')
from base_rag.core import BaseRAG
class SimpleRAG(BaseRAG):
"""简单的RAG实现示例"""
async def ingest(self, file_path: str, **kwargs):
"""实现文档导入逻辑"""
return await self.process_file_to_vector_store(file_path, **kwargs)
async def query(self, question: str) -> str:
"""实现简单的查询逻辑"""
docs = await self.similarity_search_with_rerank(question, k=3)
if not docs:
return "抱歉,没有找到相关信息。"
# 显示搜索到的文档来源
sources = []
contexts = []
for doc in docs:
source = doc.metadata.get("source_file", "未知来源")
if source not in sources:
sources.append(source)
contexts.append(doc.page_content.strip())
context = "\n\n".join(contexts)
sources_str = "".join(sources)
return f"基于以下文档({sources_str})的信息:\n\n{context}"
async def comprehensive_file_format_test():
"""全面的文件格式测试"""
print("=" * 60)
print("🚀 Base RAG 异步文件格式支持测试")
print("=" * 60)
print()
# 初始化RAG系统
rag = SimpleRAG(
vector_store_name="comprehensive_test_kb",
retriever_top_k=3,
persist_directory="/Users/liruwei/Documents/code/project/demo/base_rag/chroma_db",
status_db_path="/Users/liruwei/Documents/code/project/demo/base_rag/test_status.db"
)
# 支持的文件格式和对应的测试文件
test_files = [
{
"format": "TXT",
"path": "/Users/liruwei/Documents/code/project/demo/base_rag/test_files/knowledge.txt",
"description": "纯文本文件 - 基础知识"
},
{
"format": "MD",
"path": "/Users/liruwei/Documents/code/project/demo/base_rag/test_files/python_guide.md",
"description": "Markdown文件 - Python编程指南"
},
{
"format": "MD",
"path": "/Users/liruwei/Documents/code/project/demo/base_rag/test_files/machine_learning.md",
"description": "Markdown文件 - 机器学习入门"
},
{
"format": "DOCX",
"path": "/Users/liruwei/Documents/code/project/demo/base_rag/test_files/deep_learning_guide.docx",
"description": "Word文档 - 深度学习技术指南"
}
]
print("📂 文件处理测试\n")
# 处理每个文件
processed_files = []
for file_info in test_files:
file_path = file_info["path"]
format_name = file_info["format"]
description = file_info["description"]
if not Path(file_path).exists():
print(f"{format_name}: {description} - 文件不存在")
continue
print(f"📄 处理 {format_name} 格式: {description}")
try:
result = await rag.process_file_to_vector_store(file_path)
if result and result.get('success'):
print(f" ✅ 成功: {result['chunks_count']} 个文档片段")
processed_files.append(file_info)
else:
print(f" ⚠️ 跳过: {result.get('message', '文件可能已存在')}")
processed_files.append(file_info)
except Exception as e:
print(f" ❌ 失败: {str(e)}")
print()
print("=" * 60)
print("💬 跨格式查询测试")
print("=" * 60)
print()
# 测试跨格式查询
test_queries = [
{
"question": "Python的基本语法有哪些",
"expected_format": "MD (Python指南)"
},
{
"question": "什么是机器学习?有哪些类型?",
"expected_format": "MD (机器学习)"
},
{
"question": "深度学习有哪些核心组件?",
"expected_format": "DOCX (深度学习)"
},
{
"question": "深度学习的应用领域都有哪些?",
"expected_format": "DOCX (深度学习)"
}
]
for i, query_info in enumerate(test_queries, 1):
question = query_info["question"]
expected = query_info["expected_format"]
print(f"❓ 查询 {i}: {question}")
print(f" 期望来源: {expected}")
try:
response = await rag.query(question)
print(f" 💡 回答: {response[:200]}...")
print()
except Exception as e:
print(f" ❌ 查询失败: {str(e)}")
print()
print("=" * 60)
print("📊 测试总结")
print("=" * 60)
format_stats = {}
for file_info in processed_files:
format_name = file_info["format"]
if format_name not in format_stats:
format_stats[format_name] = 0
format_stats[format_name] += 1
print(f"✅ 成功处理的文件格式:")
for format_name, count in format_stats.items():
print(f"{format_name}: {count} 个文件")
print(f"\n🎉 异步RAG系统文件格式支持测试完成!")
print(f" 支持格式: TXT, MD, DOCX")
print(f" 异步处理: ✅ 完全支持")
print(f" 跨格式查询: ✅ 完全支持")
if __name__ == "__main__":
asyncio.run(comprehensive_file_format_test())

View File

@ -1,59 +0,0 @@
#!/usr/bin/env python3
"""
创建用于测试的 Word 文档
"""
import asyncio
from docx import Document
async def create_test_docx():
"""创建测试用的docx文件"""
doc = Document()
# 添加标题
doc.add_heading('深度学习技术指南', 0)
# 添加段落
doc.add_paragraph('深度学习是机器学习的一个重要分支,它使用多层神经网络来学习数据的表示。')
# 添加子标题
doc.add_heading('核心概念', level=1)
# 添加带格式的内容
p = doc.add_paragraph('深度学习的核心组件包括:')
p.add_run('神经网络').bold = True
p.add_run('')
p.add_run('反向传播').bold = True
p.add_run('')
p.add_run('梯度下降').bold = True
# 添加列表
doc.add_heading('主要架构', level=2)
doc.add_paragraph('卷积神经网络 (CNN)', style='List Bullet')
doc.add_paragraph('循环神经网络 (RNN)', style='List Bullet')
doc.add_paragraph('长短期记忆网络 (LSTM)', style='List Bullet')
doc.add_paragraph('生成对抗网络 (GAN)', style='List Bullet')
doc.add_paragraph('变换器 (Transformer)', style='List Bullet')
# 添加应用领域
doc.add_heading('应用领域', level=2)
applications = [
'计算机视觉:图像识别、物体检测、人脸识别',
'自然语言处理:机器翻译、文本生成、情感分析',
'语音技术:语音识别、语音合成',
'推荐系统:个性化推荐、内容推荐',
'自动驾驶:环境感知、路径规划'
]
for app in applications:
doc.add_paragraph(app, style='List Number')
# 添加技术挑战
doc.add_heading('技术挑战', level=1)
doc.add_paragraph('深度学习面临的主要挑战包括数据质量、模型可解释性、计算资源需求和泛化能力等。')
# 保存文档
doc.save('/Users/liruwei/Documents/code/project/demo/base_rag/test_files/deep_learning_guide.docx')
print("已创建 deep_learning_guide.docx")
if __name__ == "__main__":
asyncio.run(create_test_docx())

Binary file not shown.

View File

@ -1,5 +0,0 @@
NumPy是Python中用于科学计算的基础库提供多维数组对象。
Pandas是强大的数据分析和处理库提供DataFrame数据结构。
Matplotlib是Python的绘图库用于创建静态、动态和交互式图表。
Scikit-learn是机器学习库提供各种算法和工具。

View File

@ -1,5 +0,0 @@
Python是一种高级编程语言由Guido van Rossum于1991年创建。
Python具有简洁易读的语法适合初学者学习编程。
Python是解释型语言支持面向对象、函数式等多种编程范式。
Python的设计哲学强调代码的可读性和简洁性。

View File

@ -1,5 +0,0 @@
Flask是一个轻量级的Python Web框架易于学习和使用。
Django是一个功能丰富的Python Web框架适合大型项目开发。
FastAPI是现代的Python Web框架专为构建API而设计。
Tornado是一个可扩展的非阻塞Web服务器和Web应用框架。

View File

@ -0,0 +1,151 @@
#!/usr/bin/env python3
"""
多格式文件测试 - 测试 TXTMDDOCX 文件格式
"""
import sys
import os
import asyncio
import warnings
from pathlib import Path
# 过滤掉PyTorch的FutureWarning
warnings.filterwarnings("ignore", category=FutureWarning, module="torch")
# 添加源码路径
sys.path.append(os.path.join(os.path.dirname(__file__), "..", "src"))
from base_rag.core import BaseRAG
class MultiFormatRAG(BaseRAG):
"""多格式文件处理的RAG实现"""
async def ingest(self, file_path: str, **kwargs):
"""实现文档导入逻辑"""
return await self.process_file_to_vector_store(file_path, **kwargs)
async def query(self, question: str) -> str:
"""实现查询逻辑"""
docs = await self.similarity_search_with_rerank(question, k=3)
if not docs:
return "抱歉,没有找到相关信息。"
# 显示搜索到的文档来源
sources = []
contexts = []
for doc in docs:
source = doc.metadata.get("source_file", "未知来源")
if source not in sources:
sources.append(source)
contexts.append(doc.page_content.strip())
context = "\n\n".join(contexts)
sources_str = "".join(sources)
return f"基于以下文档({sources_str})的信息:\n\n{context}"
async def test_multiple_formats():
"""测试多种文件格式处理"""
print("🚀 多格式文件处理测试")
print("=" * 50)
# 创建RAG实例
rag = MultiFormatRAG(
vector_store_name="multiformat_kb",
retriever_top_k=3,
storage_directory="./test_files",
status_db_path="./status.db",
)
# 测试文件列表
test_files = [
{
"file": "knowledge.txt",
"format": "TXT",
"description": "纯文本文件"
},
{
"file": "python_guide.md",
"format": "MD",
"description": "Markdown文件"
},
{
"file": "machine_learning.md",
"format": "MD",
"description": "Markdown文件"
},
{
"file": "deep_learning_guide.docx",
"format": "DOCX",
"description": "Word文档"
}
]
print("📂 处理文件...")
processed_count = 0
for file_info in test_files:
filename = file_info["file"]
format_type = file_info["format"]
description = file_info["description"]
file_path = Path("./test_files") / filename
if not file_path.exists():
print(f"{format_type}: {filename} - 文件不存在")
continue
print(f"📄 处理 {format_type}: {filename} ({description})")
try:
result = await rag.ingest(str(file_path))
if result and result.get('success'):
print(f" ✅ 成功: {result['chunks_count']} 个片段")
processed_count += 1
else:
print(f" ⚠️ 跳过: {result.get('message', '可能已存在')}")
processed_count += 1 # 已存在也算处理过
except Exception as e:
print(f" ❌ 失败: {str(e)}")
print(f"\n📊 处理完成: {processed_count}/{len(test_files)} 个文件")
print()
# 测试跨格式查询
print("💬 跨格式查询测试...")
queries = [
"Python有什么特点",
"什么是机器学习?",
"深度学习的应用领域有哪些?",
"Web框架有哪些"
]
for query in queries:
print(f"\n{query}")
try:
answer = await rag.query(query)
if "抱歉" not in answer:
# 显示简化的回答
lines = answer.split('\n')
source_line = next((line for line in lines if line.startswith('基于')), "")
content_lines = [line for line in lines if line.strip() and not line.startswith('基于')]
if content_lines:
print(f" 💡 {content_lines[0][:100]}...")
if source_line:
print(f" 📚 {source_line}")
else:
print(f" 💡 {answer}")
except Exception as e:
print(f" ❌ 查询失败: {str(e)}")
print("\n" + "=" * 50)
print("✅ 多格式文件测试完成!")
print("支持的格式: TXT, MD, DOCX")
if __name__ == "__main__":
asyncio.run(test_multiple_formats())

View File

@ -54,51 +54,17 @@ async def test_file_processing():
rag = SimpleRAG(
vector_store_name="test_kb",
retriever_top_k=2,
storage_directory="./test_docs",
status_db_path="./test_status.db",
storage_directory="./test_files", # 统一使用test_files目录
status_db_path="./status.db", # 统一数据库名称
)
# 创建测试文件
# 使用现有的测试文件
test_dir = Path("./test_files")
test_dir.mkdir(exist_ok=True)
# 创建多个不同主题的知识文件
# Python基础知识
# 使用已有的测试文件
python_file = test_dir / "python_basics.txt"
python_file.write_text(
"""
Python是一种高级编程语言由Guido van Rossum于1991年创建
Python具有简洁易读的语法适合初学者学习编程
Python是解释型语言支持面向对象函数式等多种编程范式
Python的设计哲学强调代码的可读性和简洁性
""",
encoding="utf-8",
)
# Web框架知识
web_file = test_dir / "web_frameworks.txt"
web_file.write_text(
"""
Flask是一个轻量级的Python Web框架易于学习和使用
Django是一个功能丰富的Python Web框架适合大型项目开发
FastAPI是现代的Python Web框架专为构建API而设计
Tornado是一个可扩展的非阻塞Web服务器和Web应用框架
""",
encoding="utf-8",
)
# 数据科学知识
web_file = test_dir / "web_frameworks.txt"
datascience_file = test_dir / "data_science.txt"
datascience_file.write_text(
"""
NumPy是Python中用于科学计算的基础库提供多维数组对象
Pandas是强大的数据分析和处理库提供DataFrame数据结构
Matplotlib是Python的绘图库用于创建静态动态和交互式图表
Scikit-learn是机器学习库提供各种算法和工具
""",
encoding="utf-8",
)
print("1. 处理多个知识文件...")
files_to_process = [python_file, web_file, datascience_file]

View File

@ -1,128 +0,0 @@
#!/usr/bin/env python3
"""
最终文件格式测试 - 清理后重新测试
"""
import asyncio
import sys
import os
import shutil
from pathlib import Path
# 添加项目路径
sys.path.append('/Users/liruwei/Documents/code/project/demo/base_rag/src')
from base_rag.core import BaseRAG
class SimpleRAG(BaseRAG):
"""简单的RAG实现示例"""
async def ingest(self, file_path: str, **kwargs):
"""实现文档导入逻辑"""
return await self.process_file_to_vector_store(file_path, **kwargs)
async def query(self, question: str) -> str:
"""实现简单的查询逻辑"""
docs = await self.similarity_search_with_rerank(question, k=2)
if not docs:
return "抱歉,没有找到相关信息。"
# 显示搜索到的文档来源
sources = []
contexts = []
for doc in docs:
source = doc.metadata.get("source_file", "未知来源")
if source not in sources:
sources.append(source)
contexts.append(doc.page_content.strip())
context = "\n\n".join(contexts)
sources_str = "".join(sources)
return f"基于以下文档({sources_str})的信息:\n\n{context}"
async def final_format_test():
"""最终文件格式测试"""
print("🧹 清理测试环境...")
# 删除旧的向量数据库目录
test_db_path = Path("/Users/liruwei/Documents/code/project/demo/base_rag/chroma_db/final_test")
if test_db_path.exists():
shutil.rmtree(test_db_path)
print("✅ 环境清理完成\n")
print("🚀 文件格式支持最终测试")
print("=" * 50)
# 初始化新的RAG系统
rag = SimpleRAG(
vector_store_name="final_test",
retriever_top_k=2,
persist_directory="/Users/liruwei/Documents/code/project/demo/base_rag/chroma_db",
status_db_path="/Users/liruwei/Documents/code/project/demo/base_rag/final_test.db"
)
# 测试文件
test_files = [
{
"name": "machine_learning.md",
"path": "/Users/liruwei/Documents/code/project/demo/base_rag/test_files/machine_learning.md",
"type": "Markdown"
},
{
"name": "deep_learning_guide.docx",
"path": "/Users/liruwei/Documents/code/project/demo/base_rag/test_files/deep_learning_guide.docx",
"type": "Word文档"
}
]
print("📄 处理文件...")
for file_info in test_files:
name = file_info["name"]
path = file_info["path"]
file_type = file_info["type"]
print(f" {file_type}: {name}")
try:
result = await rag.process_file_to_vector_store(path)
if result and result.get('success'):
print(f" ✅ 成功: {result['chunks_count']} 个片段")
else:
print(f" ⚠️ {result.get('message', '处理失败')}")
except Exception as e:
print(f" ❌ 错误: {str(e)}")
print("\n💬 测试查询...")
queries = [
"什么是机器学习?",
"深度学习的应用领域有哪些?",
"神经网络的架构类型"
]
for query in queries:
print(f"\n{query}")
try:
answer = await rag.query(query)
# 显示简化的回答
if "抱歉" not in answer:
lines = answer.split('\n')
first_content = next((line for line in lines if line.strip() and not line.startswith('基于')), "")
print(f" 💡 {first_content[:100]}...")
else:
print(f" 💡 {answer}")
except Exception as e:
print(f"{str(e)}")
print("\n" + "=" * 50)
print("🎉 测试完成!")
print("✅ 支持格式: TXT, MD, DOCX")
print("✅ 异步处理: 完全支持")
print("✅ 跨格式查询: 完全支持")
if __name__ == "__main__":
asyncio.run(final_format_test())

Binary file not shown.

View File

@ -1,5 +0,0 @@
NumPy是Python中用于科学计算的基础库提供多维数组对象。
Pandas是强大的数据分析和处理库提供DataFrame数据结构。
Matplotlib是Python的绘图库用于创建静态、动态和交互式图表。
Scikit-learn是机器学习库提供各种算法和工具。

View File

@ -1,6 +0,0 @@
Python是一种高级编程语言。
它具有简洁的语法和强大的功能。
Python广泛应用于Web开发、数据科学、人工智能等领域。
机器学习库如scikit-learn、TensorFlow和PyTorch都支持Python。
Flask和Django是流行的Python Web框架。

View File

@ -1,5 +0,0 @@
Python是一种高级编程语言由Guido van Rossum于1991年创建。
Python具有简洁易读的语法适合初学者学习编程。
Python是解释型语言支持面向对象、函数式等多种编程范式。
Python的设计哲学强调代码的可读性和简洁性。

View File

@ -1,5 +0,0 @@
Flask是一个轻量级的Python Web框架易于学习和使用。
Django是一个功能丰富的Python Web框架适合大型项目开发。
FastAPI是现代的Python Web框架专为构建API而设计。
Tornado是一个可扩展的非阻塞Web服务器和Web应用框架。

View File

@ -1,91 +0,0 @@
#!/usr/bin/env python3
"""
测试 docx 文件格式的处理
"""
import asyncio
import sys
import os
# 添加项目路径
sys.path.append('/Users/liruwei/Documents/code/project/demo/base_rag/src')
from base_rag.core import BaseRAG
class SimpleRAG(BaseRAG):
"""简单的RAG实现示例"""
async def ingest(self, file_path: str, **kwargs):
"""实现文档导入逻辑"""
return await self.process_file_to_vector_store(file_path, **kwargs)
async def query(self, question: str) -> str:
"""实现简单的查询逻辑"""
docs = await self.similarity_search_with_rerank(question, k=2)
if not docs:
return "抱歉,没有找到相关信息。"
# 显示搜索到的文档来源
sources = []
contexts = []
for doc in docs:
source = doc.metadata.get("source_file", "未知来源")
if source not in sources:
sources.append(source)
contexts.append(doc.page_content.strip())
context = "\n\n".join(contexts)
sources_str = "".join(sources)
return f"基于以下文档({sources_str})的信息:\n\n{context}"
async def test_docx_format():
"""测试docx文件格式处理"""
print("=== 测试DOCX文件格式处理 ===\n")
# 初始化RAG系统
rag = SimpleRAG(
vector_store_name="test_docx_kb",
retriever_top_k=2,
persist_directory="/Users/liruwei/Documents/code/project/demo/base_rag/chroma_db",
status_db_path="/Users/liruwei/Documents/code/project/demo/base_rag/test_status.db"
)
# 测试docx文件
docx_file = "/Users/liruwei/Documents/code/project/demo/base_rag/test_files/deep_learning_guide.docx"
print(f"处理文件: {os.path.basename(docx_file)}")
try:
result = await rag.process_file_to_vector_store(docx_file)
if result:
print(f"✅ 成功处理: {result}")
else:
print(f"❌ 处理失败或文件已存在")
except Exception as e:
print(f"❌ 处理出错: {str(e)}")
print()
# 测试查询
print("=== 测试针对DOCX文档的查询 ===\n")
test_queries = [
"深度学习是什么?",
"卷积神经网络有什么特点?",
"深度学习有哪些应用领域?",
"深度学习面临哪些技术挑战?"
]
for query in test_queries:
print(f"查询: {query}")
try:
response = await rag.query(query)
print(f"回答: {response}\n")
except Exception as e:
print(f"❌ 查询出错: {str(e)}\n")
if __name__ == "__main__":
asyncio.run(test_docx_format())

View File

@ -1,96 +0,0 @@
#!/usr/bin/env python3
"""
测试 mddocx 文件格式的处理
"""
import asyncio
import sys
import os
# 添加项目路径
sys.path.append('/Users/liruwei/Documents/code/project/demo/base_rag/src')
from base_rag.core import BaseRAG
class SimpleRAG(BaseRAG):
"""简单的RAG实现示例"""
async def ingest(self, file_path: str, **kwargs):
"""实现文档导入逻辑"""
return await self.process_file_to_vector_store(file_path, **kwargs)
async def query(self, question: str) -> str:
"""实现简单的查询逻辑"""
docs = await self.similarity_search_with_rerank(question, k=2)
if not docs:
return "抱歉,没有找到相关信息。"
# 显示搜索到的文档来源
sources = []
contexts = []
for doc in docs:
source = doc.metadata.get("source_file", "未知来源")
if source not in sources:
sources.append(source)
contexts.append(doc.page_content.strip())
context = "\n\n".join(contexts)
sources_str = "".join(sources)
return f"基于以下文档({sources_str})的信息:\n\n{context}"
async def test_file_formats():
"""测试不同文件格式的处理"""
print("=== 测试文件格式处理 ===\n")
# 初始化RAG系统
rag = SimpleRAG(
vector_store_name="test_formats_kb",
retriever_top_k=2,
persist_directory="/Users/liruwei/Documents/code/project/demo/base_rag/chroma_db",
status_db_path="/Users/liruwei/Documents/code/project/demo/base_rag/test_status.db"
)
# 测试文件列表
test_files = [
"/Users/liruwei/Documents/code/project/demo/base_rag/test_files/python_guide.md",
"/Users/liruwei/Documents/code/project/demo/base_rag/test_files/machine_learning.md",
"/Users/liruwei/Documents/code/project/demo/base_rag/test_files/deep_learning_guide.docx"
]
# 处理每个文件
for file_path in test_files:
print(f"处理文件: {os.path.basename(file_path)}")
try:
result = await rag.process_file_to_vector_store(file_path)
if result:
print(f"✅ 成功处理: {result}")
else:
print(f"❌ 处理失败或文件已存在")
except Exception as e:
print(f"❌ 处理出错: {str(e)}")
print()
# 测试查询
print("=== 测试查询功能 ===\n")
test_queries = [
"Python的基本语法有哪些",
"什么是机器学习?",
"深度学习的核心概念是什么?",
"神经网络的主要架构有哪些?"
]
for query in test_queries:
print(f"查询: {query}")
try:
response = await rag.query(query)
print(f"回答: {response}\n")
except Exception as e:
print(f"❌ 查询出错: {str(e)}\n")
if __name__ == "__main__":
asyncio.run(test_file_formats())

View File

@ -1,6 +0,0 @@
这是一个测试文档。
它包含了关于人工智能的信息。
人工智能是计算机科学的一个分支,致力于创建智能机器。
机器学习是人工智能的一个重要组成部分。
深度学习是机器学习的一个子领域。

View File

@ -1,13 +0,0 @@
# RAG系统介绍
## 什么是RAG
RAGRetrieval-Augmented Generation是一种结合了检索和生成的AI技术。
## RAG的优势
- 能够利用外部知识库
- 提高回答的准确性
- 支持实时更新知识
## 应用场景
RAG系统广泛应用于问答系统、知识管理等领域。

Binary file not shown.