machineconfig 1.9__py3-none-any.whl → 1.92__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of machineconfig might be problematic. Click here for more details.

Files changed (55) hide show
  1. machineconfig/__init__.py +2 -4
  2. machineconfig/jobs/python/check_installations.py +14 -6
  3. machineconfig/jobs/python/checkout_version.py +27 -32
  4. machineconfig/jobs/python/create_bootable_media.py +1 -1
  5. machineconfig/jobs/python/python_cargo_build_share.py +2 -2
  6. machineconfig/jobs/python/tasks.py +2 -2
  7. machineconfig/jobs/python_custom_installers/{helix.py → hx.py} +21 -6
  8. machineconfig/profile/create.py +23 -21
  9. machineconfig/profile/create_hardlinks.py +101 -0
  10. machineconfig/profile/shell.py +10 -7
  11. machineconfig/scripts/python/cloud_copy.py +19 -16
  12. machineconfig/scripts/python/cloud_repo_sync.py +94 -47
  13. machineconfig/scripts/python/cloud_sync.py +78 -61
  14. machineconfig/scripts/python/croshell.py +6 -6
  15. machineconfig/scripts/python/devops.py +22 -22
  16. machineconfig/scripts/python/devops_add_ssh_key.py +1 -1
  17. machineconfig/scripts/python/devops_backup_retrieve.py +19 -10
  18. machineconfig/scripts/python/devops_devapps_install.py +80 -62
  19. machineconfig/scripts/python/devops_update_repos.py +5 -5
  20. machineconfig/scripts/python/dotfile.py +4 -4
  21. machineconfig/scripts/python/fire_jobs.py +115 -63
  22. machineconfig/scripts/python/gh_models.py +55 -0
  23. machineconfig/scripts/python/mount_nfs.py +1 -1
  24. machineconfig/scripts/python/mount_nw_drive.py +3 -3
  25. machineconfig/scripts/python/mount_ssh.py +2 -3
  26. machineconfig/scripts/python/pomodoro.py +1 -1
  27. machineconfig/scripts/python/repos.py +22 -23
  28. machineconfig/scripts/python/scheduler.py +1 -1
  29. machineconfig/scripts/python/start_slidev.py +12 -6
  30. machineconfig/scripts/python/start_terminals.py +5 -4
  31. machineconfig/scripts/python/wifi_conn.py +34 -42
  32. machineconfig/scripts/python/wsl_windows_transfer.py +1 -1
  33. machineconfig/settings/__init__.py +0 -0
  34. machineconfig/setup_windows/wt_and_pwsh/set_pwsh_theme.py +1 -1
  35. machineconfig/setup_windows/wt_and_pwsh/set_wt_settings.py +3 -2
  36. machineconfig/utils/installer.py +86 -41
  37. machineconfig/utils/procs.py +2 -2
  38. machineconfig/utils/scheduling.py +3 -3
  39. machineconfig/utils/utils.py +136 -56
  40. machineconfig/utils/ve.py +145 -95
  41. {machineconfig-1.9.dist-info → machineconfig-1.92.dist-info}/METADATA +160 -155
  42. machineconfig-1.92.dist-info/RECORD +70 -0
  43. machineconfig/jobs/python_custom_installers/azuredatastudio.py +0 -36
  44. machineconfig/jobs/python_custom_installers/bypass_paywall.py +0 -30
  45. machineconfig/jobs/python_custom_installers/docker_desktop.py +0 -52
  46. machineconfig/jobs/python_custom_installers/goes.py +0 -35
  47. machineconfig/jobs/python_custom_installers/lvim.py +0 -48
  48. machineconfig/jobs/python_custom_installers/ngrok.py +0 -39
  49. machineconfig/jobs/python_custom_installers/nvim.py +0 -48
  50. machineconfig/jobs/python_custom_installers/vscode.py +0 -45
  51. machineconfig/jobs/python_custom_installers/wezterm.py +0 -41
  52. machineconfig-1.9.dist-info/RECORD +0 -76
  53. {machineconfig-1.9.dist-info → machineconfig-1.92.dist-info}/LICENSE +0 -0
  54. {machineconfig-1.9.dist-info → machineconfig-1.92.dist-info}/WHEEL +0 -0
  55. {machineconfig-1.9.dist-info → machineconfig-1.92.dist-info}/top_level.txt +0 -0
@@ -6,79 +6,97 @@
6
6
  from tqdm import tqdm
7
7
  from crocodile.core import List as L
8
8
  from machineconfig.utils.utils import LIBRARY_ROOT, choose_multiple_options
9
- from machineconfig.utils.installer import get_installers, Installer, install_all
9
+ from machineconfig.utils.installer import get_installers, install_all, Installer, get_all_dicts
10
10
  from platform import system
11
- from typing import Any, Optional, Literal, TypeAlias
11
+ from typing import Any, Optional, Literal, TypeAlias, get_args
12
12
 
13
13
 
