summaryrefslogtreecommitdiff
path: root/biblio/bibtex/contrib/ieejtran/mixej.py
blob: 4220f518553c3393e7d5c18f3e2e1f1bab2249c2 (plain)
1
2
3
4
5
6
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
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
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
289
290
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
365
366
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
import sys
import platform
import json
import logging


SPLIT_KEY = '/ej/'
ITEM_SEP = '\\hspace{0mm}\\\\'

FILE_VERSION = '0.19'
FILE_DATE = '2023/01/26'
FILE_AUTHOR = 'Haruki Ejiri'
FILE_URL = 'https://github.com/ehki/jIEEEtran/'

logger = logging.getLogger(__name__)


def check_load_file(fn, asjson=False):
    """load file if exist else return -1.

    This code load text and json file if exist.
    If the file not exist, return -1

    Parameters
    ----------
    fn : str
        Path to the file to load
    asjson : bool
        whether the fn should be loaded using json or normal text file

    Returns
    -------
    int
        0 if success
    """

    logger.info('-- Checking file %s, ' % fn)
    try:
        with open(fn, 'r', encoding='utf-8') as f:
            logger.info('exist, load.')
            if asjson:
                return json.load(f)
            else:
                return f.read()
    except FileNotFoundError:
        logger.info('not found.')
        return -1


def save_pairs(fn, pairs):
    """save pairs to the JSON format file with the extensions of ".ejp".

    This code save the pairs to the file in JSON format.

    Parameters
    ----------
    fn : str
        Path to the file to write pairs
    pairs : list of two strings
        for example: [["en1",  "jp1"], ["en2", "jp2"], ["en3", "jp3"]]

    Returns
    -------
    int
        0 if success
    """

    logger.info('-- Saving found pairs to %s, ' % fn)
    with open(fn, 'w', encoding='utf-8') as f:
        json.dump(pairs, f)
    logger.info('done.')
    return 0


def divide_aux(fn, pairs):
    """divide comined citation(s) and bibcite(s) in aux file.

    This code divide the combined key(s) in aux file.
    For example, the following citation(s) and bibcite(s) in aux file
    --
    \\citation{englishTest7/ej/japaneseTest7}

    \\bibcite{englishTest7/ej/japaneseTest7}{16}
    --
    will be converted to the following two divided citations and bibitems.
    --
    \\citation{englishTest7,japaneseTest7}

    \\bibcite{englishTest7,japaneseTest7}{16}
    --

    Parameters
    ----------
    fn : str
        Path to the aux file to proceess
    pairs : list of two strings
        for example: [["en1",  "jp1"], ["en2", "jp2"], ["en3", "jp3"]]

    Returns
    -------
    int
        -1 if the file to process not found, 0 if success
    """

    aux = check_load_file(fn)
    if aux == -1:  # file not found
        return -1  # failed
    for k1, k2 in pairs:
        combi = SPLIT_KEY.join([k1, k2])
        # for example, combi is "engkey/ej/jpkey", wehere SPLIT_KEY is "/ej/"
        logger.info('-- Dividing %s into %s and %s' % (combi, k1, k2))
        aux = aux.replace('%s' % combi,
                          '%s,%s' % (k1, k2))
    with open(fn, 'w', encoding='utf-8') as f:
        f.write(aux)
    return 0


