xstard's picture
Implement encoder-only bilingual decision API and demo
4df9b63 verified
Raw History Blame Contribute Delete
13.6 kB
import csv
import hashlib
import json
import random
import re
from pathlib import Path
from typing import Literal
from pydantic import Field, model_validator
from .schemas import StrictModel, Text, QuestionType, NoulQuestion, ChoiceQuestion, ScoreQuestion
DEPARTMENTS = {
"uk": {"billing": "Рахунки, оплати та повернення грошей", "technical": "Усунення збоїв, багів і несправностей",
"sales": "Нові покупки, тарифи та контракти", "other": "Інші звернення: обліковий запис, доставка, інформація"},
"en": {"billing": "Billing, payments and refunds", "technical": "Fixing bugs, failures and technical faults",
"sales": "New purchases, pricing and contracts", "other": "Other requests: account, delivery and information"},
}
LEVELS = {
"uk": ["Нейтральний, спокійний тон", "Легке невдоволення", "Виразне роздратування",
"Сильний гнів", "Погрози піти або агресія"],
"en": ["Neutral, calm tone", "Mild dissatisfaction", "Clear frustration", "Strong anger", "Threats to leave or aggression"],
}
THREE_LEVELS = {
"uk": ["Спокійний, нейтральний тон", "Помірне невдоволення або роздратування", "Сильний гнів, агресія або погрози піти"],
"en": ["Calm, neutral tone", "Moderate dissatisfaction or frustration", "Strong anger, aggression or threats to leave"],
}
class Ticket(StrictModel):
id: Text
group_id: Text
language: Literal["uk", "en"]
text: Text
department: Literal["billing", "technical", "sales", "other"]
wants_refund: bool
frustration: int = Field(ge=0, le=4)
source: Text
license: Text
reviewed: bool = False
reviewer: str = ""
@model_validator(mode="after")
def review_provenance(self):
if self.reviewed and not self.reviewer.strip():
raise ValueError("Для reviewed=true потрібен reviewer.")
return self
class DecisionExample(StrictModel):
id: Text
group_id: Text
language: Literal["uk", "en"]
state: Text
question: QuestionType
gold: int = Field(ge=0)
source: Text
reviewed: bool
reviewer: str = ""
ticket_id: str = ""
demo: bool = True
@model_validator(mode="after")
def valid_gold(self):
count = 2 if self.question.type == "noul" else len(self.question.criteria)
if self.gold >= count:
raise ValueError("Gold index має відповідати наявному варіанту.")
if self.reviewed and not self.reviewer.strip():
raise ValueError("Для reviewed=true потрібен reviewer.")
return self
def to_examples(ticket, augment=False):
lang = ticket.language
department_q = "Яка команда має обробити головне прохання клієнта?" if lang == "uk" else "Which team should handle the customer's main request?"
refund_q = "Клієнт явно просить повернути гроші?" if lang == "uk" else "Does the customer explicitly request a refund?"
frustration_q = "Наскільки клієнт роздратований?" if lang == "uk" else "How frustrated is the customer?"
criteria = DEPARTMENTS[lang].copy()
rows = []
def add(suffix, q, gold, demo=True):
rows.append(DecisionExample(id=f"{ticket.id}:{suffix}", group_id=ticket.group_id, language=lang,
state=ticket.text, question=q, gold=gold, source=ticket.source, reviewed=ticket.reviewed,
reviewer=ticket.reviewer, ticket_id=ticket.id, demo=demo))
add("department", ChoiceQuestion(type="choice", instructions=department_q, criteria=criteria), list(criteria).index(ticket.department))
add("refund", NoulQuestion(type="noul", instructions=refund_q), int(ticket.wants_refund))
severity3 = 0 if ticket.frustration == 0 else (1 if ticket.frustration <= 2 else 2)
add("frustration", ScoreQuestion(type="score", instructions=frustration_q, criteria=THREE_LEVELS[lang]), severity3)
if augment:
rng = random.Random(int(hashlib.sha256(ticket.id.encode()).hexdigest()[:16], 16))
inverse_q = 'У зверненні ВІДСУТНЄ явне прохання повернути гроші?' if lang=='uk' else 'Is an explicit refund request ABSENT from this message?'
add('refund_inverse',NoulQuestion(type='noul',instructions=inverse_q),int(not ticket.wants_refund),demo=False)
for k in (2, 3, 4):
others = [key for key in criteria if key != ticket.department]
selected = [ticket.department, *rng.sample(others, k - 1)]
rng.shuffle(selected)
add(f"department{k}", ChoiceQuestion(type="choice", instructions=department_q,
criteria={key: criteria[key] for key in selected}), selected.index(ticket.department), demo=False)
binary = ["Нейтральний тон", "Будь-яке невдоволення"] if lang == "uk" else ["Neutral tone", "Any dissatisfaction"]
add("frustration2", ScoreQuestion(type="score", instructions=frustration_q, criteria=binary), int(ticket.frustration > 0), demo=False)
add("frustration5", ScoreQuestion(type="score", instructions=frustration_q, criteria=LEVELS[lang]), ticket.frustration, demo=False)
return rows
def normalize(text):
return " ".join(re.findall(r"\w+", text.casefold(), flags=re.UNICODE))
def deduplicate(records, similarity=0.92, source_texts=None):
"""Merge duplicate families, including all of their other-language siblings."""
import numpy as np
from rapidfuzz import process, fuzz
records = sorted(records, key=lambda t: t.id)
parent = {t.group_id: t.group_id for t in records}
def find(group):
while parent[group] != group:
parent[group] = parent[parent[group]]
group = parent[group]
return group
def union(a, b):
a, b = find(a), find(b)
parent[max(a, b)] = min(a, b)
def cluster(items):
if len(items) < 2:
return
keys, values = zip(*items, strict=True)
for start in range(0, len(values), 256):
scores = process.cdist(values[start:start + 256], values, scorer=fuzz.ratio,
score_cutoff=similarity * 100, workers=2, dtype=np.float32)
for local, other in np.argwhere(scores >= similarity * 100):
index = start + int(local)
if int(other) > index:
union(keys[index], keys[int(other)])
# Original source variants stay one family even after divergent generation.
owners = {t.group_id: t.group_id for t in records}
owners.update({t.id.rsplit(":", 1)[0]: t.group_id for t in records})
cluster([(owners[key], normalize(value)) for key, value in (source_texts or {}).items() if key in owners])
texts, keep = {}, []
for ticket in records:
text = normalize(ticket.text)
exact_key = (ticket.language, text)
match = texts.get(exact_key)
if match is not None:
labels = (ticket.department, ticket.wants_refund, ticket.frustration)
other_labels = (match.department, match.wants_refund, match.frustration)
if labels != other_labels:
raise ValueError(f"Суперечлива розмітка дублікатів: {ticket.id}, {match.id}")
union(ticket.group_id, match.group_id)
else:
texts[exact_key] = ticket
keep.append(ticket)
for language in ("uk", "en"):
cluster([(t.group_id, normalize(t.text)) for t in keep if t.language == language])
return [t.model_copy(update={"group_id": find(t.group_id)}) for t in keep]
def split_tickets(records, seed=42, frozen=None):
groups = sorted({t.group_id for t in records})
random.Random(seed).shuffle(groups)
n = len(groups)
a, b, c = int(n * 0.7), int(n * 0.8), int(n * 0.9)
assignment = {group: name for name, items in zip(("train", "validation", "calibration", "test"),
(groups[:a], groups[a:b], groups[b:c], groups[c:]), strict=True) for group in items}
if frozen is not None:
if any(value not in {'train','validation','calibration','test'} for value in frozen.values()):
raise ValueError('Некоректна зафіксована вибірка.')
for group in groups:
if group in frozen:
assignment[group] = frozen[group]
else:
# New families do not move the old evaluation population.
value = int(hashlib.sha256(f'{seed}:{group}'.encode()).hexdigest()[:16],16) / 2**64
assignment[group] = 'train' if value < .7 else ('validation' if value < .8 else ('calibration' if value < .9 else 'test'))
result = {name: [] for name in ("train", "validation", "calibration", "test")}
for ticket in sorted(records, key=lambda t: t.id):
result[assignment[ticket.group_id]].append(ticket)
return result
def read_jsonl(path, model=Ticket):
return [model.model_validate(json.loads(line)) for line in Path(path).read_text(encoding="utf-8-sig").splitlines() if line.strip()]
def write_jsonl(path, rows):
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_suffix(path.suffix + ".tmp")
with temporary.open("w", encoding="utf-8", newline="\n") as stream:
for row in rows:
value = row.model_dump(mode="json") if hasattr(row, "model_dump") else row
stream.write(json.dumps(value, ensure_ascii=False) + "\n")
temporary.replace(path)
def apply_reviews(records, path):
"""Reviewed full Ticket overrides retain source family and immutable provenance."""
path = Path(path)
if not path.exists():
return records
overrides = read_jsonl(path)
by_id = {r.id: r for r in overrides}
if len(by_id) != len(overrides):
raise ValueError("Повторні ID у ручних виправленнях.")
result = []
for original in records:
corrected = by_id.get(original.id, original)
if any(getattr(corrected, key) != getattr(original, key) for key in ('group_id', 'language', 'source', 'license')):
raise ValueError("Ручна корекція не може змінювати походження чи семантичну групу.")
if corrected is not original and (not corrected.reviewed or not corrected.reviewer.strip()):
raise ValueError("Ручні корекції потребують reviewed=true і reviewer.")
result.append(corrected)
return result
def prepare_splits(input_path, output_dir):
output_dir = Path(output_dir)
from .settings import ROOT
seeds_path = ROOT / 'data/generated/seeds.json'
sources = {s['id']: s['text'] for s in json.loads(seeds_path.read_text(encoding='utf-8'))} if seeds_path.exists() else {}
supplied = read_jsonl(input_path)
quarantine = [t for t in supplied if 'target_drift=' in t.source and not t.reviewed]
records = deduplicate([t for t in supplied if t not in quarantine], source_texts=sources)
output_dir.mkdir(parents=True, exist_ok=True)
assignment_path = output_dir/'frozen-splits.json'
frozen = json.loads(assignment_path.read_text(encoding='utf-8')) if assignment_path.exists() else None
splits = split_tickets(records, frozen=frozen)
assignments = dict(frozen or {})
assignments.update({t.group_id:name for name, rows in splits.items() for t in rows})
assignment_path.write_text(json.dumps(assignments,sort_keys=True,indent=2),encoding='utf-8')
stats = {}
for split, tickets in splits.items():
examples = [e for ticket in tickets for e in to_examples(ticket, augment=split == "train")]
write_jsonl(output_dir / f"{split}.jsonl", examples)
stats[split] = {"tickets": len(tickets), "examples": len(examples),
"groups": len({t.group_id for t in tickets}),
"reviewed_tickets": sum(t.reviewed for t in tickets),
"languages": {lang: sum(t.language == lang for t in tickets) for lang in ("uk", "en")},
"departments": {d: sum(t.department == d for t in tickets) for d in DEPARTMENTS["en"]}}
stats['preparation'] = {'quarantined_unreviewed_target_drift':len(quarantine)}
write_jsonl(output_dir/'quarantine.jsonl',quarantine)
(output_dir / "split-manifest.json").write_text(json.dumps(stats, indent=2, ensure_ascii=False), encoding="utf-8")
return stats
def export_review(input_path, output_path):
records = read_jsonl(input_path)
fields = list(Ticket.model_fields)
with Path(output_path).open("w", encoding="utf-8-sig", newline="") as stream:
writer = csv.DictWriter(stream, fieldnames=fields)
writer.writeheader()
writer.writerows(t.model_dump() for t in records)
def import_review(csv_path, output_path):
with Path(csv_path).open(encoding="utf-8-sig", newline="") as stream:
records = [Ticket.model_validate(row) for row in csv.DictReader(stream)]
if any(t.reviewed and not t.reviewer.strip() for t in records):
raise ValueError("Для reviewed потрібен reviewer.")
write_jsonl(output_path, records)
return len(records)