CoolFace
Apppublic

EnDevSols/Coding_Assistant

sourceHugging Faceupdated 3y agoView on Hugging Face
0likes
app.py128 linesDownload Raw Back to root
1import streamlit as st2import os3import pickle4import time5import g4f6 7st.set_page_config(page_title="CODING ASSISTANT")8 9st.markdown(10    """11    <style>12        .title {13            text-align: center;14            font-size: 2em;15            font-weight: bold;16        }17    </style>18    <div class="title"> ๐Ÿ‘จโ€๐Ÿ’ป CODING ASSISTANT โš–</div>19    """,20    unsafe_allow_html=True21)22# Load and Save Conversations23conversations_file = "conversations.pkl"24 25 26@st.cache_data27def load_conversations():28    try:29        with open(conversations_file, "rb") as f:30            return pickle.load(f)31    except (FileNotFoundError, EOFError):32        return []33 34 35def save_conversations(conversations):36    temp_conversations_file = conversations_file37    with open(temp_conversations_file, "wb") as f:38        pickle.dump(conversations, f)39    os.replace(temp_conversations_file, conversations_file)40 41 42if 'conversations' not in st.session_state:43    st.session_state.conversations = load_conversations()44 45if 'current_conversation' not in st.session_state:46    st.session_state.current_conversation = [{"role": "assistant", "content": "How may I assist you today?"}]47 48 49def truncate_string(s, length=30):50    return s[:length].rstrip() + "..." if len(s) > length else s51 52 53def display_chats_sidebar():54    with st.sidebar.container():55        st.header('Settings')56        col1, col2 = st.columns([1, 1])57 58        with col1:59            if col1.button('Start New Chat', key="new_chat"):60                st.session_state.current_conversation = []61                st.session_state.conversations.append(st.session_state.current_conversation)62 63        with col2:64            if col2.button('Clear All Chats', key="clear_all"):65                st.session_state.conversations = []66                st.session_state.current_conversation = []67 68 69    with st.sidebar.container():70        st.header('Conversations')71        for idx, conversation in enumerate(st.session_state.conversations):72            if conversation:73                chat_title_raw = next((msg["content"] for msg in conversation if msg["role"] == "user"), "New Chat")74                chat_title = truncate_string(chat_title_raw)75                if st.sidebar.button(f"{chat_title}", key=f"chat_button_{idx}"):76                    st.session_state.current_conversation = st.session_state.conversations[idx]77 78 79 80def main_app():81    for message in st.session_state.current_conversation:82        with st.chat_message(message["role"]):83            st.write(message["content"])84 85    def generate_response(prompt_input):86        string_dialogue = '''87        You are a virtual coding assistant, specialized in providing help with programming languages, software development concepts,88        debugging tips, and code optimization strategies. Your expertise covers a wide range of programming languages including but not 89        limited to Python, JavaScript, Java, C++, and HTML/CSS. You can assist with understanding programming concepts, syntax, algorithms,90        and best practices. You also offer guidance on troubleshooting and debugging code, as well as improving code efficiency and readability.91 92        Please note that your role is to assist with coding-related inquiries only. You do not engage in non-programming related discussions or provide personal opinions on matters outside of software development.93        94        Human:95        '''96        for dict_message in st.session_state.current_conversation:97            string_dialogue += dict_message["role"].capitalize() + ": " + dict_message["content"] + "\\n\\n"98 99        prompt = f"{string_dialogue}\n  {prompt_input} Assistant: "100        response_generator = g4f.ChatCompletion.create(101            model="gpt-3.5-turbo",102            messages=[{"role": "user", "content": prompt}],103            stream=True,104        )105        return response_generator106 107    if prompt := st.chat_input('Send a Message'):108        st.session_state.current_conversation.append({"role": "user", "content": prompt})109        with st.chat_message("user"):110            st.write(prompt)111 112        with st.chat_message("assistant"):113            with st.spinner("Thinking..."):114                response = generate_response(prompt)115                placeholder = st.empty()116                full_response = ''117                for item in response:118                    full_response += item119                    time.sleep(0.003)120                    placeholder.markdown(full_response)121                placeholder.markdown(full_response)122                st.session_state.current_conversation.append({"role": "assistant", "content": full_response})123                save_conversations(st.session_state.conversations)124 125 126display_chats_sidebar()127main_app()128