14
- WHICH: TypeAlias = Literal["AllEssentials", "EssentialsAndOthers", "SystemInstallers", "OtherDevApps", "PrecheckedCloudInstaller"]
14
+ WHICH_CAT: TypeAlias = Literal["AllEssentials", "EssentialsAndOthers", "SystemInstallers", "PrecheckedCloudInstaller"]
15
15
 
16
16
 
17
- def main(which: Optional[str] = None):
18
- sys = system()
19
- installers = get_installers(dev=False, system=sys) # + get_installers(dev=True, system=sys)
20
- default = "AllEssentials"
21
- options = ["SystemInstallers", "OtherDevApps", "EssentialsAndOthers", "PrecheckedCloudInstaller", default]
22
- options = [x.get_description() for x in tqdm(installers, desc="Checking installed programs")] + options
17
+ def main(which: Optional[WHICH_CAT | str] = None):
23
18
 
24
- if which is not None:
25
- return get_program(program_name=which, options=options, installers=list(installers))
19
+ if which is not None and which in get_args(WHICH_CAT): # install by category
20
+ return get_programs_by_category(program_name=which) # type: ignore
21
+
22
+ if which is not None: # install by name
23
+ program_total = ""
24
+ for a_which in (which.split(",") if type(which) == str else which):
25
+ kv = {}
26
+ for _category, v in get_all_dicts(system=system()).items():
27
+ kv.update(v)
28
+ if a_which not in kv:
29
+ raise ValueError(f"{a_which=} not found in {kv.keys()}")
30
+ print(f"Installing {a_which}", kv[a_which])
31
+ installer = Installer.from_dict(name=a_which, d=kv[a_which])
32
+ print(installer)
33
+ program = installer.install_robust(version=None) # finish the task
34
+ program = "echo 'Finished Installation'" # write an empty program
35
+ program_total += "\n" + program
36
+ return program_total
37
+
38
+ # interactive installation
39
+ installers = [Installer.from_dict(d=vd, name=name) for __kat, vds in get_all_dicts(system=system()).items() for name, vd in vds.items()]
40
+ options = [x.get_description() for x in tqdm(installers, desc="Checking installed programs")] + list(get_args(WHICH_CAT))
41
+ program_names = choose_multiple_options(msg="", options=options, header="CHOOSE DEV APP", default="AllEssentials")
26
42
 
27
- program_names = choose_multiple_options(msg="", options=options, header="CHOOSE DEV APP", default=str(default))
28
43
  total_program = ""
29
- for which in program_names:
30
- assert isinstance(which, str), f"program_name is not a string: {which}"
31
- total_program += "\n" + get_program(program_name=which, options=options, installers=list(installers))
44
+ for _an_idx, a_program_name in enumerate(program_names):
45
+ print(a_program_name)
46
+ if a_program_name in get_args(WHICH_CAT):
47
+ total_program += "\n" + get_programs_by_category(program_name=a_program_name) # type: ignore
48
+ else:
49
+ an_installer = installers[options.index(a_program_name)]
50
+ total_program += "\n" + an_installer.install_robust(version=None) # finish the task
32
51
  return total_program
33
52
 
34
53
 
