Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,378 +1,165 @@
|
|
1 |
import streamlit as st
|
2 |
import difflib
|
3 |
-
import re
|
4 |
-
import hashlib
|
5 |
import requests
|
6 |
-
import
|
7 |
-
|
8 |
-
# ---
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
14 |
|
15 |
-
def
|
|
|
16 |
headers = {
|
17 |
"Content-Type": "application/json",
|
18 |
-
"Authorization": f"Bearer {BLACKBOX_API_KEY}"
|
19 |
}
|
20 |
data = {
|
21 |
-
"
|
22 |
-
"messages": [
|
23 |
-
{"role": "user", "content": prompt}
|
24 |
-
],
|
25 |
-
"max_tokens": 2048,
|
26 |
-
"temperature": 0.7
|
27 |
}
|
28 |
-
response = requests.post(
|
29 |
if response.status_code == 200:
|
30 |
-
|
31 |
-
return
|
32 |
-
else:
|
33 |
-
return f"[Blackbox API Error {response.status_code}]: {response.text}"
|
34 |
-
|
35 |
-
# --- Cache for embeddings ---
|
36 |
-
embedding_cache = {}
|
37 |
-
|
38 |
-
def get_embedding(text):
|
39 |
-
key = hashlib.sha256(text.encode()).hexdigest()
|
40 |
-
if key in embedding_cache:
|
41 |
-
return embedding_cache[key]
|
42 |
-
embedding = [ord(c) % 100 / 100 for c in text[:512]]
|
43 |
-
embedding_cache[key] = embedding
|
44 |
-
return embedding
|
45 |
-
|
46 |
-
def cosine_similarity(vec1, vec2):
|
47 |
-
dot = sum(a*b for a,b in zip(vec1, vec2))
|
48 |
-
norm1 = sum(a*a for a in vec1) ** 0.5
|
49 |
-
norm2 = sum(b*b for b in vec2) ** 0.5
|
50 |
-
return dot / (norm1 * norm2 + 1e-8)
|
51 |
-
|
52 |
-
def split_code_into_chunks(code, lang):
|
53 |
-
if lang.lower() == "python":
|
54 |
-
pattern = r'(def\s+\w+\(.*?\):|class\s+\w+\(?.*?\)?:)'
|
55 |
-
splits = re.split(pattern, code)
|
56 |
-
chunks = []
|
57 |
-
for i in range(1, len(splits), 2):
|
58 |
-
header = splits[i]
|
59 |
-
body = splits[i+1] if (i+1) < len(splits) else ""
|
60 |
-
chunks.append(header + body)
|
61 |
-
return chunks if chunks else [code]
|
62 |
else:
|
63 |
-
return [
|
64 |
-
|
65 |
-
def semantic_search_improved(code, question, lang, skill, role, explain_lang):
|
66 |
-
chunks = split_code_into_chunks(code, lang)
|
67 |
-
question_emb = get_embedding(question)
|
68 |
-
scored_chunks = []
|
69 |
-
for chunk in chunks:
|
70 |
-
emb = get_embedding(chunk)
|
71 |
-
score = cosine_similarity(question_emb, emb)
|
72 |
-
scored_chunks.append((score, chunk))
|
73 |
-
scored_chunks.sort(key=lambda x: x[0], reverse=True)
|
74 |
-
top_chunks = [c for _, c in scored_chunks[:3]]
|
75 |
-
combined_code = "\n\n".join(top_chunks)
|
76 |
-
prompt = (
|
77 |
-
f"You are a friendly and insightful {lang} expert helping a {skill} {role}.\n"
|
78 |
-
f"Based on these relevant code snippets:\n{combined_code}\n"
|
79 |
-
f"Answer this question in {explain_lang}:\n{question}\n"
|
80 |
-
f"Explain which parts handle the question and how to modify them if needed."
|
81 |
-
)
|
82 |
-
answer = blackbox_api_call(prompt)
|
83 |
-
add_to_blackbox_history(prompt, answer, "semantic_search")
|
84 |
-
return answer
|
85 |
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
add_to_blackbox_history(prompt, answer, "workflow")
|
93 |
-
return answer
|
94 |
-
|
95 |
-
def agentic_workflow(code, skill_level, programming_language, explanation_language, user_role):
|
96 |
-
timeline = []
|
97 |
-
suggestions = []
|
98 |
-
|
99 |
-
# Explanation
|
100 |
-
explain_prompt = (
|
101 |
-
f"You are a friendly and insightful {programming_language} expert helping a {skill_level} {user_role}. "
|
102 |
-
f"Explain this code in {explanation_language} with clear examples, analogies, and why each part matters:\n\n{code}"
|
103 |
-
)
|
104 |
-
explanation = blackbox_api_call(explain_prompt)
|
105 |
-
timeline.append({"step": "Explain", "description": "Detailed explanation", "output": explanation, "code": code})
|
106 |
-
suggestions.append("Consider refactoring your code to improve readability and performance.")
|
107 |
-
add_to_blackbox_history(explain_prompt, explanation, "workflow")
|
108 |
|
109 |
-
|
110 |
-
|
111 |
-
f"Refactor this {programming_language} code. Explain the changes like a mentor helping a {skill_level} {user_role}. "
|
112 |
-
f"Include best practices and improvements:\n\n{code}"
|
113 |
-
)
|
114 |
-
refactor_response = blackbox_api_call(refactor_prompt)
|
115 |
-
add_to_blackbox_history(refactor_prompt, refactor_response, "workflow")
|
116 |
-
if "```" in refactor_response:
|
117 |
-
parts = refactor_response.split("```")
|
118 |
-
refactored_code = ""
|
119 |
-
for part in parts:
|
120 |
-
if part.strip().startswith(programming_language.lower()):
|
121 |
-
refactored_code = part.strip().split('\n', 1)[1] if '\n' in part else ""
|
122 |
-
break
|
123 |
-
if not refactored_code:
|
124 |
-
refactored_code = refactor_response
|
125 |
-
else:
|
126 |
-
refactored_code = refactor_response
|
127 |
-
timeline.append({"step": "Refactor", "description": "Refactored code with improvements", "output": refactored_code, "code": refactored_code})
|
128 |
-
suggestions.append("Review the refactored code and adapt it to your style or project needs.")
|
129 |
-
|
130 |
-
# Review
|
131 |
-
review_prompt = (
|
132 |
-
f"As a senior {programming_language} developer, review the refactored code. "
|
133 |
-
f"Give constructive feedback on strengths, weaknesses, performance, security, and improvements in {explanation_language}:\n\n{refactored_code}"
|
134 |
-
)
|
135 |
-
review = blackbox_api_call(review_prompt)
|
136 |
-
add_to_blackbox_history(review_prompt, review, "workflow")
|
137 |
-
timeline.append({"step": "Review", "description": "Code review and suggestions", "output": review, "code": refactored_code})
|
138 |
-
suggestions.append("Incorporate review feedback for cleaner, robust code.")
|
139 |
-
|
140 |
-
# Error detection & fixes
|
141 |
-
errors = error_detection_and_fixes(refactored_code, programming_language, skill_level, user_role, explanation_language)
|
142 |
-
timeline.append({"step": "Error Detection", "description": "Bugs, security, performance suggestions", "output": errors, "code": refactored_code})
|
143 |
-
suggestions.append("Apply fixes to improve code safety and performance.")
|
144 |
-
|
145 |
-
# Test generation
|
146 |
-
test_prompt = (
|
147 |
-
f"Write clear, effective unit tests for this {programming_language} code. "
|
148 |
-
f"Explain what each test does in {explanation_language}, for a {skill_level} {user_role}:\n\n{refactored_code}"
|
149 |
-
)
|
150 |
-
tests = blackbox_api_call(test_prompt)
|
151 |
-
add_to_blackbox_history(test_prompt, tests, "workflow")
|
152 |
-
timeline.append({"step": "Test Generation", "description": "Generated unit tests", "output": tests, "code": tests})
|
153 |
-
suggestions.append("Run generated tests locally to validate changes.")
|
154 |
-
|
155 |
-
return timeline, suggestions
|
156 |
-
|
157 |
-
def get_inline_diff_html(original, modified):
|
158 |
-
differ = difflib.HtmlDiff(tabsize=4, wrapcolumn=80)
|
159 |
-
html = differ.make_table(
|
160 |
-
original.splitlines(), modified.splitlines(),
|
161 |
-
"Original", "Refactored", context=True, numlines=2
|
162 |
-
)
|
163 |
-
return f'<div style="overflow-x:auto; max-height:400px;">{html}</div>'
|
164 |
-
|
165 |
-
def detect_code_type(code, programming_language):
|
166 |
-
backend_keywords = [
|
167 |
-
'flask', 'django', 'express', 'fastapi', 'spring', 'controller', 'api', 'server', 'database', 'sql', 'mongoose'
|
168 |
-
]
|
169 |
-
frontend_keywords = [
|
170 |
-
'react', 'vue', 'angular', 'component', 'html', 'css', 'document.getelementbyid', 'window.', 'render', 'jsx',
|
171 |
-
'<html', '<body', '<script', '<div', 'getelementbyid', 'queryselector', 'addeventlistener', 'innerhtml'
|
172 |
-
]
|
173 |
-
data_science_keywords = [
|
174 |
-
'pandas', 'numpy', 'sklearn', 'matplotlib', 'seaborn', 'plt', 'train_test_split', 'randomforestclassifier', 'classification_report'
|
175 |
-
]
|
176 |
-
code_lower = code.lower()
|
177 |
-
if any(word in code_lower for word in data_science_keywords):
|
178 |
-
return 'data_science'
|
179 |
-
if any(word in code_lower for word in frontend_keywords):
|
180 |
-
return 'frontend'
|
181 |
-
if programming_language.lower() in ['python', 'java', 'c#']:
|
182 |
-
if any(word in code_lower for word in backend_keywords):
|
183 |
-
return 'backend'
|
184 |
-
if programming_language.lower() in ['javascript', 'typescript', 'java', 'c#']:
|
185 |
-
if any(word in code_lower for word in frontend_keywords):
|
186 |
-
return 'frontend'
|
187 |
-
if programming_language.lower() in ['python', 'java', 'c#']:
|
188 |
-
return 'backend'
|
189 |
-
if programming_language.lower() in ['javascript', 'typescript']:
|
190 |
-
return 'frontend'
|
191 |
-
return 'unknown'
|
192 |
-
|
193 |
-
def code_complexity(code):
|
194 |
lines = code.count('\n') + 1
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
"python": [
|
205 |
-
"def ", "class ", "import ", "from ", "try:", "except", "raise", "lambda",
|
206 |
-
"with ", "yield", "async ", "await ", "print(", "self.", "__init__", "__name__",
|
207 |
-
"if __name__ == '__main__':", "#!",
|
208 |
-
],
|
209 |
-
"c++": [
|
210 |
-
"#include", "int main(", "std::", "::", "cout <<", "cin >>", "new ", "delete ",
|
211 |
-
"try {", "catch(", "template<", "using namespace", "class ", "struct ", "#define",
|
212 |
-
],
|
213 |
-
"java": [
|
214 |
-
"package ", "import java.", "public class", "private ", "protected ", "public static void main",
|
215 |
-
"System.out.println", "try {", "catch(", "throw new ", "implements ", "extends ",
|
216 |
-
"@Override", "interface ", "enum ", "synchronized ", "final ",
|
217 |
-
],
|
218 |
-
"c#": [
|
219 |
-
"using System", "namespace ", "class ", "interface ", "public static void Main",
|
220 |
-
"Console.WriteLine", "try {", "catch(", "throw ", "async ", "await ", "get;", "set;",
|
221 |
-
"List<", "Dictionary<", "[Serializable]", "[Obsolete]",
|
222 |
-
],
|
223 |
-
"javascript": [
|
224 |
-
"function ", "const ", "let ", "var ", "document.", "window.", "console.log",
|
225 |
-
"if(", "for(", "while(", "switch(", "try {", "catch(", "export ", "import ", "async ",
|
226 |
-
"await ", "=>", "this.", "class ", "prototype", "new ", "$(",
|
227 |
-
],
|
228 |
-
"typescript": [
|
229 |
-
"function ", "const ", "let ", "interface ", "type ", ": string", ": number", ": boolean",
|
230 |
-
"implements ", "extends ", "enum ", "public ", "private ", "protected ", "readonly ",
|
231 |
-
"import ", "export ", "console.log", "async ", "await ", "=>", "this.",
|
232 |
-
],
|
233 |
-
"html": [
|
234 |
-
"<!doctype html", "<html", "<head>", "<body>", "<script", "<style", "<meta ", "<link ",
|
235 |
-
"<title>", "<div", "<span", "<p>", "<h1>", "<ul>", "<li>", "<form", "<input", "<button",
|
236 |
-
"<table", "<footer", "<header", "<section", "<article", "<nav", "<img", "<a ", "</html>",
|
237 |
-
],
|
238 |
-
}
|
239 |
-
match_patterns = patterns.get(language, [])
|
240 |
-
match_count = sum(1 for pattern in match_patterns if pattern in code_lower)
|
241 |
-
return match_count >= 1
|
242 |
-
|
243 |
-
# --- Chat History ---
|
244 |
-
if 'blackbox_chat_history' not in st.session_state:
|
245 |
-
st.session_state['blackbox_chat_history'] = []
|
246 |
-
|
247 |
-
def add_to_blackbox_history(prompt, response, mode):
|
248 |
-
st.session_state['blackbox_chat_history'].append({
|
249 |
-
'mode': mode, # 'workflow' or 'semantic_search'
|
250 |
-
'prompt': prompt,
|
251 |
-
'response': response
|
252 |
-
})
|
253 |
-
|
254 |
-
def show_blackbox_history():
|
255 |
-
st.sidebar.markdown('---')
|
256 |
-
st.sidebar.subheader('🕑 Blackbox Agent Chat History')
|
257 |
-
if not st.session_state['blackbox_chat_history']:
|
258 |
-
st.sidebar.info('No chat history this session.')
|
259 |
-
else:
|
260 |
-
for i, entry in enumerate(reversed(st.session_state['blackbox_chat_history'])):
|
261 |
-
with st.sidebar.expander(f"{entry['mode'].replace('_', ' ').title()} #{len(st.session_state['blackbox_chat_history'])-i}"):
|
262 |
-
st.markdown(f"**Prompt:**\n{entry['prompt']}")
|
263 |
-
st.markdown(f"**Response:**\n{entry['response']}")
|
264 |
-
|
265 |
-
# --- Page config ---
|
266 |
-
st.set_page_config(page_title="🚀 AI Assistant with Workflow + Semantic Search", layout="wide")
|
267 |
-
|
268 |
-
# --- Sidebar ---
|
269 |
-
st.sidebar.title("🔧 Configuration")
|
270 |
-
lang = st.sidebar.selectbox("Programming Language", ["Python", "JavaScript", "C++", "Java", "C#", "TypeScript"])
|
271 |
-
skill = st.sidebar.selectbox("Skill Level", ["Beginner", "Intermediate", "Expert"])
|
272 |
-
role = st.sidebar.selectbox("Your Role", ["Student", "Frontend Developer", "Backend Developer", "Data Scientist"])
|
273 |
-
explain_lang = st.sidebar.selectbox("Explanation Language", ["English", "Spanish", "Chinese", "Urdu"])
|
274 |
-
st.sidebar.markdown("---")
|
275 |
-
st.sidebar.markdown("<span style='color:#fff;'>Powered by <b>BLACKBOX.AI</b></span>", unsafe_allow_html=True)
|
276 |
-
|
277 |
-
# Show chat history in sidebar
|
278 |
-
show_blackbox_history()
|
279 |
-
|
280 |
-
# Download chat history
|
281 |
-
if st.session_state['blackbox_chat_history']:
|
282 |
-
chat_history_text = ""
|
283 |
-
for entry in st.session_state['blackbox_chat_history']:
|
284 |
-
chat_history_text += f"Mode: {entry['mode']}\nPrompt: {entry['prompt']}\nResponse: {entry['response']}\n\n"
|
285 |
-
st.sidebar.download_button(
|
286 |
-
label="Download Chat History",
|
287 |
-
data=chat_history_text,
|
288 |
-
file_name="blackbox_chat_history.txt",
|
289 |
-
mime="text/plain"
|
290 |
-
)
|
291 |
-
|
292 |
-
tabs = st.tabs(["🧠 Full AI Workflow", "🔍 Semantic Search"])
|
293 |
-
|
294 |
-
# --- Tab 1: Full AI Workflow ---
|
295 |
-
with tabs[0]:
|
296 |
-
st.title("🧠 Full AI Workflow")
|
297 |
-
file_types = {
|
298 |
-
"Python": ["py"],
|
299 |
-
"JavaScript": ["js"],
|
300 |
-
"C++": ["cpp", "h", "hpp"],
|
301 |
-
"Java": ["java"],
|
302 |
-
"C#": ["cs"],
|
303 |
-
"TypeScript": ["ts"],
|
304 |
-
}
|
305 |
-
|
306 |
-
uploaded_file = st.file_uploader(
|
307 |
-
f"Upload {', '.join(file_types.get(lang, []))} file(s)",
|
308 |
-
type=file_types.get(lang, None)
|
309 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
310 |
if uploaded_file:
|
311 |
code_input = uploaded_file.read().decode("utf-8")
|
312 |
-
|
313 |
-
|
314 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
315 |
if code_input:
|
316 |
-
st.
|
317 |
-
|
318 |
-
if st.button("Run AI Workflow"):
|
319 |
if not code_input.strip():
|
320 |
-
st.
|
321 |
-
elif not code_matches_language(code_input,
|
322 |
-
st.error(f"
|
323 |
-
else:
|
324 |
-
|
325 |
-
|
326 |
-
|
327 |
-
|
328 |
-
|
329 |
-
|
330 |
-
|
331 |
-
|
332 |
-
|
333 |
-
|
334 |
-
|
335 |
-
|
336 |
-
|
337 |
-
|
338 |
-
|
339 |
-
|
340 |
-
|
341 |
-
|
342 |
-
|
343 |
-
|
344 |
-
|
345 |
-
|
346 |
-
for
|
347 |
-
|
348 |
-
|
349 |
-
|
350 |
-
|
351 |
-
|
352 |
-
|
353 |
-
|
354 |
-
|
355 |
-
|
356 |
-
|
357 |
-
|
358 |
-
|
359 |
-
|
360 |
-
|
361 |
-
|
362 |
-
|
363 |
-
|
364 |
-
|
365 |
-
|
366 |
-
st.
|
367 |
-
|
368 |
-
|
369 |
if st.button("Run Semantic Search"):
|
370 |
-
if not
|
371 |
-
st.
|
|
|
|
|
372 |
else:
|
373 |
-
with st.spinner("Running
|
374 |
-
answer =
|
375 |
-
st.
|
376 |
-
st.
|
377 |
-
|
378 |
-
st.markdown("---")
|
|
|
1 |
import streamlit as st
|
2 |
import difflib
|
|
|
|
|
3 |
import requests
|
4 |
+
import datetime
|
5 |
+
|
6 |
+
# --- CONFIG ---
|
7 |
+
# Place your API keys here or use Streamlit secrets
|
8 |
+
GROQ_API_KEY = st.secrets.get('GROQ_API_KEY', 'YOUR_GROQ_API_KEY')
|
9 |
+
BLACKBOX_API_KEY = st.secrets.get('BLACKBOX_API_KEY', 'YOUR_BLACKBOX_API_KEY')
|
10 |
+
|
11 |
+
PROGRAMMING_LANGUAGES = ["Python", "JavaScript", "TypeScript", "Java", "C++", "C#"]
|
12 |
+
SKILL_LEVELS = ["Beginner", "Intermediate", "Expert"]
|
13 |
+
USER_ROLES = ["Student", "Frontend Developer", "Backend Developer", "Data Scientist"]
|
14 |
+
EXPLANATION_LANGUAGES = ["English", "Spanish", "Chinese", "Urdu"]
|
15 |
+
EXAMPLE_QUESTIONS = [
|
16 |
+
"What does this function do?",
|
17 |
+
"How can I optimize this code?",
|
18 |
+
"What are the potential bugs in this code?",
|
19 |
+
"How does this algorithm work?",
|
20 |
+
"What design patterns are used here?",
|
21 |
+
"How can I make this code more readable?"
|
22 |
+
]
|
23 |
+
|
24 |
+
# --- API CALLS ---
|
25 |
+
def call_groq_api(prompt, model="llama3-70b-8192"):
|
26 |
+
headers = {"Authorization": f"Bearer {GROQ_API_KEY}", "Content-Type": "application/json"}
|
27 |
+
data = {"model": model, "messages": [{"role": "user", "content": prompt}]}
|
28 |
+
response = requests.post("https://api.groq.com/openai/v1/chat/completions", json=data, headers=headers)
|
29 |
+
if response.status_code == 200:
|
30 |
+
return response.json()['choices'][0]['message']['content']
|
31 |
+
else:
|
32 |
+
return f"[Groq API Error] {response.text}"
|
33 |
|
34 |
+
def call_blackbox_agent(prompt):
|
35 |
+
url = "https://api.blackboxai.dev/chat"
|
36 |
headers = {
|
37 |
"Content-Type": "application/json",
|
38 |
+
"Authorization": f"Bearer {BLACKBOX_API_KEY}"
|
39 |
}
|
40 |
data = {
|
41 |
+
"message": prompt
|
|
|
|
|
|
|
|
|
|
|
42 |
}
|
43 |
+
response = requests.post(url, headers=headers, json=data)
|
44 |
if response.status_code == 200:
|
45 |
+
# Adjust this if the response structure is different
|
46 |
+
return response.json().get("response", response.json())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
47 |
else:
|
48 |
+
return f"[Blackbox.ai API Error] {response.status_code}: {response.text}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
49 |
|
50 |
+
# --- UTILS ---
|
51 |
+
def code_matches_language(code, language):
|
52 |
+
# Simple heuristic, can be improved
|
53 |
+
if language.lower() in code.lower():
|
54 |
+
return True
|
55 |
+
return True # For demo, always True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
56 |
|
57 |
+
def calculate_code_complexity(code):
|
58 |
+
# Dummy complexity metric
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
59 |
lines = code.count('\n') + 1
|
60 |
+
return f"{lines} lines"
|
61 |
+
|
62 |
+
def get_inline_diff(original, modified):
|
63 |
+
diff = difflib.unified_diff(
|
64 |
+
original.splitlines(),
|
65 |
+
modified.splitlines(),
|
66 |
+
lineterm='',
|
67 |
+
fromfile='Original',
|
68 |
+
tofile='Refactored'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
69 |
)
|
70 |
+
return '\n'.join(diff)
|
71 |
+
|
72 |
+
# --- STREAMLIT APP ---
|
73 |
+
st.set_page_config(page_title="AI Workflow App", layout="wide")
|
74 |
+
st.title("AI Assistant with Workflow (Streamlit Edition)")
|
75 |
+
|
76 |
+
# Navigation
|
77 |
+
page = st.sidebar.radio("Navigate", ["Home", "AI Workflow", "Semantic Search"])
|
78 |
+
|
79 |
+
if page == "Home":
|
80 |
+
st.header("Welcome to the AI Assistant!")
|
81 |
+
st.markdown("""
|
82 |
+
- **Full AI Workflow:** Complete code analysis pipeline with explanation, refactoring, review, and testing (powered by Groq/Blackbox)
|
83 |
+
- **Semantic Search:** Ask natural language questions about your code and get intelligent answers
|
84 |
+
""")
|
85 |
+
st.info("Select a feature from the sidebar to get started.")
|
86 |
+
|
87 |
+
elif page == "AI Workflow":
|
88 |
+
st.header("Full AI Workflow")
|
89 |
+
code_input = st.text_area("Paste your code here", height=200)
|
90 |
+
uploaded_file = st.file_uploader("Or upload a code file", type=["py", "js", "ts", "java", "cpp", "cs"])
|
91 |
if uploaded_file:
|
92 |
code_input = uploaded_file.read().decode("utf-8")
|
93 |
+
st.text_area("File content", code_input, height=200, key="file_content")
|
94 |
+
col1, col2, col3, col4 = st.columns(4)
|
95 |
+
with col1:
|
96 |
+
programming_language = st.selectbox("Programming Language", PROGRAMMING_LANGUAGES)
|
97 |
+
with col2:
|
98 |
+
skill_level = st.selectbox("Skill Level", SKILL_LEVELS)
|
99 |
+
with col3:
|
100 |
+
user_role = st.selectbox("Your Role", USER_ROLES)
|
101 |
+
with col4:
|
102 |
+
explanation_language = st.selectbox("Explanation Language", EXPLANATION_LANGUAGES)
|
103 |
if code_input:
|
104 |
+
st.caption(f"Complexity: {calculate_code_complexity(code_input)}")
|
105 |
+
if st.button("Run Workflow", type="primary"):
|
|
|
106 |
if not code_input.strip():
|
107 |
+
st.error("Please paste or upload your code.")
|
108 |
+
elif not code_matches_language(code_input, programming_language):
|
109 |
+
st.error(f"Language mismatch. Please check your code and language selection.")
|
110 |
+
else:
|
111 |
+
with st.spinner("Running AI Workflow..."):
|
112 |
+
# Simulate workflow steps
|
113 |
+
steps = [
|
114 |
+
("Explain", call_groq_api(f"Explain this {programming_language} code for a {skill_level} {user_role} in {explanation_language}:\n{code_input}")),
|
115 |
+
("Refactor", call_blackbox_agent(f"Refactor this {programming_language} code: {code_input}")),
|
116 |
+
("Review", call_groq_api(f"Review this {programming_language} code for errors and improvements: {code_input}")),
|
117 |
+
("ErrorDetection", call_groq_api(f"Find bugs in this {programming_language} code: {code_input}")),
|
118 |
+
("TestGeneration", call_groq_api(f"Generate tests for this {programming_language} code: {code_input}")),
|
119 |
+
]
|
120 |
+
timeline = []
|
121 |
+
for step, output in steps:
|
122 |
+
timeline.append({"step": step, "output": output})
|
123 |
+
st.success("Workflow complete!")
|
124 |
+
for t in timeline:
|
125 |
+
st.subheader(t["step"])
|
126 |
+
st.write(t["output"])
|
127 |
+
# Show code diff (Original vs Refactored)
|
128 |
+
st.subheader("Code Diff (Original vs Refactored)")
|
129 |
+
refactored_code = steps[1][1] # Blackbox agent output
|
130 |
+
st.code(get_inline_diff(code_input, refactored_code), language=programming_language.lower())
|
131 |
+
# Download report
|
132 |
+
report = f"AI Workflow Report\nGenerated on: {datetime.datetime.now()}\nLanguage: {programming_language}\nSkill Level: {skill_level}\nRole: {user_role}\n\n"
|
133 |
+
for t in timeline:
|
134 |
+
report += f"## {t['step']}\n{t['output']}\n\n---\n\n"
|
135 |
+
st.download_button("Download Report", report, file_name="ai_workflow_report.txt")
|
136 |
+
|
137 |
+
elif page == "Semantic Search":
|
138 |
+
st.header("Semantic Search")
|
139 |
+
code_input = st.text_area("Paste your code here", height=200, key="sem_code")
|
140 |
+
uploaded_file = st.file_uploader("Or upload a code file", type=["py", "js", "ts", "java", "cpp", "cs"], key="sem_file")
|
141 |
+
if uploaded_file:
|
142 |
+
code_input = uploaded_file.read().decode("utf-8")
|
143 |
+
st.text_area("File content", code_input, height=200, key="sem_file_content")
|
144 |
+
col1, col2, col3, col4 = st.columns(4)
|
145 |
+
with col1:
|
146 |
+
programming_language = st.selectbox("Programming Language", PROGRAMMING_LANGUAGES, key="sem_lang")
|
147 |
+
with col2:
|
148 |
+
skill_level = st.selectbox("Skill Level", SKILL_LEVELS, key="sem_skill")
|
149 |
+
with col3:
|
150 |
+
user_role = st.selectbox("Your Role", USER_ROLES, key="sem_role")
|
151 |
+
with col4:
|
152 |
+
explanation_language = st.selectbox("Explanation Language", EXPLANATION_LANGUAGES, key="sem_expl")
|
153 |
+
question = st.text_input("Ask a question about your code")
|
154 |
+
st.caption("Example questions:")
|
155 |
+
st.write(", ".join(EXAMPLE_QUESTIONS))
|
156 |
if st.button("Run Semantic Search"):
|
157 |
+
if not code_input.strip() or not question.strip():
|
158 |
+
st.error("Both code and question are required.")
|
159 |
+
elif not code_matches_language(code_input, programming_language):
|
160 |
+
st.error(f"Language mismatch. Please check your code and language selection.")
|
161 |
else:
|
162 |
+
with st.spinner("Running Semantic Search..."):
|
163 |
+
answer = call_groq_api(f"{question}\n\nCode:\n{code_input}")
|
164 |
+
st.success("Answer:")
|
165 |
+
st.write(answer)
|
|
|
|