一、环境准备与基础依赖安装
本指南基于Ubuntu 20.04 LTS环境,构建一套符合档案管理规范的系统,包含文件上传、元数据管理及中文OCR识别功能。请确保系统已具备root权限。
1. 系统依赖与OCR引擎安装
档案管理核心在于对纸质文件的数字化识别,需安装Tesseract OCR引擎及中文语言包,同时安装Python与Node.js运行环境。
```bash
更新源并安装系统级依赖
sudo apt-get update
sudo apt-get install -y python3.10 python3-pip python3-venv postgresql postgresql-contrib tesseract-ocr tesseract-ocr-chi-sim nginx nodejs npm
验证Tesseract中文支持
tesseract --list-langs | grep chi_sim
```
2. 数据库初始化配置
使用PostgreSQL存储档案元数据。执行以下命令创建数据库用户及实例。
```bash
启动PostgreSQL服务
sudo service postgresql start
切换到postgres用户执行数据库设置
sudo -u postgres psql <
二、后端服务开发
后端采用Python FastAPI框架,提供高性能的API接口,处理文件存储、OCR提取及数据持久化。
1. 创建项目目录与虚拟环境
```bash
mkdir -p /opt/kunming_archive
cd /opt/kunming_archive
python3.10 -m venv venv
source venv/bin/activate
```
2. 安装Python依赖包
创建requirements.txt并写入以下内容,确保版本一致性。
```text
fastapi==0.104.1
uvicorn[standard]==0.24.0
sqlalchemy==2.0.23
psycopg2-binary==2.9.9
python-multipart==0.0.6
python-dotenv==1.0.0
pytesseract==0.3.10
pillow==10.1.0
alembic==1.12.1
pydantic==2.5.0
```
执行安装命令:
```bash
pip install -r requirements.txt
```
3. 数据库模型定义
创建models.py,定义符合档案管理标准的数据表结构,包含档号、题名、保管期限等核心字段。
```python
models.py
from sqlalchemy import Column, Integer, String, DateTime, Text
from sqlalchemy.ext.declarative import declarative_base
from datetime import datetime
Base = declarative_base()
class ArchiveRecord(Base):
__tablename__ = "archive_records"
id = Column(Integer, primary_key=True, index=True)
archive_code = Column(String(50), unique=True, index=True, nullable=False, comment="档号")
title = Column(String(200), nullable=False, comment="题名")
category = Column(String(50), nullable=False, comment="门类代码")
retention_period = Column(String(20), nullable=False, comment="保管期限")
security_level = Column(String(20), default="内部", comment="密级")
file_path = Column(String(500), nullable=True, comment="电子文件路径")
ocr_content = Column(Text, nullable=True, comment="OCR识别全文")
created_at = Column(DateTime, default=datetime.utcnow, comment="归档日期")
```
4. 数据库连接配置
创建database.py,配置数据库连接池。
```python
database.py
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
import os
DATABASE_URL = "postgresql://archive_admin:Km_Archive_2024!Secure@localhost/kunming_archive_db"
engine = create_engine(DATABASE_URL, pool_pre_ping=True)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
```
5. 核心业务逻辑与API接口
创建main.py,实现文件上传、OCR处理及档案入库接口。确保创建uploads目录用于存储文件。
```python
main.py
import os
import shutil
import uuid
import pytesseract
from PIL import Image
from fastapi import FastAPI, File, UploadFile, Form, Depends, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from sqlalchemy.orm import Session
from typing import Optional
from database import engine, get_db
from models import Base, ArchiveRecord
创建表结构
Base.metadata.create_all(bind=engine)
app = FastAPI(title="Kunming Archive Management API")
允许跨域访问
app.add_middleware(
CORSMiddleware,
allow_origins=[""],
allow_credentials=True,
allow_methods=[""],
allow_headers=[""],
)
UPLOAD_DIR = "/opt/kunming_archive/uploads"
os.makedirs(UPLOAD_DIR, exist_ok=True)
设置Tesseract路径(Ubuntu默认在PATH中,若报错需指定绝对路径)
pytesseract.pytesseract.tesseract_cmd = r'/usr/bin/tesseract'
@app.post("/api/v1/archives/upload")
async def upload_archive(
file: UploadFile = File(...),
archive_code: str = Form(...),
title: str = Form(...),
category: str = Form(...),
retention_period: str = Form(...),
db: Session = Depends(get_db)
):
1. 验证档号唯一性
existing = db.query(ArchiveRecord).filter(ArchiveRecord.archive_code == archive_code).first()
if existing:
raise HTTPException(status_code=400, detail="档号已存在")
2. 保存文件
file_extension = file.filename.split(".")[-1]
new_filename = f"{uuid.uuid4().hex}.{file_extension}"
file_location = os.path.join(UPLOAD_DIR, new_filename)
try:
with open(file_location, "wb+") as file_object:
shutil.copyfileobj(file.file, file_object)
except Exception as e:
raise HTTPException(status_code=500, detail=f"文件保存失败: {str(e)}")
3. OCR识别 (仅对图片进行处理)
ocr_text = ""
if file_extension.lower() in ['png', 'jpg', 'jpeg', 'tiff', 'bmp']:
try:
image = Image.open(file_location)
lang='chi_sim' 指定简体中文
ocr_text = pytesseract.image_to_string(image, lang='chi_sim+eng')
except Exception as e:
print(f"OCR Error: {e}")
ocr_text = "识别失败"
4. 入库
db_archive = ArchiveRecord(
archive_code=archive_code,
title=title,
category=category,
retention_period=retention_period,
file_path=file_location,
ocr_content=ocr_text
)
db.add(db_archive)
db.commit()
db.refresh(db_archive)
return {"message": "归档成功", "id": db_archive.id, "ocr_preview": ocr_text[:100]}
@app.get("/api/v1/archives")
def list_archives(skip: int = 0, limit: int = 10, db: Session = Depends(get_db)):
archives = db.query(ArchiveRecord).offset(skip).limit(limit).all()
return archives
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
```
三、前端界面开发

使用Vue 3构建简洁的操作界面,实现档案录入与列表展示功能。
1. 初始化Vue项目
```bash
cd /opt/kunming_archive
npm init vue@latest frontend
cd frontend
npm install
npm install axios element-plus
```
2. 配置前端入口文件
修改frontend/src/main.js,引入Element Plus组件库。
```javascript
import { createApp } from 'vue'
import App from './App.vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
const app = createApp(App)
app.use(ElementPlus)
app.mount('app')
```
3. 编写主界面组件
修改frontend/src/App.vue,提供完整的上传表单和列表展示代码。
```html
昆明档案管理系统
拖拽文件到此处或 点击上传
提交归档
{{ new Date(scope.row.created_at).toLocaleString() }}
查看全文
```
四、系统启动与验证
完成代码编写后,按顺序启动后端API服务和前端开发服务器。
1. 启动后端服务
```bash
cd /opt/kunming_archive
source venv/bin/activate
python main.py
```
访问 http://localhost:8000/docs 可查看自动生成的Swagger API文档。
2. 启动前端服务
```bash
cd /opt/kunming_archive/frontend
npm run dev
```
终端会输出前端访问地址,通常是 http://localhost:5173。在浏览器中打开该地址,即可看到“昆明档案管理系统”界面。
3. 功能验证步骤
- 上传测试: 准备一张包含中文文字的JPG图片。在界面填写档号(如:KM-TEST-001)、题名等信息,选择“文书档案”和“永久”,拖入图片并点击提交。
- OCR验证: 提交成功后,下方列表会刷新。点击该条目右侧的“查看全文”按钮,应能看到图片中提取出的中文文本内容。
- 数据验证: 检查PostgreSQL数据库,确认
archive_records表中已插入对应数据,且file_path指向uploads目录下的实际文件。
五、生产环境Nginx反向代理配置
为了方便实际访问,使用Nginx代理前端静态页面及后端API接口。
编辑Nginx配置文件:
```bash
sudo nano /etc/nginx/sites-available/kunming_archive
```
写入以下配置:
```nginx
server {
listen 80;
server_name _;
前端静态资源代理
location / {
root /opt/kunming_archive/frontend/dist;
try_files $uri $uri/ /index.html;
}
后端API代理
location /api/ {
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
```
执行以下命令启用配置并重启Nginx:
```bash
构建前端生产包
cd /opt/kunming_archive/frontend
npm run build
启用Nginx配置
sudo ln -s /etc/nginx/sites-available/kunming_archive /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx
```
现在,直接访问服务器的IP地址即可使用完整的昆明档案管理软件系统。