Spaces:
Sleeping
Sleeping
Download bot.py from rolefitter/salesbrain-bot: direct link, hf CLI and curl.
- Browser
- Download file 21.2 kB
-
https://huggingface.co/spaces/rolefitter/salesbrain-bot/resolve/main/bot.py
- Command line
-
hf download hf://spaces/rolefitter/salesbrain-bot/bot.py
-
curl -L -o bot.py https://huggingface.co/spaces/rolefitter/salesbrain-bot/resolve/main/bot.py
21.2 kB
| import os | |
| import telebot | |
| from telebot import types | |
| from groq import Groq | |
| from supabase import create_client | |
| from sentence_transformers import SentenceTransformer | |
| import faiss | |
| import pickle | |
| import numpy as np | |
| TELEGRAM_TOKEN = os.environ.get('TELEGRAM_TOKEN') | |
| GROQ_API_KEY = os.environ.get('GROQ_API_KEY') | |
| SUPABASE_URL = os.environ.get('SUPABASE_URL') | |
| SUPABASE_KEY = os.environ.get('SUPABASE_KEY') | |
| bot = telebot.TeleBot(TELEGRAM_TOKEN) | |
| groq = Groq(api_key=GROQ_API_KEY) | |
| supabase = create_client(SUPABASE_URL, SUPABASE_KEY) | |
| print("Loading search engine...") | |
| encoder = SentenceTransformer('paraphrase-multilingual-MiniLM-L12-v2') | |
| index = faiss.read_index("salesbrain.faiss") | |
| with open("salesbrain_meta.pkl", "rb") as f: | |
| metadata = pickle.load(f) | |
| print(f"Search engine ready. {index.ntotal} conversations indexed.") | |
| last_suggestion = {} | |
| conversation_history = {} | |
| user_industry = {} | |
| MAX_HISTORY = 6 | |
| def get_total(): | |
| result = supabase.table("conversations").select("id", count="exact").execute() | |
| return result.count | |
| def get_feedback_count(): | |
| result = supabase.table("feedback").select("id", count="exact").execute() | |
| return result.count | |
| def detect_industry(text): | |
| text_lower = text.lower() | |
| insurance_keywords = ["policy", "insurance", "lic", "premium", "term plan", "cover", "claim", "bima", "hdfc life", "max life", "sbi life", "nominee"] | |
| real_estate_keywords = ["property", "flat", "house", "ghar", "plot", "apartment", "builder", "possession", "registry", "rent", "makaan", "zameen", "bhk"] | |
| automobile_keywords = ["car", "gaadi", "vehicle", "showroom", "test drive", "maruti", "honda", "hyundai", "tata", "petrol", "diesel", "cng", "ev"] | |
| fintech_keywords = ["mutual fund", "sip", "stock", "share", "demat", "zerodha", "groww", "fd", "fixed deposit", "investment", "portfolio", "nifty", "elss"] | |
| pharma_keywords = ["doctor", "dr", "molecule", "drug", "medicine", "prescription", "patient", "clinic", "hospital", "sample", "tablet", "clinical"] | |
| edtech_keywords = ["course", "student", "padhna", "coaching", "class", "certificate", "placement", "batch", "enroll", "fee", "learning", "career"] | |
| scores = { | |
| "insurance": sum(1 for k in insurance_keywords if k in text_lower), | |
| "real_estate": sum(1 for k in real_estate_keywords if k in text_lower), | |
| "automobile": sum(1 for k in automobile_keywords if k in text_lower), | |
| "fintech": sum(1 for k in fintech_keywords if k in text_lower), | |
| "pharma": sum(1 for k in pharma_keywords if k in text_lower), | |
| "edtech": sum(1 for k in edtech_keywords if k in text_lower) | |
| } | |
| best = max(scores, key=scores.get) | |
| if scores[best] == 0: | |
| return "general" | |
| return best | |
| def detect_emotion(text): | |
| text_lower = text.lower() | |
| if any(w in text_lower for w in ["gussa", "angry", "bakwaas", "bekar", "fraud", "kyun call", "disturb", "baar baar", "gali", "sala", "bsdk", "mc", "bc"]): | |
| return "anger" | |
| if any(w in text_lower for w in ["irritate", "pehle bhi bola", "kitni baar", "time waste", "bore", "tang", "pareshan"]): | |
| return "irritation" | |
| if any(w in text_lower for w in ["haan haan sab best", "bilkul free", "pakka guarantee", "100%", "sure sure", "han han"]): | |
| return "sarcasm" | |
| if any(w in text_lower for w in ["mehenga", "expensive", "costly", "itna paisa", "afford", "budget", "paisa nahi", "price"]): | |
| return "price_sensitivity" | |
| if any(w in text_lower for w in ["trust nahi", "fraud", "sach mein", "guarantee", "proof", "review", "fake", "jhooth"]): | |
| return "trust_issues" | |
| if any(w in text_lower for w in ["dar", "risk", "kya hoga", "safe", "loss", "doob", "scary", "tension"]): | |
| return "fear" | |
| if any(w in text_lower for w in ["samajh nahi", "confuse", "complicated", "explain", "kya hai", "matlab"]): | |
| return "confusion" | |
| if any(w in text_lower for w in ["dusri company", "competitor", "xyz better", "already", "doosra", "better option"]): | |
| return "competitor_loyalty" | |
| if any(w in text_lower for w in ["baad mein", "later", "abhi nahi", "kal", "next month", "sochta hoon", "time chahiye"]): | |
| return "time_pressure" | |
| if any(w in text_lower for w in ["excited", "great", "amazing", "chahiye", "interested", "batao", "tell me more"]): | |
| return "excited" | |
| if any(w in text_lower for w in ["achha laga", "thank", "shukriya", "helpful", "bahut achha", "happy"]): | |
| return "happy" | |
| return "general" | |
| def search_brain(query, industry="general", top_k=5): | |
| embedding = encoder.encode([query]).astype(np.float32) | |
| distances, indices = index.search(embedding, top_k * 4) | |
| results = [] | |
| fallback = [] | |
| for idx in indices[0]: | |
| if idx < len(metadata): | |
| conv = metadata[idx] | |
| if industry != "general" and conv.get('industry') == industry: | |
| results.append(conv) | |
| else: | |
| fallback.append(conv) | |
| if len(results) >= top_k: | |
| break | |
| if len(results) < top_k: | |
| results.extend(fallback[:top_k - len(results)]) | |
| return results[:top_k] | |
| def get_emotion_guide(emotion): | |
| guides = { | |
| "anger": """Customer is ANGRY. | |
| - Never argue. Never defend. | |
| - Acknowledge first: "Sir aap bilkul sahi frustrate hain" | |
| - Create pause: "Main sun raha hoon β bataiye kya hua" | |
| - One sentence only then silence | |
| - If abusive: "Sir main samajhta hoon. Jab ready hon tab baat karte hain" β end call politely""", | |
| "irritation": """Customer is IRRITATED. | |
| - Acknowledge immediately: "Sir main samajhta hoon β aapka time bahut valuable hai" | |
| - Promise brevity: "Sirf 30 second β ek important update tha" | |
| - Never justify why you called again | |
| - Get to point instantly""", | |
| "sarcasm": """Customer is being SARCASTIC. | |
| - Agree with the sarcasm β flip it | |
| - "Sir aap sahi keh rahe hain β main bhi pehle yehi sochta tha" | |
| - Then one specific fact that changes the frame | |
| - Never get defensive""", | |
| "price_sensitivity": """Customer is PRICE SENSITIVE. | |
| - Convert to daily cost: "Rs 17/day β ek chai ki kimat" | |
| - Compare to something they spend on daily | |
| - Show cost of NOT buying: "Agar kuch ho gaya toh family ko..." | |
| - Never reduce price first β show value first""", | |
| "trust_issues": """Customer has TRUST ISSUES. | |
| - Never pressure: "Koi pressure nahi β aap decide karein" | |
| - Social proof: "Mere X customers ne same concern diya tha β aaj sab khush hain" | |
| - Offer proof: "Main ek existing customer ka number dunga β unse pooch sakte hain" | |
| - Small step: "Sirf information lijiye β koi commitment nahi" """, | |
| "fear": """Customer is FEARFUL. | |
| - Acknowledge fear first: "Sir yeh concern bilkul valid hai" | |
| - Reduce risk: "Isliye free look period hai β 15 din mein full refund" | |
| - Social proof: "Lakhs of customers ne same decision liya" | |
| - Never minimize their fear""", | |
| "confusion": """Customer is CONFUSED. | |
| - Simplify immediately: "Main ek simple example deta hoon" | |
| - Use analogy: relate to something they know | |
| - One point at a time β never overwhelm | |
| - Check understanding: "Yeh part clear hua?" """, | |
| "competitor_loyalty": """Customer is COMPETITOR LOYAL. | |
| - Never attack competitor: "Woh bhi achhe hain" | |
| - Bridge technique: "Unke saath rahein β bas ek comparison dekhein" | |
| - Highlight one unique strength only | |
| - "Aap khud decide karein β main pressure nahi dunga" """, | |
| "time_pressure": """Customer wants MORE TIME. | |
| - Create gentle urgency: "Sir rate March ke baad badh raha hai" | |
| - Small step close: "Sirf form fill kar lete hain β lock ho jaayega rate" | |
| - Or fix next meeting: "Theek hai β kal 5 baje 10 minute denge?" """, | |
| "excited": """Customer is EXCITED β CLOSE NOW. | |
| - Do not waste time β assume the sale | |
| - "Chaliye abhi lock kar lete hain" | |
| - Move to paperwork immediately | |
| - Any delay kills excitement""", | |
| "happy": """Customer is HAPPY/SATISFIED β UPSELL + REFERRAL. | |
| - Cross-sell: "Ek aur cheez hai jo aapke liye relevant hai" | |
| - Referral ask: "Aapke 2 friends jo same situation mein hain β unka number milega?" | |
| - Deepen relationship""", | |
| "general": """Standard approach: | |
| - Empathy first | |
| - Understand before answering | |
| - One focused suggestion""" | |
| } | |
| return guides.get(emotion, guides["general"]) | |
| def get_industry_guide(industry): | |
| guides = { | |
| "insurance": """ | |
| OPENING: "Namaste sir, ek padosi ne aapka number diya β ghar mein recent changes ke baare mein baat karni thi. Bas 2 minute." | |
| OBJECTIONS: | |
| - Price: "Rs 17/day β ek chai ki kimat mein family ka future secure" | |
| - Already policy: "Bilkul sahi. Lekin ek policy rarely enough hoti hai. Aapki policy mein kya cover hai?" | |
| - Competitor: "LIC 67 saal purani, 98% claim settlement, government backed" | |
| - Trust: "Koi pressure nahi. Bas 10 minute information β decision aapka" | |
| CLOSING: "Sir form fill kar lete hain β koi commitment nahi, sirf details" """, | |
| "real_estate": """ | |
| OPENING: "Sir pre-launch price hai β 3 mahine baad 15% badhega. 5 minute mein details?" | |
| OBJECTIONS: | |
| - Mehengi: "Rent mein 20 saal mein 50 lakh β woh paisa kisi ka nahi. EMI mein ghar apna" | |
| - Rent better: "Rent hamesha badhta hai. EMI fixed rehti hai" | |
| - Builder trust: "RERA registered. Delay pe penalty clause hai" | |
| CLOSING: "Rs 11,000 token se flat block β price lock aaj ki" """, | |
| "automobile": """ | |
| OPENING: "Sir koi pressure nahi β freely dekho. Kaunsa model?" | |
| OBJECTIONS: | |
| - Mehengi: "Daily Rs 267 β ek Ola ride mein apni gaadi" | |
| - EMI zyada: "Tenure badha dete hain β same gaadi, kam EMI" | |
| - Discount: "Price fixed β free accessories add karta hoon" | |
| CLOSING: "Rs 5,000 mein color block aaj" """, | |
| "fintech": """ | |
| OPENING: "FD mein paisa pada hai β 2 minute mein batata hoon kaise 3x kaam kare" | |
| OBJECTIONS: | |
| - Risky: "FD 7% β inflation 6% β real return 1%. SIP mein 12-15%" | |
| - FD better: "FD pe tax cut. ELSS mein 80C benefit bhi" | |
| - Market crash: "Crash mein SIP fayda deta hai β zyada units milte hain" | |
| CLOSING: "Rs 500 SIP se shuru β 5 minute mein account" """, | |
| "pharma": """ | |
| OPENING: "Doctor saab β 2 minute. Ek molecule hai jo aapke patients ke liye specifically design hua" | |
| OBJECTIONS: | |
| - Competitor: "Humara formulation superior absorption β clinical data hai" | |
| - No time: "Sirf 2 minute β ek key study" | |
| - Generic: "Branded mein consistent bioavailability" | |
| CLOSING: "Next Tuesday aaunga feedback lene β samples try karwana" """, | |
| "edtech": """ | |
| OPENING: "Directly poochta hoon β [job role] mein jaana chahte ho? 6 mahine ka roadmap hai" | |
| OBJECTIONS: | |
| - Mehenga: "Ek placement se poori fee recover" | |
| - YouTube free: "YouTube pe info hai, structure nahi. Hum placement dete hain" | |
| CLOSING: "Batch Monday β seat block karte hain" """, | |
| "general": """ | |
| OPENING: "Namaste sir. 2 minute le sakta hoon?" | |
| OBJECTIONS: Value dikhao. Daily cost mein convert karo. Social proof use karo. | |
| CLOSING: Small step lo β token, form, ya next meeting""" | |
| } | |
| return guides.get(industry, guides["general"]) | |
| def learn_from_feedback(): | |
| helpful = supabase.table("feedback").select("*").eq("rating", "helpful").execute() | |
| not_helpful = supabase.table("feedback").select("*").eq("rating", "not_helpful").execute() | |
| learned = 0 | |
| for fb in helpful.data: | |
| situation = fb.get('agent_situation', '') | |
| suggestion = fb.get('suggestion', '') | |
| if not situation or not suggestion: | |
| continue | |
| existing = supabase.table("conversations").select("id").eq("raw_text", situation[:200]).eq("source", "feedback_loop").execute() | |
| if existing.data: | |
| continue | |
| industry = detect_industry(situation) | |
| supabase.table("conversations").insert({ | |
| "source": "feedback_loop", "language": "hindi", "industry": industry, | |
| "raw_text": f"Situation: {situation} Response: {suggestion}", | |
| "outcome": "closed", "objections_found": [], "winning_phrases": [suggestion[:200]], | |
| "losing_phrases": [], "psychological_techniques": [], | |
| "key_lesson": f"Agent confirmed this worked: {suggestion[:150]}", "quality_score": 1.0 | |
| }).execute() | |
| learned += 1 | |
| for fb in not_helpful.data: | |
| situation = fb.get('agent_situation', '') | |
| suggestion = fb.get('suggestion', '') | |
| if not situation or not suggestion: | |
| continue | |
| existing = supabase.table("conversations").select("id").eq("raw_text", situation[:200]).eq("source", "feedback_loop").execute() | |
| if existing.data: | |
| continue | |
| industry = detect_industry(situation) | |
| supabase.table("conversations").insert({ | |
| "source": "feedback_loop", "language": "hindi", "industry": industry, | |
| "raw_text": f"Situation: {situation} Response: {suggestion}", | |
| "outcome": "rejected", "objections_found": [], "winning_phrases": [], | |
| "losing_phrases": [suggestion[:200]], "psychological_techniques": [], | |
| "key_lesson": f"Agent said this did NOT work: {suggestion[:150]}", "quality_score": 0.0 | |
| }).execute() | |
| learned += 1 | |
| return learned | |
| def rebuild_index(): | |
| global index, metadata | |
| all_data = [] | |
| page_size = 1000 | |
| offset = 0 | |
| while True: | |
| result = supabase.table("conversations").select("id, raw_text, outcome, key_lesson, winning_phrases, industry").neq("outcome", "unknown").range(offset, offset + page_size - 1).execute() | |
| if not result.data: | |
| break | |
| all_data.extend(result.data) | |
| if len(result.data) < page_size: | |
| break | |
| offset += page_size | |
| texts = [] | |
| new_metadata = [] | |
| for conv in all_data: | |
| raw = conv.get('raw_text', '') | |
| lesson = conv.get('key_lesson', '') | |
| outcome = conv.get('outcome', 'unknown') | |
| phrases = conv.get('winning_phrases', []) | |
| industry = conv.get('industry', 'general') | |
| searchable = f"{raw[:300]} Outcome: {outcome}. Lesson: {lesson}" | |
| texts.append(searchable) | |
| new_metadata.append({"id": conv['id'], "outcome": outcome, "lesson": lesson, "winning_phrases": phrases, "industry": industry}) | |
| batch_size = 1024 | |
| all_embeddings = [] | |
| for i in range(0, len(texts), batch_size): | |
| batch = texts[i:i+batch_size] | |
| embeddings = encoder.encode(batch, batch_size=32, show_progress_bar=False) | |
| all_embeddings.append(embeddings) | |
| final_embeddings = np.vstack(all_embeddings).astype(np.float32) | |
| new_index = faiss.IndexFlatL2(final_embeddings.shape[1]) | |
| new_index.add(final_embeddings) | |
| faiss.write_index(new_index, "salesbrain.faiss") | |
| with open("salesbrain_meta.pkl", "wb") as f: | |
| pickle.dump(new_metadata, f) | |
| index = new_index | |
| metadata = new_metadata | |
| return new_index.ntotal | |
| def start(message): | |
| bot.reply_to(message, """π§ SalesBrain AI β Emotion Aware Version | |
| Insurance | Real Estate | Automobile | |
| Fintech | Pharma | Edtech | |
| Main samajhta hoon customer ki emotion aur wahi technique suggest karta hoon jo uss emotion ke liye kaam karti hai. | |
| Type karo kya situation hai: | |
| "Customer gussa ho raha hai" | |
| "Customer bol raha hai mehenga hai" | |
| "Customer excited hai but commit nahi kar raha" | |
| "LIC cold call β kya bolun" | |
| /status β brain stats | |
| /reset β naya call shuru karo""") | |
| def reset(message): | |
| user_id = str(message.from_user.id) | |
| conversation_history[user_id] = [] | |
| user_industry[user_id] = "general" | |
| bot.reply_to(message, "π Naya call shuru. Context clear.") | |
| def status(message): | |
| total = get_total() | |
| helpful = supabase.table("feedback").select("id", count="exact").eq("rating", "helpful").execute() | |
| not_helpful = supabase.table("feedback").select("id", count="exact").eq("rating", "not_helpful").execute() | |
| bot.reply_to(message, f"""π§ SalesBrain Status | |
| Conversations: {total} | |
| Searchable: {index.ntotal} | |
| Industries: Insurance | Real Estate | Auto | |
| Fintech | Pharma | Edtech | |
| Feedback: π {helpful.count} | π {not_helpful.count} | |
| Emotions detected: 15 types | |
| Memory: ON | Auto-learning: ON | |
| Status: LIVE""") | |
| def handle_message(message): | |
| user_id = str(message.from_user.id) | |
| detected = detect_industry(message.text) | |
| if detected != "general": | |
| user_industry[user_id] = detected | |
| elif user_id not in user_industry: | |
| user_industry[user_id] = "general" | |
| industry = user_industry[user_id] | |
| emotion = detect_emotion(message.text) | |
| similar = search_brain(message.text, industry=industry, top_k=5) | |
| closed_patterns = [s for s in similar if s['outcome'] == 'closed'] | |
| rejected_patterns = [s for s in similar if s['outcome'] == 'rejected'] | |
| brain_context = "" | |
| if closed_patterns: | |
| brain_context += "Similar situations jo CLOSE hue:\n" | |
| for p in closed_patterns[:3]: | |
| lesson = p.get('lesson', '') | |
| if lesson and 'Emotion' in lesson: | |
| brain_context += f"- {lesson[:120]}\n" | |
| elif lesson: | |
| brain_context += f"- {lesson[:80]}\n" | |
| if rejected_patterns: | |
| brain_context += "\nSimilar situations jo FAIL hue:\n" | |
| for p in rejected_patterns[:2]: | |
| lesson = p.get('lesson', '') | |
| if lesson: | |
| brain_context += f"- Avoid: {lesson[:80]}\n" | |
| emotion_guide = get_emotion_guide(emotion) | |
| industry_guide = get_industry_guide(industry) | |
| if user_id not in conversation_history: | |
| conversation_history[user_id] = [] | |
| system_message = f"""Tu SalesBrain AI hai β Indian sales agents ka expert coach. | |
| Industry: {industry.upper()} | |
| Customer Emotion Detected: {emotion.upper()} | |
| EMOTION GUIDE FOR {emotion.upper()}: | |
| {emotion_guide} | |
| INDUSTRY GUIDE: | |
| {industry_guide} | |
| Brain patterns from {index.ntotal} conversations: | |
| {brain_context} | |
| RULES: | |
| - Emotion ke hisaab se respond karo β yeh sabse important hai | |
| - SIRF EK suggestion do | |
| - Hindi mein Hindi, English mein English | |
| - Pichla context yaad rakho | |
| - Opening/objection/closing β situation ke hisaab se | |
| Format: | |
| π― Emotion: [{emotion}] | |
| Situation samjha: [1 line] | |
| Yeh bolo abhi: "[exact words]" | |
| Kyun kaam karega: [1 line β emotion + technique]""" | |
| conversation_history[user_id].append({ | |
| "role": "user", | |
| "content": f"Agent ki situation: {message.text}" | |
| }) | |
| if len(conversation_history[user_id]) > MAX_HISTORY: | |
| conversation_history[user_id] = conversation_history[user_id][-MAX_HISTORY:] | |
| messages = [{"role": "user", "content": system_message}] | |
| messages.append({"role": "assistant", "content": "Samjha. Emotion aur context ke hisaab se suggest karunga."}) | |
| messages.extend(conversation_history[user_id]) | |
| response = groq.chat.completions.create( | |
| model="llama-3.1-8b-instant", | |
| messages=messages, | |
| max_tokens=180, | |
| temperature=0.1 | |
| ) | |
| suggestion = response.choices[0].message.content | |
| conversation_history[user_id].append({"role": "assistant", "content": suggestion}) | |
| last_suggestion[user_id] = {"situation": message.text, "suggestion": suggestion} | |
| markup = types.InlineKeyboardMarkup() | |
| markup.add( | |
| types.InlineKeyboardButton("π Kaam aaya", callback_data="helpful"), | |
| types.InlineKeyboardButton("π Kaam nahi aaya", callback_data="not_helpful") | |
| ) | |
| industry_emoji = { | |
| "insurance": "π‘οΈ", "real_estate": "π ", "automobile": "π", | |
| "fintech": "π", "pharma": "π", "edtech": "π", "general": "π‘" | |
| } | |
| emotion_emoji = { | |
| "anger": "π€", "irritation": "π", "sarcasm": "π", | |
| "price_sensitivity": "π°", "trust_issues": "π€", "fear": "π°", | |
| "confusion": "π", "competitor_loyalty": "βοΈ", "time_pressure": "β°", | |
| "excited": "π₯", "happy": "π", "general": "π‘" | |
| } | |
| bot.send_message( | |
| message.chat.id, | |
| f"""{emotion_emoji.get(emotion, 'π‘')} {industry_emoji.get(industry, 'π‘')} SalesBrain:\n\n{suggestion}\n\nπ§ {index.ntotal} conversations searched""", | |
| reply_markup=markup | |
| ) | |
| def handle_feedback(call): | |
| user_id = str(call.from_user.id) | |
| data = last_suggestion.get(user_id, {}) | |
| supabase.table("feedback").insert({ | |
| "agent_situation": data.get("situation", ""), | |
| "suggestion": data.get("suggestion", ""), | |
| "rating": call.data | |
| }).execute() | |
| if call.data == "helpful": | |
| bot.answer_callback_query(call.id, "π Badiya!") | |
| bot.send_message(call.message.chat.id, "β Feedback saved.") | |
| else: | |
| bot.answer_callback_query(call.id, "π Noted.") | |
| bot.send_message(call.message.chat.id, "π Feedback saved.") | |
| feedback_count = get_feedback_count() | |
| if feedback_count % 5 == 0: | |
| bot.send_message(call.message.chat.id, "π§ Brain seekh raha hai...") | |
| learned = learn_from_feedback() | |
| if learned > 0: | |
| new_total = rebuild_index() | |
| bot.send_message(call.message.chat.id, f"β¨ Brain updated. {new_total} conversations indexed.") | |