File size: 10,930 Bytes
a77dc20
 
 
 
 
 
 
98edac6
 
d8e1d06
 
8aef6ee
 
a77dc20
 
 
 
 
 
 
 
 
d8e1d06
 
 
 
b1ededf
 
 
 
98edac6
 
 
 
 
 
 
 
a77dc20
 
 
 
b1ededf
98edac6
 
 
 
 
 
a77dc20
 
 
 
 
 
80d4148
a77dc20
 
80d4148
 
 
d8e1d06
 
80d4148
a77dc20
 
b1ededf
d8e1d06
b1ededf
d8e1d06
 
 
b1ededf
 
d8e1d06
 
b1ededf
8aef6ee
 
 
b1ededf
 
 
 
 
 
 
 
d8e1d06
80d4148
a77dc20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98edac6
a77dc20
 
d8e1d06
 
 
 
 
 
 
 
 
 
 
 
a77dc20
d8e1d06
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a77dc20
d8e1d06
 
 
 
 
 
 
98edac6
 
 
 
 
 
 
 
 
 
b1ededf
 
 
 
 
98edac6
a77dc20
 
 
 
 
98edac6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80d4148
 
98edac6
 
764b8c8
 
3e82f96
a77dc20
98edac6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80d4148
98edac6
 
 
 
 
80d4148
98edac6
 
 
80d4148
 
 
 
 
 
d8e1d06
80d4148
 
 
d8e1d06
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80d4148
 
d8e1d06
 
 
 
 
80d4148
98edac6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a77dc20
98edac6
a77dc20
 
 
 
 
 
98edac6
 
 
a77dc20
 
 
3e82f96
 
 
47e375c
 
3e82f96
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
import gradio as gr
from transformers import AutoTokenizer, AutoModelForCausalLM
import torch
from huggingface_hub import login
import os
import logging
from datetime import datetime
import json
from typing import List, Dict
import warnings

# Filter out warnings
warnings.filterwarnings('ignore')

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Environment variables
HF_TOKEN = os.getenv("HUGGING_FACE_TOKEN")
MODEL_NAME = os.getenv("MODEL_NAME", "google/gemma-2b-it")

# Cache directory for model
CACHE_DIR = "/home/user/.cache/huggingface"
os.makedirs(CACHE_DIR, exist_ok=True)

# Enable ZeroGPU features
os.environ["ZERO_GPU"] = "1"
os.environ["CUDA_VISIBLE_DEVICES"] = "0"

class Review:
    def __init__(self, code: str, language: str, suggestions: str):
        self.code = code
        self.language = language
        self.suggestions = suggestions
        self.timestamp = datetime.now().isoformat()
        self.response_time = 0.0

class CodeReviewer:
    def __init__(self):
        self.model = None
        self.tokenizer = None
        self.device = None
        self.review_history: List[Review] = []
        self.metrics = {
            'total_reviews': 0,
            'avg_response_time': 0.0,
            'reviews_today': 0
        }
        self.initialize_model()
        
    def initialize_model(self):
        """Initialize the model and tokenizer."""
        try:
            if HF_TOKEN:
                login(token=HF_TOKEN, add_to_git_credential=False)
            
            logger.info("Loading tokenizer...")
            self.tokenizer = AutoTokenizer.from_pretrained(
                MODEL_NAME,
                token=HF_TOKEN,
                trust_remote_code=True,
                cache_dir=CACHE_DIR
            )
            
            logger.info("Loading model...")
            # Initialize model with ZeroGPU configuration
            model_kwargs = {
                "torch_dtype": torch.float16,
                "trust_remote_code": True,
                "low_cpu_mem_usage": True,
                "cache_dir": CACHE_DIR,
                "token": HF_TOKEN,
                "device_map": {"": 0}  # Use first GPU
            }
            
            # Load model with ZeroGPU support
            self.model = AutoModelForCausalLM.from_pretrained(
                MODEL_NAME,
                **model_kwargs
            )
            
            # Set device based on ZeroGPU availability
            self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
            if self.device.type == "cpu":
                logger.warning("Running on CPU - ZeroGPU not initialized")
            else:
                logger.info("ZeroGPU initialized successfully")
            
            logger.info(f"Model loaded successfully on {self.device}")
        except Exception as e:
            logger.error(f"Error initializing model: {e}")
            raise

    def create_review_prompt(self, code: str, language: str) -> str:
        """Create a structured prompt for code review."""
        return f"""Review this {language} code. List specific points in these sections:
Issues:
Improvements:
Best Practices:
Security:

Code:
```{language}
{code}
```"""

    def review_code(self, code: str, language: str) -> str:
        """Perform code review using the model."""
        try:
            start_time = datetime.now()
            prompt = self.create_review_prompt(code, language)
            
            # Tokenize with error handling
            try:
                inputs = self.tokenizer(
                    prompt,
                    return_tensors="pt",
                    truncation=True,
                    max_length=512,
                    padding=True
                ).to(self.device)
            except Exception as token_error:
                logger.error(f"Tokenization error: {token_error}")
                return "Error: Failed to process input code. Please try again."
            
            # Generate with error handling
            try:
                with torch.no_grad():
                    outputs = self.model.generate(
                        **inputs,
                        max_new_tokens=512,
                        do_sample=True,
                        temperature=0.7,
                        top_p=0.95,
                        num_beams=1,
                        early_stopping=True
                    )
            except Exception as gen_error:
                logger.error(f"Generation error: {gen_error}")
                return "Error: Failed to generate review. Please try again."
            
            # Decode with error handling
            try:
                response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
                suggestions = response[len(prompt):].strip()
            except Exception as decode_error:
                logger.error(f"Decoding error: {decode_error}")
                return "Error: Failed to decode model output. Please try again."
            
            # Create review and update metrics
            end_time = datetime.now()
            review = Review(code, language, suggestions)
            review.response_time = (end_time - start_time).total_seconds()
            self.review_history.append(review)
            
            # Update metrics
            self.update_metrics(review)
            
            # Clear GPU memory if using CUDA
            if self.device.type == "cuda":
                del inputs, outputs
                torch.cuda.empty_cache()
            
            return suggestions
            
        except Exception as e:
            logger.error(f"Error during code review: {e}")
            return f"Error performing code review: {str(e)}"

    def update_metrics(self, review: Review):
        """Update metrics with new review."""
        self.metrics['total_reviews'] += 1
        
        # Update average response time
        total_time = self.metrics['avg_response_time'] * (self.metrics['total_reviews'] - 1)
        total_time += review.response_time
        self.metrics['avg_response_time'] = total_time / self.metrics['total_reviews']
        
        # Update reviews today
        today = datetime.now().date()
        self.metrics['reviews_today'] = sum(
            1 for r in self.review_history 
            if datetime.fromisoformat(r.timestamp).date() == today
        )

    def get_history(self) -> List[Dict]:
        """Get formatted review history."""
        return [
            {
                'timestamp': r.timestamp,
                'language': r.language,
                'code': r.code,
                'suggestions': r.suggestions,
                'response_time': f"{r.response_time:.2f}s"
            }
            for r in reversed(self.review_history[-10:])  # Last 10 reviews
        ]

    def get_metrics(self) -> Dict:
        """Get current metrics."""
        return {
            'Total Reviews': self.metrics['total_reviews'],
            'Average Response Time': f"{self.metrics['avg_response_time']:.2f}s",
            'Reviews Today': self.metrics['reviews_today'],
            'Device': str(self.device)
        }

