rahul7star commited on
Commit
47815ca
·
verified ·
1 Parent(s): 0d1af65

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -0
app.py CHANGED
@@ -83,7 +83,52 @@ def extract_code_from_text(text: str):
83
 
84
  return code.strip()
85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  def install_packages_from_code(code: str):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
  """
88
  Scan Python code for imports and install missing packages automatically.
89
  """
 
83
 
84
  return code.strip()
85
 
86
+ import re
87
+ import subprocess
88
+ import sys
89
+ import importlib.util
90
+
91
+ # List of common standard library modules to skip
92
+ STD_LIBS = {
93
+ "os", "sys", "math", "re", "json", "time", "pathlib",
94
+ "subprocess", "itertools", "functools", "collections",
95
+ "random", "datetime", "threading", "multiprocessing",
96
+ "shutil", "tempfile", "logging"
97
+ }
98
+
99
  def install_packages_from_code(code: str):
100
+ """
101
+ Scan Python code for any imports and attempt to install missing packages automatically.
102
+ Works for:
103
+ - import X
104
+ - import X as Y
105
+ - from X import Y
106
+ - from X.Y import Z
107
+ """
108
+ # Find all import statements
109
+ matches = re.findall(r'^\s*(?:import|from)\s+([a-zA-Z0-9_\.]+)', code, flags=re.MULTILINE)
110
+
111
+ # Convert to top-level package names
112
+ packages = set()
113
+ for m in matches:
114
+ top_pkg = m.split(".")[0] # take top-level module
115
+ if top_pkg not in STD_LIBS:
116
+ packages.add(top_pkg)
117
+
118
+ # Install packages via pip
119
+ for pkg in packages:
120
+ # Skip if already installed
121
+ if importlib.util.find_spec(pkg) is not None:
122
+ continue
123
+ print(f"📦 Installing {pkg} ...")
124
+ try:
125
+ subprocess.run(
126
+ [sys.executable, "-m", "pip", "install", pkg],
127
+ check=True
128
+ )
129
+ except subprocess.CalledProcessError as e:
130
+ print(f"⚠️ Failed to install package {pkg}: {e}")
131
+ def install_packages_from_code0(code: str):
132
  """
133
  Scan Python code for imports and install missing packages automatically.
134
  """