def divide_bbl(fn, pairs):
    """divide comined bibitem(s) in bbl file.

    This code divide the combined key(s) in bbl file.
    For example, the following combined bibitem(s) in bbl file
    --
    \\bibitem{englishTest5/ej/japaneseTest5}
    I.~Yamada, J.~Sato, S.~Tanaka, S.~Suzuki: ``Article title'', Japanese
    Transaction, Vol.10, No.5, pp.45--60 (2016-3)\\hspace{0mm}\\\\
    山田~一郎・佐藤~次郎・田中~三郎・鈴木~四郎:「文献タイトル」,
    日本語学会,Vol.10,No.5,pp.45--60(2016-3)
    --
    will be converted to the following two divided bibitems.
    --
    \\bibitem{englishTest5}
    I.~Yamada, J.~Sato, S.~Tanaka, S.~Suzuki: ``Article title'', Japanese
    Transaction, Vol.10, No.5, pp.45--60 (2016-3)

    \\bibitem{japaneseTest5}
    山田~一郎・佐藤~次郎・田中~三郎・鈴木~四郎:「文献タイトル」,
    日本語学会,Vol.10,No.5,pp.45--60(2016-3)
    --

    Parameters
    ----------
    fn : str
        Path to the bbl file to proceess
    pairs : list of two strings
        for example: [["en1",  "jp1"], ["en2", "jp2"], ["en3", "jp3"]]

    Returns
    -------
    int
        -1 if the file to process not found, 0 if success
    """

    bbl = check_load_file(fn)
    if bbl == -1:  # file not found
        return -1  # failed
    for k1, k2 in pairs:
        combi = SPLIT_KEY.join([k1, k2])
        # for example, combi is "engkey/ej/jpkey", wehere SPLIT_KEY is "/ej/"
        logger.info('-- Dividing %s into %s and %s' % (combi, k1, k2))
        bbl = bbl.replace(ITEM_SEP, '\n\n\\bibitem{%s}' % k2)
        bbl = bbl.replace('\\bibitem{%s}' % combi, '\\bibitem{%s}' % k1)
    logger.info('-- Saving divided bbl to %s, ' % fn)
    with open(fn, 'w', encoding='utf-8') as f:
        f.write(bbl)
    logger.info('done.')
    return 0  # successfully finished


def find_pairs(fn, aux):
    """find english/japanese pair from string in aux.

    This code find and store english/japanese pair.
    Reading each line in aux strings, the engligh and japanese keys
    are extracted if SPLIT_KEY is in the line.
    If the combined english/japanese keys in the aux file,
    the pairs are stored to the external JSON file

    Parameters
    ----------
    fn : str
        Path to the aux file to proceess
    aux : strings in aux file
        loaded string

    Returns
    -------
    int
        0 if no combined keys found
        num-of-pairs if successfully processed
    """

    pairs = []
    logger.info('-- ')
    for line in aux.split('\n'):
        if SPLIT_KEY not in line or '\\citation' not in line:
            continue
        # the line contains \citation and /ej/
        for ln in line.replace('\\citation{', '').replace('}', '').split(','):
            # convert '\citation{hoge1/ej/hoge2}' to 'hoge1/ej/hoge2'
            if len(ln.split(SPLIT_KEY)) == 2:
                pairs.append(ln.split(SPLIT_KEY))
                # store as ['hoge1', 'hoge2'] pairs
                logger.info('%s' % str(ln.split(SPLIT_KEY)))
    if len(pairs) == 0:
        logger.info('No combined keys found.')
        ret = 0
    if len(pairs) > 0:
        logger.info(' %d combined keys found.' % len(pairs))
        ret = pairs
        save_pairs(fn, pairs)
    return ret


def combine_aux(fn, pairs):
    """combine divided citation(s) and bibcite(s) in aux file.

    This code combine the divided key(s) in aux file.
    For example, the following two divided citation(s) and bibcite(s)
    in aux file
    --
    \\citation{englishTest7,japaneseTest7}

    \\bibcite{englishTest7,japaneseTest7}{16}
    --
    will be converted to the following combined citations and bibitems.
    --
    \\citation{englishTest7/ej/japaneseTest7}

    \\bibcite{englishTest7/ej/japaneseTest7}{16}
    --

    Parameters
    ----------
    fn : str
        Path to the aux file to proceess
    pairs : list of two strings
        for example: [["en1",  "jp1"], ["en2", "jp2"], ["en3", "jp3"]]

    Returns
    -------
    int
        -1 if the file to process not found, 0 if success
    """

    aux = check_load_file(fn)
    if aux == -1:  # file not found
        return -1  # failed
    for k1, k2 in pairs:
        combi = SPLIT_KEY.join([k1, k2])
        # for example, combi is "engkey/ej/jpkey", wehere SPLIT_KEY is "/ej/"
        logger.info('-- Combining %s and %s to %s' % (k1, k2, combi))
        aux = aux.replace('%s,%s' % (k1, k2), '%s' % combi)
    logger.info('-- Saving combined aux to %s, ' % fn)
    with open(fn, 'w', encoding='utf-8') as f:
        f.write(aux)
    logger.info('done.')


