Skip to content

hsg.commands

heisigtools (parse, enrich, list, stories, stories-import)

hsg.commands.heisigtools

enrich(text, file, max_frame, known_set, known_file, max_known, verbose)

Parses a text and highlights unknown Heisig frames (blue) and non-Heisig characters (red).

If no text is passed as argument fallbacks to stdin then clipboard

Source code in hsg/commands/heisigtools.py
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
@click.command()
@click.argument('text', required=False)
@click.option('-f', '--file', required=False, type=click.File('r'), default=sys.stdin)
@click.option('-m', '--max-frame', type=click.INT, default=-1)
@click.option(
    '--known-set',
    type=click.Choice(['heisig', 'hsk', 'file']),
    default=None,
    help='Known-character source (default: heisig).',
)
@click.option(
    '--known-file',
    type=click.Path(exists=True),
    default=None,
    help='Path to known-characters file (for --known-set file).',
)
@click.option(
    '--max',
    'max_known',
    type=click.INT,
    default=None,
    help='Max frame/level for known-set (overrides --max-frame).',
)
@click.option('-v', '--verbose', required=False, is_flag=True)
def enrich(
    text: str | None,
    file: Any,
    max_frame: int,
    known_set: str | None,
    known_file: str | None,
    max_known: int | None,
    verbose: bool,
) -> None:
    """Parses a text and highlights unknown Heisig frames (blue) and non-Heisig characters (red).

    If no text is passed as argument fallbacks to stdin then clipboard"""
    ks_backend = known_set or 'heisig'
    ks_max = max_known if max_known is not None else max_frame

    if ks_backend == 'file':
        if not known_file:
            raise click.UsageError('--known-set file requires --known-file')
        hsg = create_known_set('file', filepath=known_file)
    else:
        hsg = create_known_set(ks_backend, max=ks_max, frequencies_corpus='subtlexch')

    input_text = get_input(text, file)
    chars = list(input_text.strip())
    statistics = hsg.get_statistics(chars)

    # output data
    for char in chars:
        if not hsg.is_known(char):
            if isinstance(hsg, Heisig) and char in hsg.heisig:
                print(f'[bold blue]{char}[/bold blue]', end='')
            else:
                print(f'[bold red]{char}[/bold red]', end='')
        else:
            print(f'[bold white]{char}[/bold white]', end='')

    # output stats
    if verbose:
        print(f'\r\n\r\nKnown characters: {statistics["known"]}/{statistics["chars"]} ({statistics["known_percent"]}%)')
        print(f'Unknown characters: {statistics["unknown"]}/{statistics["chars"]} ({statistics["unknown_percent"]}%)')
        print(
            f'Known unique characters: {statistics["known_unique"]}'
            f'/{statistics["chars_unique"]}'
            f' ({statistics["known_unique_percent"]}%)'
        )
        print(
            f'Unknown unique characters: {statistics["unknown_unique"]}'
            f'/{statistics["chars_unique"]}'
            f' ({statistics["unknown_unique_percent"]}%)\r\n'
        )

list_frames(min, max, sort, frequencies_corpus, reverse, format, max_results)

Prints Heisig frames data.

Source code in hsg/commands/heisigtools.py
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
@click.command(name='list')
@click.option('--min', type=click.INT, default=0)
@click.option('--max', type=click.INT, default=9999)
@click.option('-s', '--sort', type=click.Choice(['frame', 'frequency']), default='frame')
@click.option(
    '-c',
    '--frequencies-corpus',
    type=click.Choice(['renminwang', 'subtlexch']),
    default='subtlexch',
    help='Frequencies data corpus.',
)
@click.option('-r', '--reverse', required=False, is_flag=True, default=False, help='Reverse sorting order.')
@click.option(
    '-f',
    '--format',
    required=False,
    type=click.Choice(['csv', 'json', 'tabulate']),
    default='tabulate',
    help='Output format (default csv).',
)
@click.option('-m', '--max-results', required=False, type=click.INT, default=-1, help='Show max n results.')
def list_frames(
    min: int,
    max: int,
    sort: str,
    frequencies_corpus: str,
    reverse: bool,
    format: str,
    max_results: int,
) -> None:
    """Prints Heisig frames data."""
    hsg = Heisig(frequencies_corpus)
    frames = [frame for idx, frame in enumerate(hsg.heisig.values()) if idx + 1 >= min and idx + 1 <= max]
    if sort == 'frame' and reverse:
        frames.reverse()
    if sort == 'frequency':
        frames = sorted(frames, key=lambda x: x['frequency'], reverse=reverse)
    if max_results > -1:
        frames = frames[:max_results]
    hsg.output(frames, format)

