rahul7star commited on
Commit
2c3595b
Β·
verified Β·
1 Parent(s): 3aaa4d5

run pythin code add

Browse files
Files changed (1) hide show
  1. app.py +142 -92
app.py CHANGED
@@ -3,7 +3,7 @@ import subprocess
3
  import os
4
  from pathlib import Path
5
  import json
6
- import sys
7
 
8
  # -------------------------
9
  # Configuration
@@ -16,7 +16,7 @@ SESSION_LOG = DATA_DIR / "session.log"
16
  BOOK_FILE = DATA_DIR / "book.txt"
17
 
18
  # Debug flag
19
- DEBUG = False
20
 
21
  # -------------------------
22
  # Helper functions
@@ -43,9 +43,6 @@ def run_pencilclaw_command(command: str):
43
  text=True,
44
  timeout=120
45
  )
46
- if DEBUG:
47
- print(f"[DEBUG] Pencilclaw command: {command}")
48
- print(f"[DEBUG] Output: {result.stdout}, Error: {result.stderr}")
49
  return result.stdout.strip() if result.stdout else result.stderr.strip()
50
  except subprocess.TimeoutExpired:
51
  return "⏱️ Pencilclaw command timed out."
@@ -61,9 +58,6 @@ def run_ollama_cli(prompt: str, model: str = OLLAMA_MODEL):
61
  text=True,
62
  timeout=60
63
  )
64
- if DEBUG:
65
- print(f"[DEBUG] Ollama prompt: {prompt}")
66
- print(f"[DEBUG] Output: {result.stdout}, Error: {result.stderr}")
67
  return result.stdout.strip() if result.stdout else result.stderr.strip()
68
  except subprocess.TimeoutExpired:
69
  return "⏱️ Ollama CLI timed out."
@@ -74,24 +68,29 @@ def run_ollama_cli(prompt: str, model: str = OLLAMA_MODEL):
74
  # Command processor
75
  # -------------------------
76
  def process_command(cmd: str, model: str = OLLAMA_MODEL):
77
- global DEBUG
78
  cmd = cmd.strip()
79
 
 
80
  if cmd == "/HELP":
81
- return (
82
- "Commands:\n"
83
- "/STORY <title>\n"
84
- "/POEM <title>\n"
85
- "/BOOK <text>\n"
86
- "/EXECUTE <code>\n"
87
- "/FILES\n"
88
- "/DEBUG\n"
89
- "/DEBUG_EXECUTE <code>\n"
90
- "/WRITE_PY <instruction>"
91
- )
 
 
 
 
92
 
 
93
  elif cmd == "/FILES":
94
- # Recursively build folder contents
95
  def build_tree(path: Path):
