|
|
| """
|
| Decrypt the Answer column of UIS-QA encrypted TSV.
|
| For use by researchers who have received the decryption key from the dataset authors.
|
| Output: decrypted TSV (for local evaluation) or a simple id -> answer mapping.
|
| """
|
|
|
| import argparse
|
| import csv
|
| import sys
|
| from pathlib import Path
|
|
|
| try:
|
| from cryptography.fernet import Fernet
|
| from cryptography.hazmat.primitives import hashes
|
| from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
|
| from cryptography.hazmat.backends import default_backend
|
| except ImportError:
|
| print("Install cryptography: pip install cryptography", file=sys.stderr)
|
| sys.exit(1)
|
|
|
| ENC_PREFIX = "UIS_ENC_V1:"
|
|
|
|
|
| def derive_key_from_password(password: str, salt: bytes) -> bytes:
|
| """Same as in encrypt_answers.py."""
|
| kdf = PBKDF2HMAC(
|
| algorithm=hashes.SHA256(),
|
| length=32,
|
| salt=salt,
|
| iterations=480000,
|
| backend=default_backend(),
|
| )
|
| key_material = kdf.derive(password.encode("utf-8"))
|
| import base64
|
| return base64.urlsafe_b64encode(key_material)
|
|
|
|
|
| def decrypt_tsv(
|
| input_path: str,
|
| output_path: str | None,
|
| key: bytes,
|
| ) -> list[tuple[int, str]]:
|
| """
|
| Read encrypted TSV, decrypt Answer column.
|
| If output_path is set, write full decrypted TSV; else only return list of (row_id, answer).
|
| """
|
| fernet = Fernet(key)
|
| salt = b"uis-qa-benchmark-v1"
|
| rows: list[list[str]] = []
|
| answers_for_eval: list[tuple[int, str]] = []
|
|
|
| with open(input_path, "r", encoding="utf-8", newline="") as f:
|
| reader = csv.reader(f, delimiter="\t", quoting=csv.QUOTE_MINIMAL)
|
| header = next(reader)
|
| if "Answer" not in header:
|
| raise ValueError("TSV must have an 'Answer' column")
|
| ans_col = header.index("Answer")
|
| rows.append(header)
|
|
|
| for idx, row in enumerate(reader):
|
| if len(row) <= ans_col:
|
| rows.append(row)
|
| continue
|
| cell = row[ans_col]
|
| if cell.startswith(ENC_PREFIX):
|
| ciphertext = cell[len(ENC_PREFIX) :].encode("ascii")
|
| try:
|
| plain = fernet.decrypt(ciphertext).decode("utf-8")
|
| except Exception as e:
|
| raise ValueError(f"Row {idx + 2}: decryption failed: {e}") from e
|
| row[ans_col] = plain
|
| answers_for_eval.append((idx, plain))
|
| else:
|
| answers_for_eval.append((idx, row[ans_col]))
|
| rows.append(row)
|
|
|
| if output_path:
|
| Path(output_path).parent.mkdir(parents=True, exist_ok=True)
|
| with open(output_path, "w", encoding="utf-8", newline="") as f:
|
| writer = csv.writer(f, delimiter="\t", quoting=csv.QUOTE_MINIMAL)
|
| writer.writerows(rows)
|
| print(f"Decrypted TSV written to {output_path}")
|
|
|
| return answers_for_eval
|
|
|
|
|
| def main():
|
| ap = argparse.ArgumentParser(
|
| description="Decrypt Answer column in UIS-QA encrypted TSV (for evaluators)."
|
| )
|
| ap.add_argument(
|
| "input",
|
| nargs="?",
|
| default="test/uis_qa_encrypted.tsv",
|
| help="Encrypted TSV path",
|
| )
|
| ap.add_argument(
|
| "-o", "--output",
|
| default=None,
|
| help="Output decrypted TSV path (default: print answers only)",
|
| )
|
| ap.add_argument(
|
| "--key-file",
|
| help="Path to file containing Fernet key (from dataset authors)",
|
| )
|
| ap.add_argument(
|
| "--password",
|
| help="Password to derive key (if dataset was encrypted with password)",
|
| )
|
| ap.add_argument(
|
| "--answers-only",
|
| action="store_true",
|
| help="Print only row index and answer (for scripting)",
|
| )
|
| args = ap.parse_args()
|
|
|
| if not args.key_file and not args.password:
|
| print("Error: provide --key-file or --password.", file=sys.stderr)
|
| sys.exit(1)
|
|
|
| if args.key_file:
|
| key = Path(args.key_file).read_bytes()
|
| else:
|
| key = derive_key_from_password(args.password, b"uis-qa-benchmark-v1")
|
|
|
| answers = decrypt_tsv(args.input, args.output, key)
|
|
|
| if args.answers_only:
|
| for idx, ans in answers:
|
| print(f"{idx}\t{ans}")
|
|
|
|
|
| if __name__ == "__main__":
|
| main()
|
|
|