# Initialize reviewer
reviewer = CodeReviewer()

# Create Gradio interface
with gr.Blocks(theme=gr.themes.Soft()) as iface:
    gr.Markdown("# Code Review Assistant")
    gr.Markdown("An automated code review system powered by Gemma-2b")
    
    with gr.Tabs():
        with gr.Tab("Review Code"):
            with gr.Row():
                with gr.Column():
                    code_input = gr.Textbox(
                        lines=10,
                        placeholder="Enter your code here...",
                        label="Code"
                    )
                    language_input = gr.Dropdown(
                        choices=["python", "javascript", "java", "cpp", "typescript", "go", "rust"],
                        value="python",
                        label="Language"
                    )
                    submit_btn = gr.Button("Submit for Review")
                with gr.Column():
                    output = gr.Textbox(
                        label="Review Results",
                        lines=10
                    )
        
        with gr.Tab("History"):
            refresh_history = gr.Button("Refresh History")
            history_output = gr.Textbox(
                label="Review History",
                lines=20
            )
        
        with gr.Tab("Metrics"):
            refresh_metrics = gr.Button("Refresh Metrics")
            metrics_output = gr.JSON(
                label="Performance Metrics"
            )
    
    # Set up event handlers
    def review_code_interface(code: str, language: str) -> str:
        if not code.strip():
            return "Please enter some code to review."
        try:
            return reviewer.review_code(code, language)
        except Exception as e:
            logger.error(f"Interface error: {e}")
            return f"Error: {str(e)}"
    
    def get_history_interface() -> str:
        try:
            history = reviewer.get_history()
            if not history:
                return "No reviews yet."
            result = ""
            for review in history:
                result += f"Time: {review['timestamp']}\n"
                result += f"Language: {review['language']}\n"
                result += f"Response Time: {review['response_time']}\n"
                result += "Code:\n```\n" + review['code'] + "\n```\n"
                result += "Suggestions:\n" + review['suggestions'] + "\n"
                result += "-" * 80 + "\n\n"
            return result
        except Exception as e:
            logger.error(f"History error: {e}")
            return "Error retrieving history"
    
    def get_metrics_interface() -> Dict:
        try:
            return reviewer.get_metrics()
        except Exception as e:
            logger.error(f"Metrics error: {e}")
            return {"error": str(e)}
    
    submit_btn.click(
        review_code_interface,
        inputs=[code_input, language_input],
        outputs=output
    )
    refresh_history.click(
        get_history_interface,
        outputs=history_output
    )
    refresh_metrics.click(
        get_metrics_interface,
        outputs=metrics_output
    )
    
    # Add example inputs
    gr.Examples(
        examples=[
            ["""def add_numbers(a, b):
    return a + b""", "python"],
            ["""function calculateSum(numbers) {
    let sum = 0;
    for(let i = 0; i < numbers.length; i++) {
        sum += numbers[i];
    }
    return sum;
}""", "javascript"]
        ],
        inputs=[code_input, language_input]
    )

# Launch the app
if __name__ == "__main__":
    iface.launch(
        server_name="0.0.0.0",
        server_port=7860,
        show_error=True,
        quiet=False
    )