MegaTronX commited on
Commit
2f55627
·
verified ·
1 Parent(s): 34b86b6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +67 -56
app.py CHANGED
@@ -2,84 +2,95 @@ import os
2
  import gradio as gr
3
  import spaces
4
  import zipfile
 
 
 
5
  from huggingface_hub import hf_hub_download
6
  from llama_cpp import Llama
7
- from llama_cpp_agent import LlamaCppAgent, Tool, ToolCall, MessagesFormatterType
8
  from llama_cpp_agent.providers import LlamaCppPythonProvider
9
 
10
  MODEL_NAME = "neuraldaredevil-8b-abliterated-q4_k_m-imat.gguf"
11
  MODEL_PATH = f"models/{MODEL_NAME}"
12
 
 
13
  hf_hub_download(
14
  repo_id="tHottie/NeuralDaredevil-8B-abliterated-Q4_K_M-GGUF",
15
  filename=MODEL_NAME,
16
- local_dir="./models"
17
  )
18
 
19
- # Define tools for the agent
20
- def create_file(filename: str, content: str) -> str:
21
- os.makedirs("generated", exist_ok=True)
22
- filepath = os.path.join("generated", filename)
23
- with open(filepath, "w", encoding="utf-8") as f:
24
- f.write(content)
25
- return f"Created {filename}"
26
-
27
- def package_zip(output_name="code_package.zip"):
28
- zip_path = os.path.join("generated", output_name)
29
- with zipfile.ZipFile(zip_path, "w") as zipf:
30
- for root, _, files in os.walk("generated"):
31
- for file in files:
32
- if file != output_name:
33
- zipf.write(os.path.join(root, file), arcname=file)
34
- return zip_path
35
-
36
- # Wrap tools as LLM-callable
37
- tools = [
38
- Tool(
39
- name="create_file",
40
- description="Create a file from given filename and content.",
41
- parameters={"filename": str, "content": str},
42
- function=create_file
43
- ),
44
- Tool(
45
- name="package_zip",
46
- description="Package all created files into a zip and return path.",
47
- parameters={},
48
- function=package_zip
49
- )
50
- ]
51
-
52
  @spaces.GPU(duration=120)
53
- def respond(prompt):
 
54
  llm = Llama(
55
  model_path=MODEL_PATH,
56
- n_gpu_layers=81,
57
- n_ctx=8192,
58
- n_batch=1024,
 
59
  verbose=False
60
  )
61
  provider = LlamaCppPythonProvider(llm)
62
  agent = LlamaCppAgent(
63
  provider,
64
- tools=tools,
65
- system_prompt="You are an agent that receives instructions and uses tools like create_file and package_zip to generate and package code files into a downloadable zip.",
66
- predefined_messages_formatter_type=MessagesFormatterType.GEMMA_2
 
 
 
 
67
  )
68
 
69
- output = ""
70
- for chunk in agent.run(prompt):
71
- output += chunk
72
- return output, package_zip()
73
 
74
- with gr.Blocks() as demo:
75
- gr.Markdown("""### Code Generator with GGUF Model
76
- Paste your AI response below. The model will generate code files and return a downloadable zip.
77
- """)
78
- input_text = gr.Textbox(lines=20, label="AI Response or Prompt")
79
- output_text = gr.Textbox(lines=10, label="Agent Response")
80
- download_file = gr.File(label="Download Code Package (.zip)")
81
- submit_btn = gr.Button("Generate and Package")
 
 
 
 
 
 
 
 
82
 
83
- submit_btn.click(respond, inputs=[input_text], outputs=[output_text, download_file])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
 
85
- demo.launch()
 
2
  import gradio as gr
3
  import spaces
4
  import zipfile
5
+ import json
6
+ import re
7
+ import uuid
8
  from huggingface_hub import hf_hub_download
9
  from llama_cpp import Llama
