mirror of
https://github.com/kuhyx/WUT_Computer_Science.git
synced 2026-11-10 21:27:08 +01:00
749 findings across six labs and two projects. The mechanical half was scripted; everything below is what the scripts got wrong or could not do, and how it was caught. Three regressions I introduced and then found by RUNNING the code, not by reading it: - Converting print() to logger.info() made the programs SILENT. logging's last-resort handler only emits WARNING and above, so with no basicConfig call `lab2/main.py -t 1 1` printed nothing at all. Fifteen files across the repo now configure logging where they log. - The same conversion dropped `end=""`. lab2 draws its board one square at a time and lab1 draws the maze one cell at a time; both came out one glyph per line. Those thirteen call sites are sys.stdout.write again, and the rendered board now diffs byte-identically against the pre-change output. - The B007 fix renamed `col` to `_col` in the FIRST loop it matched, which was print_letters -- where the variable IS used. That would have been a NameError on the first call. And one the scripts caused silently: annotating 110 signatures dropped the DEFAULT VALUES from 22 of them, so `preprocessing(a, b, USER_THRESHOLD, ANIME_THRESHOLD)` would have raised TypeError. Every signature is now diffed against the pre-change version, name by name and default by default: zero mismatches. Real defects the lint surfaced: - `alpha_beta` ended with an unreachable `return None` that violated its own return type. Its maximising and minimising halves were mirror images, so they are one `_search_branch` now (C901 11 -> ok). - `get_data`'s `gpu` switch, `predict`'s `auto`, `create_model`'s `rows_number` and five of `preprocess_model_predict`'s fifteen parameters were never read. Gone, with their call sites. - np.random.* -> Generator throughout (NPY002), `.values` -> `.to_numpy()`, `datetime.now()` with a tzinfo, `inplace=True` removed, `except:` given a type, `random.*` -> `SystemRandom` (S311). - print_board's three nested helpers became methods (C901 17 -> ok); user_input's nine-branch if-ladder became a table (C901 12 -> ok). Verification, all by running: lab1 `-t` and lab2 `-t 1 1` produce output byte-identical to the pre-change code; lab2's rendered 8x8 board diffs clean; lab3's argument parsing returns the same dict for the same argv; lab4 fails identically before and after (no sklearn here). Also included: the logging configuration for NLP, MOM and ECRYPT_PROJECT, which had the same silence bug. Repo-wide: 2,775 findings -> 1,883. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0172dj34FDpao6wsix8ZuCzE
172 lines
5.8 KiB
Python
Executable File
172 lines
5.8 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Load the SemEval corpus: sentences, chunkings and gold alignments."""
|
|
|
|
import sys
|
|
import logging
|
|
import re
|
|
from pathlib import Path
|
|
|
|
import numpy as np
|
|
import pandas as pd
|
|
from lxml import etree
|
|
|
|
logger = logging.getLogger(__name__)
|
|
logging.basicConfig(format="%(message)s", level=logging.INFO)
|
|
|
|
|
|
def load_sentences(senteance1_path: str, sentance2_path: str) -> pd.DataFrame:
|
|
"""Load the sentences from the given paths and outputs in a 2 columns dataframe."""
|
|
sentance1 = pd.read_csv(senteance1_path, dtype=str, delimiter="}", header=None)
|
|
sentance1.columns = ["sentance1"]
|
|
|
|
sentance2 = pd.read_csv(sentance2_path, dtype=str, delimiter="}", header=None)
|
|
sentance2.columns = ["sentance2"]
|
|
|
|
return pd.concat([sentance1, sentance2], axis=1)
|
|
|
|
|
|
def chunk2list(chunks: str) -> list:
|
|
"""Split one chunked sentence into its chunks."""
|
|
chunks = chunks.replace("[", "")
|
|
chunks = chunks.replace("]", "")
|
|
chunks = chunks.replace(" ", "|")
|
|
split = chunks.split("|")
|
|
|
|
split = [
|
|
re.sub(r"^\s+|\s+$", "", s) for s in split
|
|
] # remove spaces at the beggining and end of chunks
|
|
return [re.sub(r"[^\w\s]", "", s) for s in split] # remove punctuation
|
|
|
|
|
|
def load_chunked(chunked_path1: str, chunked_path2: str) -> pd.DataFrame:
|
|
"""Load two chunk files into a dataframe of chunk lists.
|
|
|
|
The on-disk format is ``[ chunk1 ] [ chunk2 ] ...`` per line.
|
|
"""
|
|
chunked_sentance1 = pd.read_csv(
|
|
chunked_path1, dtype=str, delimiter="}", header=None
|
|
)
|
|
chunked_sentance1.columns = ["chunked_sentance1"]
|
|
|
|
chunked_sentance2 = pd.read_csv(
|
|
chunked_path2, dtype=str, delimiter="}", header=None
|
|
)
|
|
chunked_sentance2.columns = ["chunked_sentance2"]
|
|
|
|
headlines_chunked = pd.concat([chunked_sentance1, chunked_sentance2], axis=1)
|
|
|
|
# convert chunks from str to list
|
|
headlines_chunked["chunked_sentance1"] = headlines_chunked[
|
|
"chunked_sentance1"
|
|
].apply(chunk2list)
|
|
headlines_chunked["chunked_sentance2"] = headlines_chunked[
|
|
"chunked_sentance2"
|
|
].apply(chunk2list)
|
|
|
|
return headlines_chunked
|
|
|
|
|
|
def return_characteers(cell: str) -> str:
|
|
"""Convert the alignment data to restore the <==> and & tokens."""
|
|
cell = cell.replace("ARROWS_PLACEHOLDER", "<==>")
|
|
return cell.replace("AMPERSAND_PLACEHOLDER", "&")
|
|
|
|
|
|
def load_alignment(alignment_path: str) -> pd.DataFrame:
|
|
"""Load the gold alignment file into a dataframe.
|
|
|
|
Only the ``<alignment>`` tag is parsed; the rest of the .wa XML is
|
|
metadata this project does not use.
|
|
"""
|
|
with Path(alignment_path).open() as file:
|
|
file_content = file.read()
|
|
|
|
# <==> and & break xml loaders so it needs to be replaces with something else
|
|
modified_content = file_content.replace("<==>", "ARROWS_PLACEHOLDER").replace(
|
|
"&", "AMPERSAND_PLACEHOLDER"
|
|
)
|
|
# it also needs a root wrapped to function properly
|
|
modified_content = f"<root>{modified_content}</root>"
|
|
|
|
modified_file_path = "temp.wa"
|
|
with Path(modified_file_path).open("w") as modified_file:
|
|
modified_file.write(modified_content)
|
|
|
|
# Parse the modified file using ElementTree
|
|
tree = etree.parse(modified_file_path)
|
|
root = tree.getroot()
|
|
|
|
# get ansewrs
|
|
alignments_data = []
|
|
|
|
for alignment in root.xpath("//alignment"):
|
|
# Extract relevant information from the alignment element
|
|
data = {
|
|
"sentence_id": alignment.xpath("ancestor::sentence/@id")[0],
|
|
"alignment_text": alignment.text,
|
|
}
|
|
alignments_data.append(data)
|
|
|
|
y = pd.DataFrame(alignments_data)
|
|
y = y.drop(columns=["sentence_id"])
|
|
y["alignment_text"] = y["alignment_text"].apply(return_characteers)
|
|
return y
|
|
|
|
|
|
def prettyprint(element: etree._Element, **kwargs: object) -> None:
|
|
"""Log an XML element with lxml's pretty printer."""
|
|
xml = etree.tostring(element, pretty_print=True, **kwargs)
|
|
sys.stdout.write(xml.decode())
|
|
|
|
|
|
def log_first_alignment(alignments_data: list[dict[str, str]]) -> None:
|
|
"""Log the first parsed alignment, to eyeball the .wa parsing.
|
|
|
|
This was `test_XML()` and read a module-level `alignments_data` that does
|
|
not exist at module scope -- it only ever worked when pasted into a
|
|
session where load_alignment had already run. It takes the data as an
|
|
argument now, and is no longer named test_* so pytest does not collect it.
|
|
"""
|
|
logger.info("%s", alignments_data[0]["alignment_text"])
|
|
|
|
|
|
def generate_train_test_split(xy: pd.DataFrame) -> tuple[pd.DataFrame, pd.DataFrame]:
|
|
"""Split the dataframe into a train and a test half.
|
|
|
|
The docstring said 60/20/20 when it was written; the code splits at 3%,
|
|
which is what the experiments actually used.
|
|
"""
|
|
data = xy
|
|
train, test = np.split(
|
|
data.sample(frac=1, random_state=42), [int(0.03 * len(data))]
|
|
)
|
|
|
|
return train, test
|
|
|
|
|
|
def generate_alignment_format(data_frame: pd.DataFrame, row_id: int) -> str:
|
|
"""Render one row's two chunkings as the numbered text GPT is shown."""
|
|
output = "seq1:\n"
|
|
chunks1 = data_frame["chunked_sentance1"][row_id]
|
|
for i, chunk in enumerate(chunks1):
|
|
output = output + str(i + 1) + ") " + str(chunk) + "\n"
|
|
output = output + "\nseq2:\n"
|
|
chunks2 = data_frame["chunked_sentance2"][row_id]
|
|
for i, chunk in enumerate(chunks2):
|
|
output = output + str(i + 1) + ") " + str(chunk) + "\n"
|
|
return output
|
|
|
|
|
|
def get_chunks_as_text(data: pd.DataFrame) -> tuple[list[str], pd.Index]:
|
|
"""Render every row's chunk pair as bracketed text, with its index."""
|
|
output = []
|
|
for _index, row in data.iterrows():
|
|
chunks = ""
|
|
for chunk in row["chunked_sentance1"]:
|
|
chunks = chunks + "[ " + chunk + " ] "
|
|
chunks = chunks + "\n"
|
|
for chunk in row["chunked_sentance2"]:
|
|
chunks = chunks + "[ " + chunk + " ] "
|
|
output.append(chunks)
|
|
return output, data.index
|