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|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import boto3
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
from typing import Optional, Tuple
|
| 6 |
+
import nbformat
|
| 7 |
+
from io import StringIO
|
| 8 |
+
import sys
|
| 9 |
+
|
| 10 |
+
class CodingCopilot:
|
| 11 |
+
def __init__(self):
|
| 12 |
+
"""Initialize the coding copilot with AWS Bedrock client."""
|
| 13 |
+
self.setup_aws_client()
|
| 14 |
+
|
| 15 |
+
def setup_aws_client(self):
|
| 16 |
+
"""Setup AWS Bedrock client with credentials from environment variables."""
|
| 17 |
+
try:
|
| 18 |
+
self.bedrock_client = boto3.client(
|
| 19 |
+
'bedrock-runtime',
|
| 20 |
+
aws_access_key_id=os.getenv('AWS_ACCESS_KEY_ID'),
|
| 21 |
+
aws_secret_access_key=os.getenv('AWS_SECRET_ACCESS_KEY'),
|
| 22 |
+
region_name='us-east-1' # Claude is available in us-east-1
|
| 23 |
+
)
|
| 24 |
+
except Exception as e:
|
| 25 |
+
print(f"Error setting up AWS client: {e}")
|
| 26 |
+
self.bedrock_client = None
|
| 27 |
+
|
| 28 |
+
def call_claude(self, prompt: str, max_tokens: int = 4000) -> str:
|
| 29 |
+
"""Call Claude 3 Haiku via AWS Bedrock."""
|
| 30 |
+
if not self.bedrock_client:
|
| 31 |
+
return "Error: AWS Bedrock client not initialized. Please check your credentials."
|
| 32 |
+
|
| 33 |
+
try:
|
| 34 |
+
# Prepare the request payload for Claude
|
| 35 |
+
body = {
|
| 36 |
+
"anthropic_version": "bedrock-2023-05-31",
|
| 37 |
+
"max_tokens": max_tokens,
|
| 38 |
+
"messages": [
|
| 39 |
+
{
|
| 40 |
+
"role": "user",
|
| 41 |
+
"content": prompt
|
| 42 |
+
}
|
| 43 |
+
],
|
| 44 |
+
"temperature": 0.1,
|
| 45 |
+
"top_p": 0.9,
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
response = self.bedrock_client.invoke_model(
|
| 49 |
+
modelId="anthropic.claude-3-haiku-20240307-v1:0",
|
| 50 |
+
contentType='application/json',
|
| 51 |
+
accept='application/json',
|
| 52 |
+
body=json.dumps(body)
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
response_body = json.loads(response['body'].read())
|
| 56 |
+
return response_body['content'][0]['text']
|
| 57 |
+
|
| 58 |
+
except Exception as e:
|
| 59 |
+
return f"Error calling Claude: {str(e)}"
|
| 60 |
+
|
| 61 |
+
def read_python_file(self, file_path: str) -> str:
|
| 62 |
+
"""Read content from a Python file."""
|
| 63 |
+
try:
|
| 64 |
+
with open(file_path, 'r', encoding='utf-8') as f:
|
| 65 |
+
return f.read()
|
| 66 |
+
except Exception as e:
|
| 67 |
+
return f"Error reading file: {str(e)}"
|
| 68 |
+
|
| 69 |
+
def read_notebook_file(self, file_path: str) -> str:
|
| 70 |
+
"""Read and extract code from a Jupyter notebook file."""
|
| 71 |
+
try:
|
| 72 |
+
with open(file_path, 'r', encoding='utf-8') as f:
|
| 73 |
+
nb = nbformat.read(f, as_version=4)
|
| 74 |
+
|
| 75 |
+
code_cells = []
|
| 76 |
+
for cell in nb.cells:
|
| 77 |
+
if cell.cell_type == 'code':
|
| 78 |
+
code_cells.append(f"# Cell {len(code_cells) + 1}")
|
| 79 |
+
code_cells.append(cell.source)
|
| 80 |
+
code_cells.append("") # Add empty line between cells
|
| 81 |
+
|
| 82 |
+
return '\n'.join(code_cells)
|
| 83 |
+
except Exception as e:
|
| 84 |
+
return f"Error reading notebook: {str(e)}"
|
| 85 |
+
|
| 86 |
+
def analyze_code(self, code_content: str, analysis_type: str) -> str:
|
| 87 |
+
"""Analyze code using Claude."""
|
| 88 |
+
prompts = {
|
| 89 |
+
"review": f"""Please review this code and provide:
|
| 90 |
+
1. Code quality assessment
|
| 91 |
+
2. Potential bugs or issues
|
| 92 |
+
3. Performance improvements
|
| 93 |
+
4. Best practices suggestions
|
| 94 |
+
5. Security considerations
|
| 95 |
+
|
| 96 |
+
Code:
|
| 97 |
+
```python
|
| 98 |
+
{code_content}
|
| 99 |
+
```""",
|
| 100 |
+
|
| 101 |
+
"explain": f"""Please explain this code in detail:
|
| 102 |
+
1. What does this code do?
|
| 103 |
+
2. How does it work?
|
| 104 |
+
3. Key functions and their purposes
|
| 105 |
+
4. Dependencies and requirements
|
| 106 |
+
5. Usage examples
|
| 107 |
+
|
| 108 |
+
Code:
|
| 109 |
+
```python
|
| 110 |
+
{code_content}
|
| 111 |
+
```""",
|
| 112 |
+
|
| 113 |
+
"optimize": f"""Please optimize this code:
|
| 114 |
+
1. Suggest performance improvements
|
| 115 |
+
2. Refactor for better readability
|
| 116 |
+
3. Reduce complexity where possible
|
| 117 |
+
4. Improve memory usage
|
| 118 |
+
5. Provide the optimized version
|
| 119 |
+
|
| 120 |
+
Code:
|
| 121 |
+
```python
|
| 122 |
+
{code_content}
|
| 123 |
+
```""",
|
| 124 |
+
|
| 125 |
+
"debug": f"""Please help debug this code:
|
| 126 |
+
1. Identify potential bugs
|
| 127 |
+
2. Suggest fixes
|
| 128 |
+
3. Add error handling
|
| 129 |
+
4. Improve robustness
|
| 130 |
+
5. Provide corrected version
|
| 131 |
+
|
| 132 |
+
Code:
|
| 133 |
+
```python
|
| 134 |
+
{code_content}
|
| 135 |
+
```""",
|
| 136 |
+
|
| 137 |
+
"document": f"""Please add comprehensive documentation to this code:
|
| 138 |
+
1. Add docstrings to functions/classes
|
| 139 |
+
2. Add inline comments
|
| 140 |
+
3. Create usage examples
|
| 141 |
+
4. Document parameters and return values
|
| 142 |
+
5. Add type hints where appropriate
|
| 143 |
+
|
| 144 |
+
Code:
|
| 145 |
+
```python
|
| 146 |
+
{code_content}
|
| 147 |
+
```"""
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
prompt = prompts.get(analysis_type, prompts["review"])
|
| 151 |
+
return self.call_claude(prompt)
|
| 152 |
+
|
| 153 |
+
def generate_code(self, description: str, language: str = "python") -> str:
|
| 154 |
+
"""Generate code based on description."""
|
| 155 |
+
prompt = f"""Please generate {language} code based on this description:
|
| 156 |
+
|
| 157 |
+
{description}
|
| 158 |
+
|
| 159 |
+
Requirements:
|
| 160 |
+
1. Write clean, well-documented code
|
| 161 |
+
2. Include error handling
|
| 162 |
+
3. Add type hints where appropriate
|
| 163 |
+
4. Provide usage examples
|
| 164 |
+
5. Follow best practices
|
| 165 |
+
|
| 166 |
+
Please provide only the code with comments."""
|
| 167 |
+
|
| 168 |
+
return self.call_claude(prompt)
|
| 169 |
+
|
| 170 |
+
def chat_with_code(self, code_content: str, question: str) -> str:
|
| 171 |
+
"""Chat about specific code."""
|
| 172 |
+
prompt = f"""Given this code:
|
| 173 |
+
|
| 174 |
+
```python
|
| 175 |
+
{code_content}
|
| 176 |
+
```
|
| 177 |
+
|
| 178 |
+
Question: {question}
|
| 179 |
+
|
| 180 |
+
Please provide a detailed answer about the code."""
|
| 181 |
+
|
| 182 |
+
return self.call_claude(prompt)
|
| 183 |
+
|
| 184 |
+
# Initialize the copilot
|
| 185 |
+
copilot = CodingCopilot()
|
| 186 |
+
|
| 187 |
+
def process_file_upload(file) -> Tuple[str, str]:
|
| 188 |
+
"""Process uploaded file and return content."""
|
| 189 |
+
if file is None:
|
| 190 |
+
return "", "No file uploaded"
|
| 191 |
+
|
| 192 |
+
file_path = file.name
|
| 193 |
+
file_extension = os.path.splitext(file_path)[1].lower()
|
| 194 |
+
|
| 195 |
+
if file_extension == '.py':
|
| 196 |
+
content = copilot.read_python_file(file_path)
|
| 197 |
+
elif file_extension == '.ipynb':
|
| 198 |
+
content = copilot.read_notebook_file(file_path)
|
| 199 |
+
else:
|
| 200 |
+
return "", f"Unsupported file type: {file_extension}. Please upload .py or .ipynb files."
|
| 201 |
+
|
| 202 |
+
return content, f"Successfully loaded {file_extension} file"
|
| 203 |
+
|
| 204 |
+
def analyze_uploaded_code(file, analysis_type):
|
| 205 |
+
"""Analyze uploaded code file."""
|
| 206 |
+
if file is None:
|
| 207 |
+
return "Please upload a file first."
|
| 208 |
+
|
| 209 |
+
content, status = process_file_upload(file)
|
| 210 |
+
if not content or content.startswith("Error"):
|
| 211 |
+
return status or content
|
| 212 |
+
|
| 213 |
+
return copilot.analyze_code(content, analysis_type)
|
| 214 |
+
|
| 215 |
+
def generate_new_code(description, language):
|
| 216 |
+
"""Generate new code based on description."""
|
| 217 |
+
if not description.strip():
|
| 218 |
+
return "Please provide a description of what you want to generate."
|
| 219 |
+
|
| 220 |
+
return copilot.generate_code(description, language)
|
| 221 |
+
|
| 222 |
+
def chat_about_code(file, question):
|
| 223 |
+
"""Chat about uploaded code."""
|
| 224 |
+
if file is None:
|
| 225 |
+
return "Please upload a file first."
|
| 226 |
+
|
| 227 |
+
if not question.strip():
|
| 228 |
+
return "Please ask a question about the code."
|
| 229 |
+
|
| 230 |
+
content, status = process_file_upload(file)
|
| 231 |
+
if not content or content.startswith("Error"):
|
| 232 |
+
return status or content
|
| 233 |
+
|
| 234 |
+
return copilot.chat_with_code(content, question)
|
| 235 |
+
|
| 236 |
+
# Create Gradio interface
|
| 237 |
+
with gr.Blocks(title="Coding Copilot", theme=gr.themes.Soft()) as app:
|
| 238 |
+
gr.Markdown("# 🤖 Coding Copilot")
|
| 239 |
+
gr.Markdown("Upload your Python files (.py) or Jupyter notebooks (.ipynb) for analysis, or generate new code!")
|
| 240 |
+
|
| 241 |
+
with gr.Tabs():
|
| 242 |
+
# File Analysis Tab
|
| 243 |
+
with gr.TabItem("📁 Analyze Code"):
|
| 244 |
+
with gr.Row():
|
| 245 |
+
with gr.Column():
|
| 246 |
+
file_input = gr.File(
|
| 247 |
+
label="Upload Python File (.py) or Jupyter Notebook (.ipynb)",
|
| 248 |
+
file_types=[".py", ".ipynb"]
|
| 249 |
+
)
|
| 250 |
+
analysis_type = gr.Dropdown(
|
| 251 |
+
choices=["review", "explain", "optimize", "debug", "document"],
|
| 252 |
+
value="review",
|
| 253 |
+
label="Analysis Type"
|
| 254 |
+
)
|
| 255 |
+
analyze_btn = gr.Button("Analyze Code", variant="primary")
|
| 256 |
+
|
| 257 |
+
with gr.Column():
|
| 258 |
+
analysis_output = gr.Textbox(
|
| 259 |
+
label="Analysis Result",
|
| 260 |
+
lines=20,
|
| 261 |
+
max_lines=30
|
| 262 |
+
)
|
| 263 |
+
|
| 264 |
+
analyze_btn.click(
|
| 265 |
+
analyze_uploaded_code,
|
| 266 |
+
inputs=[file_input, analysis_type],
|
| 267 |
+
outputs=analysis_output
|
| 268 |
+
)
|
| 269 |
+
|
| 270 |
+
# Code Generation Tab
|
| 271 |
+
with gr.TabItem("⚡ Generate Code"):
|
| 272 |
+
with gr.Row():
|
| 273 |
+
with gr.Column():
|
| 274 |
+
code_description = gr.Textbox(
|
| 275 |
+
label="Describe what you want to code",
|
| 276 |
+
lines=5,
|
| 277 |
+
placeholder="E.g., Create a function to sort a list of dictionaries by a specific key..."
|
| 278 |
+
)
|
| 279 |
+
code_language = gr.Dropdown(
|
| 280 |
+
choices=["python", "javascript", "java", "cpp", "c"],
|
| 281 |
+
value="python",
|
| 282 |
+
label="Programming Language"
|
| 283 |
+
)
|
| 284 |
+
generate_btn = gr.Button("Generate Code", variant="primary")
|
| 285 |
+
|
| 286 |
+
with gr.Column():
|
| 287 |
+
generated_code = gr.Code(
|
| 288 |
+
label="Generated Code",
|
| 289 |
+
language="python",
|
| 290 |
+
lines=20
|
| 291 |
+
)
|
| 292 |
+
|
| 293 |
+
generate_btn.click(
|
| 294 |
+
generate_new_code,
|
| 295 |
+
inputs=[code_description, code_language],
|
| 296 |
+
outputs=generated_code
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
# Code Chat Tab
|
| 300 |
+
with gr.TabItem("💬 Chat About Code"):
|
| 301 |
+
with gr.Row():
|
| 302 |
+
with gr.Column():
|
| 303 |
+
chat_file_input = gr.File(
|
| 304 |
+
label="Upload Code File",
|
| 305 |
+
file_types=[".py", ".ipynb"]
|
| 306 |
+
)
|
| 307 |
+
code_question = gr.Textbox(
|
| 308 |
+
label="Ask a question about your code",
|
| 309 |
+
lines=3,
|
| 310 |
+
placeholder="E.g., How can I improve the performance of this function?"
|
| 311 |
+
)
|
| 312 |
+
chat_btn = gr.Button("Ask Question", variant="primary")
|
| 313 |
+
|
| 314 |
+
with gr.Column():
|
| 315 |
+
chat_output = gr.Textbox(
|
| 316 |
+
label="Answer",
|
| 317 |
+
lines=15,
|
| 318 |
+
max_lines=25
|
| 319 |
+
)
|
| 320 |
+
|
| 321 |
+
chat_btn.click(
|
| 322 |
+
chat_about_code,
|
| 323 |
+
inputs=[chat_file_input, code_question],
|
| 324 |
+
outputs=chat_output
|
| 325 |
+
)
|
| 326 |
+
|
| 327 |
+
# Footer
|
| 328 |
+
gr.Markdown("---")
|
| 329 |
+
gr.Markdown("**Note:** This copilot uses Claude 3 Haiku for intelligent code analysis and generation.")
|
| 330 |
+
|
| 331 |
+
# Launch the app
|
| 332 |
+
if __name__ == "__main__":
|
| 333 |
+
app.launch()
|