10
+ from llama_cpp_agent import LlamaCppAgent, MessagesFormatterType
11
  from llama_cpp_agent.providers import LlamaCppPythonProvider
12
 
13
  MODEL_NAME = "neuraldaredevil-8b-abliterated-q4_k_m-imat.gguf"
14
  MODEL_PATH = f"models/{MODEL_NAME}"
15
 
16
+ # Download model ahead of time
17
  hf_hub_download(
18
  repo_id="tHottie/NeuralDaredevil-8B-abliterated-Q4_K_M-GGUF",
19
  filename=MODEL_NAME,
20
+ local_dir="./models",
21
  )
22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  @spaces.GPU(duration=120)
24
+ def process_and_package(ai_response: str):
25
+ # Initialize the LLM & agent
26
  llm = Llama(
27
  model_path=MODEL_PATH,
28
+ # Use CPU / fallback settings (or GPU if supported)
29
+ n_gpu_layers=0,
30
+ n_batch=512,
31
+ n_ctx=4096,
32
  verbose=False
33
  )
34
  provider = LlamaCppPythonProvider(llm)
35
  agent = LlamaCppAgent(
36
  provider,
37
+ system_prompt=(
38
+ "You are a code parsing assistant. The user will paste an AI response "
39
+ "that mentions multiple code files. Output a JSON object where keys are filenames "
40
+ "and values are the full source code text. Make sure the JSON structure is valid."
41
+ ),
42
+ predefined_messages_formatter_type=MessagesFormatterType.GEMMA_2,
43
+ debug_output=True
44
  )
45
 
46
+ # Ask the agent to output the JSON mapping
47
+ full = ""
48
+ for chunk in agent.run(ai_response):
49
+ full += chunk
50
 
51
+ # Try to parse JSON
52
+ file_map = {}
53
+ try:
54
+ file_map = json.loads(full)
55
+ except Exception as e:
56
+ # Fallback: simple regex heuristics
57
+ # Match patterns like "Filename: x/y.py ``` ... ```"
58
+ pattern = r"Filename:\s*(?P<fname>[\w\.\-/]+)\s*```(?:[a-zA-Z0-9]*\n)?(?P<code>[\s\S]*?)```"
59
+ for m in re.finditer(pattern, full, re.DOTALL):
60
+ fname = m.group("fname").strip()
61
+ code = m.group("code").rstrip()
62
+ file_map[fname] = code
63
+
64
+ if not file_map:
65
+ # as ultimate fallback, put entire output in a single file
66
+ file_map["output.txt"] = full
67
 
68
+ # Write files and zip
69
+ temp_dir = f"/tmp/codeproj_{uuid.uuid4().hex}"
70
+ os.makedirs(temp_dir, exist_ok=True)
71
+
72
+ for fname, code in file_map.items():
73
+ dest = os.path.join(temp_dir, fname)
74
+ os.makedirs(os.path.dirname(dest), exist_ok=True)
75
+ with open(dest, "w", encoding="utf-8") as f:
76
+ f.write(code)
77
+
78
+ zip_name = f"code_bundle_{uuid.uuid4().hex}.zip"
79
+ zip_path = os.path.join("/tmp", zip_name)
80
+ with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
81
+ for root, _, files in os.walk(temp_dir):
82
+ for fn in files:
83
+ fullp = os.path.join(root, fn)
84
+ rel = os.path.relpath(fullp, temp_dir)
85
+ zf.write(fullp, arcname=rel)
86
+
87
+ return zip_path
88
+
89
+ with gr.Blocks() as demo:
90
+ gr.Markdown("### Paste AI response below; get downloadable zip of parsed files")
91
+ inp = gr.Textbox(lines=15, label="AI response text")
92
+ btn = gr.Button("Generate Zip")
93
+ out = gr.File(label="Download .zip")
94
+ btn.click(fn=process_and_package, inputs=inp, outputs=out)
95
 
96
+ demo.launch()