35
- def get_program(program_name: str, options: list[str], installers: list[Installer]):
36
- if program_name == "AllEssentials" or program_name == "EssentialsAndOthers":
37
- installers_ = get_installers(dev=False, system=system())
38
- if program_name == "EssentialsAndOthers":
39
- installers_ += get_installers(dev=True, system=system())
40
- install_all(installers=L(installers))
41
- program = ""
42
- elif program_name == "SystemInstallers":
43
- if system() == "Windows": options_system = parse_apps_installer_windows(LIBRARY_ROOT.joinpath("setup_windows/apps.ps1").read_text())
44
- elif system() == "Linux":
45
- options_system_1 = parse_apps_installer_linux(LIBRARY_ROOT.joinpath("setup_linux/apps_dev.sh").read_text())
46
- options_system_2 = parse_apps_installer_linux(LIBRARY_ROOT.joinpath("setup_linux/apps.sh").read_text())
47
- options_system = {**options_system_1, **options_system_2}
48
- else: raise NotImplementedError(f"System {system()} not supported")
49
- program_names = choose_multiple_options(msg="", options=sorted(list(options_system.keys())), header="CHOOSE DEV APP")
50
- program = ""
51
- for name in program_names:
52
- sub_program = options_system[name]
53
- if sub_program.startswith("#winget"): sub_program = sub_program[1:]
54
- program += "\n" + sub_program
55
- elif program_name == "OtherDevApps":
56
- installers = get_installers(dev=True, system=system())
57
- options__: list[str] = [x.get_description() for x in tqdm(installers, desc="Checking installed programs")]
58
- program_names = choose_multiple_options(msg="", options=sorted(options__) + ["all"], header="CHOOSE DEV APP")
59
- if "all" in program_names: program_names = options__
60
- program = ""
61
- print(f"Installing:")
62
- L(program_names).print()
63
- for name in program_names:
64
- try:
65
- idx = options__.index(name)
66
- except ValueError as ve:
67
- print(f"{name=}")
68
- print(f"{options__=}")
69
- raise ve
70
- print(f"Installing {name}")
71
- sub_program = installers[idx].install_robust(version=None) # finish the task
72
- elif program_name == "PrecheckedCloudInstaller":
73
- from machineconfig.jobs.python.check_installations import PrecheckedCloudInstaller
74
- ci = PrecheckedCloudInstaller()
75
- ci.download_safe_apps(name="AllEssentials")
76
- program = ""
77
- else:
78
- idx = options.index(program_name)
79
- print(installers[idx])
80
- program = installers[idx].install_robust(version=None) # finish the task
81
- program = "echo 'Finished Installation'" # write an empty program
54
+ def get_programs_by_category(program_name: WHICH_CAT):
55
+ match program_name:
56
+ case "AllEssentials" | "EssentialsAndOthers":
57
+ installers_ = get_installers(dev=False, system=system())
58
+ if program_name == "EssentialsAndOthers":
59
+ installers_ += get_installers(dev=True, system=system())
60
+ install_all(installers=L(installers_))
61
+ program = ""
62
+
63
+ case "SystemInstallers":
64
+ if system() == "Windows": options_system = parse_apps_installer_windows(LIBRARY_ROOT.joinpath("setup_windows/apps.ps1").read_text())
65
+ elif system() == "Linux":
66
+ options_system_1 = parse_apps_installer_linux(LIBRARY_ROOT.joinpath("setup_linux/apps_dev.sh").read_text())
67
+ options_system_2 = parse_apps_installer_linux(LIBRARY_ROOT.joinpath("setup_linux/apps.sh").read_text())
68
+ options_system = {**options_system_1, **options_system_2}
69
+ else: raise NotImplementedError(f"System {system()} not supported")
70
+ program_names = choose_multiple_options(msg="", options=sorted(list(options_system.keys())), header="CHOOSE DEV APP")
71
+ program = ""
72
+ for name in program_names:
73
+ sub_program = options_system[name]
74
+ if sub_program.startswith("#winget"): sub_program = sub_program[1:]
75
+ program += "\n" + sub_program
76
+
77
+ # case "OtherDevApps":
78
+ # installers = get_installers(dev=True, system=system())
79
+ # options__: list[str] = [x.get_description() for x in tqdm(installers, desc="Checking installed programs")]
80
+ # program_names = choose_multiple_options(msg="", options=sorted(options__) + ["all"], header="CHOOSE DEV APP")
81
+ # if "all" in program_names: program_names = options__
82
+ # program = ""
83
+ # print("Installing:")
84
+ # L(program_names).print()
85
+ # for name in program_names:
86
+ # try:
87
+ # idx = options__.index(name)
88
+ # except ValueError as ve:
89
+ # print(f"{name=}")
90
+ # print(f"{options__=}")
91
+ # raise ve
92
+ # print(f"Installing {name}")
93
+ # sub_program = installers[idx].install_robust(version=None) # finish the task
94
+
95
+ case "PrecheckedCloudInstaller":
96
+ from machineconfig.jobs.python.check_installations import PrecheckedCloudInstaller
97
+ ci = PrecheckedCloudInstaller()
98
+ ci.download_safe_apps(name="AllEssentials")
99
+ program = ""
82
100
  return program
83
101
 
84
102
 
@@ -3,7 +3,6 @@
3
3
  """
4
4
 
5
5
  from crocodile.file_management import P, Read
6
- from crocodile.core import install_n_import
7
6
  from machineconfig.utils.utils import DEFAULTS_PATH
8
7
  from platform import system
9
8
 
@@ -11,7 +10,7 @@ from platform import system
11
10
  sep = "\n"
12
11
 
13
12
 
14
- def main(verbose: bool = True) -> str:
13
+ def main(verbose: bool=True) -> str:
15
14
  _ = verbose
16
15
  repos: list[str] = ["~/code/crocodile", "~/code/machineconfig", ]
17
16
  try:
@@ -20,10 +19,10 @@ def main(verbose: bool = True) -> str:
20
19
  repos += tmp
21
20
  except (FileNotFoundError, KeyError, IndexError):
22
21
  print(f"Missing {DEFAULTS_PATH} or section [general] or key repos. Using default repos.")
23
- print(f"""It should look like this:
22
+ print("""It should look like this:
24
23
  [general]
25
24
  repos = ~/code/repo1,~/code/repo2
26
- rclone_config_name = onedriveWork
25
+ rclone_config_name = onedrivePersonal
27
26
  email_config_name = Yahoo3
28
27
  to_email = myemail@email.com
29
28
  """)
@@ -31,7 +30,8 @@ to_email = myemail@email.com
31
30
  repos_objs = []
32
31
  for a_package_path in repos:
33
32
  try:
34
- repo = install_n_import("git", "gitpython").Repo(str(P(a_package_path).expanduser()), search_parent_directories=True)
33
+ import git
34
+ repo = git.Repo(str(P(a_package_path).expanduser()), search_parent_directories=True)
35
35
  repos_objs.append(repo)
36
36
  except Exception as ex:
37
37
  print(ex)
@@ -4,7 +4,7 @@
4
4
 
5
5
 
6
6
  from crocodile.file_management import P
7
- from machineconfig.profile.create import symlink
7
+ from machineconfig.profile.create import symlink_func
8
8
  from machineconfig.utils.utils import LIBRARY_ROOT, REPO_ROOT
9
9
  import argparse
10
10
 
@@ -16,7 +16,7 @@ def main():
16
16
  # FLAGS
17
17
  parser.add_argument("--overwrite", "-o", help="Overwrite.", action="store_true") # default is False
18
18
  # optional
19
- parser.add_argument("-d", "--dest", help=f"destination folder", default="")
19
+ parser.add_argument("-d", "--dest", help="destination folder", default="")
20
20
 
21
21
  args = parser.parse_args()
22
22
  orig_path = P(args.file).expanduser().absolute()
@@ -28,9 +28,9 @@ def main():
28
28
  new_path = REPO_ROOT.joinpath(junction)
29
29
  else: new_path = P(args.dest).expanduser().absolute().create().joinpath(orig_path.name)
30
30
 
31
- symlink(this=orig_path, to_this=new_path, prioritize_to_this=args.overwrite)
31
+ symlink_func(this=orig_path, to_this=new_path, prioritize_to_this=args.overwrite)
32
32
 
33
- print(f"Map completed. To enshrine this mapping, add the following line to the mapper.toml file:")
33
+ print("Map completed. To enshrine this mapping, add the following line to the mapper.toml file:")
34
34
  print(f"nano {LIBRARY_ROOT}/symlinks/mapper.toml")
