rahul7star commited on
Commit
71e7255
·
verified ·
1 Parent(s): 1ef8258

instal pacgs on fly

Browse files
Files changed (1) hide show
  1. app.py +35 -30
app.py CHANGED
@@ -74,15 +74,23 @@ def extract_code_from_text(text: str):
74
  return text
75
 
76
  def install_packages_from_code(code: str):
77
- """Install packages if import statements detected"""
78
- packages = set()
79
- for line in code.splitlines():
80
- match = re.match(r"^\s*import (\w+)", line) or re.match(r"^\s*from (\w+) import", line)
81
- if match:
82
- packages.add(match.group(1))
83
  for pkg in packages:
84
- if pkg not in ("os", "sys", "subprocess", "pathlib", "re", "json"):
85
- subprocess.run(["pip3", "install", "--quiet", pkg], capture_output=True)
 
 
 
 
 
 
 
 
 
86
 
87
  def execute_code(code_text: str):
88
  """Run arbitrary python code and return stdout/stderr"""
@@ -109,35 +117,23 @@ def process_command(cmd: str, model: str = OLLAMA_MODEL):
109
  cmd = cmd.strip()
110
 
111
  if cmd == "/HELP":
112
- return (
113
- "Commands:\n"
114
- "/STORY <title>\n"
115
- "/POEM <title>\n"
116
- "/BOOK <text>\n"
117
- "/EXECUTE <code>\n"
118
- "/FILES\n"
119
- "/DEBUG\n"
120
- "/WRITE_PY <instruction>"
121
- )
122
 
123
  elif cmd == "/DEBUG":
124
  DEBUG_MODE = not DEBUG_MODE
125
- return f"✅ Debug mode {'enabled' if DEBUG_MODE else 'disabled'}"
126
 
127
  elif cmd == "/FILES":
128
  def build_tree(path: Path):
129
- node = {
130
- "name": path.name,
131
- "type": "folder" if path.is_dir() else "file",
132
- "path": str(path)
133
- }
134
  if path.is_dir():
135
  node["children"] = [build_tree(p) for p in sorted(path.iterdir())]
136
  else:
137
  node["size"] = path.stat().st_size
138
  return node
139
- tree = build_tree(DATA_DIR)
140
- return json.dumps(tree, indent=2)
141
 
142
  elif cmd.startswith("/STORY"):
143
  title = cmd.replace("/STORY", "").strip() or "fantasy adventure"
@@ -182,14 +178,24 @@ def process_command(cmd: str, model: str = OLLAMA_MODEL):
182
  if not instruction:
183
  return "⚠️ /WRITE_PY requires instructions."
184
 
185
- llm_prompt = f"Write Python code ONLY and explain all lines clearly in comments. Instructions: {instruction}"
 
 
 
 
 
 
 
 
 
186
  response_text = run_ollama_cli(llm_prompt, model)
 
187
  code = extract_code_from_text(response_text)
188
- st.session_state.last_generated_code = code
189
  st.session_state.editable_code = code
 
 
190
  install_packages_from_code(code)
191
 
192
- # Show full LLM response with explanation
193
  append_message("assistant", f"```python\n{response_text}\n```")
194
  log_session(f"[WRITE_PY]\n{instruction}\n{response_text}")
195
  return response_text
@@ -197,7 +203,6 @@ def process_command(cmd: str, model: str = OLLAMA_MODEL):
197
  else:
198
  return run_ollama_cli(cmd, model)
199
 
200
-
201
  # -------------------------
202
  # Initialize session state
203
  # -------------------------
 
74
  return text
75
 
76
  def install_packages_from_code(code: str):
77
+ """
78
+ Scan Python code for imports and install missing packages automatically.
79
+ """
80
+ import_lines = re.findall(r'^\s*(?:import|from)\s+([\w_]+)', code, flags=re.MULTILINE)
81
+ packages = set(import_lines)
 
82
  for pkg in packages:
83
+ if pkg in ["os", "sys", "math", "re", "json", "time", "pathlib", "subprocess", "itertools", "functools"]:
84
+ continue # skip stdlib
85
+ try:
86
+ subprocess.run(
87
+ ["pip", "install", pkg],
88
+ check=True,
89
+ stdout=subprocess.PIPE,
90
+ stderr=subprocess.PIPE
91
+ )
92
+ except subprocess.CalledProcessError as e:
93
+ print(f"⚠️ Failed to install package {pkg}: {e}")
94
 
95
  def execute_code(code_text: str):
96
  """Run arbitrary python code and return stdout/stderr"""
 
117
  cmd = cmd.strip()
118
 
119
  if cmd == "/HELP":
120
+ return ("Commands:\n"
121
+ "/STORY <title>\n/POEM <title>\n/BOOK <text>\n/EXECUTE <code>\n"
122
+ "/FILES\n/WRITE_PY <instructions>\n/DEBUG")
 
 
 
 
 
 
 
123
 
124
  elif cmd == "/DEBUG":
125
  DEBUG_MODE = not DEBUG_MODE
126
+ return f"✅ DEBUG mode {'enabled' if DEBUG_MODE else 'disabled'}."
127
 
128
  elif cmd == "/FILES":
129
  def build_tree(path: Path):
130
+ node = {"name": path.name, "type": "folder" if path.is_dir() else "file", "path": str(path)}
 
 
 
 
131
  if path.is_dir():
132
  node["children"] = [build_tree(p) for p in sorted(path.iterdir())]
133
  else:
134
  node["size"] = path.stat().st_size
135
  return node
136
+ return json.dumps(build_tree(DATA_DIR), indent=2)
 
137
 
138
  elif cmd.startswith("/STORY"):
139
  title = cmd.replace("/STORY", "").strip() or "fantasy adventure"
 
178
  if not instruction:
179
  return "⚠️ /WRITE_PY requires instructions."
180
 
181
+ llm_prompt = f"""
182
+ You are an thinking expert software engineer with deep knowledge of multiple programming languages, frameworks, and architectural patterns. Your primary responsibility is to write clean, efficient, and maintainable code that fulfills the user's requirements precisely. You must think before acting.
183
+
184
+ You must think first via [think]...[/think], you must write your thoughts before you output anything.
185
+ During thinking, you will first propose 3 possible solutions and find the best one via self-verification and comparisons.
186
+
187
+ User instruction: {instruction}
188
+
189
+ Finally, provide the Python code ONLY with clear comments explaining every line.
190
+ """
191
  response_text = run_ollama_cli(llm_prompt, model)
192
+
193
  code = extract_code_from_text(response_text)
 
194
  st.session_state.editable_code = code
195
+
196
+ # Automatically install required packages
197
  install_packages_from_code(code)
198
 
 
199
  append_message("assistant", f"```python\n{response_text}\n```")
200
  log_session(f"[WRITE_PY]\n{instruction}\n{response_text}")
201
  return response_text
 
203
  else:
204
  return run_ollama_cli(cmd, model)
205
 
 
206
  # -------------------------
207
  # Initialize session state
208
  # -------------------------