File size: 9,101 Bytes
cf81250
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
import gradio as gr
import torch
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
import logging
import json
import re
from typing import List, Dict
from datetime import datetime

# Setup logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

# Model configuration
MODEL_NAME = "wizcodes12/snaxfix-model"
SUPPORTED_LANGUAGES = [
    "python", "javascript", "java", "c", "cpp", "csharp", "rust", 
    "php", "html", "css", "sql"
]
MAX_LENGTH = 512

# Example code snippets with errors for testing
EXAMPLE_SNIPPETS = {
    "python": {
        "broken": 'def add(a b):\n    return a + b',
        "description": "Missing comma in function parameters"
    },
    "javascript": {
        "broken": 'function greet() {\n    console.log("Hello"\n}',
        "description": "Missing closing parenthesis and brace"
    },
    "java": {
        "broken": 'public class Hello {\n    public static void main(String[] args) {\n        System.out.println("Hello World")\n    }\n}',
        "description": "Missing semicolon"
    },
    "c": {
        "broken": '#include <stdio.h>\n\nint main() {\n    printf("Hello World")\n    return 0;\n}',
        "description": "Missing semicolon"
    },
    "cpp": {
        "broken": '#include <iostream>\n\nint main() {\n    std::cout << "Hello World" << std::endl\n    return 0;\n}',
        "description": "Missing semicolon"
    },
    "csharp": {
        "broken": 'class Program {\n    static void Main(string[] args) {\n        Console.WriteLine("Hello World")\n    }\n}',
        "description": "Missing semicolon"
    },
    "rust": {
        "broken": 'fn main() {\n    println!("Hello World")\n}',
        "description": "Missing semicolon"
    },
    "php": {
        "broken": '<?php\n    echo "Hello World"\n?>',
        "description": "Missing semicolon"
    },
    "html": {
        "broken": '<div>\n    <p>Hello World</div>\n</p>',
        "description": "Incorrect tag nesting"
    },
    "css": {
        "broken": 'body {\n    background-color: #ffffff\n}',
        "description": "Missing semicolon"
    },
    "sql": {
        "broken": 'SELECT name age FROM users WHERE age > 18',
        "description": "Missing comma in SELECT clause"
    }
}

class SyntaxFixerApp:
    def __init__(self):
        logger.info("Initializing SyntaxFixerApp...")
        self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
        logger.info(f"Using device: {self.device}")
        
        # Load model and tokenizer
        try:
            self.tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
            self.model = AutoModelForSeq2SeqLM.from_pretrained(MODEL_NAME)
            self.model.to(self.device)
            self.model.eval()
            logger.info("Model and tokenizer loaded successfully")
        except Exception as e:
            logger.error(f"Failed to load model: {e}")
            raise
        
        # Initialize history
        self.history = []
        
    def fix_syntax(self, broken_code: str, language: str) -> str:
        """Fix syntax errors in the provided code."""
        if not broken_code.strip():
            return "Error: Please enter code to fix."
        
        if language not in SUPPORTED_LANGUAGES:
            return f"Error: Language '{language}' is not supported. Choose from: {', '.join(SUPPORTED_LANGUAGES)}"
        
        try:
            # Prepare input
            input_text = f"<{language.upper()}> Fix the syntax errors in this {language} code: {broken_code}"
            inputs = self.tokenizer(
                input_text,
                max_length=MAX_LENGTH,
                truncation=True,
                padding=True,
                return_tensors="pt"
            ).to(self.device)
            
            # Generate fixed code
            with torch.no_grad():
                outputs = self.model.generate(
                    **inputs,
                    max_length=MAX_LENGTH,
                    num_beams=4,
                    early_stopping=True,
                    do_sample=False,
                    temperature=0.7,
                    pad_token_id=self.tokenizer.pad_token_id,
                    use_cache=True
                )
            
            fixed_code = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
            
            # Save to history
            self.history.append({
                "timestamp": datetime.now().isoformat(),
                "language": language,
                "broken_code": broken_code,
                "fixed_code": fixed_code
            })
            
            return fixed_code
        except Exception as e:
            logger.error(f"Error fixing code: {e}")
            return f"Error: Failed to fix code - {str(e)}"

    def load_example(self, language: str) -> str:
        """Load example broken code for the selected language."""
        return EXAMPLE_SNIPPETS.get(language, {}).get("broken", "No example available for this language.")

    def get_history(self) -> str:
        """Return formatted history of fixes."""
        if not self.history:
            return "No history available."
        
        history_text = "=== Fix History ===\n"
        for entry in self.history:
            history_text += f"Timestamp: {entry['timestamp']}\n"
            history_text += f"Language: {entry['language']}\n"
            history_text += f"Broken Code:\n{entry['broken_code']}\n"
            history_text += f"Fixed Code:\n{entry['fixed_code']}\n"
            history_text += "-" * 50 + "\n"
        return history_text

    def clear_history(self) -> str:
        """Clear the history of fixes."""
        self.history = []
        return "History cleared."

def create_gradio_interface():
    """Create and return the Gradio interface."""
    app = SyntaxFixerApp()
    
    with gr.Blocks(theme=gr.themes.Soft()) as demo:
        gr.Markdown("# SnaxFix: Advanced Syntax Error Fixer")
        gr.Markdown("Fix syntax errors in code across multiple programming languages using the `snaxfix-model` by wizcodes12.")
        
        with gr.Row():
            with gr.Column(scale=2):
                language_dropdown = gr.Dropdown(
                    choices=SUPPORTED_LANGUAGES,
                    label="Select Programming Language",
                    value="python"
                )
                code_input = gr.Code(
                    label="Enter Code with Syntax Errors",
                    lines=10,
                    language="python"
                )
                with gr.Row():
                    fix_button = gr.Button("Fix Syntax", variant="primary")
                    example_button = gr.Button("Load Example", variant="secondary")
                    clear_button = gr.Button("Clear Input", variant="secondary")
            
            with gr.Column(scale=2):
                code_output = gr.Code(
                    label="Fixed Code",
                    lines=10,
                    language="python"
                )
        
        with gr.Accordion("History of Fixes", open=False):
            history_output = gr.Textbox(label="Fix History", lines=10)
            clear_history_button = gr.Button("Clear History")
        
        with gr.Accordion("About & License", open=False):
            gr.Markdown("""
                **About SnaxFix**
                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.
                
                **MIT License**
                This project is licensed under the MIT License. See the [LICENSE](https://github.com/wizcodes12/snaxfix-model/blob/main/LICENSE) file for details.
            """)
        
        # Event handlers
        def update_code_language(language):
            return gr.update(language=language)
        
        fix_button.click(
            fn=app.fix_syntax,
            inputs=[code_input, language_dropdown],
            outputs=code_output
        )
        example_button.click(
            fn=app.load_example,
            inputs=language_dropdown,
            outputs=code_input
        )
        clear_button.click(
            fn=lambda: "",
            inputs=None,
            outputs=code_input
        )
        language_dropdown.change(
            fn=update_code_language,
            4
            outputs=code_input
        )
        clear_history_button.click(
            fn=app.clear_history,
            inputs=None,
            outputs=history_output
        )
        fix_button.click(
            fn=app.get_history,
            inputs=None,
            outputs=history_output,
            _js="() => {return []}"  # Ensure history updates after fixing
        )
    
    return demo

if __name__ == "__main__":
    logger.info("Starting Gradio application...")
    demo = create_gradio_interface()
    try:
        demo.launch()
    except Exception as e:
        logger.error(f"Failed to launch Gradio app: {e}")
        raise