Repository navigation
feat: JSONL 추출을 위한 export_jsonl.py 도구 추가 #781
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
Draft
seonghobae
wants to merge
2
commits into
develop
Choose a base branch
from
feat/add-jsonl-export-14058315870946212790
base: develop
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.
Draft
Changes from 1 commit
Commits
Show all changes
2 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,116 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import json | ||
| from pathlib import Path | ||
|
|
||
| import pytest | ||
|
|
||
| from tools.export_jsonl import export_jsonl, main | ||
|
|
||
| VALID_JSON_DATA = { | ||
| "document_id": "test_doc", | ||
| "pages": [ | ||
| { | ||
| "page_number": 1, | ||
| "articles": [ | ||
| { | ||
| "article_id": "art_1", | ||
| "headline": "Test Headline 1", | ||
| "body_blocks": ["Block 1", "Block 2"], | ||
| }, | ||
| { | ||
| "article_id": "art_2", | ||
| "headline": "Test Headline 2", | ||
| "body_blocks": [], | ||
| }, | ||
| ], | ||
| }, | ||
| "not_a_dict_page", | ||
| { | ||
| "page_number": 2, | ||
| "articles": [ | ||
| "not_a_dict_article", | ||
| { | ||
| "article_id": "art_3", | ||
| "headline": "Test Headline 3", | ||
| "body_blocks": ["Block 3"], | ||
| }, | ||
| ], | ||
| }, | ||
| ], | ||
| } | ||
|
|
||
|
|
||
| def test_export_jsonl_success(tmp_path: Path) -> None: | ||
| input_file = tmp_path / "input.json" | ||
| input_file.write_text(json.dumps(VALID_JSON_DATA), encoding="utf-8") | ||
| output_file = tmp_path / "output.jsonl" | ||
|
|
||
| export_jsonl(input_file, output_file) | ||
|
|
||
| assert output_file.exists() | ||
|
|
||
| with output_file.open("r", encoding="utf-8") as f: | ||
| lines = f.readlines() | ||
|
|
||
| assert len(lines) == 3 | ||
| record0 = json.loads(lines[0]) | ||
| assert record0["document_id"] == "test_doc" | ||
| assert record0["page_number"] == 1 | ||
| assert record0["article_id"] == "art_1" | ||
| assert record0["headline"] == "Test Headline 1" | ||
| assert record0["body_blocks"] == ["Block 1", "Block 2"] | ||
|
|
||
| record1 = json.loads(lines[1]) | ||
| assert record1["article_id"] == "art_2" | ||
| assert record1["body_blocks"] == [] | ||
|
|
||
| record2 = json.loads(lines[2]) | ||
| assert record2["page_number"] == 2 | ||
| assert record2["article_id"] == "art_3" | ||
| assert record2["body_blocks"] == ["Block 3"] | ||
|
|
||
|
|
||
| def test_export_jsonl_invalid_file(tmp_path: Path) -> None: | ||
| output_file = tmp_path / "output.jsonl" | ||
|
|
||
| non_existent = tmp_path / "not_exist.json" | ||
| with pytest.raises(FileNotFoundError, match="File not found"): | ||
| export_jsonl(non_existent, output_file) | ||
|
|
||
| not_json = tmp_path / "input.txt" | ||
| not_json.write_text("plain text", encoding="utf-8") | ||
| with pytest.raises(ValueError, match="must be a .json file"): | ||
| export_jsonl(not_json, output_file) | ||
|
|
||
| invalid_json = tmp_path / "invalid.json" | ||
| invalid_json.write_text("{invalid_json:", encoding="utf-8") | ||
| with pytest.raises(ValueError, match="Invalid JSON file"): | ||
| export_jsonl(invalid_json, output_file) | ||
|
|
||
|
|
||
| def test_export_jsonl_cli_success(tmp_path: Path, capsys: pytest.CaptureFixture) -> None: | ||
| input_file = tmp_path / "input.json" | ||
| input_file.write_text(json.dumps(VALID_JSON_DATA), encoding="utf-8") | ||
| output_file = tmp_path / "output.jsonl" | ||
|
|
||
| main([str(input_file), str(output_file)]) | ||
|
|
||
| assert output_file.exists() | ||
| captured = capsys.readouterr() | ||
| assert "JSONL successfully written" in captured.out | ||
|
|
||
|
|
||
| def test_export_jsonl_cli_invalid_file( | ||
| tmp_path: Path, capsys: pytest.CaptureFixture | ||
| ) -> None: | ||
| not_json = tmp_path / "input.txt" | ||
| not_json.write_text("plain text", encoding="utf-8") | ||
| output_file = tmp_path / "output.jsonl" | ||
|
|
||
| with pytest.raises(SystemExit) as exc_info: | ||
| main([str(not_json), str(output_file)]) | ||
|
|
||
| assert exc_info.value.code == 1 | ||
| captured = capsys.readouterr() | ||
| assert "Error exporting JSONL:" in captured.err | ||
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,60 @@ | ||||||||||||||||||||||||||
| from __future__ import annotations | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| import argparse | ||||||||||||||||||||||||||
| import json | ||||||||||||||||||||||||||
| import sys | ||||||||||||||||||||||||||
| from pathlib import Path | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| def export_jsonl(json_path: Path, output_path: Path) -> None: | ||||||||||||||||||||||||||
| """Export NewsDOM JSON to a JSONL file containing article objects.""" | ||||||||||||||||||||||||||
| if not json_path.is_file(): | ||||||||||||||||||||||||||
| raise FileNotFoundError(f"File not found or is not a file: {json_path}") | ||||||||||||||||||||||||||
| if json_path.suffix.lower() != ".json": | ||||||||||||||||||||||||||
| raise ValueError("Input file must be a .json file.") | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| try: | ||||||||||||||||||||||||||
| data = json.loads(json_path.read_text(encoding="utf-8")) | ||||||||||||||||||||||||||
| except json.JSONDecodeError as exc: | ||||||||||||||||||||||||||
| raise ValueError(f"Invalid JSON file: {exc}") from exc | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| pages = data.get("pages", []) | ||||||||||||||||||||||||||
| document_id = data.get("document_id", "Unknown Document") | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| with output_path.open("w", encoding="utf-8") as f: | ||||||||||||||||||||||||||
| for page in pages: | ||||||||||||||||||||||||||
| if not isinstance(page, dict): | ||||||||||||||||||||||||||
| continue | ||||||||||||||||||||||||||
| page_number = page.get("page_number", "Unknown") | ||||||||||||||||||||||||||
| articles = page.get("articles", []) | ||||||||||||||||||||||||||
| for article in articles: | ||||||||||||||||||||||||||
| if not isinstance(article, dict): | ||||||||||||||||||||||||||
| continue | ||||||||||||||||||||||||||
| record = { | ||||||||||||||||||||||||||
| "document_id": document_id, | ||||||||||||||||||||||||||
| "page_number": page_number, | ||||||||||||||||||||||||||
| "article_id": article.get("article_id", "Unknown Article ID"), | ||||||||||||||||||||||||||
| "headline": article.get("headline", ""), | ||||||||||||||||||||||||||
| "body_blocks": article.get("body_blocks", []), | ||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||
|
Comment on lines
+33
to
+39
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 기사의 이미지와 주석이 누락됨 유효한 기사도
Suggested change
Was this helpful? React with 👍 or 👎 to provide feedback. |
||||||||||||||||||||||||||
| f.write(json.dumps(record, ensure_ascii=False) + "\n") | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| def main(argv: list[str] | None = None) -> None: | ||||||||||||||||||||||||||
| """Run the JSON-to-JSONL export CLI.""" | ||||||||||||||||||||||||||
| parser = argparse.ArgumentParser(description="Export a NewsDOM JSON file to JSONL.") | ||||||||||||||||||||||||||
| parser.add_argument("input", type=Path, help="Path to the input JSON file.") | ||||||||||||||||||||||||||
| parser.add_argument("output", type=Path, help="Path to write the JSONL output file.") | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| args = parser.parse_args(argv) | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| try: | ||||||||||||||||||||||||||
| export_jsonl(args.input, args.output) | ||||||||||||||||||||||||||
| print(f"JSONL successfully written to {args.output}") | ||||||||||||||||||||||||||
| except Exception as exc: | ||||||||||||||||||||||||||
| print(f"Error exporting JSONL: {exc}", file=sys.stderr) | ||||||||||||||||||||||||||
| sys.exit(1) | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| if __name__ == "__main__": # pragma: no cover | ||||||||||||||||||||||||||
| main() | ||||||||||||||||||||||||||
Oops, something went wrong.
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.
🔍 성공 테스트가 정식 스키마를 위반함
VALID_JSON_DATA는 문자열 페이지와 기사를 포함합니다. 실제ParseResponsefixture로 전체 기사 필드 보존을 검증해야 합니다.Was this helpful? React with 👍 or 👎 to provide feedback.