JoeArmani
commited on
Commit
·
e5be70f
1
Parent(s):
7a0020b
reranker scoring
Browse files- chatbot_model.py +92 -143
- chatbot_validator.py +47 -40
- new_iteration/run_taskmaster_processor.py +1 -1
- new_iteration/taskmaster_processor.py +112 -56
- validate_model.py +0 -4
chatbot_model.py
CHANGED
|
@@ -10,7 +10,6 @@ from pathlib import Path
|
|
| 10 |
import datetime
|
| 11 |
import faiss
|
| 12 |
import gc
|
| 13 |
-
|
| 14 |
import re
|
| 15 |
from tf_data_pipeline import TFDataPipeline
|
| 16 |
from response_quality_checker import ResponseQualityChecker
|
|
@@ -280,15 +279,6 @@ class RetrievalChatbot(DeviceAwareModel):
|
|
| 280 |
|
| 281 |
dummy_input = tf.zeros((1, config.max_context_token_limit), dtype=tf.int32)
|
| 282 |
_ = chatbot.encoder(dummy_input, training=False)
|
| 283 |
-
|
| 284 |
-
# # Then load your custom weights
|
| 285 |
-
# custom_weights_path = load_dir / "encoder_custom_weights.weights.h5"
|
| 286 |
-
# if custom_weights_path.exists():
|
| 287 |
-
# logger.info(f"Loading custom top-level weights from {custom_weights_path}")
|
| 288 |
-
# chatbot.encoder.load_weights(str(custom_weights_path))
|
| 289 |
-
# logger.info("Custom top-level weights loaded successfully.")
|
| 290 |
-
# else:
|
| 291 |
-
# logger.warning(f"Custom weights file not found at {custom_weights_path}.")
|
| 292 |
|
| 293 |
# 4) Load tokenizer
|
| 294 |
chatbot.tokenizer = AutoTokenizer.from_pretrained(load_dir / "tokenizer")
|
|
@@ -361,7 +351,10 @@ class RetrievalChatbot(DeviceAwareModel):
|
|
| 361 |
self.tokenizer.save_pretrained(save_dir / "tokenizer")
|
| 362 |
|
| 363 |
logger.info(f"Models and tokenizer saved to {save_dir}.")
|
| 364 |
-
|
|
|
|
|
|
|
|
|
|
| 365 |
def retrieve_responses_cross_encoder(
|
| 366 |
self,
|
| 367 |
query: str,
|
|
@@ -391,31 +384,34 @@ class RetrievalChatbot(DeviceAwareModel):
|
|
| 391 |
logger.info(f"Summarized Query: {query}")
|
| 392 |
|
| 393 |
detected_domain = self.detect_domain_from_query(query)
|
| 394 |
-
logger.debug(f"Detected domain '{detected_domain}' for query: {query}")
|
| 395 |
|
| 396 |
-
#
|
| 397 |
initial_k = min(top_k * 10, len(self.data_pipeline.response_pool))
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
boosted_candidates = dense_candidates
|
| 401 |
|
| 402 |
-
|
|
|
|
|
|
|
| 403 |
if not reranker:
|
| 404 |
-
logger.warning("No CrossEncoderReranker provided; creating a default one.")
|
| 405 |
reranker = CrossEncoderReranker(model_name="cross-encoder/ms-marco-MiniLM-L-12-v2")
|
| 406 |
|
| 407 |
-
texts = [item[0] for item in boosted_candidates]
|
| 408 |
ce_scores = reranker.rerank(query, texts, max_length=256)
|
| 409 |
|
| 410 |
# Combine cross-encoder score with the base FAISS score (simple multiplicative approach)
|
| 411 |
final_candidates = []
|
| 412 |
-
for (resp_text, faiss_score), ce_score in zip(
|
| 413 |
# TODO: dial this in.
|
| 414 |
-
|
| 415 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 416 |
length_adjusted_score = self.length_adjust_score(resp_text, combined_score)
|
| 417 |
#combined_score = ce_score * faiss_score
|
| 418 |
-
final_candidates.append((resp_text, combined_score))
|
|
|
|
| 419 |
|
| 420 |
# Sort descending by combined score
|
| 421 |
final_candidates.sort(key=lambda x: x[1], reverse=True)
|
|
@@ -434,29 +430,34 @@ class RetrievalChatbot(DeviceAwareModel):
|
|
| 434 |
|
| 435 |
def extract_keywords(self, query: str) -> List[str]:
|
| 436 |
"""
|
| 437 |
-
|
| 438 |
"""
|
| 439 |
query_lower = query.lower()
|
| 440 |
-
|
| 441 |
-
for domain,
|
| 442 |
-
for kw in
|
| 443 |
if kw in query_lower:
|
| 444 |
-
|
| 445 |
-
return list(
|
| 446 |
|
| 447 |
-
def length_adjust_score(
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
if
|
| 456 |
-
|
| 457 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 458 |
base_score += bonus
|
| 459 |
-
|
| 460 |
return base_score
|
| 461 |
|
| 462 |
def detect_domain_from_query(self, query: str) -> str:
|
|
@@ -464,12 +465,12 @@ class RetrievalChatbot(DeviceAwareModel):
|
|
| 464 |
Detect the domain of the query based on keywords.
|
| 465 |
"""
|
| 466 |
domain_patterns = {
|
| 467 |
-
'restaurant': r'\b(restaurant|dining|food|dine|reservation|table|menu|cuisine|eat|place\s?to\s?eat|hungry|chef|dish|meal|fork|knife|spoon|brunch|bistro|buffet|catering|gourmet|fast\s?food|fine\s?dining|takeaway|delivery|restaurant\s?booking)\b',
|
| 468 |
-
'movie': r'\b(movie|cinema|film|ticket|showtime|showing|theater|flick|screening|film\s?ticket|film\s?show|blockbuster|premiere|trailer|director|actor|actress|plot|genre|screen|sequel|animation|documentary)\b',
|
| 469 |
-
'ride_share': r'\b(ride|taxi|uber|lyft|car\s?service|pickup|dropoff|driver|cab|hailing|rideshare|ride\s?hailing|carpool|chauffeur|transit|transportation|hail\s?ride)\b',
|
| 470 |
-
'coffee': r'\b(coffee|café|cafe|starbucks|espresso|latte|mocha|americano|barista|brew|cappuccino|macchiato|iced\s?coffee|cold\s?brew|espresso\s?machine|coffee\s?shop|tea|chai|java|bean|roast|decaf)\b',
|
| 471 |
-
'pizza': r'\b(pizza|delivery|order\s?food|pepperoni|topping|pizzeria|slice|pie|margherita|deep\s?dish|thin\s?crust|cheese|oven|tossed|sauce|garlic\s?bread|calzone)\b',
|
| 472 |
-
'auto': r'\b(car|vehicle|repair|maintenance|mechanic|oil\s?change|garage|auto\s?shop|tire|check\s?engine|battery|transmission|brake|engine\s?diagnostics|carwash|detail|alignment|exhaust|spark\s?plug|dashboard)\b',
|
| 473 |
}
|
| 474 |
|
| 475 |
# Check for matches
|
|
@@ -479,20 +480,20 @@ class RetrievalChatbot(DeviceAwareModel):
|
|
| 479 |
|
| 480 |
return 'other'
|
| 481 |
|
| 482 |
-
def is_numeric_response(text: str) -> bool:
|
| 483 |
"""
|
| 484 |
-
Return True if `text` is purely digits (and/or spaces)
|
| 485 |
-
|
| 486 |
"""
|
| 487 |
-
pattern = r'
|
| 488 |
-
return bool(re.match(pattern, text))
|
| 489 |
|
| 490 |
def retrieve_responses_faiss(
|
| 491 |
self,
|
| 492 |
query: str,
|
| 493 |
domain: str = 'other',
|
| 494 |
top_k: int = 5,
|
| 495 |
-
boost_factor: float = 1.
|
| 496 |
) -> List[Tuple[str, float]]:
|
| 497 |
"""
|
| 498 |
Retrieve top-k responses from the FAISS index (IndexFlatIP) given a user query.
|
|
@@ -511,117 +512,65 @@ class RetrievalChatbot(DeviceAwareModel):
|
|
| 511 |
q_emb_np = q_emb.reshape(1, -1).astype('float32')
|
| 512 |
|
| 513 |
# Search the index
|
| 514 |
-
distances, indices = self.data_pipeline.index.search(q_emb_np, top_k * 10)
|
| 515 |
|
| 516 |
# IndexFlatIP: 'distances' are inner products (cosine similarities for normalized vectors)
|
| 517 |
candidates = []
|
| 518 |
for rank, idx in enumerate(indices[0]):
|
| 519 |
-
if idx
|
| 520 |
-
continue
|
| 521 |
response = self.data_pipeline.response_pool[idx]
|
| 522 |
-
text = response.get('text', '')
|
| 523 |
cand_domain = response.get('domain', 'other')
|
| 524 |
score = distances[0][rank]
|
| 525 |
|
| 526 |
-
#
|
| 527 |
-
|
| 528 |
-
|
| 529 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 530 |
if not candidates:
|
| 531 |
-
logger.warning("No valid candidates found after initial filtering.")
|
| 532 |
return []
|
| 533 |
|
| 534 |
# Sort candidates by score descending
|
| 535 |
candidates.sort(key=lambda x: x[2], reverse=True)
|
| 536 |
|
| 537 |
# Filter in-domain responses
|
| 538 |
-
if
|
| 539 |
-
|
| 540 |
-
|
| 541 |
-
|
| 542 |
-
in_domain_responses = candidates
|
| 543 |
-
else:
|
| 544 |
-
in_domain_responses = candidates
|
| 545 |
|
| 546 |
# Boost responses containing query keywords
|
| 547 |
query_keywords = self.extract_keywords(query)
|
| 548 |
-
|
| 549 |
-
for resp_text, resp_domain, score in
|
| 550 |
-
|
| 551 |
-
|
| 552 |
-
|
| 553 |
-
|
| 554 |
-
|
| 555 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 556 |
|
| 557 |
# Sort boosted responses
|
| 558 |
-
|
| 559 |
-
|
| 560 |
-
# Select top_k responses
|
| 561 |
-
top_responses = boosted_responses[:top_k]
|
| 562 |
-
logger.debug(f"Top {top_k} responses selected.")
|
| 563 |
-
|
| 564 |
-
return top_responses
|
| 565 |
-
# def retrieve_responses_faiss(
|
| 566 |
-
# self,
|
| 567 |
-
# query: str,
|
| 568 |
-
# domain: str = 'other',
|
| 569 |
-
# top_k: int = 5,
|
| 570 |
-
# boost_factor: float = 1.3
|
| 571 |
-
# ) -> List[Tuple[str, float]]:
|
| 572 |
-
# """
|
| 573 |
-
# Retrieve top-k responses from the FAISS index (IndexFlatIP) given a user query.
|
| 574 |
-
|
| 575 |
-
# Args:
|
| 576 |
-
# query: The user input text
|
| 577 |
-
# top_k: Number of top results to return
|
| 578 |
-
|
| 579 |
-
# Returns:
|
| 580 |
-
# List of (response_text, similarity) sorted by descending similarity
|
| 581 |
-
# """
|
| 582 |
-
# # Encode the query
|
| 583 |
-
# q_emb = self.data_pipeline.encode_query(query)
|
| 584 |
-
# q_emb_np = q_emb.reshape(1, -1).astype('float32')
|
| 585 |
-
|
| 586 |
-
# # Search the index
|
| 587 |
-
# distances, indices = self.data_pipeline.index.search(q_emb_np, top_k * 10) # distances: shape [1, k], indices: shape [1, k]
|
| 588 |
-
|
| 589 |
-
# # IndexFlatIP: 'distances' are cosine similarities in [-1, +1].
|
| 590 |
-
# candidates = []
|
| 591 |
-
# for rank, idx in enumerate(indices[0]):
|
| 592 |
-
# text = self.response_pool[idx]['text']
|
| 593 |
-
# cand_domain = self.response_pool[idx]['domain']
|
| 594 |
-
# score = distances[0][rank]
|
| 595 |
-
|
| 596 |
-
# # filter out responses with only numbers or too few words
|
| 597 |
-
# word_count = len(text.split())
|
| 598 |
-
# if not self.is_numeric_resonse(text) and word_count >= 2:
|
| 599 |
-
# candidates.append((text, cand_domain, score))
|
| 600 |
-
|
| 601 |
-
# # Filter to in-domain responses
|
| 602 |
-
# candidates.sort(key=lambda x: x[2], reverse=True)
|
| 603 |
-
# in_domain_responses = [(text, score) for (text, cand_domain, score) in candidates if cand_domain == domain]
|
| 604 |
|
| 605 |
-
|
| 606 |
-
|
| 607 |
-
|
| 608 |
-
|
| 609 |
-
|
| 610 |
-
|
| 611 |
-
# if kw in resp_text.lower():
|
| 612 |
-
# boosted_score = score * boost_factor
|
| 613 |
-
# print(f"Boosting response: '{resp_text}' by factor {boost_factor}")
|
| 614 |
-
# break
|
| 615 |
-
# else:
|
| 616 |
-
# boosted_score = score
|
| 617 |
-
# boosted_responses.append((resp_text, domain, boosted_score))
|
| 618 |
-
|
| 619 |
-
# # Debug
|
| 620 |
-
# logger.debug("\nFAISS Search Results (top 15 for debug):")
|
| 621 |
-
# for i, (resp, score) in enumerate(boosted_responses[:15], start=1):
|
| 622 |
-
# logger.debug(f"{i}. Score: {score:.4f} -> {resp[:60]}")
|
| 623 |
-
|
| 624 |
-
# return boosted_responses[:top_k]
|
| 625 |
|
| 626 |
def chat(
|
| 627 |
self,
|
|
|
|
| 10 |
import datetime
|
| 11 |
import faiss
|
| 12 |
import gc
|
|
|
|
| 13 |
import re
|
| 14 |
from tf_data_pipeline import TFDataPipeline
|
| 15 |
from response_quality_checker import ResponseQualityChecker
|
|
|
|
| 279 |
|
| 280 |
dummy_input = tf.zeros((1, config.max_context_token_limit), dtype=tf.int32)
|
| 281 |
_ = chatbot.encoder(dummy_input, training=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 282 |
|
| 283 |
# 4) Load tokenizer
|
| 284 |
chatbot.tokenizer = AutoTokenizer.from_pretrained(load_dir / "tokenizer")
|
|
|
|
| 351 |
self.tokenizer.save_pretrained(save_dir / "tokenizer")
|
| 352 |
|
| 353 |
logger.info(f"Models and tokenizer saved to {save_dir}.")
|
| 354 |
+
|
| 355 |
+
def sigmoid(self, x: float) -> float:
|
| 356 |
+
return 1 / (1 + np.exp(-x))
|
| 357 |
+
|
| 358 |
def retrieve_responses_cross_encoder(
|
| 359 |
self,
|
| 360 |
query: str,
|
|
|
|
| 384 |
logger.info(f"Summarized Query: {query}")
|
| 385 |
|
| 386 |
detected_domain = self.detect_domain_from_query(query)
|
| 387 |
+
#logger.debug(f"Detected domain '{detected_domain}' for query: {query}")
|
| 388 |
|
| 389 |
+
# Retrieve initial candidates from FAISS
|
| 390 |
initial_k = min(top_k * 10, len(self.data_pipeline.response_pool))
|
| 391 |
+
faiss_candidates = self.retrieve_responses_faiss(query, domain=detected_domain, top_k=initial_k)
|
|
|
|
|
|
|
| 392 |
|
| 393 |
+
texts = [item[0] for item in faiss_candidates]
|
| 394 |
+
|
| 395 |
+
# Re-rank these boosted candidates
|
| 396 |
if not reranker:
|
|
|
|
| 397 |
reranker = CrossEncoderReranker(model_name="cross-encoder/ms-marco-MiniLM-L-12-v2")
|
| 398 |
|
|
|
|
| 399 |
ce_scores = reranker.rerank(query, texts, max_length=256)
|
| 400 |
|
| 401 |
# Combine cross-encoder score with the base FAISS score (simple multiplicative approach)
|
| 402 |
final_candidates = []
|
| 403 |
+
for (resp_text, faiss_score), ce_score in zip(faiss_candidates, ce_scores):
|
| 404 |
# TODO: dial this in.
|
| 405 |
+
ce_prob = self.sigmoid(ce_score) # ~ relevance in [0..1]
|
| 406 |
+
faiss_norm = (faiss_score + 1)/2.0
|
| 407 |
+
combined_score = 0.9 * ce_prob + 0.1 * faiss_norm
|
| 408 |
+
# alpha = 0.9
|
| 409 |
+
# print(f'CE SCORE: {ce_score} FAISS SCORE: {faiss_score}')
|
| 410 |
+
# combined_score = alpha * ce_score + (1 - alpha) * faiss_score
|
| 411 |
length_adjusted_score = self.length_adjust_score(resp_text, combined_score)
|
| 412 |
#combined_score = ce_score * faiss_score
|
| 413 |
+
#final_candidates.append((resp_text, combined_score))
|
| 414 |
+
final_candidates.append((resp_text, length_adjusted_score))
|
| 415 |
|
| 416 |
# Sort descending by combined score
|
| 417 |
final_candidates.sort(key=lambda x: x[1], reverse=True)
|
|
|
|
| 430 |
|
| 431 |
def extract_keywords(self, query: str) -> List[str]:
|
| 432 |
"""
|
| 433 |
+
Return any domain keywords present in the query (lowercased).
|
| 434 |
"""
|
| 435 |
query_lower = query.lower()
|
| 436 |
+
found = set()
|
| 437 |
+
for domain, kw_list in self.DOMAIN_KEYWORDS.items():
|
| 438 |
+
for kw in kw_list:
|
| 439 |
if kw in query_lower:
|
| 440 |
+
found.add(kw)
|
| 441 |
+
return list(found)
|
| 442 |
|
| 443 |
+
def length_adjust_score(self, text: str, base_score: float) -> float:
|
| 444 |
+
"""
|
| 445 |
+
Penalize very short lines or numeric lines; mildly reward longer lines.
|
| 446 |
+
Adjust carefully so you don't overshadow cross-encoder signals.
|
| 447 |
+
"""
|
| 448 |
+
words = text.split()
|
| 449 |
+
wcount = len(words)
|
| 450 |
+
|
| 451 |
+
# Penalty if under 3 words
|
| 452 |
+
if wcount < 4:
|
| 453 |
+
return base_score * 0.8
|
| 454 |
+
|
| 455 |
+
# Bonus for lines > 12 words
|
| 456 |
+
if wcount > 12:
|
| 457 |
+
extra = min(wcount - 12, 8)
|
| 458 |
+
bonus = 0.0005 * extra
|
| 459 |
base_score += bonus
|
| 460 |
+
|
| 461 |
return base_score
|
| 462 |
|
| 463 |
def detect_domain_from_query(self, query: str) -> str:
|
|
|
|
| 465 |
Detect the domain of the query based on keywords.
|
| 466 |
"""
|
| 467 |
domain_patterns = {
|
| 468 |
+
'restaurant': r'\b(restaurant|restaurants?|dining|food|foods?|dine|reservation|reservations?|table|tables?|menu|menus?|cuisine|cuisines?|eat|eats?|place\s?to\s?eat|places\s?to\s?eat|hungry|chef|chefs?|dish|dishes?|meal|meals?|fork|forks?|knife|knives?|spoon|spoons?|brunch|bistro|buffet|buffets?|catering|caterings?|gourmet|fast\s?food|fine\s?dining|takeaway|takeaways?|delivery|deliveries|restaurant\s?booking)\b',
|
| 469 |
+
'movie': r'\b(movie|movies?|cinema|cinemas?|film|films?|ticket|tickets?|showtime|showtimes?|showing|showings?|theater|theaters?|flick|flicks?|screening|screenings?|film\s?ticket|film\s?tickets?|film\s?show|film\s?shows?|blockbuster|blockbusters?|premiere|premieres?|trailer|trailers?|director|directors?|actor|actors?|actress|actresses?|plot|plots?|genre|genres?|screen|screens?|sequel|sequels?|animation|animations?|documentary|documentaries)\b',
|
| 470 |
+
'ride_share': r'\b(ride|rides?|taxi|taxis?|uber|lyft|car\s?service|car\s?services?|pickup|pickups?|dropoff|dropoffs?|driver|drivers?|cab|cabs?|hailing|hailings?|rideshare|rideshares?|ride\s?hailing|ride\s?hailings?|carpool|carpools?|chauffeur|chauffeurs?|transit|transits?|transportation|transportations?|hail\s?ride|hail\s?rides?)\b',
|
| 471 |
+
'coffee': r'\b(coffee|coffees?|café|cafés?|cafe|cafes?|starbucks|espresso|espressos?|latte|lattes?|mocha|mochas?|americano|americanos?|barista|baristas?|brew|brews?|cappuccino|cappuccinos?|macchiato|macchiatos?|iced\s?coffee|iced\s?coffees?|cold\s?brew|cold\s?brews?|espresso\s?machine|espresso\s?machines?|coffee\s?shop|coffee\s?shops?|tea|teas?|chai|chais?|java|javas?|bean|beans?|roast|roasts?|decaf)\b',
|
| 472 |
+
'pizza': r'\b(pizza|pizzas?|delivery|deliveries|order\s?food|order\s?foods?|pepperoni|pepperonis?|topping|toppings?|pizzeria|pizzerias?|slice|slices?|pie|pies?|margherita|margheritas?|deep\s?dish|deep\s?dishes?|thin\s?crust|thin\s?crusts?|cheese|cheeses?|oven|ovens?|tossed|tosses?|sauce|sauces?|garlic\s?bread|garlic\s?breads?|calzone|calzones?)\b',
|
| 473 |
+
'auto': r'\b(car|cars?|vehicle|vehicles?|repair|repairs?|maintenance|maintenances?|mechanic|mechanics?|oil\s?change|oil\s?changes?|garage|garages?|auto\s?shop|auto\s?shops?|tire|tires?|check\s?engine|check\s?engines?|battery|batteries?|transmission|transmissions?|brake|brakes?|engine\s?diagnostics|engine\s?diagnostic|carwash|carwashes?|detail|details?|alignment|alignments?|exhaust|exhausts?|spark\s?plug|spark\s?plugs?|dashboard|dashboards?)\b',
|
| 474 |
}
|
| 475 |
|
| 476 |
# Check for matches
|
|
|
|
| 480 |
|
| 481 |
return 'other'
|
| 482 |
|
| 483 |
+
def is_numeric_response(self, text: str) -> bool:
|
| 484 |
"""
|
| 485 |
+
Return True if `text` is purely digits (and/or spaces),
|
| 486 |
+
with optional punctuation like '.' at the end.
|
| 487 |
"""
|
| 488 |
+
pattern = r'^[\s]*[\d]+([\s.,\d]+)*[\s]*$'
|
| 489 |
+
return bool(re.match(pattern, text.strip()))
|
| 490 |
|
| 491 |
def retrieve_responses_faiss(
|
| 492 |
self,
|
| 493 |
query: str,
|
| 494 |
domain: str = 'other',
|
| 495 |
top_k: int = 5,
|
| 496 |
+
boost_factor: float = 1.05
|
| 497 |
) -> List[Tuple[str, float]]:
|
| 498 |
"""
|
| 499 |
Retrieve top-k responses from the FAISS index (IndexFlatIP) given a user query.
|
|
|
|
| 512 |
q_emb_np = q_emb.reshape(1, -1).astype('float32')
|
| 513 |
|
| 514 |
# Search the index
|
| 515 |
+
distances, indices = self.data_pipeline.index.search(q_emb_np, top_k * 10)
|
| 516 |
|
| 517 |
# IndexFlatIP: 'distances' are inner products (cosine similarities for normalized vectors)
|
| 518 |
candidates = []
|
| 519 |
for rank, idx in enumerate(indices[0]):
|
| 520 |
+
if idx < 0:
|
| 521 |
+
continue
|
| 522 |
response = self.data_pipeline.response_pool[idx]
|
| 523 |
+
text = response.get('text', '').strip()
|
| 524 |
cand_domain = response.get('domain', 'other')
|
| 525 |
score = distances[0][rank]
|
| 526 |
|
| 527 |
+
# Skip purely numeric or extremely short text (fewer than 3 words):
|
| 528 |
+
words = text.split()
|
| 529 |
+
if len(words) < 4:
|
| 530 |
+
continue
|
| 531 |
+
if self.is_numeric_response(text):
|
| 532 |
+
continue
|
| 533 |
+
|
| 534 |
+
candidates.append((text, cand_domain, score))
|
| 535 |
+
|
| 536 |
if not candidates:
|
| 537 |
+
logger.warning("No valid candidates found after initial numeric/length filtering.")
|
| 538 |
return []
|
| 539 |
|
| 540 |
# Sort candidates by score descending
|
| 541 |
candidates.sort(key=lambda x: x[2], reverse=True)
|
| 542 |
|
| 543 |
# Filter in-domain responses
|
| 544 |
+
in_domain = [c for c in candidates if c[1] == domain]
|
| 545 |
+
if not in_domain:
|
| 546 |
+
logger.info(f"No in-domain responses found for '{domain}'. Using all candidates.")
|
| 547 |
+
in_domain = candidates
|
|
|
|
|
|
|
|
|
|
| 548 |
|
| 549 |
# Boost responses containing query keywords
|
| 550 |
query_keywords = self.extract_keywords(query)
|
| 551 |
+
boosted = []
|
| 552 |
+
for (resp_text, resp_domain, score) in in_domain:
|
| 553 |
+
new_score = score
|
| 554 |
+
# If the domain is known AND the response text
|
| 555 |
+
# shares any query keywords, apply a small boost
|
| 556 |
+
if query_keywords and any(kw in resp_text.lower() for kw in query_keywords):
|
| 557 |
+
new_score *= boost_factor
|
| 558 |
+
#logger.debug(f"Boosting response: '{resp_text}' by factor {boost_factor}")
|
| 559 |
+
|
| 560 |
+
# Apply length penalty/bonus
|
| 561 |
+
new_score = self.length_adjust_score(resp_text, new_score)
|
| 562 |
+
|
| 563 |
+
boosted.append((resp_text, new_score))
|
| 564 |
|
| 565 |
# Sort boosted responses
|
| 566 |
+
boosted.sort(key=lambda x: x[1], reverse=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 567 |
|
| 568 |
+
# Print top 10
|
| 569 |
+
for resp, score in boosted[:100]:
|
| 570 |
+
logger.debug(f"Candidate: '{resp}' with score {score}")
|
| 571 |
+
|
| 572 |
+
# 8) Return top_k
|
| 573 |
+
return boosted[:top_k]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 574 |
|
| 575 |
def chat(
|
| 576 |
self,
|
chatbot_validator.py
CHANGED
|
@@ -31,41 +31,48 @@ class ChatbotValidator:
|
|
| 31 |
# Basic domain-specific test queries (easy examples)
|
| 32 |
# Taskmaster-1 and Schema-Guided style
|
| 33 |
self.domain_queries = {
|
| 34 |
-
'restaurant': [
|
| 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 |
def run_validation(
|
|
@@ -237,13 +244,13 @@ class ChatbotValidator:
|
|
| 237 |
is_confident = metrics.get('is_confident', False)
|
| 238 |
|
| 239 |
logger.info(f"Domain: {domain} | Confidence: {'Yes' if is_confident else 'No'}")
|
| 240 |
-
logger.info("Quality Metrics:")
|
| 241 |
-
for k, v in metrics.items():
|
| 242 |
-
|
| 243 |
-
|
| 244 |
|
| 245 |
-
logger.info("Top
|
| 246 |
-
for i, (resp_text, score) in enumerate(responses[:
|
| 247 |
logger.info(f"{i}) Score: {score:.4f} | {resp_text}")
|
| 248 |
if i == 1 and not is_confident:
|
| 249 |
logger.info(" [Low Confidence on Top Response]")
|
|
|
|
| 31 |
# Basic domain-specific test queries (easy examples)
|
| 32 |
# Taskmaster-1 and Schema-Guided style
|
| 33 |
self.domain_queries = {
|
| 34 |
+
# 'restaurant': [
|
| 35 |
+
# "Hi, I have a question about your restaurant. Do they take reservations?",
|
| 36 |
+
# "I'd like to make a reservation for dinner tonight after 6pm. Is that time available?",
|
| 37 |
+
# "Can you recommend an Italian restaurant with wood-fired pizza?",
|
| 38 |
+
# "Is there parking available if we dine at your restaurant tomorrow evening?",
|
| 39 |
+
# "What's the average cost per plate at your restaurant?"
|
| 40 |
+
# # ],
|
| 41 |
+
'movie': [
|
| 42 |
+
"How much are movie tickets for two people?",
|
| 43 |
+
"I'm looking for showings after 6pm?",
|
| 44 |
+
"Is this at the new theater with reclining seats?",
|
| 45 |
+
"Hi, I'm thinking about reserving tickets for the new movie.",
|
| 46 |
+
"What is the price for your largest popcorn?"
|
| 47 |
],
|
| 48 |
+
# 'ride_share': [
|
| 49 |
+
# "I need a ride from the airport to downtown.",
|
| 50 |
+
# "How much would it cost to get to the mall?",
|
| 51 |
+
# "Can you book a car for tomorrow morning?",
|
| 52 |
+
# "Is there a driver available right now?",
|
| 53 |
+
# "What's the estimated arrival time for the driver?"
|
| 54 |
+
# ],
|
| 55 |
+
# 'coffee': [
|
| 56 |
+
# "Can I get a latte with almond milk?",
|
| 57 |
+
# "Can I get a cappuccino with oat milk?",
|
| 58 |
+
# "Can I get a mocha with coconut milk?",
|
| 59 |
+
# "Can I get a cappuccino with almond milk?",
|
| 60 |
+
# "Can I get a mocha with oat milk?",
|
| 61 |
+
# ],
|
| 62 |
+
# 'pizza': [
|
| 63 |
+
# "Can I get a pizza with extra cheese?",
|
| 64 |
+
# "Can I get a pizza with mushrooms?",
|
| 65 |
+
# "Can I get a pizza with bell peppers?",
|
| 66 |
+
# "Can I get a pizza with onions?",
|
| 67 |
+
# "Can I get a pizza with olives?"
|
| 68 |
+
# ],
|
| 69 |
+
# 'auto': [
|
| 70 |
+
# "I need to schedule an oil change for my car.",
|
| 71 |
+
# "When can I bring my car in for maintenance?",
|
| 72 |
+
# "Do you have any openings for auto repair today?",
|
| 73 |
+
# "How long will the service take?",
|
| 74 |
+
# "Can I get an estimate for brake repair?"
|
| 75 |
+
#],
|
| 76 |
}
|
| 77 |
|
| 78 |
def run_validation(
|
|
|
|
| 244 |
is_confident = metrics.get('is_confident', False)
|
| 245 |
|
| 246 |
logger.info(f"Domain: {domain} | Confidence: {'Yes' if is_confident else 'No'}")
|
| 247 |
+
# logger.info("Quality Metrics:")
|
| 248 |
+
# for k, v in metrics.items():
|
| 249 |
+
# if isinstance(v, (int, float)):
|
| 250 |
+
# logger.info(f" {k}: {v:.4f}")
|
| 251 |
|
| 252 |
+
logger.info("Top 10 Responses:")
|
| 253 |
+
for i, (resp_text, score) in enumerate(responses[:10], 1):
|
| 254 |
logger.info(f"{i}) Score: {score:.4f} | {resp_text}")
|
| 255 |
if i == 1 and not is_confident:
|
| 256 |
logger.info(" [Low Confidence on Top Response]")
|
new_iteration/run_taskmaster_processor.py
CHANGED
|
@@ -9,7 +9,7 @@ def main():
|
|
| 9 |
# 1) Setup config
|
| 10 |
config = PipelineConfig(
|
| 11 |
max_length=512,
|
| 12 |
-
min_turns=
|
| 13 |
min_user_words=3,
|
| 14 |
debug=True
|
| 15 |
)
|
|
|
|
| 9 |
# 1) Setup config
|
| 10 |
config = PipelineConfig(
|
| 11 |
max_length=512,
|
| 12 |
+
min_turns=4,
|
| 13 |
min_user_words=3,
|
| 14 |
debug=True
|
| 15 |
)
|
new_iteration/taskmaster_processor.py
CHANGED
|
@@ -1,33 +1,52 @@
|
|
| 1 |
-
import
|
| 2 |
import re
|
|
|
|
| 3 |
from pathlib import Path
|
| 4 |
-
from typing import List, Dict,
|
| 5 |
from dataclasses import dataclass, field
|
| 6 |
|
| 7 |
-
from pipeline_config import PipelineConfig
|
| 8 |
-
|
| 9 |
@dataclass
|
| 10 |
class TaskmasterDialogue:
|
| 11 |
-
"""Structured representation of a Taskmaster-1 dialogue."""
|
| 12 |
conversation_id: str
|
| 13 |
instruction_id: Optional[str]
|
| 14 |
scenario: Optional[str]
|
| 15 |
-
domain: str
|
| 16 |
-
turns: List[Dict[str, Any]]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
def validate(self) -> bool:
|
| 19 |
-
"""Check if this dialogue has an ID and a list of turns."""
|
| 20 |
return bool(self.conversation_id and isinstance(self.turns, list))
|
| 21 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
class TaskmasterProcessor:
|
| 23 |
"""
|
| 24 |
-
Loads Taskmaster-1 dialogues, extracts domain from scenario,
|
| 25 |
-
filters them, and outputs a
|
| 26 |
"""
|
| 27 |
def __init__(self, config: PipelineConfig):
|
| 28 |
self.config = config
|
| 29 |
|
| 30 |
-
def load_taskmaster_dataset(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
"""
|
| 32 |
Load and parse Taskmaster JSON for self-dialogs & woz-dialogs (Taskmaster-1).
|
| 33 |
Combines scenario text + conversation utterances to detect domain more robustly.
|
|
@@ -35,14 +54,14 @@ class TaskmasterProcessor:
|
|
| 35 |
required_files = {
|
| 36 |
"self-dialogs": "self-dialogs.json",
|
| 37 |
"woz-dialogs": "woz-dialogs.json",
|
| 38 |
-
"ontology": "ontology.json", # we might not actively use
|
| 39 |
}
|
| 40 |
-
# Check for missing
|
| 41 |
missing = [k for k, v in required_files.items() if not Path(base_dir, v).exists()]
|
| 42 |
if missing:
|
| 43 |
raise FileNotFoundError(f"Missing Taskmaster files: {missing}")
|
| 44 |
|
| 45 |
-
#
|
| 46 |
ontology_path = Path(base_dir, required_files["ontology"])
|
| 47 |
with open(ontology_path, 'r', encoding='utf-8') as f:
|
| 48 |
ontology = json.load(f)
|
|
@@ -51,7 +70,6 @@ class TaskmasterProcessor:
|
|
| 51 |
|
| 52 |
dialogues: List[TaskmasterDialogue] = []
|
| 53 |
|
| 54 |
-
# We'll read the 2 main files
|
| 55 |
file_keys = ["self-dialogs", "woz-dialogs"]
|
| 56 |
for file_key in file_keys:
|
| 57 |
file_path = Path(base_dir, required_files[file_key])
|
|
@@ -61,26 +79,23 @@ class TaskmasterProcessor:
|
|
| 61 |
for d in raw_data:
|
| 62 |
conversation_id = d.get("conversation_id", "")
|
| 63 |
instruction_id = d.get("instruction_id", None)
|
| 64 |
-
scenario_text = d.get("scenario", "")
|
| 65 |
-
|
| 66 |
-
#
|
| 67 |
utterances = d.get("utterances", [])
|
| 68 |
turns = self._process_utterances(utterances)
|
| 69 |
|
| 70 |
-
#
|
| 71 |
-
|
| 72 |
-
domain = self._extract_domain(
|
| 73 |
-
scenario_text,
|
| 74 |
-
turns # pass the entire turn list so we can pick up domain keywords
|
| 75 |
-
)
|
| 76 |
|
| 77 |
-
#
|
| 78 |
new_dlg = TaskmasterDialogue(
|
| 79 |
conversation_id=conversation_id,
|
| 80 |
instruction_id=instruction_id,
|
| 81 |
scenario=scenario_text,
|
| 82 |
domain=domain,
|
| 83 |
-
turns=turns
|
|
|
|
| 84 |
)
|
| 85 |
dialogues.append(new_dlg)
|
| 86 |
|
|
@@ -93,85 +108,126 @@ class TaskmasterProcessor:
|
|
| 93 |
|
| 94 |
def _extract_domain(self, scenario: str, turns: List[Dict[str, str]]) -> str:
|
| 95 |
"""
|
| 96 |
-
Combine scenario text + all turn texts to detect
|
| 97 |
"""
|
| 98 |
-
# 1) Combine scenario + conversation text
|
| 99 |
combined_text = scenario.lower()
|
| 100 |
for turn in turns:
|
| 101 |
-
|
| 102 |
-
combined_text += " " +
|
| 103 |
|
| 104 |
-
#
|
| 105 |
domain_patterns = {
|
| 106 |
-
'restaurant': r'\b(restaurant|dining|food|reservation|table|menu|cuisine|eat)\b',
|
| 107 |
-
'movie': r'\b(movie|cinema|film|ticket|showtime|theater)\b',
|
| 108 |
-
'ride_share': r'\b(ride|taxi|uber|lyft|car\s?service|pickup|dropoff)\b',
|
| 109 |
'coffee': r'\b(coffee|café|cafe|starbucks|espresso|latte|mocha|americano)\b',
|
| 110 |
-
'pizza': r'\b(pizza|delivery|order\s?food|pepperoni|topping|pizzeria)\b',
|
| 111 |
'auto': r'\b(car|vehicle|repair|maintenance|mechanic|oil\s?change)\b'
|
| 112 |
}
|
| 113 |
|
| 114 |
-
# 3) Return first matched domain or 'other'
|
| 115 |
for dom, pattern in domain_patterns.items():
|
| 116 |
if re.search(pattern, combined_text):
|
| 117 |
-
|
|
|
|
|
|
|
| 118 |
return dom
|
| 119 |
|
| 120 |
-
|
|
|
|
| 121 |
return 'other'
|
| 122 |
|
| 123 |
def _process_utterances(self, utterances: List[Dict[str, Any]]) -> List[Dict[str, str]]:
|
| 124 |
-
"""
|
| 125 |
-
|
|
|
|
|
|
|
|
|
|
| 126 |
for utt in utterances:
|
| 127 |
speaker = 'assistant' if utt.get('speaker') == 'ASSISTANT' else 'user'
|
| 128 |
-
|
| 129 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
'speaker': speaker,
|
| 131 |
'text': text
|
| 132 |
})
|
| 133 |
-
return
|
| 134 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
def filter_and_convert(self, dialogues: List[TaskmasterDialogue]) -> List[Dict]:
|
| 136 |
"""
|
| 137 |
Filter out dialogues that don't meet min turns / min user words,
|
| 138 |
-
then convert them to final pipeline
|
| 139 |
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
...
|
| 146 |
-
]
|
| 147 |
-
}
|
| 148 |
"""
|
| 149 |
results = []
|
| 150 |
for dlg in dialogues:
|
| 151 |
if not dlg.validate():
|
| 152 |
continue
|
| 153 |
|
|
|
|
| 154 |
if len(dlg.turns) < self.config.min_turns:
|
| 155 |
continue
|
| 156 |
|
| 157 |
# Check user-turn min words
|
|
|
|
| 158 |
keep = True
|
| 159 |
for turn in dlg.turns:
|
| 160 |
if turn['speaker'] == 'user':
|
| 161 |
-
|
| 162 |
-
if
|
| 163 |
keep = False
|
| 164 |
break
|
|
|
|
| 165 |
if not keep:
|
| 166 |
continue
|
| 167 |
|
| 168 |
pipeline_dlg = {
|
| 169 |
'dialogue_id': dlg.conversation_id,
|
| 170 |
'domain': dlg.domain,
|
| 171 |
-
'turns': dlg.turns #
|
| 172 |
}
|
| 173 |
results.append(pipeline_dlg)
|
| 174 |
|
| 175 |
if self.config.debug:
|
| 176 |
-
print(f"[TaskmasterProcessor] Filtered down to {len(results)} dialogues.")
|
| 177 |
return results
|
|
|
|
| 1 |
+
import os
|
| 2 |
import re
|
| 3 |
+
import json
|
| 4 |
from pathlib import Path
|
| 5 |
+
from typing import List, Dict, Optional, Any
|
| 6 |
from dataclasses import dataclass, field
|
| 7 |
|
|
|
|
|
|
|
| 8 |
@dataclass
|
| 9 |
class TaskmasterDialogue:
|
|
|
|
| 10 |
conversation_id: str
|
| 11 |
instruction_id: Optional[str]
|
| 12 |
scenario: Optional[str]
|
| 13 |
+
domain: Optional[str]
|
| 14 |
+
turns: List[Dict[str, Any]]
|
| 15 |
+
original_metadata: Dict[str, Any] = field(default_factory=dict)
|
| 16 |
+
|
| 17 |
+
def __str__(self):
|
| 18 |
+
return f"TaskmasterDialogue(conversation_id={self.conversation_id}, turns={len(self.turns)} turns)"
|
| 19 |
|
| 20 |
def validate(self) -> bool:
|
|
|
|
| 21 |
return bool(self.conversation_id and isinstance(self.turns, list))
|
| 22 |
|
| 23 |
+
class PipelineConfig:
|
| 24 |
+
"""
|
| 25 |
+
Example config structure. Adjust to your real config usage.
|
| 26 |
+
"""
|
| 27 |
+
def __init__(
|
| 28 |
+
self,
|
| 29 |
+
debug: bool = True,
|
| 30 |
+
min_turns: int = 2,
|
| 31 |
+
min_user_words: int = 3
|
| 32 |
+
):
|
| 33 |
+
self.debug = debug
|
| 34 |
+
self.min_turns = min_turns
|
| 35 |
+
self.min_user_words = min_user_words
|
| 36 |
+
|
| 37 |
class TaskmasterProcessor:
|
| 38 |
"""
|
| 39 |
+
Loads Taskmaster-1 dialogues, extracts domain from scenario,
|
| 40 |
+
cleans + filters them, and outputs a pipeline-friendly format.
|
| 41 |
"""
|
| 42 |
def __init__(self, config: PipelineConfig):
|
| 43 |
self.config = config
|
| 44 |
|
| 45 |
+
def load_taskmaster_dataset(
|
| 46 |
+
self,
|
| 47 |
+
base_dir: str,
|
| 48 |
+
max_examples: Optional[int] = None
|
| 49 |
+
) -> List[TaskmasterDialogue]:
|
| 50 |
"""
|
| 51 |
Load and parse Taskmaster JSON for self-dialogs & woz-dialogs (Taskmaster-1).
|
| 52 |
Combines scenario text + conversation utterances to detect domain more robustly.
|
|
|
|
| 54 |
required_files = {
|
| 55 |
"self-dialogs": "self-dialogs.json",
|
| 56 |
"woz-dialogs": "woz-dialogs.json",
|
| 57 |
+
"ontology": "ontology.json", # we might not actively use it, but let's expect it
|
| 58 |
}
|
| 59 |
+
# 1) Check for missing
|
| 60 |
missing = [k for k, v in required_files.items() if not Path(base_dir, v).exists()]
|
| 61 |
if missing:
|
| 62 |
raise FileNotFoundError(f"Missing Taskmaster files: {missing}")
|
| 63 |
|
| 64 |
+
# 2) Optionally load ontology
|
| 65 |
ontology_path = Path(base_dir, required_files["ontology"])
|
| 66 |
with open(ontology_path, 'r', encoding='utf-8') as f:
|
| 67 |
ontology = json.load(f)
|
|
|
|
| 70 |
|
| 71 |
dialogues: List[TaskmasterDialogue] = []
|
| 72 |
|
|
|
|
| 73 |
file_keys = ["self-dialogs", "woz-dialogs"]
|
| 74 |
for file_key in file_keys:
|
| 75 |
file_path = Path(base_dir, required_files[file_key])
|
|
|
|
| 79 |
for d in raw_data:
|
| 80 |
conversation_id = d.get("conversation_id", "")
|
| 81 |
instruction_id = d.get("instruction_id", None)
|
| 82 |
+
scenario_text = d.get("scenario", "")
|
| 83 |
+
|
| 84 |
+
# 3) Convert raw utterances
|
| 85 |
utterances = d.get("utterances", [])
|
| 86 |
turns = self._process_utterances(utterances)
|
| 87 |
|
| 88 |
+
# 4) Domain detection
|
| 89 |
+
domain = self._extract_domain(scenario_text, turns)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
|
| 91 |
+
# 5) Build the structured object
|
| 92 |
new_dlg = TaskmasterDialogue(
|
| 93 |
conversation_id=conversation_id,
|
| 94 |
instruction_id=instruction_id,
|
| 95 |
scenario=scenario_text,
|
| 96 |
domain=domain,
|
| 97 |
+
turns=turns,
|
| 98 |
+
original_metadata={}
|
| 99 |
)
|
| 100 |
dialogues.append(new_dlg)
|
| 101 |
|
|
|
|
| 108 |
|
| 109 |
def _extract_domain(self, scenario: str, turns: List[Dict[str, str]]) -> str:
|
| 110 |
"""
|
| 111 |
+
Combine scenario text + all turn texts to detect domain more robustly.
|
| 112 |
"""
|
|
|
|
| 113 |
combined_text = scenario.lower()
|
| 114 |
for turn in turns:
|
| 115 |
+
txt = turn.get('text', '').lower()
|
| 116 |
+
combined_text += " " + txt
|
| 117 |
|
| 118 |
+
# Expanded domain patterns
|
| 119 |
domain_patterns = {
|
| 120 |
+
'restaurant': r'\b(restaurant|dining|food|reservation|table|menu|cuisine|eat|hungry)\b',
|
| 121 |
+
'movie': r'\b(movie|cinema|film|ticket|showtime|theater|flick|screening)\b',
|
| 122 |
+
'ride_share': r'\b(ride|taxi|uber|lyft|car\s?service|pickup|dropoff|driver)\b',
|
| 123 |
'coffee': r'\b(coffee|café|cafe|starbucks|espresso|latte|mocha|americano)\b',
|
| 124 |
+
'pizza': r'\b(pizza|delivery|order\s?food|pepperoni|topping|pizzeria|slice)\b',
|
| 125 |
'auto': r'\b(car|vehicle|repair|maintenance|mechanic|oil\s?change)\b'
|
| 126 |
}
|
| 127 |
|
|
|
|
| 128 |
for dom, pattern in domain_patterns.items():
|
| 129 |
if re.search(pattern, combined_text):
|
| 130 |
+
# Optional: print if debug
|
| 131 |
+
if self.config.debug:
|
| 132 |
+
print(f"Matched domain: {dom} in scenario/turns")
|
| 133 |
return dom
|
| 134 |
|
| 135 |
+
if self.config.debug:
|
| 136 |
+
print("No domain match, returning 'other'")
|
| 137 |
return 'other'
|
| 138 |
|
| 139 |
def _process_utterances(self, utterances: List[Dict[str, Any]]) -> List[Dict[str, str]]:
|
| 140 |
+
"""
|
| 141 |
+
Convert raw utterances to a cleaned list of (speaker, text).
|
| 142 |
+
Skip or remove lines that are numeric, too short, or empty.
|
| 143 |
+
"""
|
| 144 |
+
cleaned_turns = []
|
| 145 |
for utt in utterances:
|
| 146 |
speaker = 'assistant' if utt.get('speaker') == 'ASSISTANT' else 'user'
|
| 147 |
+
raw_text = utt.get('text', '').strip()
|
| 148 |
+
|
| 149 |
+
# 1) Optional text cleaning
|
| 150 |
+
text = self._clean_text(raw_text)
|
| 151 |
+
|
| 152 |
+
# 2) Skip blank or numeric lines
|
| 153 |
+
if not text:
|
| 154 |
+
continue
|
| 155 |
+
if self._is_numeric_line(text):
|
| 156 |
+
continue
|
| 157 |
+
|
| 158 |
+
# 3) If it's extremely short, skip.
|
| 159 |
+
# (For example, "ok" or "yes" might be 1-2 words.)
|
| 160 |
+
if len(text.split()) < 2:
|
| 161 |
+
# Optionally keep "ok" or "yes" if you'd like, but let's skip them to keep quality up
|
| 162 |
+
continue
|
| 163 |
+
|
| 164 |
+
# 4) Append
|
| 165 |
+
cleaned_turns.append({
|
| 166 |
'speaker': speaker,
|
| 167 |
'text': text
|
| 168 |
})
|
| 169 |
+
return cleaned_turns
|
| 170 |
|
| 171 |
+
def _clean_text(self, text: str) -> str:
|
| 172 |
+
"""
|
| 173 |
+
Basic text normalization: remove repeated punctuation, handle weird spacing, etc.
|
| 174 |
+
Adjust to your needs.
|
| 175 |
+
"""
|
| 176 |
+
# Example: collapse multiple spaces
|
| 177 |
+
text = re.sub(r'\s+', ' ', text)
|
| 178 |
+
# Example: remove trailing punctuation or repeated punctuation
|
| 179 |
+
# e.g. "Sure!!!" => "Sure!"
|
| 180 |
+
text = re.sub(r'([!?.,])\1+', r'\1', text)
|
| 181 |
+
return text.strip()
|
| 182 |
+
|
| 183 |
+
def _is_numeric_line(self, text: str) -> bool:
|
| 184 |
+
"""
|
| 185 |
+
Return True if line is purely digits/punctuation/spaces,
|
| 186 |
+
e.g. "4 3 13", "12345", "3.14". Adjust as needed.
|
| 187 |
+
"""
|
| 188 |
+
pattern = r'^[\s]*[\d]+([\s\d.,]+)*[\s]*$'
|
| 189 |
+
return bool(re.match(pattern, text))
|
| 190 |
+
|
| 191 |
def filter_and_convert(self, dialogues: List[TaskmasterDialogue]) -> List[Dict]:
|
| 192 |
"""
|
| 193 |
Filter out dialogues that don't meet min turns / min user words,
|
| 194 |
+
then convert them to final pipeline format:
|
| 195 |
|
| 196 |
+
{
|
| 197 |
+
"dialogue_id": "...",
|
| 198 |
+
"domain": "...",
|
| 199 |
+
"turns": [ {"speaker": "user", "text": "..."}, ... ]
|
| 200 |
+
}
|
|
|
|
|
|
|
|
|
|
| 201 |
"""
|
| 202 |
results = []
|
| 203 |
for dlg in dialogues:
|
| 204 |
if not dlg.validate():
|
| 205 |
continue
|
| 206 |
|
| 207 |
+
# If after cleaning, we have too few turns, skip
|
| 208 |
if len(dlg.turns) < self.config.min_turns:
|
| 209 |
continue
|
| 210 |
|
| 211 |
# Check user-turn min words
|
| 212 |
+
# E.g. user must have >= 3 words
|
| 213 |
keep = True
|
| 214 |
for turn in dlg.turns:
|
| 215 |
if turn['speaker'] == 'user':
|
| 216 |
+
words_count = len(turn['text'].split())
|
| 217 |
+
if words_count < self.config.min_user_words:
|
| 218 |
keep = False
|
| 219 |
break
|
| 220 |
+
|
| 221 |
if not keep:
|
| 222 |
continue
|
| 223 |
|
| 224 |
pipeline_dlg = {
|
| 225 |
'dialogue_id': dlg.conversation_id,
|
| 226 |
'domain': dlg.domain,
|
| 227 |
+
'turns': dlg.turns # already cleaned
|
| 228 |
}
|
| 229 |
results.append(pipeline_dlg)
|
| 230 |
|
| 231 |
if self.config.debug:
|
| 232 |
+
print(f"[TaskmasterProcessor] Filtered down to {len(results)} dialogues after cleaning.")
|
| 233 |
return results
|
validate_model.py
CHANGED
|
@@ -103,10 +103,6 @@ def validate_chatbot():
|
|
| 103 |
chatbot.data_pipeline.response_pool = json.load(f)
|
| 104 |
logger.info(f"Response pool loaded from {RESPONSE_POOL_PATH}.")
|
| 105 |
|
| 106 |
-
print("Sample from response pool (first 10):")
|
| 107 |
-
for i, response in enumerate(chatbot.data_pipeline.response_pool[:10]):
|
| 108 |
-
print(f"{i}: {response}")
|
| 109 |
-
|
| 110 |
print("\nTotal responses in pool:", len(chatbot.data_pipeline.response_pool))
|
| 111 |
|
| 112 |
# Validate dimension consistency
|
|
|
|
| 103 |
chatbot.data_pipeline.response_pool = json.load(f)
|
| 104 |
logger.info(f"Response pool loaded from {RESPONSE_POOL_PATH}.")
|
| 105 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
print("\nTotal responses in pool:", len(chatbot.data_pipeline.response_pool))
|
| 107 |
|
| 108 |
# Validate dimension consistency
|