96
  node = {
97
  "name": path.name,
@@ -103,20 +102,43 @@ def process_command(cmd: str, model: str = OLLAMA_MODEL):
103
  else:
104
  node["size"] = path.stat().st_size
105
  return node
106
-
107
  tree = build_tree(DATA_DIR)
108
  return json.dumps(tree, indent=2)
109
 
110
- elif cmd == "/DEBUG":
111
- DEBUG = not DEBUG
112
- return f"βœ… Debug mode {'enabled' if DEBUG else 'disabled'}."
113
-
114
- elif cmd.startswith("/DEBUG_EXECUTE"):
115
- code = cmd.replace("/DEBUG_EXECUTE", "").strip()
116
- if not code:
117
- return "⚠️ /DEBUG_EXECUTE command requires Python code."
118
- tmp_file = DATA_DIR / "ai_debug.py"
119
- tmp_file.write_text(code)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
  try:
121
  result = subprocess.run(
122
  ["python3", str(tmp_file)],
@@ -124,74 +146,83 @@ def process_command(cmd: str, model: str = OLLAMA_MODEL):
124
  text=True,
125
  timeout=60
126
  )
127
- output = f"[STDOUT]\n{result.stdout}\n[STDERR]\n{result.stderr}"
128
  except Exception as e:
129
  output = f"Execution error: {e}"
130
- finally:
131
- tmp_file.unlink(missing_ok=True)
132
- return output if output else "βœ… Debug code executed with no output."
133
 
134
- elif cmd.startswith("/WRITE_PY"):
135
- instruction = cmd.replace("/WRITE_PY", "").strip()
136
- if not instruction:
137
- return "⚠️ /WRITE_PY requires an instruction describing the Python code to generate."
138
-
139
- # Generate Python code via Ollama
140
- prompt = f"Write a Python script based on the following instruction:\n{instruction}\n"
141
- code = run_ollama_cli(prompt, model)
142
 
143
- # Save generated code
144
- gen_file = DATA_DIR / "ai_generated.py"
145
- gen_file.write_text(code)
146
 
147
- # Check if torch is mentioned and install
148
- extra = ""
149
- if "torch" in code or "import torch" in code:
 
 
 
150
  try:
151
- subprocess.run([sys.executable, "-m", "pip", "install", "torch"], check=True, text=True)
152
- extra = "βœ… PyTorch detected and installed automatically."
 
 
 
 
 
153
  except Exception as e:
154
- extra = f"⚠️ Failed to install torch: {e}"
 
 
155
 
156
- return f"βœ… Python code generated and saved to `{gen_file}`.\n{extra}\n\n```python\n{code}\n```"
 
157
 
158
- elif cmd.startswith("/STORY"):
159
- title = cmd.replace("/STORY", "").strip() or "fantasy adventure"
160
- return run_ollama_cli(f"Write a short story about: {title}", model)
161
 
162
- elif cmd.startswith("/POEM"):
163
- title = cmd.replace("/POEM", "").strip() or "nature"
164
- return run_ollama_cli(f"Write a poem about: {title}", model)
 
 
165
 
166
- elif cmd.startswith("/BOOK"):
167
- chapter_text = cmd.replace("/BOOK", "").strip()
168
- if chapter_text:
169
- with open(BOOK_FILE, "a") as f:
170
- f.write(chapter_text + "\n\n")
171
- return f"βœ… Chapter appended to {BOOK_FILE.name}."
172
- else:
173
- return "⚠️ /BOOK command requires text to append."
174
 
175
- elif cmd.startswith("/EXECUTE"):
176
- code = cmd.replace("/EXECUTE", "").strip()
177
- if not code:
178
- return "⚠️ /EXECUTE command requires Python code."
179
- tmp_file = DATA_DIR / "ai_code.py"
180
- tmp_file.write_text(code)
181
  try:
182
  result = subprocess.run(
183
- ["python3", str(tmp_file)],
184
  capture_output=True,
185
  text=True,
186
- timeout=30
187
  )
188
  output = result.stdout + result.stderr
189
  except Exception as e:
190
  output = f"Execution error: {e}"
191
- finally:
192
- tmp_file.unlink(missing_ok=True)
193
- return output if output else "βœ… Code executed with no output."
194
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
195
  else:
196
  return run_ollama_cli(cmd, model)
197
 
@@ -214,9 +245,13 @@ col1, col2 = st.columns([2, 1])
214
 
215
  with col1:
216
  st.markdown("### πŸ“– Current Session")
 
 
217
  for msg in st.session_state.messages:
218
  with st.chat_message(msg["role"]):
219
  st.markdown(msg["content"])
 
 
220
  prompt = st.chat_input("Type your prompt or command...")
221
  if prompt:
222
  append_message("user", prompt)
@@ -227,49 +262,64 @@ with col1:
227
 
228
  with col2:
229
  st.markdown("### βš™οΈ Controls")
 
 
230
  model_name = st.text_input("Model Name", value=OLLAMA_MODEL)
 
 
231
  st.markdown("#### Status")
232
  st.write("Pencilclaw:", "βœ… Compiled" if check_pencilclaw() else "❌ Not Compiled")
 
 
233
  if st.button("πŸ—‘οΈ Clear Session"):
234
  st.session_state.messages = []
235
  st.session_state.last_response = ""
 
 
236
  if SESSION_LOG.exists():
237
  log_content = SESSION_LOG.read_text()
238
- st.download_button("πŸ“₯ Download Session Log", data=log_content, file_name="pencilclaw_session.log", mime="text/plain")
239
-
 
 
 
 
 
 
240
  st.markdown("### Quick Commands")
 
241
  story_input = st.text_input("Story Title", key="story_input")
242
  if st.button("Generate Story"):
243
  response = process_command(f"/STORY {story_input}", model_name)
244
  append_message("assistant", response)
245
  log_session(f"[STORY] {story_input}\n{response}")
246
-
247
  poem_input = st.text_input("Poem Title", key="poem_input")
248
  if st.button("Generate Poem"):
249
  response = process_command(f"/POEM {poem_input}", model_name)
250
  append_message("assistant", response)
251
  log_session(f"[POEM] {poem_input}\n{response}")
252
-
253
  book_input = st.text_area("Book Chapter", key="book_input")
254
  if st.button("Append Chapter"):
255
  response = process_command(f"/BOOK {book_input}", model_name)
256
  append_message("assistant", response)
257
  log_session(f"[BOOK] {book_input}\n{response}")
258
-
259
  code_input = st.text_area("Python Code", key="code_input")
260
  if st.button("Execute Code"):
261
  response = process_command(f"/EXECUTE {code_input}", model_name)
262
  append_message("assistant", response)
263
  log_session(f"[EXECUTE]\n{code_input}\n{response}")
264
 
265
- # -------------------------
266
- # New /WRITE_PY UI
267
- st.markdown("### ✨ Generate Python Code")
268
- py_instr = st.text_area("Instruction for Python Code", key="py_instr")
269
- if st.button("Generate Python Code"):
270
- response = process_command(f"/WRITE_PY {py_instr}", model_name)
271
- append_message("assistant", response)
272
- log_session(f"[WRITE_PY]\n{py_instr}\n{response}")
273
 
274
  st.markdown("---")
275
  st.markdown("πŸ’‘ Tip: Use `/HELP` in chat to see all available commands.")
 
3
  import os
4
  from pathlib import Path
5
  import json
6
+ from io import BytesIO
7
 
8
  # -------------------------
9
  # Configuration
 
16
  BOOK_FILE = DATA_DIR / "book.txt"
17
 
18
  # Debug flag
19
+ DEBUG_MODE = False
20
 
21
  # -------------------------
22
  # Helper functions
 
43
  text=True,
44
  timeout=120
45
  )
 
 
 
