File size: 13,073 Bytes
d64fc7d
6e859ed
9ac75db
707c51e
491e90a
6417ede
d64fc7d
707c51e
3a3d800
707c51e
e8658a5
9ac75db
707c51e
 
 
 
843a094
1ef8258
491e90a
1ef8258
2c3595b
6060ac3
707c51e
e8658a5
707c51e
 
 
 
 
9cf2f8c
707c51e
e8658a5
 
 
 
9cf2f8c
707c51e
9ac75db
9cf2f8c
707c51e
 
 
 
 
 
c29a6a8
707c51e
e8658a5
707c51e
e8658a5
707c51e
 
9cf2f8c
e8658a5
2006b3b
707c51e
e8658a5
 
 
 
c29a6a8
707c51e
e8658a5
 
 
707c51e
e8658a5
9cf2f8c
9fc3a8c
 
491e90a
9fc3a8c
 
 
491e90a
9fc3a8c
 
 
 
 
 
 
 
 
491e90a
47815ca
 
 
 
 
 
 
 
 
 
 
 
 
491e90a
47815ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71e7255
 
 
 
 
491e90a
71e7255
 
 
 
 
 
 
 
 
 
 
491e90a
d89e088
9fc3a8c
1ef8258
9fc3a8c
6418c23
9fc3a8c
 
 
 
 
 
 
 
6418c23
1ef8258
6418c23
 
c29a6a8
6418c23
9fc3a8c
 
 
 
 
 
 
 
 
6418c23
 
9fc3a8c
1ef8258
 
 
 
 
 
 
 
 
 
 
e4fb16c
 
 
 
 
 
 
 
 
 
1ef8258
 
 
e4fb16c
1ef8258
 
 
e4fb16c
 
 
 
 
1ef8258
 
 
 
 
e4fb16c
 
1ef8258
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c29a6a8
1ef8258
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e096130
1ef8258
 
9fc3a8c
e4fb16c
1ef8258
 
 
e4fb16c
1ef8258
 
 
 
9fc3a8c
 
 
1ef8258
 
 
e4fb16c
37b940c
 
 
 
 
 
 
6418c23
 
1ef8258
 
 
 
37b940c
 
 
 
3aaa4d5
1ef8258
 
37b940c
491e90a
 
 
 
 
1ef8258
 
6418c23
 
1ef8258
6418c23
1ef8258
 
0d1af65
 
 
 
 
 
1ef8258
 
0d1af65
9fc3a8c
1ef8258
0d1af65
 
 
 
1ef8258
 
6418c23
491e90a
 
 
 
37b940c
 
 
 
 
 
 
 
 
 
491e90a
37b940c
 
 
 
 
 
 
 
 
 
 
 
 
 
2c3595b
 
 
 
 
 
491e90a
 
37b940c
 
 
 
 
491e90a
37b940c
 
 
 
 
491e90a
37b940c
 
 
 
 
491e90a
37b940c
 
 
 
 
 
 
491e90a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
import streamlit as st
import subprocess
import os
from pathlib import Path
import re
import json

# -------------------------
# Configuration
# -------------------------
OLLAMA_MODEL = "qwen2.5:0.5b"
PENCILCLAW_PATH = Path("/workspace/pencilclaw")
DATA_DIR = Path("/workspace/pencil_data")
DATA_DIR.mkdir(parents=True, exist_ok=True)
SESSION_LOG = DATA_DIR / "session.log"
BOOK_FILE = DATA_DIR / "book.txt"

# -------------------------
# Global debug flag
# -------------------------
DEBUG_MODE = False

# -------------------------
# Helper functions
# -------------------------
def append_message(role, content):
    st.session_state.messages.append({"role": role, "content": content})
    with st.chat_message(role):
        st.markdown(content)

def log_session(text):
    if SESSION_LOG.exists():
        SESSION_LOG.write_text(SESSION_LOG.read_text() + f"\n{text}\n")
    else:
        SESSION_LOG.write_text(f"{text}\n")

