Haseeb-001 commited on
Commit
3602504
Β·
verified Β·
1 Parent(s): 21737f6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +167 -86
app.py CHANGED
@@ -1,124 +1,205 @@
1
  # app.py
2
  import os
3
  import time
 
 
 
4
  import streamlit as st
5
  from groq import Groq
6
  from streamlit_lottie import st_lottie
7
- import requests
8
- import json
9
- import base64
10
 
11
  # --- Constants ---
12
  PRIMARY_MODEL = "qwen-2.5-coder-32b"
13
- SUPPORTED_LANGUAGES = ["Python", "JavaScript", "Java", "C++", "Go", "Rust"]
14
- LOTTIE_URL = "https://assets3.lottiefiles.com/packages/lf20_hi95bvmx/ai.json"
 
 
 
 
 
 
 
 
 
 
 
15
 
16
- # --- Setup ---
17
  st.set_page_config(
18
  page_title="CodeForge AI",
19
- page_icon="πŸš€",
20
  layout="wide",
21
  initial_sidebar_state="expanded"
22
  )
23
 
24
- # --- Lottie Animation Loader ---
25
- def load_lottie(url):
26
- response = requests.get(url)
27
- return response.json() if response.status_code == 200 else None
28
-
29
  # --- Custom CSS ---
30
  def inject_css():
31
  st.markdown(f"""
32
  <style>
33
- .main {{
34
- background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
35
- color: #ffffff;
36
  }}
37
-
38
  .stTextInput input {{
 
39
  background: rgba(0,0,0,0.3) !important;
40
- border: 2px solid #4fffb0 !important;
41
- color: #4fffb0 !important;
42
  }}
43
-
44
- .code-editor {{
45
- border: 2px solid #4fffb0;
46
- border-radius: 15px;
47
- padding: 1rem;
48
- background: rgba(0,0,0,0.5) !important;
49
- }}
50
-
51
- .download-btn {{
52
- background: linear-gradient(45deg, #4fffb0, #2bd2ff) !important;
53
- color: #1a1a2e !important;
54
  border: none !important;
55
- border-radius: 25px;
56
- padding: 12px 24px;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
  }}
58
  </style>
59
  """, unsafe_allow_html=True)
60
 
61
- # --- File Download Generator ---
62
- def get_download_link(code, filename):
63
- b64 = base64.b64encode(code.encode()).decode()
64
- return f'<a href="data:file/txt;base64,{b64}" download="{filename}" class="download-btn">⬇️ Download {filename}</a>'
65
 
66
- # --- Model Client ---
67
- @st.cache_resource
68
- def init_groq():
69
- return Groq(api_key=os.environ.get("GROQ_API_KEY"))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
 
71
- # --- Code Generation Core ---
72
- def generate_code(client, query, lang):
73
- try:
74
- response = client.chat.completions.create(
75
- model=PRIMARY_MODEL,
76
- messages=[{
77
- "role": "user",
78
- "content": f"Generate {lang} code for: {query}. Include comments and error handling."
79
- }],
80
- temperature=0.7,
81
- max_tokens=4096
82
- )
83
- return response.choices[0].message.content
84
- except Exception as e:
85
- st.error(f"Error: {str(e)}")
86
- return None
87
 
88
- # --- Main UI ---
89
  def main():
90
- inject_css()
91
  client = init_groq()
 
92
 
93
- # --- Hero Section ---
94
- col1, col2 = st.columns([1, 2])
95
- with col1:
96
- lottie_anim = load_lottie(LOTTIE_URL)
97
- if lottie_anim:
98
- st_lottie(lottie_anim, height=150)
99
- with col2:
100
- st.markdown("# CodeForge AI")
101
- st.markdown("### _Transform Ideas into Production Code_ ⚑")
102
-
103
- # --- Language Selector ---
104
- lang = st.sidebar.selectbox("πŸ’» Language", SUPPORTED_LANGUAGES)
105
- user_query = st.text_input("🎯 Describe your requirement:", placeholder="e.g., 'Create a REST API with JWT authentication'")
106
-
107
- # --- Generation Flow ---
108
- if st.button("πŸš€ Generate Code", use_container_width=True):
109
- if user_query:
110
- with st.spinner(f"🧠 Crafting {lang} code..."):
111
- code = generate_code(client, user_query, lang)
112
- if code:
113
- st.session_state.code = code
114
- st.balloons()
115
-
116
- with st.expander(f"✨ Generated Code", expanded=True):
117
- st.code(code)
118
- ext = {"Python": "py", "JavaScript": "js"}.get(lang, "txt")
119
- st.markdown(get_download_link(code, f"code.{ext}"), unsafe_allow_html=True)
120
- else:
121
- st.warning("Please enter a requirement!")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
 
