bhagyabonam commited on
Commit
adb6afd
·
verified ·
1 Parent(s): 151534c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +37 -30
app.py CHANGED
@@ -1,12 +1,10 @@
1
- import chromadb
2
  from chromadb.config import Settings
3
- from chromadb import Client
4
  from transformers import AutoTokenizer, AutoModel, AutoModelForSequenceClassification, pipeline
5
  import pandas as pd
6
  import numpy as np
7
  import streamlit as st
8
  import speech_recognition as sr
9
- from textblob import TextBlob
10
  from google.oauth2.service_account import Credentials
11
  from googleapiclient.discovery import build
12
  import torch
@@ -24,7 +22,32 @@ SERVICE_ACCOUNT_FILE = r"C:\Users\bhagy\AI\credentials.json"
24
 
25
  csv_file_path = r"C:\Users\bhagy\OneDrive\Desktop\INFOSYS PROJECT\900_products_dataset.csv"
26
 
27
- # sentiment_pipeline = pipeline("sentiment-analysis")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  def get_google_sheets_service():
29
  creds = Credentials.from_service_account_file(
30
  SERVICE_ACCOUNT_FILE,
@@ -60,8 +83,11 @@ def update_google_sheet(transcribed_text, sentiment,objection, recommendations,o
60
  st.error(f"Failed to update Google Sheets: {e}")
61
 
62
  load_dotenv()
63
- huggingface_api_key= os.getenv("HUGGINGFACE_TOKEN")
64
- login(token=huggingface_api_key)
 
 
 
65
 
66
  model_name = "tabularisai/multilingual-sentiment-analysis"
67
  model = AutoModelForSequenceClassification.from_pretrained(model_name)
@@ -80,7 +106,7 @@ def analyze_sentiment(text):
80
 
81
  print(f"Sentiment Analysis Result: {result}")
82
 
83
- # Map raw labels to sentiments
84
  sentiment_map = {
85
  'Very Negative': "NEGATIVE",
86
  'Negative': "NEGATIVE",
@@ -153,27 +179,7 @@ def query_crm_data_with_context(prompt, top_k=3):
153
  return ["Error in querying recommendations."]
154
 
155
 
156
- class CustomEmbeddingFunction:
157
- def __init__(self, model_name="sentence-transformers/all-MiniLM-L6-v2"):
158
- self.tokenizer = AutoTokenizer.from_pretrained(model_name)
159
- self.model = AutoModel.from_pretrained(model_name)
160
-
161
- def __call__(self, text):
162
- inputs = self.tokenizer(text, return_tensors="pt", truncation=True, padding=True, max_length=512)
163
- with torch.no_grad():
164
- outputs = self.model(**inputs)
165
- embeddings = outputs.last_hidden_state.mean(dim=1).squeeze().numpy()
166
- return embeddings
167
-
168
- chroma_client = Client(Settings(persist_directory="chromadb_storage"))
169
- embedding_fn = CustomEmbeddingFunction()
170
- collection_name = "crm_data"
171
 
172
- try:
173
- collection = chroma_client.get_collection(collection_name)
174
- except Exception:
175
- collection = chroma_client.create_collection(collection_name)
176
-
177
  sentence_model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
178
  faiss_index = faiss.IndexFlatL2(384)
179
 
@@ -514,7 +520,7 @@ def generate_post_call_summary(sentiment_history, recommendations=[]):
514
 
515
  st.markdown("### **Future Insights**")
516
 
517
-
518
  if overall_sentiment == "Negative":
519
  st.write("Consider addressing customer pain points more directly. More empathy might improve the sentiment.")
520
  elif overall_sentiment == "Positive":
@@ -535,6 +541,8 @@ def generate_post_call_summary(sentiment_history, recommendations=[]):
535
 
536
  # Main
537
  def main():
 
 
538
  st.title("🤖 RealTime AI-Powered Sales Assistant For Enhanced Conversation")
539
  st.markdown(
540
  "An intelligent assistant to analyze speech, handle objections, and recommend products in real-time."
@@ -609,8 +617,7 @@ def main():
609
  st.markdown(f"{idx}. {feedback_entry}")
610
  else:
611
  st.warning("No feedback submitted yet.")
612
-
613
-
614
  file_path = csv_file_path
615
  data = load_csv(file_path)
616
 
 
 
1
  from chromadb.config import Settings
2
+ from chromadb import PersistentClient
3
  from transformers import AutoTokenizer, AutoModel, AutoModelForSequenceClassification, pipeline
4
  import pandas as pd
5
  import numpy as np
6
  import streamlit as st
7
  import speech_recognition as sr
 
8
  from google.oauth2.service_account import Credentials
9
  from googleapiclient.discovery import build
10
  import torch
 
22
 
23
  csv_file_path = r"C:\Users\bhagy\OneDrive\Desktop\INFOSYS PROJECT\900_products_dataset.csv"
24
 
25
+
26
+ class CustomEmbeddingFunction:
27
+ def __init__(self, model_name="sentence-transformers/all-MiniLM-L6-v2"):
28
+ self.tokenizer = AutoTokenizer.from_pretrained(model_name)
29
+ self.model = AutoModel.from_pretrained(model_name)
30
+
31
+ def __call__(self, text):
32
+ inputs = self.tokenizer(text, return_tensors="pt", truncation=True, padding=True, max_length=512)
33
+ with torch.no_grad():
34
+ outputs = self.model(**inputs)
35
+ embeddings = outputs.last_hidden_state.mean(dim=1).squeeze().numpy()
36
+ return embeddings
37
+
38
+
39
+ sentiment_pipeline = pipeline("sentiment-analysis")
40
+ persist_directory = "chromadb_storage"
41
+ chroma_client = PersistentClient(path=persist_directory)
42
+
43
+ collection_name = "crm_data"
44
+
45
+ try:
46
+ collection = chroma_client.get_collection(name=collection_name)
47
+ except Exception:
48
+ collection = chroma_client.create_collection(name=collection_name)
49
+ embedding_fn = CustomEmbeddingFunction()
50
+
51
  def get_google_sheets_service():
52
  creds = Credentials.from_service_account_file(
53
  SERVICE_ACCOUNT_FILE,
 
83
  st.error(f"Failed to update Google Sheets: {e}")
84
 
85
  load_dotenv()
86
+ hf_token= os.getenv("HUGGINGFACE_TOKEN")
87
+ login(token=hf_token)
88
+ if not hf_token:
89
+ raise ValueError("Hugging Face API key not found! Please set the HUGGINGFACE_TOKEN variable.")
90
+ print(f"API Key Loaded: {hf_token[:5]}****")
91
 
92
  model_name = "tabularisai/multilingual-sentiment-analysis"
93
  model = AutoModelForSequenceClassification.from_pretrained(model_name)
 
106
 
107
  print(f"Sentiment Analysis Result: {result}")
108
 
109
+
110
  sentiment_map = {
111
  'Very Negative': "NEGATIVE",
112
  'Negative': "NEGATIVE",
 
179
  return ["Error in querying recommendations."]
180
 
181
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
182
 
 
 
 
 
 
183
  sentence_model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
184
  faiss_index = faiss.IndexFlatL2(384)
185
 
 
520
 
521
  st.markdown("### **Future Insights**")
522
 
523
+
524
  if overall_sentiment == "Negative":
525
  st.write("Consider addressing customer pain points more directly. More empathy might improve the sentiment.")
526
  elif overall_sentiment == "Positive":
 
541
 
542
  # Main
543
  def main():
544
+
545
+ st.set_page_config(page_title="RealTime AI-Powered Sales Assistant", layout="wide")
546
  st.title("🤖 RealTime AI-Powered Sales Assistant For Enhanced Conversation")
547
  st.markdown(
548
  "An intelligent assistant to analyze speech, handle objections, and recommend products in real-time."
 
617
  st.markdown(f"{idx}. {feedback_entry}")
618
  else:
619
  st.warning("No feedback submitted yet.")
620
+
 
621
  file_path = csv_file_path
622
  data = load_csv(file_path)
623