import streamlit as st import requests import re # Backend URL - Hugging Face Space API endpoint BACKEND_URL = "https://shiva9876-code-gen-backend.hf.space" # Page Config with Logo st.set_page_config( page_title="Write any code", page_icon="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f4/Code.org_logo.svg/1200px-Code.org_logo.svg.png", layout="centered", ) # Custom CSS for Logo & UI st.markdown(""" """, unsafe_allow_html=True) # Logo st.markdown( '', unsafe_allow_html=True ) # Title st.markdown('
Write any code: Verbose❇️
', unsafe_allow_html=True) # Chat history if "messages" not in st.session_state: st.session_state.messages = [] for msg in st.session_state.messages: if msg["role"] == "user": st.markdown(f'
User:
{msg["content"]}
', unsafe_allow_html=True) elif msg["role"] == "ai": explanation, code = msg["content"] st.markdown(f'
AI:
{explanation}
', unsafe_allow_html=True) if code: # st.subheader("Generated Code:") st.code(code, language="python") # Fixed Input Form at the bottom st.markdown('", unsafe_allow_html=True) # API Call Logic if submit_button: if user_input.strip(): st.session_state.messages.append({"role": "user", "content": user_input}) try: response = requests.post(f"{BACKEND_URL}/generate/", json={"prompt": user_input, "response_type": "both"}) if response.status_code == 200: data = response.json() raw_text = data.get("response", "").strip() if not raw_text or raw_text.lower() == "none": st.warning("⚠️ No valid response generated. Try a different prompt.") else: explanation, code = raw_text, None code_match = re.search(r"```(?:python)?\n(.*?)\n```", raw_text, re.DOTALL) if code_match: code = code_match.group(1).strip() explanation = raw_text.replace(code_match.group(0), "").strip() st.session_state.messages.append({"role": "ai", "content": (explanation, code)}) st.rerun() else: st.error(f"API Error: {response.status_code} - {response.text}") except requests.exceptions.ConnectionError: st.error("⚠️ Cannot connect to backend! Make sure FastAPI is running.") else: st.warning("Write something in input cell.")