Skip to content

[Enhancement] Improve configuration management: Support environment variables and custom model paths #563

Description

@suntp

问题描述 / Problem Description

中文: 配置管理存在问题,使用硬编码的相对路径,在不同工作目录下可能失效,且难以自定义模型位置。

English: Configuration management has issues with hardcoded relative paths that may fail in different working directories and make it difficult to customize model locations.

问题位置 / Location

文件 / File: src/config/inference_config.py

问题代码 / Problematic Code

checkpoint_F: str = make_abs_path('../../pretrained_weights/liveportrait/base_models/appearance_feature_extractor.pth')
checkpoint_M: str = make_abs_path('../../pretrained_weights/liveportrait/base_models/motion_extractor.pth')
# ... 更多硬编码路径 / More hardcoded paths

影响 / Impact

中文:

  1. 路径失效: 不同工作目录下相对路径可能错误
  2. 难以自定义: 无法轻松更改模型位置
  3. 部署困难: 生产环境中模型可能存放在不同位置
  4. 测试困难: 单元测试需要特定的目录结构

English:

  1. Path failures: Relative paths may be incorrect in different working directories
  2. Difficult to customize: Cannot easily change model locations
  3. Deployment difficulties: Models may be stored in different locations in production
  4. Testing difficulties: Unit tests require specific directory structures

场景示例 / Scenario Examples

场景1: 在项目根目录运行 / Scenario 1: Run from Project Root

cd LivePortrait
python inference.py  # ✅ 正常工作 / Works normally

场景2: 在其他目录运行 / Scenario 2: Run from Other Directory

cd /tmp
python /path/to/LivePortrait/inference.py  # ❌ 路径错误 / Path error

场景3: 模型在共享存储 / Scenario 3: Models in Shared Storage

# 模型在 /shared/models/LivePortrait/
# 代码在 /home/user/projects/LivePortrait/
# 无法直接使用 ❌ / Cannot use directly ❌

建议修复 / Suggested Fixes

方案1: 使用环境变量 / Solution 1: Use Environment Variables

import os

class InferenceConfig:
    def __init__(self):
        # 支持环境变量自定义 / Support environment variable customization
        self.model_root = os.environ.get(
            'LIVEPORTRAIT_MODEL_ROOT',
            make_abs_path('../../pretrained_weights')
        )
        
        self.checkpoint_F = os.path.join(
            self.model_root,
            'liveportrait/base_models/appearance_feature_extractor.pth'
        )
        # ... 其他模型路径 / Other model paths

使用 / Usage:

export LIVEPORTRAIT_MODEL_ROOT=/shared/models/LivePortrait
python inference.py

方案2: 使用配置文件 / Solution 2: Use Configuration File

# config.yaml
model_root: ./pretrained_weights
models:
  appearance_extractor: liveportrait/base_models/appearance_feature_extractor.pth
  motion_extractor: liveportrait/base_models/motion_extractor.pth
  # ...
# inference_config.py
import yaml

class InferenceConfig:
    def __init__(self, config_path='config.yaml'):
        with open(config_path) as f:
            config = yaml.safe_load(f)
        
        self.model_root = config['model_root']
        self.checkpoint_F = os.path.join(
            self.model_root,
            config['models']['appearance_extractor']
        )

方案3: 使用 Pydantic / Solution 3: Use Pydantic

from pydantic import BaseSettings, validator

class LivePortraitConfig(BaseSettings):
    model_root: str = './pretrained_weights'
    device: str = 'cuda'
    use_fp16: bool = True
    
    @validator('model_root')
    def validate_model_path(cls, v):
        if not os.path.exists(v):
            raise ValueError(f"Model path not found: {v}")
        return v
    
    class Config:
        env_prefix = "LIVEPORTRAIT_"  # 支持环境变量 / Support environment variables
        env_file = ".env"              # 支持 .env 文件 / Support .env file

# 使用 / Usage
config = LivePortraitConfig()
# 或从环境变量加载 / Or load from environment variables
# export LIVEPORTRAIT_MODEL_ROOT=/shared/models

方案4: 命令行参数 / Solution 4: Command Line Arguments

# inference.py
parser.add_argument('--model-root', type=str, 
                    default='./pretrained_weights',
                    help='Path to pretrained models')

迁移方案 / Migration Plan

为保持向后兼容 / To maintain backward compatibility:

class InferenceConfig:
    def __init__(self, model_root=None):
        # 优先级: 参数 > 环境变量 > 默认路径
        # Priority: parameter > environment variable > default path
        self.model_root = (
            model_root or
            os.environ.get('LIVEPORTRAIT_MODEL_ROOT') or
            make_abs_path('../../pretrained_weights')
        )

优先级 / Priority

P2 - 建议中期改进 / Recommend medium-term improvement

相关信息 / Related Information

  • 发现时间 / Discovered: 2026-03-05
  • 影响 / Impact: 部署灵活性、测试便利性 / Deployment flexibility, testing convenience

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions