Team Ai
Apppublic

hereisSwapnil/Transcript-Sentiment-Analysis

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
main.py140 linesDownload Raw Back to root
1from flask import Flask, request, jsonify, send_file2import os3import re4import json5from transformers import pipeline6from groq import Groq7from werkzeug.utils import secure_filename8from dotenv import load_dotenv9 10load_dotenv()11 12app = Flask(__name__)13 14GROQ_API_KEY = os.getenv("GROQ_API_KEY")15 16# Sentiment analysis model17sentimentAnalyzer = pipeline(18    "sentiment-analysis", model="lxyuan/distilbert-base-multilingual-cased-sentiments-student")19 20# Initialize Groq API21client = Groq(api_key=GROQ_API_KEY)22 23# Load transcript file24 25 26def loadTranscript(file_path):27    with open(file_path, 'r') as file:28        return file.read()29 30# Extract data from transcript31 32 33def extractCallData(transcript):34    pattern = r'\[(.*?) (\d{2}:\d{2})\]\n(.*?)(?=\[|$)'35    return re.findall(pattern, transcript, re.DOTALL)36 37# Analyze sentiments38 39 40def analyzeSentiment(transcript_data):41    result = []42    for data in transcript_data:43        text = data[2].strip()44        sentiment = sentimentAnalyzer(text)[0]45 46        result.append({47            'time': data[1],48            'text': text,49            'speaker': data[0],50            'sentiment': sentiment['label'],51            'sentiment_score': sentiment['score'],52        })53    return result54 55# Generating feedback56 57 58def getGroqFeedback(analysis_data):59    total_entries = len(analysis_data)60    sentiment_counts = {'positive': 0, 'neutral': 0, 'negative': 0}61    agent_entries = [62        entry for entry in analysis_data if entry['speaker'] == 'Sales Agent']63 64    for entry in analysis_data:65        sentiment_counts[entry['sentiment'].lower()] += 166 67    # Prompt68    prompt = f"""Analyze the following call transcript summary and provide brief, specific feedback on the agent's performance:69 70    Call Summary:71    - Total exchanges: {total_entries}72    - Sentiment distribution: Positive {sentiment_counts['positive']}, Neutral {sentiment_counts['neutral']}, Negative {sentiment_counts['negative']}73    - Agent responses: {len(agent_entries)}74 75    Provide concise, actionable feedback in no more than 150 words."""76 77    chat_completion = client.chat.completions.create(78        messages=[79            {"role": "system", "content": "You are a concise call transcript performance analyst. Provide brief, specific feedback."},80            {"role": "user", "content": prompt}81        ],82        model="mixtral-8x7b-32768",83    )84 85    feedback = chat_completion.choices[0].message.content86    return feedback.strip()87 88# analyze the uploaded transcript89 90 91@app.route('/analyze', methods=['POST'])92def analyze_transcript():93    if 'file' not in request.files:94        return jsonify({"error": "No file uploaded"}), 40095 96    file = request.files['file']97    if file.filename == '':98        return jsonify({"error": "No file selected"}), 40099 100    try:101        filename = secure_filename(file.filename)102        file_path = os.path.join('uploads', filename)103        file.save(file_path)104 105        transcript = loadTranscript(file_path)106        transcriptData = extractCallData(transcript)107        sentimentData = analyzeSentiment(transcriptData)108 109        groq_feedback = getGroqFeedback(sentimentData)110 111        analysis_result_path = os.path.join(112            'results', f'{filename}_analysis.json')113        with open(analysis_result_path, 'w') as result_file:114            json.dump({"analysis_data": sentimentData,115                      "groq_feedback": groq_feedback}, result_file)116 117        return jsonify({118            "message": "Analysis completed",119            "file": analysis_result_path,120            "feedback": groq_feedback,121            "sentiment_data": sentimentData122        }), 200123    except Exception as e:124        return jsonify({"error": str(e)}), 500125 126 127# Download the analysis file128@app.route('/download/<filename>', methods=['GET'])129def download_file(filename):130    try:131        return send_file(os.path.join('results', secure_filename(filename)), as_attachment=True)132    except FileNotFoundError:133        return jsonify({"error": "File not found"}), 404134 135 136if __name__ == '__main__':137    os.makedirs('uploads', exist_ok=True)138    os.makedirs('results', exist_ok=True)139    app.run(debug=False)140