File size: 13,539 Bytes
f59cf24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
# import json

# def analyze_code(language, code, tokenizer, model):
#     messages = [
#         {
#             "role": "system",
#             "content": (
#                 "You are a helpful and expert-level AI code reviewer and bug fixer. "
#                 "Your task is to analyze the given buggy code in the specified programming language, "
#                 "identify bugs (logical, syntax, runtime, etc.), and fix them. "
#                 "Return a JSON object with the following keys:\n\n"
#                 "1. 'bug_analysis': a list of objects, each containing:\n"
#                 "   - 'line_number': the line number (approximate if needed)\n"
#                 "   - 'error_message': a short name of the bug\n"
#                 "   - 'explanation': short explanation of the problem\n"
#                 "   - 'fix_suggestion': how to fix it\n"
#                 "2. 'corrected_code': the entire corrected code block.\n\n"
#                 "Respond with ONLY the raw JSON object, no extra commentary or markdown."
#             )
#         },
#         {
#             "role": "user",
#             "content": f"πŸ’» Language: {language}\n🐞 Buggy Code:\n```{language.lower()}\n{code.strip()}\n```"
#         }
#     ]

#     inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt").to(model.device)
#     attention_mask = (inputs != tokenizer.pad_token_id).long()

#     outputs = model.generate(
#         inputs,
#         attention_mask=attention_mask,
#         max_new_tokens=1024,
#         do_sample=False,
#         pad_token_id=tokenizer.eos_token_id,
#         eos_token_id=tokenizer.eos_token_id
#     )

#     response = tokenizer.decode(outputs[0][inputs.shape[1]:], skip_special_tokens=True)

#     # Try parsing response to JSON
#     try:
#         json_output = json.loads(response)
#         return json_output
#     except json.JSONDecodeError:
#         print("⚠️ Could not decode response into JSON. Here's the raw output:\n")
#         print(response)
#         return None
# import json
# import logging
# import time
# import torch

# # Configure logging
# logger = logging.getLogger(__name__)

# def analyze_code(language, code, tokenizer, model):
#     """
#     Analyze code and return bug analysis with improved logging and error handling
#     """
#     start_time = time.time()
#     logger.info(f"πŸ” Starting analysis for {language} code ({len(code)} characters)")
    
#     try:
#         # Prepare messages
#         messages = [
#             {
#                 "role": "system",
#                 "content": (
#                     "You are a helpful and expert-level AI code reviewer and bug fixer. "
#                     "Your task is to analyze the given buggy code in the specified programming language, "
#                     "identify bugs (logical, syntax, runtime, etc.), and fix them. "
#                     "Return a JSON object with the following keys:\n\n"
#                     "1. 'bug_analysis': a list of objects, each containing:\n"
#                     "   - 'line_number': the line number (approximate if needed)\n"
#                     "   - 'error_message': a short name of the bug\n"
#                     "   - 'explanation': short explanation of the problem\n"
#                     "   - 'fix_suggestion': how to fix it\n"
#                     "2. 'corrected_code': the entire corrected code block.\n\n"
#                     "Respond with ONLY the raw JSON object, no extra commentary or markdown."
#                 )
#             },
#             {
#                 "role": "user",
#                 "content": f"πŸ’» Language: {language}\n🐞 Buggy Code:\n```{language.lower()}\n{code.strip()}\n```"
#             }
#         ]

#         logger.info("πŸ”§ Applying chat template...")
#         inputs = tokenizer.apply_chat_template(
#             messages, 
#             add_generation_prompt=True, 
#             return_tensors="pt"
#         ).to(model.device)
        
#         attention_mask = (inputs != tokenizer.pad_token_id).long()
        
#         logger.info(f"πŸ“ Input length: {inputs.shape[1]} tokens")
#         logger.info("πŸš€ Starting model generation...")
        
#         generation_start = time.time()
        
