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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import torch
|
3 |
+
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
|
4 |
+
import logging
|
5 |
+
import json
|
6 |
+
import re
|
7 |
+
from typing import List, Dict
|
8 |
+
from datetime import datetime
|
9 |
+
|
10 |
+
# Setup logging
|
11 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
12 |
+
logger = logging.getLogger(__name__)
|
13 |
+
|
14 |
+
# Model configuration
|
15 |
+
MODEL_NAME = "wizcodes12/snaxfix-model"
|
16 |
+
SUPPORTED_LANGUAGES = [
|
17 |
+
"python", "javascript", "java", "c", "cpp", "csharp", "rust",
|
18 |
+
"php", "html", "css", "sql"
|
19 |
+
]
|
20 |
+
MAX_LENGTH = 512
|
21 |
+
|
22 |
+
# Example code snippets with errors for testing
|
23 |
+
EXAMPLE_SNIPPETS = {
|
24 |
+
"python": {
|
25 |
+
"broken": 'def add(a b):\n return a + b',
|
26 |
+
"description": "Missing comma in function parameters"
|
27 |
+
},
|
28 |
+
"javascript": {
|
29 |
+
"broken": 'function greet() {\n console.log("Hello"\n}',
|
30 |
+
"description": "Missing closing parenthesis and brace"
|
31 |
+
},
|
32 |
+
"java": {
|
33 |
+
"broken": 'public class Hello {\n public static void main(String[] args) {\n System.out.println("Hello World")\n }\n}',
|
34 |
+
"description": "Missing semicolon"
|
35 |
+
},
|
36 |
+
"c": {
|
37 |
+
"broken": '#include <stdio.h>\n\nint main() {\n printf("Hello World")\n return 0;\n}',
|
38 |
+
"description": "Missing semicolon"
|
39 |
+
},
|
40 |
+
"cpp": {
|
41 |
+
"broken": '#include <iostream>\n\nint main() {\n std::cout << "Hello World" << std::endl\n return 0;\n}',
|
42 |
+
"description": "Missing semicolon"
|
43 |
+
},
|
44 |
+
"csharp": {
|
45 |
+
"broken": 'class Program {\n static void Main(string[] args) {\n Console.WriteLine("Hello World")\n }\n}',
|
46 |
+
"description": "Missing semicolon"
|
47 |
+
},
|
48 |
+
"rust": {
|
49 |
+
"broken": 'fn main() {\n println!("Hello World")\n}',
|
50 |
+
"description": "Missing semicolon"
|
51 |
+
},
|
52 |
+
"php": {
|
53 |
+
"broken": '<?php\n echo "Hello World"\n?>',
|
54 |
+
"description": "Missing semicolon"
|
55 |
+
},
|
56 |
+
"html": {
|
57 |
+
"broken": '<div>\n <p>Hello World</div>\n</p>',
|
58 |
+
"description": "Incorrect tag nesting"
|
59 |
+
},
|
60 |
+
"css": {
|
61 |
+
"broken": 'body {\n background-color: #ffffff\n}',
|
62 |
+
"description": "Missing semicolon"
|
63 |
+
},
|
64 |
+
"sql": {
|
65 |
+
"broken": 'SELECT name age FROM users WHERE age > 18',
|
66 |
+
"description": "Missing comma in SELECT clause"
|
67 |
+
}
|
68 |
+
}
|
69 |
+
|
70 |
+
class SyntaxFixerApp:
|
71 |
+
def __init__(self):
|
72 |
+
logger.info("Initializing SyntaxFixerApp...")
|
73 |
+
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
74 |
+
logger.info(f"Using device: {self.device}")
|
75 |
+
|
76 |
+
# Load model and tokenizer
|
77 |
+
try:
|
78 |
+
self.tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
|
79 |
+
self.model = AutoModelForSeq2SeqLM.from_pretrained(MODEL_NAME)
|
80 |
+
self.model.to(self.device)
|
81 |
+
self.model.eval()
|
82 |
+
logger.info("Model and tokenizer loaded successfully")
|
83 |
+
except Exception as e:
|
84 |
+
logger.error(f"Failed to load model: {e}")
|
85 |
+
raise
|
86 |
+
|
87 |
+
# Initialize history
|
88 |
+
self.history = []
|
89 |
+
|
90 |
+
def fix_syntax(self, broken_code: str, language: str) -> str:
|
91 |
+
"""Fix syntax errors in the provided code."""
|
92 |
+
if not broken_code.strip():
|
93 |
+
return "Error: Please enter code to fix."
|
94 |
+
|
95 |
+
if language not in SUPPORTED_LANGUAGES:
|
96 |
+
return f"Error: Language '{language}' is not supported. Choose from: {', '.join(SUPPORTED_LANGUAGES)}"
|
97 |
+
|
98 |
+
try:
|
99 |
+
# Prepare input
|
100 |
+
input_text = f"<{language.upper()}> Fix the syntax errors in this {language} code: {broken_code}"
|
101 |
+
inputs = self.tokenizer(
|
102 |
+
input_text,
|
103 |
+
max_length=MAX_LENGTH,
|
104 |
+
truncation=True,
|
105 |
+
padding=True,
|
106 |
+
return_tensors="pt"
|
107 |
+
).to(self.device)
|
108 |
+
|
109 |
+
# Generate fixed code
|
110 |
+
with torch.no_grad():
|
111 |
+
outputs = self.model.generate(
|
112 |
+
**inputs,
|
113 |
+
max_length=MAX_LENGTH,
|
114 |
+
num_beams=4,
|
115 |
+
early_stopping=True,
|
116 |
+
do_sample=False,
|
117 |
+
temperature=0.7,
|
118 |
+
pad_token_id=self.tokenizer.pad_token_id,
|
119 |
+
use_cache=True
|
120 |
+
)
|
121 |
+
|
122 |
+
fixed_code = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
|
123 |
+
|
124 |
+
# Save to history
|
125 |
+
self.history.append({
|
126 |
+
"timestamp": datetime.now().isoformat(),
|
127 |
+
"language": language,
|
128 |
+
"broken_code": broken_code,
|
129 |
+
"fixed_code": fixed_code
|
130 |
+
})
|
131 |
+
|
132 |
+
return fixed_code
|
133 |
+
except Exception as e:
|
134 |
+
logger.error(f"Error fixing code: {e}")
|
135 |
+
return f"Error: Failed to fix code - {str(e)}"
|
136 |
+
|
137 |
+
def load_example(self, language: str) -> str:
|
138 |
+
"""Load example broken code for the selected language."""
|
139 |
+
return EXAMPLE_SNIPPETS.get(language, {}).get("broken", "No example available for this language.")
|
140 |
+
|
141 |
+
def get_history(self) -> str:
|
142 |
+
"""Return formatted history of fixes."""
|
143 |
+
if not self.history:
|
144 |
+
return "No history available."
|
145 |
+
|
146 |
+
history_text = "=== Fix History ===\n"
|
147 |
+
for entry in self.history:
|
148 |
+
history_text += f"Timestamp: {entry['timestamp']}\n"
|
149 |
+
history_text += f"Language: {entry['language']}\n"
|
150 |
+
history_text += f"Broken Code:\n{entry['broken_code']}\n"
|
151 |
+
history_text += f"Fixed Code:\n{entry['fixed_code']}\n"
|
152 |
+
history_text += "-" * 50 + "\n"
|
153 |
+
return history_text
|
154 |
+
|
155 |
+
def clear_history(self) -> str:
|
156 |
+
"""Clear the history of fixes."""
|
157 |
+
self.history = []
|
158 |
+
return "History cleared."
|
159 |
+
|
160 |
+
def create_gradio_interface():
|
161 |
+
"""Create and return the Gradio interface."""
|
162 |
+
app = SyntaxFixerApp()
|
163 |
+
|
164 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
165 |
+
gr.Markdown("# SnaxFix: Advanced Syntax Error Fixer")
|
166 |
+
gr.Markdown("Fix syntax errors in code across multiple programming languages using the `snaxfix-model` by wizcodes12.")
|
167 |
+
|
168 |
+
with gr.Row():
|
169 |
+
with gr.Column(scale=2):
|
170 |
+
language_dropdown = gr.Dropdown(
|
171 |
+
choices=SUPPORTED_LANGUAGES,
|
172 |
+
label="Select Programming Language",
|
173 |
+
value="python"
|
174 |
+
)
|
175 |
+
code_input = gr.Code(
|
176 |
+
label="Enter Code with Syntax Errors",
|
177 |
+
lines=10,
|
178 |
+
language="python"
|
179 |
+
)
|
180 |
+
with gr.Row():
|
181 |
+
fix_button = gr.Button("Fix Syntax", variant="primary")
|
182 |
+
example_button = gr.Button("Load Example", variant="secondary")
|
183 |
+
clear_button = gr.Button("Clear Input", variant="secondary")
|
184 |
+
|
185 |
+
with gr.Column(scale=2):
|
186 |
+
code_output = gr.Code(
|
187 |
+
label="Fixed Code",
|
188 |
+
lines=10,
|
189 |
+
language="python"
|
190 |
+
)
|
191 |
+
|
192 |
+
with gr.Accordion("History of Fixes", open=False):
|
193 |
+
history_output = gr.Textbox(label="Fix History", lines=10)
|
194 |
+
clear_history_button = gr.Button("Clear History")
|
195 |
+
|
196 |
+
with gr.Accordion("About & License", open=False):
|
197 |
+
gr.Markdown("""
|
198 |
+
**About SnaxFix**
|
199 |
+
SnaxFix is an AI-powered tool for fixing syntax errors in multiple programming languages, built with `google/flan-t5-base` and fine-tuned by wizcodes12.
|
200 |
+
|
201 |
+
**MIT License**
|
202 |
+
This project is licensed under the MIT License. See the [LICENSE](https://github.com/wizcodes12/snaxfix-model/blob/main/LICENSE) file for details.
|
203 |
+
""")
|
204 |
+
|
205 |
+
# Event handlers
|
206 |
+
def update_code_language(language):
|
207 |
+
return gr.update(language=language)
|
208 |
+
|
209 |
+
fix_button.click(
|
210 |
+
fn=app.fix_syntax,
|
211 |
+
inputs=[code_input, language_dropdown],
|
212 |
+
outputs=code_output
|
213 |
+
)
|
214 |
+
example_button.click(
|
215 |
+
fn=app.load_example,
|
216 |
+
inputs=language_dropdown,
|
217 |
+
outputs=code_input
|
218 |
+
)
|
219 |
+
clear_button.click(
|
220 |
+
fn=lambda: "",
|
221 |
+
inputs=None,
|
222 |
+
outputs=code_input
|
223 |
+
)
|
224 |
+
language_dropdown.change(
|
225 |
+
fn=update_code_language,
|
226 |
+
4
|
227 |
+
outputs=code_input
|
228 |
+
)
|
229 |
+
clear_history_button.click(
|
230 |
+
fn=app.clear_history,
|
231 |
+
inputs=None,
|
232 |
+
outputs=history_output
|
233 |
+
)
|
234 |
+
fix_button.click(
|
235 |
+
fn=app.get_history,
|
236 |
+
inputs=None,
|
237 |
+
outputs=history_output,
|
238 |
+
_js="() => {return []}" # Ensure history updates after fixing
|
239 |
+
)
|
240 |
+
|
241 |
+
return demo
|
242 |
+
|
243 |
+
if __name__ == "__main__":
|
244 |
+
logger.info("Starting Gradio application...")
|
245 |
+
demo = create_gradio_interface()
|
246 |
+
try:
|
247 |
+
demo.launch()
|
248 |
+
except Exception as e:
|
249 |
+
logger.error(f"Failed to launch Gradio app: {e}")
|
250 |
+
raise
|