46
  return result.stdout.strip() if result.stdout else result.stderr.strip()
47
  except subprocess.TimeoutExpired:
48
  return "⏱️ Pencilclaw command timed out."
 
58
  text=True,
59
  timeout=60
60
  )
 
 
 
61
  return result.stdout.strip() if result.stdout else result.stderr.strip()
62
  except subprocess.TimeoutExpired:
63
  return "⏱️ Ollama CLI timed out."
 
68
  # Command processor
69
  # -------------------------
70
  def process_command(cmd: str, model: str = OLLAMA_MODEL):
71
+ global DEBUG_MODE
72
  cmd = cmd.strip()
73
 
74
+ # Help
75
  if cmd == "/HELP":
76
+ return ("Commands:\n"
77
+ "/STORY <title>\n"
78
+ "/POEM <title>\n"
79
+ "/BOOK <text>\n"
80
+ "/EXECUTE <code>\n"
81
+ "/DEBUG_EXEC <code>\n"
82
+ "/WRITE_PY <instruction>\n"
83
+ "/RUN_PY <filename>\n"
84
+ "/FILES\n"
85
+ "/DEBUG")
86
+
87
+ # Toggle debug mode
88
+ elif cmd == "/DEBUG":
89
+ DEBUG_MODE = not DEBUG_MODE
90
+ return f"βœ… Debug mode {'enabled' if DEBUG_MODE else 'disabled'}."
91
 
92
+ # List all files in pencil_data recursively
93
  elif cmd == "/FILES":
 
94
  def build_tree(path: Path):