#         # Generate with more conservative settings
#         with torch.no_grad():  # Ensure no gradients are computed
#             outputs = model.generate(
#                 inputs,
#                 attention_mask=attention_mask,
#                 max_new_tokens=512,  # Reduced from 1024 for faster inference
#                 do_sample=False,
#                 temperature=0.1,  # Add temperature for more consistent output
#                 pad_token_id=tokenizer.eos_token_id,
#                 eos_token_id=tokenizer.eos_token_id,
#                 use_cache=True,  # Enable KV cache for efficiency
#             )
        
#         generation_time = time.time() - generation_start
#         logger.info(f"⚑ Generation completed in {generation_time:.2f} seconds")
        
#         logger.info("πŸ“ Decoding response...")
#         response = tokenizer.decode(outputs[0][inputs.shape[1]:], skip_special_tokens=True)
        
#         logger.info(f"πŸ“„ Response length: {len(response)} characters")
#         logger.info(f"πŸ” First 100 chars: {response[:100]}...")

#         # Try parsing response to JSON
#         logger.info("πŸ” Attempting to parse JSON...")
#         try:
#             # Clean up response - remove any markdown formatting
#             cleaned_response = response.strip()
#             if cleaned_response.startswith('```json'):
#                 cleaned_response = cleaned_response[7:]
#             if cleaned_response.startswith('```'):
#                 cleaned_response = cleaned_response[3:]
#             if cleaned_response.endswith('```'):
#                 cleaned_response = cleaned_response[:-3]
            
#             cleaned_response = cleaned_response.strip()
            
#             json_output = json.loads(cleaned_response)
            
#             total_time = time.time() - start_time
#             logger.info(f"βœ… Analysis completed successfully in {total_time:.2f} seconds")
            
#             # Validate the JSON structure
#             if not isinstance(json_output, dict):
#                 raise ValueError("Response is not a dictionary")
                
#             if 'bug_analysis' not in json_output:
#                 logger.warning("⚠️ Missing 'bug_analysis' key, adding empty list")
#                 json_output['bug_analysis'] = []
                
#             if 'corrected_code' not in json_output:
#                 logger.warning("⚠️ Missing 'corrected_code' key, adding original code")
#                 json_output['corrected_code'] = code
            
#             return json_output
            
#         except json.JSONDecodeError as e:
#             logger.error(f"❌ JSON decode error: {e}")
#             logger.error(f"πŸ“„ Raw response: {repr(response)}")
            
#             # Return a fallback structure with the raw response
#             fallback_response = {
#                 "bug_analysis": [{
#                     "line_number": 1,
#                     "error_message": "Analysis parsing failed",
#                     "explanation": "The AI model returned a response that couldn't be parsed as JSON",
#                     "fix_suggestion": "Please try again or check the code format"
#                 }],
#                 "corrected_code": code,
#                 "raw_output": response,
#                 "parsing_error": str(e)
#             }
            
#             return fallback_response
            
#     except Exception as e:
#         total_time = time.time() - start_time
#         logger.error(f"❌ Analysis failed after {total_time:.2f} seconds: {str(e)}")
#         logger.error(f"πŸ’₯ Exception type: {type(e).__name__}")
        
#         # Return error response
#         return {
#             "bug_analysis": [{
#                 "line_number": 1,
#                 "error_message": "Analysis failed",
#                 "explanation": f"An error occurred during analysis: {str(e)}",
#                 "fix_suggestion": "Please try again or contact support"
#             }],
#             "corrected_code": code,
#             "error": str(e),
#             "error_type": type(e).__name__
#         }

# analyzer.py

import torch
import json
import time
import logging

