updating nlp policies; more robust recognition beyond rules
This commit is contained in:
@@ -0,0 +1,64 @@
|
||||
"""Learning from the corrections made while reviewing documents: once an
|
||||
import is written, each document source whose records a person corrected
|
||||
teaches its domain's extraction ranker (`models.io.extraction_ranker`), in
|
||||
the background so the import never waits for it, one batch at a time.
|
||||
|
||||
`EXTRACTION_LEARNING=0` turns it off.
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
from concurrent.futures import Future, ThreadPoolExecutor
|
||||
from typing import Sequence
|
||||
|
||||
from webapi.imports.connectors.document import DocumentConnector
|
||||
|
||||
LEARNING_ENV = "EXTRACTION_LEARNING"
|
||||
SOURCE = "revision"
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
_executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="extraction-learning")
|
||||
|
||||
|
||||
def enabled() -> bool:
|
||||
return os.environ.get(LEARNING_ENV, "1").strip().lower() not in ("0", "false", "no")
|
||||
|
||||
|
||||
def _connector(source) -> DocumentConnector | None:
|
||||
if source.source_type == "document":
|
||||
connector = source.connector()
|
||||
elif source.documents:
|
||||
connector, _, _ = source.document_connector()
|
||||
else:
|
||||
return None
|
||||
return connector if isinstance(connector, DocumentConnector) else None
|
||||
|
||||
|
||||
def learn_from_reviews(sources: Sequence) -> list[Future]:
|
||||
"""Queues one learning step per corrected document source; returns them,
|
||||
for a caller that wants to wait."""
|
||||
if not enabled():
|
||||
return []
|
||||
futures = []
|
||||
for source in sources:
|
||||
try:
|
||||
connector = _connector(source)
|
||||
if connector is None or not connector.overrides:
|
||||
continue
|
||||
examples, unreachable, records = connector.learning_examples()
|
||||
except Exception: # noqa: BLE001 - the import is already written
|
||||
logger.exception("no se pudieron preparar ejemplos de %s", getattr(source, "target", "?"))
|
||||
continue
|
||||
if examples:
|
||||
documents = len(connector.files)
|
||||
futures.append(_executor.submit(_learn, connector.domain, examples, unreachable, records, documents))
|
||||
return futures
|
||||
|
||||
|
||||
def _learn(domain: str, examples: list, unreachable: dict[str, int], records: int, documents: int) -> str | None:
|
||||
from models.io.extraction_ranker import Batch, learn
|
||||
|
||||
try:
|
||||
return learn(domain, Batch(examples, SOURCE, documents, records, unreachable))
|
||||
except Exception: # noqa: BLE001
|
||||
logger.exception("el ranker de extracción de %s no pudo aprender de la revisión", domain)
|
||||
return None
|
||||
Reference in New Issue
Block a user