35
35
  print(f"""
36
36
  [{new_path.parent.name}]
@@ -10,7 +10,7 @@ fire
10
10
 
11
11
 
12
12
  from machineconfig.utils.utils import display_options, choose_one_option, PROGRAM_PATH, choose_ssh_host, match_file_name, sanitize_path
13
- from crocodile.file_management import P, install_n_import
13
+ from crocodile.file_management import P, install_n_import, Read
14
14
  from crocodile.core import Display, randstr
15
15
  import inspect
16
16
  import platform
@@ -19,6 +19,45 @@ from typing import Callable, Any, Optional
19
19
  import argparse
20
20
 
21
21
 
22
+ def search_for_files_of_interest(path_obj: P):
23
+ if path_obj.joinpath(".venv").exists():
24
+ path_objects = path_obj.search("*", not_in=[".venv"]).list
25
+ files: list[P] = []
26
+ for a_path_obj in path_objects:
27
+ files += search_for_files_of_interest(path_obj=a_path_obj)
28
+ return files
29
+ py_files = path_obj.search(pattern="*.py", not_in=["__init__.py"], r=True).list
30
+ ps_files = path_obj.search(pattern="*.ps1", r=True).list
31
+ sh_files = path_obj.search(pattern="*.sh", r=True).list
32
+ files = py_files + ps_files + sh_files
33
+ return files
34
+
35
+
36
+ def convert_kwargs_to_fire_kwargs_str(kwargs: dict[str, Any]) -> str:
37
+ # https://google.github.io/python-fire/guide/
38
+ # https://github.com/google/python-fire/blob/master/docs/guide.md#argument-parsing
39
+ if not kwargs: # empty dict
40
+ kwargs_str = ''
41
+ else:
42
+ if len(kwargs) == 1:
43
+ kwargs_str = f""" --{list(kwargs.keys())[0]} {list(kwargs.values())[0]} """
44
+ else:
45
+ # print(f"len(kwargs) = {len(kwargs)}")
46
+ tmp_list: list[str] = []
47
+ for k, v in kwargs.items():
48
+ if v is not None:
49
+ item = f'"{k}": "{v}"'
50
+ else:
51
+ item = f'"{k}": None'
52
+ tmp_list.append(item)
53
+ tmp__ = ", ".join(tmp_list)
54
+ kwargs_str = "'{" + tmp__ + "}'"
55
+ return kwargs_str
56
+
57
+
58
+ str2obj = {"True": True, "False": False, "None": None}
59
+
60
+
22
61
  def main() -> None:
23
62
  parser = argparse.ArgumentParser()
24
63
  parser.add_argument("path", nargs='?', type=str, help="The directory containing the jobs", default=".")
@@ -37,30 +76,32 @@ def main() -> None:
37
76
  parser.add_argument("--streamlit", "-S", action="store_true", help="run as streamlit app")
38
77
  parser.add_argument("--history", "-H", action="store_true", help="choose from history")
39
78
  # parser.add_argument("--git_pull", "-g", action="store_true", help="Start by pulling the git repo")
79
+ parser.add_argument("--optimized", "-O", action="store_true", help="Run the optimized version of the function")
40
80
  parser.add_argument("--Nprocess", "-p", type=int, help="Number of processes to use", default=1)
41
- parser.add_argument("--kw", nargs="*", default=None, help="keyword arguments to pass to the function in the form of k1 v1 k2 v2 ...")
81
+ parser.add_argument("--kw", nargs="*", default=None, help="keyword arguments to pass to the function in the form of k1 v1 k2 v2 ... (meaning k1=v1, k2=v2, etc)")
42
82
 
43
83
  args = parser.parse_args()
84
+
85
+ # Convert args.kw to dictionary
44
86
  if args.kw is not None:
45
87
  assert len(args.kw) % 2 == 0, f"args.kw must be a list of even length. Got {len(args.kw)}"
46
88
  kwargs = dict(zip(args.kw[::2], args.kw[1::2]))
47
- # print(f"kwargs = {kwargs}")
89
+ for key, value in kwargs.items():
90
+ if value in str2obj:
91
+ kwargs[key] = str2obj[value]
92
+ if args.function is None: # if user passed arguments and forgot to pass function, then assume they want to run the main function.
93
+ args.choose_function = True
48
94
  else:
49
95
  kwargs = {}
50
96
 
51
97
  path_obj = sanitize_path(P(args.path))
52
98
  if not path_obj.exists():
53
- path_obj = match_file_name(args.path)
54
- print(path_obj)
99
+ path_obj = match_file_name(sub_string=args.path)
55
100
  else: pass
56
101
 
57
102
  if path_obj.is_dir():
58
103
  print(f"Seaching recursively for all python file in directory `{path_obj}`")
59
- py_files = path_obj.search(pattern="*.py", not_in=["__init__.py"], r=True).list
60
- ps_files = path_obj.search(pattern="*.ps1", r=True).list
61
- sh_files = path_obj.search(pattern="*.sh", r=True).list
62
- files = py_files + ps_files + sh_files
63
-
104
+ files = search_for_files_of_interest(path_obj)
64
105
  choice_file = choose_one_option(options=files, fzf=True)
65
106
  choice_file = P(choice_file)
66
107
  else:
@@ -90,13 +131,21 @@ def main() -> None:
90
131
  args.ve = get_ve_profile(choice_file)
91
132
 
92
133
  if args.streamlit:
93
- import socket
94
- try: local_ip_v4 = socket.gethostbyname(socket.gethostname() + ".local") # without .local, in linux machines, '/etc/hosts' file content, you have an IP address mapping with '127.0.1.1' to your hostname
95
- except Exception:
96
- print(f"Warning: Could not get local_ip_v4. This is probably because you are running a WSL instance") # TODO find a way to get the local_ip_v4 in WSL
97
- local_ip_v4 = socket.gethostbyname(socket.gethostname())
98
- print(f"🚀 Streamlit app is running at: http://{local_ip_v4}:8501")
134
+ from crocodile.environment import get_network_addresses
135
+ local_ip_v4 = get_network_addresses()["local_ip_v4"]
136
+ computer_name = platform.node()
137
+ port = 8501
138
+ if choice_file.parent.joinpath(".streamlit/config.toml").exists():
139
+ config = Read.toml(choice_file.parent.joinpath(".streamlit/config.toml"))
140
+ if "server" in config:
141
+ if "port" in config["server"]:
142
+ port = config["server"]["port"]
143
+ message = f"🚀 Streamlit app is running @:\n1- http://{local_ip_v4}:{port}\n2- http://{computer_name}:{port}\n3- http://localhost:{port}"
144
+ from rich.panel import Panel
145
+ from rich import print as rprint
146
+ rprint(Panel(message))
99
147
  exe = "streamlit run --server.address 0.0.0.0 --server.headless true"
148
+ exe = f"cd '{choice_file.parent}'; " + exe
100
149
  elif args.interactive is False: exe = "python"
101
150
  elif args.jupyter: exe = "jupyter-lab"
102
151
  else:
@@ -120,6 +169,7 @@ except (ImportError, ModuleNotFoundError) as ex:
120
169
  txt = txt + f"""
121
170
  res = {choice_function}({('**' + str(kwargs)) if kwargs else ''})
122
171
  """
172
+
123
173
  txt = f"""
124
174
  try:
125
175
  from rich.panel import Panel
@@ -132,49 +182,27 @@ except ImportError as _ex:
132
182
  """ + txt
133
183
  choice_file = P.tmp().joinpath(f'tmp_scripts/python/{P(choice_file).parent.name}_{P(choice_file).stem}_{randstr()}.py').create(parents_only=True).write_text(txt)
134
184
 
135
- # determining basic command structure: putting together exe & choice_file & choice_function & pdb
185
+ # ========================= determining basic command structure: putting together exe & choice_file & choice_function & pdb
136
186
  if args.debug:
137
187
  if platform.system() == "Windows":
138
188
  command = f"{exe} -m ipdb {choice_file} " # pudb is not available on windows machines, use poor man's debugger instead.
139
189
  elif platform.system() in ["Linux", "Darwin"]:
140
190
  command = f"{exe} -m pudb {choice_file} " # TODO: functions not supported yet in debug mode.
141
191
  else: raise NotImplementedError(f"Platform {platform.system()} not supported.")
142
- elif choice_function is not None and not args.module: # if args.module, then kwargs are handled in the impot script, no need to pass them in fire command.
143
- # https://google.github.io/python-fire/guide/
144
- # https://github.com/google/python-fire/blob/master/docs/guide.md#argument-parsing
145
- if not kwargs: # empty dict
146
- kwargs_str = ''
147
- else:
148
- if len(kwargs) == 1:
149
- kwargs_str = f""" --{list(kwargs.keys())[0]} {list(kwargs.values())[0]} """
150
- else:
151
- # print(f"len(kwargs) = {len(kwargs)}")
152
- tmp_list: list[str] = []
153
- for k, v in kwargs.items():
154
- if v is not None:
155
- item = f'"{k}": "{v}"'
156
- else:
157
- item = f'"{k}": None'
158
- tmp_list.append(item)
159
- tmp__ = ", ".join(tmp_list)
160
- kwargs_str = "'{" + tmp__ + "}'"
192
+ elif args.module:
193
+ # both selected function and kwargs are mentioned in the made up script, therefore no need for fire module.
194
+ command = f"{exe} {choice_file} "
195
+ elif choice_function is not None:
196
+ kwargs_str = convert_kwargs_to_fire_kwargs_str(kwargs)
161
197
  command = f"{exe} -m fire {choice_file} {choice_function} {kwargs_str}"
162
- # else:
163
- # print(f"{kwargs=}")
164
- # print(f"{choice_function_args=}")
165
- # if choice_function != "RUN AS MAIN":
166
- # kgs1, _ = interactively_run_function(module[choice_function])
167
- # " ".join([f"--{k} {v}" for k, v in kgs1.items()])
198
+ elif args.streamlit:
199
+ # for .streamlit config to work, it needs to be in the current directory.
200
+ command = f"cd {choice_file.parent}\n\n{exe} {choice_file.name}\n\ncd {P.cwd()}"
201
+ elif args.cmd:
202
+ command = rf""" cd /d {choice_file.parent} & {exe} {choice_file.name} """
168
203
  else:
169
- if not args.streamlit: command = f"{exe} {choice_file} "
170
- else:
171
- if not args.cmd:
172
- # for .streamlit config to work, it needs to be in the current directory.
173
- command = f"cd {choice_file.parent}\n\n{exe} {choice_file.name}\n\ncd {P.cwd()}"
174
- else:
175
- command = rf""" cd /d {choice_file.parent} & {exe} {choice_file.name} """
176
- # command = f"cd {choice_file.parent}\n\n{exe} {choice_file.name}\n\ncd {P.cwd()}"
177
-
204
+ # command = f"cd {choice_file.parent}\n\n{exe} {choice_file.name}\n\ncd {P.cwd()}"
205
+ command = f"{exe} {choice_file} "
178
206
  # this installs in ve env, which is not execution env
179
207
  # if "ipdb" in command: install_n_import("ipdb")
180
208
  # if "pudb" in command: install_n_import("pudb")
@@ -183,9 +211,9 @@ except ImportError as _ex:
183
211
  if "ipdb" in command: command = f"pip install ipdb\n\n{command}"
184
212
  if "pudb" in command: command = f"pip install pudb\n\n{command}"
185
213
  if platform.system() == "Windows":
186
- command = f". activate_ve {args.ve}\n\n{command}"
214
+ command = f". $HOME/scripts/activate_ve {args.ve}\n\n{command}"
187
215
  else:
188
- command = f". ~/scripts/activate_ve {args.ve}\n\n{command}"
216
+ command = f". $HOME/scripts/activate_ve {args.ve}\n\n{command}"
189
217
  else:
190
218
  # CMD equivalent
191
219
  if "ipdb" in command: command = f"pip install ipdb & {command}"
@@ -195,20 +223,23 @@ except ImportError as _ex:
195
223
 
196
224
  if args.submit_to_cloud:
197
225
  command = f"""
198
- . activate_ve {args.ve}
226
+ . $HOME/scripts/activate_ve {args.ve}
199
227
  python -m crocodile.cluster.templates.cli_click --file {choice_file} """
200
- if choice_function is not None: command += f"--function {choice_function} "
228
+ if choice_function is not None:
229
+ command += f"--function {choice_function} "
201
230
  try: install_n_import("clipboard").copy(command)
202
231
  except Exception as ex: print(f"Failed to copy command to clipboard. {ex}")
203
232
 
204
233
  if args.loop:
205
- command = command + f"\n" + f". {PROGRAM_PATH}"
234
+ command = command + "\n" + f". {PROGRAM_PATH}"
206
235
 
207
236
  if args.Nprocess > 1:
208
237
  lines = [f""" zellij action new-tab --name nProcess{randstr(2)}"""]
209
- command = command.replace(". activate_ve", ". ~/scripts/activate_ve")
238
+ command = command.replace(". activate_ve", ". $HOME/scripts/activate_ve")
210
239
  for an_arg in range(args.Nprocess):
211
240
  sub_command = f"{command} --idx={an_arg} --idx_max={args.Nprocess}"
241
+ if args.optimized:
242
+ sub_command = sub_command.replace("python ", "python -OO ")
212
243
  sub_command_path = P.tmpfile(suffix=".sh").write_text(sub_command)
213
244
  lines.append(f"""zellij action new-pane -- bash {sub_command_path} """)
214
245
  lines.append("sleep 1") # python tends to freeze if you launch instances within 1 microsecond of each other
@@ -216,9 +247,17 @@ python -m crocodile.cluster.templates.cli_click --file {choice_file} """
216
247
 
217
248
  # TODO: send this command to terminal history. In powershell & bash there is no way to do it with a command other than goiing to history file. In Mcfly there is a way but its linux only tool. # if platform.system() == "Windows": command = f" ({command}) | Add-History -PassThru "
218
249
  # mcfly add --exit 0 command
219
- print(f"🔥 command:\n{command}\n\n")
250
+ if args.optimized:
251
+ # note that in ipython, optimization is meaningless.
252
+ command = command.replace("python ", "python -OO ")
220
253
  # if platform.system() == "Linux":
221
254
  # command = "timeout 1s aafire -driver slang\nclear\n" + command
255
+
256
+ from rich.panel import Panel
257
+ from rich.console import Console
258
+ from rich.syntax import Syntax
259
+ console = Console()
260
+ console.print(Panel(Syntax(command, lexer="shell"), title=f"🔥 fire command @ {PROGRAM_PATH}: "), style="bold red")
222
261
  PROGRAM_PATH.write_text(command)
223
262
 
224
263
 
@@ -290,7 +329,8 @@ def interactively_run_function(func: Callable[[Any], Any]):
290
329
  if value == "": value = default
291
330
  else: value = input(f"Please enter a value for argument `{param.name}` (type = {hint}) : ")
292
331
  try:
293
- if param.annotation is not inspect.Parameter.empty: value = param.annotation(value)
332
+ if param.annotation is not inspect.Parameter.empty:
333
+ value = param.annotation
294
334
  except (TypeError, ValueError) as err:
295
335
  raise ValueError(f"Invalid input: {value} is not of type {param.annotation}") from err
296
336
  if param.kind == inspect.Parameter.KEYWORD_ONLY: kwargs[param.name] = value
@@ -315,7 +355,7 @@ def run_on_remote(func_file: str, args: argparse.Namespace):
315
355
 
316
356
  def find_repo_root_path(start_path: str) -> Optional[str]:
317
357
  root_files = ['setup.py', 'pyproject.toml', '.git']
318
- path: str = start_path
358
+ path: str=start_path
319
359
  trials = 0
320
360
  root_path = os.path.abspath(os.sep)
321
361
  while path != root_path and trials < 20:
@@ -331,11 +371,23 @@ def find_repo_root_path(start_path: str) -> Optional[str]:
331
371
  def get_import_module_code(module_path: str):
332
372
  root_path = find_repo_root_path(module_path)
333
373
  if root_path is None: # just make a desperate attempt to import it
334
- module_name = module_path.lstrip(os.sep).replace(os.sep, '.').replace('.py', '')
374
+ module_name = module_path.lstrip(os.sep).replace(os.sep, '.')
375
+ if module_name.endswith(".py"):
376
+ module_name = module_name[:-3]
335
377
  else:
336
378
  relative_path = module_path.replace(root_path, '')
337
- module_name = relative_path.lstrip(os.sep).replace(os.sep, '.').replace('.py', '')
338
- module_name = module_name.replace("src.", "").replace("myresources.", "").replace("resources.", "").replace("source.", "").replace("resources.", "").replace("source.", "").replace("src.", "").replace("myresources.", "").replace("resources.", "").replace("source.", "").replace("src.", "").replace("myresources.", "").replace("resources.", "").replace("source.", "").replace("src.", "").replace("myresources.", "").replace("resources.", "").replace("source.", "").replace("src.", "").replace("myresources.", "").replace("resources.", "").replace("source.", "").replace("src.", "").replace("myresources.", "").replace("resources.", "").replace("source.", "").replace("src.", "").replace("myresources.", "").replace("resources.", "").replace("source.", "").replace("src.", "").replace("resources.", "").replace("source.", "")
379
+ module_name = relative_path.lstrip(os.sep).replace(os.sep, '.')
380
+ if module_name.endswith(".py"):
381
+ module_name = module_name[:-3]
382
+ # module_name = module_name.replace("src.", "").replace("myresources.", "").replace("resources.", "").replace("source.", "")
383
+ if module_name.startswith("src."):
384
+ module_name = module_name[4:]
385
+ if module_name.startswith("myresources."):
386
+ module_name = module_name[12:]
387
+ if module_name.startswith("resources."):
388
+ module_name = module_name[10:]
389
+ if module_name.startswith("source."):
390
+ module_name = module_name[7:]
339
391
  if any(char in module_name for char in "- :/\\"):
340
392
  module_name = "IncorrectModuleName"
341
393
  # TODO: use py_compile to check if the statement is valid code to avoid syntax errors that can't be caught.
@@ -0,0 +1,55 @@
1
+
2
+ # as per https://github.com/marketplace/models/azure-openai/o1-preview
3
+ from openai import OpenAI
4
+ from crocodile.file_management import Read, P
5
+
6
+
7
+ gh_token = Read.ini(P.home().joinpath("dotfiles/creds/git/git_host_tokens.ini"))['thisismygitrepo']['newLongterm']
8
+ endpoint = "https://models.inference.ai.azure.com"
9
+ model_name_preferences = ["o3-mini", "o1-preview", "o1-mini", "GPT-4o", "GPT-4-o-mini"]
10
+ client__ = OpenAI(
11
+ base_url=endpoint,
12
+ api_key=gh_token,
13
+ )
14
+
15
+
16
+ def get_response(client, model_name: str, messages: list[str]):
17
+ print(f"Getting response from model {model_name}")
18
+ try:
19
+ response = client.chat.completions.create(
20
+ messages=messages,
21
+ model=model_name
22
+ )
23
+ return response.choices
24
+ except Exception as e:
25
+ print(f"Error with model {model_name}: {e}")
26
+ return None
27
+
28
+
29
+ def interactive_chat():
30
+ conversation_history = []
31
+ model_index = 0
32
+ model_name = model_name_preferences[model_index]
33
+ while True:
34
+ print(f"Using model {model_name}".center(80, "="))
35
+ while True:
36
+ user_input = input("You: ")
37
+ conversation_history.append({"role": "user", "content": user_input})
38
+
39
+ while True:
40
+ choices = get_response(client__, model_name, conversation_history)
41
+ if choices is None:
42
+ model_index += 1
43
+ model_name = model_name_preferences[model_index % len(model_name_preferences)]
44
+ print(f"Switching to model {model_name}".center(80, "="))
45
+ continue
46
+ else:
47
+ break
48
+
49
+ for a_choice in choices:
50
+ response_content = a_choice.message.content
51
+ print("\n" * 5)
52
+ print(f"AI: {response_content}")
53
+ conversation_history.append({"role": "assistant", "content": response_content})
54
+
55
+ interactive_chat()
@@ -11,7 +11,7 @@ import platform
11
11
 
12
12
 
13
13
  def main():
14
- print(f"Mounting NFS Share ... ")
14
+ print("Mounting NFS Share ... ")
15
15
  share_info = input("share path? (e.g. machine:~/data/share_nfs) [press enter for interactive choice] = ")
16
16
  if share_info == "":
17
17
  tmp = choose_ssh_host(multi=False)
@@ -6,15 +6,15 @@ import platform
6
6
 
7
7
 
8
8
  def main():
9
- print(f"Welcome to the WindowsNetworkDrive Mounting Wizard")
9
+ print("Welcome to the WindowsNetworkDrive Mounting Wizard")
10
10
  drive_location = input("Enter the network drive location (ex: //192.168.1.100/Share): ")
11
11
  machine_name = drive_location.split("//")[1].split("/")[0]
12
12
  mount_point = input(f"Enter the mount point directory (ex: /mnt/network) [default: ~/data/mount_nw/{machine_name}]: ")
13
13
  if mount_point == "": mount_point = P.home().joinpath(fr"data/mount_nw/{machine_name}")
14
14
  else: mount_point = P(mount_point).expanduser()
15
15
 
16
- username = input(f"Enter the username: ")
17
- password = input(f"Enter the password: ")
16
+ username = input("Enter the username: ")
17
+ password = input("Enter the password: ")
18
18
  if platform.system() == "Linux":
19
19
  PROGRAM_PATH.write_text(f"""
20
20
  drive_location='{drive_location}'
@@ -11,8 +11,7 @@ from machineconfig.utils.utils import PROGRAM_PATH, choose_ssh_host
11
11
 
12
12
 
13
13
  def main():
14
-
15
- print(f"Mounting SSHFS ... ")
14
+ print("Mounting SSHFS ... ")
16
15
  share_info = input("share path? (e.g. user@host:/path) [press enter for interactive choice] = ")
17
16
  if share_info == "":
18
17
  tmp = choose_ssh_host(multi=False)
@@ -28,7 +27,7 @@ def main():
28
27
  if mount_point == "": mount_point = P.home().joinpath(fr"data/mount_ssh/{ssh.hostname}")
29
28
 
30
29
  if system() == "Linux":
31
- txt = fr"""
30
+ txt = """
32
31
  sshfs alex@:/media/dbhdd /media/dbhdd\
33
32
  """
34
33
  elif system() == "Windows":