Certainly! Let's walk through the code segment by segment to understand what's happening.
Imports
from __future__ import annotations
import logging
from typing import List
from django.contrib.auth.models import User
from .common import Tagger
from .plan import TaggingPlan
import autotagging.taggers.gliner_based, autotagging.taggers.rule_based
import autotagging.taggers.recognizer_based, autotagging.taggers.spacy_based
from __future__ import annotations: This future import allows for postponed evaluation of type annotations in Python, meaning that string annotations won't be evaluated until necessary. This helps avoid issues with forward references and allows for cleaner code.
- Standard library modules
logging and typing are imported. List is specifically imported for type hinting.
- Django's
User model is imported, though not used in this snippet.
Tagger and TaggingPlan are imported from the local/common modules.
- Four modules from
autotagging.taggers are imported. These imports are forced to load the tagger classes.
Class Definition: TaggingPlanFactory
class TaggingPlanFactory:
"""
This class builds a sequence of taggers according to a specific tagging plan
"""
def __init__(self):
# register all taggers classes
self.tagger_classes = self._find_tagger_classes()
if not self.tagger_classes:
logging.error("No tagger classes found!")
- The class
TaggingPlanFactory is responsible for creating taggers as specified in a tagging plan.
- The
__init__ method initializes the factory by finding all tagger classes and storing them in self.tagger_classes.
- If no tagger classes are found, an error is logged.
Method: build_taggers
def build_taggers(self, plan: TaggingPlan) -> List[Tagger]:
"""
This method builds a sequence of taggers according to the tagging plan
"""
built_taggers = []
plan_context = plan.context
for tagger_config in plan.taggers:
tagger_id = tagger_config.id
cls = self._get_tagger_cls(tagger_id)
if cls:
try:
new_tagger = cls(plan_context, tagger_config)
logging.warning(f"Tagger with id:{tagger_id} built")
built_taggers.append(new_tagger)
except Exception as e:
logging.error(f"Exception raised tagger {tagger_id}: {e}")
else:
logging.warning(f"Tagger with id:{tagger_id} not built")
return built_taggers
build_taggers method:
- Takes a
TaggingPlan object as input and returns a list of Tagger objects.
- Iterates through the taggers specified in the plan (
plan.taggers).
- For each tagger configuration, it retrieves the corresponding tagger class using
_get_tagger_cls.
- Attempts to instantiate this class with
plan_context and tagger_config.
- Logs a warning upon successful instantiation and adds the tagger to
built_taggers.
- Catches and logs any exceptions that occur during instantiation to handle errors gracefully.
- Returns the list of instantiated taggers.
Private Methods: _get_tagger_cls and _find_tagger_classes
def _get_tagger_cls(self, tagger_id):
"""
Return the registered tagger class that matches tagger_id
"""
return next((cls for cls in self.tagger_classes if cls.TAGGER_ID == tagger_id), None)
def _find_tagger_classes(self):
"""
Find all leaf Tagger classes
"""
def all_subclasses(cls):
return {cls}.union({s for c in cls.__subclasses__() for s in all_subclasses(c)})
res = all_subclasses(Tagger)
# filter subclasses by only retaining leaf subclasses
res = list(filter(lambda cls: not cls.__subclasses__(), res))
return res
-
_get_tagger_cls:
- Takes a
tagger_id and returns the first matching tagger class from the registered tagger classes.
- Uses a generator expression to find the match and returns
None if no match is found.
-
_find_tagger_classes:
- Finds all leaf subclasses of the
Tagger base class.
- Defines a nested function
all_subclasses that recursively finds all subclasses of a given class.
- Uses
all_subclasses to get all subclasses of Tagger.
- Filters this list to retain only the leaf subclasses (i.e., classes with no further subclasses).
- Returns this list.
Summary
- The
TaggingPlanFactory class automates the creation of tagger sequences based on a tagging plan.
- It dynamically loads and registers all available tagger subclasses.
- Provides the
build_taggers method to instantiate a sequence of taggers as defined in a TaggingPlan.
- Uses private methods to find and select the appropriate tagger classes.
This approach maintains flexibility and scalability, allowing new tagger implementations to be added without major changes to the factory's codebase.