TellmeStpToGlb/utils/helpers.py
root 5102bd57e8 feat: 服务化改造STP到GLB转换器
- 🚀 新增FastAPI Web服务支持
-  实现异步任务处理和并发转换
- 📊 添加实时进度追踪(0-100%)
- 🏗️ 重构为模块化架构:core/api/services/utils
- 🔧 完整的任务管理系统和状态追踪
- 📖 自动生成API文档(Swagger/ReDoc)
- 🔄 保持CLI模式100%向后兼容
- 🛡️ 增强错误处理和文件验证
- 📝 更新完整文档(README/CLAUDE.md)

技术栈: FastAPI + uvicorn + pydantic + asyncio
API端点: /health, /api/v1/convert, /api/v1/status, /api/v1/tasks

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-08-02 09:44:43 +08:00

88 lines
2.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
"""
工具函数
提供通用的辅助功能
"""
import os
import uuid
from typing import Optional
from datetime import datetime
def generate_task_id() -> str:
"""生成唯一任务ID"""
return str(uuid.uuid4())
def validate_file_path(file_path: str, must_exist: bool = True) -> bool:
"""验证文件路径"""
if not file_path:
return False
if must_exist:
return os.path.isfile(file_path)
# 检查父目录是否存在或可创建
parent_dir = os.path.dirname(file_path)
if parent_dir and not os.path.exists(parent_dir):
try:
os.makedirs(parent_dir, exist_ok=True)
return True
except Exception:
return False
return True
def get_file_extension(file_path: str) -> str:
"""获取文件扩展名(小写)"""
return os.path.splitext(file_path)[1].lower()
def is_stp_file(file_path: str) -> bool:
"""检查是否为STP文件"""
ext = get_file_extension(file_path)
return ext in ['.stp', '.step']
def is_glb_file(file_path: str) -> bool:
"""检查是否为GLB文件"""
ext = get_file_extension(file_path)
return ext == '.glb'
def format_datetime(dt: Optional[datetime]) -> Optional[str]:
"""格式化日期时间"""
if dt is None:
return None
return dt.strftime("%Y-%m-%d %H:%M:%S")
def get_file_size_mb(file_path: str) -> float:
"""获取文件大小MB"""
if not os.path.isfile(file_path):
return 0.0
size_bytes = os.path.getsize(file_path)
return size_bytes / (1024 * 1024)
def cleanup_temp_files(base_path: str) -> None:
"""清理临时文件"""
temp_extensions = ['.tmp', '.temp', '.tmp.stl']
base_dir = os.path.dirname(base_path)
base_name = os.path.splitext(os.path.basename(base_path))[0]
if not os.path.exists(base_dir):
return
for file_name in os.listdir(base_dir):
if file_name.startswith(base_name):
for ext in temp_extensions:
if file_name.endswith(ext):
temp_file = os.path.join(base_dir, file_name)
try:
os.remove(temp_file)
except Exception:
pass # 忽略删除失败的情况