from sentence_transformers import SentenceTransformer, util
import torch

# Load the model
model = SentenceTransformer('all-MiniLM-L6-v2')

# Updated representative sentences for each category
categories_with_sentences = [
    {'category': 'Infrastructure', 'sentence': 'We need assistance with building maintenance and infrastructure issues like plumbing, gates, or waterproofing.'},
    {'category': 'Soft Services', 'sentence': 'We require services related to cleaning, catering, waste management, or landscaping.'},
    {'category': 'Power Systems', 'sentence': 'There is a problem with our power systems such as emergency power, UPS, or solar energy systems.'},
    {'category': 'HVAC', 'sentence': 'Our heating, ventilation, or air conditioning systems are not working properly.'},
    {'category': 'Electrical', 'sentence': 'We are experiencing issues with electrical systems like lighting, distribution, or main supply.'},
    {'category': 'Fire Services', 'sentence': 'We need support with fire safety systems including fire alarms, sprinklers, or suppression systems.'},
    {'category': 'Security', 'sentence': 'We need security services such as CCTV surveillance, intruder alarms, or security patrols.'},
    {'category': 'Water Reticulation', 'sentence': 'We have problems with water systems like domestic water supply, drainage, or water features.'},
    {'category': 'Appliances', 'sentence': 'There are issues with appliances like kitchen equipment, audio-visual devices, or gym equipment.'},
    {'category': 'Mechanical Units', 'sentence': 'We require maintenance for mechanical units like hoists, conveyors, or mechanical equipment.'},
    {'category': 'Masts and Towers', 'sentence': 'We need services related to masts, towers, or satellite antennas.'},
    {'category': 'Access Control', 'sentence': 'We need assistance with **access to a site**, including **key numbers**, **gate access**, **access codes**, or **site permissions**.'},
    {'category': 'Remote Monitoring', 'sentence': 'We require help with systems that enable us to **monitor sites remotely**, such as surveillance or tracking systems.'},
    {'category': 'Safety, Health, and Environment', 'sentence': 'We need safety equipment like first aid kits or assistance with health and environmental issues.'},
    {'category': 'Workplace Services', 'sentence': 'We require workplace services like furniture moves, indoor plants, or archiving.'},
    {'category': 'Lifts', 'sentence': 'Our lifts or escalators are malfunctioning and need repair.'},
    {'category': 'Cable Pressurisation and Dehydration', 'sentence': 'We need services related to cable pressurisation and dehydration systems.'},
    {'category': 'Vehicles', 'sentence': 'We require maintenance or services for vehicles or transportation equipment.'},
    {'category': 'Data and IT Equipment', 'sentence': 'There are issues with data servers, IT equipment, or intelligent cabinets.'},
    {'category': 'Other', 'sentence': 'We have a request that does not fit into standard categories and need assistance.'},
]

# Extract sentences and categories
sentences = [item['sentence'] for item in categories_with_sentences]
categories = [item['category'] for item in categories_with_sentences]

# Encode the category sentences into embeddings
category_embeddings = model.encode(sentences, convert_to_tensor=True)

# Transcribed calls (the actual transcripts)
transcripts = [
    """Thank you for calling me to see now for speaking. Can I assist you? I need access to a site, please. Glam key number? Charlie Papa 87. Charlie Papa 87. 87. Speaking to Leon. Leon, yeah. Site number? 353380. 353380. Site number three five double three eight oh three five double three eight oh, yeah, I'm going to the main listening. No, I'm saying how long? How long? Give us two hours, please. All right, you cannot make sure to close any of that. I'll do that. Thank you. All right, thank you. Bye. Bye-bye.""",
    """Thank you for calling ATC. I'm supposed to push you. How can I assist? Hello. Can you please confirm if the site is logged? 352824. You said it's 352824. And we are at, what's the name? Uku Kanya. Uku Kanya. Okay. The file is closed. Thank you for your concern. Thank you back.""",
    """Okay, how are you? I'm good. Can I please access a site? Key number? B-8-E-W-5-9. Site I-B-8-8-5-3-0-3-8. N-G? Yes. Which gate? N Main gate. Who am I speaking to? Masugi. Which company? CGA. What are you doing then? Maintenance on cell phone. 0902. Sorry. 092-084. 890902-6092-084. How many are you there? I'm alone. And say 5. Thank you.""",
    # Include the rest of your transcripts
]

# Preprocessing function to clean transcripts
def preprocess_transcript(text):
    # Lowercase the text
    text = text.lower()
    # Remove filler words and irrelevant phrases
    filler_phrases = [
        'thank you for calling', 'can i assist you', 'may i assist you',
        'hi', 'hello', 'bye', 'goodbye',
        'how are you', "i'm good", 'i\'m fine', "i'm okay",
        'speaking', 'talking', 'call', 'calling',
        'through to', 'good morning', 'good afternoon', 'good evening',
        'no problem', 'thank you', 'thanks', 'please hold', 'hold on',
        # Additional phrases
        'this is', 'you're speaking with', 'have a nice day', 'bye-bye'
    ]
    for phrase in filler_phrases:
        text = text.replace(phrase, '')
    # Remove extra whitespace
    text = ' '.join(text.split())
    return text

# Process each transcript
for transcript_idx, transcript in enumerate(transcripts):
    # Preprocess the transcript
    cleaned_transcript = preprocess_transcript(transcript)

    # Encode the transcript into an embedding
    transcript_embedding = model.encode(cleaned_transcript, convert_to_tensor=True)

    # Compute cosine similarities between the transcript and all category sentences
    cosine_scores = util.cos_sim(transcript_embedding, category_embeddings)[0]

    # Get the top category with the highest similarity score
    top_result = torch.topk(cosine_scores, k=1)
    top_idx = top_result.indices[0].item()
    top_score = top_result.values[0].item()
    matched_category = categories[top_idx]
    matched_sentence = sentences[top_idx]

    print(f"Transcript {transcript_idx + 1}:\n")
    print(transcript)
    print("\nMatched Category:")
    print(f"Category: {matched_category} (Score: {top_score:.4f})")
    print('-' * 80)


 Cell In[38], line 59
    'this is', 'you're speaking with', 'have a nice day', '''bye-bye'''
                                                                    ^
SyntaxError: unterminated triple-quoted string literal (detected at line 89)