# from pydantic import NoneStr import os import mimetypes import requests import tempfile import gradio as gr import openai import re import json from transformers import pipeline import matplotlib.pyplot as plt import plotly.express as px class SentimentAnalyzer: def __init__(self): self.model="facebook/bart-large-mnli" def analyze_sentiment(self, text): pipe = pipeline("zero-shot-classification", model=self.model) label=["positive","negative","neutral"] result = pipe(text, label) sentiment_scores= {result['labels'][0]:result['scores'][0],result['labels'][1]:result['scores'][1],result['labels'][2]:result['scores'][2]} sentiment_scores_str = f"Positive: {sentiment_scores['positive']:.2f}, Neutral: {sentiment_scores['neutral']:.2f}, Negative: {sentiment_scores['negative']:.2f}" return sentiment_scores_str def emotion_analysis(self,text): prompt = f""" Your task is to analyze {text} and predict the emotion using scores. Emotions are categorized into the following list: Sadness, Happiness, Joy, Fear, Disgust, and Anger. You need to provide the emotion with the highest score. The scores should be in the range of 0.0 to 1.0, where 1.0 represents the highest intensity of the emotion. Please analyze the text and provide the output in the following format: emotion: score [with one result having the highest score].""" response = openai.Completion.create( model="text-davinci-003", prompt=prompt, temperature=1, max_tokens=60, top_p=1, frequency_penalty=0, presence_penalty=0 ) message = response.choices[0].text.strip().replace("\n","") print(message) return message def analyze_sentiment_for_graph(self, text): pipe = pipeline("zero-shot-classification", model=self.model) label=["positive", "negative", "neutral"] result = pipe(text, label) sentiment_scores = { result['labels'][0]: result['scores'][0], result['labels'][1]: result['scores'][1], result['labels'][2]: result['scores'][2] } return sentiment_scores def emotion_analysis_for_graph(self,text): list_of_emotion=text.split(":") label=list_of_emotion[0] score=list_of_emotion[1] score_dict={ label:float(score) } print(score_dict) return score_dict class Summarizer: def __init__(self): pass def generate_summary(self, text): model_engine = "text-davinci-003" prompt = f"""summarize the following conversation delimited by triple backticks. write within 30 words. ```{text}``` """ completions = openai.Completion.create( engine=model_engine, prompt=prompt, max_tokens=60, n=1, stop=None, temperature=0.5, ) message = completions.choices[0].text.strip() return message history_state = gr.State() summarizer = Summarizer() sentiment = SentimentAnalyzer() class LangChain_Document_QA: def __init__(self): pass def _add_text(self,history, text): history = history + [(text, None)] history_state.value = history return history,gr.update(value="", interactive=False) def _agent_text(self,history, text): response = text history[-1][1] = response history_state.value = history return history def _chat_history(self): history = history_state.value formatted_history = " " for entry in history: customer_text, agent_text = entry formatted_history += f"Customer: {customer_text}\n" if agent_text: formatted_history += f"Agent: {agent_text}\n" return formatted_history def _display_history(self): formatted_history=self._chat_history() summary=summarizer.generate_summary(formatted_history) return summary def _display_graph(self,sentiment_scores): labels = sentiment_scores.keys() scores = sentiment_scores.values() fig = px.bar(x=scores, y=labels, orientation='h', color=labels, color_discrete_map={"Negative": "red", "Positive": "green", "Neutral": "gray"}) fig.update_traces(texttemplate='%{x:.2f}%', textposition='outside') fig.update_layout(height=500, width=200) return fig def _history_of_chat(self): history = history_state.value formatted_history = "" client="" agent="" for entry in history: customer_text, agent_text = entry client+=customer_text formatted_history += f"Customer: {customer_text}\n" if agent_text: agent+=agent_text formatted_history += f"Agent: {agent_text}\n" return client,agent def _suggested_answer(self,text): try: history = self._chat_history() start_sequence = "\nCustomer:" restart_sequence = "\nVodafone Customer Relationship Manager:" prompt = 'your task is make a conversation between a customer and vodafone telecom customer relationship manager.' file_path = "vodafone_customer_details.json" with open(file_path) as file: customer_details = json.load(file) prompt = f"""{history}{start_sequence}{text}{restart_sequence} if customer ask any information take it from {customer_details}. if customer say thanks or thankyou tone related messages You should not ask anything to end the conversation with greetings tone. """ response = openai.Completion.create( model="text-davinci-003", prompt=prompt, temperature=0, max_tokens=500, top_p=1, frequency_penalty=0, presence_penalty=0.6, ) message = response.choices[0].text.strip() if ":" in message: message = re.sub(r'^.*:', '', message) return message.strip() except: return "I can't get the response" def _text_box(self,customer_emotion,agent_emotion,agent_sentiment_score,customer_sentiment_score): agent_score = ", ".join([f"{key}: {value:.2f}" for key, value in agent_sentiment_score.items()]) customer_score = ", ".join([f"{key}: {value:.2f}" for key, value in customer_sentiment_score.items()]) return f"customer_emotion:{customer_emotion}\nagent_emotion:{agent_emotion}\nAgent_Sentiment_score:{agent_score}\nCustomer_sentiment_score:{customer_score}" def _on_sentiment_btn_click(self): client,agent=self._history_of_chat() customer_emotion=sentiment.emotion_analysis(client) customer_sentiment_score = sentiment.analyze_sentiment_for_graph(client) agent_emotion=sentiment.emotion_analysis(agent) agent_sentiment_score = sentiment.analyze_sentiment_for_graph(agent) scores=self._text_box(customer_emotion,agent_emotion,agent_sentiment_score,customer_sentiment_score) customer_fig=self._display_graph(customer_sentiment_score) customer_fig.update_layout(title="Sentiment Analysis",width=800) agent_fig=self._display_graph(agent_sentiment_score) agent_fig.update_layout(title="Sentiment Analysis",width=800) agent_emotion_score = sentiment.emotion_analysis_for_graph(agent_emotion) agent_emotion_fig=self._display_graph(agent_emotion_score) agent_emotion_fig.update_layout(title="Emotion Analysis",width=800) customer_emotion_score = sentiment.emotion_analysis_for_graph(customer_emotion) customer_emotion_fig=self._display_graph(customer_emotion_score) customer_emotion_fig.update_layout(title="Emotion Analysis",width=800) return scores,customer_fig,agent_fig,customer_emotion_fig,agent_emotion_fig def clear_func(self): history_state.clear() def gradio_interface(self): with gr.Blocks(css="style.css",theme=gr.themes.Soft()) as demo: with gr.Row(): gr.HTML("""Image Image""") with gr.Row(): gr.HTML("""

