|
| 1 | +import os |
| 2 | +import warnings |
| 3 | +import pandas as pd |
| 4 | +from .cheetah import Cheetah |
| 5 | + |
| 6 | +class CheetahTermFormatter: |
| 7 | + """ |
| 8 | + Loads search terms from a Markdown file and returns them as |
| 9 | + plain strings or dict blocks, with optional category filtering. |
| 10 | + Can also generate a substitutions lookup dict mapping phrases |
| 11 | + to underscored forms and back, if substitutions=True. |
| 12 | + |
| 13 | + New parameters: |
| 14 | + all_categories (bool): if True, ignore `category` and |
| 15 | + `include_general` and include every section. |
| 16 | + """ |
| 17 | + def __init__(self, markdown_file, lower=False, category=None, |
| 18 | + include_general=True, substitutions=False, all_categories=False): |
| 19 | + self.markdown_file = markdown_file |
| 20 | + self.lower = lower |
| 21 | + self.category = category |
| 22 | + self.include_general = include_general |
| 23 | + self.substitutions = substitutions |
| 24 | + self.all_categories = all_categories |
| 25 | + |
| 26 | + self.substitution_forward = {} |
| 27 | + self.substitution_reverse = {} |
| 28 | + |
| 29 | + # parse the markdown into self.terms |
| 30 | + self.terms = self._parse_markdown() |
| 31 | + |
| 32 | + # optionally build lookup table |
| 33 | + if self.substitutions: |
| 34 | + self._build_substitutions_lookup() |
| 35 | + |
| 36 | + |
| 37 | + def _parse_markdown(self): |
| 38 | + terms = [] |
| 39 | + current_term = None |
| 40 | + positives = [] |
| 41 | + negatives = [] |
| 42 | + active_block = False |
| 43 | + current_section = None |
| 44 | + |
| 45 | + try: |
| 46 | + with open(self.markdown_file, 'r', encoding='utf-8') as f: |
| 47 | + lines = f.readlines() |
| 48 | + except FileNotFoundError: |
| 49 | + warnings.warn(f"File '{self.markdown_file}' not found. Returning empty list.") |
| 50 | + return [] |
| 51 | + |
| 52 | + for raw in lines: |
| 53 | + line = raw.strip() |
| 54 | + |
| 55 | + # Section header |
| 56 | + if line.startswith("# Category:"): |
| 57 | + current_section = line.split(":", 1)[1].strip() |
| 58 | + continue |
| 59 | + |
| 60 | + # Decide whether to include this section |
| 61 | + if self.all_categories: |
| 62 | + include_section = True |
| 63 | + elif self.category is None: |
| 64 | + # no filtering → include everything |
| 65 | + include_section = True |
| 66 | + else: |
| 67 | + if current_section is None and self.include_general: |
| 68 | + include_section = True |
| 69 | + else: |
| 70 | + include_section = (current_section == self.category) |
| 71 | + |
| 72 | + # Term header |
| 73 | + if line.startswith("##"): |
| 74 | + # finish previous block |
| 75 | + if current_term is not None and active_block: |
| 76 | + if positives or negatives: |
| 77 | + terms.append({ |
| 78 | + current_term: { |
| 79 | + "positives": positives, |
| 80 | + "negatives": negatives |
| 81 | + } |
| 82 | + }) |
| 83 | + else: |
| 84 | + terms.append(current_term) |
| 85 | + |
| 86 | + # reset for new block |
| 87 | + positives = [] |
| 88 | + negatives = [] |
| 89 | + header = line.lstrip("#").strip() |
| 90 | + if self.lower: |
| 91 | + header = header.lower() |
| 92 | + current_term = header |
| 93 | + active_block = include_section |
| 94 | + |
| 95 | + # collect positives / negatives |
| 96 | + elif active_block and line.lower().startswith("must have:"): |
| 97 | + items = [i.strip() for i in line.split(":", 1)[1].split(",") if i.strip()] |
| 98 | + positives.extend(items) |
| 99 | + elif active_block and line.lower().startswith("exclude with:"): |
| 100 | + items = [i.strip() for i in line.split(":", 1)[1].split(",") if i.strip()] |
| 101 | + negatives.extend(items) |
| 102 | + |
| 103 | + # final block |
| 104 | + if current_term is not None and active_block: |
| 105 | + if positives or negatives: |
| 106 | + terms.append({ |
| 107 | + current_term: { |
| 108 | + "positives": positives, |
| 109 | + "negatives": negatives |
| 110 | + } |
| 111 | + }) |
| 112 | + else: |
| 113 | + terms.append(current_term) |
| 114 | + |
| 115 | + return terms |
| 116 | + |
| 117 | + def _build_substitutions_lookup(self): |
| 118 | + """ |
| 119 | + Build a dict mapping each term to its underscored form and vice versa. |
| 120 | + """ |
| 121 | + for entry in self.terms: |
| 122 | + if isinstance(entry, str): |
| 123 | + term = entry |
| 124 | + underscored = term.replace(" ", "_") |
| 125 | + self.substitution_forward[term] = underscored |
| 126 | + self.substitution_reverse[underscored] = term |
| 127 | + elif isinstance(entry, dict): |
| 128 | + for term in entry.keys(): |
| 129 | + underscored = term.replace(" ", "_") |
| 130 | + self.substitution_forward[term] = underscored |
| 131 | + self.substitution_reverse[underscored] = term |
| 132 | + |
| 133 | + def get_terms(self): |
| 134 | + return self.terms |
| 135 | + |
| 136 | + def get_substitution_maps(self): |
| 137 | + """ |
| 138 | + Return the substitutions lookup dict (empty if substitutions=False). |
| 139 | + """ |
| 140 | + return self.substitution_forward, self.substitution_reverse |
| 141 | + |
| 142 | + |
| 143 | +def convert_txt_to_cheetah_markdown(txt_path, markdown_path): |
| 144 | + import ast |
| 145 | + |
| 146 | + with open(txt_path, 'r', encoding='utf-8') as f: |
| 147 | + lines = [line.strip() for line in f if line.strip()] |
| 148 | + |
| 149 | + markdown_lines = [] |
| 150 | + |
| 151 | + for line in lines: |
| 152 | + if line.startswith("{") and line.endswith("}"): |
| 153 | + try: |
| 154 | + parsed = ast.literal_eval(line) |
| 155 | + for key, value in parsed.items(): |
| 156 | + positives = [v.lstrip('+') for v in value if v.startswith('+')] |
| 157 | + negatives = [v for v in value if not v.startswith('+')] |
| 158 | + markdown_lines.append(f"## {key}") |
| 159 | + if positives: |
| 160 | + markdown_lines.append(f"positives: {', '.join(positives)}") |
| 161 | + if negatives: |
| 162 | + markdown_lines.append(f"negatives: {', '.join(negatives)}") |
| 163 | + except Exception as e: |
| 164 | + print(f"Skipping line due to parse error: {line}\nError: {e}") |
| 165 | + else: |
| 166 | + markdown_lines.append(f"## {line.strip()}") |
| 167 | + |
| 168 | + with open(markdown_path, 'w', encoding='utf-8') as f: |
| 169 | + f.write("\n".join(markdown_lines)) |
| 170 | + |
| 171 | + print(f"Converted markdown saved to: {markdown_path}") |
0 commit comments