123
  if __name__ == "__main__":
124
  main()
 
1
  # app.py
2
  import os
3
  import time
4
+ import json
5
+ import zipfile
6
+ import io
7
  import streamlit as st
8
  from groq import Groq
9
  from streamlit_lottie import st_lottie
10
+ from streamlit_extras.stylable_container import stylable_container
 
 
11
 
12
  # --- Constants ---
13
  PRIMARY_MODEL = "qwen-2.5-coder-32b"
14
+ BACKUP_MODEL = "llama3-70b-8192"
15
+ LANGUAGES = ["Python", "JavaScript", "Java", "C++", "Go", "Rust"]
16
+ THEMES = ["Dracula", "Monokai", "Nord", "Solarized", "One Dark"]
17
+
18
+ # --- Load Assets ---
19
+ def load_lottie(filepath):
20
+ with open(filepath, "r") as f:
21
+ return json.load(f)
22
+
23
+ # --- Initialize Clients ---
24
+ @st.cache_resource
25
+ def init_groq():
26
+ return Groq(api_key=os.getenv("GROQ_API_KEY"))
27
 
28
+ # --- UI Config ---
29
  st.set_page_config(
30
  page_title="CodeForge AI",
31
+ page_icon="⚑",
32
  layout="wide",
33
  initial_sidebar_state="expanded"
34
  )
35
 
 
 
 
 
 
36
  # --- Custom CSS ---
37
  def inject_css():
38
  st.markdown(f"""
39
  <style>
40
+ [data-testid="stAppViewContainer"] {{
41
+ background: linear-gradient(135deg, #0f0c29 0%, #302b63 50%, #24243e 100%);
 
42
  }}
 
43
  .stTextInput input {{
44
+ color: #00ffaa !important;
45
  background: rgba(0,0,0,0.3) !important;
46
+ border: 2px solid #00ffaa !important;
47
+ box-shadow: 0 0 10px rgba(0,255,170,0.5);
48
  }}
49
+ .stButton>button {{
50
+ background: linear-gradient(90deg, #00ffaa 0%, #0088ff 100%) !important;
51
+ color: #111 !important;
52
+ font-weight: bold !important;
 
 
 
 
 
 
 
53
  border: none !important;
54
+ box-shadow: 0 0 15px rgba(0,255,170,0.7);
55
+ transition: all 0.3s ease !important;
56
+ }}
57
+ .stButton>button:hover {{
58
+ transform: scale(1.05);
59
+ box-shadow: 0 0 20px rgba(0,255,170,0.9);
60
+ }}
61
+ .code-header {{
62
+ color: #00ffaa;
63
+ font-family: 'Fira Code', monospace;
64
+ text-shadow: 0 0 10px rgba(0,255,170,0.7);
65
+ }}
66
+ [data-testid="stSidebar"] {{
67
+ background: rgba(16, 18, 33, 0.8) !important;
68
+ backdrop-filter: blur(10px);
69
+ border-right: 1px solid rgba(0,255,170,0.3);
70
  }}
71
  </style>
72
  """, unsafe_allow_html=True)
73
 
74
+ inject_css()
 
 
 
75
 
