Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os
- from transformers import pipeline, AutoTokenizer, AutoModelForTokenClassification
- # ══════════════════════════════════════════════
- # НАСТРОЙКИ
- # ══════════════════════════════════════════════
- MODEL_NAME = "Davlan/bert-base-multilingual-cased-ner-hrl" # NER: имена, места, организации
- MODELS_DIR = "models"
- # ══════════════════════════════════════════════
- # Загрузка модели
- # ══════════════════════════════════════════════
- local_path = os.path.join(MODELS_DIR, MODEL_NAME.replace("/", "_"))
- if os.path.exists(local_path):
- print(f"✓ Модель найдена на диске: {local_path}")
- else:
- print(f"⏳ Скачиваю «{MODEL_NAME}»...")
- tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
- model = AutoModelForTokenClassification.from_pretrained(MODEL_NAME)
- os.makedirs(local_path, exist_ok=True)
- tokenizer.save_pretrained(local_path)
- model.save_pretrained(local_path)
- print(f"✓ Модель сохранена в: {local_path}\n")
- ner = pipeline("ner", model=local_path, aggregation_strategy="simple")
- # ══════════════════════════════════════════════
- # Тексты для анализа
- # ══════════════════════════════════════════════
- texts = [
- "Владимир Путин провёл встречу с Си Цзиньпином в Пекине.",
- "Компания Яндекс открыла новый офис в Санкт-Петербурге.",
- "Журналист Иван Сафронов был задержан сотрудниками ФСБ в Москве.",
- "МГУ и Высшая школа экономики вошли в рейтинг Times Higher Education.",
- "Газпром подписал контракт с турецкой Botas на поставку газа через Анкару.",
- ]
- # ══════════════════════════════════════════════
- # Метки NER → понятные названия
- # ══════════════════════════════════════════════
- LABEL_MAP = {
- "PER": "ПЕРСОНА",
- "LOC": "МЕСТО",
- "ORG": "ОРГАНИЗАЦИЯ",
- }
- # ══════════════════════════════════════════════
- # Анализ
- # ══════════════════════════════════════════════
- for text in texts:
- print("═" * 60)
- print(f"Текст: {text}\n")
- results = ner(text)
- if not results:
- print(" Сущности не найдены.\n")
- continue
- for r in results:
- label = LABEL_MAP.get(r["entity_group"], r["entity_group"])
- word = r["word"]
- score = r["score"]
- print(f" {label:15s} {word:25s} {score:.0%}")
- print()
- # ══════════════════════════════════════════════
- # Сводная таблица: кто, где, какие организации
- # ══════════════════════════════════════════════
- print("\n" + "═" * 60)
- print("СВОДКА ПО ВСЕМ ТЕКСТАМ\n")
- all_entities = {"PER": set(), "LOC": set(), "ORG": set()}
- for text in texts:
- for r in ner(text):
- group = r["entity_group"]
- if group in all_entities:
- all_entities[group].add(r["word"])
- for group, label in LABEL_MAP.items():
- entities = sorted(all_entities[group])
- print(f" {label}:")
- for e in entities:
- print(f" • {e}")
- print()
Advertisement
Add Comment
Please, Sign In to add comment