def check_pencilclaw():
    return PENCILCLAW_PATH.exists() and PENCILCLAW_PATH.is_file() and os.access(str(PENCILCLAW_PATH), os.X_OK)

def run_pencilclaw_command(command: str):
    try:
        result = subprocess.run(
            [str(PENCILCLAW_PATH), command],
            capture_output=True,
            text=True,
            timeout=600
        )
        return result.stdout.strip() if result.stdout else result.stderr.strip()
    except subprocess.TimeoutExpired:
        return "⏱️ Pencilclaw command timed out."
    except Exception as e:
        return f"❌ Pencilclaw Error: {str(e)}"

def run_ollama_cli(prompt: str, model: str = OLLAMA_MODEL):
    """Run Ollama via CLI"""
    try:
        result = subprocess.run(
            ["ollama", "run", model, prompt],
            capture_output=True,
            text=True,
            timeout=600
        )
        return result.stdout.strip() if result.stdout else result.stderr.strip()
    except subprocess.TimeoutExpired:
        return "⏱️ Ollama CLI timed out."
    except Exception as e:
        return f"❌ Ollama CLI Error: {str(e)}"

import textwrap

def extract_code_from_text(text: str):
    """Extract Python code from triple backticks and normalize indentation"""
    code_blocks = re.findall(r"```(?:python)?\s*(.*?)```", text, re.DOTALL | re.IGNORECASE)

    if code_blocks:
        code = "\n\n".join(code_blocks)
    else:
        code = text

    # Fix indentation issues
    code = textwrap.dedent(code)
    code = code.replace("\t", "    ")

    return code.strip()

import re
import subprocess
import sys
import importlib.util

# List of common standard library modules to skip
STD_LIBS = {
    "os", "sys", "math", "re", "json", "time", "pathlib",
    "subprocess", "itertools", "functools", "collections",
    "random", "datetime", "threading", "multiprocessing",
    "shutil", "tempfile", "logging"
}

def install_packages_from_code(code: str):
    """
    Scan Python code for any imports and attempt to install missing packages automatically.
    Works for:
      - import X
      - import X as Y
      - from X import Y
      - from X.Y import Z
    """
    # Find all import statements
    matches = re.findall(r'^\s*(?:import|from)\s+([a-zA-Z0-9_\.]+)', code, flags=re.MULTILINE)

    # Convert to top-level package names
    packages = set()
    for m in matches:
        top_pkg = m.split(".")[0]  # take top-level module
        if top_pkg not in STD_LIBS:
            packages.add(top_pkg)

    # Install packages via pip
    for pkg in packages:
        # Skip if already installed
        if importlib.util.find_spec(pkg) is not None:
            continue
        print(f"📦 Installing {pkg} ...")
        try:
            subprocess.run(
                [sys.executable, "-m", "pip", "install", pkg],
                check=True
            )
        except subprocess.CalledProcessError as e:
            print(f"⚠️ Failed to install package {pkg}: {e}")
def install_packages_from_code0(code: str):
    """
    Scan Python code for imports and install missing packages automatically.
    """
    import_lines = re.findall(r'^\s*(?:import|from)\s+([\w_]+)', code, flags=re.MULTILINE)
    packages = set(import_lines)
    for pkg in packages:
        if pkg in ["os", "sys", "math", "re", "json", "time", "pathlib", "subprocess", "itertools", "functools"]:
            continue  # skip stdlib
        try:
            subprocess.run(
                ["pip", "install", pkg],
                check=True,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE
            )
        except subprocess.CalledProcessError as e:
            print(f"⚠️ Failed to install package {pkg}: {e}")

