Files
miem_workers/app/services/council_assessment.py
T

280 lines
20 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Explicit, sourced council evidence kept outside crawler-owned records."""
import json
import re
from datetime import date
from functools import lru_cache
from pathlib import Path
from app.services.council_catalog import catalog, safe_url
from app.services.council_source import _doi, _name
EVIDENCE = Path(__file__).resolve().parents[1] / "data/council_evidence.json"
BRANCHES = {}
for names, minimum, monographs in [
("биологические|географические|геолого-минералогические|медицинские|фармацевтические|физико-математические|химические", 11, 0),
("архитектура|ветеринарные|сельскохозяйственные|технические", 9, 0),
("исторические|педагогические|политические|психологические|социологические|филологические|философские|экономические|теология", 8, 1),
("юридические", 8, 0), ("искусствоведение|культурология", 7, 0),
]:
for name in names.split("|"):
BRANCHES[name] = (minimum, monographs)
SYSTEMS = {"Web of Science", "Scopus", "PubMed", "MathSciNet", "zbMATH", "Chemical Abstracts", "Springer", "GeoRef"}
TYPE_LABELS = {"article": "Статья", "monograph": "Книга", "book": "Книга", "chapter": "Глава книги",
"report": "Доклад", "patent": "Патент", "preprint": "Препринт", "conference_paper": "Материал конференции"}
def iso_date(value):
if not isinstance(value, str) or not re.fullmatch(r"\d{4}-\d{2}-\d{2}", value):
raise ValueError("Дата должна иметь формат ГГГГ-ММ-ДД")
return date.fromisoformat(value)
def sourced(record):
if not isinstance(record, dict) or not isinstance(record.get("source"), str) or not record["source"].strip():
return False
try:
iso_date(record.get("checked_on"))
except ValueError:
return False
return True
def publication_type_allowed(types, kind, policy, *, preliminary=False):
if kind is None:
return preliminary and (not types or types == ["Статья"])
if types and types != [TYPE_LABELS.get(kind)]:
return False
if kind == "article":
return True
admitted = policy.get("publication_types", {})
return sourced(admitted) and kind in admitted.get("values", [])
def degree_level(degree):
if re.fullmatch(r"доктор\b.+\bнаук", degree, re.I):
return 2
if re.fullmatch(r"кандидат\b.+\bнаук|ph\.?\s*d\.?", degree, re.I):
return 1
return 0
@lru_cache(maxsize=1)
def evidence():
data = json.loads(EVIDENCE.read_text(encoding="utf-8"))
if not isinstance(data, dict) or type(data.get("schema_version")) is not int or data["schema_version"] != 1 or not isinstance(data.get("employees"), dict):
raise ValueError("Invalid council evidence schema")
if not isinstance(data.get("policy", {}), dict):
raise ValueError("Invalid council policy")
admitted = data.get("policy", {}).get("publication_types", {})
if not isinstance(admitted, dict) or not isinstance(admitted.get("values", []), list) or not all(
isinstance(v, str) for v in admitted.get("values", [])
):
raise ValueError("Invalid admitted publication types")
for employee in data["employees"].values():
if not isinstance(employee, dict):
raise ValueError("Invalid employee evidence")
for field in ("degrees", "publications"):
if not isinstance(employee.get(field, []), list) or not all(isinstance(r, dict) for r in employee.get(field, [])):
raise ValueError("Invalid council evidence records")
for record in employee.get("publications", []):
for field in ("doi", "source_hash"):
if record.get(field) is not None and not isinstance(record[field], str):
raise ValueError("Invalid publication evidence identifier")
if not (isinstance(record.get("doi"), str) and record["doi"]) and not (
isinstance(record.get("source_hash"), str) and record["source_hash"]
):
raise ValueError("Publication evidence requires a stable identifier")
if record.get("doi") and record["doi"] != _doi(record["doi"]):
raise ValueError("Publication evidence DOI must be normalized")
if record.get("kind") is not None and not isinstance(record["kind"], str):
raise ValueError("Invalid publication kind")
if not isinstance(record.get("bases", []), list) or not all(isinstance(b, dict) for b in record.get("bases", [])):
raise ValueError("Invalid publication bases")
for basis in record.get("bases", []):
for field in ("basis", "system", "category", "metric"):
if basis.get(field) is not None and not isinstance(basis[field], str):
raise ValueError("Invalid publication basis field")
if not isinstance(record.get("issns", []), list) or not all(isinstance(v, str) for v in record.get("issns", [])):
raise ValueError("Invalid publication ISSN")
review = record.get("thematic_review")
if review is not None and (not isinstance(review, dict) or not isinstance(review.get("point_numbers", []), list)
or not all(type(v) is int for v in review.get("point_numbers", []))):
raise ValueError("Invalid thematic review")
if review is not None:
for field in ("specialty_code", "branch", "passport_id", "passport_sha256", "result"):
if review.get(field) is not None and not isinstance(review[field], str):
raise ValueError("Invalid thematic review field")
return data
def publication_proofs(employee_evidence, article):
matches = []
for record in employee_evidence.get("publications", []):
doi_matches = bool(article["doi"] and record.get("doi") == article["doi"])
hash_matches = bool(record.get("source_hash") and record["source_hash"] in article.get("source_hashes", []))
if record.get("doi") and record.get("source_hash"):
if doi_matches != hash_matches:
article["proof_identity_conflict"] = True
matched = doi_matches and hash_matches
else:
matched = doi_matches or hash_matches
if matched:
matches.append(record)
return matches
def assess_article(article, proofs, start, end, level, branch, specialty, policy):
reasons = [*article.get("catalog_issues", []), *article.get("quartile_issues", [])]
warnings = {"journal": list(dict.fromkeys(reasons)), "year": [], "type": [], "quartile": [], "specialty": []}
def report(field, message):
reasons.append(message)
warnings[field].append(message)
years = article["source_years"]
dates = set()
for proof in proofs:
if proof.get("publication_date") and sourced(proof.get("date_evidence")):
try:
dates.add(iso_date(proof["publication_date"]))
except ValueError:
pass # Exact dates are optional; the calendar-year window uses the publication year.
date_years = {value.year for value in dates}
date_conflict = len(years) > 1 or len(date_years) > 1 or bool(date_years and years and not date_years <= set(years))
if date_conflict:
report("year", "Источники указывают разные годы публикации. Уточните год статьи")
exact = next(iter(dates)) if len(dates) == 1 else None
publication_year = article["year"] if article["year"] is not None else next(iter(date_years)) if len(date_years) == 1 else None
in_period = publication_year is not None and start.year <= publication_year <= end.year
if not in_period:
report("year", f"Вне пятилетнего периода {start.year}–{end.year}" if publication_year is not None
else "Год не указан — период не подтверждён")
types = {proof["kind"] for proof in proofs if proof.get("kind") and sourced(proof.get("kind_evidence"))}
automatic_bases = [b for b in article.get("automatic_quartile_bases", [])
if b["applicable_year"] == (exact.year if exact else article["year"])
and not article.get("catalog_issues") and not article.get("quartile_issues")]
if not types and not (article["types"] == ["Статья"] and automatic_bases):
if len(article["types"]) > 1:
report("type", "Источники называют разные виды работы: " + ", ".join(article["types"]) + ". Уточните тип материала")
elif not article["types"]:
report("type", "В источниках не указан тип материала. В карточке показано «Статья», но для зачёта нужно уточнить вид работы")
elif article["types"] == ["Статья"]:
report("quartile", "Тип «Статья» указан в источнике, но для зачёта по К1/К2/RSCI отдельная запись проверки работы не сохранена. Проверьте основание зачёта")
else:
report("type", f"Источник указывает вид «{article['types'][0]}». Для включения такого материала в минимум нужно отдельное подтверждение")
kind = next(iter(types)) if len(types) == 1 else "article" if not types and article["types"] == ["Статья"] and automatic_bases else None
type_conflict = len(types) > 1 or bool(article["types"] and kind and article["types"] != [TYPE_LABELS.get(kind)])
if type_conflict:
report("type", "Источники называют разные виды работы. Уточните, является ли публикация статьёй")
eligible_kind = publication_type_allowed(article["types"], kind, policy)
if kind and kind != "article" and not eligible_kind:
report("type", "Это другой вид работы, а не статья. Его включение в публикационный минимум требует отдельного основания")
bases = []
basis_year = exact.year if exact else article["year"]
for proof in proofs:
for basis in proof.get("bases", []):
if not isinstance(basis, dict):
report("quartile", "Запись об основании зачёта повреждена. Проверьте источник категории журнала")
continue
category = basis.get("basis")
valid = sourced(basis) and type(basis.get("applicable_year")) is int and basis["applicable_year"] == basis_year
if category in {"Q1", "Q2"}:
valid = valid and basis.get("system") in SYSTEMS and bool(basis.get("category")) and bool(basis.get("metric")) and type(basis.get("metric_year")) is int
elif category not in {"К1", "К2", "RSCI"}:
valid = False
if valid:
bases.append(basis)
else:
report("quartile", "Для категории журнала не подтверждён источник или год применимости. Нельзя переносить категорию автоматически на год статьи")
if kind == "article":
bases.extend(automatic_bases)
# Different categories may legitimately have different quartiles; conflicting
# claims for the same system/category/year must not be resolved by ordering.
claims = {}
basis_conflict = False
for basis in bases:
key = ("ВАК", basis_year) if basis["basis"] in {"К1", "К2"} else (
basis.get("system", basis["basis"]), basis.get("category"), basis.get("metric"), basis.get("metric_year"), basis_year)
if key in claims and claims[key] != basis["basis"]:
report("quartile", "Подтверждённые основания источников расходятся: для одной системы, категории, метрики и года указаны разные значения")
basis_conflict = True
claims[key] = basis["basis"]
accepted = [b for b in bases if level == 2 or b["basis"] != "К2"]
if not accepted:
report("quartile", f"Нет подтверждённого основания за {basis_year or 'год публикации'}: Q1/Q2, К1{'/К2' if level == 2 else ''} или RSCI. Проверьте категорию журнала, год и источник")
# Missing optional evidence is not a veto on another sufficient independent
# basis. Identity/date/type conflicts, however, invalidate the whole work.
identity_conflict = bool(article.get("quartile_issues")) or any("расход" in reason or "идентичности" in reason or "разные журналы" in reason
for reason in article.get("catalog_issues", []))
if article.get("proof_identity_conflict"):
identity_conflict = True
report("journal", "DOI и идентификатор в ручном подтверждении указывают на разные работы. Проверьте привязку источника к этой статье")
conflicts = date_conflict or type_conflict or basis_conflict or identity_conflict
article["confirmed"] = bool(in_period and eligible_kind and accepted and not conflicts)
mono_policy = policy.get("monograph_period", {})
article["monograph_confirmed"] = bool(kind == "monograph" and not conflicts and sourced(mono_policy)
and (mono_policy.get("value") == "all_years" or
(mono_policy.get("value") == "five_years" and in_period)))
article["confirmation_reasons"] = list(dict.fromkeys(reasons))
article["warnings"] = warnings
article["display_type"] = article["type_label"] if len(article["types"]) == 1 else "Статья"
article["publication_date"] = exact
article["confirmed_bases"] = [{**b, "source_url": safe_url(b.get("source_url"))} for b in accepted]
article["thematic_status"] = "Рассмотрение статьи по паспорту не подтверждено" if specialty else "Специальность для рассмотрения статьи не выбрана"
reviews = [p.get("thematic_review") for p in proofs if p.get("thematic_review")]
valid_reviews = []
for review in reviews:
if not isinstance(review, dict):
continue
passport = catalog()["passports"].get(review.get("passport_id"), {})
passport_branch = passport.get("branch", "см. паспорт").removesuffix(" науки")
if (sourced(review) and review.get("specialty_code") == specialty and review.get("branch") == branch and
(passport_branch == "см. паспорт" or passport_branch == branch) and
passport.get("specialty_code") == specialty and review.get("passport_sha256") == passport.get("sha256") and
review.get("point_numbers") and set(review["point_numbers"]) <= {p["number"] for p in passport.get("directions", [])} and
review.get("materials") and isinstance(review.get("checked_conditions"), list) and review.get("result") in {"confirmed", "requires_check"}):
valid_reviews.append(review)
article["thematic_status"] = ("Статья рассмотрена: " + {"confirmed": "соответствие подтверждено", "requires_check": "требует проверки"}[review["result"]] + f"; паспорт {review['passport_id']}; "
f"пункты {review['point_numbers']}; {review['checked_on']}")
if len({r["result"] for r in valid_reviews}) > 1:
article["thematic_status"] = "Результаты рассмотрения статьи расходятся — требуется проверка"
if specialty and (not valid_reviews or any(r["result"] != "confirmed" for r in valid_reviews)):
warnings["specialty"].append("Связь журнала со специальностью не доказывает соответствие содержания каждой статьи. Рассмотрение этой работы по паспорту специальности не подтверждено")
def assess_candidate(degrees, articles, employee_evidence, branch, specialty, start, end):
proofs = [r for r in employee_evidence.get("degrees", []) if isinstance(r.get("degree"), str) and sourced(r)]
history = list(dict.fromkeys([*degrees, *(r["degree"] for r in proofs)]))
level = max((degree_level(d) for d in history), default=0)
selected = sorted((d for d in history if degree_level(d) == level and level), key=_name)
degree_confirmed = bool(selected and any(degree_level(r["degree"]) == level for r in proofs))
minimum, monographs = BRANCHES.get(branch, (None, 0)) if level == 2 else (20, 0) if level == 1 else (None, 0)
policy = evidence().get("policy", {})
for article in articles:
assess_article(article, publication_proofs(employee_evidence, article), start, end, level, branch, specialty, policy)
if article["confirmed"]:
for basis in article["confirmed_bases"]:
article[{"К1": "k1", "К2": "k2", "RSCI": "rsci", "Q1": "q1", "Q2": "q2"}[basis["basis"]]] = True
article["qualifies"] = article["q1"] or article["q2"] or article["k1"] or article["rsci"] or (level == 2 and article["k2"])
confirmed = sum(a["confirmed"] for a in articles)
mono_count = sum(a["monograph_confirmed"] for a in articles)
reasons = []
if not level:
reasons.append("Учёная степень для пунктов 5–6 не установлена")
elif not degree_confirmed:
reasons.append("Высшая текущая степень документально не подтверждена")
if not branch:
reasons.append("Отрасль предполагаемого включения не задана")
if not articles:
reasons.append("Доступных публикаций нет; полнота сведений не подтверждена")
if minimum is not None and confirmed < minimum:
reasons.append(f"Подтверждено {confirmed} из требуемых {minimum}; полнота перечня требует проверки")
if mono_count < monographs:
reasons.append("Обязательная монография не подтверждена")
clause = 5 if level == 2 else 6 if level == 1 else None
status = f"Соответствует публикационным критериям пункта {clause}" if clause and not reasons else "Требует проверки"
return {"degree": "; ".join(history) or "Учёная степень не указана", "selected_degree": "; ".join(selected),
"degree_confirmed": degree_confirmed, "degree_level": level, "clause": clause, "minimum": minimum,
"monograph_minimum": monographs, "monograph_count": mono_count, "confirmed_count": confirmed,
"assessment_status": status, "assessment_reasons": reasons}