Heyjab's picture VINAY-UMRETHE's picture
Duplicate from heretic-org/Multilingual-Harmless-Harmful
67520a7
Raw History Blame Contribute Delete
5.61 kB
"""
Reads .txt files from data/ and generates content/ with json, csv, and text.
Schema: text (the translation), english (the original).
Run: python scripts/convert.py
"""
from __future__ import annotations
import csv
import json
import os
import shutil
SCRIPT_DIRECTORY: str = os.path.dirname(os.path.abspath(__file__))
PROJECT_ROOT: str = os.path.dirname(SCRIPT_DIRECTORY)
DATA_DIRECTORY: str = os.path.join(PROJECT_ROOT, "data")
CONTENT_DIRECTORY: str = os.path.join(PROJECT_ROOT, "content")
def read_lines(file_path: str) -> list[str]:
with open(file_path, encoding="utf-8") as file_handle:
return [line.strip() for line in file_handle if line.strip()]
def detect_languages() -> dict[str, str]:
detected: dict[str, str] = {}
if not os.path.isdir(DATA_DIRECTORY):
print(f"Data directory not found: {DATA_DIRECTORY}.")
return detected
for language_name in sorted(os.listdir(DATA_DIRECTORY)):
language_directory: str = os.path.join(DATA_DIRECTORY, language_name)
if not os.path.isdir(language_directory):
continue
files: list[str] = os.listdir(language_directory)
harmful_files: list[str] = [
file_name for file_name in files if file_name.endswith("_harmful.txt")
]
if len(harmful_files) != 1:
continue
harmful_file: str = harmful_files[0]
language_code: str = harmful_file.removesuffix("_harmful.txt")
harmless_file: str = f"{language_code}_harmless.txt"
if harmless_file not in files:
continue
with open(
os.path.join(language_directory, harmful_file), encoding="utf-8"
) as file_handle:
harmful_count: int = sum(1 for line in file_handle if line.strip())
with open(
os.path.join(language_directory, harmless_file), encoding="utf-8"
) as file_handle:
harmless_count: int = sum(1 for line in file_handle if line.strip())
try:
response: str = (
input(
f"Detected {language_name} ({language_code}): {harmful_count} harmful + {harmless_count} harmless. Use it? [y/N]: "
)
.strip()
.lower()
)
except EOFError:
response = "y"
if response in ("y", "yes"):
detected[language_name] = language_code
else:
print(f"Skipping {language_name}.")
return detected
def main() -> None:
languages: dict[str, str] = detect_languages()
if not languages:
print("No languages detected.")
return
english_directory: str = os.path.join(DATA_DIRECTORY, "english")
english_files: list[str] = (
os.listdir(english_directory) if os.path.isdir(english_directory) else []
)
english_harmful_files: list[str] = [
file_name for file_name in english_files if file_name.endswith("_harmful.txt")
]
if not english_harmful_files:
print("English not found, cannot align translations")
return
english_code: str = english_harmful_files[0].removesuffix("_harmful.txt")
english_harmful: list[str] = read_lines(
os.path.join(DATA_DIRECTORY, "english", f"{english_code}_harmful.txt")
)
english_harmless: list[str] = read_lines(
os.path.join(DATA_DIRECTORY, "english", f"{english_code}_harmless.txt")
)
for language_name, language_code in languages.items():
harmful = read_lines(
os.path.join(DATA_DIRECTORY, language_name, f"{language_code}_harmful.txt")
)
harmless = read_lines(
os.path.join(DATA_DIRECTORY, language_name, f"{language_code}_harmless.txt")
)
rows: list[dict[str, str]] = [
{"text": prompt, "english": english_prompt, "type": "harmful"}
for prompt, english_prompt in zip(harmful, english_harmful)
] + [
{"text": prompt, "english": english_prompt, "type": "harmless"}
for prompt, english_prompt in zip(harmless, english_harmless)
]
language_content: str = os.path.join(CONTENT_DIRECTORY, language_name)
json_directory: str = os.path.join(language_content, "json")
csv_directory: str = os.path.join(language_content, "csv")
text_directory: str = os.path.join(language_content, "text")
os.makedirs(json_directory, exist_ok=True)
os.makedirs(csv_directory, exist_ok=True)
os.makedirs(text_directory, exist_ok=True)
with open(
os.path.join(json_directory, f"{language_name}.json"),
"w",
encoding="utf-8",
) as json_file:
json.dump(rows, json_file, ensure_ascii=False, indent=2)
with open(
os.path.join(csv_directory, f"{language_name}.csv"),
"w",
encoding="utf-8",
newline="",
) as csv_file:
writer = csv.DictWriter(csv_file, fieldnames=["text", "english", "type"])
writer.writeheader()
writer.writerows(rows)
shutil.copy2(
os.path.join(DATA_DIRECTORY, language_name, f"{language_code}_harmful.txt"),
os.path.join(text_directory, f"{language_name}_harmful.txt"),
)
shutil.copy2(
os.path.join(
DATA_DIRECTORY, language_name, f"{language_code}_harmless.txt"
),
os.path.join(text_directory, f"{language_name}_harmless.txt"),
)
print(f"{language_name}: {len(rows)} rows.")
if __name__ == "__main__":
main()