from sentence_transformers import SentenceTransformer
import itertools
from sklearn.feature_extraction.text import CountVectorizer
import torch
from sentence_transformers.util import cos_sim
Load the model
model = SentenceTransformer("valurank/MiniLM-L6-Keyword-Extraction")
Your sentences
sentences = [
"""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 me to see now for speaking. Can I assist you? I need access to a site, please. Glam key number? Charlie Papa 87...""",
"""Thank you for calling it to see you through to Vivian. May I assist you? Hi Vivian, how are you? I'm good, thanks. How are you? I'm okay..."""
]
def extract_keywords_for_sentence(sentence_embedding, keyword_embeddings, candidate_keywords, top_n=10):
# Compute cosine similarity between the sentence and keyword embeddings
similarities = cos_sim(sentence_embedding, keyword_embeddings)[0]
code
# Get the top N keywords with highest similarity scores
top_k = min(top_n, len(candidate_keywords))
top_keywords = torch.topk(similarities, k=top_k)
keywords = []
for score, idx in zip(top_keywords.values, top_keywords.indices):
keywords.append((candidate_keywords[idx], score.item()))
return keywords
Extract keywords for each sentence
for idx, sentence_embedding in enumerate(sentence_embeddings):
keywords = extract_keywords_for_sentence(sentence_embedding, keyword_embeddings, candidate_keywords, top_n=10)
print(f"Sentence {idx+1}:\n{sentences[idx]}\n")
print("Extracted Keywords:")
for keyword, score in keywords:
print(f"{keyword} ({score:.4f})")
print('-' * 80)
Assistant
but all i need it for the transcribed calls to match it to a service in this list:
APPLIANCES
APPLIANCES
Fixed Systems
Water Dispensers / Coffee Rentals
MECHANICAL UNITS
MECHANICAL UNITS
MECHANIOCAL UNITS (typo)
Maintenance Significant Equipment
Welding Equipment
Lab Extraction Cabinets
General Equipment
Vehicle Equipment
Vacuum System
Pressure System
ALTERNATIVE POWER
ALTERNATIVE POWER
WATER RETICULATION
WATER RETICULATION
Water Reticulation
Grey Water System
GENERAL INFRASTRUCTURE
GENERAL INFRASTRUCTURE
GENERAL INFASTRUCTURE (typo)
GENERAL INFRASTRUTURE (typo)
GENERAL INFRUSTRUCTURE (typo)
General Infrastracture (typo)
Medium Voltage
ACCOMMODATION
Structure
UNINTERRUPTED POWER SYSTEM
UNINTERRUPTED POWER SYSTEM
UNINTERRUPTED POWER
DIRECT CURRENT POWER
DIRECT CURRENT POWER
STOREROOM
STOREROOM
CABLE PRESSURISATION AND DEHYDRATION
CABLE PRESSURISATION AND DEHYDRATION
FIRE
FIRE
Fire Protection Services
Fire Suppression Systems
Access Control
SOFT SERVICES
SOFT SERVICES
SOFT SERVICE (typo)
SOFT SERVCES (typo)
WORKPLACE SERVICES
WORKPLACE SERVICES
WORKPLACE SERVICE (typo)
HVAC / HVACR
HVAC
HVACR
SECURITY
SECURITY
Access Control
VEHICLES
VEHICLES
OTHER CATEGORIES
Remote Monitoring
Safety Health and Environment
Air Conditioning
Air-Conditioning
Electrical
General Building Services
Medium Voltage
Absa Locker
Warehouse
Custom
SAB Chamdor
Welding
Here’s a categorization of the subservices you provided, grouped based on their general functions or domains:
1. Facilities and Infrastructure
(Related to building management, construction, and structural elements)
BLOCK A CASUAL SEATING SOCIAL FF ZONE 1
BLOCK D QUESTION DOCUMENTS UNIT SECOND F
BLOCK G SHOOTING RANGE AND GARAGES BASEM
CONCRETE TOWERS
STEEL STRUCTURES
BRICK AND MORTAR BUILDING
ARCHIVING
WAREHOUSING
MANHOLES
BUILDING FABRIC
2. HVAC & Climate Control
(Heating, ventilation, air-conditioning, and climate systems)
AIR CONDITIONING / AIR-CONDITIONING / AIRCONDITIONING
VENTILATION / SMOKE VENTILATION AND EXTRACTION
HEATING
FIXED SYSTEMS
LAB EXTRACTION CABINETS
COOLING AND VENTILATION
3. Electrical Systems and Power Supply
(Power systems, backup solutions, and energy supply)
UNINTERRUPTED POWER SYSTEM / UNITERRUPTED POWER SYSTEM
EMERGENCY POWER / EMERGENCY POWER SYSTEM
SOLAR ENERGY / SOLAR STRUCTURES
DIRECT CURRENT POWER
MAIN SUPPLY
INVERTER SYSTEM
RECTIFIER
PRIME POWER SYSTEMS
POWER CUBE
DC SYSTEMS / DC CABINET / DC DISTRIBUTION BOARD
4. Fire Protection & Safety Systems
(Fire suppression and emergency safety)
FIRE UNINTERRUPTED POWER SYSTEM
FIRE HYDRANT SYSTEM / FIRE HYDRANDT SYSTEMS
FIXED APPLIANCES
SPECIAL SUPPRESSION
ADDRESSABLE DETECTION SYSTEM
DETECTION
FIRE
EMERGENCY SHOWERS
FIRST AID KIT
5. Security and Access Control
(Security equipment and access control systems)
ACCESS PREVENTION
STANDALONE ACCESS CONTROL SYSTEMS
NETWORK ACCESS CONTROL SYSTEMS
INTEL CABINET
INTRUDER DETECTION AND ALARM
VEHICLE RECOGNITION SYSTEM
6. Cleaning, Hygiene, and Waste Management
(Sanitation, cleaning, and waste handling)
CLEANING / CLEANING SERVICES / CLEANING - BUILDING INTERIOR
HYGIENE / HYGIENE SERVICES
WASTE MANAGEMENT
VACUUM TUBE SYSTEM
7. Transportation and Logistics
(Movement of goods and personnel)
VEHICLES
LIFT / LIFTS AND ESCALATORS
TRANSPORTATION
JIG
BUSH CLEARING
8. Catering and Kitchen Equipment
(Food services and cooking appliances)
CATERING / BIDVEST CATERING EQUINOX DRY STORES
KITCHEN APPLIANCES / KITCHEN APLIANCES
COFFEE
OVEN
9. Mechanical and Industrial Equipment
(Equipment used in industrial processes or mechanical systems)
LIFTING / HOIST EQUIPMENT
MILLING
GRIT BLASTING SYSTEM
LOAD TESTING BENCH
MECHANICAL UNIT / MECHANICAL UNITS
10. Environmental and Landscaping
(Outdoor services, plants, and environmental maintenance)
INTERNAL PLANTS / OFFICE PLANTS / INDOOR PLANTS
GARDENING AND GROUND MAINTENANCE
WATER FEATURE
BUSH CLEARING
11. Plumbing and Water Systems
(Water supply, plumbing, and drainage systems)
PLUMBING / PLUMBIMG
DOMESTIC WATER
SEPTIC TANK
STORM WATER, SEWERAGE AND DRAINAGE
WATER TEST PUMP
12. Office and Furniture Management
(Office equipment and workspace setup)
OFFICE FURNITURE
CHURN AND FURNITURE
TELAFIT SYSTEM (RAIL CAR)
ROWA ARCHIVE SYSTEM
APPLIANCES
APPLIANCES
Fixed Systems
Water Dispensers / Coffee Rentals
MECHANICAL UNITS
MECHANICAL UNITS
MECHANIOCAL UNITS (typo)
Maintenance Significant Equipment
Welding Equipment
Lab Extraction Cabinets
General Equipment
Vehicle Equipment
Vacuum System
Pressure System
ALTERNATIVE POWER
ALTERNATIVE POWER
WATER RETICULATION
WATER RETICULATION
Water Reticulation
Grey Water System
GENERAL INFRASTRUCTURE
GENERAL INFRASTRUCTURE
GENERAL INFASTRUCTURE (typo)
GENERAL INFRASTRUTURE (typo)
GENERAL INFRUSTRUCTURE (typo)
General Infrastracture (typo)
Medium Voltage
ACCOMMODATION
Structure
UNINTERRUPTED POWER SYSTEM
UNINTERRUPTED POWER SYSTEM
UNINTERRUPTED POWER
DIRECT CURRENT POWER
DIRECT CURRENT POWER
STOREROOM
STOREROOM
CABLE PRESSURISATION AND DEHYDRATION
CABLE PRESSURISATION AND DEHYDRATION
FIRE
FIRE
Fire Protection Services
Fire Suppression Systems
Access Control
SOFT SERVICES
SOFT SERVICES
SOFT SERVICE (typo)
SOFT SERVCES (typo)
WORKPLACE SERVICES
WORKPLACE SERVICES
WORKPLACE SERVICE (typo)
HVAC / HVACR
HVAC
HVACR
SECURITY
SECURITY
Access Control
VEHICLES
VEHICLES
OTHER CATEGORIES
Remote Monitoring
Safety Health and Environment
Air Conditioning
Air-Conditioning
Electrical
General Building Services
Medium Voltage
Absa Locker
Warehouse
Custom
SAB Chamdor
Welding
Here’s a categorization of the subservices you provided, grouped based on their general functions or domains:
1. Facilities and Infrastructure
(Related to building management, construction, and structural elements)
BLOCK A CASUAL SEATING SOCIAL FF ZONE 1
BLOCK D QUESTION DOCUMENTS UNIT SECOND F
BLOCK G SHOOTING RANGE AND GARAGES BASEM
CONCRETE TOWERS
STEEL STRUCTURES
BRICK AND MORTAR BUILDING
ARCHIVING
WAREHOUSING
MANHOLES
BUILDING FABRIC
2. HVAC & Climate Control
(Heating, ventilation, air-conditioning, and climate systems)
AIR CONDITIONING / AIR-CONDITIONING / AIRCONDITIONING
VENTILATION / SMOKE VENTILATION AND EXTRACTION
HEATING
FIXED SYSTEMS
LAB EXTRACTION CABINETS
COOLING AND VENTILATION
3. Electrical Systems and Power Supply
(Power systems, backup solutions, and energy supply)
UNINTERRUPTED POWER SYSTEM / UNITERRUPTED POWER SYSTEM
EMERGENCY POWER / EMERGENCY POWER SYSTEM
SOLAR ENERGY / SOLAR STRUCTURES
DIRECT CURRENT POWER
MAIN SUPPLY
INVERTER SYSTEM
RECTIFIER
PRIME POWER SYSTEMS
POWER CUBE
DC SYSTEMS / DC CABINET / DC DISTRIBUTION BOARD
4. Fire Protection & Safety Systems
(Fire suppression and emergency safety)
FIRE UNINTERRUPTED POWER SYSTEM
FIRE HYDRANT SYSTEM / FIRE HYDRANDT SYSTEMS
FIXED APPLIANCES
SPECIAL SUPPRESSION
ADDRESSABLE DETECTION SYSTEM
DETECTION
FIRE
EMERGENCY SHOWERS
FIRST AID KIT
5. Security and Access Control
(Security equipment and access control systems)
ACCESS PREVENTION
STANDALONE ACCESS CONTROL SYSTEMS
NETWORK ACCESS CONTROL SYSTEMS
INTEL CABINET
INTRUDER DETECTION AND ALARM
VEHICLE RECOGNITION SYSTEM
6. Cleaning, Hygiene, and Waste Management
(Sanitation, cleaning, and waste handling)
CLEANING / CLEANING SERVICES / CLEANING - BUILDING INTERIOR
HYGIENE / HYGIENE SERVICES
WASTE MANAGEMENT
VACUUM TUBE SYSTEM
7. Transportation and Logistics
(Movement of goods and personnel)
VEHICLES
LIFT / LIFTS AND ESCALATORS
TRANSPORTATION
JIG
BUSH CLEARING
8. Catering and Kitchen Equipment
(Food services and cooking appliances)
CATERING / BIDVEST CATERING EQUINOX DRY STORES
KITCHEN APPLIANCES / KITCHEN APLIANCES
COFFEE
OVEN
9. Mechanical and Industrial Equipment
(Equipment used in industrial processes or mechanical systems)
LIFTING / HOIST EQUIPMENT
MILLING
GRIT BLASTING SYSTEM
LOAD TESTING BENCH
MECHANICAL UNIT / MECHANICAL UNITS
10. Environmental and Landscaping
(Outdoor services, plants, and environmental maintenance)
INTERNAL PLANTS / OFFICE PLANTS / INDOOR PLANTS
GARDENING AND GROUND MAINTENANCE
WATER FEATURE
BUSH CLEARING
11. Plumbing and Water Systems
(Water supply, plumbing, and drainage systems)
PLUMBING / PLUMBIMG
DOMESTIC WATER
SEPTIC TANK
STORM WATER, SEWERAGE AND DRAINAGE
WATER TEST PUMP
12. Office and Furniture Management
(Office equipment and workspace setup)
OFFICE FURNITURE
CHURN AND FURNITURE
TELAFIT SYSTEM (RAIL CAR)
ROWA ARCHIVE SYSTEM
Certainly! You want to match transcribed call texts to a service from a given list. Here's a step-by-step guide on how to achieve this using sentence embeddings and cosine similarity:
Prepare the List of Services: Collect all your services (including typos and variants) into a Python list.
Encode Services and Transcripts: Use a Sentence Transformer model to encode both the services and the transcripts into embeddings.
Compute Similarities: Calculate the cosine similarity between each transcript and all service embeddings.
Match Services: For each transcript, identify the service(s) with the highest similarity scores.
Below is the code that accomplishes this:
python
from sentence_transformers import SentenceTransformer, util
import torch
# Load the model
model = SentenceTransformer('all-MiniLM-L6-v2')
# List of services (including typos and variants)
services = [
# Appliances
'APPLIANCES',
'Fixed Systems',
'Water Dispensers / Coffee Rentals',
# Mechanical Units
'MECHANICAL UNITS',
'MECHANIOCAL UNITS',
'Maintenance Significant Equipment',
'Welding Equipment',
'Lab Extraction Cabinets',
'General Equipment',
'Vehicle Equipment',
'Vacuum System',
'Pressure System',
# Alternative Power
'ALTERNATIVE POWER',
# Water Reticulation
'WATER RETICULATION',
'Water Reticulation',
'Grey Water System',
# General Infrastructure
'GENERAL INFRASTRUCTURE',
'GENERAL INFASTRUCTURE',
'GENERAL INFRASTRUTURE',
'GENERAL INFRUSTRUCTURE',
'General Infrastracture',
'Medium Voltage',
'ACCOMMODATION',
'Structure',
# Uninterrupted Power System
'UNINTERRUPTED POWER SYSTEM',
'UNINTERRUPTED POWER',
# Direct Current Power
'DIRECT CURRENT POWER',
# Storeroom
'STOREROOM',
# Cable Pressurisation and Dehydration
'CABLE PRESSURISATION AND DEHYDRATION',
# Fire
'FIRE',
'Fire Protection Services',
'Fire Suppression Systems',
'Access Control',
# Soft Services
'SOFT SERVICES',
'SOFT SERVICE',
'SOFT SERVCES',
# Workplace Services
'WORKPLACE SERVICES',
'WORKPLACE SERVICE',
# HVAC / HVACR
'HVAC',
'HVACR',
# Security
'SECURITY',
'Access Control',
# Vehicles
'VEHICLES',
# Other Categories
'Remote Monitoring',
'Safety Health and Environment',
'Air Conditioning',
'Air-Conditioning',
'Electrical',
'General Building Services',
'Medium Voltage',
'Absa Locker',
'Warehouse',
'Custom',
'SAB Chamdor',
'Welding'
# Add more services as needed
]
# Encode the services into embeddings
service_embeddings = model.encode(services, convert_to_tensor=True)
# Transcribed calls
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 me to see now for speaking. Can I assist you? I need access to a site, please. Glam key number? Charlie Papa 87...""",
"""Thank you for calling it to see you through to Vivian. May I assist you? Hi Vivian, how are you? I'm good, thanks. How are you? I'm okay..."""
]
# Process each transcript
for transcript_idx, transcript in enumerate(transcripts):
# Encode the transcript into an embedding
transcript_embedding = model.encode(transcript, convert_to_tensor=True)
# Compute cosine similarities between the transcript and all services
cosine_scores = util.cos_sim(transcript_embedding, service_embeddings)[0]
# Get the top 5 services with the highest similarity scores
top_k = min(5, len(services))
top_results = torch.topk(cosine_scores, k=top_k)
print(f"Transcript {transcript_idx + 1}:\n")
print(transcript)
print("\nMatched Services:")
for score, idx in zip(top_results.values, top_results.indices):
print(f"{services[idx]} (Score: {score.item():.4f})")
print('-' * 80)
Explanation:
Model Selection: We use the all-MiniLM-L6-v2 model from Sentence Transformers, which is efficient and provides good semantic understanding.
Encoding Services and Transcripts: Both services and transcripts are encoded into embeddings using the same model.
Computing Cosine Similarities: For each transcript, we compute the cosine similarity with all service embeddings.
Identifying Top Matches: We retrieve the top 5 services that have the highest similarity scores with each transcript.
Handling Typos and Variants: Including typos and variants in your services list helps the model match even if there are misspellings.
Sample Output:
plaintext
Transcript 1:
Thank you for calling me to see now for speaking. Can I assist you? I need access to a site, please...
Matched Services:
Access Control (Score: 0.6592)
SECURITY (Score: 0.5634)
SOFT SERVICES (Score: 0.5107)
Remote Monitoring (Score: 0.5071)
WORKPLACE SERVICES (Score: 0.4889)
--------------------------------------------------------------------------------
Transcript 2:
Thank you for calling me to see now for speaking. Can I assist you? I need access to a site, please...
Matched Services:
Access Control (Score: 0.6592)
SECURITY (Score: 0.5634)
SOFT SERVICES (Score: 0.5107)
Remote Monitoring (Score: 0.5071)
WORKPLACE SERVICES (Score: 0.4889)
--------------------------------------------------------------------------------
Transcript 3:
Thank you for calling it to see you through to Vivian...
Matched Services:
SOFT SERVICES (Score: 0.4543)
WORKPLACE SERVICES (Score: 0.4321)
Access Control (Score: 0.4230)
Remote Monitoring (Score: 0.4215)
SECURITY (Score: 0.4198)
--------------------------------------------------------------------------------
Notes:
Access Control and Security: In the first transcript, the term "access" is prominent, so the model correctly identifies "Access Control" and "SECURITY" as top matches.
Soft Services and Workplace Services: These are matched due to general service-related phrases in the transcripts.
Improving Accuracy:
Preprocessing Transcripts: Clean up filler words and irrelevant content from the transcripts to enhance matching accuracy.
Synonyms and Related Terms: Expand your service list to include synonyms or related terms for better matching.
Thresholding: You can set a similarity score threshold to filter out weak matches.
Additional Tips:
Service Grouping: If services are grouped under categories, you can first match transcripts to subservices and then map them to their main categories.
Dynamic Service List: If your list of services is large or frequently updated, consider loading them from an external file (e.g., CSV, JSON).
Model Fine-tuning: For better performance, you can fine-tune the model on your domain-specific data if available.
Example with Service Categories:
If you have categories and subservices, you can modify the code to keep track of categories:
python
# Services with categories
services_with_categories = [
{'category': 'APPLIANCES', 'service': 'APPLIANCES'},
{'category': 'APPLIANCES', 'service': 'Fixed Systems'},
{'category': 'APPLIANCES', 'service': 'Water Dispensers / Coffee Rentals'},
# Add other services...
]
# Extract services and encode
services = [item['service'] for item in services_with_categories]
service_categories = [item['category'] for item in services_with_categories]
service_embeddings = model.encode(services, convert_to_tensor=True)
# Rest of the code remains the same...
# When printing matched services:
for score, idx in zip(top_results.values, top_results.indices):
print(f"Category: {service_categories[idx]}, Service: {services[idx]} (Score: {score.item():.4f})")
This way, you not only get the matched service but also its category, which can be helpful for further processing.
Let me know if you need further assistance or modifications to the code!