Spaces:
Sleeping
Sleeping
File size: 3,501 Bytes
51b5ec9 29ba63d 51b5ec9 ddcb55f 29ba63d ddcb55f 29ba63d 51b5ec9 ddcb55f 29ba63d ddcb55f 51b5ec9 ddcb55f 51b5ec9 ddcb55f 51b5ec9 ddcb55f 51b5ec9 ddcb55f | 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 | import pandas as pd
from pathlib import Path
import csv
def load_and_prepare_data(csv_dir, min_samples=4):
csv_dir_path = Path(csv_dir)
dataframes = []
# Recursively find all csv files
for file_path in csv_dir_path.rglob("*.csv"):
try:
try:
df = pd.read_csv(file_path, on_bad_lines='skip', engine='python')
except pd.errors.EmptyDataError:
continue
required_cols = ["Intent Name", "Training Phrase", "Approved Response"]
if not all(col in df.columns for col in required_cols):
continue
df = df[required_cols].dropna()
# Clean up the texts
df['Intent Name'] = df['Intent Name'].astype(str).str.strip()
df['Training Phrase'] = df['Training Phrase'].astype(str).str.strip()
df['Approved Response'] = df['Approved Response'].astype(str).str.strip()
# Strip extra literal quotes if any are remaining
df['Approved Response'] = df['Approved Response'].str.replace(r'^"+|"+$', '', regex=True)
if not df.empty:
dataframes.append(df)
except Exception as e:
print(f"Failed to read {file_path}: {e}")
if not dataframes:
raise ValueError(f"No valid CSV files found in {csv_dir}")
combined_df = pd.concat(dataframes, ignore_index=True)
combined_df.dropna(subset=['Intent Name', 'Training Phrase', 'Approved Response'], inplace=True)
# Bug 10 Fix: Consolidate micro-intents into broader hierarchical classes and add entity extraction.
def extract_hierarchical(intent_str):
prefixes = ['Explain', 'Define', 'Implement', 'Compare', 'Solve', 'What_is', 'How_to']
suffixes = ['Definition', 'Concept', 'Operations', 'Complexity', 'Analysis', 'Example', 'Overview', 'Properties']
for p in prefixes:
if intent_str.startswith(p + '_'):
return p, intent_str[len(p)+1:]
for s in suffixes:
if intent_str.endswith('_' + s):
return s, intent_str[:-len(s)-1]
parts = intent_str.split('_')
if len(parts) > 1:
return parts[0], '_'.join(parts[1:])
return intent_str, 'General'
extracted = combined_df['Intent Name'].apply(extract_hierarchical)
combined_df['Broad Intent'] = [x[0] for x in extracted]
combined_df['Entity'] = [x[1] for x in extracted]
# Filter intents by minimum sample count using Broad Intent
counts = combined_df['Broad Intent'].value_counts()
valid_intents = counts[counts >= min_samples].index
filtered_df = combined_df[combined_df['Broad Intent'].isin(valid_intents)].copy()
return filtered_df
def build_response_map(df):
responses = {}
has_broad = 'Broad Intent' in df.columns and 'Entity' in df.columns
for _, row in df.iterrows():
if has_broad:
b_intent = row['Broad Intent']
entity = row['Entity']
if b_intent not in responses:
responses[b_intent] = {}
if entity not in responses[b_intent]:
responses[b_intent][entity] = row['Approved Response']
else:
intent = row['Intent Name']
if intent not in responses:
responses[intent] = row['Approved Response']
return responses
|