File size: 13,545 Bytes
7205347
 
 
9a46911
7205347
 
 
 
 
 
 
 
 
 
 
 
 
9a46911
 
 
 
 
 
7205347
9a46911
7205347
 
5d7b6b9
9a46911
5d7b6b9
 
7205347
 
9a46911
7205347
 
 
9a46911
7205347
 
 
 
 
 
 
9a46911
7205347
 
9a46911
7205347
 
 
 
9a46911
7205347
 
 
 
9a46911
5d7b6b9
7205347
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a46911
7205347
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a46911
7205347
9a46911
 
7205347
 
 
 
 
 
9a46911
7205347
 
 
 
 
 
 
 
9a46911
7205347
 
 
 
 
 
9a46911
7205347
 
 
 
 
 
 
 
5d7b6b9
7205347
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5d7b6b9
7205347
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a46911
7205347
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a46911
 
 
7205347
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
# SPDX-License-Identifier: AGPL-3.0-or-later
# Copyright (C) 2026  Vinay Umrethe.

"""
Builds the derived artifacts of the dataset from the per-language source files.

Sources are under `content/<language_name>/text/` folder:
- <language_name>_harmful.txt
- <language_name>_harmless.txt
- <iso_code>_keywords.txt

Generates the JSON and the CSV mirrors in the `content/` folder, updates the `config.multilingual.toml`
file, the YAML frontmatter language list, and the language count and the language index table of `README.md`.

The parquet files and the `dataset_info` and the `configs` of the YAML frontmatter are handled
entirely by the `datasets` library, which writes them when the dataset is pushed.

Run: python scripts/convert.py
"""

from __future__ import annotations

import csv
import io
import json
import re
from dataclasses import dataclass
from pathlib import Path

PROJECT_ROOT: Path = Path(__file__).resolve().parent.parent
CONTENT_DIRECTORY: Path = PROJECT_ROOT / "content"
README_PATH: Path = PROJECT_ROOT / "README.md"
KEYWORD_MARKERS_PATH: Path = PROJECT_ROOT / "config.multilingual.toml"

# The original English datasets for both harmless and harmful have exactly
# 416 prompts, so the translations must match that count.
EXPECTED_PROMPT_COUNT: int = 416

# Heretic's default keyword markers list for refusals had 33 keyword patterns
# when `config.multilingual.toml` was originally added to this dataset.
# We'll update this count only if we ever synchronize it with heretic's default
# keyword markers as per the latest version. This would require translating the new
# keyword markers for **all** existing languages in this dataset, plus whichever
# new language is being added by this Pull Request (since this script is being used).
EXPECTED_KEYWORD_COUNT: int = 33

# For the "What is this?" section of the README.md file.
LANGUAGE_COUNT_PATTERN: re.Pattern[str] = re.compile(r"into \*\*\d+\*\* languages")

# For the language index table in the README.md file.
LANGUAGE_TABLE_PATTERN: re.Pattern[str] = re.compile(
    r"(\| No\. \| Language \| Code \|\n\|---\|-+\|-+\|\n)(?:\|[^\n]*\n)+"
)

# For the language list in the README.md YAML frontmatter.
LANGUAGE_LIST_PATTERN: re.Pattern[str] = re.compile(
    r"^language:\n((?:- \w+\n)+)", re.MULTILINE
)


class SourceError(Exception):
    """A source file is missing, malformed or incomplete."""


@dataclass(frozen=True)
class Language:
    """One language of the dataset and the source files that define it."""

    name: str
    iso_code: str
    harmful_source: Path
    harmless_source: Path
    keywords_source: Path


@dataclass(frozen=True)
class LanguageArtifacts:
    """Everything known about one language after its sources have been read."""

    language: Language
    harmful_prompts: list[str]
    harmless_prompts: list[str]
    keyword_markers: list[str]


def display_name(language: Language) -> str:
    """The name of a language in English, for the commit messages and the table."""
    return language.name.title()


def read_source_lines(source_path: Path) -> list[str]:
    """Reads one prompt per line from the source.
    Empty or padded lines are an error, and they are not skipped.

    Skipping them would shift every following line out of alignment with the
    English source, so a malformed file stops the build.
    """
    if not source_path.is_file():
        raise SourceError(f"{source_path}: file not found")

    content = source_path.read_text(encoding="utf-8").replace("\r\n", "\n")
    lines = content.split("\n")
    if lines[-1] == "":
        lines.pop()

    for line_number, line in enumerate(lines, start=1):
        if not line.strip():
            raise SourceError(f"{source_path}: line {line_number} is empty")
        if line != line.strip():
            raise SourceError(
                f"{source_path}: line {line_number} has leading or trailing whitespace"
            )
    return lines


