Update app.py
Browse files
app.py
CHANGED
|
@@ -5,6 +5,7 @@ from dotenv import load_dotenv
|
|
| 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,20 +16,61 @@ BLACKBOX_API_KEY = os.getenv("BLACKBOX_API_KEY")
|
|
| 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 |
-
|
| 32 |
"https://api.blackbox.ai/chat/completions",
|
| 33 |
headers=headers,
|
| 34 |
json={
|
|
@@ -39,131 +81,83 @@ class CodeCopilot:
|
|
| 39 |
},
|
| 40 |
timeout=30
|
| 41 |
)
|
| 42 |
-
|
| 43 |
-
return
|
| 44 |
-
except requests.exceptions.RequestException as e:
|
| 45 |
-
return f"API Error: {str(e)}"
|
| 46 |
except Exception as e:
|
| 47 |
-
return f"
|
| 48 |
-
|
| 49 |
-
def
|
| 50 |
-
"""Analyze text for coding patterns"""
|
| 51 |
-
sentences = sent_tokenize(text)
|
| 52 |
-
patterns = {
|
| 53 |
-
'function_def': sum(1 for s in sentences if 'def ' in s),
|
| 54 |
-
'class_def': sum(1 for s in sentences if 'class ' in s),
|
| 55 |
-
'loop': sum(1 for s in sentences if any(word in s for word in ['for ', 'while ', 'loop'])),
|
| 56 |
-
'conditional': sum(1 for s in sentences if any(word in s for word in ['if ', 'else ', 'elif ']))
|
| 57 |
-
}
|
| 58 |
-
return patterns
|
| 59 |
-
|
| 60 |
-
def generate_suggestions(self, text, patterns):
|
| 61 |
-
"""Generate suggestions based on detected patterns and actual code"""
|
| 62 |
suggestions = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
|
| 64 |
-
|
| 65 |
-
|
|
|
|
| 66 |
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
else:
|
| 71 |
-
suggestions.append("π You might benefit from list comprehensions or using `map`/`filter` functions.")
|
| 72 |
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
else:
|
| 77 |
-
suggestions.append("π§ Simplify conditionals with clearer boolean logic or helper functions.")
|
| 78 |
|
|
|
|
| 79 |
if not suggestions:
|
| 80 |
-
suggestions.append("β
|
| 81 |
-
|
| 82 |
return "\n".join(suggestions)
|
| 83 |
|
| 84 |
def process_input(self, user_input):
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
|
|
|
| 88 |
context = "\nPrevious conversation:\n" + "\n".join(
|
| 89 |
-
[f"User: {h[0]}\nAI: {h[1]}" for h in self.chat_history[-self.context_window:]]
|
| 90 |
-
|
| 91 |
-
prompt = f"
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
response = self.get_blackbox_response(prompt)
|
| 100 |
-
suggestions = self.generate_suggestions(user_input, patterns)
|
| 101 |
-
|
| 102 |
-
self.chat_history.append((user_input, response))
|
| 103 |
-
|
| 104 |
-
return response, patterns, suggestions
|
| 105 |
|
| 106 |
# Initialize copilot
|
| 107 |
copilot = CodeCopilot()
|
| 108 |
|
| 109 |
-
# Gradio
|
| 110 |
with gr.Blocks(theme=gr.themes.Soft(), title="π€ AI Code Copilot") as demo:
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
</div>
|
| 118 |
-
"""
|
| 119 |
)
|
| 120 |
-
|
| 121 |
-
# Main layout: input on the left, outputs on the right
|
| 122 |
with gr.Row():
|
| 123 |
with gr.Column(scale=3, min_width=300):
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
)
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
# Display response
|
| 134 |
-
gr.Markdown("**Assistant Response:**")
|
| 135 |
-
output_text = gr.Markdown()
|
| 136 |
-
# Display suggestions
|
| 137 |
-
gr.Markdown("**Suggestions:**")
|
| 138 |
-
suggestions_output = gr.Markdown()
|
| 139 |
-
# Display pattern analysis
|
| 140 |
-
gr.Markdown("**Pattern Analysis:**")
|
| 141 |
-
pattern_display = gr.Dataframe(
|
| 142 |
-
headers=["Pattern", "Count"],
|
| 143 |
-
datatype=["str", "number"],
|
| 144 |
-
interactive=False,
|
| 145 |
-
label="Detected code patterns"
|
| 146 |
-
)
|
| 147 |
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
return response, sugg, pattern_df
|
| 156 |
-
|
| 157 |
-
submit_btn.click(
|
| 158 |
-
fn=process_input_wrapper,
|
| 159 |
-
inputs=input_text,
|
| 160 |
-
outputs=[output_text, suggestions_output, pattern_display]
|
| 161 |
-
)
|
| 162 |
-
input_text.submit(
|
| 163 |
-
fn=process_input_wrapper,
|
| 164 |
-
inputs=input_text,
|
| 165 |
-
outputs=[output_text, suggestions_output, pattern_display]
|
| 166 |
-
)
|
| 167 |
|
| 168 |
if __name__ == "__main__":
|
| 169 |
demo.launch()
|
|
|
|
| 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 |
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 |
+
resp = requests.post(
|
| 74 |
"https://api.blackbox.ai/chat/completions",
|
| 75 |
headers=headers,
|
| 76 |
json={
|
|
|
|
| 81 |
},
|
| 82 |
timeout=30
|
| 83 |
)
|
| 84 |
+
resp.raise_for_status()
|
| 85 |
+
return resp.json()["choices"][0]["message"]["content"]
|
|
|
|
|
|
|
| 86 |
except Exception as e:
|
| 87 |
+
return f"API Error: {e}"
|
| 88 |
+
|
| 89 |
+
def generate_suggestions(self, analysis):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
suggestions = []
|
| 91 |
+
# Functions
|
| 92 |
+
if analysis['function_def'] == 0:
|
| 93 |
+
suggestions.append("π Consider defining functions to organize your code and improve reuse.")
|
| 94 |
+
elif analysis['function_def'] > 3:
|
| 95 |
+
suggestions.append(f"π Detected {analysis['function_def']} functions β consider grouping related functions into classes or modules.")
|
| 96 |
|
| 97 |
+
# Loops
|
| 98 |
+
if analysis['loop'] >= 1:
|
| 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 |
+
# AST analysis
|
| 116 |
+
analyzer = CodeAnalyzer()
|
| 117 |
+
analysis = analyzer.analyze(user_input)
|
| 118 |
+
# Build context prompt
|
| 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 improvements.\n{context}\nNew input:\n{user_input}"
|
| 123 |
+
# AI response
|
| 124 |
+
ai_resp = self.get_blackbox_response(prompt)
|
| 125 |
+
# Suggestions
|
| 126 |
+
sugg = self.generate_suggestions(analysis)
|
| 127 |
+
self.chat_history.append((user_input, ai_resp))
|
| 128 |
+
return ai_resp, analysis, sugg
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
|
| 130 |
# Initialize copilot
|
| 131 |
copilot = CodeCopilot()
|
| 132 |
|
| 133 |
+
# Build Gradio UI
|
| 134 |
with gr.Blocks(theme=gr.themes.Soft(), title="π€ AI Code Copilot") as demo:
|
| 135 |
+
gr.Markdown("""
|
| 136 |
+
<div style='text-align: center; margin-bottom: 1rem;'>
|
| 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, min_width=300):
|
| 144 |
+
inp = gr.Textbox(label="Your Code / Question", lines=10, placeholder="Enter code here...")
|
| 145 |
+
btn = gr.Button("π Generate")
|
| 146 |
+
with gr.Column(scale=6, min_width=500):
|
| 147 |
+
gr.Markdown("**Assistant Response**")
|
| 148 |
+
out = gr.Markdown()
|
| 149 |
+
gr.Markdown("**Pattern Analysis**")
|
| 150 |
+
df = gr.Dataframe(headers=["Metric","Count"], datatype=["str","number"], interactive=False)
|
| 151 |
+
gr.Markdown("**Suggestions**")
|
| 152 |
+
sug = gr.Markdown()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
|
| 154 |
+
def run_all(text):
|
| 155 |
+
ai_text, analysis, suggestions = copilot.process_input(text)
|
| 156 |
+
df_data = {"Metric": list(analysis.keys()), "Count": list(analysis.values())}
|
| 157 |
+
return ai_text, pd.DataFrame(df_data), suggestions
|
| 158 |
+
|
| 159 |
+
btn.click(fn=run_all, inputs=inp, outputs=[out, df, sug])
|
| 160 |
+
inp.submit(fn=run_all, inputs=inp, outputs=[out, df, sug])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 161 |
|
| 162 |
if __name__ == "__main__":
|
| 163 |
demo.launch()
|