Engr-Usman-Ali commited on
Commit
2271fe8
Β·
verified Β·
1 Parent(s): 3f23a70

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +102 -127
app.py CHANGED
@@ -1,138 +1,113 @@
1
  import streamlit as st
2
- from huggingface_hub import InferenceClient
3
  from groq import Groq
4
 
5
- # =======================
6
- # API Keys
7
- # =======================
8
- HF_API_TOKEN = st.secrets.get("HF_API_TOKEN", None)
9
- GROQ_API_KEY = st.secrets.get("GROQ_API_KEY", None)
10
-
11
- # =======================
12
- # Model Lists
13
- # =======================
14
- HF_MODELS = [
15
- "bigcode/starcoder2-3b",
16
- "mistralai/Mistral-7B-Instruct-v0.2",
17
- "tiiuae/falcon-7b-instruct"
18
- ]
19
-
20
- GROQ_MODELS = [
21
- "llama-3.1-8b-instant",
22
- "llama-3.3-70b-versatile",
23
- "openai/gpt-oss-20b",
24
- "meta-llama/llama-guard-4-12b"
25
- ]
26
-
27
- # =======================
28
- # Query Functions
29
- # =======================
30
- def query_hf(model, prompt):
31
- try:
32
- client = InferenceClient(token=HF_API_TOKEN)
33
- response = client.text_generation(
34
- model=model,
35
- prompt=prompt,
36
- max_new_tokens=600,
37
- temperature=0.7
38
- )
39
- return response
40
- except Exception as e:
41
- return f"⚠️ Hugging Face Error: {e}"
42
-
43
- def query_groq(model, prompt):
44
- try:
45
- client = Groq(api_key=GROQ_API_KEY)
46
- resp = client.chat.completions.create(
47
- model=model,
48
- messages=[{"role": "user", "content": prompt}],
49
- temperature=0.7,
50
- max_tokens=600
51
- )
52
- return resp.choices[0].message.content
53
- except Exception as e:
54
- return f"⚠️ Groq Error: {e}"
55
-
56
- # =======================
57
- # Streamlit UI
58
- # =======================
59
- st.set_page_config(page_title="CodeCraft AI", page_icon="⚑", layout="wide")
60
- st.title("⚑ CodeCraft AI – Mini Copilot for Hackathons")
61
 
62
- st.markdown("Choose a task below: Generate Code, Debug, or Explain.")
63
-
64
- backend = st.radio("Choose Backend", ["Hugging Face", "Groq"])
65
-
66
- if backend == "Hugging Face":
67
- model_choice = st.selectbox("Select Hugging Face Model", HF_MODELS)
68
- else:
69
- model_choice = st.selectbox("Select Groq Model", GROQ_MODELS)
70
-
71
- tabs = st.tabs(["πŸ’» Generate Code", "🐞 Debug Code", "πŸ“– Explain Code"])
72
 
73
- # -----------------------
74
- # Generate Code Tab
75
- # -----------------------
76
- with tabs[0]:
77
- prompt = st.text_area("πŸ’‘ Enter your problem statement", height=200, key="gen_input")
78
- if st.button("πŸš€ Generate Code"):
79
- if not prompt.strip():
80
- st.warning("Please enter something.")
81
  else:
82
- with st.spinner("AI is generating code..."):
83
- output = query_hf(model_choice, prompt) if backend == "Hugging Face" else query_groq(model_choice, prompt)
84
- st.subheader("βœ… Generated Code")
85
- st.code(output, language="python")
86
-
87
- # -----------------------
88
- # Debug Tab
89
- # -----------------------
90
- with tabs[1]:
91
- buggy_code = st.text_area("🐞 Paste your buggy code here", height=200, key="debug_input")
92
- if st.button("πŸ”§ Debug Code"):
93
- if not buggy_code.strip():
94
- st.warning("Please paste some code.")
95
- else:
96
- debug_prompt = f"""
97
- You are a Python code debugger. The user has provided buggy code.
98
- 1. First, output the corrected version of the code ONLY inside a code block.
99
- 2. Then, after the code block, explain clearly what needed to change and what was changed to fix the code.
100
- Do not list fixes as Fix 1, Fix 2. Just a flowing explanation.
101
-
102
- Buggy code:
103
- {buggy_code}
104
- """
105
- with st.spinner("AI is debugging..."):
106
- output = query_hf(model_choice, debug_prompt) if backend == "Hugging Face" else query_groq(model_choice, debug_prompt)
107
-
108
- # Split into code + explanation
109
- if "```" in output:
110
- try:
111
- corrected = output.split("```")[1].replace("python", "").strip()
112
- explanation = output.split("```")[-1].strip()
113
- st.subheader("βœ… Corrected Code")
114
- st.code(corrected, language="python")
115
- st.subheader("πŸ“˜ Explanation")
116
- st.write(explanation)
117
- except:
118
- st.write(output)
119
  else:
