Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate_from_xml.py
More file actions
Latest commit
304 lines (246 loc) · 11.4 KB
/
Copy pathgenerate_from_xml.py
File metadata and controls
304 lines (246 loc) · 11.4 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
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
#!/usr/bin/env python3
"""
generate_from_xml.py
Directly parses Courseplay FS25 XML configuration and translation files,
crops DDS textures to PNG (using an in-memory DDS cache for performance while
guaranteeing update safety), and generates multilingual Markdown documentation for MkDocs.
"""
importre
importsys
importshutil
importsubprocess
importargparse
importlogging
importxml.etree.ElementTreeasET
logging.basicConfig(level=logging.INFO, format='%(message)s')
frompathlibimportPath
fromdataclassesimportdataclass
fromtypingimportOptional
fromPILimportImageasPIL_Image
CURRENT_DIR: Path=Path.cwd()
GAME_REPO_DIR: Path=CURRENT_DIR/"game_repo"
CONFIG_FILE: Path=GAME_REPO_DIR/"config"/"HelpMenu.xml"
TRANSLATIONS_DIR: Path=GAME_REPO_DIR/"translations"
OUTPUT_DIR: Path=CURRENT_DIR/"docs"
IMAGES_DIR: Path=OUTPUT_DIR/"assets"/"images"
FS25_TO_MKDOCS_LOCALE_MAP: dict[str, str] = {
"br": "pt-BR",
"cs": "zh",
"ct": "zh-TW",
"cz": "cs",
"ea": "es-BR",
"fc": "fr-CA",
"jp": "ja",
"kr": "ko",
"no": "nb",
}
@dataclass
classHelpParagraph:
raw_title: str
raw_text: str
image_filename: Optional[str] =None
@dataclass
classHelpPage:
raw_title: str
paragraphs: list[HelpParagraph]
defsetup_game_repo(force_update: bool=False) ->None:
"""Clones or updates the Courseplay_FS25 repository using shallow sparse-checkout."""
ifnotGAME_REPO_DIR.exists() orforce_update:
logging.info("Setting up shallow sparse-checkout of Courseplay FS25...")
ifGAME_REPO_DIR.exists():
shutil.rmtree(GAME_REPO_DIR)
GAME_REPO_DIR.mkdir(parents=True, exist_ok=True)
# Sequential execution without shell=True guarantees reliability on Windows, Linux and CI
try:
subprocess.run(
["git", "clone", "--filter=blob:none", "--no-checkout", "--depth", "1",
"https://github.com/Courseplay/Courseplay_FS25.git", str(GAME_REPO_DIR)],
check=True
)
subprocess.run(
["git", "-C", str(GAME_REPO_DIR), "sparse-checkout", "set",
"config/HelpMenu.xml", "translations", "img"],
check=True
)
subprocess.run(
["git", "-C", str(GAME_REPO_DIR), "checkout"],
check=True
)
exceptsubprocess.CalledProcessErrorase:
logging.error(f"Git operation failed: {e}")
sys.exit(1)
logging.info("Game repository cloned successfully.")
else:
logging.info("Using existing local game_repo directory. (Use --update to force refresh)")
defescape_attribute_newlines(xml_string: str) ->str:
"""Replaces newlines inside XML attribute values with '
' to preserve linebreaks during parsing."""
xml_string=re.sub(r"<\?.+\?>", "", xml_string) # Removes the xml declaration
regex=r'((?<=((=")))[^"]+(?<!"))'
matches=list(re.finditer(regex, xml_string))
formatchinreversed(matches):
s=re.sub(r"\r\n|\n\r|\n|\r| ", "
", match.group())
xml_string=xml_string[:match.start()] +s+xml_string[match.end():]
returnxml_string
# Backward-compatibility alias
filter_xml_text=escape_attribute_newlines
defload_translations() ->dict[str, dict[str, str]]:
"""Loads all language translation XML files from the game repo into dictionaries."""
translations: dict[str, dict[str, str]] = {}
ifnotTRANSLATIONS_DIR.exists():
raiseFileNotFoundError(f"Translations directory not found: {TRANSLATIONS_DIR}")
forfile_pathinTRANSLATIONS_DIR.iterdir():
iffile_path.name.startswith("translation_") andfile_path.name.endswith(".xml"):
lang_code_raw=file_path.name.split("_")[1][:-4]
lang_code=FS25_TO_MKDOCS_LOCALE_MAP.get(lang_code_raw, lang_code_raw)
content=file_path.read_text(encoding="utf-8")
content_filtered=escape_attribute_newlines(content)
try:
root=ET.fromstring(content_filtered)
exceptExceptionase:
logging.error(f"Error parsing {file_path.name}: {e}")
continue
translations[lang_code] = {}
forentryinroot.iter("text"):
name=entry.attrib.get("name")
val=entry.attrib.get("text", "")
ifname:
translations[lang_code][name] =val
returntranslations
defprocess_image(
image_elem: ET.Element,
used_images: set[str],
dds_cache: dict[Path, PIL_Image.Image]
) ->Optional[str]:
"""Extracts image metadata, converts DDS texture to cropped PNG using in-memory caching, and returns markdown filename."""
raw_filename=image_elem.attrib.get("filename")
ifnotraw_filename:
returnNone
uvs_str=image_elem.attrib.get("uvs", "")
uvs= [int(val) forvalinuvs_str.replace("px", "").split()]
iflen(uvs) !=4:
logging.warning(f"Warning: Invalid UV coordinates for {raw_filename}: {uvs_str}")
returnNone
base_name=Path(raw_filename).stem
cropped_filename=f"{base_name}_{uvs[0]}_{uvs[1]}_{uvs[2]}_{uvs[3]}.png"
dest_path=IMAGES_DIR/cropped_filename
# If this exact snippet hasn't been generated in the current run yet, generate it now.
# This guarantees that updated source DDS graphics are always exported on every new run,
# while preventing duplicate file saving within the same execution loop.
ifcropped_filenamenotinused_images:
source_path=GAME_REPO_DIR/Path(*raw_filename.split("/"))
ifsource_path.exists():
try:
ifsource_pathnotindds_cache:
dds_cache[source_path] =PIL_Image.open(source_path)
img=dds_cache[source_path]
box= (uvs[0], uvs[1], uvs[0] +uvs[2], uvs[1] +uvs[3])
cropped=img.crop(box)
cropped.save(dest_path)
exceptExceptionase:
logging.error(f"Failed to convert/crop image {source_path}: {e}")
else:
logging.warning(f"Warning: Source image not found at {source_path}")
used_images.add(cropped_filename)
returncropped_filename
defload_help_menu_config(used_images: set[str]) ->list[HelpPage]:
"""Parses HelpMenu.xml and returns structured HelpPage models while processing required images."""
ifnotCONFIG_FILE.exists():
raiseFileNotFoundError(f"Configuration file not found: {CONFIG_FILE}")
content=CONFIG_FILE.read_text(encoding="utf-8")
content_filtered=re.sub(r"<\?.+\?>", "", content)
root=ET.fromstring(content_filtered)
dds_cache: dict[Path, PIL_Image.Image] = {}
pages: list[HelpPage] = []
try:
forcategoryinroot.iter("category"):
forpageincategory.iter("page"):
raw_title=page.attrib.get("title", "").replace("$l10n_", "")
paragraphs: list[HelpParagraph] = []
forparagraphinpage.iter("paragraph"):
para_title_elem=paragraph.find("title")
para_text_elem=paragraph.find("text")
para_image_elem=paragraph.find("image")
para_title=""
ifpara_title_elemisnotNoneand"text"inpara_title_elem.attrib:
para_title=para_title_elem.attrib["text"].replace("$l10n_", "")
para_text=""
ifpara_text_elemisnotNoneand"text"inpara_text_elem.attrib:
para_text=para_text_elem.attrib["text"].replace("$l10n_", "")
cropped_img: Optional[str] =None
ifpara_image_elemisnotNone:
cropped_img=process_image(para_image_elem, used_images, dds_cache)
paragraphs.append(HelpParagraph(
raw_title=para_title,
raw_text=para_text,
image_filename=cropped_img
))
pages.append(HelpPage(raw_title=raw_title, paragraphs=paragraphs))
finally:
# Clean up open PIL image file handles
forimg_handleindds_cache.values():
try:
img_handle.close()
exceptException:
pass
returnpages
defcreate_markdown_file(
language_code: str,
page: HelpPage,
translations_lang: dict[str, str],
output_dir: Path,
file_index: int,
is_index: bool=False
) ->None:
"""Creates a localized Markdown file for a single help menu page."""
file_name="index.md"ifis_indexelsef"{file_index:02d}_page_{page.raw_title}.md"
file_path=output_dir/file_name
page_title=translations_lang.get(page.raw_title, page.raw_title)
lines: list[str] = [f"# {page_title}\n\n"]
forparainpage.paragraphs:
ifpara.raw_title:
title=translations_lang.get(para.raw_title, para.raw_title)
iftitle:
lines.append(f"## {title}\n\n")
ifpara.raw_text:
text=translations_lang.get(para.raw_text, para.raw_text)
iftext:
formatted_text=text.replace("\n", " \n")
lines.append(f"{formatted_text}\n\n")
ifpara.image_filename:
image_path=f"../assets/images/{para.image_filename}"
lines.append(f"\n\n")
file_path.write_text("".join(lines), encoding="utf-8")
defdelete_unused_images(used_images: set[str]) ->None:
"""Removes any unused images from the docs/assets/images directory."""
ifIMAGES_DIR.exists():
forfile_pathinIMAGES_DIR.glob("*.png"):
iffile_path.namenotinused_images:
try:
file_path.unlink(missing_ok=True)
logging.info(f"Deleted unused image asset: {file_path.name}")
exceptOSErrorase:
logging.error(f"Failed to delete {file_path.name}: {e}")
defgenerate_docs(force_update: bool=False) ->None:
"""Main routine to set up repository, extract translation dictionaries and output markdown documentation."""
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
IMAGES_DIR.mkdir(parents=True, exist_ok=True)
setup_game_repo(force_update=force_update)
used_images: set[str] =set()
pages=load_help_menu_config(used_images)
translations=load_translations()
logging.info(f"Loaded {len(pages)} help pages and {len(translations)} languages.")
forlang_code, trans_dictintranslations.items():
lang_output_dir=OUTPUT_DIR/lang_code
lang_output_dir.mkdir(parents=True, exist_ok=True)
forindex, pageinenumerate(pages, start=1):
is_index= (index==1)
create_markdown_file(lang_code, page, trans_dict, lang_output_dir, index, is_index=is_index)
delete_unused_images(used_images)
logging.info("Documentation generated successfully!")
# Alias for backward compatibility if imported externally
generate_site=generate_docs
if__name__=="__main__":
parser=argparse.ArgumentParser(description="Generate Courseplay FS25 documentation from game XMLs.")
parser.add_argument("--update", action="store_true", help="Force update of local game_repo sparse checkout.")
args=parser.parse_args()
generate_docs(force_update=args.update)