akupriyanovhse

BERT NER

Apr 17th, 2026 (edited)
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.37 KB | None | 0 0
  1. import os
  2. from transformers import pipeline, AutoTokenizer, AutoModelForTokenClassification
  3.  
  4. # ══════════════════════════════════════════════
  5. # НАСТРОЙКИ
  6. # ══════════════════════════════════════════════
  7. MODEL_NAME = "Davlan/bert-base-multilingual-cased-ner-hrl"   # NER: имена, места, организации
  8. MODELS_DIR = "models"
  9.  
  10. # ══════════════════════════════════════════════
  11. # Загрузка модели
  12. # ══════════════════════════════════════════════
  13. local_path = os.path.join(MODELS_DIR, MODEL_NAME.replace("/", "_"))
  14.  
  15. if os.path.exists(local_path):
  16.     print(f"✓ Модель найдена на диске: {local_path}")
  17. else:
  18.     print(f"⏳ Скачиваю «{MODEL_NAME}»...")
  19.     tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
  20.     model = AutoModelForTokenClassification.from_pretrained(MODEL_NAME)
  21.     os.makedirs(local_path, exist_ok=True)
  22.     tokenizer.save_pretrained(local_path)
  23.     model.save_pretrained(local_path)
  24.     print(f"✓ Модель сохранена в: {local_path}\n")
  25.  
  26. ner = pipeline("ner", model=local_path, aggregation_strategy="simple")
  27.  
  28. # ══════════════════════════════════════════════
  29. # Тексты для анализа
  30. # ══════════════════════════════════════════════
  31. texts = [
  32.     "Владимир Путин провёл встречу с Си Цзиньпином в Пекине.",
  33.     "Компания Яндекс открыла новый офис в Санкт-Петербурге.",
  34.     "Журналист Иван Сафронов был задержан сотрудниками ФСБ в Москве.",
  35.     "МГУ и Высшая школа экономики вошли в рейтинг Times Higher Education.",
  36.     "Газпром подписал контракт с турецкой Botas на поставку газа через Анкару.",
  37. ]
  38.  
  39. # ══════════════════════════════════════════════
  40. # Метки NER → понятные названия
  41. # ══════════════════════════════════════════════
  42. LABEL_MAP = {
  43.     "PER": "ПЕРСОНА",
  44.     "LOC": "МЕСТО",
  45.     "ORG": "ОРГАНИЗАЦИЯ",
  46. }
  47.  
  48. # ══════════════════════════════════════════════
  49. # Анализ
  50. # ══════════════════════════════════════════════
  51. for text in texts:
  52.     print("═" * 60)
  53.     print(f"Текст: {text}\n")
  54.  
  55.     results = ner(text)
  56.  
  57.     if not results:
  58.         print("  Сущности не найдены.\n")
  59.         continue
  60.  
  61.     for r in results:
  62.         label = LABEL_MAP.get(r["entity_group"], r["entity_group"])
  63.         word = r["word"]
  64.         score = r["score"]
  65.         print(f"  {label:15s}  {word:25s}  {score:.0%}")
  66.  
  67.     print()
  68.  
  69. # ══════════════════════════════════════════════
  70. # Сводная таблица: кто, где, какие организации
  71. # ══════════════════════════════════════════════
  72. print("\n" + "═" * 60)
  73. print("СВОДКА ПО ВСЕМ ТЕКСТАМ\n")
  74.  
  75. all_entities = {"PER": set(), "LOC": set(), "ORG": set()}
  76.  
  77. for text in texts:
  78.     for r in ner(text):
  79.         group = r["entity_group"]
  80.         if group in all_entities:
  81.             all_entities[group].add(r["word"])
  82.  
  83. for group, label in LABEL_MAP.items():
  84.     entities = sorted(all_entities[group])
  85.     print(f"  {label}:")
  86.     for e in entities:
  87.         print(f"    • {e}")
  88.     print()
Tags: bert
Advertisement
Add Comment
Please, Sign In to add comment