Team Ai
Apppublic

kingvicky25/StarCoder_GenAI_Coder

sourceHugging Faceapache-2.0updated 9mo agoView on Hugging Face
1likes
streamlit_app.py117 linesDownload Raw Back to src
1import streamlit as st2import pinecone3import os4import subprocess5import json6import requests7from pinecone import Pinecone, ServerlessSpec8#from streamlit_extras.add_vertical_space import add_vertical_space9 10# Set page config11st.set_page_config(page_title="StarCoder AI Code Generator", page_icon="๐Ÿค–", layout="wide")12 13# Custom CSS for Grok-like UI14st.markdown("""15    <style>16        body {background-color: #121212; color: white;}17        .stApp {background: #181818; color: white; font-family: 'Arial', sans-serif;}18        .stTextArea textarea {background: #282828; color: white; border-radius: 10px;}19        .stTextInput input {background: #282828; color: white; border-radius: 10px;}20        .stButton>button {background: #3f51b5; color: white; border-radius: 8px; padding: 10px;}21        .stDownloadButton>button {background: #4caf50; color: white; border-radius: 8px; padding: 10px;}22        .stCode {background: #202020; padding: 15px; border-radius: 10px;}23        .stSidebar {background: #202020; color: white;}24        .stSidebar .stButton>button {background: #ff9800; color: white;}25    </style>26""", unsafe_allow_html=True)27 28# Pinecone API Key29PINECONE_API_KEY = "your pinecone api key here"30pc = Pinecone(api_key=PINECONE_API_KEY)31INDEX_NAME = "code-gen"32if INDEX_NAME not in pc.list_indexes().names():33    pc.create_index(name=INDEX_NAME, dimension=1536, metric='euclidean',34                    spec=ServerlessSpec(cloud='aws', region='us-east-1'))35index = pc.Index(INDEX_NAME)36 37# Hugging Face API Key38HUGGINGFACE_API_KEY = "your huggingface api key"39 40# Initialize session state41if "chat_history" not in st.session_state:42    st.session_state.chat_history = []43if "current_chat" not in st.session_state:44    st.session_state.current_chat = []45 46 47def new_chat():48    if st.session_state.current_chat:49        st.session_state.chat_history.append(st.session_state.current_chat)50    st.session_state.current_chat = []51 52 53# Sidebar - Chat History54st.sidebar.title("๐Ÿ’ฌ Chat History")55for i, chat in enumerate(st.session_state.chat_history):56    if st.sidebar.button(f"Chat {i + 1} ๐Ÿ•’"):57        st.session_state.current_chat = chat58 59# Sidebar - New Chat Button60if st.sidebar.button("New Chat โž•"):61    new_chat()62 63 64# Function to query Hugging Face model65def generate_code(prompt, examples=[]):66    formatted_prompt = "".join(examples) + "\n" + prompt67    headers = {"Authorization": f"Bearer {HUGGINGFACE_API_KEY}"}68    data = {"inputs": formatted_prompt, "parameters": {"temperature": 0.5, "max_length": 512}}69    response = requests.post("https://api-inference.huggingface.co/models/bigcode/starcoder2-15b", headers=headers,70                             json=data)71    return response.json()[0][72        'generated_text'].strip() if response.status_code == 200 else "Error: Unable to generate code"73 74 75def execute_python_code(code):76    try:77        result = subprocess.run(["python", "-c", code], capture_output=True, text=True, timeout=5)78        return result.stdout if result.returncode == 0 else result.stderr79    except Exception as e:80        return str(e)81 82 83def store_in_pinecone(prompt, code):84    vector = [0.1] * 1536  # Placeholder vector85    index.upsert([(prompt, vector, {"code": code})])86 87 88def retrieve_from_pinecone(prompt):89    response = index.query(vector=[0.1] * 1536, top_k=2, include_metadata=True)90    return [r["metadata"]["code"] for r in response["matches"]]91 92 93# Main UI94st.title("๐Ÿค– StarCoder AI Code Generator")95 96# User Input97prompt = st.text_area("โœ๏ธ Enter your prompt:", height=100)98mode = st.selectbox("โšก Choose prompting mode", ["One-shot", "Two-shot"])99 100generate_button = st.button("๐Ÿš€ Generate Code")101 102if generate_button and prompt:103    examples = retrieve_from_pinecone(prompt) if mode == "Two-shot" else []104    generated_code = generate_code(prompt, examples)105    st.session_state.current_chat.append((prompt, generated_code))106    st.subheader("๐Ÿ“œ Generated Code")107    st.code(generated_code, language="python")108    store_in_pinecone(prompt, generated_code)109 110    execute_button = st.button("โ–ถ๏ธ Run Code")111    if execute_button:112        execution_result = execute_python_code(generated_code)113        st.subheader("๐Ÿ–ฅ๏ธ Execution Output")114        st.text(execution_result)115 116    st.download_button("๐Ÿ“ฅ Download Code", generated_code, file_name="generated_code.py")117