hari7261 commited on
Commit
5e2d96b
Β·
verified Β·
1 Parent(s): 713d1ab

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +318 -0
app.py ADDED
@@ -0,0 +1,318 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ from transformers import pipeline
4
+ import re
5
+ import time
6
+
7
+ # Initialize the model pipeline
8
+ model_id = "openai/gpt-oss-120b"
9
+ pipe = None
10
+
11
+ def initialize_model():
12
+ global pipe
13
+ try:
14
+ pipe = pipeline(
15
+ "text-generation",
16
+ model=model_id,
17
+ torch_dtype="auto",
18
+ device_map="auto",
19
+ )
20
+ return "βœ… Model loaded successfully!"
21
+ except Exception as e:
22
+ return f"❌ Error loading model: {str(e)}"
23
+
24
+ def generate_code(prompt, task_type, language, max_tokens, temperature):
25
+ if pipe is None:
26
+ return "❌ Model not initialized. Please load the model first.", ""
27
+
28
+ try:
29
+ # Customize prompt based on task type
30
+ if task_type == "Generate Code":
31
+ system_prompt = f"You are an expert {language} programmer. Generate clean, optimized, and well-commented code for the following request:"
32
+ full_prompt = f"{system_prompt}\n\n{prompt}\n\nCode:"
33
+ elif task_type == "Fix Bugs":
34
+ system_prompt = f"You are an expert {language} debugger. Analyze the following code and fix all bugs, then provide the corrected version:"
35
+ full_prompt = f"{system_prompt}\n\n{prompt}\n\nFixed Code:"
36
+ elif task_type == "Optimize Code":
37
+ system_prompt = f"You are an expert {language} optimizer. Analyze and optimize the following code for better performance and readability:"
38
+ full_prompt = f"{system_prompt}\n\n{prompt}\n\nOptimized Code:"
39
+ else: # Explain Code
40
+ system_prompt = f"You are an expert {language} teacher. Explain the following code step by step:"
41
+ full_prompt = f"{system_prompt}\n\n{prompt}\n\nExplanation:"
42
+
43
+ messages = [
44
+ {"role": "user", "content": full_prompt},
45
+ ]
46
+
47
+ outputs = pipe(
48
+ messages,
49
+ max_new_tokens=int(max_tokens),
50
+ temperature=temperature,
51
+ do_sample=True,
52
+ pad_token_id=pipe.tokenizer.eos_token_id
53
+ )
54
+
55
+ generated_text = outputs[0]["generated_text"][-1]["content"] if isinstance(outputs[0]["generated_text"], list) else outputs[0]["generated_text"]
56
+
57
+ # Extract code if it's wrapped in code blocks
58
+ code_match = re.search(r'```(?:\w+\n)?(.*?)```', generated_text, re.DOTALL)
59
+ if code_match:
60
+ code_output = code_match.group(1).strip()
61
+ else:
62
+ code_output = generated_text.strip()
63
+
64
+ # Generate explanation based on the output
65
+ explanation = f"Task completed successfully! Generated {len(code_output)} characters of {language} code."
66
+ if task_type == "Fix Bugs":
67
+ explanation = "Bugs have been identified and fixed. Please review the corrected code."
68
+ elif task_type == "Optimize Code":
69
+ explanation = "Code has been optimized for better performance and readability."
70
+ elif task_type == "Explain Code":
71
+ explanation = "Code explanation provided below."
72
+
73
+ return code_output, explanation
74
+
75
+ except Exception as e:
76
+ return f"❌ Error generating code: {str(e)}", "Please try again with different parameters."
77
+
78
+ # Custom CSS for modern UI
79
+ css = """
80
+ .gradio-container {
81
+ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
82
+ }
83
+
84
+ .header {
85
+ text-align: center;
86
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
87
+ color: white;
88
+ padding: 2rem;
89
+ border-radius: 15px;
90
+ margin-bottom: 2rem;
91
+ box-shadow: 0 10px 30px rgba(0,0,0,0.2);
92
+ }
93
+
94
+ .header h1 {
95
+ font-size: 2.5rem;
96
+ font-weight: 700;
97
+ margin: 0;
98
+ text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
99
+ }
100
+
101
+ .header p {
102
+ font-size: 1.2rem;
103
+ margin: 0.5rem 0 0 0;
104
+ opacity: 0.9;
105
+ }
106
+
107
+ .custom-button {
108
+ background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
109
+ border: none;
110
+ color: white;
111
+ font-weight: 600;
112
+ border-radius: 8px;
113
+ transition: all 0.3s ease;
114
+ }
115
+
116
+ .custom-button:hover {
117
+ transform: translateY(-2px);
118
+ box-shadow: 0 5px 15px rgba(79, 172, 254, 0.4);
119
+ }
120
+
121
+ .footer {
122
+ text-align: center;
123
+ margin-top: 3rem;
124
+ padding: 2rem;
125
+ background: linear-gradient(135deg, #2d3436 0%, #636e72 100%);
126
+ color: white;
127
+ border-radius: 15px;
128
+ box-shadow: 0 5px 15px rgba(0,0,0,0.1);
129
+ }
130
+
131
+ .footer h3 {
132
+ margin: 0 0 1rem 0;
133
+ font-size: 1.3rem;
134
+ }
135
+
136
+ .footer a {
137
+ color: #74b9ff;
138
+ text-decoration: none;
139
+ margin: 0 1rem;
140
+ font-weight: 500;
141
+ transition: color 0.3s ease;
142
+ }
143
+
144
+ .footer a:hover {
145
+ color: #0984e3;
146
+ }
147
+
148
+ .status-box {
149
+ padding: 1rem;
150
+ border-radius: 8px;
151
+ margin: 1rem 0;
152
+ font-weight: 500;
153
+ }
154
+
155
+ .code-output {
156
+ background: #1e1e1e;
157
+ border-radius: 8px;
158
+ border: 1px solid #333;
159
+ }
160
+
161
+ .explanation-output {
162
+ background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
163
+ border-radius: 8px;
164
+ padding: 1rem;
165
+ }
166
+ """
167
+
168
+ # Create the Gradio interface
169
+ with gr.Blocks(css=css, title="AI Code Generator & Bug Fixer", theme=gr.themes.Soft()) as demo:
170
+
171
+ # Header
172
+ gr.HTML("""
173
+ <div class="header">
174
+ <h1>πŸš€ AI Code Generator & Bug Fixer</h1>
175
+ <p>Powered by Advanced AI β€’ Generate, Fix, Optimize & Explain Code</p>
176
+ </div>
177
+ """)
178
+
179
+ # Model initialization section
180
+ with gr.Row():
181
+ with gr.Column(scale=3):
182
+ model_status = gr.Textbox(
183
+ label="πŸ€– Model Status",
184
+ value="Click 'Initialize Model' to load the AI model",
185
+ interactive=False
186
+ )
187
+ with gr.Column(scale=1):
188
+ init_btn = gr.Button(
189
+ "Initialize Model",
190
+ variant="primary",
191
+ elem_classes=["custom-button"]
192
+ )
193
+
194
+ gr.Markdown("---")
195
+
196
+ # Main interface
197
+ with gr.Row():
198
+ with gr.Column(scale=1):
199
+ gr.Markdown("### βš™οΈ Configuration")
200
+
201
+ task_type = gr.Dropdown(
202
+ choices=["Generate Code", "Fix Bugs", "Optimize Code", "Explain Code"],
203
+ value="Generate Code",
204
+ label="🎯 Task Type"
205
+ )
206
+
207
+ language = gr.Dropdown(
208
+ choices=["Python", "JavaScript", "Java", "C++", "C#", "Go", "Rust", "TypeScript", "PHP", "Ruby"],
209
+ value="Python",
210
+ label="πŸ’» Programming Language"
211
+ )
212
+
213
+ max_tokens = gr.Slider(
214
+ minimum=50,
215
+ maximum=1000,
216
+ value=256,
217
+ step=50,
218
+ label="πŸ“ Max Tokens"
219
+ )
220
+
221
+ temperature = gr.Slider(
222
+ minimum=0.1,
223
+ maximum=1.0,
224
+ value=0.7,
225
+ step=0.1,
226
+ label="🌑️ Temperature (Creativity)"
227
+ )
228
+
229
+ generate_btn = gr.Button(
230
+ "πŸš€ Generate/Fix Code",
231
+ variant="primary",
232
+ size="lg",
233
+ elem_classes=["custom-button"]
234
+ )
235
+
236
+ with gr.Column(scale=2):
237
+ gr.Markdown("### πŸ“ Input")
238
+
239
+ prompt = gr.Textbox(
240
+ label="Your Code Request or Buggy Code",
241
+ placeholder="Example: Create a function to sort a list of dictionaries by a specific key...",
242
+ lines=8
243
+ )
244
+
245
+ gr.Markdown("### πŸ’‘ Examples")
246
+ examples = gr.Examples(
247
+ examples=[
248
+ ["Generate Code", "Python", "Create a REST API with FastAPI for user management with CRUD operations"],
249
+ ["Fix Bugs", "JavaScript", "function calculateSum(arr) {\n let sum = 0;\n for (let i = 0; i <= arr.length; i++) {\n sum += arr[i];\n }\n return sum;\n}"],
250
+ ["Optimize Code", "Python", "def fibonacci(n):\n if n <= 1:\n return n\n return fibonacci(n-1) + fibonacci(n-2)"],
251
+ ["Explain Code", "Python", "class decorator(func):\n def wrapper(*args, **kwargs):\n print('Before')\n result = func(*args, **kwargs)\n print('After')\n return result\n return wrapper"]
252
+ ],
253
+ inputs=[task_type, language, prompt]
254
+ )
255
+
256
+ gr.Markdown("---")
257
+
258
+ # Output section
259
+ with gr.Row():
260
+ with gr.Column():
261
+ gr.Markdown("### πŸ“€ Generated Code")
262
+ code_output = gr.Code(
263
+ label="Result",
264
+ language="python",
265
+ elem_classes=["code-output"]
266
+ )
267
+
268
+ gr.Markdown("### πŸ’¬ AI Explanation")
269
+ explanation_output = gr.Textbox(
270
+ label="Analysis & Explanation",
271
+ lines=3,
272
+ elem_classes=["explanation-output"]
273
+ )
274
+
275
+ # Footer
276
+ gr.HTML("""
277
+ <div class="footer">
278
+ <h3>πŸ› οΈ Built by Hariom Kumar Pandit</h3>
279
+ <p>
280
+ <a href="https://github.com/hari7261" target="_blank">πŸ™ GitHub: hari7261</a>
281
+ <a href="https://huggingface.co/hari7261" target="_blank">πŸ€— HuggingFace: hari7261</a>
282
+ </p>
283
+ <p style="margin-top: 1rem; font-size: 0.9rem; opacity: 0.8;">
284
+ Empowering developers with AI-assisted coding β€’ Made with ❀️
285
+ </p>
286
+ </div>
287
+ """)
288
+
289
+ # Event handlers
290
+ init_btn.click(
291
+ fn=initialize_model,
292
+ outputs=model_status
293
+ )
294
+
295
+ generate_btn.click(
296
+ fn=generate_code,
297
+ inputs=[prompt, task_type, language, max_tokens, temperature],
298
+ outputs=[code_output, explanation_output]
299
+ )
300
+
301
+ # Update code language based on selection
302
+ def update_code_language(lang):
303
+ return gr.Code(language=lang.lower())
304
+
305
+ language.change(
306
+ fn=update_code_language,
307
+ inputs=language,
308
+ outputs=code_output
309
+ )
310
+
311
+ # Launch the app
312
+ if __name__ == "__main__":
313
+ demo.launch(
314
+ server_name="0.0.0.0",
315
+ server_port=7860,
316
+ share=True,
317
+ debug=True
318
+ )