Team Ai
Apppublic

Naz786/Smart-AI-Code-Assistant

sourceHugging Faceupdated 1y agoView on Hugging Face
2likes
app.py334 linesDownload Raw Back to root
1import streamlit as st2import difflib3import re4import requests5import datetime6import streamlit.components.v1 as components7 8# --- CONFIG ---9# Place your API keys here10GROQ_API_KEY = st.secrets.get('GROQ_API_KEY', 'YOUR_GROQ_API_KEY')11BLACKBOX_API_KEY = st.secrets.get('BLACKBOX_API_KEY', 'YOUR_BLACKBOX_API_KEY')12 13PROGRAMMING_LANGUAGES = ["Python", "JavaScript", "TypeScript", "Java", "C++", "C#"]14SKILL_LEVELS = ["Beginner", "Intermediate", "Expert"]15USER_ROLES = ["Student", "Frontend Developer", "Backend Developer", "Data Scientist"]16EXPLANATION_LANGUAGES = ["English", "Spanish", "Chinese", "Urdu"]17EXAMPLE_QUESTIONS = [18    "What does this function do?",19    "How can I optimize this code?",20    "What are the potential bugs in this code?",21    "How does this algorithm work?",22    "What design patterns are used here?",23    "How can I make this code more readable?"24]25 26LANGUAGE_KEYWORDS = {27    "Python": ["def ", "import ", "self", "print(", "lambda", "None"],28    "JavaScript": ["function ", "console.log", "var ", "let ", "const ", "=>"],29    "TypeScript": ["interface ", "type ", ": string", ": number", "export ", "import "],30    "Java": ["public class", "System.out.println", "void main", "import java.", "new "],31    "C++": ["#include", "std::", "cout <<", "cin >>", "int main(", "using namespace"],32    "C#": ["using System;", "namespace ", "public class", "Console.WriteLine", "static void Main"]33}34 35# --- API STUBS ---36def call_groq_api(prompt, model="llama3-70b-8192"):37    # Replace with actual Groq API call38    headers = {"Authorization": f"Bearer {GROQ_API_KEY}", "Content-Type": "application/json"}39    data = {"model": model, "messages": [{"role": "user", "content": prompt}]}40    response = requests.post("https://api.groq.com/openai/v1/chat/completions", json=data, headers=headers)41    if response.status_code == 200:42        return response.json()['choices'][0]['message']['content']43    else:44        return f"[Groq API Error] {response.text}"45 46def call_blackbox_agent(messages):47    url = "https://api.blackbox.ai/v1/chat/completions"48    headers = {49        "Content-Type": "application/json",50        "Authorization": f"Bearer {BLACKBOX_API_KEY}"51    }52    data = {53        "model": "code-chat",54        "messages": messages55    }56    response = requests.post(url, headers=headers, json=data)57    if response.status_code == 200:58        return response.json()["choices"][0]["message"]["content"]59    else:60        return call_groq_api(messages[-1]["content"])61 62# --- UTILS ---63def code_matches_language(code, language):64    keywords = LANGUAGE_KEYWORDS.get(language, [])65    return any(kw in code for kw in keywords)66 67def calculate_code_complexity(code):68    # Dummy complexity metric69    lines = code.count('\n') + 170    return f"{lines} lines"71 72def get_inline_diff(original, modified):73    diff = difflib.unified_diff(74        original.splitlines(),75        modified.splitlines(),76        lineterm='',77        fromfile='Original',78        tofile='Refactored'79    )80    return '\n'.join(diff)81 82def is_coding_question(question):83    """84    Uses Blackbox AI agent to check if the question is about programming/code.85    Returns True if yes, False otherwise.86    """87    messages = [88        {"role": "system", "content": "You are a helpful coding assistant."},89        {"role": "user", "content": f"Is the following question about programming or code? Answer only 'yes' or 'no'. Question: {question}"}90    ]91    try:92        response = call_blackbox_agent(messages)93        return 'yes' in response.lower()94    except Exception:95        return False96 97def get_explanation_prompt(code, programming_language, skill_level, user_role, explanation_language, question=None):98    lang_instruction = f" Respond in {explanation_language}." if explanation_language != "English" else ""99    if question:100        return f"{question}\n\nCode:\n{code}\n{lang_instruction}"101    return (102        f"Explain this {programming_language} code for a {skill_level} {user_role}.{lang_instruction}\n{code}"103    )104 105# --- SESSION STATE FOR CHAT HISTORY ---106if "workflow_history" not in st.session_state:107    st.session_state.workflow_history = []108if "semantic_history" not in st.session_state:109    st.session_state.semantic_history = []110if "comment_history" not in st.session_state:111    st.session_state.comment_history = []112 113# --- STREAMLIT APP ---114st.set_page_config(page_title="Code Workflows", layout="wide")115st.title("Code Genie")116 117# Navigation118page = st.sidebar.radio("Navigate", ["Home", "Code Workflows", "Semantic Search", "Code Comment Generator"])119 120if page == "Home":121    st.header("Welcome to the Code Genie!")122    st.markdown("""123    - **Full Code Workflow:** Complete code analysis pipeline with explanation, refactoring, review, and testing (powered by Groq/Blackbox)124    - **Semantic Search:** Ask natural language questions about your code and get intelligent answers125    - **Code Comment Generator:** Helps you add helpful comments to your code for better readability126    """)127    st.info("Select a feature from the sidebar to get started.")128 129elif page == "Code Workflows":130    st.header("Full Code Workflows")131    code_input = st.text_area("Paste your code here", height=200)132    uploaded_file = st.file_uploader("Or upload a code file", type=["py", "js", "ts", "java", "cpp", "cs"])133    if uploaded_file:134        code_input = uploaded_file.read().decode("utf-8")135        st.text_area("File content", code_input, height=200, key="file_content")136    col1, col2, col3, col4 = st.columns(4)137    with col1:138        programming_language = st.selectbox("Programming Language", PROGRAMMING_LANGUAGES)139    with col2:140        skill_level = st.selectbox("Skill Level", SKILL_LEVELS)141    with col3:142        user_role = st.selectbox("Your Role", USER_ROLES)143    with col4:144        explanation_language = st.selectbox("Explanation Language", EXPLANATION_LANGUAGES)145    if code_input:146        st.caption(f"Complexity: {calculate_code_complexity(code_input)}")147    if st.button("Run Workflow", type="primary"):148        if not code_input.strip():149            st.error("Please paste or upload your code.")150        elif not code_matches_language(code_input, programming_language):151            st.error(f"Language mismatch. Please check your code and language selection.")152        else:153            with st.spinner("Running AI Workflow..."):154                lang_instruction = f" Respond in {explanation_language}." if explanation_language != "English" else ""155                role_level_instruction = f" The user is a {skill_level} {user_role}."156                steps = [157                    ("Explain", call_groq_api(get_explanation_prompt(code_input, programming_language, skill_level, user_role, explanation_language))),158                    ("Refactor", call_blackbox_agent([159                        {"role": "system", "content": "You are a helpful coding assistant."},160                        {"role": "user", "content": f"Refactor this {programming_language} code for a {skill_level} {user_role}: {code_input}{lang_instruction}"}161                    ])),162                    ("Review", call_groq_api(f"Review this {programming_language} code for errors and improvements for a {skill_level} {user_role}: {code_input}{lang_instruction}")),163                    ("ErrorDetection", call_groq_api(f"Find bugs in this {programming_language} code for a {skill_level} {user_role}: {code_input}{lang_instruction}")),164                    ("TestGeneration", call_groq_api(f"Generate tests for this {programming_language} code for a {skill_level} {user_role}: {code_input}{lang_instruction}")),165                ]166                timeline = []167                for step, output in steps:168                    timeline.append({"step": step, "output": output})169                st.success("Workflow complete!")170                for t in timeline:171                    st.subheader(t["step"])172                    st.write(t["output"])173                # Show code diff (dummy for now)174                st.subheader("Code Diff (Original vs Refactored)")175                refactored_code = steps[1][1]  # Blackbox agent output176                st.code(get_inline_diff(code_input, refactored_code), language=programming_language.lower())177                # Download report178                report = f"AI Workflow Report\nGenerated on: {datetime.datetime.now()}\nLanguage: {programming_language}\nSkill Level: {skill_level}\nRole: {user_role}\n\n"179                for t in timeline:180                    report += f"## {t['step']}\n{t['output']}\n\n---\n\n"181                st.download_button("Download Report", report, file_name="ai_workflow_report.txt")182                # Save to chat history183                st.session_state.workflow_history.append({184                    "timestamp": str(datetime.datetime.now()),185                    "user_code": code_input,186                    "params": {187                        "language": programming_language,188                        "skill": skill_level,189                        "role": user_role,190                        "explanation_language": explanation_language191                    },192                    "timeline": timeline,193                    "refactored_code": refactored_code194                })195    # Show chat history for workflows196    st.markdown("### Workflow Chat History")197    if st.button("Clear Workflow History"):198        st.session_state.workflow_history = []199    for entry in reversed(st.session_state.workflow_history):200        st.markdown(f"**[{entry['timestamp']}]**")201        st.code(entry["user_code"], language=entry["params"]["language"].lower())202        for t in entry["timeline"]:203            st.subheader(t["step"])204            st.write(t["output"])205        st.subheader("Code Diff (Original vs Refactored)")206        st.code(get_inline_diff(entry["user_code"], entry["refactored_code"]), language=entry["params"]["language"].lower())207        st.markdown("---")208 209elif page == "Semantic Search":210    st.header("Semantic Search")211    code_input = st.text_area("Paste your code here", height=200, key="sem_code")212    uploaded_file = st.file_uploader("Or upload a code file", type=["py", "js", "ts", "java", "cpp", "cs"], key="sem_file")213    if uploaded_file:214        code_input = uploaded_file.read().decode("utf-8")215        st.text_area("File content", code_input, height=200, key="sem_file_content")216    col1, col2, col3, col4 = st.columns(4)217    with col1:218        programming_language = st.selectbox("Programming Language", PROGRAMMING_LANGUAGES, key="sem_lang")219    with col2:220        skill_level = st.selectbox("Skill Level", SKILL_LEVELS, key="sem_skill")221    with col3:222        user_role = st.selectbox("Your Role", USER_ROLES, key="sem_role")223    with col4:224        explanation_language = st.selectbox("Explanation Language", EXPLANATION_LANGUAGES, key="sem_expl")225 226    st.caption("Example questions:")227    st.write(", ".join(EXAMPLE_QUESTIONS))228 229    # Only text input for question230    question = st.text_input("Ask a question about your code", key="sem_question")231 232    # Run Semantic Search button233    if st.button("Run Semantic Search"):234        if not code_input.strip() or not question.strip():235            st.error("Both code and question are required.")236        elif not code_matches_language(code_input, programming_language):237            st.error(f"Language mismatch. Please check your code and language selection.")238        else:239            with st.spinner("Running Semantic Search..."):240                prompt = get_explanation_prompt(code_input, programming_language, skill_level, user_role, explanation_language, question=question)241                answer = call_groq_api(prompt)242                st.success("Answer:")243                st.write(answer)244                # Save to chat history245                st.session_state.semantic_history.append({246                    "timestamp": str(datetime.datetime.now()),247                    "user_code": code_input,248                    "question": question,249                    "params": {250                        "language": programming_language,251                        "skill": skill_level,252                        "role": user_role,253                        "explanation_language": explanation_language254                    },255                    "answer": answer256                })257    # Show chat history for semantic search258    st.markdown("### Semantic Search Chat History")259    if st.button("Clear Semantic History"):260        st.session_state.semantic_history = []261    for entry in reversed(st.session_state.semantic_history):262        st.markdown(f"**[{entry['timestamp']}]**")263        st.code(entry["user_code"], language=entry["params"]["language"].lower())264        st.markdown(f"**Q:** {entry['question']}")265        st.markdown(f"**A:** {entry['answer']}")266        st.markdown("---")267 268elif page == "Code Comment Generator":269    st.header("Code Comment Generator")270    code_input = st.text_area("Paste your code here", height=200, key="comment_code")271    uploaded_file = st.file_uploader("Or upload a code file", type=["py", "js", "ts", "java", "cpp", "cs"], key="comment_file")272    if uploaded_file:273        code_input = uploaded_file.read().decode("utf-8")274        st.text_area("File content", code_input, height=200, key="comment_file_content")275    programming_language = st.selectbox("Programming Language", PROGRAMMING_LANGUAGES, key="comment_lang")276    if st.button("Generate Comments"):277        if not code_input.strip():278            st.error("Please paste or upload your code.")279        elif not code_matches_language(code_input, programming_language):280            st.error(f"Language mismatch. Please check your code and language selection.")281        else:282            with st.spinner("Generating commented code..."):283                lang_instruction = f" Respond in {explanation_language}." if explanation_language != "English" else ""284                role_level_instruction = f" The user is a {skill_level} {user_role}."285                prompt = (286                    f"Add clear, helpful comments to this {programming_language} code for a {skill_level} {user_role}.{lang_instruction}\n\n"287                    f"{code_input}"288                )289                commented_code = call_blackbox_agent([290                    {"role": "system", "content": "You are a helpful coding assistant."},291                    {"role": "user", "content": prompt}292                ])293                st.success("Commented code generated!")294                st.code(commented_code, language=programming_language.lower())295                st.download_button("Download Commented Code", commented_code, file_name="commented_code.txt")296                # Save to chat history297                st.session_state.comment_history.append({298                    "timestamp": str(datetime.datetime.now()),299                    "user_code": code_input,300                    "params": {301                        "language": programming_language,302                        "skill": skill_level,303                        "role": user_role,304                        "explanation_language": explanation_language305                    },306                    "commented_code": commented_code307                })308    # Show chat history for code comments309    st.markdown("### Code Comment Chat History")310    if st.button("Clear Comment History"):311        st.session_state.comment_history = []312    for entry in reversed(st.session_state.comment_history):313        st.markdown(f"**[{entry['timestamp']}]**")314        st.code(entry["user_code"], language=entry["params"]["language"].lower())315        st.markdown("**Commented Code:**")316        st.code(entry["commented_code"], language=entry["params"]["language"].lower())317        st.markdown("---")318 319st.markdown("---")320 321 322def split_code_into_chunks(code, lang):323    if lang.lower() == "python":324        # Corrected regex pattern for Python code splitting325        pattern = r'(def\s+\w+\(.*?\):|class\s+\w+\(.*?\)?:)'326        splits = re.split(pattern, code)327        chunks = []328        for i in range(1, len(splits), 2):329            header = splits[i]330            body = splits[i+1] if (i+1) < len(splits) else ""331            chunks.append(header + body)332        return chunks if chunks else [code]333    else:334        return [code]