Haseeb-001 commited on
Commit
c4cf4bc
Β·
verified Β·
1 Parent(s): 5fd2671

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +138 -57
app.py CHANGED
@@ -1,91 +1,172 @@
 
1
  import os
 
2
  import streamlit as st
3
  from groq import Groq
 
 
 
4
 
5
- # Configuration
6
  PRIMARY_MODEL = "qwen-2.5-coder-32b"
7
- BACKUP_MODEL = "llama3-70b-8192"
 
8
 
9
- # Streamlit UI Config
10
  st.set_page_config(
11
- page_title="AI Code Generator",
12
  page_icon="πŸš€",
13
  layout="wide",
14
  initial_sidebar_state="expanded"
15
  )
16
 
17
- # Custom CSS for Neon Theme
18
- def inject_custom_css():
19
- st.markdown("""
 
 
 
 
 
20
  <style>
21
- .main { background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%); }
22
- .stTextInput input { color: #4fffb0 !important; background: rgba(0,0,0,0.3) !important; }
23
- .stButton>button { background: rgba(79,255,176,0.2) !important; border: 2px solid #4fffb0 !important; }
24
- .code-editor { border: 2px solid #4fffb0; border-radius: 10px; padding: 1rem; background: rgba(0,0,0,0.5); }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  </style>
26
  """, unsafe_allow_html=True)
27
 
28
- inject_custom_css()
 
 
 
29
 
30
- # Initialize Groq Client
31
- def get_groq_client():
32
- api_key = os.getenv("GROQ_API_KEY")
33
- if not api_key:
34
- st.error("GROQ_API_KEY not found! Please set it in environment variables or secrets.")
35
- return None
36
- return Groq(api_key=api_key)
37
 
38
- # Code Generation Functions
39
- def generate_code(query, model, client):
40
  try:
41
- completion = client.chat.completions.create(
42
- model=model,
43
- messages=[{
44
- "role": "user",
45
- "content": f"Generate Python code for: {query}. Include comments and error handling."
46
- }],
47
- temperature=0.6,
 
 
 
 
 
 
 
 
48
  max_tokens=4096,
49
  top_p=0.95
50
  )
51
- return completion.choices[0].message.content
52
  except Exception as e:
53
- st.error(f"Error generating code: {str(e)}")
54
  return None
55
 
56
- # Main App Interface
57
  def main():
58
- client = get_groq_client()
59
- if not client:
60
- return
61
-
62
- st.title("AI Code Generator πŸš€")
63
 
64
- col1, col2 = st.columns([3, 1])
 
65
  with col1:
66
- query = st.text_input("Describe your coding requirement:")
67
-
68
- if 'generated_code' not in st.session_state:
69
- st.session_state.generated_code = None
70
-
71
- if col2.button("πŸ”„ New Code"):
72
- st.session_state.generated_code = None
 
73
 
74
- if query and not st.session_state.generated_code:
75
- with st.spinner("Generating code..."):
76
- code = generate_code(query, PRIMARY_MODEL, client)
77
- if not code:
78
- st.warning("Trying backup model...")
79
- code = generate_code(query, BACKUP_MODEL, client)
 
 
 
 
80
 
81
  if code:
82
- st.session_state.generated_code = code
83
- else:
84
- st.error("Failed to generate code. Please try again.")
85
-
86
- if st.session_state.generated_code:
87
- with st.expander("Generated Code", expanded=True):
88
- st.markdown(f"```python\n{st.session_state.generated_code}\n```")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
 
90
  if __name__ == "__main__":
91
  main()
 
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 json
8
+ import base64
9
 
10
+ # --- Constants ---
11
  PRIMARY_MODEL = "qwen-2.5-coder-32b"
12
+ SUPPORTED_LANGUAGES = ["Python", "JavaScript", "Java", "C++", "Go", "Rust"]
13
+ LOTTIE_ANIMATION = "https://assets3.lottiefiles.com/packages/lf20_hi95bvmx/ai.json"
14
 
15
+ # --- Setup ---
16
  st.set_page_config(
17
+ page_title="CodeForge AI",
18
  page_icon="πŸš€",
19
  layout="wide",
20
  initial_sidebar_state="expanded"
21
  )
22
 
23
+ # --- Lottie Animation Loader ---
24
+ def load_lottie(url):
25
+ with open("animation.json") as f:
26
+ return json.load(f)
27
+
28
+ # --- Custom CSS with Animations ---
29
+ def inject_css():
30
+ st.markdown(f"""
31
  <style>
32
+ @keyframes glow {{
33
+ 0% {{ box-shadow: 0 0 5px #4fffb0; }}
34
+ 50% {{ box-shadow: 0 0 20px #4fffb0; }}
35
+ 100% {{ box-shadow: 0 0 5px #4fffb0; }}
36
+ }}
37
+
38
+ .main {{
39
+ background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
40
+ color: #ffffff;
41
+ }}
42
+
43
+ .stTextInput input {{
44
+ animation: glow 2s infinite;
45
+ background: rgba(0,0,0,0.3) !important;
46
+ border: 2px solid #4fffb0 !important;
47
+ }}
48
+
49
+ .code-editor {{
50
+ border: 2px solid #4fffb0;
51
+ border-radius: 15px;
52
+ padding: 1rem;
53
+ background: rgba(0,0,0,0.5) !important;
54
+ animation: glow 2s infinite;
55
+ }}
56
+
57
+ .download-btn {{
58
+ background: linear-gradient(45deg, #4fffb0, #2bd2ff) !important;
59
+ color: #1a1a2e !important;
60
+ border: none !important;
61
+ border-radius: 25px;
62
+ padding: 12px 24px;
63
+ font-weight: bold;
64
+ transition: transform 0.3s !important;
65
+ }}
66
+
67
+ .download-btn:hover {{
68
+ transform: scale(1.05);
69
+ }}
70
  </style>
71
  """, unsafe_allow_html=True)