95
  node = {
96
  "name": path.name,
 
102
  else:
103
  node["size"] = path.stat().st_size
104
  return node
 
105
  tree = build_tree(DATA_DIR)
106
  return json.dumps(tree, indent=2)
107
 
108
+ # Generate Python code from instruction
109
+ elif cmd.startswith("/WRITE_PY"):
110
+ instruction = cmd.replace("/WRITE_PY", "").strip()
111
+ if not instruction:
112
+ return "⚠️ /WRITE_PY requires an instruction."
113
+
114
+ # Install PyTorch if requested
115
+ if "torch" in instruction.lower():
116
+ try:
117
+ subprocess.run(
118
+ ["pip3", "install", "--upgrade", "torch", "torchvision", "torchaudio"],
119
+ check=True,
120
+ capture_output=True,
121
+ text=True
122
+ )
123
+ except Exception as e:
124
+ return f"❌ Failed to install PyTorch: {e}"
125
+
126
+ # Generate Python code via Ollama
127
+ prompt = f"Write a Python script that does the following:\n{instruction}"
128
+ py_code = run_ollama_cli(prompt, model)
129
+ tmp_file = DATA_DIR / "generated.py"
130
+ tmp_file.write_text(py_code)
131
+
132
+ # Provide download
133
+ b = BytesIO(py_code.encode("utf-8"))
134
+ st.download_button(
135
+ label="πŸ“₯ Download generated Python code",
136
+ data=b,
137
+ file_name="generated.py",
138
+ mime="text/plain"
139
+ )
140
+
141
+ # Immediately run generated code and show logs
142
  try:
143
  result = subprocess.run(
144
  ["python3", str(tmp_file)],
 
146
  text=True,
147
  timeout=60
148
  )
149
+ output = result.stdout + result.stderr
150
  except Exception as e:
151
  output = f"Execution error: {e}"
 
 
 
152
 
153
+ if DEBUG_MODE:
154
+ output = f"[DEBUG OUTPUT]\n{output}"
 
 
 
 
 
 
155
 
156
+ return f"βœ… Python code generated and executed:\n```\n{py_code}\n```\n\n**Output:**\n```\n{output}\n```"
 
 
157
 
158
+ # Execute Python code
159
+ elif cmd.startswith("/EXECUTE") or cmd.startswith("/DEBUG_EXEC"):
160
+ code = cmd.replace("/EXECUTE", "").replace("/DEBUG_EXEC", "").strip()
161
+ if code:
162
+ tmp_file = DATA_DIR / "ai_code.py"
163
+ tmp_file.write_text(code)
164
  try:
165
+ result = subprocess.run(
166
+ ["python3", str(tmp_file)],
167
+ capture_output=True,
168
+ text=True,
169
+ timeout=30
170
+ )
171
+ output = result.stdout + result.stderr
172
  except Exception as e:
173
+ output = f"Execution error: {e}"
174
+ finally:
175
+ tmp_file.unlink(missing_ok=True)
176
 
177
+ if cmd.startswith("/DEBUG_EXEC") or DEBUG_MODE:
178
+ output = f"[DEBUG OUTPUT]\n{output}"
179
 
180
+ return output if output else "βœ… Code executed with no output."
181
+ else:
182
+ return "⚠️ /EXECUTE or /DEBUG_EXEC command requires Python code."
183
 
184
+ # Run a previously generated Python file
185
+ elif cmd.startswith("/RUN_PY"):
186
+ filename = cmd.replace("/RUN_PY", "").strip()
187
+ if not filename:
188
+ return "⚠️ /RUN_PY requires a filename in pencil_data/"
189
 
190
+ file_path = DATA_DIR / filename
191
+ if not file_path.exists():
192
+ return f"❌ File not found: {file_path}"
 
 
 
 
 
193
 
 
 
 
 
 
 
194
  try:
195
  result = subprocess.run(
196
+ ["python3", str(file_path)],
197
  capture_output=True,
198
  text=True,
199
+ timeout=60
200
  )
201
  output = result.stdout + result.stderr
202
  except Exception as e:
203
  output = f"Execution error: {e}"
 
 
 
204
 
205
+ return f"βœ… Output of {filename}:\n```\n{output}\n```" if output else f"βœ… {filename} ran with no output."
206
+
207
+ # Append chapter to book
208
+ elif cmd.startswith("/BOOK"):
209
+ chapter_text = cmd.replace("/BOOK", "").strip()
210
+ if chapter_text:
211
+ with open(BOOK_FILE, "a") as f:
212
+ f.write(chapter_text + "\n\n")
213
+ return f"βœ… Chapter appended to {BOOK_FILE.name}."
214
+ else:
215
+ return "⚠️ /BOOK command requires text to append."
216
+
217
+ # Generate story or poem
218
+ elif cmd.startswith("/STORY"):
219
+ title = cmd.replace("/STORY", "").strip() or "fantasy adventure"
220
+ return run_ollama_cli(f"Write a short story about: {title}", model)
221
+ elif cmd.startswith("/POEM"):
222
+ title = cmd.replace("/POEM", "").strip() or "nature"
223
+ return run_ollama_cli(f"Write a poem about: {title}", model)
224
+
225
+ # Fallback: send to Ollama
226
  else:
227
  return run_ollama_cli(cmd, model)
228
 
 
245
 
246
  with col1:
247
  st.markdown("### πŸ“– Current Session")
248
+
249
+ # Show chat history
250
  for msg in st.session_state.messages:
251
  with st.chat_message(msg["role"]):
252
  st.markdown(msg["content"])
253
+
254
+ # Chat input
255
  prompt = st.chat_input("Type your prompt or command...")
256
  if prompt:
257
  append_message("user", prompt)
 
262
 
263
  with col2:
264
  st.markdown("### βš™οΈ Controls")
265
+
266
+ # Model input
267
  model_name = st.text_input("Model Name", value=OLLAMA_MODEL)
268
+
269
+ # Status
270
  st.markdown("#### Status")
271
  st.write("Pencilclaw:", "βœ… Compiled" if check_pencilclaw() else "❌ Not Compiled")
272
+
273
+ # Clear session
274
  if st.button("πŸ—‘οΈ Clear Session"):
275
  st.session_state.messages = []
276
  st.session_state.last_response = ""
277
+
278
+ # Download logs
279
  if SESSION_LOG.exists():
280
  log_content = SESSION_LOG.read_text()
281
+ st.download_button(
282
+ label="πŸ“₯ Download Session Log",
283
+ data=log_content,
284
+ file_name="pencilclaw_session.log",
285
+ mime="text/plain"
286
+ )
287
+
288
+ # Quick command buttons
289
  st.markdown("### Quick Commands")
290
+
291
  story_input = st.text_input("Story Title", key="story_input")
292
  if st.button("Generate Story"):
293
  response = process_command(f"/STORY {story_input}", model_name)
294
  append_message("assistant", response)
295
  log_session(f"[STORY] {story_input}\n{response}")
296
+
297
  poem_input = st.text_input("Poem Title", key="poem_input")
298
  if st.button("Generate Poem"):
299
  response = process_command(f"/POEM {poem_input}", model_name)
300
  append_message("assistant", response)
301
  log_session(f"[POEM] {poem_input}\n{response}")
302
+
303
  book_input = st.text_area("Book Chapter", key="book_input")
304
  if st.button("Append Chapter"):
305
  response = process_command(f"/BOOK {book_input}", model_name)
306
  append_message("assistant", response)
307
  log_session(f"[BOOK] {book_input}\n{response}")
308
+
309
  code_input = st.text_area("Python Code", key="code_input")
310
  if st.button("Execute Code"):
311
  response = process_command(f"/EXECUTE {code_input}", model_name)
312
  append_message("assistant", response)
313
  log_session(f"[EXECUTE]\n{code_input}\n{response}")
314
 
315
+ # Run previously generated Python files
316
+ py_files = sorted([f.name for f in DATA_DIR.glob("*.py")])
317
+ if py_files:
318
+ run_file = st.selectbox("Run Generated Python File", py_files)
319
+ if st.button("Run Selected Python File"):
320
+ response = process_command(f"/RUN_PY {run_file}", model_name)
321
+ append_message("assistant", response)
322
+ log_session(f"[RUN_PY] {run_file}\n{response}")
323
 
324
  st.markdown("---")
325
  st.markdown("πŸ’‘ Tip: Use `/HELP` in chat to see all available commands.")