def discover_languages() -> list[Language]:
    """Every language that has prompt sources, English first and then alphabetically."""
    languages: list[Language] = []
    for language_directory in sorted(CONTENT_DIRECTORY.iterdir()):
        if not language_directory.is_dir():
            continue

        language_name = language_directory.name
        text_directory = language_directory / "text"
        keyword_sources = sorted(text_directory.glob("*_keywords.txt"))
        if len(keyword_sources) != 1:
            raise SourceError(
                f"{text_directory}: expected exactly one <iso_code>_keywords.txt, "
                f"found {len(keyword_sources)}"
            )

        iso_code = keyword_sources[0].name.removesuffix("_keywords.txt")
        if re.fullmatch(r"[a-z]{2}", iso_code) is None:
            raise SourceError(
                f"{keyword_sources[0]}: the file name must start with a two letter "
                f"ISO 639-1 code, got {iso_code!r}"
            )

        languages.append(
            Language(
                name=language_name,
                iso_code=iso_code,
                harmful_source=text_directory / f"{language_name}_harmful.txt",
                harmless_source=text_directory / f"{language_name}_harmless.txt",
                keywords_source=keyword_sources[0],
            )
        )

    return sorted(
        languages,
        key=lambda language: (language.name != "english", language.name),
    )


def read_language_artifacts(language: Language) -> LanguageArtifacts:
    """Read and check every source file of one language."""
    artifacts = LanguageArtifacts(
        language=language,
        harmful_prompts=read_source_lines(language.harmful_source),
        harmless_prompts=read_source_lines(language.harmless_source),
        keyword_markers=read_source_lines(language.keywords_source),
    )

    for source_path, lines, expected_count in (
        (language.harmful_source, artifacts.harmful_prompts, EXPECTED_PROMPT_COUNT),
        (language.harmless_source, artifacts.harmless_prompts, EXPECTED_PROMPT_COUNT),
        (language.keywords_source, artifacts.keyword_markers, EXPECTED_KEYWORD_COUNT),
    ):
        if len(lines) != expected_count:
            raise SourceError(
                f"{source_path}: expected {expected_count} lines, got {len(lines)}"
            )
    return artifacts


def build_content_rows(
    artifacts: LanguageArtifacts,
    english_harmful_prompts: list[str],
    english_harmless_prompts: list[str],
) -> list[dict[str, str]]:
    """Builds the JSON and CSV rows for `content/` folder.

    Schema:
    - text (str): Translated prompt in the target language.
    - english (str): The original English source prompt.
    - type (str): Split category ("harmless" or "harmful").
    """
    rows: list[dict[str, str]] = []
    for split_name, prompts, english_prompts in (
        ("harmful", artifacts.harmful_prompts, english_harmful_prompts),
        ("harmless", artifacts.harmless_prompts, english_harmless_prompts),
    ):
        rows.extend(
            {"text": prompt, "english": english_prompt, "type": split_name}
            for prompt, english_prompt in zip(prompts, english_prompts, strict=True)
        )
    return rows


def write_if_changed(file_path: Path, content: str) -> None:
    """Write a generated file, unless it already holds that content."""
    if (
        file_path.is_file()
        and file_path.read_text(encoding="utf-8").replace("\r\n", "\n") == content
    ):
        file_path.parent.mkdir(parents=True, exist_ok=True)
    with open(file_path, "w", encoding="utf-8", newline="\n") as f:
        f.write(content)


def write_content_files(language: Language, rows: list[dict[str, str]]) -> None:
    """The JSON and CSV mirrors of one language."""
    language_directory = CONTENT_DIRECTORY / language.name
    write_if_changed(
        language_directory / "json" / f"{language.name}.json",
        json.dumps(rows, ensure_ascii=False, indent=2),
    )

    buffer = io.StringIO(newline="")
    writer = csv.DictWriter(
        buffer, fieldnames=list(rows[0].keys()), lineterminator="\n"
    )
    writer.writeheader()
    writer.writerows(rows)
    write_if_changed(
        language_directory / "csv" / f"{language.name}.csv", buffer.getvalue()
    )


