MegaTronX commited on
Commit
5da2830
·
verified ·
1 Parent(s): 548ac73

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -84
app.py CHANGED
@@ -1,103 +1,90 @@
 
1
  import os
2
- import re
3
- import json
4
- import uuid
5
  import zipfile
6
- from huggingface_hub import hf_hub_download
7
  from llama_cpp import Llama
8
  from llama_cpp_agent import LlamaCppAgent, MessagesFormatterType
9
  from llama_cpp_agent.providers import LlamaCppPythonProvider
10
- import spaces
 
 
11
 
12
- LOG_PATH = "/tmp/codegen.log"
 
 
13
 
14
- def log(message: str):
15
- with open(LOG_PATH, "a", encoding="utf-8") as log_file:
16
- log_file.write(message + "\n")
17
- print(message)
18
 
19
  @spaces.GPU(duration=120)
20
- def process_code_generation(ai_response: str):
21
- try:
22
- log("=== Started process_code_generation ===")
23
 
24
- # Download model
25
- model_path = hf_hub_download(
26
- repo_id="tHottie/NeuralDaredevil-8B-abliterated-Q4_K_M-GGUF",
27
- filename="neuraldaredevil-8b-abliterated-q4_k_m-imat.gguf",
28
- local_dir="./models"
29
- )
30
- log(f"Downloaded model to: {model_path}")
 
 
 
 
 
 
 
31
 
32
- # Load LLM
33
- llm = Llama(
34
- model_path=model_path,
35
- n_gpu_layers=0,
36
- n_batch=512,
37
- n_ctx=4096,
38
- verbose=True
39
- )
40
- log("Loaded Llama model.")
41
 
42
- provider = LlamaCppPythonProvider(llm)
43
- agent = LlamaCppAgent(
44
- provider,
45
- system_prompt="Convert an AI response with multiple code files into a JSON mapping file names to code.",
46
- predefined_messages_formatter_type=MessagesFormatterType.GEMMA_2,
47
- )
 
48
 
49
- prompt = f"""Given this AI response, output a JSON like: {{"main.py": "...", "utils/helper.js": "..."}} only:
50
-
51
- {ai_response}
52
- """
53
- log("Generated prompt. Sending to model...")
54
 
55
- full_response = ""
56
- for chunk in agent.get_chat_response(prompt, returns_streaming_generator=True):
57
- full_response += chunk
58
- log("Model response received:")
59
- log(full_response)
 
 
60
 
61
- # Try parsing JSON
62
- try:
63
- parsed = json.loads(full_response)
64
- except Exception as e:
65
- log(f"JSON decode failed: {e}")
66
- parsed = {}
67
- matches = re.finditer(r"(?s)File(?:name)?:\s*(.+?)\n```(?:\w*\n)?(.*?)```", full_response)
68
- for match in matches:
69
- filename = match.group(1).strip()
70
- code = match.group(2).strip()
71
- parsed[filename] = code
72
- if not parsed:
73
- parsed = {"raw_output.txt": full_response}
74
 
75
- log(f"Parsed files: {list(parsed.keys())}")
 
 
 
 
 
 
 
 
 
76
 
77
- temp_dir = f"/tmp/files_{uuid.uuid4().hex}"
78
- os.makedirs(temp_dir, exist_ok=True)
79
-
80
- for fname, content in parsed.items():
81
- file_path = os.path.join(temp_dir, fname)
82
- os.makedirs(os.path.dirname(file_path), exist_ok=True)
83
- with open(file_path, "w", encoding="utf-8") as f:
84
- f.write(content)
85
- log(f"Saved file: {file_path}")
86
-
87
- zip_path = f"/tmp/code_bundle_{uuid.uuid4().hex}.zip"
88
- with zipfile.ZipFile(zip_path, "w") as zipf:
89
- for root, _, files in os.walk(temp_dir):
90
- for file in files:
91
- full_path = os.path.join(root, file)
92
- arcname = os.path.relpath(full_path, temp_dir)
93
- zipf.write(full_path, arcname)
94
- log(f"Added to ZIP: {arcname}")
95
-
96
- log(f"Zip file created at: {zip_path}")
97
- log("=== Finished process_code_generation ===\n\n")
98
  return zip_path
 
 
 
 
 
 
 
 
 
