-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgenerate_strings.py
More file actions
92 lines (74 loc) · 2.78 KB
/
generate_strings.py
File metadata and controls
92 lines (74 loc) · 2.78 KB
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import yaml
import argparse
from pathlib import Path
# The keys in the YAML file whose string values should be translated.
TRANSLATABLE_KEYS = {"title", "subtitle", "label"}
HEADER = """# -*- coding: utf-8 -*-
#
# DO NOT EDIT THIS FILE MANUALLY.
#
# This file is automatically generated by the 'generate_strings.py' script
# from the content of a YAML file. It is used by gettext to extract
# translatable strings from data files.
#
import gettext
_ = gettext.gettext
# --- Strings from data file ---
"""
def extract_strings_from_data(data):
"""
Recursively finds all strings from the data structure
that have a key present in TRANSLATABLE_KEYS.
"""
strings = set()
if isinstance(data, dict):
for key, value in data.items():
if key in TRANSLATABLE_KEYS and isinstance(value, str):
strings.add(value)
else:
strings.update(extract_strings_from_data(value))
elif isinstance(data, list):
for item in data:
strings.update(extract_strings_from_data(item))
return strings
def main():
"""Main function to generate the translatable strings file."""
parser = argparse.ArgumentParser(
description="Extract translatable strings from a YAML file into a Python file for gettext."
)
parser.add_argument("input_yaml", type=Path, help="Path to the input YAML file.")
parser.add_argument("output_py", type=Path, help="Path for the output Python file.")
args = parser.parse_args()
input_file: Path = args.input_yaml
output_file: Path = args.output_py
if not input_file.is_file():
print(f"Error: Input file not found at {input_file}")
sys.exit(1)
print(f"Reading strings from: {input_file}")
with open(input_file, "r", encoding="utf-8") as f:
try:
data = yaml.safe_load(f)
except yaml.YAMLError as e:
print(f"Error parsing YAML file: {e}")
sys.exit(1)
translatable_strings = extract_strings_from_data(data)
if not translatable_strings:
print("Warning: No translatable strings found.")
# Still create the file so the build process doesn't fail
with open(output_file, "w", encoding="utf-8") as f:
f.write(HEADER)
return
# Sort for deterministic output, which is good for version control
sorted_strings = sorted(list(translatable_strings))
print(f"Writing {len(sorted_strings)} strings to: {output_file}")
with open(output_file, "w", encoding="utf-8") as f:
f.write(HEADER)
for s in sorted_strings:
# Use repr() to correctly handle quotes and special characters
f.write(f"_({repr(s)})\n")
print("Done.")
if __name__ == "__main__":
main()