def execute_code(code_text: str):
    """Run arbitrary python code safely"""
    tmp_file = DATA_DIR / "user_code.py"

    try:
        import textwrap

        # Fix indentation before running
        code_text = textwrap.dedent(code_text)
        code_text = code_text.replace("\t", "    ")

        tmp_file.write_text(code_text)

        result = subprocess.run(
            ["python3", str(tmp_file)],
            capture_output=True,
            text=True,
            timeout=600
        )

        output = ""
        if result.stdout:
            output += result.stdout
        if result.stderr:
            output += "\n⚠️ Errors:\n" + result.stderr

        return output if output else "✅ Code executed with no output."

    except Exception as e:
        return f"Execution error: {e}"

    finally:
        tmp_file.unlink(missing_ok=True)

# -------------------------
# Main process_command (all old commands + new ones)
# -------------------------
def process_command(cmd: str, model: str = OLLAMA_MODEL):
    global DEBUG_MODE
    cmd = cmd.strip()

    if cmd == "/HELP":
        return (
            "Commands:\n"
            "/STORY <title>\n"
            "/POEM <title>\n"
            "/BOOK <text>\n"
            "/EXECUTE <code>\n"
            "/FILES\n"
            "/DEBUG\n"
            "/WRITE_PY <instruction>"
        )

    elif cmd == "/DEBUG":
        DEBUG_MODE = not DEBUG_MODE
        return f"✅ Debug mode {'enabled' if DEBUG_MODE else 'disabled'}"

    elif cmd == "/FILES":
        def build_tree(path: Path):
            node = {
                "name": path.name,
                "type": "folder" if path.is_dir() else "file",
                "path": str(path)
            }
            if path.is_dir():
                node["children"] = [build_tree(p) for p in sorted(path.iterdir())]
            else:
                node["size"] = path.stat().st_size
            return node
        tree = build_tree(DATA_DIR)
        return json.dumps(tree, indent=2)

    elif cmd.startswith("/STORY"):
        title = cmd.replace("/STORY", "").strip() or "fantasy adventure"
        return run_ollama_cli(f"Write a short story about: {title}", model)

    elif cmd.startswith("/POEM"):
        title = cmd.replace("/POEM", "").strip() or "nature"
        return run_ollama_cli(f"Write a poem about: {title}", model)

    elif cmd.startswith("/BOOK"):
        chapter_text = cmd.replace("/BOOK", "").strip()
        if chapter_text:
            with open(BOOK_FILE, "a") as f:
                f.write(chapter_text + "\n\n")
            return f"✅ Chapter appended to {BOOK_FILE.name}."
        else:
            return "⚠️ /BOOK command requires text to append."

    elif cmd.startswith("/EXECUTE"):
        code = cmd.replace("/EXECUTE", "").strip()
        if code:
            tmp_file = DATA_DIR / "ai_code.py"
            tmp_file.write_text(code)
            try:
                result = subprocess.run(
                    ["python3", str(tmp_file)],
                    capture_output=True,
                    text=True,
                    timeout=600
                )
                output = result.stdout + result.stderr
            except Exception as e:
                output = f"Execution error: {e}"
            finally:
                tmp_file.unlink(missing_ok=True)
            return output if output else "✅ Code executed with no output."
        else:
            return "⚠️ /EXECUTE command requires Python code."

    elif cmd.startswith("/WRITE_PY"):
        instruction = cmd.replace("/WRITE_PY", "").strip()
        if not instruction:
            return "⚠️ /WRITE_PY requires instructions."

        llm_prompt = f"Write Python code ONLY and explain all lines clearly in comments. Instructions: {instruction}"
        response_text = run_ollama_cli(llm_prompt, model)
        code = extract_code_from_text(response_text)
        code = code.replace("\t", "    ")
        st.session_state.last_generated_code = code
        st.session_state.editable_code = code
        install_packages_from_code(code)

        # Show full LLM response with explanation
        append_message("assistant", f"```python\n{response_text}\n```")
        log_session(f"[WRITE_PY]\n{instruction}\n{response_text}")
        return response_text


   

    else:
        return run_ollama_cli(cmd, model)


