Update inference.py
Browse files123456789101112134 unmodified lines18192021222311 unmodified lines3536373839404142434445464748495022 unmodified lines73747576777879808182838485868788899091921 unmodified line9495969798991001011021031041051061071081091101111121131144 unmodified lines1191201211221231241251261271281291301311321 unmodified line1341351361371381391401411421431441451461471486 unmodified lines1551561571581591601611621631641655 unmodified lines171172173# requirements!pip install torch==2.8.0 torchvision==0.17.2!pip install transformers==4.48.3 tokenizers sentencepiece accelerateimport torchfrom typing import List, Optionalfrom transformers import AutoTokenizer, AutoModelERROR_NAMES_RU = {"false_causality": "Ложная причинно-следственная связь","unsupported_claim": "Неподкрепленное утверждение",4 unmodified lines}class RQAJudge:def __init__(self, model_name="skatzR/RQA-R2", device=None, max_length: int = 512):self.device = device or ("cuda" if torch.cuda.is_available() else "cpu")11 unmodified linesself.model.eval()cfg = self.model.configself.error_types = list(cfg.error_types)self.temp_issue = float(cfg.temperature_has_issue)self.temp_hidden = float(cfg.temperature_is_hidden)self.temp_errors = list(cfg.temperature_errors)self.threshold_issue = float(cfg.threshold_has_issue)self.threshold_hidden = float(cfg.threshold_is_hidden)self.threshold_error = float(cfg.threshold_error)self.threshold_errors = list(cfg.threshold_errors)@torch.no_grad()def infer(22 unmodified linesoutputs = self.model(**inputs)issue_logit = outputs["has_issue_logits"] / self.temp_issuehidden_logit = outputs["is_hidden_logits"] / self.temp_hiddenerror_logits = outputs["errors_logits"][0].clone()for i in range(len(self.error_types)):error_logits[i] = error_logits[i] / self.temp_errors[i]issue_prob = torch.sigmoid(issue_logit).item()has_issue = issue_prob >= issue_thresholdresult = {"text": text,"class": None,"status": "ok","review_required": False,"has_issue": has_issue,"issue_probability": issue_prob,1 unmodified line"hidden_probability": None,"errors": [],"num_errors": 0,"threshold_issue": issue_threshold,"threshold_hidden": hidden_threshold,"threshold_error": error_threshold,"threshold_errors": error_thresholds,"schema_version": getattr(self.model.config, "schema_version", "unknown"),}if abs(issue_prob - issue_threshold) <= issue_uncertain_margin:result["status"] = "uncertain"result["review_required"] = Trueif not has_issue:result["class"] = "logical"return resulthidden_prob = torch.sigmoid(hidden_logit).item()is_hidden = hidden_prob >= hidden_threshold4 unmodified linesresult["status"] = "uncertain"result["review_required"] = Trueif is_hidden:result["class"] = "hidden"return resulterror_probs = torch.sigmoid(error_logits).tolist()detected = []for i, err_name in enumerate(self.error_types):prob = float(error_probs[i])threshold_i = float(error_thresholds[i] if i < len(error_thresholds) else error_threshold)if abs(prob - threshold_i) <= error_uncertain_margin:1 unmodified lineresult["review_required"] = Trueif prob >= threshold_i:detected.append((err_name, prob))detected.sort(key=lambda x: x[1], reverse=True)result["class"] = "explicit"result["errors"] = detectedresult["num_errors"] = len(detected)return resultdef pretty_print(self, r):print("\n" + "=" * 72)print("📄 Текст:")6 unmodified linesprint(f"🧠 Класс: {r['class']}")if r["status"] == "uncertain":print("⚠️ Статус: uncertain")if r["hidden_probability"] is not None:print(f"🟡 Hidden: {'ДА' if r['hidden_problem'] else 'НЕТ'} "f"({r['hidden_probability'] * 100:.2f}%)")5 unmodified linesprint("\n✅ Явных логических ошибок не обнаружено")print("=" * 72)123456789101112131415161718192021222324252627282930313233344 unmodified lines3940414243444546474811 unmodified lines60616263646566676869707172737475767778798081828322 unmodified lines1061071081091101111121131141151161171181191201 unmodified line1221231241251261271281291301311321331341351361371381391401411421431441454 unmodified lines1501511521531541551561571581591601611621631641651661671681691701711721 unmodified line1741751761771781791801811821831841851861871881891901911926 unmodified lines1992002012022032042052062072082095 unmodified lines215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416# requirements# Для inference в Colab достаточно этого стека.!pip install transformers==4.48.3 tokenizers sentencepiece accelerate# ============================================================# RQA UX Inference — R2 Interactive Version# Google Colab + CLI friendly# ============================================================import osimport jsonimport csvimport torchfrom typing import List, Optionalfrom transformers import AutoTokenizer, AutoModel# ============================================================# Константы# ============================================================ERROR_TYPES = ["false_causality","unsupported_claim","overgeneralization","missing_premise","contradiction","circular_reasoning",]ERROR_NAMES_RU = {"false_causality": "Ложная причинно-следственная связь","unsupported_claim": "Неподкрепленное утверждение",4 unmodified lines}# ============================================================# RQA Judge# ============================================================class RQAJudge:def __init__(self, model_name="skatzR/RQA-R2", device=None, max_length: int = 512):self.device = device or ("cuda" if torch.cuda.is_available() else "cpu")11 unmodified linesself.model.eval()cfg = self.model.configself.error_types = list(getattr(cfg, "error_types", ERROR_TYPES))self.temp_issue = float(getattr(cfg, "temperature_has_issue", 1.0))self.temp_hidden = float(getattr(cfg, "temperature_is_hidden", 1.0))self.temp_errors = list(getattr(cfg, "temperature_errors", [1.0] * len(self.error_types)))self.threshold_issue = float(getattr(cfg, "threshold_has_issue", 0.5))self.threshold_hidden = float(getattr(cfg, "threshold_is_hidden", 0.5))self.threshold_error = float(getattr(cfg, "threshold_error", 0.5))self.threshold_errors = list(getattr(cfg, "threshold_errors", [self.threshold_error] * len(self.error_types)))# ----------------------# Core inference# ----------------------@torch.no_grad()def infer(22 unmodified linesoutputs = self.model(**inputs)# ----- has_issue -----issue_logit = outputs["has_issue_logits"] / self.temp_issueissue_prob = torch.sigmoid(issue_logit).item()has_issue = issue_prob >= issue_thresholdresult = {"text": text,"class": None, # logical / hidden / explicit"status": "ok", # ok / uncertain"review_required": False,"has_issue": has_issue,"issue_probability": issue_prob,1 unmodified line"hidden_probability": None,"errors": [],"num_errors": 0,"schema_version": getattr(self.model.config, "schema_version", "unknown"),"threshold_issue": issue_threshold,"threshold_hidden": hidden_threshold,"threshold_error": error_threshold,"threshold_errors": error_thresholds,}if abs(issue_prob - issue_threshold) <= issue_uncertain_margin:result["status"] = "uncertain"result["review_required"] = True# ----- Gate 1: logical -----if not has_issue:result["class"] = "logical"return result# ----- hidden -----hidden_logit = outputs["is_hidden_logits"] / self.temp_hiddenhidden_prob = torch.sigmoid(hidden_logit).item()is_hidden = hidden_prob >= hidden_threshold4 unmodified linesresult["status"] = "uncertain"result["review_required"] = True# ----- Gate 2: hidden -----if is_hidden:result["class"] = "hidden"return result# ----- explicit errors -----raw_error_logits = outputs["errors_logits"][0].clone()error_probs = {}for i, logit in enumerate(raw_error_logits):calibrated = logit / self.temp_errors[i]prob = torch.sigmoid(calibrated).item()error_probs[self.error_types[i]] = probexplicit_errors = []for i, err_name in enumerate(self.error_types):prob = float(error_probs[err_name])threshold_i = float(error_thresholds[i] if i < len(error_thresholds) else error_threshold)if abs(prob - threshold_i) <= error_uncertain_margin:1 unmodified lineresult["review_required"] = Trueif prob >= threshold_i:explicit_errors.append((err_name, prob))explicit_errors.sort(key=lambda x: x[1], reverse=True)result["class"] = "explicit"result["errors"] = explicit_errorsresult["num_errors"] = len(explicit_errors)return result# ============================================================# UX output# ============================================================def pretty_print(self, r):print("\n" + "=" * 72)print("📄 Текст:")6 unmodified linesprint(f"🧠 Класс: {r['class']}")if r["status"] == "uncertain":print("⚠️ Пограничный случай: review recommended")if r["hidden_probability"] is not None:print(f"🟡 Hidden-проблема: {'ДА' if r['hidden_problem'] else 'НЕТ'} "f"({r['hidden_probability'] * 100:.2f}%)")5 unmodified linesprint("\n✅ Явных логических ошибок не обнаружено")print("=" * 72)# ============================================================# Loaders# ============================================================def load_texts_from_file(path: str) -> List[str]:ext = os.path.splitext(path)[1].lower()if ext == ".txt":with open(path, encoding="utf-8") as f:return [line.strip() for line in f if line.strip()]if ext == ".csv":with open(path, encoding="utf-8") as f:reader = csv.DictReader(f)return [row["text"] for row in reader if row.get("text")]if ext == ".json":with open(path, encoding="utf-8") as f:data = json.load(f)if isinstance(data, list):if all(isinstance(item, str) for item in data):return datatexts = []for item in data:if isinstance(item, dict) and "text" in item:texts.append(str(item["text"]))return textsraise ValueError("Неподдерживаемый формат файла")# ============================================================# Interactive CLI Interface# ============================================================class InteractiveCLI:def __init__(self, model_name="skatzR/RQA-R2"):self.judge = RQAJudge(model_name=model_name)def clear_screen(self):print("\n" * 2)def show_mode_menu(self):self.clear_screen()print("=" * 60)print("🤖 RQA-R2 — АНАЛИЗ ЛОГИЧЕСКИХ ОШИБОК")print("=" * 60)print("\nВыберите режим работы:")print("1. 📝 Одиночный ввод (одна фраза для анализа)")print("2. 📄 Множественный ввод (несколько фраз, каждая с новой строки)")print("3. 📂 Загрузка из файла (.txt, .csv, .json)")print("\nНажмите Enter без ввода для выхода.")print("-" * 60)def process_single_mode(self):self.clear_screen()print("[📝 РЕЖИМ: ОДИНОЧНЫЙ ВВОД]")print("Введите текст для анализа:")print("(Нажмите Enter без ввода для возврата в меню)")print("-" * 40)text = input("> ").strip()if not text:return Trueresult = self.judge.infer(text)self.judge.pretty_print(result)print("\n" + "-" * 40)input("Нажмите Enter для продолжения...")return Falsedef process_multiline_mode(self):self.clear_screen()print("[📄 РЕЖИМ: МНОЖЕСТВЕННЫЙ ВВОД]")print("Введите тексты для анализа (каждый с новой строки).")print("Оставьте строку пустой для завершения ввода.")print("(Нажмите Enter без ввода для возврата в меню)")print("-" * 40)texts = []print("Ввод текстов:")while True:line = input("> ").strip()if not line:if not texts:return Truebreaktexts.append(line)self.clear_screen()print(f"[📄 РЕЖИМ: МНОЖЕСТВЕННЫЙ ВВОД] — найдено {len(texts)} текстов")print("-" * 40)for i, text in enumerate(texts, 1):print(f"\n🔍 Текст #{i}:")result = self.judge.infer(text)self.judge.pretty_print(result)print("\n" + "=" * 60)input("Нажмите Enter для продолжения...")return Falsedef process_file_mode(self):self.clear_screen()print("[📂 РЕЖИМ: ЗАГРУЗКА ИЗ ФАЙЛА]")print("Поддерживаемые форматы: .txt, .csv, .json")print("Укажите путь к файлу:")print("(Нажмите Enter без ввода для возврата в меню)")print("-" * 40)file_path = input("Путь к файлу> ").strip()if not file_path:return Truetry:if not os.path.exists(file_path):print(f"\n❌ Ошибка: Файл '{file_path}' не найден!")input("\nНажмите Enter для продолжения...")return Falsetexts = load_texts_from_file(file_path)if not texts:print(f"\n⚠️ Файл '{file_path}' пуст или не содержит текстов!")input("\nНажмите Enter для продолжения...")return Falseself.clear_screen()print(f"[📂 РЕЖИМ: ЗАГРУЗКА ИЗ ФАЙЛА] — загружено {len(texts)} текстов")print(f"Файл: {file_path}")print("-" * 40)for i, text in enumerate(texts, 1):print(f"\n🔍 Текст #{i}:")result = self.judge.infer(text)self.judge.pretty_print(result)print("\n" + "=" * 60)input("Нажмите Enter для продолжения...")except Exception as e:print(f"\n❌ Ошибка при обработке файла: {str(e)}")input("\nНажмите Enter для продолжения...")return Falsedef run_interactive(self):current_mode = Nonewhile True:if not current_mode:self.show_mode_menu()choice = input("Ваш выбор (1-3)> ").strip()if not choice:print("\n👋 Выход из программы...")breakif choice == "1":current_mode = "single"elif choice == "2":current_mode = "multiline"elif choice == "3":current_mode = "file"else:print("\n❌ Неверный выбор! Попробуйте снова.")input("Нажмите Enter для продолжения...")continueshould_return_to_menu = Falseif current_mode == "single":should_return_to_menu = self.process_single_mode()elif current_mode == "multiline":should_return_to_menu = self.process_multiline_mode()elif current_mode == "file":should_return_to_menu = self.process_file_mode()if should_return_to_menu:current_mode = None# ============================================================# Точка входа# ============================================================def main():cli = InteractiveCLI()cli.run_interactive()# ============================================================# Запуск# ============================================================if __name__ == "__main__":main()
inference.py+270-27