Spaces:
Runtime error
Runtime error
Michael Hu commited on
Commit ·
462d6de
1
Parent(s): 0aa0b99
Remove Streamlit dependency and simplify Dia TTS dependency handling
Browse files- Remove streamlit from pyproject.toml and requirements.txt
- Change gradio from pinned to minimum version (>=5.9.1)
- Delete dependency_installer utility module
- Simplify Dia TTS provider to only check dependencies without auto-installation
- Replace _check_and_install_dia_dependencies with _check_dia_dependencies
- Add helpful installation messages for missing dac and dia modules
Files changed (4)
8 unmodified lines9101112131415168 unmodified linesreadme = "README.md"requires-python = ">=3.10"dependencies = ["streamlit>=1.44.1","gradio==5.9.1","nltk>=3.8","librosa>=0.10","ffmpeg-python>=0.2",8 unmodified lines91011121314158 unmodified linesreadme = "README.md"requires-python = ">=3.10"dependencies = ["gradio>=5.9.1","nltk>=3.8","librosa>=0.10","ffmpeg-python>=0.2",
12345streamlit>=1.44.1gradio==5.9.1nltk>=3.8librosa>=0.10ffmpeg-python>=0.21234gradio>=5.9.1nltk>=3.8librosa>=0.10ffmpeg-python>=0.2
10 unmodified lines111213141516172 unmodified lines202122232425262713 unmodified lines4142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888915 unmodified lines10510610710810911011111211311411511611711810 unmodified linesfrom ..base.tts_provider_base import TTSProviderBasefrom ...domain.exceptions import SpeechSynthesisExceptionfrom ..utils.dependency_installer import get_dependency_installerlogger = logging.getLogger(__name__)2 unmodified linesDEFAULT_SAMPLE_RATE = 24000# Try to import Dia dependenciesdef _check_and_install_dia_dependencies():"""Check and install Dia dependencies if needed."""global DIA_AVAILABLElogger.info("🔍 Checking Dia TTS dependencies...")13 unmodified linesexcept ImportError as e:logger.warning(f"⚠️ Dia TTS engine dependencies not available: {e}")logger.info(f"ImportError details: {type(e).__name__}: {e}")except ModuleNotFoundError as e:if "dac" in str(e):logger.warning("❌ Dia TTS engine is not available due to missing 'dac' module")elif "dia" in str(e):logger.warning("❌ Dia TTS engine is not available due to missing 'dia' module")else:logger.warning(f"❌ Dia TTS engine is not available: {str(e)}")logger.info(f"ModuleNotFoundError details: {type(e).__name__}: {e}")# Try to install missing dependencieslogger.info("🔧 Attempting to install Dia TTS dependencies...")try:installer = get_dependency_installer()success, errors = installer.install_dia_dependencies()if success:logger.info("✅ Successfully installed Dia TTS dependencies")# Try importing again after installationtry:logger.info("Re-attempting import after installation...")import torchfrom dia.model import DiaDIA_AVAILABLE = Truelogger.info("🎉 Dia TTS engine is now available after installation")return Trueexcept Exception as e:logger.error(f"❌ Dia TTS still not available after installation: {e}")logger.info(f"Post-installation import error: {type(e).__name__}: {e}")DIA_AVAILABLE = Falsereturn Falseelse:logger.error(f"❌ Failed to install Dia TTS dependencies: {errors}")DIA_AVAILABLE = Falsereturn Falseexcept Exception as e:logger.error(f"❌ Error during dependency installation: {e}")logger.info(f"Installation error details: {type(e).__name__}: {e}")DIA_AVAILABLE = Falsereturn False# Initial checklogger.info("🚀 Initializing Dia TTS provider...")_check_and_install_dia_dependencies()class DiaTTSProvider(TTSProviderBase):15 unmodified linesif self.model is None:logger.info("🔄 Ensuring Dia model is loaded...")# If Dia is not available, try to install dependenciesif not DIA_AVAILABLE:logger.info("⚠️ Dia not available, attempting to install dependencies...")if _check_and_install_dia_dependencies():DIA_AVAILABLE = Truelogger.info("✅ Dependencies installed, Dia is now available")else:logger.error("❌ Failed to install dependencies, Dia remains unavailable")return Falseif DIA_AVAILABLE:10 unmodified lines111213141516172 unmodified lines202122232425262713 unmodified lines41424344454647484950515253545556575859606162636415 unmodified lines808182838485868788899091929310 unmodified linesfrom ..base.tts_provider_base import TTSProviderBasefrom ...domain.exceptions import SpeechSynthesisExceptionlogger = logging.getLogger(__name__)2 unmodified linesDEFAULT_SAMPLE_RATE = 24000# Try to import Dia dependenciesdef _check_dia_dependencies():"""Check if Dia dependencies are available."""global DIA_AVAILABLElogger.info("🔍 Checking Dia TTS dependencies...")13 unmodified linesexcept ImportError as e:logger.warning(f"⚠️ Dia TTS engine dependencies not available: {e}")logger.info(f"ImportError details: {type(e).__name__}: {e}")DIA_AVAILABLE = Falsereturn Falseexcept ModuleNotFoundError as e:if "dac" in str(e):logger.warning("❌ Dia TTS engine is not available due to missing 'dac' module")logger.info("Please install descript-audio-codec: pip install descript-audio-codec")elif "dia" in str(e):logger.warning("❌ Dia TTS engine is not available due to missing 'dia' module")logger.info("Please install dia: pip install git+https://github.com/nari-labs/dia.git")else:logger.warning(f"❌ Dia TTS engine is not available: {str(e)}")logger.info(f"ModuleNotFoundError details: {type(e).__name__}: {e}")DIA_AVAILABLE = Falsereturn False# Initial checklogger.info("🚀 Initializing Dia TTS provider...")_check_dia_dependencies()class DiaTTSProvider(TTSProviderBase):15 unmodified linesif self.model is None:logger.info("🔄 Ensuring Dia model is loaded...")# If Dia is not available, check dependencies againif not DIA_AVAILABLE:logger.info("⚠️ Dia not available, checking dependencies again...")if _check_dia_dependencies():DIA_AVAILABLE = Truelogger.info("✅ Dependencies are now available")else:logger.error("❌ Dependencies still not available")return Falseif DIA_AVAILABLE:
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304"""Automatic dependency installer for TTS providers."""
import loggingimport subprocessimport sysimport importlibfrom typing import List, Dict, Optional, Tupleimport os
logger = logging.getLogger(__name__)
class DependencyInstaller: """Utility class for automatically installing missing dependencies."""
def __init__(self): """Initialize the dependency installer.""" self.installed_packages = set()
def check_module_available(self, module_name: str) -> bool: """ Check if a module is available for import.
Args: module_name: Name of the module to check
Returns: bool: True if module is available, False otherwise """ try: importlib.import_module(module_name) return True except ImportError: return False
def install_package(self, package_name: str, upgrade: bool = False) -> bool: """ Install a package using pip.
Args: package_name: Name of the package to install upgrade: Whether to upgrade if already installed
Returns: bool: True if installation succeeded, False otherwise """ if package_name in self.installed_packages: logger.info(f"Package {package_name} already installed in this session") return True
try: cmd = [sys.executable, "-m", "pip", "install"] if upgrade: cmd.append("--upgrade") cmd.append(package_name)
logger.info(f"Installing package: {package_name}") result = subprocess.run( cmd, capture_output=True, text=True, timeout=300 # 5 minute timeout )
if result.returncode == 0: logger.info(f"Successfully installed {package_name}") self.installed_packages.add(package_name) return True else: logger.error(f"Failed to install {package_name}: {result.stderr}") return False
except subprocess.TimeoutExpired: logger.error(f"Installation of {package_name} timed out") return False except Exception as e: logger.error(f"Error installing {package_name}: {e}") return False
def install_from_git(self, git_url: str, package_name: Optional[str] = None) -> bool: """ Install a package from a git repository.
Args: git_url: Git repository URL package_name: Optional package name for tracking
Returns: bool: True if installation succeeded, False otherwise """ package_name = package_name or git_url.split('/')[-1].replace('.git', '')
if package_name in self.installed_packages: logger.info(f"Package {package_name} already installed in this session") return True
try: cmd = [sys.executable, "-m", "pip", "install", f"git+{git_url}"]
logger.info(f"Installing package from git: {git_url}") result = subprocess.run( cmd, capture_output=True, text=True, timeout=600 # 10 minute timeout for git installs )
if result.returncode == 0: logger.info(f"Successfully installed {package_name} from git") self.installed_packages.add(package_name) return True else: logger.error(f"Failed to install {package_name} from git: {result.stderr}") return False
except subprocess.TimeoutExpired: logger.error(f"Git installation of {package_name} timed out") return False except Exception as e: logger.error(f"Error installing {package_name} from git: {e}") return False
def install_dia_dependencies(self) -> Tuple[bool, List[str]]: """ Install all dependencies required for Dia TTS.
Returns: Tuple[bool, List[str]]: (success, list of error messages) """ errors = []
# Check if Dia is already available if self.check_module_available("dia"): logger.info("Dia TTS is already available") return True, []
# Install Dia TTS from git - this will automatically install all dependencies # including descript-audio-codec as specified in pyproject.toml logger.info("Installing Dia TTS and all dependencies from GitHub") if self.install_from_git("https://github.com/nari-labs/dia.git", "dia"): logger.info("Successfully installed Dia TTS and dependencies") return True, [] else: errors.append("Failed to install Dia TTS from git")
# Fallback: try installing individual dependencies if git install fails logger.info("Git install failed, trying individual dependencies...") dependencies = [ ("torch", "torch"), ("transformers", "transformers"), ("accelerate", "accelerate"), ("soundfile", "soundfile"), ("dac", "descript-audio-codec"), ]
success = True for module_name, package_name in dependencies: if not self.check_module_available(module_name): logger.info(f"Installing missing dependency: {package_name}") if not self.install_package(package_name): errors.append(f"Failed to install {package_name}") success = False
# Try installing Dia again after dependencies if success and not self.check_module_available("dia"): if self.install_from_git("https://github.com/nari-labs/dia.git", "dia"): return True, [] else: errors.append("Failed to install Dia TTS after installing dependencies")
return success and len(errors) == 1, errors # Only the initial git error if dependencies succeeded
def install_dependencies_for_provider(self, provider_name: str) -> Tuple[bool, List[str]]: """ Install dependencies for a specific TTS provider.
Args: provider_name: Name of the TTS provider
Returns: Tuple[bool, List[str]]: (success, list of error messages) """ if provider_name.lower() == "dia": return self.install_dia_dependencies() else: return False, [f"Unknown provider: {provider_name}"]
def verify_installation(self, module_name: str) -> bool: """ Verify that a module was installed correctly.
Args: module_name: Name of the module to verify
Returns: bool: True if module can be imported, False otherwise """ try: # Clear import cache to ensure fresh import if module_name in sys.modules: del sys.modules[module_name]
importlib.import_module(module_name) logger.info(f"Successfully verified installation of {module_name}") return True except ImportError as e: logger.error(f"Failed to verify installation of {module_name}: {e}") return False
def get_installation_status(self) -> Dict[str, bool]: """ Get the installation status of key dependencies.
Returns: Dict[str, bool]: Dictionary mapping module names to availability status """ modules_to_check = [ "torch", "transformers", "accelerate", "soundfile", "numpy", "dac", "dia" ]
status = {} for module in modules_to_check: status[module] = self.check_module_available(module)
return status
def install_with_retry(self, package_name: str, max_retries: int = 3) -> bool: """ Install a package with retry logic.
Args: package_name: Name of the package to install max_retries: Maximum number of retry attempts
Returns: bool: True if installation succeeded, False otherwise """ for attempt in range(max_retries): if self.install_package(package_name): return True
if attempt < max_retries - 1: logger.warning(f"Installation attempt {attempt + 1} failed for {package_name}, retrying...") else: logger.error(f"All {max_retries} installation attempts failed for {package_name}")
return False
# Global instance for reuse_dependency_installer = None
def get_dependency_installer() -> DependencyInstaller: """ Get a global dependency installer instance.
Returns: DependencyInstaller: Global dependency installer instance """ global _dependency_installer if _dependency_installer is None: _dependency_installer = DependencyInstaller() return _dependency_installer
def install_dia_dependencies() -> Tuple[bool, List[str]]: """ Convenience function to install Dia TTS dependencies.
Returns: Tuple[bool, List[str]]: (success, list of error messages) """ installer = get_dependency_installer() return installer.install_dia_dependencies()
def check_and_install_module(module_name: str, package_name: Optional[str] = None) -> bool: """ Check if a module is available and install it if not.
Args: module_name: Name of the module to check package_name: Name of the package to install (defaults to module_name)
Returns: bool: True if module is available after check/install, False otherwise """ installer = get_dependency_installer()
if installer.check_module_available(module_name): return True
package_name = package_name or module_name if installer.install_package(package_name): return installer.verify_installation(module_name)
return Falsepyproject.toml+1-2
requirements.txt+1-2
src/infrastructure/tts/dia_provider.py+13-38
src/infrastructure/utils/dependency_installer.pyDeleted-304