-
Notifications
You must be signed in to change notification settings - Fork 1
⚡ Optimize JSON Lines (_parse_jsonl) bulk loading #118
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
wjohns989
wants to merge
1
commit into
main
Choose a base branch
from
perf/jsonl-parser-optimization-13904058837291850027
base: main
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 all commits
Commits
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -11,7 +11,7 @@ | |
| import sqlite3 | ||
| from html.parser import HTMLParser | ||
| from pathlib import Path | ||
| from typing import Dict, List, Tuple | ||
| from typing import List, Tuple | ||
| from urllib.parse import quote | ||
|
|
||
| from muninn.ingestion.models import IngestionChunk | ||
|
|
@@ -189,24 +189,43 @@ def _parse_json(path: Path) -> str: | |
|
|
||
|
|
||
| def _parse_jsonl(path: Path) -> str: | ||
| raw_content = path.read_text(encoding="utf-8", errors="replace").strip() | ||
| if not raw_content: | ||
| return "" | ||
|
|
||
| raw_lines = [line.strip() for line in raw_content.splitlines() if line.strip()] | ||
| if not raw_lines: | ||
| return "" | ||
|
|
||
| lines: List[str] = [] | ||
| with path.open("r", encoding="utf-8", errors="replace") as handle: | ||
| for raw in handle: | ||
| raw_line = raw.strip() | ||
| if not raw_line: | ||
| continue | ||
| try: | ||
| payload = json.loads(raw_line) | ||
| except json.JSONDecodeError: | ||
| lines.append(raw_line) | ||
| continue | ||
|
|
||
| # Fast path: bulk parse | ||
| bulk_json = "[" + ",".join(raw_lines) + "]" | ||
| try: | ||
| payloads = json.loads(bulk_json) | ||
| for payload in payloads: | ||
| extracted: List[str] = [] | ||
| _extract_chat_lines(payload, extracted) | ||
| if extracted: | ||
| lines.extend(extracted) | ||
| else: | ||
| lines.append(json.dumps(payload, ensure_ascii=False, sort_keys=True)) | ||
| return _truncate_output("\n".join(lines)) | ||
| except json.JSONDecodeError: | ||
| pass | ||
|
|
||
| # Fallback path: loop | ||
| for raw_line in raw_lines: | ||
| try: | ||
| payload = json.loads(raw_line) | ||
| extracted = [] | ||
| _extract_chat_lines(payload, extracted) | ||
| if extracted: | ||
| lines.extend(extracted) | ||
| else: | ||
| lines.append(json.dumps(payload, ensure_ascii=False, sort_keys=True)) | ||
| except json.JSONDecodeError: | ||
| lines.append(raw_line) | ||
|
|
||
| return _truncate_output("\n".join(lines)) | ||
|
Comment on lines
+192
to
230
Contributor
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. The
This refactor aligns with the SOTA+ philosophy of 'Production-Grade' and 'Quality Over Speed' by optimizing resource usage while improving code structure. with path.open("r", encoding="utf-8", errors="replace") as handle:
raw_lines = [line.strip() for line in handle if line.strip()]
if not raw_lines:
return ""
lines: List[str] = []
def process_payload(payload):
extracted: List[str] = []
_extract_chat_lines(payload, extracted)
if extracted:
lines.extend(extracted)
else:
lines.append(json.dumps(payload, ensure_ascii=False, sort_keys=True))
# Fast path: bulk parse
bulk_json = "[" + ",".join(raw_lines) + "]"
try:
payloads = json.loads(bulk_json)
for payload in payloads:
process_payload(payload)
return _truncate_output("\n".join(lines))
except json.JSONDecodeError:
pass
# Fallback path: line-by-line loop
for raw_line in raw_lines:
try:
payload = json.loads(raw_line)
process_payload(payload)
except json.JSONDecodeError:
lines.append(raw_line)
return _truncate_output("\n".join(lines))References
|
||
|
|
||
|
|
@@ -232,12 +251,14 @@ def _parse_html(path: Path) -> str: | |
| def _parse_pdf(path: Path) -> str: | ||
| """Parse a PDF file via the subprocess sandbox for process isolation (Phase 17).""" | ||
| from muninn.ingestion.sandbox import sandboxed_parse_binary | ||
|
|
||
| return sandboxed_parse_binary(path, "pdf", timeout=30.0) | ||
|
|
||
|
|
||
| def _parse_docx(path: Path) -> str: | ||
| """Parse a DOCX file via the subprocess sandbox for process isolation (Phase 17).""" | ||
| from muninn.ingestion.sandbox import sandboxed_parse_binary | ||
|
|
||
| return sandboxed_parse_binary(path, "docx", timeout=30.0) | ||
|
|
||
|
|
||
|
|
@@ -258,7 +279,10 @@ def _parse_sqlite(path: Path) -> str: | |
| preferred = [ | ||
| name | ||
| for name in table_names | ||
| if any(token in name.lower() for token in ("chat", "conversation", "message", "session", "copilot", "ai", "prompt")) | ||
| if any( | ||
| token in name.lower() | ||
| for token in ("chat", "conversation", "message", "session", "copilot", "ai", "prompt") | ||
| ) | ||
| ] | ||
| ordered_tables = preferred + [name for name in table_names if name not in preferred] | ||
| ordered_tables = ordered_tables[:12] | ||
|
|
@@ -298,7 +322,10 @@ def _parse_sqlite(path: Path) -> str: | |
| if len(value_text) > 2000: | ||
| value_text = value_text[:2000] + "..." | ||
| key_lower = str(key).lower() | ||
| if any(token in key_lower for token in ("content", "text", "prompt", "response", "message", "body", "value")): | ||
| if any( | ||
| token in key_lower | ||
| for token in ("content", "text", "prompt", "response", "message", "body", "value") | ||
| ): | ||
| fallback_texts.append(f"[{key}] {value_text}") | ||
| if fallback_texts: | ||
| lines.extend(fallback_texts) | ||
|
|
@@ -412,4 +439,4 @@ def build_chunks( | |
| }, | ||
| ) | ||
| ) | ||
| return chunks | ||
| return chunks | ||
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.
Avoid reading the entire JSONL file into memory before parsing.
path.read_text(...).strip()forces a full copy of the source, and the fast path then allocates another largebulk_jsonstring; for large chat/session exports this can multiply peak memory and raiseMemoryErroror kill the ingestion process. The previous implementation streamed line-by-line and did not have this failure mode, so this change introduces a scalability regression in_parse_jsonl.Useful? React with 👍 / 👎.