parse(text, file, max_frame, known_set, known_file, max_known, only_known, only_unknown, unique, format, sort, frequencies_corpus, reverse, fields, verbose)

Parses a text and returns a list of Heisig frames.

If no text is passed as argument fallbacks to stdin then clipboard

Source code in hsg/commands/heisigtools.py
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
@click.command()
@click.argument('text', required=False)
@click.option('-f', '--file', type=click.File('r'), default=sys.stdin)
@click.option('-m', '--max-frame', type=click.INT, default=-1, help='Max Heisig frame known.')
@click.option(
    '--known-set',
    type=click.Choice(['heisig', 'hsk', 'file']),
    default=None,
    help='Known-character source (default: heisig).',
)
@click.option(
    '--known-file',
    type=click.Path(exists=True),
    default=None,
    help='Path to known-characters file (for --known-set file).',
)
@click.option(
    '--max',
    'max_known',
    type=click.INT,
    default=None,
    help='Max frame/level for known-set (overrides --max-frame).',
)
@click.option('-o', '--only-known', required=False, is_flag=True, help='Print only known frames.')
@click.option('-u', '--only-unknown', required=False, is_flag=True, help='Print only unknown frames.')
@click.option('-q', '--unique', required=False, is_flag=True, help='Print every character only once.')
@click.option(
    '-t', '--format', type=click.Choice(['csv', 'json', 'tabulate']), default='csv', help='Output format (default csv).'
)
@click.option(
    '-s',
    '--sort',
    type=click.Choice(['text', 'frame', 'frequency', 'occurrencies']),
    default='text',
    help='Sort characters by original order, heisig frame number or frequency number.',
)
@click.option(
    '-c',
    '--frequencies-corpus',
    type=click.Choice(['renminwang', 'subtlexch']),
    default='subtlexch',
    help='Frequencies data corpus.',
)
@click.option(
    '-r',
    '--reverse',
    required=False,
    is_flag=True,
    default=False,
    help='Reverse order if sorting by frame or frequency.',
)
@click.option(
    '-h',
    '--fields',
    required=False,
    type=click.UNPROCESSED,
    default=['known', 'hanzi', 'frame', 'frequency', 'hsk', 'pinyin', 'keyword', 'occurrencies'],
    callback=validate_fields,
    help='Fields to show.',
)
@click.option('-v', '--verbose', required=False, is_flag=True)
def parse(
    text: str | None,
    file: Any,
    max_frame: int,
    known_set: str | None,
    known_file: str | None,
    max_known: int | None,
    only_known: bool,
    only_unknown: bool,
    unique: bool,
    format: str,
    sort: str,
    frequencies_corpus: str,
    reverse: bool,
    fields: list[str],
    verbose: bool,
) -> None:
    """Parses a text and returns a list of Heisig frames.

    If no text is passed as argument fallbacks to stdin then clipboard"""
    ks_backend = known_set or 'heisig'
    ks_max = max_known if max_known is not None else max_frame

    if ks_backend == 'file':
        if not known_file:
            raise click.UsageError('--known-set file requires --known-file')
        hsg = create_known_set('file', filepath=known_file)
    else:
        hsg = create_known_set(ks_backend, max=ks_max, frequencies_corpus=frequencies_corpus)

    hsk = HSK()
    input_text = get_input(text, file)
    chars = [c for c in input_text.replace('\r', '').replace('\n', '').strip() if not hsg.is_additional_character(c)]
    statistics = hsg.get_statistics(chars)

    # select data to output based on options
    if unique:
        chars = [c for i, c in enumerate(chars) if c not in chars[:i]]  # remove duplicates
    if only_unknown:
        chars = [c for c in chars if not hsg.is_known(c)]
    elif only_known:
        chars = [c for c in chars if hsg.is_known(c)]
    if sort == 'frame' or sort == 'frequency':
        if isinstance(hsg, Heisig):
            chars = sorted(
                chars, key=lambda x: hsg.get_char_info(x)[sort] if x in hsg.heisig else 100000, reverse=reverse
            )
    elif sort == 'occurrencies':
        chars = sorted(chars, key=lambda x: statistics['frequencies'][x]['occurrencies'], reverse=not reverse)

    # prepare data for output
    data: list[list[Any]] = []
    for char in chars:
        occurrencies = (
            f'{statistics["frequencies"][char]["occurrencies"]} ({statistics["frequencies"][char]["percent"]}%)'
        )
        hsk_level = hsk.get_hsk_new_char_level(char) if hsk.get_hsk_new_char_level(char) else ''
        if isinstance(hsg, Heisig) and char in hsg.heisig:
            info = hsg.get_char_info(char)
            item = {
                'known': '' if hsg.is_known(char) else '*',
                'hanzi': info['hanzi'],
                'frame': info['frame'],
                'frequency': info['frequency'],
                'hsk': hsk_level,
                'pinyin': info['pinyin'],
                'keyword': info['keyword'],
                'occurrencies': occurrencies,
            }
        else:
            known_val = 'NA' if isinstance(hsg, Heisig) else ('' if hsg.is_known(char) else '*')
            item = {
                'known': known_val,
                'hanzi': char,
                'frame': '',
                'frequency': '',
                'hsk': hsk_level,
                'pinyin': ' '.join(pinyin(char, style=Style.TONE3, heteronym=True)[0]),
                'keyword': '',
                'occurrencies': occurrencies,
            }
        item_list = [item[field] for field in fields]
        data.append(item_list)

    # output data
    writer_cls = WRITERS[format]
    writer_cls(fields).writerows(data)  # type: ignore[call-arg]

    # output stats
    if verbose:
        print(f'\r\nKnown characters: {statistics["known"]}/{statistics["chars"]} ({statistics["known_percent"]}%)')
        print(f'Unknown characters: {statistics["unknown"]}/{statistics["chars"]} ({statistics["unknown_percent"]}%)')
        print(
            f'Known unique characters: {statistics["known_unique"]}'
            f'/{statistics["chars_unique"]}'
            f' ({statistics["known_unique_percent"]}%)'
        )
        print(
            f'Unknown unique characters: {statistics["unknown_unique"]}'
            f'/{statistics["chars_unique"]}'
            f' ({statistics["unknown_unique_percent"]}%)\r\n'
        )

