Gosh this Leetmonkey
Browse files
app.py
CHANGED
@@ -2,12 +2,9 @@ import gradio as gr
|
|
2 |
from huggingface_hub import hf_hub_download
|
3 |
from llama_cpp import Llama
|
4 |
import re
|
5 |
-
from datasets import load_dataset
|
6 |
import random
|
7 |
import logging
|
8 |
import os
|
9 |
-
import autopep8
|
10 |
-
import textwrap
|
11 |
import jwt
|
12 |
from typing import Dict, Any
|
13 |
|
@@ -25,33 +22,9 @@ JWT_ALGORITHM = "HS256"
|
|
25 |
MODEL_NAME = "leetmonkey_peft__q8_0.gguf"
|
26 |
REPO_ID = "sugiv/leetmonkey-peft-gguf"
|
27 |
|
28 |
-
# Load the
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
def download_model(model_name):
|
33 |
-
logger.info(f"Downloading model: {model_name}")
|
34 |
-
model_path = hf_hub_download(
|
35 |
-
repo_id=REPO_ID,
|
36 |
-
filename=model_name,
|
37 |
-
cache_dir="./models",
|
38 |
-
force_download=True,
|
39 |
-
resume_download=True
|
40 |
-
)
|
41 |
-
logger.info(f"Model downloaded: {model_path}")
|
42 |
-
return model_path
|
43 |
-
|
44 |
-
# Download and load the 8-bit model at startup
|
45 |
-
model_path = download_model(MODEL_NAME)
|
46 |
-
llm = Llama(
|
47 |
-
model_path=model_path,
|
48 |
-
n_ctx=1024,
|
49 |
-
n_threads=8,
|
50 |
-
n_gpu_layers=-1, # Use all available GPU layers
|
51 |
-
verbose=False,
|
52 |
-
n_batch=512,
|
53 |
-
mlock=True
|
54 |
-
)
|
55 |
logger.info("8-bit model loaded successfully")
|
56 |
|
57 |
# Generation parameters
|
@@ -65,7 +38,17 @@ generation_kwargs = {
|
|
65 |
"repeat_penalty": 1.1
|
66 |
}
|
67 |
|
68 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
69 |
system_prompt = "You are a Python coding assistant specialized in solving LeetCode problems. Provide only the complete implementation of the given function. Ensure proper indentation and formatting. Do not include any explanations or multiple solutions."
|
70 |
full_prompt = f"""### Instruction:
|
71 |
{system_prompt}
|
@@ -80,117 +63,84 @@ Here's the complete Python function implementation:
|
|
80 |
```python
|
81 |
"""
|
82 |
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
code_match = re.search(r'```python\s*(.*?)\s*```', text, re.DOTALL)
|
89 |
if code_match:
|
90 |
code = code_match.group(1)
|
91 |
else:
|
92 |
-
code =
|
93 |
-
|
94 |
-
|
95 |
-
code = textwrap.dedent(code)
|
96 |
-
|
97 |
-
# Split the code into lines
|
98 |
-
lines = code.split('\n')
|
99 |
-
|
100 |
-
# Ensure proper indentation
|
101 |
-
indented_lines = []
|
102 |
-
for line in lines:
|
103 |
-
if line.strip().startswith('class') or line.strip().startswith('def'):
|
104 |
-
indented_lines.append(line) # Keep class and function definitions as is
|
105 |
-
elif line.strip(): # If the line is not empty
|
106 |
-
indented_lines.append(' ' + line) # Add 4 spaces of indentation
|
107 |
-
else:
|
108 |
-
indented_lines.append(line) # Keep empty lines as is
|
109 |
-
|
110 |
-
formatted_code = '\n'.join(indented_lines)
|
111 |
-
|
112 |
-
try:
|
113 |
-
return autopep8.fix_code(formatted_code)
|
114 |
-
except:
|
115 |
-
return formatted_code
|
116 |
-
|
117 |
-
def select_random_problem():
|
118 |
-
return random.choice(train_dataset)['instruction']
|
119 |
-
|
120 |
-
def verify_token(token: str) -> bool:
|
121 |
-
try:
|
122 |
-
jwt.decode(token, JWT_SECRET, algorithms=[JWT_ALGORITHM])
|
123 |
-
return True
|
124 |
-
except jwt.PyJWTError:
|
125 |
-
return False
|
126 |
-
|
127 |
-
last_generated_solution = ""
|
128 |
|
129 |
-
def
|
130 |
if not verify_token(token):
|
131 |
return {"error": "Invalid token"}
|
132 |
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
return {"solution": last_generated_solution}
|
137 |
|
138 |
-
|
139 |
-
|
140 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
141 |
|
142 |
def generate():
|
143 |
-
|
144 |
-
|
145 |
-
for token in generate_solution(instruction):
|
146 |
-
generated_text += token
|
147 |
-
yield {"token": token}
|
148 |
-
|
149 |
-
last_generated_solution = extract_and_format_code(generated_text)
|
150 |
-
yield {"solution": last_generated_solution}
|
151 |
|
152 |
return generate()
|
153 |
|
154 |
-
def
|
155 |
if not verify_token(token):
|
156 |
return {"error": "Invalid token"}
|
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 |
-
inputs=[
|
186 |
-
gr.Textbox(label="API Name"),
|
187 |
-
gr.Textbox(label="Problem Instruction"),
|
188 |
-
gr.Textbox(label="JWT Token")
|
189 |
-
],
|
190 |
-
outputs=gr.JSON(label="API Response"),
|
191 |
-
title="LeetCode Problem Solver API",
|
192 |
-
description="Provide the API name, problem instruction (if required), and JWT token to use the desired functionality."
|
193 |
)
|
194 |
|
195 |
if __name__ == "__main__":
|
196 |
-
|
|
|
2 |
from huggingface_hub import hf_hub_download
|
3 |
from llama_cpp import Llama
|
4 |
import re
|
|
|
5 |
import random
|
6 |
import logging
|
7 |
import os
|
|
|
|
|
8 |
import jwt
|
9 |
from typing import Dict, Any
|
10 |
|
|
|
22 |
MODEL_NAME = "leetmonkey_peft__q8_0.gguf"
|
23 |
REPO_ID = "sugiv/leetmonkey-peft-gguf"
|
24 |
|
25 |
+
# Load the model
|
26 |
+
model_path = hf_hub_download(repo_id=REPO_ID, filename=MODEL_NAME, cache_dir="./models")
|
27 |
+
llm = Llama(model_path=model_path, n_ctx=1024, n_threads=8, n_gpu_layers=-1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
28 |
logger.info("8-bit model loaded successfully")
|
29 |
|
30 |
# Generation parameters
|
|
|
38 |
"repeat_penalty": 1.1
|
39 |
}
|
40 |
|
41 |
+
def verify_token(token: str) -> bool:
|
42 |
+
try:
|
43 |
+
jwt.decode(token, JWT_SECRET, algorithms=[JWT_ALGORITHM])
|
44 |
+
return True
|
45 |
+
except jwt.PyJWTError:
|
46 |
+
return False
|
47 |
+
|
48 |
+
def generate_solution(instruction: str, token: str) -> Dict[str, Any]:
|
49 |
+
if not verify_token(token):
|
50 |
+
return {"error": "Invalid token"}
|
51 |
+
|
52 |
system_prompt = "You are a Python coding assistant specialized in solving LeetCode problems. Provide only the complete implementation of the given function. Ensure proper indentation and formatting. Do not include any explanations or multiple solutions."
|
53 |
full_prompt = f"""### Instruction:
|
54 |
{system_prompt}
|
|
|
63 |
```python
|
64 |
"""
|
65 |
|
66 |
+
response = llm(full_prompt, **generation_kwargs)
|
67 |
+
generated_text = response["choices"][0]["text"]
|
68 |
+
|
69 |
+
# Extract and format code
|
70 |
+
code_match = re.search(r'```python\s*(.*?)\s*```', generated_text, re.DOTALL)
|
|
|
71 |
if code_match:
|
72 |
code = code_match.group(1)
|
73 |
else:
|
74 |
+
code = generated_text
|
75 |
+
|
76 |
+
return {"solution": code}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
77 |
|
78 |
+
def stream_solution(instruction: str, token: str) -> Dict[str, Any]:
|
79 |
if not verify_token(token):
|
80 |
return {"error": "Invalid token"}
|
81 |
|
82 |
+
system_prompt = "You are a Python coding assistant specialized in solving LeetCode problems. Provide only the complete implementation of the given function. Ensure proper indentation and formatting. Do not include any explanations or multiple solutions."
|
83 |
+
full_prompt = f"""### Instruction:
|
84 |
+
{system_prompt}
|
|
|
85 |
|
86 |
+
Implement the following function for the LeetCode problem:
|
87 |
+
|
88 |
+
{instruction}
|
89 |
+
|
90 |
+
### Response:
|
91 |
+
Here's the complete Python function implementation:
|
92 |
+
|
93 |
+
```python
|
94 |
+
"""
|
95 |
|
96 |
def generate():
|
97 |
+
for chunk in llm(full_prompt, stream=True, **generation_kwargs):
|
98 |
+
yield chunk["choices"][0]["text"]
|
|
|
|
|
|
|
|
|
|
|
|
|
99 |
|
100 |
return generate()
|
101 |
|
102 |
+
def random_problem(token: str) -> Dict[str, Any]:
|
103 |
if not verify_token(token):
|
104 |
return {"error": "Invalid token"}
|
105 |
|
106 |
+
# This is a placeholder. You should replace it with actual logic to fetch a random problem from your dataset.
|
107 |
+
problems = [
|
108 |
+
"Implement a function to reverse a linked list",
|
109 |
+
"Write a function to find the maximum subarray sum",
|
110 |
+
"Implement a function to check if a binary tree is balanced"
|
111 |
+
]
|
112 |
+
return {"problem": random.choice(problems)}
|
113 |
+
|
114 |
+
# Create Gradio interfaces for each endpoint
|
115 |
+
generate_interface = gr.Interface(
|
116 |
+
fn=generate_solution,
|
117 |
+
inputs=[gr.Textbox(label="Problem Instruction"), gr.Textbox(label="JWT Token")],
|
118 |
+
outputs=gr.JSON(),
|
119 |
+
title="Generate Solution API",
|
120 |
+
description="Provide a LeetCode problem instruction and a valid JWT token to generate a solution."
|
121 |
+
)
|
122 |
|
123 |
+
stream_interface = gr.Interface(
|
124 |
+
fn=stream_solution,
|
125 |
+
inputs=[gr.Textbox(label="Problem Instruction"), gr.Textbox(label="JWT Token")],
|
126 |
+
outputs=gr.JSON(),
|
127 |
+
title="Stream Solution API",
|
128 |
+
description="Provide a LeetCode problem instruction and a valid JWT token to stream a solution."
|
129 |
+
)
|
130 |
+
|
131 |
+
random_problem_interface = gr.Interface(
|
132 |
+
fn=random_problem,
|
133 |
+
inputs=gr.Textbox(label="JWT Token"),
|
134 |
+
outputs=gr.JSON(),
|
135 |
+
title="Random Problem API",
|
136 |
+
description="Provide a valid JWT token to get a random LeetCode problem."
|
137 |
+
)
|
138 |
+
|
139 |
+
# Combine interfaces
|
140 |
+
demo = gr.TabbedInterface(
|
141 |
+
[generate_interface, stream_interface, random_problem_interface],
|
142 |
+
["Generate Solution", "Stream Solution", "Random Problem"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
143 |
)
|
144 |
|
145 |
if __name__ == "__main__":
|
146 |
+
demo.launch()
|