Spaces:
Sleeping
Sleeping
changes
#1
by
iammahmads
- opened
.env
CHANGED
|
@@ -1 +1 @@
|
|
| 1 |
-
BLACKBOX_API_KEY=sk
|
|
|
|
| 1 |
+
BLACKBOX_API_KEY=sk--yuitsASMpfxFL4jNViUGw
|
app.py
CHANGED
|
@@ -5,7 +5,6 @@ from dotenv import load_dotenv
|
|
| 5 |
import nltk
|
| 6 |
from nltk.tokenize import sent_tokenize
|
| 7 |
import pandas as pd
|
| 8 |
-
import ast
|
| 9 |
|
| 10 |
# Initialize NLTK
|
| 11 |
nltk.download('punkt', quiet=True)
|
|
@@ -16,148 +15,133 @@ BLACKBOX_API_KEY = os.getenv("BLACKBOX_API_KEY")
|
|
| 16 |
if not BLACKBOX_API_KEY:
|
| 17 |
BLACKBOX_API_KEY = os.environ.get('BLACKBOX_API_KEY')
|
| 18 |
|
| 19 |
-
class CodeAnalyzer(ast.NodeVisitor):
|
| 20 |
-
def __init__(self):
|
| 21 |
-
self.func_count = 0
|
| 22 |
-
self.loop_count = 0
|
| 23 |
-
self.cond_count = 0
|
| 24 |
-
self.max_depth = 0
|
| 25 |
-
self.current_depth = 0
|
| 26 |
-
|
| 27 |
-
def visit_FunctionDef(self, node):
|
| 28 |
-
self.func_count += 1
|
| 29 |
-
self.generic_visit(node)
|
| 30 |
-
|
| 31 |
-
def visit_For(self, node):
|
| 32 |
-
self.loop_count += 1
|
| 33 |
-
self._enter_block(node)
|
| 34 |
-
|
| 35 |
-
def visit_While(self, node):
|
| 36 |
-
self.loop_count += 1
|
| 37 |
-
self._enter_block(node)
|
| 38 |
-
|
| 39 |
-
def visit_If(self, node):
|
| 40 |
-
self.cond_count += 1
|
| 41 |
-
self._enter_block(node)
|
| 42 |
-
|
| 43 |
-
def _enter_block(self, node):
|
| 44 |
-
self.current_depth += 1
|
| 45 |
-
self.max_depth = max(self.max_depth, self.current_depth)
|
| 46 |
-
self.generic_visit(node)
|
| 47 |
-
self.current_depth -= 1
|
| 48 |
-
|
| 49 |
-
def analyze(self, code_str):
|
| 50 |
-
try:
|
| 51 |
-
tree = ast.parse(code_str)
|
| 52 |
-
self.visit(tree)
|
| 53 |
-
except SyntaxError:
|
| 54 |
-
pass
|
| 55 |
-
return {
|
| 56 |
-
'function_def': self.func_count,
|
| 57 |
-
'loop': self.loop_count,
|
| 58 |
-
'conditional': self.cond_count,
|
| 59 |
-
'max_depth': self.max_depth
|
| 60 |
-
}
|
| 61 |
-
|
| 62 |
class CodeCopilot:
|
| 63 |
def __init__(self):
|
| 64 |
self.chat_history = []
|
| 65 |
self.context_window = 3
|
| 66 |
-
|
| 67 |
def get_blackbox_response(self, prompt, max_tokens=300, temperature=0.7):
|
|
|
|
| 68 |
headers = {
|
| 69 |
"Content-Type": "application/json",
|
| 70 |
"Authorization": f"Bearer {BLACKBOX_API_KEY}"
|
| 71 |
}
|
|
|
|
| 72 |
try:
|
| 73 |
-
|
| 74 |
-
|
|
|
|
| 75 |
headers=headers,
|
| 76 |
json={
|
| 77 |
"messages": [{"role": "user", "content": prompt}],
|
| 78 |
"max_tokens": max_tokens,
|
| 79 |
"temperature": temperature,
|
| 80 |
-
"model": "
|
| 81 |
},
|
| 82 |
timeout=30
|
| 83 |
)
|
| 84 |
-
|
| 85 |
-
return
|
|
|
|
|
|
|
| 86 |
except Exception as e:
|
| 87 |
-
return f"
|
| 88 |
-
|
| 89 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
suggestions = []
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
suggestions.append(f"π {analysis['loop']} loop(s) found β check if list comprehensions or vectorized operations can simplify them.")
|
| 100 |
-
|
| 101 |
-
# Conditionals
|
| 102 |
-
if analysis['conditional'] >= 2:
|
| 103 |
-
suggestions.append(f"β {analysis['conditional']} conditional statements β consider simplifying nested logic or using lookup tables.")
|
| 104 |
-
|
| 105 |
-
# Nesting depth
|
| 106 |
-
if analysis['max_depth'] > 2:
|
| 107 |
-
suggestions.append(f"π¦ Maximum nesting depth of {analysis['max_depth']} detected β flatten nested blocks for readability.")
|
| 108 |
-
|
| 109 |
-
# Default
|
| 110 |
-
if not suggestions:
|
| 111 |
-
suggestions.append("β
Code structure looks clean based on basic analysis.")
|
| 112 |
-
return "\n".join(suggestions)
|
| 113 |
-
|
| 114 |
def process_input(self, user_input):
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
|
|
|
| 119 |
context = "\nPrevious conversation:\n" + "\n".join(
|
| 120 |
-
[f"User: {h[0]}\nAI: {h[1]}" for h in self.chat_history[-self.context_window:]]
|
| 121 |
-
|
| 122 |
-
prompt = f"You are an expert coding assistant. Analyze this code and provide
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
|
| 130 |
# Initialize copilot
|
| 131 |
copilot = CodeCopilot()
|
| 132 |
|
| 133 |
-
#
|
| 134 |
-
with gr.Blocks(theme=gr.themes.Soft(), title="
|
| 135 |
-
gr.Markdown("""
|
| 136 |
-
|
| 137 |
-
<h1>π€ AI Code Copilot</h1>
|
| 138 |
-
<p>Paste code or ask a question below to get instant analysis.</p>
|
| 139 |
-
</div>
|
| 140 |
-
"""
|
| 141 |
-
)
|
| 142 |
with gr.Row():
|
| 143 |
-
with gr.Column(scale=3
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
gr.
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 161 |
|
| 162 |
if __name__ == "__main__":
|
| 163 |
demo.launch()
|
|
|
|
| 5 |
import nltk
|
| 6 |
from nltk.tokenize import sent_tokenize
|
| 7 |
import pandas as pd
|
|
|
|
| 8 |
|
| 9 |
# Initialize NLTK
|
| 10 |
nltk.download('punkt', quiet=True)
|
|
|
|
| 15 |
if not BLACKBOX_API_KEY:
|
| 16 |
BLACKBOX_API_KEY = os.environ.get('BLACKBOX_API_KEY')
|
| 17 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
class CodeCopilot:
|
| 19 |
def __init__(self):
|
| 20 |
self.chat_history = []
|
| 21 |
self.context_window = 3
|
| 22 |
+
|
| 23 |
def get_blackbox_response(self, prompt, max_tokens=300, temperature=0.7):
|
| 24 |
+
"""Get response using Blackbox's API"""
|
| 25 |
headers = {
|
| 26 |
"Content-Type": "application/json",
|
| 27 |
"Authorization": f"Bearer {BLACKBOX_API_KEY}"
|
| 28 |
}
|
| 29 |
+
|
| 30 |
try:
|
| 31 |
+
# Correct API endpoint based on Blackbox documentation
|
| 32 |
+
response = requests.post(
|
| 33 |
+
"https://developer.blackbox.ai/api/v1/chat/completions",
|
| 34 |
headers=headers,
|
| 35 |
json={
|
| 36 |
"messages": [{"role": "user", "content": prompt}],
|
| 37 |
"max_tokens": max_tokens,
|
| 38 |
"temperature": temperature,
|
| 39 |
+
"model": "blackbox-code"
|
| 40 |
},
|
| 41 |
timeout=30
|
| 42 |
)
|
| 43 |
+
response.raise_for_status()
|
| 44 |
+
return response.json()["choices"][0]["message"]["content"]
|
| 45 |
+
except requests.exceptions.RequestException as e:
|
| 46 |
+
return f"API Error: {str(e)}"
|
| 47 |
except Exception as e:
|
| 48 |
+
return f"Processing Error: {str(e)}"
|
| 49 |
+
|
| 50 |
+
def analyze_code_patterns(self, text):
|
| 51 |
+
"""Analyze text for coding patterns"""
|
| 52 |
+
sentences = sent_tokenize(text)
|
| 53 |
+
patterns = {
|
| 54 |
+
'function_def': sum(1 for s in sentences if 'def ' in s),
|
| 55 |
+
'class_def': sum(1 for s in sentences if 'class ' in s),
|
| 56 |
+
'loop': sum(1 for s in sentences if any(word in s for word in ['for ', 'while ', 'loop'])),
|
| 57 |
+
'conditional': sum(1 for s in sentences if any(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 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):
|
| 73 |
+
"""Process user input and generate response"""
|
| 74 |
+
# Analyze patterns
|
| 75 |
+
patterns = self.analyze_code_patterns(user_input)
|
| 76 |
+
|
| 77 |
+
# Create context-aware prompt
|
| 78 |
context = "\nPrevious conversation:\n" + "\n".join(
|
| 79 |
+
[f"User: {h[0]}\nAI: {h[1]}" for h in self.chat_history[-self.context_window:]])
|
| 80 |
+
|
| 81 |
+
prompt = f"""You are an expert coding assistant. Analyze this code and provide helpful suggestions:
|
| 82 |
+
|
| 83 |
+
{context}
|
| 84 |
+
|
| 85 |
+
New input:
|
| 86 |
+
{user_input}
|
| 87 |
+
"""
|
| 88 |
+
|
| 89 |
+
# Get response
|
| 90 |
+
response = self.get_blackbox_response(prompt)
|
| 91 |
+
suggestions = self.generate_suggestions(patterns)
|
| 92 |
+
|
| 93 |
+
# Update chat history
|
| 94 |
+
self.chat_history.append((user_input, response))
|
| 95 |
+
|
| 96 |
+
return response, patterns, suggestions
|
| 97 |
|
| 98 |
# Initialize copilot
|
| 99 |
copilot = CodeCopilot()
|
| 100 |
|
| 101 |
+
# Gradio interface
|
| 102 |
+
with gr.Blocks(theme=gr.themes.Soft(), title="AI Code Copilot") as demo:
|
| 103 |
+
gr.Markdown("""<h1 style="text-align: center">π€ AI Code Copilot</h1>""")
|
| 104 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
with gr.Row():
|
| 106 |
+
with gr.Column(scale=3):
|
| 107 |
+
input_text = gr.Textbox(
|
| 108 |
+
label="Your Code or Question",
|
| 109 |
+
placeholder="Paste your code or ask a question...",
|
| 110 |
+
lines=7
|
| 111 |
+
)
|
| 112 |
+
submit_btn = gr.Button("Generate", variant="primary")
|
| 113 |
+
|
| 114 |
+
with gr.Column(scale=7):
|
| 115 |
+
with gr.Tab("Assistant Response"):
|
| 116 |
+
output_text = gr.Markdown()
|
| 117 |
+
with gr.Tab("Suggestions"):
|
| 118 |
+
suggestions = gr.Markdown()
|
| 119 |
+
with gr.Tab("Pattern Analysis"):
|
| 120 |
+
pattern_display = gr.Dataframe(
|
| 121 |
+
headers=["Pattern", "Count"],
|
| 122 |
+
datatype=["str", "number"],
|
| 123 |
+
interactive=False
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
def process_input(user_input):
|
| 127 |
+
response, patterns, sugg = copilot.process_input(user_input)
|
| 128 |
+
pattern_df = pd.DataFrame({
|
| 129 |
+
"Pattern": list(patterns.keys()),
|
| 130 |
+
"Count": list(patterns.values())
|
| 131 |
+
})
|
| 132 |
+
return response, sugg, pattern_df
|
| 133 |
+
|
| 134 |
+
submit_btn.click(
|
| 135 |
+
fn=process_input,
|
| 136 |
+
inputs=input_text,
|
| 137 |
+
outputs=[output_text, suggestions, pattern_display]
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
input_text.submit(
|
| 141 |
+
fn=process_input,
|
| 142 |
+
inputs=input_text,
|
| 143 |
+
outputs=[output_text, suggestions, pattern_display]
|
| 144 |
+
)
|
| 145 |
|
| 146 |
if __name__ == "__main__":
|
| 147 |
demo.launch()
|