hari7261 commited on
Commit
35ef561
Β·
verified Β·
1 Parent(s): 2826185

Update app.py

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