Compare commits

..
Author SHA1 Message Date
codex 41467471e2 Различать число распознанных записей и отсутствие данных
CI / test (pull_request) Successful in 12m21s
CI / Fingerprint diagnostics (production deployment temporarily disabled) (pull_request) Skipped
2026-11-24 16:56:34 +00:00
codex 8dde82ab8a Исправить подсчёт ДПО и индикацию загрузки справочника
CI / test (pull_request) Successful in 12m55s
CI / Fingerprint diagnostics (production deployment temporarily disabled) (pull_request) Skipped
2026-11-24 16:55:22 +00:00
agent 10b91314e3 Merge pull request 'Запускать Workers CD платформы после слияния в main' (#82) from feature/dispatch-workers-cd into main
CI / test (push) Successful in 12m35s
CI / Fingerprint diagnostics (production deployment temporarily disabled) (push) Skipped
Request Workers deployment / dispatch (push) Successful in 16s
2026-11-24 15:38:30 +00:00
codex 6153beaf47 Request platform CD after protected main updates
CI / test (pull_request) Successful in 12m56s
CI / Fingerprint diagnostics (production deployment temporarily disabled) (pull_request) Skipped
2026-11-24 15:12:55 +00:00
agent ebb776b9e4 Merge pull request 'Дополнительное образование: разбор профилей, документов и предупреждения' (#81) from feature/dpo-recognition-230 into main
CI / test (push) Successful in 12m46s
CI / Fingerprint diagnostics (production deployment temporarily disabled) (push) Skipped
2026-11-24 11:49:07 +00:00
codex c9f92086e5 Honor the parser's education section type in directory training filters
CI / test (pull_request) Successful in 12m46s
CI / Fingerprint diagnostics (production deployment temporarily disabled) (pull_request) Skipped
2026-11-24 11:35:59 +00:00
codex 3717a00459 Fix training year filter and reject incomplete OCR titles
CI / test (pull_request) Successful in 12m53s
CI / Fingerprint diagnostics (production deployment temporarily disabled) (pull_request) Skipped
2026-11-24 10:21:22 +00:00
codex 65d851bb92 Parse mixed education records and certificates, flag unresolved DPO
CI / test (pull_request) Successful in 12m17s
CI / Fingerprint diagnostics (production deployment temporarily disabled) (pull_request) Skipped
2026-11-20 16:02:16 +00:00
agent 8dfd700bd5 Merge pull request 'Показывать загрузку и блокировать фильтры справочника' (#80) from fix/directory-loading-state into main
CI / test (push) Successful in 12m21s
CI / Fingerprint diagnostics (production deployment temporarily disabled) (push) Skipped
2026-11-20 09:11:13 +00:00
21 changed files with 534 additions and 25 deletions

No files matched your search

+24
View File
@@ -0,0 +1,24 @@
name: Request Workers deployment
on:
push:
branches: [main]
jobs:
dispatch:
runs-on: ubuntu-latest
timeout-minutes: 3
steps:
- name: Request Workers CD on infra-platform main
env:
DISPATCH_TOKEN: ${{ secrets.INFRA_CD_DISPATCH_TOKEN }}
run: |
set -eu
test -n "$DISPATCH_TOKEN" || { echo "Missing INFRA_CD_DISPATCH_TOKEN"; exit 1; }
status=$(printf 'Authorization: token %s\n' "$DISPATCH_TOKEN" |
curl -q --silent --show-error --connect-timeout 10 --max-time 60 \
--header @- --header 'Content-Type: application/json' \
--data '{"ref":"main"}' --output /dev/null --write-out '%{http_code}' \
'https://git.vakanaut.ru/api/v1/repos/admin/infra-platform/actions/workflows/workers-cd.yml/dispatches')
case "$status" in
2??) echo "Workers deployment request accepted" ;;
*) echo "Workers deployment request failed (HTTP $status)"; exit 1 ;;
esac
+12
View File
@@ -1,5 +1,17 @@
# Changelog
## Эксплуатация · 2026-11-24
- После слияния в `main` Workers запрашивает запуск `workers-cd.yml` в `admin/infra-platform`. Результат выкладки фиксируется в Actions платформы.
## 2.3.1
- Исправлен подсчёт ДПО для многострочных записей и ранее сохранённых профилей. Возможные повторы отмечаются в справочнике и карточке. При смене страницы виден индикатор загрузки. Профессиональные интересы показаны ссылками.
## 2.3.0
- Раздел ДПО объединяет сведения из профиля и документов. Справочник показывает отдельный счётчик ДПО, а предупреждение ведёт к нераспознанным фрагментам в карточке.
## 2.2.1
- При применении фильтров справочника, переключении ППС, сортировки и размера страницы появляется заглушка «Обновляем список…». Поля, кнопки и ссылки справочника заблокированы до завершения запроса.
+1 -1
View File
@@ -6,7 +6,7 @@ ENV PYTHONDONTWRITEBYTECODE=1 \
WORKDIR /app
RUN apt-get update \
&& apt-get install -y --no-install-recommends gcc libpq-dev \
&& apt-get install -y --no-install-recommends gcc libpq-dev poppler-utils tesseract-ocr tesseract-ocr-rus \
&& rm -rf /var/lib/apt/lists/*
COPY requirements.txt .
+80
View File
@@ -0,0 +1,80 @@
"""Assemble additional education events from the public profile's mixed markup."""
import re
YEAR = re.compile(r"\b(?:19|20)\d{2}\b")
_QUOTE = re.compile(r'«([^»]+)»|"([^"]+)"')
_EVENT = re.compile(r"стажиров|стипенди|исследовательск|обучени|квалификаци|переподготовк|прош[её]л|прошла|семинар|сертификаци|программ[аеуы]|курсы?\b", re.I)
_CONTINUES = re.compile(r"(?:по программе|присвоением степени|на тему|по курсу|по теме|по специальности)[:\s]*$", re.I)
_CAPTION = re.compile(r"^(?:удостоверение|сертификат|свидетельство)(?: о повышении квалификации)?[.:]?$", re.I)
_DATED_ROW = re.compile(r'\s+(?=(?:19|20)\d{2}\s*г\.\s*["«])')
def education_title(title):
labels = {"дополнительное образование", "повышение квалификации", "курсы повышения квалификации"}
return any(part.strip().rstrip(":") in labels for part in str(title).casefold().split("/"))
def split_dated_rows(text):
return _DATED_ROW.split(text) if re.match(r"^(?:19|20)\d{2}\s*г\.", text) else [text]
def _key(text):
return " ".join(re.findall(r"\w+", text.casefold().replace("ё", "е")))
def _provider(text):
text = _key(text)
for variants in (("вшэ", "высшая школа экономики", "высшей школе экономики"),
("мифи", "московский инженерно физический институт")):
if any(v in text.split() if " " not in v else v in text for v in variants):
return variants[0]
return text
def assemble(rows):
events = []
unresolved = []
pending = []
for text, year, structured, list_item in rows:
if _CAPTION.fullmatch(text):
continue
if (pending and not structured and not list_item and not YEAR.match(text)
and (_CONTINUES.search(pending[-1][0]) or
(pending[-1][3] and not _EVENT.search(text[:20]) and not YEAR.search(text)) or
(pending[-1][3] and text.startswith("Курс ") and not YEAR.search(text)))):
pending[-1][0] += " " + text
pending[-1][3] = False
else:
pending.append([text, year, structured, list_item])
for text, year, structured, _ in pending:
certificate = re.match(r"^сертификат\s+[«\"]", text, re.I)
if not structured and (len(_key(text).split()) < 2 or not (_EVENT.search(text) or YEAR.match(text) or certificate)):
unresolved.append(text)
continue
quotes = [a or b for a, b in _QUOTE.findall(text)]
title = _key(quotes[-1]) if quotes else ""
if re.match(r'^(?:19|20)\d{2}\s*г\.\s*["«]', text) and quotes:
title = _key(quotes[0])
if structured and text.lstrip("0123456789 ").startswith("«"):
title = _key(text.split("«", 1)[1].rsplit("»", 1)[0])
provider = _provider(text.rsplit("»", 1)[-1] if structured and "»" in text else text)
if not year:
match = YEAR.search(_QUOTE.sub("", text))
year = int(match[0]) if match else None
matches = [e for e in events if title and e["title"] == title and e["provider"] == provider
and (e["year"] == year or not year or not e["year"])]
if len(matches) == 1:
target = matches[0]
hours = re.search(r"\b\d+\s+час[а-я]*", text, re.I)
if hours and hours[0] not in target["text"]:
target["text"] += " (" + hours[0] + ")"
continue
if any(e["text"] == text for e in events):
continue
if title and any(e["title"] == title and e["year"] == year for e in events):
unresolved.append("Возможный повтор: " + text)
events.append(dict(text=text, year=year, structured=structured, title=title, provider=provider))
return events, unresolved
+76
View File
@@ -0,0 +1,76 @@
"""Read public HSE education documents. An inconclusive extraction stays visible for review."""
import hashlib
import re
import subprocess
from pathlib import Path
from tempfile import TemporaryDirectory
from urllib.parse import urlsplit
import requests
_MAX_BYTES = 12 * 1024 * 1024
def _run(args):
return subprocess.run(args, check=True, capture_output=True, timeout=30).stdout.decode("utf-8")
def _certificate(text):
text = " ".join(text.split())
title = re.search(
r'(?:по (?:дополнительной профессиональной )?программе|по теме|на тему)'
r'(?: повышения квалификации| дополнительного профессионального образования)?'
r'\s*:?\s*[«"“]([^»"”]{5,300})[»"”]', text, re.I,
)
if not title:
title = re.search(r'[«"“]([^«»"“”]{8,250})[»"”]\s*[,.(]?\s*(?:в объ[её]ме|\d+ час)', text, re.I)
if title and "|" in title[1]:
return None # OCR could not read the entire program name.
years = re.findall(r"\b(?:19|20)\d{2}\b", text)
if not title or not years or not re.search(r"квалификаци|сертификат|удостоверение", text, re.I):
return None
hours = re.search(r"(\d+)\s*(?:академических\s+)?час", text, re.I)
provider = ""
if re.search(r"высш[а-я]+ школ[а-я]+ экономик|НИУ ВШЭ", text, re.I):
provider = ", НИУ ВШЭ"
elif re.search("МИСИС", text, re.I):
provider = ", НИТУ МИСИС"
return f'{years[-1]} «{title[1].strip()}», повышение квалификации{provider}' + (f", {hours[1]} часов" if hours else "")
def _recognize(data):
with TemporaryDirectory() as tmp:
src = Path(tmp) / "document"
src.write_bytes(data)
images = [src]
if data.startswith(b"%PDF"):
direct = _certificate(_run(["pdftotext", "-layout", str(src), "-"]))
if direct:
return direct
_run(["pdftoppm", "-f", "1", "-l", "2", "-scale-to", "2400", "-png", str(src), str(src)])
images = sorted(Path(tmp).glob("document-*.png"))
elif not data.startswith((b"\x89PNG", b"\xff\xd8\xff")):
return None
return _certificate(" ".join(_run(["tesseract", str(img), "stdout", "-l", "rus+eng"]) for img in images))
def read_document(session, url, timeout, cache, profile_key):
parts = urlsplit(url)
if parts.scheme != "https" or parts.netloc != "www.hse.ru" or not parts.path.startswith("/mirror/pubs/share/"):
return None
try:
with session.get(url, stream=True, timeout=timeout, allow_redirects=False) as response:
if response.status_code != 200:
return None
data = bytearray()
for chunk in response.iter_content(65536):
data.extend(chunk)
if len(data) > _MAX_BYTES:
return None
digest = hashlib.sha256(data).hexdigest()
if cache:
return cache.education_document(profile_key, url, digest, lambda: _recognize(data))
return _recognize(data)
except (OSError, ValueError, subprocess.SubprocessError, requests.RequestException):
return None
+102 -3
View File
@@ -1,12 +1,15 @@
import hashlib
import json
import re
from copy import deepcopy
from datetime import datetime, timezone
from urllib.parse import urljoin
from bs4 import BeautifulSoup, NavigableString, Tag
from bs4 import BeautifulSoup, Comment, NavigableString, Tag
from requests import Session
from app.parser.education import assemble, education_title, split_dated_rows
from app.parser.education_document import read_document
from app.parser.profile_url import normalize_profile_url, parse_profile_identity
from app.version import BACKEND_VERSION
@@ -99,7 +102,7 @@ def extract_person_header(soup: BeautifulSoup, source_url: str) -> dict:
}
def extract_sections(soup: BeautifulSoup, source_url: str) -> list[dict]:
def extract_sections(soup: BeautifulSoup, source_url: str, document_reader=None) -> list[dict]:
sections = []
for h2 in soup.select("h2"):
if h2.find_parent(class_="post") or h2.find_parent(attrs={"data-tab": "press_links_news"}):
@@ -108,6 +111,10 @@ def extract_sections(soup: BeautifulSoup, source_url: str) -> list[dict]:
if not title or "расписание занятий" in title.lower():
continue
nodes = _collect_between_h2(h2)
if (h2.find_parent(attrs={"tab-node": "additional_education"})
or education_title(title)):
sections.append(_parse_additional_education(title, nodes, source_url, document_reader))
continue
raw_text = _nodes_raw_text(nodes)
paragraphs = _nodes_paragraphs(nodes)
items = _nodes_list_items(nodes)
@@ -117,6 +124,9 @@ def extract_sections(soup: BeautifulSoup, source_url: str) -> list[dict]:
links.extend(_extract_links(node, source_url))
section_type = _infer_section_type(title, nodes)
if title.casefold().rstrip(":") == "профессиональные интересы":
sections.append({"title": title, "slug": _slugify(title), "type": "links", "links": links})
continue
section = {
"title": title,
"slug": _slugify(title),
@@ -193,7 +203,7 @@ def parse_person_profile(
soup = BeautifulSoup(html, "html.parser")
header = extract_person_header(soup, normalized_url)
tabs = extract_person_tabs(soup, normalized_url)
sections = extract_sections(soup, normalized_url)
sections = extract_sections(soup, normalized_url, lambda url: read_document(session, url, timeout, resource_cache, cache_profile_key))
sections = enrich_sections_from_hse_widgets(
session,
soup,
@@ -219,6 +229,7 @@ def parse_person_profile(
"tabs": tabs,
"sections": sections,
"employee_internal_links": internal_links,
"education_parsed": True,
"parser_version": BACKEND_VERSION,
"_html": html,
"_resource_manifest": resource_manifest,
@@ -585,6 +596,94 @@ def _parse_year_entries(nodes: list, source_url: str) -> list[dict]:
return entries
_FILE_FORMAT = r"(?:pdf|jpe?g|png|docx?|pptx?|xlsx?|zip|rar)"
_FILE_SIZE = re.compile(rf"\(\s*{_FILE_FORMAT}\s*,\s*[\d.,\s]+[кмгkmg]?\s*[бb](?:айт[а-я]*)?\s*\)", re.I)
_FILE_CAPTION = re.compile(rf"\b(?:файл|сертификат|свидетельство|удостоверение)(?:_\w+)?\s*{_FILE_SIZE.pattern}", re.I)
_FILE_URL = re.compile(rf"/mirror/pubs/share/|\.{_FILE_FORMAT}(?:[?#]|$)", re.I)
_INITIAL_YEAR = re.compile(r"^(?:19|20)\d{2}\b")
def _education_blocks(node):
"""Yield whole course rows or paragraphs once, in document order."""
if not isinstance(node, Tag):
if not isinstance(node, Comment) and normalize_ws(str(node)):
yield node
return
if node.name == "tr" and node.find("th"):
return
if (node.name in {"li", "p", "tr"} or node.find(class_="person-list-hangover", recursive=False)
or not node.find(["div", "ul", "ol", "li", "p", "table", "tr"])):
yield node
return
for child in node.children:
yield from _education_blocks(child)
def _parse_additional_education(title: str, nodes: list, source_url: str, document_reader=None) -> dict:
rows = []
documents = {}
unresolved_documents = []
links = []
for original in nodes:
node = deepcopy(original)
if isinstance(node, Tag):
for image in node.select("img[src]"):
if _FILE_URL.search(image["src"]) and not image.find_parent("a", href=True):
documents.setdefault(urljoin(source_url, image["src"]), image.get("alt") or "Изображение документа")
for anchor in node.select("a[href]"):
following = anchor.next_sibling
suffix = following.get_text(strip=True) if isinstance(following, Tag) else str(following or "")
if (_FILE_URL.search(anchor["href"]) or anchor.has_attr("download")
or _FILE_SIZE.match(normalize_ws(suffix))):
documents[urljoin(source_url, anchor["href"])] = normalize_ws(anchor.get_text(" ", strip=True)) or "Документ"
anchor.decompose()
for block in _education_blocks(node):
is_tag = isinstance(block, Tag)
content = block.get_text(" ", strip=True) if is_tag else str(block)
text = normalize_ws(_FILE_SIZE.sub("", _FILE_CAPTION.sub("", content)))
text = re.sub(r"\s+([,.;:])", r"\1", text)
text = re.sub(r"(?<=[.!?])\.$", "", text)
if not re.search(r"\w", text):
continue
block_links = _extract_links(block, source_url) if is_tag else []
links.extend(block_links)
year_node = block.find(class_="person-list-hangover", recursive=False) if is_tag else None
year_match = _INITIAL_YEAR.match(year_node.get_text(strip=True)) if year_node else None
if is_tag and not year_node and block.find("br"):
for br in block.find_all("br"):
br.replace_with("\n")
lines = []
for line in block.get_text(" ", strip=False).splitlines():
line = normalize_ws(_FILE_SIZE.sub("", _FILE_CAPTION.sub("", line)))
if not re.search(r"\w", line):
continue
if lines and not (_INITIAL_YEAR.match(line) or re.match(r"^(?:курс|повышение квалификации)\b", line, re.I)):
lines[-1] += " " + line
else:
lines.append(line)
else:
lines = [text]
for line in lines:
for part in split_dated_rows(line):
rows.append((part, int(year_match[0]) if year_match else None, bool(year_node), is_tag and block.name == "li"))
for url, caption in documents.items():
recognized = document_reader(url) if document_reader else None
if recognized:
rows.append((recognized, None, False, False))
elif document_reader:
unresolved_documents.append({"text": caption, "url": url})
events, unresolved = assemble(rows)
items = [event["text"] for event in events]
year_entries = [{"year": event["year"], "text": event["text"], "links": []}
for event in events if event["structured"]]
return {
"title": title, "slug": _slugify(title), "type": "additional_education", "education_format": 2,
"items": items, "paragraphs": [], "year_entries": year_entries,
"unresolved": unresolved, "unresolved_documents": unresolved_documents,
"raw_text": "\n".join(items), "links": links,
}
def _parse_vkr_items(nodes: list) -> list[str]:
items = []
for node in nodes:
+55 -8
View File
@@ -10,6 +10,7 @@ from sqlalchemy import Select, Text, and_, desc, func, or_, select
from sqlalchemy.orm import Session, selectinload
from app.models import CrawlError, CrawlRun, CrawlRunEmployeeChange, Employee, EmployeeNewsLink
from app.parser.education import assemble, education_title, split_dated_rows
from app.services.academic_degrees import academic_degrees
EMPLOYEE_SORTS = {
@@ -32,16 +33,16 @@ DIRECTORY_COLUMNS = (
("address", "Адрес", "address"),
("academic_degree", "Учёная степень", "academic_degree_text"),
("publications_count", "Публикации", "publications_count"),
("courses_count", "Курсы", "courses_count"),
("courses_count", "Преподаваемые курсы", "courses_count"),
("news_count", "Новости", "news_count"),
("first_seen_at", "Впервые найден", "first_seen_display"),
("last_seen_at", "Последний раз найден", "last_seen_display"),
("dismissed_at", "Дата увольнения", "dismissed_display"),
("profile", "Профиль", "canonical_url"),
("dpo_count", "Количество ДПО", "dpo_count"),
)
_TRAINING_LABEL = "повышение квалификации"
_TRAINING_KIND = re.compile(r",\s*повышение квалификации\s*(?:,|$)", re.IGNORECASE)
_TRAINING_MENTION = re.compile(
r"\b(?:повышение квалификации|(?:курс|программ)[а-яё]* (?:повышения|по повышению) квалификации)\b",
re.IGNORECASE,
@@ -55,18 +56,23 @@ def _has_training(data: dict[str, Any], since_year: int | None) -> bool:
section = _as_dict(value)
title = str(section.get("title") or "").casefold().strip().rstrip(":")
dedicated = title in {_TRAINING_LABEL, "курсы повышения квалификации"}
if not dedicated and _TRAINING_LABEL not in (part.strip() for part in title.split("/")):
if (section.get("type") != "additional_education" and not dedicated
and _TRAINING_LABEL not in (part.strip() for part in title.split("/"))):
continue
structured_texts = set()
for value in _as_list(section.get("year_entries")):
entry = _as_dict(value)
year = entry.get("year")
text = str(entry.get("text") or "").strip()
structured_texts.add(text)
if since_year is not None and (type(year) is not int or year < since_year):
continue
if text and text != str(year) and (dedicated or _TRAINING_KIND.search(_QUOTED_TEXT.sub("", text))):
if text and text != str(year) and (dedicated or _TRAINING_MENTION.search(_QUOTED_TEXT.sub("", text))):
return True
# Profiles may also list completed courses in manually entered paragraphs or lists.
for text in _clean_list(section.get("paragraphs")) + _clean_list(section.get("items")):
if text in structured_texts:
continue
description = _QUOTED_TEXT.sub("", text).strip()
if not dedicated and not _TRAINING_MENTION.search(description):
continue
@@ -78,15 +84,48 @@ def _has_training(data: dict[str, Any], since_year: int | None) -> bool:
return False
def employee_display_payload(employee: Employee) -> dict[str, Any]:
def _display_sections(data):
sections = []
for section in _as_list(data.get("sections")):
if not isinstance(section, dict) or section.get("education_format") == 2:
sections.append(section)
continue
typed = section.get("type") == "additional_education"
if not typed and not education_title(section.get("title")):
sections.append(section)
continue
# Profiles collected before dedicated DPO parsing retain years and free text separately.
rows = [(entry["text"], entry.get("year"), True, False)
for entry in section.get("year_entries", []) if isinstance(entry, dict) and entry.get("text")]
texts = _clean_list(section.get("paragraphs")) + _clean_list(section.get("items"))
if not rows and not texts:
texts = str(section.get("raw_text") or "").splitlines()
structured_texts = {row[0] for row in rows}
for text in texts:
if text not in structured_texts:
rows.extend((part, None, False, False) for part in split_dated_rows(text))
events, unresolved = assemble(rows)
unresolved.extend(_clean_list(section.get("unresolved")))
if not typed:
unresolved.append("Сведения взяты из прежней версии профиля. Требуется обновление карточки.")
sections.append({**section, "type": "additional_education", "paragraphs": [],
"items": [e["text"] for e in events],
"unresolved": list(dict.fromkeys(unresolved))})
return sections
def employee_display_payload(employee: Employee, *, sections=None) -> dict[str, Any]:
data = _as_dict(employee.current_data)
contacts = _as_dict(data.get("contacts"))
sections = _as_list(data.get("sections"))
if sections is None:
sections = _display_sections(data)
stored_news_links = _stored_news_links(employee)
positions = _clean_list(data.get("positions"))
emails = _clean_list(contacts.get("emails"))
phones = _clean_list(contacts.get("phones"))
degree_values = academic_degrees(data)
education = [s for s in sections if isinstance(s, dict) and s.get("type") == "additional_education"]
dpo_count = sum(len(s.get("items", [])) for s in education)
return {
"id": employee.id,
"full_name": employee.full_name,
@@ -103,6 +142,8 @@ def employee_display_payload(employee: Employee) -> dict[str, Any]:
"address": contacts.get("address"),
"academic_degree_text": "; ".join(degree_values),
"publications_count": _count_section_items(sections, "publications"),
"dpo_count": dpo_count or None,
"dpo_uncertain": any(not s.get("items") or s.get("unresolved") or s.get("unresolved_documents") for s in education),
"courses_count": _count_section_items(sections, "courses_by_year"),
"news_count": len(stored_news_links) or _count_section_items(sections, "news"),
"first_seen_at": employee.first_seen_at.isoformat() if employee.first_seen_at else None,
@@ -116,9 +157,10 @@ def employee_display_payload(employee: Employee) -> dict[str, Any]:
def employee_detail_payload(employee: Employee) -> dict[str, Any]:
data = _as_dict(employee.current_data)
sections = _display_sections(data)
contacts = _as_dict(data.get("contacts"))
return {
**employee_display_payload(employee),
**employee_display_payload(employee, sections=sections),
"profile_type": employee.profile_type or data.get("profile_type"),
"profile_id": employee.profile_id or data.get("profile_id"),
"parser_version": employee.parser_version or data.get("parser_version"),
@@ -130,7 +172,7 @@ def employee_detail_payload(employee: Employee) -> dict[str, Any]:
},
"external_ids": _normalize_external_ids(data.get("external_ids")),
"news_links": _detail_news_links(employee, data),
"sections": [_normalize_section(section) for section in _as_list(data.get("sections"))],
"sections": [_normalize_section(section) for section in sections],
}
@@ -444,6 +486,9 @@ def _normalize_section(section: Any) -> dict[str, Any]:
return {"title": "Раздел", "type": "generic", "paragraphs": [str(section)], "items": [], "links": []}
section_type = section.get("type") or "generic"
if str(section.get("title", "")).strip().casefold().rstrip(":") == "профессиональные интересы":
section = {"title": section["title"], "links": section.get("links")}
section_type = "links"
paragraphs = _clean_list(section.get("paragraphs"))
items = _clean_list(section.get("items"))
raw_text = str(section.get("raw_text") or "").strip()
@@ -456,6 +501,8 @@ def _normalize_section(section: Any) -> dict[str, Any]:
"raw_text": raw_text,
"paragraphs": paragraphs,
"list_items": items,
"unresolved": _clean_list(section.get("unresolved")),
"unresolved_documents": _normalize_links(section.get("unresolved_documents")),
"links": _normalize_links(section.get("links")),
"year_entries": _normalize_year_entries(section.get("year_entries")),
"publications": _normalize_publications(section.get("publications")),
+1 -1
View File
@@ -19,7 +19,7 @@ def directory_xlsx(employees: list[dict]) -> bytes:
(employee[key] or "Без имени") if key == "full_name" else employee[key]
for _, _, key in DIRECTORY_COLUMNS
])
for cell, width in zip(sheet[1], (34, 20, 48, 14, 28, 22, 34, 30, 14, 10, 10, 22, 24, 22, 46)):
for cell, width in zip(sheet[1], (34, 20, 48, 14, 28, 22, 34, 30, 14, 10, 10, 22, 24, 22, 46, 18)):
cell.font = Font(bold=True)
sheet.column_dimensions[get_column_letter(cell.column)].width = width
sheet.freeze_panes = "A2"
+18
View File
@@ -27,6 +27,24 @@ class ResourceCache:
def __init__(self, db: Session):
self.db = db
def education_document(self, profile_key, url, digest, recognize):
key = "education-document-v1"
existing = self.db.scalar(select(ParseResourceCache).where(
ParseResourceCache.profile_key == profile_key, ParseResourceCache.resource_key == key,
ParseResourceCache.request_fingerprint == digest))
if existing:
return gzip.decompress(existing.body_snapshot).decode() or None
result = recognize()
from sqlalchemy.exc import IntegrityError
try:
with self.db.begin_nested():
self.db.add(ParseResourceCache(profile_key=profile_key, resource_key=key, method="OCR", url=url,
request_fingerprint=digest, body_hash=digest, body_snapshot=gzip.compress((result or "").encode()),
parser_version=BACKEND_VERSION))
except IntegrityError:
pass # Another crawl cached the same document.
return result
def fetch_text(
self,
session: requests.Session,
+3
View File
@@ -1172,3 +1172,6 @@
.guide__fields dd { margin: 4px 0 0; overflow-wrap: anywhere; }
.guide--page { max-width: 75ch; }
.guide--page .guide__step + .guide__step { margin-block-start: 32px; }
.dpo-warning { color: #ab202b; text-decoration: none; }
#unresolved-dpo:target { outline: 2px solid #ab202b; outline-offset: 3px; }
+20 -1
View File
@@ -10,7 +10,7 @@
const columnPresets = {
review: ["full_name", "status", "academic_degree", "last_seen_at", "profile"],
contacts: ["full_name", "status", "email", "phone", "address", "profile"],
full: ["full_name", "status", "positions", "hse_start_year", "email", "phone", "address", "academic_degree", "publications_count", "courses_count", "news_count", "first_seen_at", "last_seen_at", "dismissed_at", "profile"],
full: ["full_name", "status", "positions", "hse_start_year", "email", "phone", "address", "academic_degree", "publications_count", "courses_count", "news_count", "first_seen_at", "last_seen_at", "dismissed_at", "profile", "dpo_count"],
};
function readColumns() {
@@ -196,6 +196,25 @@
} else refresh(blocking, manual);
}
pagination.addEventListener("click", (event) => {
const link = event.target.closest("a[href]");
if (!link || event.button !== 0 || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) return;
event.preventDefault();
clearTimeout(timer);
pending?.abort();
pending = null;
setLoading(true, true);
pagination.querySelector("[data-page-status]").hidden = false;
window.location.assign(link.href);
});
window.addEventListener("pageshow", (event) => {
if (event.persisted) {
setLoading(false);
summary.textContent = appliedSummary;
pagination.querySelector("[data-page-status]").hidden = true;
}
});
form.addEventListener("submit", (event) => {
event.preventDefault();
schedule(0, true, true);
+3 -1
View File
@@ -108,7 +108,7 @@
<tbody>
{% for employee in page.employees %}
<tr class="directory-table__row">
<td class="directory-table__cell" data-column="full_name"><a class="admin__link" href="/admin/employees/{{ employee.id }}">{{ employee.full_name or "Без имени" }}</a></td>
<td class="directory-table__cell" data-column="full_name"><a class="admin__link" href="/admin/employees/{{ employee.id }}">{{ employee.full_name or "Без имени" }}</a>{% if employee.dpo_uncertain %} <a class="dpo-warning" href="/admin/employees/{{ employee.id }}#unresolved-dpo" aria-label="Проверить количество ДПО" title="Проверить количество ДПО">⚠︎</a>{% endif %}</td>
<td class="directory-table__cell" data-column="status"><span class="badge {% if employee.status == "dismissed" %}badge--dismissed{% elif employee.status == "verification_required" %}badge--verification{% endif %}">{{ employee.status_display }}</span></td>
<td class="directory-table__cell" data-column="positions">{{ employee.positions_text }}</td>
<td class="directory-table__cell" data-column="hse_start_year">{{ employee.hse_start_year or "" }}</td>
@@ -123,6 +123,7 @@
<td class="directory-table__cell" data-column="last_seen_at">{{ employee.last_seen_display }}</td>
<td class="directory-table__cell" data-column="dismissed_at">{{ employee.dismissed_display }}</td>
<td class="directory-table__cell" data-column="profile"><a class="admin__link" href="{{ employee.canonical_url }}" target="_blank" rel="noopener">Внешний профиль</a></td>
<td class="directory-table__cell" data-column="dpo_count">{{ employee.dpo_count if employee.dpo_count is not none else "—" }}{% if employee.dpo_uncertain %} <a class="dpo-warning" href="/admin/employees/{{ employee.id }}#unresolved-dpo" title="Количество ДПО требует проверки" aria-label="Количество ДПО требует проверки"><span aria-hidden="true">⚠︎</span></a>{% endif %}</td>
</tr>
{% else %}
<tr><td class="directory-table__empty" colspan="{{ directory_columns|length }}">
@@ -141,6 +142,7 @@
</div>
<div class="directory__pagination" data-directory-pagination>
<span role="status" data-page-status hidden>Загружаем страницу…</span>
{% set prev_offset = filters.offset - filters.limit %}
{% set next_offset = filters.offset + filters.limit %}
{% if filters.offset > 0 %}
+14 -1
View File
@@ -4,7 +4,7 @@
<section class="employee-card">
<div class="employee-card__header">
<div class="employee-card__identity">
<h2 class="employee-card__title">{{ employee_view.full_name or employee.profile_key }}</h2>
<h2 class="employee-card__title">{{ employee_view.full_name or employee.profile_key }}{% if employee_view.dpo_uncertain %} <a class="dpo-warning" href="#unresolved-dpo" title="Количество ДПО требует проверки" aria-label="Количество ДПО требует проверки"><span aria-hidden="true">⚠︎</span></a>{% endif %}</h2>
<span class="badge {% if employee_view.status == "dismissed" %}badge--dismissed{% endif %}">{{ employee_view.status_display }}</span>
</div>
<div class="employee-card__actions">
@@ -215,6 +215,9 @@
</table>
</div>
{% else %}
{% if section.type == "additional_education" and section.list_items %}
<p class="employee-section__note">Распознано записей: {{ section.list_items | length }}</p>
{% endif %}
{% if section.paragraphs %}
{% for paragraph in section.paragraphs %}
<p class="employee-section__text">{{ paragraph }}</p>
@@ -238,6 +241,16 @@
{% endif %}
</article>
{% endfor %}
{% if employee_view.dpo_uncertain %}
<div id="unresolved-dpo" tabindex="-1">
<h4>Количество ДПО требует проверки</h4>
{% for section in profile_sections %}
{% if section.type == "additional_education" and not section.list_items %}<p>В разделе ДПО не удалось выделить отдельные записи.</p>{% endif %}
{% for text in section.unresolved %}<p>{{ text }}</p>{% endfor %}
{% for doc in section.unresolved_documents %}<p>{% if doc.url.startswith(('https://', 'http://')) %}<a href="{{ doc.url }}">{{ doc.text }}</a>{% else %}{{ doc.text }}{% endif %}</p>{% endfor %}
{% endfor %}
</div>
{% endif %}
</div>
{% else %}
<p class="employee-section__text">Разделы профиля не найдены.</p>
+3 -3
View File
@@ -1,3 +1,3 @@
APP_VERSION = "2.2.1"
FRONTEND_VERSION = "2.2.1"
BACKEND_VERSION = "2.2.1"
APP_VERSION = "2.3.1"
FRONTEND_VERSION = "2.3.1"
BACKEND_VERSION = "2.3.1"
+3 -3
View File
@@ -1,7 +1,7 @@
[project]
name = "miem-workers"
version = "2.2.1"
description = "MIEM employees parser, admin API, and web admin"
version = "2.3.1"
description = "MIEM employees parser, admin API, and web admin"
requires-python = ">=3.11"
dependencies = [
"apscheduler>=3.10.4",
@@ -12,7 +12,7 @@ dependencies = [
"lxml>=5.2.0",
"psycopg[binary]>=3.2.0",
"pydantic-settings>=2.4.0",
"openpyxl>=3.1.5,<4",
"openpyxl>=3.1.5,<4",
"python-multipart>=0.0.9",
"requests>=2.32.0",
"sqlalchemy>=2.0.32",
+12
View File
@@ -163,6 +163,18 @@ def main():
fulfill(pending.pop(0))
expect(summary).to_have_text("Показаны 0–0 из 0")
expect(overlay).to_be_hidden()
with factory() as db:
db.add_all(Employee(profile_key=f"staff:{i}", canonical_url=f"https://www.hse.ru/staff/{i}",
full_name=f"Сотрудник {i}") for i in range(3, 27))
db.commit()
page.goto("http://miem.test/admin/directory?limit=25")
page.route("**/*offset=25*", lambda route: pending.append(route))
page.get_by_role("link", name="Вперед").click(no_wait_after=True)
expect(page.locator("[data-page-status]")).to_be_visible()
expect(overlay).to_be_visible()
fulfill(pending.pop())
expect(summary).to_have_text("Показаны 26–26 из 26")
expect(overlay).to_be_hidden()
assert not errors, errors
browser.close()
finally:
+2 -2
View File
@@ -22,7 +22,7 @@ def test_health_returns_versions():
response = TestClient(app).get("/api/health")
assert response.status_code == 200
assert response.json()["backend_version"] == "2.2.1"
assert response.json()["backend_version"] == "2.3.1"
def test_api_employees_and_stats_require_admin_session():
@@ -202,7 +202,7 @@ def test_directory_export_uses_applied_filters_and_sort_across_pages(db_session)
assert [cell.value for cell in sheet[1]] == [
cell.get_text(strip=True) for cell in page.select(".directory-table th")
]
assert sheet.max_column == 15
assert sheet.max_column == 16
assert [cell.value for cell in sheet["A"][1:]] == [f"Export {number:02d}" for number in range(28)]
assert [cell.value for cell in sheet["A"][-3:]] == [
cell.get_text(strip=True) for cell in page.select("tbody [data-column='full_name']")
+1 -1
View File
@@ -230,7 +230,7 @@ def test_public_page_data_minimization_and_safe_links(db_session, export):
assert "javascript:" not in fragment.text and "private@example.org" not in fragment.text
assert "javascript:" not in response.text and "private@example.org" not in response.text
assert "/admin/employees/" not in response.text and "/admin/logout" not in response.text
assert "Backend 2.2.1 · Frontend 2.2.1" in response.text
assert "Backend 2.3.1 · Frontend 2.3.1" in response.text
assert "Вход в систему" in response.text
assert client.get("/admin/directory", follow_redirects=False).status_code in (302, 303, 401, 403)
assert "Сотрудники не найдены" in client.get("/admin/council?q=missing").text
+58
View File
@@ -0,0 +1,58 @@
from bs4 import BeautifulSoup
from app.parser.education_document import _certificate
from app.parser.profile import extract_sections
from app.services.resource_cache import ResourceCache
from app.services.admin_data import _display_sections
def test_dated_lines_and_wrapped_title_survive_old_and_new_profiles():
html = ('<h2>Дополнительное образование</h2><p>2002 г. "Первый курс".<br>'
'2006 г. "Второй курс".<br>Продолжение описания.</p>')
section, = extract_sections(BeautifulSoup(html, "html.parser"), "https://www.hse.ru")
expected = ['2002 г. "Первый курс".', '2006 г. "Второй курс". Продолжение описания.']
assert section["items"] == expected
for old in ({"type": "additional_education", "items": [" ".join(expected)]},
{"type": "paragraphs", "paragraphs": [" ".join(expected)]}):
saved, = _display_sections({"sections": [{**old, "title": section["title"]}]})
assert saved["items"] == expected
def test_possible_duplicate_requires_review_even_without_attachments():
html = ('<h2>Повышение квалификации</h2>'
'<p>2018 г. "Комплексная безопасность". МАИ.</p>'
'<p>2018 г. "Комплексная безопасность". Удостоверение.</p>')
section, = extract_sections(BeautifulSoup(html, "html.parser"), "https://www.hse.ru")
assert len(section["items"]) == 2
assert section["unresolved"] == ["Возможный повтор: " + section["items"][1]]
def test_unlinked_certificate_images_are_reviewed_once():
html = '<h2>Повышение квалификации</h2><p>' + '<img src="/mirror/pubs/share/12">' * 2 + '</p>'
section, = extract_sections(BeautifulSoup(html, "html.parser"), "https://www.hse.ru", lambda url: None)
assert not section["items"]
assert section["unresolved_documents"] == [{"text": "Изображение документа", "url": "https://www.hse.ru/mirror/pubs/share/12"}]
def test_education_events_preserve_ambiguities_and_separate_periods():
row = '<div><div class="person-list-hangover">{}</div><span>«Первая помощь»</span>, повышение квалификации, {}</div>'
html = ('<h2>Дополнительное образование</h2>' + row.format(2025, "НИУ ВШЭ") +
row.format(2025, "Высшая школа экономики") + row.format(2023, "НИУ ВШЭ") +
'<p>Прошел тест с присвоением степени</p><p>«Инженер»</p>'
'<p>Дополнительные сведения</p><p><a href="/mirror/pubs/share/1">Документ</a></p>')
section, = extract_sections(BeautifulSoup(html, "html.parser"), "https://www.hse.ru", lambda url: None)
assert len(section["items"]) == 3
assert section["items"][-1] == "Прошел тест с присвоением степени «Инженер»"
assert section["unresolved"] == ["Дополнительные сведения"]
assert section["unresolved_documents"][0]["url"] == "https://www.hse.ru/mirror/pubs/share/1"
def test_document_read_and_cache(db_session):
text = 'НИУ ВШЭ. Удостоверение о повышении квалификации по программе «Деловой английский» в объеме 24 часов. 2025 год'
result = _certificate(text)
assert result == "2025 «Деловой английский», повышение квалификации, НИУ ВШЭ, 24 часов"
assert _certificate("Сертификат 2025") is None
cache = ResourceCache(db_session)
assert cache.education_document("staff:test", "https://www.hse.ru/test", "1" * 64, lambda: result) == result
assert cache.education_document("staff:test", "https://www.hse.ru/test", "1" * 64, lambda: 1 / 0) == result
+31
View File
@@ -4,6 +4,37 @@ from app.parser.profile import enrich_sections_from_hse_widgets, extract_person_
from app.parser.profile_url import normalize_profile_url, parse_profile_identity
def test_mixed_additional_education_keeps_all_courses_and_omits_attachments():
structured = "".join(
f'<div class="g-ul"><div class="with-indent"><div class="person-list-hangover">{year}</div>'
f'<span>{title}</span><span>, {provider}</span></div></div>'
for year, title, provider in [(2025, "Экспортный контроль", "МИФИ"),
(2024, "Smart LMS", "ВШЭ"), (2018, "Методическая работа", "Дирекция")]
)
html = f'''<div tab-node="additional_education"><h2 class="c_14">Дополнительное образование</h2>
{structured}<div class="with-indent"><ul><li>2020 г. НИУ ВШЭ, организация учебного процесса</li></ul>
<p><a href="/f.pdf">Файл</a> (PDF, 407 Кб)</p>
<ul><li>2017 г. МГУ, методика <a href="/mirror/pubs/share/123">Сертификат</a></li>
<li>2016 г. КФУ, образовательные стандарты</li><li>2015 г. ЮФУ, ФГОС</li>
<li><strong>2015 г</strong>. МГТУ МИРЭА.</li></ul>
<p class="text">Направления совершенствования практической подготовки.</p>
<p><a href="/cert.jpg">Сертификат_МИРЭА</a> (JPG, 7,28 Мб).</p>
<ul><li>2014 г. АИОР, аккредитация.</li></ul>
<p><a href="/certificate">Свидетельство</a> (PDF, 9,36 Мб).</p>
<ul><li>2011 г. РАНХиГС.</li></ul>
<p>Курс <a href="/programme">Современные подходы</a>.</p>
<p><a href="/cert.jpg">Удостоверение</a> (JPG, 6,69 Мб).</p></div></div>'''
section, = extract_sections(BeautifulSoup(html, "html.parser"), "https://www.hse.ru/")
assert len(section["items"]) == 10
assert [row["year"] for row in section["year_entries"]] == [2025, 2024, 2018]
assert section["items"][0] == "2025 Экспортный контроль, МИФИ"
assert section["items"][7] == "2015 г. МГТУ МИРЭА. Направления совершенствования практической подготовки."
assert section["items"][9].startswith("2011 г. РАНХиГС. Курс Современные подходы")
assert section["links"] == [{"text": "Современные подходы", "url": "https://www.hse.ru/programme"}]
for fragment in ("Сертификат", "Файл", "Свидетельство", "Удостоверение", "PDF", "JPG"):
assert fragment not in str(section)
class FakeResponse:
def __init__(self, payload):
self.payload = payload
+15
View File
@@ -14,6 +14,8 @@ from app.services.admin_data import list_employees_page
@pytest.mark.parametrize(
("html", "has_course", "has_recent_course"),
[
('<div><div class="person-list-hangover">2025</div><span>Курс повышения квалификации по Python</span></div>', True, True),
('<div><div class="person-list-hangover">2025</div><span>Стажировка «Курс повышения квалификации»</span></div>', False, False),
('<p>2024 (11 декабря), НИУ ВШЭ. Программа повышения квалификации «ИИ».</p>', True, True),
('<ul><li>Программа повышения квалификации «ДПО», октябрь 2024 года.</li></ul>', True, True),
('<p>Курс повышения квалификации «ДПО», 7 сентября 2024 год.</p>', True, True),
@@ -111,3 +113,16 @@ def test_training_filter_uses_course_year_and_kind_before_pagination(db_session)
assert client.get("/admin/directory?training_since_year=bad").status_code == 422
finally:
app.dependency_overrides.clear()
@pytest.mark.parametrize(("content", "matches"), [
("Курс повышения квалификации по Python", True),
("Стажировка в университете", False),
])
def test_short_education_section_title_does_not_hide_course(db_session, content, matches):
url = "https://example.test/profile"
soup = BeautifulSoup(f"<h2>Дополнительное образование</h2><p>2025. {content}.</p>", "html.parser")
db_session.add(Employee(profile_key="training:short", canonical_url=url,
current_data={"sections": extract_sections(soup, url)}))
db_session.commit()
assert list_employees_page(db_session, training_since_year=2024)["total"] == int(matches)