Spaces:
Sleeping
Sleeping
local
#1
by flexingdatai - opened
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129import streamlit as stimport google.generativeai as genaiimport requestsfrom inst import system_instruction# === SETUP ===api_key = st.secrets["GEMINI_API_KEY"]genai.configure(api_key=api_key)model = genai.GenerativeModel(model_name="models/gemini-flash-latest",system_instruction=system_instruction)st.set_page_config(page_title="Flexing Data AI Chatbot", layout="centered")# === STYLES ===st.markdown("""<style>.chat-bubble {padding:10px 16px;border-radius:16px;margin:6px 0;max-width:85%;}.user-bubble {background:#075E54;color:white;margin-left:auto;}.bot-bubble {background:#fff;color:#333;margin-right:auto;border:1px solid #ccc;}.chat-container {max-height:420px;overflow-y:auto;padding:10px;background:#eaf1f8;border-radius:12px;}</style>""", unsafe_allow_html=True)st.markdown("<h3 style='text-align:center;color:#FF5722;'>🤖 Flexing Data AI Chatbot</h3>", unsafe_allow_html=True)# === USER INFO ===if "user_info" not in st.session_state:with st.form("user_form"):name = st.text_input("Name")email = st.text_input("Email")whatsapp = st.text_input("WhatsApp")submit = st.form_submit_button("Start Chat")if submit:if name and email and whatsapp:st.session_state.user_info = {"name": name, "email": email, "whatsapp": whatsapp}else:st.warning("Fill all fields")st.stop()else:st.stop()# === MEMORY ===if "messages" not in st.session_state:st.session_state.messages = []# === LEAD SCORING FUNCTION ===def classify_lead(text):text = text.lower()hot_keywords = ["price", "fees", "join", "enroll", "start", "payment"]warm_keywords = ["duration", "curriculum", "learn", "projects"]if any(k in text for k in hot_keywords):return "🔥 Hot"elif any(k in text for k in warm_keywords):return "🤔 Warm"else:return "❄️ Cold"# === GOOGLE SHEETS ===def send_to_sheet(data):try:requests.post(st.secrets["google_url"], json=data, timeout=5)except:pass# === BUILD CONTEXT ===def build_prompt(user_input):history = ""for role, msg in st.session_state.messages[-6:]:history += f"{role}: {msg}\n"return f"""Conversation so far:{history}User: {user_input}Respond helpfully, guide toward enrolling if relevant.Keep it short and friendly."""# === CHAT ===user_input = st.chat_input("Ask anything...")if user_input:user = st.session_state.user_infost.session_state.messages.append(("User", user_input))prompt = build_prompt(user_input)with st.spinner("Thinking..."):try:response = model.generate_content(prompt,generation_config={"temperature": 0.3, "max_output_tokens": 400})bot_reply = response.text.strip()except Exception as e:bot_reply = "Something went wrong"st.error(str(e))st.session_state.messages.append(("Bot", bot_reply))# === LEAD SCORE ===lead_score = classify_lead(user_input)# === SEND DATA ===send_to_sheet({"name": user["name"],"email": user["email"],"whatsapp": user["whatsapp"],"question": user_input,"answer": bot_reply,"lead_score": lead_score})# === DISPLAY ===st.markdown('<div class="chat-container">', unsafe_allow_html=True)for role, msg in st.session_state.messages:bubble = "user-bubble" if role == "User" else "bot-bubble"icon = "🧑" if role == "User" else "🤖"st.markdown(f'<div class="chat-bubble {bubble}">{icon} <b>{role}:</b><br>{msg}</div>', unsafe_allow_html=True)st.markdown('</div>', unsafe_allow_html=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126import streamlit as stimport google.generativeai as genaiimport requestsfrom datetime import datetimefrom inst import system_instruction # Contains your system role string# === SETUP ===api_key = st.secrets["GEMINI_API_KEY"]genai.configure(api_key=api_key)model = genai.GenerativeModel(model_name="models/gemini-2.0-flash",system_instruction=system_instruction)# === CONFIGURE PAGE ===st.set_page_config(page_title="Flexing Data AI Chatbot", layout="centered")# === STYLES ===st.markdown("""<style>.chat-bubble {padding: 10px 16px;border-radius: 16px;margin: 6px 0;max-width: 85%;line-height: 1.5;font-size: 14px;word-wrap: break-word;box-shadow: 0 1px 3px rgba(0,0,0,0.1);}.user-bubble {background-color: #075E54;color: white;margin-left: auto;}.bot-bubble {background-color: #ffffff;color: #333;margin-right: auto;border: 1px solid #ccc;}.chat-container {max-height: 420px;overflow-y: auto;padding: 10px;background-color: #eaf1f8;border-radius: 12px;margin-bottom: 10px;}</style>""", unsafe_allow_html=True)st.markdown("<h3 style='text-align: center; color: #FF5722;'>🤖 Flexing Data AI Chatbot</h3>", unsafe_allow_html=True)st.markdown("<p style='text-align: center;'>Ask anything about our Data Analytics Internship Program</p>", unsafe_allow_html=True)# === USER INFO FORM ===if "user_info" not in st.session_state:with st.form("user_info_form"):name = st.text_input("Your Name")email = st.text_input("Email")whatsapp = st.text_input("WhatsApp Number")submit = st.form_submit_button("Start Chat")if submit:if name and email and whatsapp:st.session_state.user_info = {"name": name.strip(),"email": email.strip(),"whatsapp": whatsapp.strip()}else:st.warning("Please fill out all fields to start chatting.")st.stop()else:st.stop()# === CHAT SESSION INIT ===if "messages" not in st.session_state:st.session_state.messages = []# === POST TO GOOGLE SHEET VIA APPS SCRIPT ===def send_to_google_apps_script(name, email, whatsapp, question, answer):url = st.secrets["google_url"] # Replace with your deployed Apps Script URLpayload = {"name": name,"email": email,"whatsapp": whatsapp,"question": question,"answer": answer}try:requests.post(url, json=payload, timeout=5)except Exception as e:st.error(f"⚠️ Failed to send data to Google Sheet: {e}")# === CHAT INPUT ===user_input = st.chat_input("Type your message...")if user_input:user = st.session_state.user_infost.session_state.messages.append(("You", user_input))with st.spinner("Thinking..."):try:response = model.generate_content(user_input)bot_reply = response.text.strip()except Exception as e:bot_reply = "⚠️ Sorry, something went wrong."st.error(str(e))st.session_state.messages.append(("Bot", bot_reply))# Send to Google Sheetssend_to_google_apps_script(user["name"], user["email"], user["whatsapp"], user_input, bot_reply)# === DISPLAY MESSAGES ===st.markdown('<div class="chat-container">', unsafe_allow_html=True)for sender, message in st.session_state.messages:bubble_class = "user-bubble" if sender == "You" else "bot-bubble"role_icon = "🧑💼" if sender == "You" else "🤖"st.markdown(f'<div class="chat-bubble {bubble_class}">{role_icon} <strong>{sender}:</strong><br>{message}</div>',unsafe_allow_html=True)st.markdown('</div>', unsafe_allow_html=True)
7 unmodified lines8910111213141516171824 unmodified lines434445464748494 unmodified lines545556575859606162636465666768697 unmodified linesWe offer a 2-month Data Analytics Internship focused on industry-level projects using Excel, SQL, Power BI, Python, AWS, Machine Learning (ML), and Generative AI (LLM). This internship is designed for those who already have basic knowledge of these tools and want to gain real-world experience.Batch Details:Start Date: June 2026Timings: Weekends (Sat-Sun, 11 AM - 3 PM) – LIVE ClassesPricing: Less than ₹25K7 Industry-Standard Projects and GenAI Projects:Sales & Revenue Analysis (Excel + SQL) – Beginner LevelCustomer Retention & Churn Dashboard (SQL + Power BI) – Intermediate LevelE-Commerce Sentiment Analysis (Python) – Intermediate Level24 unmodified linesPaid Internship (2 Months): Work on real-world projects, earn up to ₹10K stipend based on the performance.Selection Process:An exam will be conducted post batch completion1 Top performer will get 100% scholarship + 10k stipendNext 2 will get 50% scholarship + 5k stipendNext 3 will get 25% scholarship + 2k stipend4 unmodified linesWhatsApp for Queries: [9220442764](https://wa.me/9220442764)Join our WhatsApp Channel for Job & Workshop Updates: [Click here](https://whatsapp.com/channel/0029VaVvay3Fsn0jOJvhIj3e)Interested in Your Own AI Chatbot for Business?We can help you automate customer interactions with a personalized AI chatbot for your business!WhatsApp: [9220442764](https://wa.me/9220442764)Looking forward to mentoring you on this journey!If you want to connect with me 1:1 for carrer guidance, on how to become a Job-Ready GenAI Data AnalystBook and appoitment from this link:Appointment: https://topmate.io/flexingdata/509676/Best,Shashank KashyapTrainer, Flexing Data7 unmodified lines8910111213141516171824 unmodified lines434445464748494 unmodified lines54555657585960616263646566677 unmodified linesWe offer a 2-month Data Analytics Internship focused on industry-level projects using Excel, SQL, Power BI, Python, AWS, Machine Learning (ML), and Generative AI (LLM). This internship is designed for those who already have basic knowledge of these tools and want to gain real-world experience.Batch Details:Start Date: 2nd August 2025Timings: Weekends (Sat-Sun, 7 PM - 9 PM) – LIVE ClassesPricing: Less than ₹20K7 Industry-Standard Projects:Sales & Revenue Analysis (Excel + SQL) – Beginner LevelCustomer Retention & Churn Dashboard (SQL + Power BI) – Intermediate LevelE-Commerce Sentiment Analysis (Python) – Intermediate Level24 unmodified linesPaid Internship (2 Months): Work on real-world projects, earn up to ₹10K stipend based on the performance.Selection Process:An exam will be conducted on 19th July, 2025.1 Top performer will get 100% scholarship + 10k stipendNext 2 will get 50% scholarship + 5k stipendNext 3 will get 25% scholarship + 2k stipend4 unmodified linesWhatsApp for Queries: [9220442764](https://wa.me/9220442764)Join our WhatsApp Channel for Job & Workshop Updates: [Click here](https://whatsapp.com/channel/0029VaVvay3Fsn0jOJvhIj3e)Next Batch Starts in June – Don’t Miss This One!Interested in Your Own AI Chatbot for Business?We can help you automate customer interactions with a personalized AI chatbot for your business!WhatsApp: [9220442764](https://wa.me/9220442764)Looking forward to mentoring you on this journey!Best,Shashank KashyapTrainer, Flexing Data
app.py+81-84
inst.py+7-9