# -------------------------
# Initialize session state
# -------------------------
if "messages" not in st.session_state:
    st.session_state.messages = []
if "last_response" not in st.session_state:
    st.session_state.last_response = ""
if "last_generated_code" not in st.session_state:
    st.session_state.last_generated_code = ""
if "editable_code" not in st.session_state:
    st.session_state.editable_code = ""
if "debug_mode" not in st.session_state:
    st.session_state.debug_mode = False

# -------------------------
# UI Layout
# -------------------------
st.set_page_config(page_title="claw", layout="wide")



# -------------------------
# Top UI: WRITE_PY
# -------------------------
st.markdown("### 🖊️ Generate Python Code from Instructions")
write_py_input = st.text_area("Python Instructions", key="write_py_input")
if st.button("Generate Python Code") and write_py_input.strip():
    response_text = process_command(f"/WRITE_PY {write_py_input.strip()}", OLLAMA_MODEL)

# -------------------------
# Editable Code Area + Run
# -------------------------
if st.session_state.editable_code:
    st.markdown("### ✍️ Edit Generated Code")



    edited_code = st.text_area(
      "Edit the code before running",
       value=st.session_state.editable_code,
        height=350
    )

    st.session_state.editable_code = edited_code.replace("\t", "    ")



    

    if st.button("▶️ Run Edited Python Code"):
        output = execute_code(st.session_state.editable_code)
        st.text_area("Execution Output", value=output, height=250)

# -------------------------
# Main Chat and Controls
# -------------------------
col1, col2 = st.columns([2, 1])

with col1:
    st.markdown("### 📖 Current Session")
    for msg in st.session_state.messages:
        with st.chat_message(msg["role"]):
            st.markdown(msg["content"])
    prompt = st.chat_input("Type your prompt or command...")
    if prompt:
        append_message("user", prompt)
        response = process_command(prompt, OLLAMA_MODEL)
        append_message("assistant", response)
        log_session(f"[CHAT] {prompt}\n{response}")
        st.session_state.last_response = response

with col2:
    st.markdown("### ⚙️ Controls")
    model_name = st.text_input("Model Name", value=OLLAMA_MODEL)
    st.markdown("#### Status")
    st.write("Pencilclaw:", "✅ Compiled" if check_pencilclaw() else "❌ Not Compiled")
    if st.button("🗑️ Clear Session"):
        st.session_state.messages = []
        st.session_state.last_response = ""
    if SESSION_LOG.exists():
        log_content = SESSION_LOG.read_text()
        st.download_button(
            label="📥 Download Session Log",
            data=log_content,
            file_name="pencilclaw_session.log",
            mime="text/plain"
        )

    # Quick commands
    story_input = st.text_input("Story Title", key="story_input")
    if st.button("Generate Story"):
        response = process_command(f"/STORY {story_input}", model_name)
        append_message("assistant", response)
        log_session(f"[STORY] {story_input}\n{response}")

    poem_input = st.text_input("Poem Title", key="poem_input")
    if st.button("Generate Poem"):
        response = process_command(f"/POEM {poem_input}", model_name)
        append_message("assistant", response)
        log_session(f"[POEM] {poem_input}\n{response}")

    book_input = st.text_area("Book Chapter", key="book_input")
    if st.button("Append Chapter"):
        response = process_command(f"/BOOK {book_input}", model_name)
        append_message("assistant", response)
        log_session(f"[BOOK] {book_input}\n{response}")

    code_input = st.text_area("Python Code", key="code_input")
    if st.button("Execute Code"):
        response = process_command(f"/EXECUTE {code_input}", model_name)
        append_message("assistant", response)
        log_session(f"[EXECUTE]\n{code_input}\n{response}")

st.markdown("---")
st.markdown("💡 Tip: Use `/HELP` to see all commands, `/DEBUG` to toggle debug mode.")