99
 
100
- except Exception as ex:
101
- error_msg = f"Exception: {repr(ex)}"
102
- log(error_msg)
103
- return error_msg
 
1
+ import spaces
2
  import os
3
+ import gradio as gr
 
 
4
  import zipfile
5
+ import tempfile
6
  from llama_cpp import Llama
7
  from llama_cpp_agent import LlamaCppAgent, MessagesFormatterType
8
  from llama_cpp_agent.providers import LlamaCppPythonProvider
9
+ from llama_cpp_agent.chat_history import BasicChatHistory
10
+ from llama_cpp_agent.chat_history.messages import Roles
11
+ from huggingface_hub import hf_hub_download
12
 
13
+ MODEL_REPO = "tHottie/NeuralDaredevil-8B-abliterated-Q4_K_M-GGUF"
14
+ MODEL_FILENAME = "neuraldaredevil-8b-abliterated-q4_k_m-imat.gguf"
15
+ MODEL_PATH = f"models/{MODEL_FILENAME}"
16
 
17
+ hf_hub_download(repo_id=MODEL_REPO, filename=MODEL_FILENAME, local_dir="./models")
 
 
 
18
 
19
  @spaces.GPU(duration=120)
20
+ def generate_code_zip(prompt):
21
+ chat_template = MessagesFormatterType.GEMMA_2
 
22
 
23
+ llm = Llama(
24
+ model_path=MODEL_PATH,
25
+ flash_attn=True,
26
+ n_gpu_layers=81,
27
+ n_batch=1024,
28
+ n_ctx=8192,
29
+ )
30
+ provider = LlamaCppPythonProvider(llm)
31
+ agent = LlamaCppAgent(
32
+ provider,
33
+ system_prompt="You are an AI code generation agent. Respond with code blocks per file name.",
34
+ predefined_messages_formatter_type=chat_template,
35
+ debug_output=True
36
+ )
37
 
38
+ messages = BasicChatHistory()
39
+ messages.add_message({"role": Roles.user, "content": prompt})
 
 
 
 
 
 
 
40
 
41
+ stream = agent.get_chat_response(
42
+ prompt,
43
+ llm_sampling_settings=provider.get_provider_default_settings(),
44
+ chat_history=messages,
45
+ returns_streaming_generator=False,
46
+ print_output=True
47
+ )
48
 
49
+ response = stream if isinstance(stream, str) else "".join(stream)
50
+ file_map = parse_code_blocks(response)
51
+
52
+ temp_dir = tempfile.mkdtemp()
53
+ zip_path = os.path.join(temp_dir, "generated_code.zip")
54
 
55
+ with zipfile.ZipFile(zip_path, "w") as zipf:
56
+ for filename, code in file_map.items():
57
+ full_path = os.path.join(temp_dir, filename)
58
+ os.makedirs(os.path.dirname(full_path), exist_ok=True)
59
+ with open(full_path, "w", encoding="utf-8") as f:
60
+ f.write(code)
61
+ zipf.write(full_path, arcname=filename)
62
 
63
+ return zip_path
 
 
 
 
 
 
 
 
 
 
 
 
64
 
65
+ def parse_code_blocks(text):
66
+ import re
67
+ file_blocks = {}
68
+ pattern = r"###\s*(.*?)\n```(?:[a-zA-Z0-9+]*\n)?(.*?)```"
69
+ matches = re.findall(pattern, text, re.DOTALL)
70
+ for filename, content in matches:
71
+ cleaned_filename = filename.strip()
72
+ cleaned_code = content.strip()
73
+ file_blocks[cleaned_filename] = cleaned_code
74
+ return file_blocks
75
 
76
+ def interface_fn(prompt):
77
+ try:
78
+ zip_path = generate_code_zip(prompt)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
  return zip_path
80
+ except Exception as e:
81
+ return f"Error: {e}"
82
+
83
+ with gr.Blocks() as demo:
84
+ gr.Markdown("## AI Code Packager (GGUF-Powered)")
85
+ prompt = gr.Textbox(label="Enter AI response or code instructions")
86
+ output = gr.File(label="Download Zip")
87
+ btn = gr.Button("Generate Zip")
88
+ btn.click(fn=interface_fn, inputs=prompt, outputs=output)
89
 
90
+ demo.launch()