stories(text, file, stories_file)

Parses a text and returns Heisig stories from a JSON file.

Source code in hsg/commands/heisigtools.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
@click.command()
@click.argument('text', required=False)
@click.option('-f', '--file', type=click.File('r'), default=sys.stdin)
@click.option(
    '--stories-file',
    type=click.Path(exists=True),
    default=None,
    help='Path to stories JSON file (use `hsg stories-import` to create one).',
)
def stories(text: str | None, file: Any, stories_file: str | None) -> None:
    """Parses a text and returns Heisig stories from a JSON file."""
    from hsg.classes.stories import StoryStore

    if not stories_file:
        raise click.UsageError('--stories-file is required (use `hsg stories-import` to create one)')

    store = StoryStore(stories_file)
    input_text = get_input(text, file)
    chars = list(input_text.replace('\r', '').replace('\n', '').strip())
    for idx, char in enumerate(chars):
        data = store.get_story(char)
        if not data:
            print(f'{char}: NO STORY')
        else:
            print(f'{char} ({data.get("keyword", "")} | {data.get("keyword_ita", "")}): {data.get("story", "")}')
        if idx < len(chars) - 1:
            print()

stories_import(text, file, out, deck)

Imports stories from AnkiConnect into a JSON file.

Source code in hsg/commands/heisigtools.py
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
@click.command(name='stories-import')
@click.argument('text', required=False)
@click.option('-f', '--file', type=click.File('r'), default=sys.stdin)
@click.option('--out', type=click.Path(), default='stories.json', help='Output JSON file (default: stories.json).')
@click.option('--deck', default='Cinese::Heisig', help='Anki deck name.')
def stories_import(text: str | None, file: Any, out: str, deck: str) -> None:
    """Imports stories from AnkiConnect into a JSON file."""
    from hsg.classes.stories import _strip_tags

    def find_notes(hanzi: str) -> list[int]:
        url = 'http://localhost:8765'
        payload = {
            'action': 'findNotes',
            'version': 6,
            'params': {
                'query': f'deck:{deck} Hanzi:{hanzi}',
            },
        }
        try:
            response = requests.request('POST', url, json=payload, timeout=5)
        except requests.RequestException as e:
            logger.warning('AnkiConnect not available: %s', e)
            return []
        ids = cast(list[int], json.loads(response.text)['result'])
        return ids

    def get_note(note_id: int) -> dict[str, Any] | None:
        url = 'http://localhost:8765'
        payload = {
            'action': 'notesInfo',
            'version': 6,
            'params': {
                'notes': [note_id],
            },
        }
        try:
            response = requests.request('POST', url, json=payload, timeout=5)
        except requests.RequestException as e:
            logger.warning('AnkiConnect not available: %s', e)
            return None
        notes = cast(list[dict[str, Any]], json.loads(response.text)['result'])
        if len(notes) > 0:
            return notes[0]
        return None

    def get_data(hanzi: str) -> dict[str, str] | None:
        ids = find_notes(hanzi)
        if ids:
            note = get_note(ids[0])
            if note:
                return {
                    'keyword': note['fields']['Keyword']['value'],
                    'keyword_ita': note['fields']['KeywordIta']['value'],
                    'primitive': note['fields']['PrimitiveMeaning']['value'],
                    'primitive_ita': note['fields']['PrimitiveMeaningIta']['value'],
                    'story': _strip_tags(note['fields']['Story']['value']),
                }
        return None

    input_text = get_input(text, file)
    chars = list(input_text.replace('\r', '').replace('\n', '').strip())
    stories_data: dict[str, dict[str, str]] = {}
    for char in chars:
        data = get_data(char)
        if data:
            stories_data[char] = data
            print(f'{char} ({data["keyword"]}): imported')
        else:
            print(f'{char}: NO HEISIG')

    with open(out, 'w') as f:
        json.dump(stories_data, f, ensure_ascii=False, indent=2)
    print(f'\nWrote {len(stories_data)} stories to {out}')

