| 1 |
#!/usr/bin/python3 |
| 2 |
# |
| 3 |
# Copyright (C) 2024 Apertium |
| 4 |
# |
| 5 |
# This program is free software; you can redistribute it and/or |
| 6 |
# modify it under the terms of the GNU General Public License as |
| 7 |
# published by the Free Software Foundation; either version 2 of the |
| 8 |
# License, or (at your option) any later version. |
| 9 |
# |
| 10 |
# This program is distributed in the hope that it will be useful, but |
| 11 |
# WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
| 13 |
# General Public License for more details. |
| 14 |
# |
| 15 |
# You should have received a copy of the GNU General Public License |
| 16 |
# along with this program; if not, see <https://www.gnu.org/licenses/>. |
| 17 |
# |
| 18 |
|
| 19 |
import argparse |
| 20 |
import sys |
| 21 |
import xml.etree.ElementTree as ET |
| 22 |
|
| 23 |
parser = argparse.ArgumentParser('Filter out language-specific rules from Apertium XML files') |
| 24 |
parser.add_argument('lang', nargs='+', action='store') |
| 25 |
parser.add_argument('infile', action='store') |
| 26 |
parser.add_argument('outfile', action='store', default='-', nargs='?') |
| 27 |
args = parser.parse_args() |
| 28 |
|
| 29 |
Langs = set(args.lang) |
| 30 |
|
| 31 |
SKIP_TAGS = [ |
| 32 |
'with-param', 'param', 'list-item', 'lit', 'lit-tag', 'attr-item', 'def-var' |
| 33 |
] |
| 34 |
|
| 35 |
def process_node(node): |
| 36 |
to_remove = [] |
| 37 |
for ch in node: |
| 38 |
if ch.tag in SKIP_TAGS: |
| 39 |
continue |
| 40 |
if 'v' in ch.attrib: |
| 41 |
node_langs = set(ch.attrib['v'].split()) |
| 42 |
del ch.attrib['v'] |
| 43 |
if Langs <= node_langs: |
| 44 |
process_node(ch) |
| 45 |
else: |
| 46 |
to_remove.append(ch) |
| 47 |
else: |
| 48 |
process_node(ch) |
| 49 |
for ch in to_remove: |
| 50 |
node.remove(ch) |
| 51 |
|
| 52 |
infile = sys.stdin if args.infile == '-' else args.infile |
| 53 |
outfile = sys.stdout.buffer if args.outfile == '-' else args.outfile |
| 54 |
|
| 55 |
parser = ET.XMLParser(target=ET.TreeBuilder(insert_comments=True)) |
| 56 |
tree = ET.parse(infile, parser=parser) |
| 57 |
process_node(tree.getroot()) |
| 58 |
tree.write(outfile, encoding='utf-8') |