Vodafone Generative AI CRM ChatBot

""") chatbot = gr.Chatbot([], elem_id="chatbot").style(height=300) with gr.Row(): with gr.Column(scale=0.50): txt = gr.Textbox( show_label=False, placeholder="Customer", ).style(container=False) with gr.Column(scale=0.50): txt2 = gr.Textbox( show_label=False, placeholder="Agent", ).style(container=False) with gr.Column(scale=0.40): txt3 =gr.Textbox( show_label=False, placeholder="GPT_Suggestion", ).style(container=False) with gr.Column(scale=0.10, min_width=0): button=gr.Button( value="🚀" ) with gr.Column(scale=0.10, min_width=0): clear_btn=gr.Button( value="Clear" ) with gr.Row(): with gr.Column(scale=0.40): txt4 =gr.Textbox( show_label=False, lines=4, placeholder="Summary", ).style(container=False) with gr.Column(scale=0.10, min_width=0): end_btn=gr.Button( value="End" ) with gr.Column(scale=0.40): txt5 =gr.Textbox( show_label=False, lines=4, placeholder="Sentiment", ).style(container=False) with gr.Column(scale=0.10, min_width=0): Sentiment_btn=gr.Button( value="📊",callback=self._on_sentiment_btn_click ) with gr.Row(): gr.HTML("""

Sentiment and Emotion Score Graph

""") with gr.Row(): with gr.Column(scale=0.70, min_width=0): plot =gr.Plot(label="Customer", size=(500, 600)) with gr.Row(): with gr.Column(scale=0.70, min_width=0): plot_2 =gr.Plot(label="Agent", size=(500, 600)) with gr.Row(): with gr.Column(scale=0.70, min_width=0): plot_3 =gr.Plot(label="Customer_Emotion", size=(500, 600)) with gr.Row(): with gr.Column(scale=0.70, min_width=0): plot_4 =gr.Plot(label="Agent_Emotion", size=(500, 600)) txt_msg = txt.submit(self._add_text, [chatbot, txt], [chatbot, txt]) txt_msg.then(lambda: gr.update(interactive=True), None, [txt]) txt.submit(self._suggested_answer,txt,txt3) button.click(self._agent_text, [chatbot,txt3], chatbot) txt2.submit(self._agent_text, [chatbot, txt2], chatbot).then( self._agent_text, [chatbot, txt2], chatbot ) end_btn.click(self._display_history, [], txt4) clear_btn.click(self.clear_func,[],[]) clear_btn.click(lambda: None, None, chatbot, queue=False) Sentiment_btn.click(self._on_sentiment_btn_click,[],[txt5,plot,plot_2,plot_3,plot_4]) demo.title = "Vodafone Generative AI CRM ChatBot" demo.launch() document_qa =LangChain_Document_QA() document_qa.gradio_interface()