Spaces:
Sleeping
Sleeping
Update utils/json_to_spacy.py
Browse files- utils/json_to_spacy.py +86 -67
utils/json_to_spacy.py
CHANGED
|
@@ -1,67 +1,86 @@
|
|
| 1 |
-
import json
|
| 2 |
-
import spacy
|
| 3 |
-
from spacy.tokens import DocBin
|
| 4 |
-
|
| 5 |
-
def read_in_chunks(file_path, chunk_size=1024):
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import spacy
|
| 3 |
+
from spacy.tokens import DocBin
|
| 4 |
+
|
| 5 |
+
def read_in_chunks(file_path, chunk_size=1024):
|
| 6 |
+
"""Read file in chunks to handle large files."""
|
| 7 |
+
print(f"Reading file: {file_path}")
|
| 8 |
+
if not os.path.exists(file_path):
|
| 9 |
+
print(f"Error: File not found at {file_path}")
|
| 10 |
+
return
|
| 11 |
+
|
| 12 |
+
with open(file_path, 'r', encoding='utf-8') as file:
|
| 13 |
+
while True:
|
| 14 |
+
data = file.read(chunk_size)
|
| 15 |
+
if not data:
|
| 16 |
+
break
|
| 17 |
+
yield data
|
| 18 |
+
|
| 19 |
+
def extract_text_and_entities(item):
|
| 20 |
+
"""Dynamically extract text and entities, handling multiple JSON formats."""
|
| 21 |
+
print(f"Processing item: {item}")
|
| 22 |
+
if isinstance(item, dict):
|
| 23 |
+
# Dictionary structure: {"text": ..., "entities": ...}
|
| 24 |
+
text = item.get("text", "")
|
| 25 |
+
entities = item.get("entities", [])
|
| 26 |
+
elif isinstance(item, list) and len(item) >= 2:
|
| 27 |
+
# List structure: ["text", {"entities": ...}]
|
| 28 |
+
text = item[0] if isinstance(item[0], str) else ""
|
| 29 |
+
entities = item[1].get("entities", []) if isinstance(item[1], dict) else []
|
| 30 |
+
else:
|
| 31 |
+
print(f"Unexpected item format: {item}")
|
| 32 |
+
return None, [] # Return empty text and entities
|
| 33 |
+
|
| 34 |
+
valid_entities = [
|
| 35 |
+
(start, end, label) for start, end, label in entities
|
| 36 |
+
if isinstance(start, int) and isinstance(end, int) and isinstance(label, str)
|
| 37 |
+
]
|
| 38 |
+
return text, valid_entities
|
| 39 |
+
|
| 40 |
+
def convert_json_to_spacy(json_file_path, spacy_file_path):
|
| 41 |
+
"""Convert JSON data to spaCy format and save as .spacy file."""
|
| 42 |
+
try:
|
| 43 |
+
print(f"Reading JSON from: {json_file_path}")
|
| 44 |
+
file_content = "".join(chunk for chunk in read_in_chunks(json_file_path))
|
| 45 |
+
|
| 46 |
+
data = json.loads(file_content) # Parse JSON data
|
| 47 |
+
print(f"Successfully loaded JSON data. Found {len(data)} items.")
|
| 48 |
+
|
| 49 |
+
spacy_format = []
|
| 50 |
+
for item in data:
|
| 51 |
+
text, entities = extract_text_and_entities(item)
|
| 52 |
+
if text: # Skip if text is empty or invalid
|
| 53 |
+
spacy_format.append({"text": text, "entities": entities})
|
| 54 |
+
|
| 55 |
+
# Create a blank spaCy model
|
| 56 |
+
nlp = spacy.blank("en")
|
| 57 |
+
doc_bin = DocBin()
|
| 58 |
+
|
| 59 |
+
for entry in spacy_format:
|
| 60 |
+
print(f"Creating spaCy Doc for text: {entry['text']}")
|
| 61 |
+
doc = nlp.make_doc(entry["text"])
|
| 62 |
+
entities = []
|
| 63 |
+
seen_positions = set()
|
| 64 |
+
|
| 65 |
+
for start, end, label in entry["entities"]:
|
| 66 |
+
if start < 0 or end > len(doc.text) or start >= end:
|
| 67 |
+
print(f"Invalid span: start={start}, end={end}, label={label}")
|
| 68 |
+
continue
|
| 69 |
+
if not any(start < e_end and end > e_start for e_start, e_end, _ in seen_positions):
|
| 70 |
+
span = doc.char_span(start, end, label=label)
|
| 71 |
+
if span is not None:
|
| 72 |
+
entities.append(span)
|
| 73 |
+
seen_positions.add((start, end, label))
|
| 74 |
+
else:
|
| 75 |
+
print(f"Overlapping span: start={start}, end={end}, label={label}")
|
| 76 |
+
|
| 77 |
+
doc.ents = entities
|
| 78 |
+
doc_bin.add(doc)
|
| 79 |
+
|
| 80 |
+
doc_bin.to_disk(spacy_file_path)
|
| 81 |
+
print(f"Data has been successfully saved to {spacy_file_path}!")
|
| 82 |
+
|
| 83 |
+
except json.JSONDecodeError as e:
|
| 84 |
+
print(f"Error decoding JSON: {e}")
|
| 85 |
+
except Exception as e:
|
| 86 |
+
print(f"An unexpected error occurred: {e}")
|