def combine_bbl(fn, pairs):
    """combine divided bibitem(s) in bbl file.

    This code divide the combined key(s) in bbl file.
    For example, the following two divided bibitem(s) in bbl file
    --
    \\bibitem{englishTest5}
    I.~Yamada, J.~Sato, S.~Tanaka, S.~Suzuki: ``Article title'', Japanese
    Transaction, Vol.10, No.5, pp.45--60 (2016-3)

    \\bibitem{japaneseTest5}
    山田~一郎・佐藤~次郎・田中~三郎・鈴木~四郎:「文献タイトル」,
    日本語学会,Vol.10,No.5,pp.45--60(2016-3)
    --
    will be converted to the following combined citations and bibitems.
    --
    \\bibitem{englishTest5/ej/japaneseTest5}
    I.~Yamada, J.~Sato, S.~Tanaka, S.~Suzuki: ``Article title'', Japanese
    Transaction, Vol.10, No.5, pp.45--60 (2016-3)\\hspace{0mm}\\\\
    山田~一郎・佐藤~次郎・田中~三郎・鈴木~四郎:「文献タイトル」,
    日本語学会,Vol.10,No.5,pp.45--60(2016-3)
    --

    Parameters
    ----------
    fn : str
        Path to the aux file to proceess
    pairs : list of two strings
        for example: [["en1",  "jp1"], ["en2", "jp2"], ["en3", "jp3"]]

    Returns
    -------
    int
        -1 if the file to process not found, 0 if success
    """

    bbl = check_load_file(fn)
    if bbl == -1:  # file not found
        return -1  # failed
    for k1, k2 in pairs:
        combi = SPLIT_KEY.join([k1, k2])
        # for example, combi is "engkey/ej/jpkey", wehere SPLIT_KEY is "/ej/"
        logger.info('-- Combining %s and %s to %s' % (k1, k2, combi))
        bbl = bbl.replace('\n\n\\bibitem{%s}' % k2, ITEM_SEP)
        bbl = bbl.replace('\\bibitem{%s}' % k1,
                          '\\bibitem{%s}' % combi)
    logger.info('-- Saving combined bbl to %s, ' % fn)
    with open(fn, 'w', encoding='utf-8') as f:
        f.write(bbl)
    logger.info('done.')


def divide_ej_key(bn):
    """divide combined english and japanese bibiteems in bbl and aux file.

    This code divide the combined key(s) in aux and bbl file.
    For example, the following combined bibitem(s) in bbl file
    --
    \\bibitem{englishTest5/ej/japaneseTest5}
    I.~Yamada, J.~Sato, S.~Tanaka, S.~Suzuki: ``Article title'', Japanese
    Transaction, Vol.10, No.5, pp.45--60 (2016-3)\\hspace{0mm}\\\\
    山田~一郎・佐藤~次郎・田中~三郎・鈴木~四郎:「文献タイトル」,
    日本語学会,Vol.10,No.5,pp.45--60(2016-3)
    --
    will be converted to the following two divided bibitems.
    --
    \\bibitem{englishTest5}
    I.~Yamada, J.~Sato, S.~Tanaka, S.~Suzuki: ``Article title'', Japanese
    Transaction, Vol.10, No.5, pp.45--60 (2016-3)

    \\bibitem{japaneseTest5}
    山田~一郎・佐藤~次郎・田中~三郎・鈴木~四郎:「文献タイトル」,
    日本語学会,Vol.10,No.5,pp.45--60(2016-3)
    --
    The following two combined citation(s) and bibcite(s) in aux file
    --
    \\citation{englishTest7/ej/japaneseTest7}

    \\bibcite{englishTest7/ej/japaneseTest7}{16}
    --
    will also be converted to the following combined citations and bibitems.
    --
    \\citation{englishTest7}
    \\citation{japaneseTest7}

    \\bibcite{englishTest7}{1}
    \\bibcite{japaneseTest7}{16}
    --
    The first process during LaTeX compile, there would no bbl file.
    If the bbl file not exist, the dividing process would be skipped.
    A list of english/japanese pairs will be extracted from aux file,
    and if will be saved in the JSON file with
    ".ejp" (english-japanese-pair) extension

    Parameters
    ----------
    bn : str
        Target file to process without extension.
        if your target tex file is '/DIRNAME/main.tex'
        the bn would be '/DIRNAME/main'

    Returns
    -------
    int
        -1 if the file to process not found
        0 if no combined keys found
        num-of-pairs if successfully processed
    """

    logger.info('--')
    logger.info('-- Dividing combinecd keys.')
    aux = check_load_file(bn + '.aux')
    if aux == -1:  # aux file not found
        return -1  # abort
    logger.info('-- Search combined keys from %s.aux.' % bn)
    pairs = find_pairs(bn + '.ejp', aux)
    if pairs == 0:  # no combined keys
        return 0  # probably already divided
    divide_aux(bn + '.aux', pairs)
    divide_bbl(bn + '.bbl', pairs)
    return len(pairs)