heisigtatoeba (sentences, random)

hsg.commands.heisigtatoeba

print_sentences(sentences, format)

Print sentence results in the specified format (csv, json, tabulate).

Enriches each sentence with pinyin before printing.

Source code in hsg/commands/heisigtatoeba.py
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
def print_sentences(sentences: list[Sentence], format: str) -> None:
    """Print sentence results in the specified format (csv, json, tabulate).

    Enriches each sentence with pinyin before printing.
    """
    for s in sentences:
        s['pinyin'] = ' '.join([p[0] for p in pinyin(s['hanzi'])])
    if format == 'csv':
        writer = csv.writer(sys.stdout, delimiter='\t')
        for s in sentences:
            writer.writerow([s['hanzi'], s['pinyin'], ' / '.join(s['translations'])])
    elif format == 'json':
        print(json.dumps(sentences))
    elif format == 'tabulate':
        for s in sentences:
            s['translations'] = ' / '.join(s['translations'])
        print(tabulate(sentences, headers='keys', tablefmt='github'))

random_sentences(max_frame, all_characters, sentences_number, min_length, reverse, format, known_set, known_file, max_known)

Returns random sentences from the Tatoeba corpus with the specified keyword

Source code in hsg/commands/heisigtatoeba.py
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
@click.command(name='random')
@click.option('-m', '--max-frame', type=click.INT, default=-1, help='Max Heisig frame known.')
@click.option(
    '-a', '--all-characters', required=False, is_flag=True, default=False, help='Allow all non-Heisig characters.'
)
@click.option('-n', '--sentences-number', type=click.INT, default=10, help='Return n sentences (default 10).')
@click.option(
    '-l', '--min-length', type=click.INT, default=10, help='Return only sentences of length l or above (default 10).'
)
@click.option(
    '-r', '--reverse', required=False, is_flag=True, default=False, help='Return longer sentences first (default FALSE)'
)
@click.option(
    '-f', '--format', type=click.Choice(['csv', 'json', 'tabulate']), default='csv', help='Output format (default csv).'
)
@click.option(
    '--known-set',
    type=click.Choice(['heisig', 'hsk', 'file']),
    default=None,
    help='Known-character source (default: heisig).',
)
@click.option(
    '--known-file',
    type=click.Path(exists=True),
    default=None,
    help='Path to known-characters file (for --known-set file).',
)
@click.option(
    '--max',
    'max_known',
    type=click.INT,
    default=None,
    help='Max frame/level for known-set (overrides --max-frame).',
)
def random_sentences(
    max_frame: int,
    all_characters: bool,
    sentences_number: int,
    min_length: int,
    reverse: bool,
    format: str,
    known_set: str | None,
    known_file: str | None,
    max_known: int | None,
) -> None:
    """Returns random sentences from the Tatoeba corpus with the specified keyword"""
    known_chars = _resolve_known_chars(all_characters, known_set, known_file, max_known, max_frame)
    corpus = TatoebaCorpus(TATOEBA_CSV)
    found = corpus.find_random_sentences(
        sentences_number, min_length=min_length, known_chars=known_chars, reverse=reverse
    )
    print_sentences(found, format)