120
- st.write(output)
121
-
122
- # -----------------------
123
- # Explain Tab
124
- # -----------------------
125
- with tabs[2]:
126
- code_to_explain = st.text_area("πŸ“– Paste code to explain", height=200, key="explain_input")
127
- if st.button("πŸ“ Explain Code"):
128
- if not code_to_explain.strip():
129
- st.warning("Please paste some code.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
130
  else:
131
- explain_prompt = f"Explain this Python code in simple steps:\n{code_to_explain}"
132
- with st.spinner("AI is explaining..."):
133
- output = query_hf(model_choice, explain_prompt) if backend == "Hugging Face" else query_groq(model_choice, explain_prompt)
134
- st.subheader("πŸ“˜ Explanation")
135
- st.write(output)
136
 
137
 
138
  # =======================
 
1
  import streamlit as st
 
2
  from groq import Groq
3
 
4
+ # Initialize Groq client
5
+ client = Groq(api_key=st.secrets["GROQ_API_KEY"])
6
+
7
+ # Sidebar for model selection
8
+ st.sidebar.title("βš™οΈ Settings")
9
+ model_choice = st.sidebar.selectbox(
10
+ "Choose AI Model",
11
+ ["llama-3.1-8b-instant", "llama-3.1-70b-versatile", "mixtral-8x7b-32768"]
12
+ )
13
+
14
+ st.title("πŸ€– CodeCraft AI - Mini Copilot")
15
+
16
+ # Tabs
17
+ tab1, tab2, tab3 = st.tabs(["πŸ’‘ Generate Code", "πŸ›  Debug Code", "πŸ“˜ Explain Code"])
18
+
19
+ # ------------------------- Generate Code -------------------------
20
+ with tab1:
21
+ st.subheader("πŸ’‘ Generate Code from Statement")
22
+ statement = st.text_area("Enter your problem statement (e.g., 'Build a calculator in Python')")
23
+
24
+ if st.button("Generate Code"):
25
+ if statement.strip():
26
+ with st.spinner("Generating code..."):
27
+ response = client.chat.completions.create(
28
+ model=model_choice,
29
+ messages=[
30
+ {"role": "system", "content": "You are a helpful coding assistant."},
31
+ {"role": "user", "content": f"Generate correct code for: {statement}. "
32
+ f"First show the code block clearly. "
33
+ f"Then give a short simple explanation."}
34
+ ],
35
+ temperature=0.3
36
+ )
37
+ result = response.choices[0].message.content
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
+ # Split into code + explanation
40
+ if "```" in result:
41
+ parts = result.split("```")
42
+ code = parts[1] if len(parts) > 1 else ""
43
+ explanation = "".join(parts[2:]) if len(parts) > 2 else result
44
+ else:
45
+ code, explanation = result, ""
 
 
 
46
 
47
+ # Show code (with copy button provided by Streamlit automatically)
48
+ st.code(code, language="python")
49
+ # Show explanation (plain text, no copy)
50
+ st.markdown("### πŸ“˜ Explanation")
51
+ st.write(explanation.strip())
 
 
 
52
  else:
53
+ st.warning("⚠️ Please enter a statement.")
54
+
55
+ # ------------------------- Debug Code -------------------------
56
+ with tab2:
57
+ st.subheader("πŸ›  Debug Your Code")
58
+ user_code = st.text_area("Paste your buggy code here")
59
+
60
+ if st.button("Debug Code"):
61
+ if user_code.strip():
62
+ with st.spinner("Analyzing and fixing your code..."):
63
+ response = client.chat.completions.create(
64
+ model=model_choice,
65
+ messages=[
66
+ {"role": "system", "content": "You are an expert code debugger."},
67
+ {"role": "user", "content": f"Here is code: {user_code}. "
68
+ f"Fix errors and give corrected code. "
69
+ f"Then explain simply what I needed to change and why. "
70
+ f"Do not use 'fix 1, fix 2' format, just a simple explanation."}
71
+ ],
72
+ temperature=0.2
73
+ )
74
+ result = response.choices[0].message.content
75
+
76
+ if "```" in result:
77
+ parts = result.split("```")
78
+ code = parts[1] if len(parts) > 1 else ""
79
+ explanation = "".join(parts[2:]) if len(parts) > 2 else result
 
 
 
 
 
 
 
 
 
 
80
  else:
81
+ code, explanation = result, ""
82
+
83
+ st.code(code, language="python")
84
+ st.markdown("### πŸ“˜ Explanation of Fixes")
85
+ st.write(explanation.strip())
86
+ else:
87
+ st.warning("⚠️ Please paste your code.")
88
+
89
+ # ------------------------- Explain Code -------------------------
90
+ with tab3:
91
+ st.subheader("πŸ“˜ Explain Your Code")
92
+ code_to_explain = st.text_area("Paste your code to understand it")
93
+
94
+ if st.button("Explain Code"):
95
+ if code_to_explain.strip():
96
+ with st.spinner("Explaining your code..."):
97
+ response = client.chat.completions.create(
98
+ model=model_choice,
99
+ messages=[
100
+ {"role": "system", "content": "You are a teacher that explains code in simple terms."},
101
+ {"role": "user", "content": f"Explain this code in very simple words:\n{code_to_explain}"}
102
+ ],
103
+ temperature=0.5
104
+ )
105
+ explanation = response.choices[0].message.content
106
+
107
+ st.markdown("### πŸ“˜ Explanation")
108
+ st.write(explanation.strip())
109
  else:
110
+ st.warning("⚠️ Please paste your code.")
 
 
 
 
111
 
112
 
113
  # =======================