def combine_ej_key(bn):
    """combine english and japanese bibiteems in bbl and aux file.

    This code combine the divided key(s) in aux and bbl file.
    For example, the following divided bibitem(s) in bbl file
    --
    \\bibitem{englishTest5}
    I.~Yamada, J.~Sato, S.~Tanaka, S.~Suzuki: ``Article title'', Japanese
    Transaction, Vol.10, No.5, pp.45--60 (2016-3)

    \\bibitem{japaneseTest5}
    山田~一郎・佐藤~次郎・田中~三郎・鈴木~四郎:「文献タイトル」,
    日本語学会,Vol.10,No.5,pp.45--60(2016-3)
    --
    will be converted to the following two divided bibitems.
    --
    \\bibitem{englishTest5/ej/japaneseTest5}
    I.~Yamada, J.~Sato, S.~Tanaka, S.~Suzuki: ``Article title'', Japanese
    Transaction, Vol.10, No.5, pp.45--60 (2016-3)\\hspace{0mm}\\\\
    山田~一郎・佐藤~次郎・田中~三郎・鈴木~四郎:「文献タイトル」,
    日本語学会,Vol.10,No.5,pp.45--60(2016-3)
    --
    The following two divided citation(s) and bibcite(s) in aux file
    --
    \\citation{englishTest7}
    \\citation{japaneseTest7}

    \\bibcite{englishTest7}{1}
    \\bibcite{japaneseTest7}{16}
    --
    will also be converted to the following combined citations and bibitems.
    --
    \\citation{englishTest7/ej/japaneseTest7}

    \\bibcite{englishTest7/ej/japaneseTest7}{16}
    --

    Parameters
    ----------
    bn : str
        Target file to process without extension.
        if your target tex file is '/DIRNAME/main.tex'
        the bn would be '/DIRNAME/main'

    Returns
    -------
    int
        -1 if the file to process not found
        0 if no combined keys found
        num-of-pairs if successfully processed
    """

    logger.info('--')
    logger.info('-- Combining divided keys.')
    pairs = check_load_file(bn + '.ejp', asjson=True)
    if pairs == -1:  # file not found
        return -1
    if len(pairs) == 0:  # no combined keys
        return 0
    combine_aux(bn + '.aux', pairs)
    combine_bbl(bn + '.bbl', pairs)
    return len(pairs)


if __name__ == '__main__':

    logger = logging.getLogger()
    logger.setLevel(logging.INFO)

    sh = logging.StreamHandler()
    logger.addHandler(sh)

    logger.info(
        'This is python version %s ' % platform.python_version())
    logger.info(
        'mixje.py version %s (%s) by %s.' %
        (FILE_VERSION, FILE_DATE, FILE_AUTHOR)
    )
    logger.info('See web site: %s' % FILE_URL)
    try:
        fname = sys.argv[1]
        logger.info('Target: %s' % fname)
    except IndexError:
        logger.info('Fatal error: You must assign target.')
        sys.exit(0)

    sk = divide_ej_key(fname)
    if sk > 0:  # combined keys existed
        logger.info('-- Fin, %d keys were divided.' % sk)
        sys.exit(0)
    elif sk < 0:  # Abort
        sys.exit(0)

    ck = combine_ej_key(fname)
    if ck != 0:
        # print('-- %d divided citation keys were successfully combined' % ck)
        logger.info('-- Fin, %d keys were combined.' % ck)
        sys.exit(0)
    with open(sys.argv[1] + '.ejp', 'w', encoding='utf-8') as f:
        json.dump([], f)
    logger.info(
        '-- No cmobined nor divided citation key in the aux file')
    sys.exit(0)