Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,129 +1,153 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
-
import requests
|
| 3 |
import os
|
|
|
|
| 4 |
from dotenv import load_dotenv
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
# Load environment variables
|
| 7 |
load_dotenv()
|
|
|
|
| 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 |
-
timeout=30
|
| 37 |
-
)
|
| 38 |
|
| 39 |
-
#
|
| 40 |
-
|
|
|
|
|
|
|
|
|
|
| 41 |
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
analysis_prompt = f"""
|
| 59 |
-
Analyze this code and provide detailed suggestions for improvement:
|
| 60 |
-
- Code quality
|
| 61 |
-
- Optimizations
|
| 62 |
-
- Best practices
|
| 63 |
-
- Security considerations
|
| 64 |
-
- Readability enhancements
|
| 65 |
-
|
| 66 |
-
Code to analyze:
|
| 67 |
-
{code}
|
| 68 |
-
|
| 69 |
-
Respond with clear bullet points and explanations.
|
| 70 |
-
"""
|
| 71 |
-
return generate_text_with_blackbox(analysis_prompt)
|
| 72 |
|
| 73 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
with gr.Row():
|
| 75 |
-
gr.
|
| 76 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
|
| 78 |
-
with gr.
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
lines=3
|
| 85 |
-
)
|
| 86 |
-
generate_btn = gr.Button("Generate Code")
|
| 87 |
-
output = gr.Code(
|
| 88 |
-
label="Generated Code",
|
| 89 |
-
language="python",
|
| 90 |
-
interactive=True
|
| 91 |
-
)
|
| 92 |
-
|
| 93 |
-
with gr.TabItem("Code Analysis"):
|
| 94 |
-
with gr.Column():
|
| 95 |
-
code_input = gr.Code(
|
| 96 |
-
label="Paste your code here",
|
| 97 |
-
language="python",
|
| 98 |
-
lines=10
|
| 99 |
-
)
|
| 100 |
-
analyze_btn = gr.Button("Analyze Code")
|
| 101 |
-
suggestions = gr.Markdown(
|
| 102 |
-
label="Suggestions",
|
| 103 |
-
value="Your suggestions will appear here..."
|
| 104 |
-
)
|
| 105 |
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
|
|
|
|
|
|
|
|
|
| 111 |
|
| 112 |
-
|
| 113 |
-
fn=
|
| 114 |
-
inputs=
|
| 115 |
-
outputs=
|
| 116 |
)
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
gr.Markdown("### Note:")
|
| 120 |
-
gr.Markdown("1. Make sure you have a valid BLACKBOX_API_KEY in your `.env` file")
|
| 121 |
-
gr.Markdown("2. Be specific with your prompts for better results")
|
| 122 |
|
| 123 |
if __name__ == "__main__":
|
| 124 |
-
|
| 125 |
-
server_name="0.0.0.0",
|
| 126 |
-
server_port=7860,
|
| 127 |
-
show_error=True,
|
| 128 |
-
debug=True
|
| 129 |
-
)
|
|
|
|
| 1 |
import gradio as gr
|
|
|
|
| 2 |
import os
|
| 3 |
+
import requests
|
| 4 |
from dotenv import load_dotenv
|
| 5 |
+
import nltk
|
| 6 |
+
from nltk.tokenize import sent_tokenize
|
| 7 |
+
import numpy as np
|
| 8 |
+
import pandas as pd
|
| 9 |
+
from tqdm import tqdm
|
| 10 |
+
|
| 11 |
+
# Initialize NLTK (download punkt if needed)
|
| 12 |
+
nltk.download('punkt', quiet=True)
|
| 13 |
|
| 14 |
# Load environment variables
|
| 15 |
load_dotenv()
|
| 16 |
+
BLACKBOX_API_KEY = os.getenv("BLACKBOX_API_KEY")
|
| 17 |
|
| 18 |
+
class CodeCopilot:
|
| 19 |
+
def __init__(self):
|
| 20 |
+
self.chat_history = []
|
| 21 |
+
self.context_window = 5
|
| 22 |
+
|
| 23 |
+
def get_blackbox_response(self, prompt, max_tokens=300, temperature=0.7):
|
| 24 |
+
"""Get response from Blackbox AI API"""
|
| 25 |
+
headers = {
|
| 26 |
+
"Authorization": f"Bearer {BLACKBOX_API_KEY}",
|
| 27 |
+
"Content-Type": "application/json"
|
| 28 |
+
}
|
| 29 |
+
data = {
|
| 30 |
+
"prompt": prompt,
|
| 31 |
+
"max_tokens": max_tokens,
|
| 32 |
+
"temperature": temperature
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
try:
|
| 36 |
+
response = requests.post(
|
| 37 |
+
"https://api.blackbox.ai/generate",
|
| 38 |
+
headers=headers,
|
| 39 |
+
json=data,
|
| 40 |
+
timeout=30
|
| 41 |
+
)
|
| 42 |
+
response.raise_for_status()
|
| 43 |
+
return response.json().get("text", "No response text found.")
|
| 44 |
+
except Exception as e:
|
| 45 |
+
return f"Error: {str(e)}"
|
| 46 |
|
| 47 |
+
def analyze_code_patterns(self, text):
|
| 48 |
+
"""Analyze text for coding patterns"""
|
| 49 |
+
sentences = sent_tokenize(text)
|
| 50 |
+
# Simple pattern detection (can be expanded)
|
| 51 |
+
patterns = {
|
| 52 |
+
'function_def': sum(1 for s in sentences if 'def ' in s),
|
| 53 |
+
'class_def': sum(1 for s in sentences if 'class ' in s),
|
| 54 |
+
'loop': sum(1 for s in sentences if any(
|
| 55 |
+
word in s for word in ['for ', 'while ', 'loop'])),
|
| 56 |
+
'conditional': sum(1 for s in sentences if any(
|
| 57 |
+
word in s for word in ['if ', 'else ', 'elif ']))
|
| 58 |
+
}
|
| 59 |
+
return patterns
|
| 60 |
|
| 61 |
+
def generate_suggestions(self, patterns):
|
| 62 |
+
"""Generate suggestions based on detected patterns"""
|
| 63 |
+
suggestions = []
|
| 64 |
+
if patterns['function_def'] > 3:
|
| 65 |
+
suggestions.append("Consider breaking down into smaller functions or using a class structure.")
|
| 66 |
+
if patterns['loop'] > 2:
|
| 67 |
+
suggestions.append("You might benefit from using list comprehensions or map/filter functions.")
|
| 68 |
+
if patterns['conditional'] > 3:
|
| 69 |
+
suggestions.append("Complex conditionals might be simplified using polymorphism or strategy pattern.")
|
| 70 |
+
return "\n".join(suggestions) if suggestions else "No specific suggestions at this time."
|
| 71 |
|
| 72 |
+
def process_input(self, user_input, history=None):
|
| 73 |
+
"""Process user input and generate response"""
|
| 74 |
+
# Analyze patterns
|
| 75 |
+
patterns = self.analyze_code_patterns(user_input)
|
| 76 |
+
suggestions = self.generate_suggestions(patterns)
|
|
|
|
|
|
|
| 77 |
|
| 78 |
+
# Create context-aware prompt
|
| 79 |
+
context = "\n".join([f"User: {h[0]}\nAI: {h[1]}" for h in self.chat_history[-self.context_window:]])
|
| 80 |
+
prompt = f"""
|
| 81 |
+
Context:
|
| 82 |
+
{context}
|
| 83 |
|
| 84 |
+
User Input:
|
| 85 |
+
{user_input}
|
| 86 |
+
|
| 87 |
+
Respond as a helpful coding assistant that also provides suggestions for improvement.
|
| 88 |
+
Suggestions to consider:
|
| 89 |
+
{suggestions}
|
| 90 |
+
"""
|
| 91 |
+
|
| 92 |
+
# Get response from Blackbox AI
|
| 93 |
+
response = self.get_blackbox_response(prompt)
|
| 94 |
+
|
| 95 |
+
# Update chat history
|
| 96 |
+
self.chat_history.append((user_input, response))
|
| 97 |
+
|
| 98 |
+
# Format full response with suggestions
|
| 99 |
+
full_response = f"{response}\n\n=== Suggestions ===\n{suggestions}"
|
| 100 |
+
return full_response
|
| 101 |
|
| 102 |
+
# Initialize copilot
|
| 103 |
+
copilot = CodeCopilot()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
|
| 105 |
+
# Gradio interface
|
| 106 |
+
with gr.Blocks(title="AI Code Copilot") as demo:
|
| 107 |
+
gr.Markdown("""
|
| 108 |
+
# AI Code Copilot
|
| 109 |
+
Your intelligent assistant for coding tasks that learns patterns and provides proactive suggestions.
|
| 110 |
+
""")
|
| 111 |
+
|
| 112 |
with gr.Row():
|
| 113 |
+
with gr.Column():
|
| 114 |
+
input_text = gr.Textbox(
|
| 115 |
+
label="Your code or question",
|
| 116 |
+
placeholder="Paste your code or ask a question...",
|
| 117 |
+
lines=5
|
| 118 |
+
)
|
| 119 |
+
submit_btn = gr.Button("Generate")
|
| 120 |
+
|
| 121 |
+
with gr.Column():
|
| 122 |
+
output_text = gr.Textbox(
|
| 123 |
+
label="Copilot Response",
|
| 124 |
+
lines=10,
|
| 125 |
+
interactive=False
|
| 126 |
+
)
|
| 127 |
|
| 128 |
+
with gr.Accordion("Pattern Analysis", open=False):
|
| 129 |
+
pattern_display = gr.Dataframe(
|
| 130 |
+
headers=["Pattern", "Count"],
|
| 131 |
+
datatype=["str", "number"],
|
| 132 |
+
interactive=False
|
| 133 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
|
| 135 |
+
def process_and_analyze(input_text):
|
| 136 |
+
response = copilot.process_input(input_text)
|
| 137 |
+
patterns = copilot.analyze_code_patterns(input_text)
|
| 138 |
+
pattern_df = pd.DataFrame({
|
| 139 |
+
"Pattern": list(patterns.keys()),
|
| 140 |
+
"Count": list(patterns.values())
|
| 141 |
+
})
|
| 142 |
+
return response, pattern_df
|
| 143 |
|
| 144 |
+
submit_btn.click(
|
| 145 |
+
fn=process_and_analyze,
|
| 146 |
+
inputs=input_text,
|
| 147 |
+
outputs=[output_text, pattern_display]
|
| 148 |
)
|
| 149 |
+
|
| 150 |
+
demo.launch()
|
|
|
|
|
|
|
|
|
|
| 151 |
|
| 152 |
if __name__ == "__main__":
|
| 153 |
+
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|