def build_keyword_markers_configuration(artifacts: list[LanguageArtifacts]) -> str:
    """Rebuild `config.multilingual.toml` from the keyword markers of every language."""
    language_order = [artifact.language.name for artifact in artifacts]
    header_lines = [
        "# Generated by `scripts/convert.py` from",
        "# `content/<language_name>/text/<iso_code>_keywords.txt` file.",
        "#",
        "# Rename this file to config.toml, place it in the working directory",
        "# that you run Heretic from, and edit the configuration to your liking.",
        "#",
        "# Translations in keyword_markers follow this exact order:",
        "# [" + ", ".join(f'"{name}"' for name in language_order) + "]",
        "",
        "keyword_markers = [",
    ]

    entry_lines: list[str] = []
    for markers in zip(
        *(artifact.keyword_markers for artifact in artifacts), strict=True
    ):
        entry_lines.append("".join(f'    "{marker}",\n' for marker in markers))
    return "\n".join(header_lines) + "\n" + "\n".join(entry_lines) + "]\n"


def build_language_table(artifacts: list[LanguageArtifacts]) -> str:
    """The language table of the README, English first and then alphabetically."""
    rows: list[str] = []
    for number, artifact in enumerate(artifacts, start=1):
        language = artifact.language
        name = display_name(language)
        suffix = " (original)" if language.name == "english" else ""
        rows.append(f"| {number} | {name}{suffix} | `{language.iso_code}` |\n")
    return "".join(rows)


def split_readme(readme_text: str) -> tuple[str, str]:
    """Splits the YAML front matter and the main body of a README.md file."""
    parts = readme_text.split("---\n", 2)
    if len(parts) != 3:
        raise SourceError(f"{README_PATH}: no YAML front matter found")
    return parts[1].removesuffix("\n"), parts[2]


def update_language_list(front_matter: str, iso_codes: list[str]) -> str:
    """Adds the ISO codes of the languages that the YAML frontmatter does not list yet.

    The `datasets` library only writes `dataset_info` and the `configs`,
    so the language list is maintained here.
    """
    match = LANGUAGE_LIST_PATTERN.search(front_matter)
    listed_codes = re.findall(r"-\s*([a-z]{2})", match.group(1)) if match else []
    new_codes = listed_codes + [
        iso_code for iso_code in iso_codes if iso_code not in listed_codes
    ]
    new_list = "".join(f"- {iso_code}\n" for iso_code in new_codes)
    if match is None:
        return front_matter + "language:\n" + new_list
    return front_matter[: match.start(1)] + new_list + front_matter[match.end(1) :]


def update_readme(artifacts: list[LanguageArtifacts]) -> None:
    """Updates the language list, the language count and the language index table.

    The `dataset_info` and the `configs` of the YAML frontmatter are
    written by the `datasets` library when the dataset is pushed.

    NOTE:
    The count and the table are found by regex patterns, fix the patterns
    if the wording of the README is ever changed.
    """
    readme_text = README_PATH.read_text(encoding="utf-8")
    front_matter, body = split_readme(readme_text)

    front_matter = update_language_list(
        front_matter, [artifact.language.iso_code for artifact in artifacts]
    )
    body = LANGUAGE_COUNT_PATTERN.sub(
        f"into **{len(artifacts)}** languages", body, count=1
    )
    body = LANGUAGE_TABLE_PATTERN.sub(
        lambda match: match.group(1) + build_language_table(artifacts), body, count=1
    )

    README_PATH.write_text("---\n" + front_matter + "\n---\n" + body, encoding="utf-8")


def read_english_prompts(languages: list[Language]) -> tuple[list[str], list[str]]:
    """The English prompts that the English column of every language is built from."""
    english_language = next(
        (language for language in languages if language.name == "english"),
        None,
    )
    if english_language is None:
        raise SourceError(f"{CONTENT_DIRECTORY}: the English sources are missing")
    return (
        read_source_lines(english_language.harmful_source),
        read_source_lines(english_language.harmless_source),
    )


def main() -> int:
    """Convert every language, rebuild the generated files and report the results."""
    try:
        languages = discover_languages()
        english_harmful_prompts, english_harmless_prompts = read_english_prompts(
            languages
        )
        built_artifacts = [read_language_artifacts(language) for language in languages]
    except SourceError as error:
        print(f"error: {error}")
        return 1

    for artifacts in built_artifacts:
        language = artifacts.language
        write_content_files(
            language,
            build_content_rows(
                artifacts, english_harmful_prompts, english_harmless_prompts
            ),
        )
        print(f"{display_name(language)} ({language.iso_code}): converted.")

    KEYWORD_MARKERS_PATH.write_text(
        build_keyword_markers_configuration(built_artifacts), encoding="utf-8"
    )
    update_readme(built_artifacts)
    print()
    print(f"Rebuilt the {KEYWORD_MARKERS_PATH.name} and the {README_PATH.name}.")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())