Leetmonkey In Action via Inference
Browse files
app.py
CHANGED
@@ -3,14 +3,11 @@ import re
|
|
3 |
import logging
|
4 |
import textwrap
|
5 |
import autopep8
|
|
|
6 |
from huggingface_hub import hf_hub_download
|
7 |
from llama_cpp import Llama
|
8 |
import jwt
|
9 |
-
from typing import
|
10 |
-
from fastapi import FastAPI, HTTPException, Depends
|
11 |
-
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
12 |
-
from pydantic import BaseModel
|
13 |
-
from fastapi.responses import StreamingResponse
|
14 |
|
15 |
# Set up logging
|
16 |
logging.basicConfig(level=logging.INFO)
|
@@ -79,32 +76,22 @@ Here's the complete Python function implementation:
|
|
79 |
return response["choices"][0]["text"]
|
80 |
|
81 |
def extract_and_format_code(text: str) -> str:
|
82 |
-
# Extract code between triple backticks
|
83 |
code_match = re.search(r'```python\s*(.*?)\s*```', text, re.DOTALL)
|
84 |
if code_match:
|
85 |
code = code_match.group(1)
|
86 |
else:
|
87 |
code = text
|
88 |
|
89 |
-
# Remove any text before the function definition
|
90 |
code = re.sub(r'^.*?(?=def\s+\w+\s*\()', '', code, flags=re.DOTALL)
|
91 |
-
|
92 |
-
# Dedent the code to remove any common leading whitespace
|
93 |
code = textwrap.dedent(code)
|
94 |
-
|
95 |
-
# Split the code into lines
|
96 |
lines = code.split('\n')
|
97 |
-
|
98 |
-
# Find the function definition line
|
99 |
func_def_index = next((i for i, line in enumerate(lines) if line.strip().startswith('def ')), 0)
|
100 |
-
|
101 |
-
# Ensure proper indentation
|
102 |
-
indented_lines = [lines[func_def_index]] # Keep the function definition as is
|
103 |
for line in lines[func_def_index + 1:]:
|
104 |
-
if line.strip():
|
105 |
-
indented_lines.append(' ' + line)
|
106 |
else:
|
107 |
-
indented_lines.append(line)
|
108 |
|
109 |
formatted_code = '\n'.join(indented_lines)
|
110 |
|
@@ -113,57 +100,38 @@ def extract_and_format_code(text: str) -> str:
|
|
113 |
except:
|
114 |
return formatted_code
|
115 |
|
116 |
-
|
117 |
-
app = FastAPI()
|
118 |
-
|
119 |
-
class ProblemRequest(BaseModel):
|
120 |
-
instruction: str
|
121 |
-
|
122 |
-
def verify_token(credentials: HTTPAuthorizationCredentials = Depends(security)):
|
123 |
try:
|
124 |
-
jwt.decode(
|
125 |
return True
|
126 |
except jwt.PyJWTError:
|
127 |
-
|
128 |
|
129 |
-
|
130 |
-
|
|
|
|
|
131 |
logger.info("Generating solution")
|
132 |
-
generated_output = generate_solution(
|
133 |
formatted_code = extract_and_format_code(generated_output)
|
134 |
logger.info("Solution generated successfully")
|
135 |
return {"solution": formatted_code}
|
136 |
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
```python
|
153 |
-
"""
|
154 |
-
|
155 |
-
generated_text = ""
|
156 |
-
for chunk in llm(full_prompt, stream=True, **generation_kwargs):
|
157 |
-
token = chunk["choices"][0]["text"]
|
158 |
-
generated_text += token
|
159 |
-
yield token
|
160 |
-
|
161 |
-
formatted_code = extract_and_format_code(generated_text)
|
162 |
-
logger.info("Solution generated successfully")
|
163 |
-
yield formatted_code
|
164 |
-
|
165 |
-
return StreamingResponse(generate(), media_type="text/plain")
|
166 |
|
167 |
if __name__ == "__main__":
|
168 |
-
|
169 |
-
uvicorn.run(app, host="0.0.0.0", port=8000)
|
|
|
3 |
import logging
|
4 |
import textwrap
|
5 |
import autopep8
|
6 |
+
import gradio as gr
|
7 |
from huggingface_hub import hf_hub_download
|
8 |
from llama_cpp import Llama
|
9 |
import jwt
|
10 |
+
from typing import Dict, Any
|
|
|
|
|
|
|
|
|
11 |
|
12 |
# Set up logging
|
13 |
logging.basicConfig(level=logging.INFO)
|
|
|
76 |
return response["choices"][0]["text"]
|
77 |
|
78 |
def extract_and_format_code(text: str) -> str:
|
|
|
79 |
code_match = re.search(r'```python\s*(.*?)\s*```', text, re.DOTALL)
|
80 |
if code_match:
|
81 |
code = code_match.group(1)
|
82 |
else:
|
83 |
code = text
|
84 |
|
|
|
85 |
code = re.sub(r'^.*?(?=def\s+\w+\s*\()', '', code, flags=re.DOTALL)
|
|
|
|
|
86 |
code = textwrap.dedent(code)
|
|
|
|
|
87 |
lines = code.split('\n')
|
|
|
|
|
88 |
func_def_index = next((i for i, line in enumerate(lines) if line.strip().startswith('def ')), 0)
|
89 |
+
indented_lines = [lines[func_def_index]]
|
|
|
|
|
90 |
for line in lines[func_def_index + 1:]:
|
91 |
+
if line.strip():
|
92 |
+
indented_lines.append(' ' + line)
|
93 |
else:
|
94 |
+
indented_lines.append(line)
|
95 |
|
96 |
formatted_code = '\n'.join(indented_lines)
|
97 |
|
|
|
100 |
except:
|
101 |
return formatted_code
|
102 |
|
103 |
+
def verify_token(token: str) -> bool:
|
|
|
|
|
|
|
|
|
|
|
|
|
104 |
try:
|
105 |
+
jwt.decode(token, JWT_SECRET, algorithms=[JWT_ALGORITHM])
|
106 |
return True
|
107 |
except jwt.PyJWTError:
|
108 |
+
return False
|
109 |
|
110 |
+
def generate_code(instruction: str, token: str) -> Dict[str, Any]:
|
111 |
+
if not verify_token(token):
|
112 |
+
return {"error": "Invalid token"}
|
113 |
+
|
114 |
logger.info("Generating solution")
|
115 |
+
generated_output = generate_solution(instruction)
|
116 |
formatted_code = extract_and_format_code(generated_output)
|
117 |
logger.info("Solution generated successfully")
|
118 |
return {"solution": formatted_code}
|
119 |
|
120 |
+
# Gradio API
|
121 |
+
api = gr.Interface(
|
122 |
+
fn=generate_code,
|
123 |
+
inputs=[
|
124 |
+
gr.Textbox(label="LeetCode Problem Instruction"),
|
125 |
+
gr.Textbox(label="JWT Token")
|
126 |
+
],
|
127 |
+
outputs=gr.JSON(),
|
128 |
+
title="LeetCode Problem Solver API",
|
129 |
+
description="Provide a LeetCode problem instruction and a valid JWT token to generate a solution.",
|
130 |
+
examples=[
|
131 |
+
["Implement a function to reverse a linked list", "your_jwt_token_here"],
|
132 |
+
["Write a function to find the maximum subarray sum", "your_jwt_token_here"]
|
133 |
+
]
|
134 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
135 |
|
136 |
if __name__ == "__main__":
|
137 |
+
api.launch(server_name="0.0.0.0", server_port=7860)
|
|