kingvicky25 commited on
Commit
a675706
Β·
verified Β·
1 Parent(s): 84ffab2

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +114 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,116 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ import pinecone
3
+ import os
4
+ import subprocess
5
+ import json
6
+ import requests
7
+ from pinecone import Pinecone, ServerlessSpec
8
+ #from streamlit_extras.add_vertical_space import add_vertical_space
9
 
10
+ # Set page config
11
+ st.set_page_config(page_title="StarCoder AI Code Generator", page_icon="πŸ€–", layout="wide")
12
+
13
+ # Custom CSS for Grok-like UI
14
+ st.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 Key
29
+ PINECONE_API_KEY = "your pinecone api key here"
30
+ pc = Pinecone(api_key=PINECONE_API_KEY)
31
+ INDEX_NAME = "code-gen"
32
+ if 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'))
35
+ index = pc.Index(INDEX_NAME)
36
+
37
+ # Hugging Face API Key
38
+ HUGGINGFACE_API_KEY = "your huggingface api key"
39
+
40
+ # Initialize session state
41
+ if "chat_history" not in st.session_state:
42
+ st.session_state.chat_history = []
43
+ if "current_chat" not in st.session_state:
44
+ st.session_state.current_chat = []
45
+
46
+
47
+ def 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 History
54
+ st.sidebar.title("πŸ’¬ Chat History")
55
+ for i, chat in enumerate(st.session_state.chat_history):
56
+ if st.sidebar.button(f"Chat {i + 1} πŸ•’"):
57
+ st.session_state.current_chat = chat
58
+
59
+ # Sidebar - New Chat Button
60
+ if st.sidebar.button("New Chat βž•"):
61
+ new_chat()
62
+
63
+
64
+ # Function to query Hugging Face model
65
+ def generate_code(prompt, examples=[]):
66
+ formatted_prompt = "".join(examples) + "\n" + prompt
67
+ 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
+
75
+ def 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.stderr
79
+ except Exception as e:
80
+ return str(e)
81
+
82
+
83
+ def store_in_pinecone(prompt, code):
84
+ vector = [0.1] * 1536 # Placeholder vector
85
+ index.upsert([(prompt, vector, {"code": code})])
86
+
87
+
88
+ def 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 UI
94
+ st.title("πŸ€– StarCoder AI Code Generator")
95
+
96
+ # User Input
97
+ prompt = st.text_area("✍️ Enter your prompt:", height=100)
98
+ mode = st.selectbox("⚑ Choose prompting mode", ["One-shot", "Two-shot"])
99
+
100
+ generate_button = st.button("πŸš€ Generate Code")
101
+
102
+ if 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")