72
 
73
+ # --- File Download Generator ---
74
+ def get_download_link(code, filename):
75
+ b64 = base64.b64encode(code.encode()).decode()
76
+ return f'<a href="data:file/txt;base64,{b64}" download="{filename}" class="download-btn">⬇️ Download {filename}</a>'
77
 
78
+ # --- Model Client ---
79
+ @st.cache_resource
80
+ def init_groq():
81
+ return Groq(api_key=os.environ.get("GROQ_API_KEY"))
 
 
 
82
 
83
+ # --- Code Generation Core ---
84
+ def generate_code(client, query, lang):
85
  try:
86
+ system_prompt = f"""
87
+ You are a {lang} expert. Generate:
88
+ 1. Clean, production-ready code
89
+ 2. With error handling
90
+ 3. Proper documentation
91
+ 4. Optimized for performance
92
+ """
93
+
94
+ response = client.chat.completions.create(
95
+ model=PRIMARY_MODEL,
96
+ messages=[
97
+ {"role": "system", "content": system_prompt},
98
+ {"role": "user", "content": query}
99
+ ],
100
+ temperature=0.7,
101
  max_tokens=4096,
102
  top_p=0.95
103
  )
104
+ return response.choices[0].message.content
105
  except Exception as e:
106
+ st.error(f"🚨 Generation Error: {str(e)}")
107
  return None
108
 
109
+ # --- UI Components ---
110
  def main():
111
+ inject_css()
112
+ client = init_groq()
 
 
 
113
 
114
+ # --- Hero Section ---
115
+ col1, col2 = st.columns([1, 2])
116
  with col1:
117
+ st_lottie(load_lottie(LOTTIE_ANIMATION), height=200)
118
+ with col2:
119
+ st.markdown("# CodeForge AI")
120
+ st.markdown("### _Transform Ideas into Production Code_ ⚑")
121
+
122
+ # --- Language Selector ---
123
+ lang = st.sidebar.selectbox("πŸ’» Programming Language", SUPPORTED_LANGUAGES, index=0)
124
+ user_query = st.text_input("🎯 Describe your coding requirement:", placeholder="e.g., 'Create a REST API with JWT authentication'")
125
 
126
+ # --- Main Generation Flow ---
127
+ if st.button("πŸš€ Generate Code", use_container_width=True):
128
+ if not user_query:
129
+ st.warning("⚠️ Please enter a coding requirement!")
130
+ return
131
+
132
+ with st.spinner(f"🧠 Crafting {lang} magic..."):
133
+ start_time = time.time()
134
+ code = generate_code(client, user_query, lang)
135
+ gen_time = time.time() - start_time
136
 
137
  if code:
138
+ st.session_state.code = code
139
+ st.balloons()
140
+
141
+ # --- Code Display ---
142
+ with st.expander(f"✨ Generated {lang} Code", expanded=True):
143
+ st.code(code, language="python" if lang == "Python" else "javascript")
144
+
145
+ # --- Download Button ---
146
+ ext = {"Python": "py", "JavaScript": "js", "Java": "java",
147
+ "C++": "cpp", "Go": "go", "Rust": "rs"}[lang]
148
+ st.markdown(get_download_link(code, f"generated_code.{ext}"),
149
+ unsafe_allow_html=True)
150
+
151
+ # --- Performance Metrics ---
152
+ st.sidebar.markdown(f"""
153
+ ### πŸ“Š Generation Metrics
154
+ ⏱️ **Time**: {gen_time:.2f}s
155
+ πŸ“ **Tokens**: {len(code.split())}
156
+ 🧠 **Model**: {PRIMARY_MODEL}
157
+ """)
158
+
159
+ # --- Explanation Section ---
160
+ if st.button("πŸ“– Explain Implementation"):
161
+ with st.spinner("πŸ” Analyzing code structure..."):
162
+ explanation = client.chat.completions.create(
163
+ model=PRIMARY_MODEL,
164
+ messages=[{
165
+ "role": "user",
166
+ "content": f"Explain this {lang} code:\n\n{code}"
167
+ }]
168
+ )
169
+ st.markdown(f"## Code Breakdown\n{explanation.choices[0].message.content}")
170
 
171
  if __name__ == "__main__":
172
  main()