sentences(keyword, max_frame, all_characters, max_sentences, reverse, format, known_set, known_file, max_known)

Returns all sentences from the Tatoeba corpus with the specified keyword

Source code in hsg/commands/heisigtatoeba.py
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
@click.command()
@click.argument('keyword')
@click.option('-m', '--max-frame', type=click.INT, default=-1, help='Max Heisig frame known. (default MAX)')
@click.option(
    '-a', '--all-characters', required=False, is_flag=True, default=False, help='Allow all non-Heisig characters.'
)
@click.option('-n', '--max-sentences', type=click.INT, default=10000, help='Max sentences to return (default ALL)')
@click.option(
    '-r', '--reverse', required=False, is_flag=True, default=False, help='Return longer sentences first (default FALSE)'
)
@click.option(
    '-f', '--format', type=click.Choice(['csv', 'json', 'tabulate']), default='csv', help='Output format (default csv).'
)
@click.option(
    '--known-set',
    type=click.Choice(['heisig', 'hsk', 'file']),
    default=None,
    help='Known-character source (default: heisig).',
)
@click.option(
    '--known-file',
    type=click.Path(exists=True),
    default=None,
    help='Path to known-characters file (for --known-set file).',
)
@click.option(
    '--max',
    'max_known',
    type=click.INT,
    default=None,
    help='Max frame/level for known-set (overrides --max-frame).',
)
def sentences(
    keyword: str,
    max_frame: int,
    all_characters: bool,
    max_sentences: int,
    reverse: bool,
    format: str,
    known_set: str | None,
    known_file: str | None,
    max_known: int | None,
) -> None:
    """Returns all sentences from the Tatoeba corpus with the specified keyword"""
    known_chars = _resolve_known_chars(all_characters, known_set, known_file, max_known, max_frame)
    corpus = TatoebaCorpus(TATOEBA_CSV)
    found = corpus.find_sentences(keyword, known_chars=known_chars, max_sentences=max_sentences, reverse=reverse)
    print_sentences(found, format)

ccedictsearch (lookup)

hsg.commands.ccedictsearch

search(query, exact, show_traditional, format, sort, frequencies_corpus, reverse, max_hsk, max_results, all_results)

Searches the CC-CEDICT dictionary for a query string.

Source code in hsg/commands/ccedictsearch.py
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
@click.command(name='lookup')
@click.argument('query')
@click.option('-e', '--exact', required=False, is_flag=True, default=False, help='Search exact expression.')
@click.option(
    '-t', '--show-traditional', required=False, is_flag=True, default=False, help='Show traditional characters.'
)
@click.option(
    '-f',
    '--format',
    required=False,
    type=click.Choice(['csv', 'json', 'tabulate']),
    default='tabulate',
    help='Output format (default csv).',
)
@click.option(
    '-s',
    '--sort',
    type=click.Choice(['hsk', 'frequency']),
    default='frequency',
    help='Sort results by hsk or frequency.',
)
@click.option(
    '-c',
    '--frequencies-corpus',
    type=click.Choice(['renminwang', 'subtlexch']),
    default='subtlexch',
    help='Frequencies data corpus.',
)
@click.option(
    '-r', '--reverse', required=False, is_flag=True, default=False, help='Reverse order if sorting by hsk or frequency.'
)
@click.option(
    '-h',
    '--max-hsk',
    required=False,
    type=click.Choice(['1', '2', '3', '4', '5', '6', '7', '7-9']),
    default=None,
    help='Show only words with specified hsk level or above.',
)
@click.option(
    '-m', '--max-results', required=False, type=click.INT, default=15, help='Show max n results (default 15).'
)
@click.option('-a', '--all-results', required=False, is_flag=True, default=False, help='Show all results.')
def search(
    query: str,
    exact: bool,
    show_traditional: bool,
    format: str,
    sort: str,
    frequencies_corpus: str,
    reverse: bool,
    max_hsk: str,
    max_results: int,
    all_results: bool,
) -> None:
    """Searches the CC-CEDICT dictionary for a query string."""
    ce: Ccedict = Ccedict(CCEDICT_CSV, frequencies_corpus)
    ce.search(query, exact, show_traditional, format, sort, reverse, max_hsk, max_results, all_results)

