diff --git a/apis_ontology/templatetags/parse_comment.py b/apis_ontology/templatetags/parse_comment.py index 375b385..347c241 100644 --- a/apis_ontology/templatetags/parse_comment.py +++ b/apis_ontology/templatetags/parse_comment.py @@ -4,46 +4,57 @@ logger = logging.getLogger(__name__) from django import template +from django.contrib.contenttypes.models import ContentType from apis_ontology.models import ZoteroEntry +from apis_core.apis_metainfo.models import RootObject register = template.Library() @register.filter def parse_comment(value): - if not value: - return "" - print(f"Parsing {value}") - - def replace_zotero_link(match): + def custom_replace(match): if match.group("text"): - # Case: <> + # Handle <> text = match.group("text") zotero_id = match.group("zotero_id") - return f'{text}' + replacement = f'{text}' elif match.group("zotero_id_only"): - # Case: [ID] + # Handle [ZoteroID] zotero_id = match.group("zotero_id_only") try: zotero_obj = ZoteroEntry.objects.filter(zoteroId=zotero_id)[0] - return f'{zotero_obj.shortTitle}' + link_text = ( + zotero_obj.shortTitle if zotero_obj.shortTitle else zotero_id + ) + return f'{link_text}' except Exception as e: - logger.error(e) + logger.error(f"Error finding cached Zotero entry with ID %s", zotero_id) + logger.error(repr(e)) return f'{zotero_id}' + elif match.group("entity_id"): + # Handle (ID: number) + entity_id = match.group("entity_id") + try: + root_obj = RootObject.objects_inheritance.get_subclass(pk=entity_id) + ct = ContentType.objects.get_for_model(root_obj) + return f'{root_obj}' + + except Exception as e: + logger.error("Error finding entity #%s", entity_id) + logger.error(repr(e)) + return f'{entity_id}' + else: + # If no specific group is matched, return the original match + replacement = match.group(0) - def replace_entity_link(match): - entity_id = match.group("entity_id") - return f'{entity_id}' + return replacement - # Combined regex pattern to handle all cases + # Define the regex pattern to capture different groups combined_pattern = r"<<(?P.*?) \[(?P[A-Z0-9]+)\]>>|\[(?P[A-Z0-9]+)\]|\(ID:\s*(?P\d+)\)" - # Apply substitutions using the combined pattern - transformed_value = re.sub( - combined_pattern, - lambda match: replace_zotero_link(match) or replace_entity_link(match), - value, - ) + # Apply substitutions using the combined pattern and custom replacement function + transformed_value = re.sub(combined_pattern, custom_replace, value) return transformed_value