metahuman-stream代码规范:Python/JS风格指南
·
metahuman-stream代码规范:Python/JS风格指南
【免费下载链接】metahuman-stream 项目地址: https://gitcode.com/GitHub_Trending/me/metahuman-stream
概述
metahuman-stream作为实时数字人交互系统,代码质量直接影响系统稳定性与可维护性。本指南基于项目现有代码风格(如app.py、llm.py及Web前端文件),结合PEP 8与Airbnb规范,制定Python/JavaScript统一编码标准,解决多人协作中的代码风格冲突问题。
目录
Python规范
1. 基本格式
| 规范项 | 要求 | 示例 |
|---|---|---|
| 缩进 | 4空格,不使用制表符 | def func():return True |
| 行宽 | 每行≤120字符 | 长表达式使用括号换行,不使用反斜杠 |
| 空行 | 函数/类间空2行,方法间空1行 | app.py中类定义与方法的间隔 |
2. 命名约定
# 模块名:小写+下划线
import lipreal # 正确
import LipReal # 错误
# 类名:PascalCase
class HumanPlayer: # 正确
class human_player: # 错误
# 函数/变量:snake_case
def build_nerfreal(sessionid): # 正确
def buildNerfreal(sessionId): # 错误
# 常量:全大写+下划线
MAX_SESSION = 10 # 正确
maxSession = 10 # 错误
3. 导入规范
# 顺序:标准库→第三方库→本地模块,每组间空行
import re
import time
from typing import Dict, List
import torch
import numpy as np
from logger import logger
from basereal import BaseReal # 本地模块使用相对导入
4. 注释规范
def llm_response(message, nerfreal: BaseReal):
"""
调用LLM生成响应并推送到数字人流
Args:
message: 用户输入文本
nerfreal: BaseReal实例,用于推送消息
Returns:
None,结果通过nerfreal.put_msg_txt异步推送
"""
start = time.perf_counter() # 性能计时起点
# TODO: 添加请求重试机制
from openai import OpenAI # 延迟导入优化启动速度
5. 类型注解
所有公共函数必须添加类型注解:
def negotiate() -> None: # 无返回值显式标注None
"""WebRTC协商流程"""
pass
def randN(N: int) -> int: # 参数与返回值均标注类型
"""生成长度为N的随机数"""
return random.randint(pow(10, N-1), pow(10, N)-1)
JavaScript规范
1. 基本格式
| 规范项 | 要求 | 示例 |
|---|---|---|
| 缩进 | 2空格 | function handleMsg() {console.log(msg);} |
| 行宽 | 每行≤100字符 | 长表达式使用模板字符串换行 |
| 分号 | 强制使用语句结束分号 | const x = 5;(而非const x =5) |
2. 命名约定
// 变量/函数:camelCase
const sampleBuf = new Uint8Array(); // 正确
const SampleBuf = new Uint8Array(); // 错误
// 常量:UPPER_SNAKE_CASE
const CHUNK_SIZE = 960; // 正确
const chunkSize = 960; // 错误
// 类/构造函数:PascalCase
class WebSocketConnectMethod { ... }
3. 语言特性
优先使用ES6+特性:
// 使用箭头函数简化回调
const onTrack = (evt) => {
if (evt.track.kind === 'video') {
videoElement.srcObject = evt.streams[0];
}
};
// 使用解构赋值
const { sessionid } = answer; // 替代answer.sessionid
document.getElementById('sessionid').value = sessionid;
// 使用async/await处理异步
async function waitSpeakingEnd() {
while (await is_speaking()) {
await new Promise(resolve => setTimeout(resolve, 1000));
}
}
4. 注释规范
/**
* WebSocket消息处理函数
* @param {Object} jsonMsg - 包含服务端响应的消息对象
* @param {string} jsonMsg.data - JSON字符串格式的响应数据
* @returns {void}
*/
function getJsonMessage(jsonMsg) {
const data = JSON.parse(jsonMsg.data);
console.log(`ASR result: ${data.text}`); // 使用模板字符串
// TODO: 添加错误边界处理
if (!data.text) return;
}
通用规范
1. 文件组织
metahuman-stream/
├── app.py # 主程序入口(Python)
├── llm.py # LLM交互模块(Python)
├── web/ # Web前端目录
│ ├── client.js # 客户端核心逻辑(JS)
│ └── asr/ # 语音识别子模块
│ ├── main.js # ASR主逻辑(JS)
│ └── pcm.js # 音频处理工具(JS)
└── musetalk/ # 数字人渲染模块
├── models/ # 模型定义
└── utils/ # 工具函数
2. 错误处理
Python
try:
# 使用with语句自动释放资源
with open(opt.customvideo_config, 'r') as f:
opt.customopt = json.load(f)
except FileNotFoundError:
logger.warning(f"配置文件{opt.customvideo_config}不存在,使用默认配置")
opt.customopt = []
except json.JSONDecodeError as e:
logger.error(f"配置文件解析失败: {str(e)}")
raise # 严重错误向上抛出
JavaScript
// 使用try/catch处理异步错误
async function fetchOffer() {
try {
const response = await fetch('/offer', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(offer)
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return await response.json();
} catch (e) {
console.error('Offer请求失败:', e);
showErrorToast('连接服务器失败,请检查网络'); // 向用户反馈
}
}
3. 版本控制
- 提交信息格式:
<类型>: <描述>
示例:feat: 添加数字人打断功能、fix: 修复WebSocket重连 Bug - 类型包括:feat(新功能)、fix(修复)、docs(文档)、style(格式)、refactor(重构)
规范落地工具
1. Python工具链
# 安装依赖
pip install black isort pylint
# 自动格式化(Black)
black app.py llm.py --line-length 120
# 导入排序(isort)
isort . --profile black # 与Black兼容
# 代码检查(Pylint)
pylint app.py --disable=C0114,C0115 # 忽略缺少类/函数注释的警告
2. JavaScript工具链
# 安装依赖
npm install -g eslint prettier
# 初始化配置文件
eslint --init # 生成.eslintrc.js
prettier --write "web/**/*.js" # 自动格式化JS文件
3. 代码审查流程
附录
A. 术语表
| 术语 | 解释 | 示例 |
|---|---|---|
| ASR | 自动语音识别 | web/asr/main.js处理ASR逻辑 |
| WebRTC | 网页实时通信技术 | client.js中RTCPeerConnection实现 |
| NeRF | 神经辐射场 | 3D数字人渲染核心技术 |
B. 参考资料
执行规范,提升协作效率
本规范基于项目现有代码抽象总结,所有新增代码必须遵守。定期进行代码规范审查,违规代码将被要求重构。
【免费下载链接】metahuman-stream 项目地址: https://gitcode.com/GitHub_Trending/me/metahuman-stream
更多推荐

所有评论(0)