frequencytools (freq)

hsg.commands.frequencytools

search(text, file, skip_clipboard, max_results, skip_known, only_known, known_set, known_file, max_known, type, min_length, sort, reverse, frequencies_corpus, format)

Returns most frequent characters or words, optionally filtered to a known-set or input text.

Source code in hsg/commands/frequencytools.py
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
@click.command(name='freq')
@click.argument('text', required=False)
@click.option('-f', '--file', type=click.File('r'), default=sys.stdin)
@click.option('-k', '--skip-clipboard', required=False, is_flag=True, help='Skip clipboard content.')
@click.option(
    '-m', '--max-results', required=False, type=click.INT, default=-1, help='Show max n results (default all).'
)
@click.option('--skip-known', is_flag=True, default=False, help='Skip known characters.')
@click.option('--only-known', is_flag=True, default=False, help='Show only known characters.')
@click.option(
    '--known-set',
    type=click.Choice(['heisig', 'hsk', 'file']),
    default='heisig',
    help='Known-character source (default: heisig).',
)
@click.option(
    '--known-file',
    type=click.Path(exists=True),
    default=None,
    help='Path to known-characters file (for --known-set file).',
)
@click.option(
    '--max',
    'max_known',
    type=click.INT,
    default=-1,
    help='Max frame/level for known-set.',
)
@click.option(
    '-p',
    '--type',
    type=click.Choice(['chars', 'words']),
    default='chars',
    help='Return character or word frequencies (default chars).',
)
@click.option('-l', '--min_length', type=click.INT, default=1, help='Minimum word length.')
@click.option(
    '-s',
    '--sort',
    type=click.Choice(['count', 'count_million', 'count_log', 'cd', 'cd_percent', 'cd_log', 'rank', 'count_x_cd']),
    default='rank',
    help='Sort results specified field.',
)
@click.option(
    '-r', '--reverse', required=False, is_flag=True, default=False, help='Reverse order if sorting by hsk or frequency.'
)
@click.option(
    '-c',
    '--frequencies-corpus',
    type=click.Choice(['renminwang', 'subtlexch']),
    default='subtlexch',
    help='Frequencies data corpus.',
)
@click.option(
    '-t',
    '--format',
    required=False,
    type=click.Choice(['csv', 'json', 'tabulate']),
    default='tabulate',
    help='Output format (default tabulate).',
)
def search(
    text: str | None,
    file: Any,
    skip_clipboard: bool,
    max_results: int,
    skip_known: bool,
    only_known: bool,
    known_set: str,
    known_file: str | None,
    max_known: int,
    type: str,
    min_length: int,
    sort: str,
    reverse: bool,
    frequencies_corpus: str,
    format: str,
) -> None:
    """Returns most frequent characters or words, optionally filtered to a known-set or input text."""
    fq: Frequency = create_frequency(frequencies_corpus)

    if skip_known or only_known:
        if known_set == 'file':
            if not known_file:
                raise click.UsageError('--known-set file requires --known-file')
            ks = create_known_set('file', filepath=known_file)
        else:
            ks = create_known_set(known_set, max=max_known)
        known_chars: set[str] | None = set(ks.get_known_characters())
    else:
        known_chars = None

    skip_chars = known_chars if skip_known else None
    only_chars = known_chars if only_known else None

    lemmas = fq.get_most_frequent_lemmas(
        type,
        max_results,
        skip_known=skip_chars,
        only_known=only_chars,
        min_length=min_length,
        sort=sort,
        reverse=reverse,
    )

    # filter results by text input
    input_text = get_input(text, file)
    if input_text and not skip_clipboard:
        chars = list(input_text.replace('\r', '').replace('\n', '').strip())
        lemmas = [lemma for lemma in lemmas if lemma['lemma'] in chars]

    if lemmas:
        if format == 'csv':
            writer: csv.DictWriter[str] = csv.DictWriter(
                sys.stdout, fieldnames=list(lemmas[0].keys()), delimiter='\t', extrasaction='ignore'
            )
            writer.writeheader()
            writer.writerows(lemmas)
        elif format == 'json':
            print(json.dumps(lemmas))
        elif format == 'tabulate':
            print(tabulate(lemmas, headers='keys', tablefmt='github'))