hbs2/test
0
1import os2import sys3import urllib.request4import subprocess5import argparse6 7def convert_to_bool(in_bool):8 # Convert the input to string and lower case, then check against true values9 return str(in_bool).lower() in ('true', 'on', '1', 'y', 'yes')10 11def install_packages_from_requirements(requirements_file):12 try:13 subprocess.run(['pip3', 'install', '-r', requirements_file, '--upgrade'], check=True)14 print("Packages installed successfully using pip3.")15 except subprocess.CalledProcessError:16 try:17 subprocess.run(['pip', 'install', '-r', requirements_file, '--upgrade'], check=True)18 print("Packages installed successfully using pip.")19 except subprocess.CalledProcessError:20 print("Failed to install packages using both pip3 and pip.")21 22def download_from_github(url, output_file):23 try:24 with urllib.request.urlopen(url) as response, open(output_file, 'wb') as out_file:25 data = response.read()26 out_file.write(data)27 print(f"File downloaded successfully to {output_file}")28 except urllib.error.HTTPError as e:29 print(f"Failed to download file from {url}. HTTP Error Code: {e.code}")30 except urllib.error.URLError as e:31 print(f"URL Error: {e.reason}")32 except Exception as e:33 print(f"An error occurred: {e}")34 35def prompt_and_save_bazarr_env_variables():36 instructions = (37 "You will be prompted for several configuration values.\n"38 "If you wish to use the default value for any of them, simply press Enter without typing anything.\n"39 "The default values are shown in brackets [] next to the prompts.\n"40 "Items can be the value of true, on, 1, y, yes, false, off, 0, n, no, or an appropriate text response.\n"41 )42 print(instructions)43 env_vars = {44 'WHISPER_MODEL': ('Whisper Model', 'Enter the Whisper model you want to run: tiny, tiny.en, base, base.en, small, small.en, medium, medium.en, large, distil-large-v2, distil-medium.en, distil-small.en', 'distil-small.en'),45 'WEBHOOKPORT': ('Webhook Port', 'Default listening port for subgen.py', '9000'),46 'TRANSCRIBE_DEVICE': ('Transcribe Device', 'Set as cpu or gpu', 'gpu'),47 # Defaulting to False here for the prompt, user can change48 'DEBUG': ('Debug', 'Enable debug logging (true/false)', 'False'),49 'CLEAR_VRAM_ON_COMPLETE': ('Clear VRAM', 'Attempt to clear VRAM when complete (Windows users may need to set this to False)', 'False'),50 'APPEND': ('Append', 'Append \'Transcribed by whisper\' to generated subtitle (true/false)', 'False'),51 }52 53 user_input = {}54 with open('subgen.env', 'w') as file:55 for var, (description, prompt, default) in env_vars.items():56 value = input(f"{prompt} [{default}]: ") or default57 file.write(f"{var}={value}\n")58 print("Environment variables have been saved to subgen.env")59 60def load_env_variables(env_filename='subgen.env'):61 try:62 with open(env_filename, 'r') as file:63 for line in file:64 line = line.strip()65 if line and not line.startswith('#') and '=' in line:66 var, value = line.split('=', 1)67 # Only set if not already set by a higher priority mechanism (like external env var)68 # For this simple loader, we'll let it overwrite,69 # and CLI args will overwrite these later if specified.70 os.environ[var] = value71 print(f"Environment variables have been loaded from {env_filename}")72 except FileNotFoundError:73 print(f"{env_filename} file not found. Consider running with --setup-bazarr or creating it manually.")74 75def main():76 if 'python3' in sys.executable:77 python_cmd = 'python3'78 elif 'python' in sys.executable:79 python_cmd = 'python'80 else:81 print("Script started with an unknown command")82 sys.exit(1)83 if sys.version_info[0] < 3:84 print(f"This script requires Python 3 or higher, you are running {sys.version}")85 sys.exit(1)86 87 os.chdir(os.path.dirname(os.path.abspath(__file__)))88 89 parser = argparse.ArgumentParser(prog="python launcher.py", formatter_class=argparse.ArgumentDefaultsHelpFormatter)90 # Changed: action='store_true' means it's False by default, True if flag is present91 parser.add_argument('-d', '--debug', action='store_true', help="Enable console debugging (overrides .env and external ENV)")92 parser.add_argument('-i', '--install', action='store_true', help="Install/update all necessary packages")93 # Changed: action='store_true'94 parser.add_argument('-a', '--append', action='store_true', help="Append 'Transcribed by whisper' (overrides .env and external ENV)")95 parser.add_argument('-u', '--update', action='store_true', help="Update Subgen")96 parser.add_argument('-x', '--exit-early', action='store_true', help="Exit without running subgen.py")97 parser.add_argument('-s', '--setup-bazarr', action='store_true', help="Prompt for common Bazarr setup parameters and save them for future runs")98 parser.add_argument('-b', '--branch', type=str, default='main', help='Specify the branch to download from')99 parser.add_argument('-l', '--launcher-update', action='store_true', help="Update launcher.py and re-launch")100 101 args = parser.parse_args()102 103 branch_name = args.branch if args.branch != 'main' else os.getenv('BRANCH', 'main')104 script_name_suffix = f"-{branch_name}.py" if branch_name != "main" else ".py"105 subgen_script_to_run = f"subgen{script_name_suffix}"106 language_code_script_to_download = f"language_code{script_name_suffix}"107 108 109 if args.launcher_update or convert_to_bool(os.getenv('LAUNCHER_UPDATE')):110 print(f"Updating launcher.py from GitHub branch {branch_name}...")111 download_from_github(f"https://raw.githubusercontent.com/McCloudS/subgen/{branch_name}/launcher.py", f'launcher{script_name_suffix}')112 excluded_args = ['--launcher-update', '-l']113 new_args = [arg for arg in sys.argv[1:] if arg not in excluded_args]114 print(f"Relaunching updated launcher: launcher{script_name_suffix}")115 os.execl(sys.executable, sys.executable, f"launcher{script_name_suffix}", *new_args)116 # The script will not continue past os.execl117 118 # --- Environment Variable Handling ---119 # 1. Load from .env file first. This sets a baseline.120 # External environment variables (set before launcher.py) will already be in os.environ121 # and won't be overwritten by load_env_variables IF load_env_variables checked for existence.122 # For simplicity, this version of load_env_variables *will* overwrite.123 # If you need to preserve external env vars over .env, load_env_variables needs adjustment.124 if args.setup_bazarr:125 prompt_and_save_bazarr_env_variables()126 # After saving, load them immediately for this run127 load_env_variables()128 else:129 # Load if not setting up, assuming subgen.env might exist130 load_env_variables()131 132 133 # 2. Override with command-line arguments (highest priority for these specific flags)134 if args.debug: # If -d or --debug was passed135 os.environ['DEBUG'] = 'True'136 print("Launcher CLI: DEBUG set to True")137 elif 'DEBUG' not in os.environ: # If not set by CLI and not by .env or external138 os.environ['DEBUG'] = 'False' # Default to False if nothing else specified it139 print("Launcher: DEBUG defaulted to False (no prior setting)")140 141 142 if args.append: # If -a or --append was passed143 os.environ['APPEND'] = 'True'144 print("Launcher CLI: APPEND set to True")145 elif 'APPEND' not in os.environ: # If not set by CLI and not by .env or external146 os.environ['APPEND'] = 'False' # Default to False if nothing else specified it147 #print("Launcher: APPEND defaulted to False (no prior setting)")148 # --- End Environment Variable Handling ---149 150 151 requirements_url = "https://raw.githubusercontent.com/McCloudS/subgen/main/requirements.txt"152 requirements_file = "requirements.txt"153 154 if args.install:155 download_from_github(requirements_url, requirements_file)156 install_packages_from_requirements(requirements_file)157 158 if not os.path.exists(subgen_script_to_run) or args.update or convert_to_bool(os.getenv('UPDATE')):159 print(f"Downloading {subgen_script_to_run} from GitHub branch {branch_name}...")160 download_from_github(f"https://raw.githubusercontent.com/McCloudS/subgen/{branch_name}/subgen.py", subgen_script_to_run)161 print(f"Downloading {language_code_script_to_download} from GitHub branch {branch_name}...")162 download_from_github(f"https://raw.githubusercontent.com/McCloudS/subgen/{branch_name}/language_code.py", language_code_script_to_download)163 164 else:165 print(f"{subgen_script_to_run} exists and UPDATE is set to False, skipping download.")166 167 if not args.exit_early:168 #print(f"DEBUG environment variable for subgen.py: {os.getenv('DEBUG')}")169 #print(f"APPEND environment variable for subgen.py: {os.getenv('APPEND')}")170 print(f'Launching {subgen_script_to_run}')171 try:172 subprocess.run([python_cmd, '-u', subgen_script_to_run], check=True)173 except FileNotFoundError:174 print(f"Error: Could not find {subgen_script_to_run}. Make sure it was downloaded correctly.")175 except subprocess.CalledProcessError as e:176 print(f"Error running {subgen_script_to_run}: {e}")177 178 else:179 print("Not running subgen.py: -x or --exit-early set")180 181if __name__ == "__main__":182 main()183 