# Configure logger
logger = logging.getLogger("CodeAnalyzer")
logger.setLevel(logging.INFO)
handler = logging.StreamHandler()
formatter = logging.Formatter("[%(asctime)s] [%(levelname)s] - %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)


def analyze_code(tokenizer, model, language, code):
    start_time = time.time()

    messages = [
        {
            "role": "system",
            "content": (
                "You are a helpful and expert-level AI code reviewer and bug fixer. "
                "Your task is to analyze the given buggy code in the specified programming language, "
                "identify bugs (logical, syntax, runtime, etc.), and fix them. "
                "Return a JSON object with the following keys:\n\n"
                "1. 'bug_analysis': a list of objects, each containing:\n"
                "   - 'line_number': the line number (approximate if needed)\n"
                "   - 'error_message': a short name of the bug\n"
                "   - 'explanation': short explanation of the problem\n"
                "   - 'fix_suggestion': how to fix it\n"
                "2. 'corrected_code': the entire corrected code block.\n\n"
                "Respond only with a JSON block, no extra commentary."
            )
        },
        {
            "role": "user",
            "content": f"πŸ’» Language: {language}\n🐞 Buggy Code:\n```{language.lower()}\n{code.strip()}\n```"
        }
    ]

    try:
        logger.info("πŸ“¦ Tokenizing input...")
        inputs = tokenizer.apply_chat_template(
            messages,
            add_generation_prompt=True,
            return_tensors="pt"
        ).to(model.device)

        attention_mask = (inputs != tokenizer.pad_token_id).long()

        logger.info("βš™οΈ Starting generation...")
        generation_start = time.time()
        outputs = model.generate(
            inputs,
            attention_mask=attention_mask,
            max_new_tokens=1024,
            do_sample=False,
            pad_token_id=tokenizer.eos_token_id,
            eos_token_id=tokenizer.eos_token_id
        )
        generation_time = time.time() - generation_start
        logger.info(f"⚑ Generation completed in {generation_time:.2f} seconds")

        logger.info("πŸ“ Decoding response...")
        response = tokenizer.decode(outputs[0][inputs.shape[1]:], skip_special_tokens=True)

        logger.info(f"πŸ“„ Response length: {len(response)} characters")
        logger.info(f"πŸ” First 100 chars: {response[:100]}...")

        # Attempt to parse as JSON
        logger.info("πŸ” Attempting to parse JSON...")
        cleaned_response = response.strip()
        if cleaned_response.startswith('```json'):
            cleaned_response = cleaned_response[7:]
        elif cleaned_response.startswith('```'):
            cleaned_response = cleaned_response[3:]
        if cleaned_response.endswith('```'):
            cleaned_response = cleaned_response[:-3]

        cleaned_response = cleaned_response.strip()

        json_output = json.loads(cleaned_response)

        total_time = time.time() - start_time
        logger.info(f"βœ… Analysis completed successfully in {total_time:.2f} seconds")

        # Validate and patch missing keys
        if not isinstance(json_output, dict):
            raise ValueError("Parsed response is not a dictionary")

        if 'bug_analysis' not in json_output:
            logger.warning("⚠️ Missing 'bug_analysis' key, adding empty list")
            json_output['bug_analysis'] = []

        if 'corrected_code' not in json_output:
            logger.warning("⚠️ Missing 'corrected_code' key, adding original code")
            json_output['corrected_code'] = code

        return json_output

    except json.JSONDecodeError as e:
        logger.error(f"❌ JSON decode error: {e}")
        logger.error(f"πŸ“„ Raw response: {repr(response)}")
        return {
            "bug_analysis": [{
                "line_number": 1,
                "error_message": "Analysis parsing failed",
                "explanation": "The AI model returned a response that couldn't be parsed as JSON",
                "fix_suggestion": "Please try again or check the code format"
            }],
            "corrected_code": code,
            "raw_output": response,
            "parsing_error": str(e)
        }

    except Exception as e:
        total_time = time.time() - start_time
        logger.error(f"❌ Analysis failed after {total_time:.2f} seconds: {str(e)}")
        logger.error(f"πŸ’₯ Exception type: {type(e).__name__}")
        return {
            "bug_analysis": [{
                "line_number": 1,
                "error_message": "Analysis failed",
                "explanation": f"An error occurred during analysis: {str(e)}",
                "fix_suggestion": "Please try again or contact support"
            }],
            "corrected_code": code,
            "error": str(e),
            "error_type": type(e).__name__
        }