File size: 9,007 Bytes
e3fefe8 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 | const ProfessionalModel = require('../models/professionalModel');
const Groq = require('groq-sdk');
// Initialize Groq client
const groq = new Groq({
apiKey: process.env.GROQ_API_KEY || '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'
});
// Service type mappings for fuzzy matching
const SERVICE_TYPES = [
'plumber', 'electrician', 'carpenter', 'ac mechanic', 'ac technician',
'painter', 'cleaner', 'house cleaner', 'tutor', 'teacher', 'driver',
'chef', 'cook', 'beautician', 'makeup artist', 'hairdresser',
'it technician', 'computer repair', 'security guard', 'gardener',
'mechanic', 'car mechanic', 'welder', 'mason', 'electrician',
'hvac', 'refrigerator repair', 'washing machine repair', 'mobile repair'
];
// Keywords to service type mapping (simple fallback)
const keywordToService = {
'plumb': 'plumber',
'pipe': 'plumber',
'leak': 'plumber',
'tap': 'plumber',
'sink': 'plumber',
'electric': 'electrician',
'wire': 'electrician',
'fan': 'electrician',
'light': 'electrician',
'carpent': 'carpenter',
'wood': 'carpenter',
'furniture': 'carpenter',
'ac': 'ac mechanic',
'cool': 'ac mechanic',
'air condition': 'ac mechanic',
'paint': 'painter',
'wall': 'painter',
'clean': 'cleaner',
'house clean': 'cleaner',
'tutor': 'tutor',
'teach': 'tutor',
'study': 'tutor',
'drive': 'driver',
'car': 'driver',
'chef': 'chef',
'cook': 'chef',
'food': 'chef',
'beauty': 'beautician',
'makeup': 'beautician',
'hair': 'beautician',
'it': 'it technician',
'computer': 'it technician',
'laptop': 'it technician',
'software': 'it technician',
'security': 'security guard',
'guard': 'security guard'
};
const SearchController = {
/**
* GET /api/search?q=
* Search professionals using Groq AI
*/
async search(req, res) {
try {
const { q } = req.query;
if (!q || q.trim().length === 0) {
return res.status(400).json({
success: false,
message: 'Search query is required.'
});
}
const query = q.trim().toLowerCase();
// Step 1: Try Groq AI for smart search
let matchedServices = [];
let aiUsed = false;
try {
const aiResult = await this._aiSearch(query);
if (aiResult && aiResult.services && aiResult.services.length > 0) {
matchedServices = aiResult.services;
aiUsed = true;
}
} catch (aiError) {
console.error('Groq AI error:', aiError.message);
// Fallback to keyword matching
}
// Step 2: Fallback to keyword matching if AI fails or returns nothing
if (matchedServices.length === 0) {
matchedServices = this._keywordSearch(query);
}
// Step 3: Get professionals matching the services
const allProfessionals = await ProfessionalModel.getAll();
// Filter professionals by matched services
let filtered = allProfessionals.filter(pro => {
if (!pro.isAvailable) return false;
const proServices = pro.services || [];
return matchedServices.some(service =>
proServices.some(s => s.toLowerCase().includes(service) || service.includes(s.toLowerCase()))
);
});
// If no matches by service, try name matching
if (filtered.length === 0) {
filtered = allProfessionals.filter(pro => {
if (!pro.isAvailable) return false;
const name = (pro.name || '').toLowerCase();
return name.includes(query) || query.includes(name);
});
}
// Add relevance score and sort
const results = filtered.map(pro => ({
phone: pro.phone,
name: pro.name,
services: pro.services || [],
location: pro.location,
rating: pro.rating || 0,
isAvailable: pro.isAvailable,
photoURL: pro.photoURL || '',
relevance: this._calculateRelevance(pro, query, matchedServices)
}));
// Sort by relevance (highest first)
results.sort((a, b) => b.relevance - a.relevance);
return res.status(200).json({
success: true,
data: {
query,
aiUsed,
matchedServices,
results,
count: results.length
}
});
} catch (error) {
console.error('Search error:', error);
return res.status(500).json({
success: false,
message: 'Search failed. Please try again.'
});
}
},
/**
* AI-based search using Groq
*/
async _aiSearch(query) {
try {
const prompt = `You are a service matching assistant. Analyze the user query and return ONLY the matching service types from this list: ${SERVICE_TYPES.join(', ')}.
User query: "${query}"
Return a JSON object with this exact format:
{
"services": ["service1", "service2"],
"confidence": "high/medium/low",
"explanation": "brief reason"
}
If no service matches, return empty array for services.`;
const completion = await groq.chat.completions.create({
messages: [
{
role: 'system',
content: 'You are a service matching assistant. Return only valid JSON.'
},
{
role: 'user',
content: prompt
}
],
model: 'llama3-8b-8192',
temperature: 0.3,
max_tokens: 500
});
const response = completion.choices[0]?.message?.content || '';
// Extract JSON from response
const jsonMatch = response.match(/\{[\s\S]*\}/);
if (jsonMatch) {
const result = JSON.parse(jsonMatch[0]);
return {
services: result.services || [],
confidence: result.confidence || 'low',
explanation: result.explanation || ''
};
}
return { services: [], confidence: 'low', explanation: '' };
} catch (error) {
console.error('Groq AI error:', error);
return { services: [], confidence: 'low', explanation: '' };
}
},
/**
* Keyword-based search (fallback)
*/
_keywordSearch(query) {
const matchedServices = new Set();
// Check direct service type matches
for (const service of SERVICE_TYPES) {
if (service.includes(query) || query.includes(service)) {
matchedServices.add(service);
}
}
// Check keyword mapping
for (const [keyword, service] of Object.entries(keywordToService)) {
if (query.includes(keyword)) {
matchedServices.add(service);
}
}
// If still no matches, add common services based on query length
if (matchedServices.size === 0 && query.length > 2) {
// Try partial matches
for (const service of SERVICE_TYPES) {
if (service.split(' ').some(word => query.includes(word) || word.includes(query))) {
matchedServices.add(service);
}
}
}
return Array.from(matchedServices);
},
/**
* Calculate relevance score for sorting
*/
_calculateRelevance(professional, query, matchedServices) {
let score = 0;
// Service match (higher weight)
const proServices = (professional.services || []).map(s => s.toLowerCase());
for (const service of matchedServices) {
if (proServices.some(s => s.includes(service) || service.includes(s))) {
score += 10;
}
}
// Name match
const name = (professional.name || '').toLowerCase();
if (name.includes(query)) {
score += 5;
}
// Rating boost
score += (professional.rating || 0);
return score;
},
/**
* GET /api/search/suggest?q=
* Get search suggestions (auto-complete)
*/
async getSuggestions(req, res) {
try {
const { q } = req.query;
if (!q || q.trim().length < 2) {
return res.status(200).json({
success: true,
data: { suggestions: [] }
});
}
const query = q.trim().toLowerCase();
const suggestions = new Set();
// Add matching service types
for (const service of SERVICE_TYPES) {
if (service.includes(query) || query.includes(service)) {
suggestions.add(service);
}
}
// Add suggestions from professional names
const allProfessionals = await ProfessionalModel.getAll();
for (const pro of allProfessionals) {
const name = (pro.name || '').toLowerCase();
if (name.includes(query)) {
suggestions.add(name);
}
}
return res.status(200).json({
success: true,
data: {
suggestions: Array.from(suggestions).slice(0, 10)
}
});
} catch (error) {
console.error('Suggestions error:', error);
return res.status(500).json({
success: false,
message: 'Failed to get suggestions.'
});
}
}
};
module.exports = SearchController; |