S-Dreamer commited on
Commit
a90a47c
·
verified ·
1 Parent(s): b637fc4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -431
app.py CHANGED
@@ -1,8 +1,30 @@
 
 
 
1
  import gradio as gr
2
  import requests
3
  import os
4
  from typing import Dict, Tuple
5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  # Constants
7
  DEFAULTS = {
8
  "SYSTEM_MESSAGE": "You are CodePal.ai, an expert AI assistant specialized in helping programmers. You generate clean, efficient, and well-documented code based on user requirements.",
@@ -17,6 +39,19 @@ API_URLS = {
17
  "CODE_EXTENDER": "https://api.codepal.ai/v1/code-extender/query",
18
  }
19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  def get_api_key() -> str:
21
  """Fetch API key from environment variables."""
22
  return os.environ.get("CODEPAL_API_KEY", "")
@@ -54,449 +89,37 @@ def handle_api_response(response) -> Tuple[bool, str]:
54
 
55
  return True, result["result"]
56
 
57
- def generate_code(language: str, requirements: str, code_style: str, include_tests: bool,
58
- max_tokens: int = DEFAULTS["MAX_TOKENS"],
59
- temperature: float = DEFAULTS["TEMPERATURE"],
60
  top_p: float = DEFAULTS["TOP_P"]) -> Tuple[bool, str]:
61
  """Generate code using CodePal.ai API."""
62
- if not is_api_key_valid():
63
- return False, "Error: CodePal.ai API key is not configured. Please set the CODEPAL_API_KEY environment variable."
64
-
65
- flavor = {
66
- "minimal": "minimal",
67
- "verbose": "documented"
68
- }.get(code_style, "standard") if code_style in ["minimal", "verbose"] else "tests" if include_tests else "standard"
69
-
70
- api_key = get_api_key()
71
- headers = {
72
- "Authorization": f"Bearer {api_key}",
73
- "Content-Type": "application/json"
74
- }
75
-
76
- data = build_request_data(language, requirements, flavor, max_tokens, temperature, top_p)
77
-
78
  try:
79
- response = requests.post(API_URLS["CODE_GENERATOR"], headers=headers, json=data)
80
- return handle_api_response(response)
81
- except Exception as e:
82
- return False, f"Error: {str(e)}"
83
-
84
- def fix_code(code: str, instructions: str, language: str = "",
85
- max_tokens: int = DEFAULTS["MAX_TOKENS"],
86
- temperature: float = DEFAULTS["TEMPERATURE"],
87
- top_p: float = DEFAULTS["TOP_P"]) -> Tuple[bool, str]:
88
- """Fix existing code using CodePal.ai API."""
89
- if not is_api_key_valid():
90
- return False, "Error: CodePal.ai API key is not configured. Please set the CODEPAL_API_KEY environment variable."
91
-
92
- api_key = get_api_key()
93
- headers = {
94
- "Authorization": f"Bearer {api_key}",
95
- "Content-Type": "application/json"
96
- }
97
-
98
- data = build_request_data(language, instructions, "", max_tokens, temperature, top_p)
99
- if language and language != "auto-detect":
100
- data["language"] = language
101
 
102
- try:
103
- response = requests.post(API_URLS["CODE_FIXER"], headers=headers, json=data)
104
- return handle_api_response(response)
105
- except Exception as e:
106
- return False, f"Error: {str(e)}"
107
 
108
- def extend_code(code: str, instructions: str, language: str = "",
109
- max_tokens: int = DEFAULTS["MAX_TOKENS"],
110
- temperature: float = DEFAULTS["TEMPERATURE"],
111
- top_p: float = DEFAULTS["TOP_P"]) -> Tuple[bool, str]:
112
- """Extend existing code using CodePal.ai API."""
113
- if not is_api_key_valid():
114
- return False, "Error: CodePal.ai API key is not configured. Please set the CODEPAL_API_KEY environment variable."
115
-
116
- api_key = get_api_key()
117
- headers = {
118
- "Authorization": f"Bearer {api_key}",
119
- "Content-Type": "application/json"
120
- }
121
-
122
- data = build_request_data(language, instructions, "", max_tokens, temperature, top_p)
123
- if language and language != "auto-detect":
124
- data["language"] = language
125
 
126
- try:
127
- response = requests.post(API_URLS["CODE_EXTENDER"], headers=headers, json=data)
128
  return handle_api_response(response)
129
  except Exception as e:
 
130
  return False, f"Error: {str(e)}"
131
 
132
- def save_to_file(code: str, language: str, file_name: str = "generated_code") -> str:
133
- """Save the generated code to a file with appropriate extension."""
134
- extensions = {
135
- "python": ".py", "javascript": ".js", "typescript": ".ts", "java": ".java",
136
- "c": ".c", "cpp": ".cpp", "csharp": ".cs", "go": ".go", "rust": ".rs",
137
- "php": ".php", "ruby": ".rb", "swift": ".swift", "kotlin": ".kt",
138
- "html": ".html", "css": ".css", "sql": ".sql", "shell": ".sh",
139
- }
140
-
141
- extension = extensions.get(language.lower(), ".txt")
142
- full_file_name = f"{file_name}{extension}"
143
-
144
- try:
145
- with open(full_file_name, "w") as f:
146
- f.write(code)
147
- return f"Code successfully saved to {full_file_name}"
148
- except Exception as e:
149
- return f"Error saving code to file: {str(e)}"
150
-
151
- def ui_generate_code(language: str, generation_type: str, requirements: str, code_style: str,
152
- dependencies: str, include_tests: bool,
153
- max_tokens: int = DEFAULTS["MAX_TOKENS"],
154
- temperature: float = DEFAULTS["TEMPERATURE"],
155
- top_p: float = DEFAULTS["TOP_P"],
156
- save_file: bool = False) -> str:
157
- """UI handler for code generation."""
158
- combined_requirements = f"{generation_type}: {requirements}"
159
- if dependencies:
160
- combined_requirements += f"\nDependencies: {dependencies}"
161
-
162
- success, result = generate_code(language, combined_requirements, code_style, include_tests,
163
- max_tokens, temperature, top_p)
164
-
165
- if not success:
166
- return result
167
-
168
- if save_file:
169
- file_message = save_to_file(result, language)
170
- result = f"{result}\n\n{file_message}"
171
-
172
- return result
173
-
174
- def ui_fix_code(code: str, instructions: str, language: str,
175
- max_tokens: int = DEFAULTS["MAX_TOKENS"],
176
- temperature: float = DEFAULTS["TEMPERATURE"],
177
- top_p: float = DEFAULTS["TOP_P"],
178
- save_file: bool = False) -> str:
179
- """UI handler for code fixing."""
180
- success, result = fix_code(code, instructions, language, max_tokens, temperature, top_p)
181
-
182
- if not success:
183
- return result
184
-
185
- if save_file:
186
- file_message = save_to_file(result, language, "fixed_code")
187
- result = f"{result}\n\n{file_message}"
188
-
189
- return result
190
-
191
- def ui_extend_code(code: str, instructions: str, language: str,
192
- max_tokens: int = DEFAULTS["MAX_TOKENS"],
193
- temperature: float = DEFAULTS["TEMPERATURE"],
194
- top_p: float = DEFAULTS["TOP_P"],
195
- save_file: bool = False) -> str:
196
- """UI handler for code extension."""
197
- success, result = extend_code(code, instructions, language, max_tokens, temperature, top_p)
198
-
199
- if not success:
200
- return result
201
-
202
- if save_file:
203
- file_message = save_to_file(result, language, "extended_code")
204
- result = f"{result}\n\n{file_message}"
205
-
206
- return result
207
-
208
- # Create Gradio Interface with tabs for different functionality
209
- with gr.Blocks(title="CodePal.ai Interface") as app:
210
- gr.Markdown(
211
- """
212
- # CodePal.ai Code Generator
213
-
214
- A custom interface for the CodePal.ai API providing code generation, fixing, and extension capabilities.
215
-
216
- **Note**: You need to set the `CODEPAL_API_KEY` environment variable with your CodePal.ai API key.
217
- """
218
- )
219
-
220
- api_key_status = gr.Markdown(
221
- "⚠️ **API Key Status**: Checking..." if is_api_key_valid() else "❌ **API Key Status**: Missing. Please set the CODEPAL_API_KEY environment variable."
222
- )
223
-
224
- with gr.Tabs():
225
- # Generate Code Tab
226
- with gr.TabItem("Generate Code"):
227
- with gr.Row():
228
- with gr.Column(scale=1):
229
- language = gr.Dropdown(
230
- choices=["javascript", "typescript", "python", "react", "vue", "node", "php", "java", "csharp", "html", "css", "ruby", "go", "rust", "swift"],
231
- value="javascript",
232
- label="Language/Framework"
233
- )
234
-
235
- generation_type = gr.Radio(
236
- choices=["component", "function", "api", "algorithm", "style", "other"],
237
- value="function",
238
- label="Generation Type"
239
- )
240
-
241
- requirements = gr.Textbox(
242
- lines=5,
243
- placeholder="Describe what you need in detail. Example: Create a function that sorts an array of objects by a specific property.",
244
- label="Requirements",
245
- info="Be as specific as possible for better results."
246
- )
247
-
248
- with gr.Accordion("Advanced Options", open=False):
249
- code_style = gr.Dropdown(
250
- choices=["standard", "functional", "oop", "minimal", "verbose"],
251
- value="standard",
252
- label="Code Style"
253
- )
254
-
255
- dependencies = gr.Textbox(
256
- lines=2,
257
- placeholder="E.g., react-router-dom, lodash, axios",
258
- label="Dependencies (optional)",
259
- info="List any packages or libraries you want to use."
260
- )
261
-
262
- include_tests = gr.Checkbox(
263
- label="Include unit tests",
264
- value=False
265
- )
266
-
267
- with gr.Group():
268
- gr.Markdown("### Model Settings")
269
- max_tokens = gr.Slider(
270
- minimum=1000,
271
- maximum=8000,
272
- step=100,
273
- value=DEFAULTS["MAX_TOKENS"],
274
- label="Max Tokens",
275
- info="Maximum number of tokens (words) in the generated response"
276
- )
277
-
278
- temperature = gr.Slider(
279
- minimum=0.1,
280
- maximum=1.0,
281
- step=0.05,
282
- value=DEFAULTS["TEMPERATURE"],
283
- label="Temperature",
284
- info="Higher values make output more random, lower values make it more deterministic"
285
- )
286
-
287
- top_p = gr.Slider(
288
- minimum=0.5,
289
- maximum=1.0,
290
- step=0.05,
291
- value=DEFAULTS["TOP_P"],
292
- label="Top P",
293
- info="Controls diversity via nucleus sampling"
294
- )
295
-
296
- save_gen_file = gr.Checkbox(
297
- label="Save generated code to file",
298
- value=False,
299
- info="Automatically save the generated code to a file with appropriate extension"
300
- )
301
-
302
- generate_btn = gr.Button("Generate Code", variant="primary")
303
-
304
- with gr.Column(scale=1):
305
- output_code = gr.Code(
306
- label="Generated Code",
307
- language="javascript",
308
- interactive=False,
309
- lines=20
310
- )
311
-
312
- generate_btn.click(
313
- fn=ui_generate_code,
314
- inputs=[language, generation_type, requirements, code_style, dependencies, include_tests,
315
- max_tokens, temperature, top_p],
316
- outputs=[output_code]
317
- )
318
-
319
- language.change(
320
- fn=lambda lang: gr.update(language=lang.lower()),
321
- inputs=[language],
322
- outputs=[output_code]
323
- )
324
-
325
- # Fix Code Tab
326
- with gr.TabItem("Fix Code"):
327
- with gr.Row():
328
- with gr.Column(scale=1):
329
- fix_language = gr.Dropdown(
330
- choices=["auto-detect", "javascript", "typescript", "python", "react", "vue", "node", "php", "java", "csharp", "html", "css", "ruby", "go", "rust", "swift"],
331
- value="auto-detect",
332
- label="Language (optional)"
333
- )
334
-
335
- original_code = gr.Code(
336
- label="Code to Fix",
337
- language="javascript",
338
- lines=10
339
- )
340
-
341
- fix_instructions = gr.Textbox(
342
- lines=3,
343
- placeholder="Describe what's wrong or what needs to be fixed.",
344
- label="Fix Instructions",
345
- info="Be specific about the issues or errors you want resolved."
346
- )
347
-
348
- with gr.Accordion("Advanced Model Settings", open=False):
349
- fix_max_tokens = gr.Slider(
350
- minimum=1000,
351
- maximum=8000,
352
- step=100,
353
- value=DEFAULTS["MAX_TOKENS"],
354
- label="Max Tokens",
355
- info="Maximum number of tokens (words) in the generated response"
356
- )
357
-
358
- fix_temperature = gr.Slider(
359
- minimum=0.1,
360
- maximum=1.0,
361
- step=0.05,
362
- value=DEFAULTS["TEMPERATURE"],
363
- label="Temperature",
364
- info="Higher values make output more random, lower values make it more deterministic"
365
- )
366
-
367
- fix_top_p = gr.Slider(
368
- minimum=0.5,
369
- maximum=1.0,
370
- step=0.05,
371
- value=DEFAULTS["TOP_P"],
372
- label="Top P",
373
- info="Controls diversity via nucleus sampling"
374
- )
375
-
376
- save_fix_file = gr.Checkbox(
377
- label="Save fixed code to file",
378
- value=False,
379
- info="Automatically save the fixed code to a file with appropriate extension"
380
- )
381
-
382
- fix_btn = gr.Button("Fix Code", variant="primary")
383
-
384
- with gr.Column(scale=1):
385
- fixed_code = gr.Code(
386
- label="Fixed Code",
387
- language="javascript",
388
- interactive=False,
389
- lines=20
390
- )
391
-
392
- fix_btn.click(
393
- fn=ui_fix_code,
394
- inputs=[original_code, fix_instructions, fix_language,
395
- fix_max_tokens, fix_temperature, fix_top_p],
396
- outputs=[fixed_code]
397
- )
398
-
399
- fix_language.change(
400
- fn=lambda lang: gr.update(language=lang.lower() if lang != "auto-detect" else "javascript"),
401
- inputs=[fix_language],
402
- outputs=[fixed_code]
403
- )
404
-
405
- # Extend Code Tab
406
- with gr.TabItem("Extend Code"):
407
- with gr.Row():
408
- with gr.Column(scale=1):
409
- extend_language = gr.Dropdown(
410
- choices=["auto-detect", "javascript", "typescript", "python", "react", "vue", "node", "php", "java", "csharp", "html", "css", "ruby", "go", "rust", "swift"],
411
- value="auto-detect",
412
- label="Language (optional)"
413
- )
414
-
415
- base_code = gr.Code(
416
- label="Base Code",
417
- language="javascript",
418
- lines=10
419
- )
420
-
421
- extend_instructions = gr.Textbox(
422
- lines=3,
423
- placeholder="Describe how you want to extend the code.",
424
- label="Extension Instructions",
425
- info="Be specific about what new functionality or features you want to add."
426
- )
427
-
428
- with gr.Accordion("Advanced Model Settings", open=False):
429
- extend_max_tokens = gr.Slider(
430
- minimum=1000,
431
- maximum=8000,
432
- step=100,
433
- value=DEFAULTS["MAX_TOKENS"],
434
- label="Max Tokens",
435
- info="Maximum number of tokens (words) in the generated response"
436
- )
437
-
438
- extend_temperature = gr.Slider(
439
- minimum=0.1,
440
- maximum=1.0,
441
- step=0.05,
442
- value=DEFAULTS["TEMPERATURE"],
443
- label="Temperature",
444
- info="Higher values make output more random, lower values make it more deterministic"
445
- )
446
-
447
- extend_top_p = gr.Slider(
448
- minimum=0.5,
449
- maximum=1.0,
450
- step=0.05,
451
- value=DEFAULTS["TOP_P"],
452
- label="Top P",
453
- info="Controls diversity via nucleus sampling"
454
- )
455
-
456
- extend_btn = gr.Button("Extend Code", variant="primary")
457
-
458
- with gr.Column(scale=1):
459
- extended_code = gr.Code(
460
- label="Extended Code",
461
- language="javascript",
462
- interactive=False,
463
- lines=20
464
- )
465
-
466
- extend_btn.click(
467
- fn=ui_extend_code,
468
- inputs=[base_code, extend_instructions, extend_language,
469
- extend_max_tokens, extend_temperature, extend_top_p],
470
- outputs=[extended_code]
471
- )
472
-
473
- extend_language.change(
474
- fn=lambda lang: gr.update(language=lang.lower() if lang != "auto-detect" else "javascript"),
475
- inputs=[extend_language],
476
- outputs=[extended_code]
477
- )
478
-
479
- # Launch the app
480
  if __name__ == "__main__":
481
- import sys
482
- port = int(os.environ.get("GRADIO_SERVER_PORT", 5000))
483
- alt_port = 6000
484
-
485
  try:
486
- app.launch(
487
- server_name="0.0.0.0",
488
- server_port=port,
489
- share=True,
490
- debug=True
491
- )
492
- except OSError:
493
- print(f"Port {port} is in use, trying port {alt_port} instead...")
494
- app.launch(
495
- server_name="0.0.0.0",
496
- server_port=alt_port,
497
- share=True,
498
- debug=True
499
- )
500
  except Exception as e:
501
  print(f"Error starting the Gradio application: {str(e)}")
502
  sys.exit(1)
 
1
+ import sys
2
+ import subprocess
3
+ import logging
4
  import gradio as gr
5
  import requests
6
  import os
7
  from typing import Dict, Tuple
8
 
9
+ logging.basicConfig(level=logging.INFO)
10
+ logger = logging.getLogger(__name__)
11
+
12
+ def install(package):
13
+ subprocess.check_call([sys.executable, "-m", "pip", "install", package])
14
+
15
+ required_packages = ['gradio', 'requests']
16
+ for package in required_packages:
17
+ try:
18
+ __import__(package)
19
+ except ImportError:
20
+ print(f"{package} not found. Installing...")
21
+ install(package)
22
+
23
+ if not os.environ.get("CODEPAL_API_KEY"):
24
+ print("Error: CODEPAL_API_KEY environment variable is not set.")
25
+ print("Please set it and try again.")
26
+ sys.exit(1)
27
+
28
  # Constants
29
  DEFAULTS = {
30
  "SYSTEM_MESSAGE": "You are CodePal.ai, an expert AI assistant specialized in helping programmers. You generate clean, efficient, and well-documented code based on user requirements.",
 
39
  "CODE_EXTENDER": "https://api.codepal.ai/v1/code-extender/query",
40
  }
41
 
42
+ def check_api_endpoints():
43
+ for name, url in API_URLS.items():
44
+ try:
45
+ response = requests.head(url)
46
+ if response.status_code == 200:
47
+ print(f"{name} API endpoint is accessible.")
48
+ else:
49
+ print(f"Warning: {name} API endpoint returned status code {response.status_code}")
50
+ except requests.RequestException as e:
51
+ print(f"Error accessing {name} API endpoint: {str(e)}")
52
+
53
+ check_api_endpoints()
54
+
55
  def get_api_key() -> str:
56
  """Fetch API key from environment variables."""
57
  return os.environ.get("CODEPAL_API_KEY", "")
 
89
 
90
  return True, result["result"]
91
 
92
+ def generate_code(language: str, requirements: str, code_style: str, include_tests: bool,
93
+ max_tokens: int = DEFAULTS["MAX_TOKENS"],
94
+ temperature: float = DEFAULTS["TEMPERATURE"],
95
  top_p: float = DEFAULTS["TOP_P"]) -> Tuple[bool, str]:
96
  """Generate code using CodePal.ai API."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
  try:
98
+ if not is_api_key_valid():
99
+ return False, "Error: CodePal.ai API key is not configured. Please set the CODEPAL_API_KEY environment variable."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
100
 
101
+ flavor = {
102
+ "minimal": "minimal",
103
+ "verbose": "documented"
104
+ }.get(code_style, "standard") if code_style in ["minimal", "verbose"] else "tests" if include_tests else "standard"
 
105
 
106
+ api_key = get_api_key()
107
+ headers = {
108
+ "Authorization": f"Bearer {api_key}",
109
+ "Content-Type": "application/json"
110
+ }
 
 
 
 
 
 
 
 
 
 
 
 
111
 
112
+ data = build_request_data(language, requirements, flavor, max_tokens, temperature, top_p)
113
+ response = requests.post(API_URLS["CODE_GENERATOR"], headers=headers, json=data)
114
  return handle_api_response(response)
115
  except Exception as e:
116
+ logger.error(f"Error in generate_code: {str(e)}")
117
  return False, f"Error: {str(e)}"
118
 
119
+ # Launch the app (if applicable)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
  if __name__ == "__main__":
 
 
 
 
121
  try:
122
+ app.launch(share=True) # Modify based on your application's entry point
 
 
 
 
 
 
 
 
 
 
 
 
 
123
  except Exception as e:
124
  print(f"Error starting the Gradio application: {str(e)}")
125
  sys.exit(1)