76
+ # --- Animation ---
77
+ def render_hero():
78
+ col1, col2 = st.columns([2, 1])
79
+ with col1:
80
+ st.markdown("""
81
+ # <span class="code-header">⚑ CodeForge AI</span>
82
+ ### _Generate β€’ Optimize β€’ Deploy_
83
+ """, unsafe_allow_html=True)
84
+ with col2:
85
+ st_lottie(load_lottie("https://assets9.lottiefiles.com/packages/lf20_2znxgjyt.json"),
86
+ height=150, key="hero")
87
+
88
+ # --- Main Generator ---
89
+ def generate_code(client, prompt, language, model):
90
+ messages = [{
91
+ "role": "system",
92
+ "content": f"You are an expert {language} developer. Generate clean, efficient, production-ready code."
93
+ }, {
94
+ "role": "user",
95
+ "content": prompt
96
+ }]
97
+
98
+ response = client.chat.completions.create(
99
+ model=model,
100
+ messages=messages,
101
+ temperature=0.7,
102
+ max_tokens=4000,
103
+ top_p=0.95,
104
+ stream=True
105
+ )
106
+
107
+ return response
108
+
109
+ # --- UI Components ---
110
+ def language_selector():
111
+ with st.sidebar:
112
+ with stylable_container(
113
+ key="lang-select",
114
+ css_styles="""
115
+ {
116
+ border: 2px solid #00ffaa;
117
+ border-radius: 10px;
118
+ padding: 10px;
119
+ background: rgba(0,0,0,0.2);
120
+ }
121
+ """
122
+ ):
123
+ return st.selectbox("πŸ—οΈ Select Language", LANGUAGES, index=0)
124
+
125
+ def theme_selector():
126
+ with st.sidebar:
127
+ with stylable_container(
128
+ key="theme-select",
129
+ css_styles="""
130
+ {
131
+ border: 2px solid #0088ff;
132
+ border-radius: 10px;
133
+ padding: 10px;
134
+ background: rgba(0,0,0,0.2);
135
+ }
136
+ """
137
+ ):
138
+ return st.selectbox("🎨 Editor Theme", THEMES, index=0)
139
 
140
+ # --- Download Handler ---
141
+ def create_download_zip(code, language):
142
+ zip_buffer = io.BytesIO()
143
+ with zipfile.ZipFile(zip_buffer, "a") as zf:
144
+ zf.writestr(f"generated_code.{language.lower()}", code)
145
+ return zip_buffer.getvalue()
 
 
 
 
 
 
 
 
 
 
146
 
147
+ # --- Main App ---
148
  def main():
 
149
  client = init_groq()
150
+ render_hero()
151
 
152
+ # Sidebar Controls
153
+ language = language_selector()
154
+ theme = theme_selector()
155
+
156
+ # Main Input
157
+ with st.form(key="input_form"):
158
+ prompt = st.text_area("πŸ’‘ Describe your coding task:", height=150,
159
+ placeholder="e.g. 'Create a REST API with FastAPI and MongoDB'")
160
+
161
+ col1, col2, col3 = st.columns([1,1,2])
162
+ with col1:
163
+ generate_btn = st.form_submit_button("✨ Generate Code")
164
+ with col2:
165
+ explain_btn = st.form_submit_button("πŸ“š Explain")
166
+ with col3:
167
+ optimize_btn = st.form_submit_button("⚑ Optimize")
168
+
169
+ # Generation Logic
170
+ if generate_btn and prompt:
171
+ with st.spinner("πŸš€ Generating your code..."):
172
+ try:
173
+ response = generate_code(client, prompt, language, PRIMARY_MODEL)
174
+
175
+ code_container = st.empty()
176
+ full_response = []
177
+
178
+ for chunk in response:
179
+ if chunk.choices[0].delta.content:
180
+ full_response.append(chunk.choices[0].delta.content)
181
+ current_code = "".join(full_response)
182
+ code_container.code(current_code, language=language.lower(), line_numbers=True)
183
+
184
+ st.session_state.generated_code = "".join(full_response)
185
+
186
+ # Download Button
187
+ zip_data = create_download_zip(st.session_state.generated_code, language)
188
+ st.download_button(
189
+ label="πŸ“₯ Download Code",
190
+ data=zip_data,
191
+ file_name=f"codeforge_{int(time.time())}.zip",
192
+ mime="application/zip"
193
+ )
194
+
195
+ except Exception as e:
196
+ st.error(f"🚨 Generation failed: {str(e)}")
197
+ st.info("Attempting with backup model...")
198
+ try:
199
+ response = generate_code(client, prompt, language, BACKUP_MODEL)
200
+ # ... [backup handling logic]
201
+ except Exception as e:
202
+ st.error("All models failed. Please try again later.")
203
 
204
  if __name__ == "__main__":
205
  main()