Spaces:
Sleeping
Sleeping
Upload 6 files
Browse files- .gitattributes +1 -0
- Dockerfile +16 -0
- app.py +26 -0
- bot.py +463 -0
- requirements.txt +10 -0
- salesbrain.faiss +3 -0
- salesbrain_meta.pkl +3 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
salesbrain.faiss filter=lfs diff=lfs merge=lfs -text
|
Dockerfile
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.10-slim
|
| 2 |
+
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
|
| 5 |
+
RUN apt-get update && apt-get install -y \
|
| 6 |
+
build-essential \
|
| 7 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 8 |
+
|
| 9 |
+
COPY requirements.txt .
|
| 10 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 11 |
+
|
| 12 |
+
COPY . .
|
| 13 |
+
|
| 14 |
+
EXPOSE 7860
|
| 15 |
+
|
| 16 |
+
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
|
app.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, Request
|
| 2 |
+
import telebot
|
| 3 |
+
import requests
|
| 4 |
+
import os
|
| 5 |
+
import bot as salesbot
|
| 6 |
+
|
| 7 |
+
app = FastAPI()
|
| 8 |
+
|
| 9 |
+
@app.get("/")
|
| 10 |
+
def home():
|
| 11 |
+
return {"status": "SalesBrain is LIVE π§ "}
|
| 12 |
+
|
| 13 |
+
@app.post("/webhook")
|
| 14 |
+
async def webhook(request: Request):
|
| 15 |
+
json_data = await request.json()
|
| 16 |
+
update = telebot.types.Update.de_json(json_data)
|
| 17 |
+
salesbot.bot.process_new_updates([update])
|
| 18 |
+
return {"ok": True}
|
| 19 |
+
|
| 20 |
+
@app.on_event("startup")
|
| 21 |
+
def set_webhook():
|
| 22 |
+
token = os.environ.get("TELEGRAM_TOKEN")
|
| 23 |
+
url = f"https://api.telegram.org/bot{token}/setWebhook"
|
| 24 |
+
webhook_url = "https://rolefitter-salesbrain-bot.hf.space/webhook"
|
| 25 |
+
response = requests.post(url, json={"url": webhook_url})
|
| 26 |
+
print(f"Webhook set: {response.json()}")
|
bot.py
ADDED
|
@@ -0,0 +1,463 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import telebot
|
| 3 |
+
from telebot import types
|
| 4 |
+
from groq import Groq
|
| 5 |
+
from supabase import create_client
|
| 6 |
+
from sentence_transformers import SentenceTransformer
|
| 7 |
+
import faiss
|
| 8 |
+
import pickle
|
| 9 |
+
import numpy as np
|
| 10 |
+
|
| 11 |
+
TELEGRAM_TOKEN = os.environ.get('TELEGRAM_TOKEN')
|
| 12 |
+
GROQ_API_KEY = os.environ.get('GROQ_API_KEY')
|
| 13 |
+
SUPABASE_URL = os.environ.get('SUPABASE_URL')
|
| 14 |
+
SUPABASE_KEY = os.environ.get('SUPABASE_KEY')
|
| 15 |
+
|
| 16 |
+
bot = telebot.TeleBot(TELEGRAM_TOKEN)
|
| 17 |
+
groq = Groq(api_key=GROQ_API_KEY)
|
| 18 |
+
supabase = create_client(SUPABASE_URL, SUPABASE_KEY)
|
| 19 |
+
|
| 20 |
+
print("Loading search engine...")
|
| 21 |
+
encoder = SentenceTransformer('paraphrase-multilingual-MiniLM-L12-v2')
|
| 22 |
+
index = faiss.read_index("salesbrain.faiss")
|
| 23 |
+
with open("salesbrain_meta.pkl", "rb") as f:
|
| 24 |
+
metadata = pickle.load(f)
|
| 25 |
+
print(f"Search engine ready. {index.ntotal} conversations indexed.")
|
| 26 |
+
|
| 27 |
+
last_suggestion = {}
|
| 28 |
+
conversation_history = {}
|
| 29 |
+
user_industry = {}
|
| 30 |
+
MAX_HISTORY = 6
|
| 31 |
+
|
| 32 |
+
def get_total():
|
| 33 |
+
result = supabase.table("conversations").select("id", count="exact").execute()
|
| 34 |
+
return result.count
|
| 35 |
+
|
| 36 |
+
def get_feedback_count():
|
| 37 |
+
result = supabase.table("feedback").select("id", count="exact").execute()
|
| 38 |
+
return result.count
|
| 39 |
+
|
| 40 |
+
def detect_industry(text):
|
| 41 |
+
text_lower = text.lower()
|
| 42 |
+
insurance_keywords = ["policy", "insurance", "lic", "premium", "term plan", "cover", "claim", "bima", "hdfc life", "max life", "sbi life", "nominee"]
|
| 43 |
+
real_estate_keywords = ["property", "flat", "house", "ghar", "plot", "apartment", "builder", "possession", "registry", "rent", "makaan", "zameen", "bhk"]
|
| 44 |
+
automobile_keywords = ["car", "gaadi", "vehicle", "showroom", "test drive", "maruti", "honda", "hyundai", "tata", "petrol", "diesel", "cng", "ev"]
|
| 45 |
+
fintech_keywords = ["mutual fund", "sip", "stock", "share", "demat", "zerodha", "groww", "fd", "fixed deposit", "investment", "portfolio", "nifty", "elss"]
|
| 46 |
+
pharma_keywords = ["doctor", "dr", "molecule", "drug", "medicine", "prescription", "patient", "clinic", "hospital", "sample", "tablet", "clinical"]
|
| 47 |
+
edtech_keywords = ["course", "student", "padhna", "coaching", "class", "certificate", "placement", "batch", "enroll", "fee", "learning", "career"]
|
| 48 |
+
|
| 49 |
+
scores = {
|
| 50 |
+
"insurance": sum(1 for k in insurance_keywords if k in text_lower),
|
| 51 |
+
"real_estate": sum(1 for k in real_estate_keywords if k in text_lower),
|
| 52 |
+
"automobile": sum(1 for k in automobile_keywords if k in text_lower),
|
| 53 |
+
"fintech": sum(1 for k in fintech_keywords if k in text_lower),
|
| 54 |
+
"pharma": sum(1 for k in pharma_keywords if k in text_lower),
|
| 55 |
+
"edtech": sum(1 for k in edtech_keywords if k in text_lower)
|
| 56 |
+
}
|
| 57 |
+
best = max(scores, key=scores.get)
|
| 58 |
+
if scores[best] == 0:
|
| 59 |
+
return "general"
|
| 60 |
+
return best
|
| 61 |
+
|
| 62 |
+
def detect_emotion(text):
|
| 63 |
+
text_lower = text.lower()
|
| 64 |
+
if any(w in text_lower for w in ["gussa", "angry", "bakwaas", "bekar", "fraud", "kyun call", "disturb", "baar baar", "gali", "sala", "bsdk", "mc", "bc"]):
|
| 65 |
+
return "anger"
|
| 66 |
+
if any(w in text_lower for w in ["irritate", "pehle bhi bola", "kitni baar", "time waste", "bore", "tang", "pareshan"]):
|
| 67 |
+
return "irritation"
|
| 68 |
+
if any(w in text_lower for w in ["haan haan sab best", "bilkul free", "pakka guarantee", "100%", "sure sure", "han han"]):
|
| 69 |
+
return "sarcasm"
|
| 70 |
+
if any(w in text_lower for w in ["mehenga", "expensive", "costly", "itna paisa", "afford", "budget", "paisa nahi", "price"]):
|
| 71 |
+
return "price_sensitivity"
|
| 72 |
+
if any(w in text_lower for w in ["trust nahi", "fraud", "sach mein", "guarantee", "proof", "review", "fake", "jhooth"]):
|
| 73 |
+
return "trust_issues"
|
| 74 |
+
if any(w in text_lower for w in ["dar", "risk", "kya hoga", "safe", "loss", "doob", "scary", "tension"]):
|
| 75 |
+
return "fear"
|
| 76 |
+
if any(w in text_lower for w in ["samajh nahi", "confuse", "complicated", "explain", "kya hai", "matlab"]):
|
| 77 |
+
return "confusion"
|
| 78 |
+
if any(w in text_lower for w in ["dusri company", "competitor", "xyz better", "already", "doosra", "better option"]):
|
| 79 |
+
return "competitor_loyalty"
|
| 80 |
+
if any(w in text_lower for w in ["baad mein", "later", "abhi nahi", "kal", "next month", "sochta hoon", "time chahiye"]):
|
| 81 |
+
return "time_pressure"
|
| 82 |
+
if any(w in text_lower for w in ["excited", "great", "amazing", "chahiye", "interested", "batao", "tell me more"]):
|
| 83 |
+
return "excited"
|
| 84 |
+
if any(w in text_lower for w in ["achha laga", "thank", "shukriya", "helpful", "bahut achha", "happy"]):
|
| 85 |
+
return "happy"
|
| 86 |
+
return "general"
|
| 87 |
+
|
| 88 |
+
def search_brain(query, industry="general", top_k=5):
|
| 89 |
+
embedding = encoder.encode([query]).astype(np.float32)
|
| 90 |
+
distances, indices = index.search(embedding, top_k * 4)
|
| 91 |
+
results = []
|
| 92 |
+
fallback = []
|
| 93 |
+
for idx in indices[0]:
|
| 94 |
+
if idx < len(metadata):
|
| 95 |
+
conv = metadata[idx]
|
| 96 |
+
if industry != "general" and conv.get('industry') == industry:
|
| 97 |
+
results.append(conv)
|
| 98 |
+
else:
|
| 99 |
+
fallback.append(conv)
|
| 100 |
+
if len(results) >= top_k:
|
| 101 |
+
break
|
| 102 |
+
if len(results) < top_k:
|
| 103 |
+
results.extend(fallback[:top_k - len(results)])
|
| 104 |
+
return results[:top_k]
|
| 105 |
+
|
| 106 |
+
def get_emotion_guide(emotion):
|
| 107 |
+
guides = {
|
| 108 |
+
"anger": """Customer is ANGRY.
|
| 109 |
+
- Never argue. Never defend.
|
| 110 |
+
- Acknowledge first: "Sir aap bilkul sahi frustrate hain"
|
| 111 |
+
- Create pause: "Main sun raha hoon β bataiye kya hua"
|
| 112 |
+
- One sentence only then silence
|
| 113 |
+
- If abusive: "Sir main samajhta hoon. Jab ready hon tab baat karte hain" β end call politely""",
|
| 114 |
+
"irritation": """Customer is IRRITATED.
|
| 115 |
+
- Acknowledge immediately: "Sir main samajhta hoon β aapka time bahut valuable hai"
|
| 116 |
+
- Promise brevity: "Sirf 30 second β ek important update tha"
|
| 117 |
+
- Never justify why you called again
|
| 118 |
+
- Get to point instantly""",
|
| 119 |
+
"sarcasm": """Customer is being SARCASTIC.
|
| 120 |
+
- Agree with the sarcasm β flip it
|
| 121 |
+
- "Sir aap sahi keh rahe hain β main bhi pehle yehi sochta tha"
|
| 122 |
+
- Then one specific fact that changes the frame
|
| 123 |
+
- Never get defensive""",
|
| 124 |
+
"price_sensitivity": """Customer is PRICE SENSITIVE.
|
| 125 |
+
- Convert to daily cost: "Rs 17/day β ek chai ki kimat"
|
| 126 |
+
- Compare to something they spend on daily
|
| 127 |
+
- Show cost of NOT buying: "Agar kuch ho gaya toh family ko..."
|
| 128 |
+
- Never reduce price first β show value first""",
|
| 129 |
+
"trust_issues": """Customer has TRUST ISSUES.
|
| 130 |
+
- Never pressure: "Koi pressure nahi β aap decide karein"
|
| 131 |
+
- Social proof: "Mere X customers ne same concern diya tha β aaj sab khush hain"
|
| 132 |
+
- Offer proof: "Main ek existing customer ka number dunga β unse pooch sakte hain"
|
| 133 |
+
- Small step: "Sirf information lijiye β koi commitment nahi" """,
|
| 134 |
+
"fear": """Customer is FEARFUL.
|
| 135 |
+
- Acknowledge fear first: "Sir yeh concern bilkul valid hai"
|
| 136 |
+
- Reduce risk: "Isliye free look period hai β 15 din mein full refund"
|
| 137 |
+
- Social proof: "Lakhs of customers ne same decision liya"
|
| 138 |
+
- Never minimize their fear""",
|
| 139 |
+
"confusion": """Customer is CONFUSED.
|
| 140 |
+
- Simplify immediately: "Main ek simple example deta hoon"
|
| 141 |
+
- Use analogy: relate to something they know
|
| 142 |
+
- One point at a time β never overwhelm
|
| 143 |
+
- Check understanding: "Yeh part clear hua?" """,
|
| 144 |
+
"competitor_loyalty": """Customer is COMPETITOR LOYAL.
|
| 145 |
+
- Never attack competitor: "Woh bhi achhe hain"
|
| 146 |
+
- Bridge technique: "Unke saath rahein β bas ek comparison dekhein"
|
| 147 |
+
- Highlight one unique strength only
|
| 148 |
+
- "Aap khud decide karein β main pressure nahi dunga" """,
|
| 149 |
+
"time_pressure": """Customer wants MORE TIME.
|
| 150 |
+
- Create gentle urgency: "Sir rate March ke baad badh raha hai"
|
| 151 |
+
- Small step close: "Sirf form fill kar lete hain β lock ho jaayega rate"
|
| 152 |
+
- Or fix next meeting: "Theek hai β kal 5 baje 10 minute denge?" """,
|
| 153 |
+
"excited": """Customer is EXCITED β CLOSE NOW.
|
| 154 |
+
- Do not waste time β assume the sale
|
| 155 |
+
- "Chaliye abhi lock kar lete hain"
|
| 156 |
+
- Move to paperwork immediately
|
| 157 |
+
- Any delay kills excitement""",
|
| 158 |
+
"happy": """Customer is HAPPY/SATISFIED β UPSELL + REFERRAL.
|
| 159 |
+
- Cross-sell: "Ek aur cheez hai jo aapke liye relevant hai"
|
| 160 |
+
- Referral ask: "Aapke 2 friends jo same situation mein hain β unka number milega?"
|
| 161 |
+
- Deepen relationship""",
|
| 162 |
+
"general": """Standard approach:
|
| 163 |
+
- Empathy first
|
| 164 |
+
- Understand before answering
|
| 165 |
+
- One focused suggestion"""
|
| 166 |
+
}
|
| 167 |
+
return guides.get(emotion, guides["general"])
|
| 168 |
+
|
| 169 |
+
def get_industry_guide(industry):
|
| 170 |
+
guides = {
|
| 171 |
+
"insurance": """
|
| 172 |
+
OPENING: "Namaste sir, ek padosi ne aapka number diya β ghar mein recent changes ke baare mein baat karni thi. Bas 2 minute."
|
| 173 |
+
OBJECTIONS:
|
| 174 |
+
- Price: "Rs 17/day β ek chai ki kimat mein family ka future secure"
|
| 175 |
+
- Already policy: "Bilkul sahi. Lekin ek policy rarely enough hoti hai. Aapki policy mein kya cover hai?"
|
| 176 |
+
- Competitor: "LIC 67 saal purani, 98% claim settlement, government backed"
|
| 177 |
+
- Trust: "Koi pressure nahi. Bas 10 minute information β decision aapka"
|
| 178 |
+
CLOSING: "Sir form fill kar lete hain β koi commitment nahi, sirf details" """,
|
| 179 |
+
"real_estate": """
|
| 180 |
+
OPENING: "Sir pre-launch price hai β 3 mahine baad 15% badhega. 5 minute mein details?"
|
| 181 |
+
OBJECTIONS:
|
| 182 |
+
- Mehengi: "Rent mein 20 saal mein 50 lakh β woh paisa kisi ka nahi. EMI mein ghar apna"
|
| 183 |
+
- Rent better: "Rent hamesha badhta hai. EMI fixed rehti hai"
|
| 184 |
+
- Builder trust: "RERA registered. Delay pe penalty clause hai"
|
| 185 |
+
CLOSING: "Rs 11,000 token se flat block β price lock aaj ki" """,
|
| 186 |
+
"automobile": """
|
| 187 |
+
OPENING: "Sir koi pressure nahi β freely dekho. Kaunsa model?"
|
| 188 |
+
OBJECTIONS:
|
| 189 |
+
- Mehengi: "Daily Rs 267 β ek Ola ride mein apni gaadi"
|
| 190 |
+
- EMI zyada: "Tenure badha dete hain β same gaadi, kam EMI"
|
| 191 |
+
- Discount: "Price fixed β free accessories add karta hoon"
|
| 192 |
+
CLOSING: "Rs 5,000 mein color block aaj" """,
|
| 193 |
+
"fintech": """
|
| 194 |
+
OPENING: "FD mein paisa pada hai β 2 minute mein batata hoon kaise 3x kaam kare"
|
| 195 |
+
OBJECTIONS:
|
| 196 |
+
- Risky: "FD 7% β inflation 6% β real return 1%. SIP mein 12-15%"
|
| 197 |
+
- FD better: "FD pe tax cut. ELSS mein 80C benefit bhi"
|
| 198 |
+
- Market crash: "Crash mein SIP fayda deta hai β zyada units milte hain"
|
| 199 |
+
CLOSING: "Rs 500 SIP se shuru β 5 minute mein account" """,
|
| 200 |
+
"pharma": """
|
| 201 |
+
OPENING: "Doctor saab β 2 minute. Ek molecule hai jo aapke patients ke liye specifically design hua"
|
| 202 |
+
OBJECTIONS:
|
| 203 |
+
- Competitor: "Humara formulation superior absorption β clinical data hai"
|
| 204 |
+
- No time: "Sirf 2 minute β ek key study"
|
| 205 |
+
- Generic: "Branded mein consistent bioavailability"
|
| 206 |
+
CLOSING: "Next Tuesday aaunga feedback lene β samples try karwana" """,
|
| 207 |
+
"edtech": """
|
| 208 |
+
OPENING: "Directly poochta hoon β [job role] mein jaana chahte ho? 6 mahine ka roadmap hai"
|
| 209 |
+
OBJECTIONS:
|
| 210 |
+
- Mehenga: "Ek placement se poori fee recover"
|
| 211 |
+
- YouTube free: "YouTube pe info hai, structure nahi. Hum placement dete hain"
|
| 212 |
+
CLOSING: "Batch Monday β seat block karte hain" """,
|
| 213 |
+
"general": """
|
| 214 |
+
OPENING: "Namaste sir. 2 minute le sakta hoon?"
|
| 215 |
+
OBJECTIONS: Value dikhao. Daily cost mein convert karo. Social proof use karo.
|
| 216 |
+
CLOSING: Small step lo β token, form, ya next meeting"""
|
| 217 |
+
}
|
| 218 |
+
return guides.get(industry, guides["general"])
|
| 219 |
+
|
| 220 |
+
def learn_from_feedback():
|
| 221 |
+
helpful = supabase.table("feedback").select("*").eq("rating", "helpful").execute()
|
| 222 |
+
not_helpful = supabase.table("feedback").select("*").eq("rating", "not_helpful").execute()
|
| 223 |
+
learned = 0
|
| 224 |
+
for fb in helpful.data:
|
| 225 |
+
situation = fb.get('agent_situation', '')
|
| 226 |
+
suggestion = fb.get('suggestion', '')
|
| 227 |
+
if not situation or not suggestion:
|
| 228 |
+
continue
|
| 229 |
+
existing = supabase.table("conversations").select("id").eq("raw_text", situation[:200]).eq("source", "feedback_loop").execute()
|
| 230 |
+
if existing.data:
|
| 231 |
+
continue
|
| 232 |
+
industry = detect_industry(situation)
|
| 233 |
+
supabase.table("conversations").insert({
|
| 234 |
+
"source": "feedback_loop", "language": "hindi", "industry": industry,
|
| 235 |
+
"raw_text": f"Situation: {situation} Response: {suggestion}",
|
| 236 |
+
"outcome": "closed", "objections_found": [], "winning_phrases": [suggestion[:200]],
|
| 237 |
+
"losing_phrases": [], "psychological_techniques": [],
|
| 238 |
+
"key_lesson": f"Agent confirmed this worked: {suggestion[:150]}", "quality_score": 1.0
|
| 239 |
+
}).execute()
|
| 240 |
+
learned += 1
|
| 241 |
+
for fb in not_helpful.data:
|
| 242 |
+
situation = fb.get('agent_situation', '')
|
| 243 |
+
suggestion = fb.get('suggestion', '')
|
| 244 |
+
if not situation or not suggestion:
|
| 245 |
+
continue
|
| 246 |
+
existing = supabase.table("conversations").select("id").eq("raw_text", situation[:200]).eq("source", "feedback_loop").execute()
|
| 247 |
+
if existing.data:
|
| 248 |
+
continue
|
| 249 |
+
industry = detect_industry(situation)
|
| 250 |
+
supabase.table("conversations").insert({
|
| 251 |
+
"source": "feedback_loop", "language": "hindi", "industry": industry,
|
| 252 |
+
"raw_text": f"Situation: {situation} Response: {suggestion}",
|
| 253 |
+
"outcome": "rejected", "objections_found": [], "winning_phrases": [],
|
| 254 |
+
"losing_phrases": [suggestion[:200]], "psychological_techniques": [],
|
| 255 |
+
"key_lesson": f"Agent said this did NOT work: {suggestion[:150]}", "quality_score": 0.0
|
| 256 |
+
}).execute()
|
| 257 |
+
learned += 1
|
| 258 |
+
return learned
|
| 259 |
+
|
| 260 |
+
def rebuild_index():
|
| 261 |
+
global index, metadata
|
| 262 |
+
all_data = []
|
| 263 |
+
page_size = 1000
|
| 264 |
+
offset = 0
|
| 265 |
+
while True:
|
| 266 |
+
result = supabase.table("conversations").select("id, raw_text, outcome, key_lesson, winning_phrases, industry").neq("outcome", "unknown").range(offset, offset + page_size - 1).execute()
|
| 267 |
+
if not result.data:
|
| 268 |
+
break
|
| 269 |
+
all_data.extend(result.data)
|
| 270 |
+
if len(result.data) < page_size:
|
| 271 |
+
break
|
| 272 |
+
offset += page_size
|
| 273 |
+
texts = []
|
| 274 |
+
new_metadata = []
|
| 275 |
+
for conv in all_data:
|
| 276 |
+
raw = conv.get('raw_text', '')
|
| 277 |
+
lesson = conv.get('key_lesson', '')
|
| 278 |
+
outcome = conv.get('outcome', 'unknown')
|
| 279 |
+
phrases = conv.get('winning_phrases', [])
|
| 280 |
+
industry = conv.get('industry', 'general')
|
| 281 |
+
searchable = f"{raw[:300]} Outcome: {outcome}. Lesson: {lesson}"
|
| 282 |
+
texts.append(searchable)
|
| 283 |
+
new_metadata.append({"id": conv['id'], "outcome": outcome, "lesson": lesson, "winning_phrases": phrases, "industry": industry})
|
| 284 |
+
batch_size = 1024
|
| 285 |
+
all_embeddings = []
|
| 286 |
+
for i in range(0, len(texts), batch_size):
|
| 287 |
+
batch = texts[i:i+batch_size]
|
| 288 |
+
embeddings = encoder.encode(batch, batch_size=32, show_progress_bar=False)
|
| 289 |
+
all_embeddings.append(embeddings)
|
| 290 |
+
final_embeddings = np.vstack(all_embeddings).astype(np.float32)
|
| 291 |
+
new_index = faiss.IndexFlatL2(final_embeddings.shape[1])
|
| 292 |
+
new_index.add(final_embeddings)
|
| 293 |
+
faiss.write_index(new_index, "salesbrain.faiss")
|
| 294 |
+
with open("salesbrain_meta.pkl", "wb") as f:
|
| 295 |
+
pickle.dump(new_metadata, f)
|
| 296 |
+
index = new_index
|
| 297 |
+
metadata = new_metadata
|
| 298 |
+
return new_index.ntotal
|
| 299 |
+
|
| 300 |
+
@bot.message_handler(commands=['start'])
|
| 301 |
+
def start(message):
|
| 302 |
+
bot.reply_to(message, """π§ SalesBrain AI β Emotion Aware Version
|
| 303 |
+
|
| 304 |
+
Insurance | Real Estate | Automobile
|
| 305 |
+
Fintech | Pharma | Edtech
|
| 306 |
+
|
| 307 |
+
Main samajhta hoon customer ki emotion aur wahi technique suggest karta hoon jo uss emotion ke liye kaam karti hai.
|
| 308 |
+
|
| 309 |
+
Type karo kya situation hai:
|
| 310 |
+
"Customer gussa ho raha hai"
|
| 311 |
+
"Customer bol raha hai mehenga hai"
|
| 312 |
+
"Customer excited hai but commit nahi kar raha"
|
| 313 |
+
"LIC cold call β kya bolun"
|
| 314 |
+
|
| 315 |
+
/status β brain stats
|
| 316 |
+
/reset β naya call shuru karo""")
|
| 317 |
+
|
| 318 |
+
@bot.message_handler(commands=['reset'])
|
| 319 |
+
def reset(message):
|
| 320 |
+
user_id = str(message.from_user.id)
|
| 321 |
+
conversation_history[user_id] = []
|
| 322 |
+
user_industry[user_id] = "general"
|
| 323 |
+
bot.reply_to(message, "π Naya call shuru. Context clear.")
|
| 324 |
+
|
| 325 |
+
@bot.message_handler(commands=['status'])
|
| 326 |
+
def status(message):
|
| 327 |
+
total = get_total()
|
| 328 |
+
helpful = supabase.table("feedback").select("id", count="exact").eq("rating", "helpful").execute()
|
| 329 |
+
not_helpful = supabase.table("feedback").select("id", count="exact").eq("rating", "not_helpful").execute()
|
| 330 |
+
bot.reply_to(message, f"""π§ SalesBrain Status
|
| 331 |
+
|
| 332 |
+
Conversations: {total}
|
| 333 |
+
Searchable: {index.ntotal}
|
| 334 |
+
|
| 335 |
+
Industries: Insurance | Real Estate | Auto
|
| 336 |
+
Fintech | Pharma | Edtech
|
| 337 |
+
|
| 338 |
+
Feedback: π {helpful.count} | π {not_helpful.count}
|
| 339 |
+
|
| 340 |
+
Emotions detected: 15 types
|
| 341 |
+
Memory: ON | Auto-learning: ON
|
| 342 |
+
Status: LIVE""")
|
| 343 |
+
|
| 344 |
+
@bot.message_handler(func=lambda m: True)
|
| 345 |
+
def handle_message(message):
|
| 346 |
+
user_id = str(message.from_user.id)
|
| 347 |
+
detected = detect_industry(message.text)
|
| 348 |
+
if detected != "general":
|
| 349 |
+
user_industry[user_id] = detected
|
| 350 |
+
elif user_id not in user_industry:
|
| 351 |
+
user_industry[user_id] = "general"
|
| 352 |
+
industry = user_industry[user_id]
|
| 353 |
+
emotion = detect_emotion(message.text)
|
| 354 |
+
similar = search_brain(message.text, industry=industry, top_k=5)
|
| 355 |
+
closed_patterns = [s for s in similar if s['outcome'] == 'closed']
|
| 356 |
+
rejected_patterns = [s for s in similar if s['outcome'] == 'rejected']
|
| 357 |
+
brain_context = ""
|
| 358 |
+
if closed_patterns:
|
| 359 |
+
brain_context += "Similar situations jo CLOSE hue:\n"
|
| 360 |
+
for p in closed_patterns[:3]:
|
| 361 |
+
lesson = p.get('lesson', '')
|
| 362 |
+
if lesson and 'Emotion' in lesson:
|
| 363 |
+
brain_context += f"- {lesson[:120]}\n"
|
| 364 |
+
elif lesson:
|
| 365 |
+
brain_context += f"- {lesson[:80]}\n"
|
| 366 |
+
if rejected_patterns:
|
| 367 |
+
brain_context += "\nSimilar situations jo FAIL hue:\n"
|
| 368 |
+
for p in rejected_patterns[:2]:
|
| 369 |
+
lesson = p.get('lesson', '')
|
| 370 |
+
if lesson:
|
| 371 |
+
brain_context += f"- Avoid: {lesson[:80]}\n"
|
| 372 |
+
emotion_guide = get_emotion_guide(emotion)
|
| 373 |
+
industry_guide = get_industry_guide(industry)
|
| 374 |
+
if user_id not in conversation_history:
|
| 375 |
+
conversation_history[user_id] = []
|
| 376 |
+
system_message = f"""Tu SalesBrain AI hai β Indian sales agents ka expert coach.
|
| 377 |
+
|
| 378 |
+
Industry: {industry.upper()}
|
| 379 |
+
Customer Emotion Detected: {emotion.upper()}
|
| 380 |
+
|
| 381 |
+
EMOTION GUIDE FOR {emotion.upper()}:
|
| 382 |
+
{emotion_guide}
|
| 383 |
+
|
| 384 |
+
INDUSTRY GUIDE:
|
| 385 |
+
{industry_guide}
|
| 386 |
+
|
| 387 |
+
Brain patterns from {index.ntotal} conversations:
|
| 388 |
+
{brain_context}
|
| 389 |
+
|
| 390 |
+
RULES:
|
| 391 |
+
- Emotion ke hisaab se respond karo β yeh sabse important hai
|
| 392 |
+
- SIRF EK suggestion do
|
| 393 |
+
- Hindi mein Hindi, English mein English
|
| 394 |
+
- Pichla context yaad rakho
|
| 395 |
+
- Opening/objection/closing β situation ke hisaab se
|
| 396 |
+
|
| 397 |
+
Format:
|
| 398 |
+
π― Emotion: [{emotion}]
|
| 399 |
+
Situation samjha: [1 line]
|
| 400 |
+
Yeh bolo abhi: "[exact words]"
|
| 401 |
+
Kyun kaam karega: [1 line β emotion + technique]"""
|
| 402 |
+
|
| 403 |
+
conversation_history[user_id].append({
|
| 404 |
+
"role": "user",
|
| 405 |
+
"content": f"Agent ki situation: {message.text}"
|
| 406 |
+
})
|
| 407 |
+
if len(conversation_history[user_id]) > MAX_HISTORY:
|
| 408 |
+
conversation_history[user_id] = conversation_history[user_id][-MAX_HISTORY:]
|
| 409 |
+
messages = [{"role": "user", "content": system_message}]
|
| 410 |
+
messages.append({"role": "assistant", "content": "Samjha. Emotion aur context ke hisaab se suggest karunga."})
|
| 411 |
+
messages.extend(conversation_history[user_id])
|
| 412 |
+
response = groq.chat.completions.create(
|
| 413 |
+
model="llama-3.1-8b-instant",
|
| 414 |
+
messages=messages,
|
| 415 |
+
max_tokens=180,
|
| 416 |
+
temperature=0.1
|
| 417 |
+
)
|
| 418 |
+
suggestion = response.choices[0].message.content
|
| 419 |
+
conversation_history[user_id].append({"role": "assistant", "content": suggestion})
|
| 420 |
+
last_suggestion[user_id] = {"situation": message.text, "suggestion": suggestion}
|
| 421 |
+
markup = types.InlineKeyboardMarkup()
|
| 422 |
+
markup.add(
|
| 423 |
+
types.InlineKeyboardButton("π Kaam aaya", callback_data="helpful"),
|
| 424 |
+
types.InlineKeyboardButton("π Kaam nahi aaya", callback_data="not_helpful")
|
| 425 |
+
)
|
| 426 |
+
industry_emoji = {
|
| 427 |
+
"insurance": "π‘οΈ", "real_estate": "π ", "automobile": "π",
|
| 428 |
+
"fintech": "π", "pharma": "π", "edtech": "π", "general": "π‘"
|
| 429 |
+
}
|
| 430 |
+
emotion_emoji = {
|
| 431 |
+
"anger": "π€", "irritation": "π", "sarcasm": "π",
|
| 432 |
+
"price_sensitivity": "π°", "trust_issues": "π€", "fear": "π°",
|
| 433 |
+
"confusion": "π", "competitor_loyalty": "βοΈ", "time_pressure": "β°",
|
| 434 |
+
"excited": "π₯", "happy": "π", "general": "π‘"
|
| 435 |
+
}
|
| 436 |
+
bot.send_message(
|
| 437 |
+
message.chat.id,
|
| 438 |
+
f"""{emotion_emoji.get(emotion, 'π‘')} {industry_emoji.get(industry, 'π‘')} SalesBrain:\n\n{suggestion}\n\nπ§ {index.ntotal} conversations searched""",
|
| 439 |
+
reply_markup=markup
|
| 440 |
+
)
|
| 441 |
+
|
| 442 |
+
@bot.callback_query_handler(func=lambda call: call.data in ["helpful", "not_helpful"])
|
| 443 |
+
def handle_feedback(call):
|
| 444 |
+
user_id = str(call.from_user.id)
|
| 445 |
+
data = last_suggestion.get(user_id, {})
|
| 446 |
+
supabase.table("feedback").insert({
|
| 447 |
+
"agent_situation": data.get("situation", ""),
|
| 448 |
+
"suggestion": data.get("suggestion", ""),
|
| 449 |
+
"rating": call.data
|
| 450 |
+
}).execute()
|
| 451 |
+
if call.data == "helpful":
|
| 452 |
+
bot.answer_callback_query(call.id, "π Badiya!")
|
| 453 |
+
bot.send_message(call.message.chat.id, "β
Feedback saved.")
|
| 454 |
+
else:
|
| 455 |
+
bot.answer_callback_query(call.id, "π Noted.")
|
| 456 |
+
bot.send_message(call.message.chat.id, "π Feedback saved.")
|
| 457 |
+
feedback_count = get_feedback_count()
|
| 458 |
+
if feedback_count % 5 == 0:
|
| 459 |
+
bot.send_message(call.message.chat.id, "π§ Brain seekh raha hai...")
|
| 460 |
+
learned = learn_from_feedback()
|
| 461 |
+
if learned > 0:
|
| 462 |
+
new_total = rebuild_index()
|
| 463 |
+
bot.send_message(call.message.chat.id, f"β¨ Brain updated. {new_total} conversations indexed.")
|
requirements.txt
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pyTelegramBotAPI
|
| 2 |
+
groq
|
| 3 |
+
supabase
|
| 4 |
+
sentence-transformers
|
| 5 |
+
faiss-cpu
|
| 6 |
+
numpy
|
| 7 |
+
fastapi
|
| 8 |
+
uvicorn
|
| 9 |
+
python-multipart
|
| 10 |
+
requests
|
salesbrain.faiss
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2ed29126cf888a18822aba930394b881093da2a948fa58aa1548dc0d661b4ebe
|
| 3 |
+
size 29988909
|
salesbrain_meta.pkl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:553e849f1624bb2840d4e4f3aef1065c90fedd1ab2107dc1130dcab81e60e729
|
| 3 |
+
size 3380737
|