-
Notifications
You must be signed in to change notification settings - Fork 38
DAGE-47: Add MtebWriter #200
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
nseidan
wants to merge
5
commits into
dataset-generator
Choose a base branch
from
DAGE-47_mteb_writer
base: dataset-generator
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 3 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,23 +1,32 @@ | ||
import argparse | ||
import re | ||
import html | ||
from pathlib import Path | ||
|
||
import re | ||
from typing import Any | ||
|
||
_TAG_REGEX = re.compile('<.*?>') | ||
|
||
|
||
def parse_args(): | ||
parser = argparse.ArgumentParser(description='Parse arguments for CLI.') | ||
|
||
parser.add_argument('-c', '--config_file', type=str, | ||
help='Config file path to use for the application [default: \"config.yaml\"]', | ||
required=False, default="config.yaml") | ||
|
||
parser.add_argument('-v', '--verbose',action='store_true', | ||
parser.add_argument('-v', '--verbose', action='store_true', | ||
help='Activate debug mode for logging [default: False]') | ||
|
||
return parser.parse_args() | ||
|
||
|
||
def clean_text(text: str) -> str: | ||
text_without_html = re.sub(_TAG_REGEX, '', text).strip() | ||
return html.unescape(re.sub(r"\s{2,}", " ", text_without_html)) | ||
|
||
|
||
def _to_string(value: Any) -> str: | ||
if value is None: | ||
return "" | ||
if isinstance(value, (list, tuple)): | ||
return " ".join(str(val) for val in value if val is not None) | ||
return str(value) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,95 @@ | ||
import json | ||
import logging | ||
import os | ||
from pathlib import Path | ||
|
||
from src.config import Config | ||
from src.search_engine.data_store import DataStore | ||
from src.utils import _to_string | ||
from src.writers.abstract_writer import AbstractWriter | ||
|
||
log = logging.getLogger(__name__) | ||
|
||
|
||
class MtebWriter(AbstractWriter): | ||
""" | ||
MtebWriter: Write data namely corpus, queries, and candidates to JSONL file for MTEB | ||
https://github.com/embeddings-benchmark/mteb | ||
|
||
Corpus format: id,title,text | ||
Queries format: id,text | ||
Candidates format: query_id,doc_id,rating | ||
""" | ||
|
||
@classmethod | ||
def build(cls, config: Config, data_store: DataStore): | ||
return cls(datastore=data_store) | ||
|
||
def _write_corpus(self, output_path: str | Path) -> None: | ||
""" | ||
Writes corpus records extracted from search engine to JSONL file: | ||
{"id": <doc_id>, "title": <title>, "text": <description>} | ||
""" | ||
path = Path(output_path) | ||
os.makedirs(path.parent, exist_ok=True) | ||
with path.open("w", encoding="utf-8") as file: | ||
for doc in self.datastore.get_documents(): | ||
doc_id = str(doc.id) | ||
fields = doc.fields | ||
title = _to_string(fields.get("title")) | ||
text = _to_string(fields.get("description")) | ||
|
||
row = {"id": doc_id, "title": title, "text": text} | ||
file.write(json.dumps(row, ensure_ascii=False) + "\n") | ||
|
||
def _write_queries(self, output_path: str | Path) -> None: | ||
""" | ||
Writes queries LLM-generated and/or user-defined records to JSONL file: | ||
{"id": <query_id>, "text": <query_text>} | ||
""" | ||
path = Path(output_path) | ||
os.makedirs(path.parent, exist_ok=True) | ||
with path.open("w", encoding="utf-8") as file: | ||
for query_context in self.datastore.get_queries(): | ||
query_id = query_context.get_query_id() | ||
query_text = query_context.get_query_text() | ||
|
||
row = {"id": query_id, "text": query_text} | ||
file.write(json.dumps(row, ensure_ascii=False) + "\n") | ||
|
||
def _write_candidates(self, output_path: str | Path) -> None: | ||
""" | ||
Writes candidates to JSONL file: | ||
{"query_id": <query_id>, "doc_id": <doc_id>, "rating": <rating_score>} | ||
""" | ||
path = Path(output_path) | ||
os.makedirs(path.parent, exist_ok=True) | ||
with path.open("w", encoding="utf-8") as file: | ||
for query_context in self.datastore.get_queries(): | ||
query_id = query_context.get_query_id() | ||
for doc_id in query_context.get_doc_ids(): | ||
if query_context.has_rating_score(doc_id): | ||
rating_score = query_context.get_rating_score(doc_id) | ||
|
||
row = {"query_id": query_id, "doc_id": doc_id, "rating": rating_score} | ||
file.write(json.dumps(row, ensure_ascii=False) + "\n") | ||
|
||
def write(self, output_path: str | Path) -> None: | ||
dantuzi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
""" | ||
Write corpus, queries, and candidates JSONL files for MTEB. | ||
""" | ||
path = Path(output_path) | ||
os.makedirs(path, exist_ok=True) | ||
try: | ||
self._write_corpus(path / "corpus.jsonl") | ||
log.info("Corpus written successfully") | ||
|
||
self._write_queries(path / "queries.jsonl") | ||
log.info("Queries written successfully") | ||
|
||
self._write_candidates(path / "candidates.jsonl") | ||
log.info("Candidates written successfully") | ||
|
||
except Exception as e: | ||
log.exception("Failed to write MTEB files: %s", e) | ||
raise |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
96 changes: 96 additions & 0 deletions
96
rre-dataset-generator/tests/unit/writers/test_mteb_writer.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,96 @@ | ||
import json | ||
from pathlib import Path | ||
|
||
import pytest | ||
|
||
from src.config import Config | ||
from src.search_engine.data_store import DataStore | ||
from src.writers.mteb_writer import MtebWriter | ||
|
||
|
||
@pytest.fixture | ||
def config(): | ||
"""Loads a valid config.""" | ||
return Config.load("tests/unit/resources/good_config.yaml") | ||
|
||
|
||
@pytest.fixture | ||
def populated_datastore() -> DataStore: | ||
"""Returns a DataStore instance populated with test data.""" | ||
datastore = DataStore() | ||
|
||
# Query 1: 2 rated docs | ||
query_1_id = datastore.add_query("test query 1", "doc1") | ||
datastore.add_query("test query 1", "doc2") | ||
datastore.add_rating_score(query_1_id, "doc1", 1) | ||
datastore.add_rating_score(query_1_id, "doc2", 1) | ||
|
||
# Query 2: 1 rated doc | ||
query_2_id = datastore.add_query("test query 2", "doc4") | ||
datastore.add_rating_score(query_2_id, "doc4", 2) | ||
|
||
# Query 3: No rated docs | ||
datastore.add_query("test query 3", "doc5") | ||
|
||
return datastore | ||
|
||
|
||
class TestMtebWriter: | ||
|
||
def test_write_expect_written_to_jsonl(self, config, populated_datastore, tmp_path: Path): | ||
output_dir = tmp_path / "data" | ||
writer = MtebWriter(populated_datastore) | ||
|
||
writer.write(output_dir) | ||
|
||
corpus_file = output_dir / "corpus.jsonl" | ||
queries_file = output_dir / "queries.jsonl" | ||
candidates_file = output_dir / "candidates.jsonl" | ||
|
||
assert corpus_file.exists() | ||
assert queries_file.exists() | ||
assert candidates_file.exists() | ||
|
||
lines = corpus_file.read_text(encoding="utf-8").splitlines() | ||
rows = [json.loads(line) for line in lines if line.strip()] | ||
|
||
docs = populated_datastore.get_documents() | ||
assert len(rows) == len(docs) | ||
|
||
for row in rows: | ||
assert set(row.keys()) == {"id", "title", "text"} | ||
assert isinstance(row["id"], str) | ||
assert isinstance(row["title"], str) | ||
assert isinstance(row["text"], str) | ||
|
||
lines = queries_file.read_text(encoding="utf-8").splitlines() | ||
rows = [json.loads(line) for line in lines if line.strip()] | ||
|
||
queries = populated_datastore.get_queries() | ||
assert len(rows) == len(queries) | ||
|
||
for row in rows: | ||
assert set(row.keys()) == {"id", "text"} | ||
assert isinstance(row["id"], str) | ||
assert isinstance(row["text"], str) | ||
|
||
lines = candidates_file.read_text(encoding="utf-8").splitlines() | ||
rows = [json.loads(line) for line in lines if line.strip()] | ||
|
||
expected = set() | ||
for query_context in populated_datastore.get_queries(): | ||
query_id = query_context.get_query_id() | ||
for doc_id in query_context.get_doc_ids(): | ||
if query_context.has_rating_score(doc_id): | ||
expected.add((query_id, doc_id, query_context.get_rating_score(doc_id))) | ||
|
||
assert len(rows) == len(expected) | ||
|
||
for row in rows: | ||
assert set(row.keys()) == {"query_id", "doc_id", "rating"} | ||
assert isinstance(row["query_id"], str) | ||
assert isinstance(row["doc_id"], str) | ||
assert isinstance(row["rating"], int) | ||
|
||
written = {(row["query_id"], row["doc_id"], row["rating"]) for row in rows} | ||
assert written == expected |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is already done in the method
write
, so we get the output_path with typePath
and avoid creating the directory.If the method were public as it was before, this piece of code would be necessary but now the method is private
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
updated