Files
AiDataParser/task/ner_jokar_old/data_normalizer.py
T
2026-11-28 16:36:19 +00:00

192 lines
6.8 KiB
Python
Executable File

import os
import re
import orjson
from pathlib import Path
import numpy as np
def load_orjson(path: str | Path):
path = Path(path)
with path.open("rb") as f: # باید باینری باز بشه برای orjson
return orjson.loads(f.read())
def save_orjson(path, data):
with open(path, "wb") as f:
f.write(orjson.dumps(data, option=orjson.OPT_INDENT_2 | orjson.OPT_NON_STR_KEYS))
def make_data(
all_data, system_prompt, assistant_prompt=None
):
api_batch = []
for item in all_data:
# user_prompt = f"Input: `{item.get('sanad')}`"
api_batch.append(
{
"id": str(item.get("id")),
"user_prompt": str(item.get("user_prompt")),
"system_prompt": system_prompt,
"assistant_prompt": assistant_prompt,
}
)
return api_batch
SYS_PROMPT ='''You are an expert NER indexer.
Your task is to find the exact start and end character indices of given named entities within a Persian legal text.
---
### Rules:
1. You are given two inputs:
- `text`: the original Persian legal paragraph.
- `result`: a list of detected entities, each with:
- `word`: the entity text
- `label`: the entity type
2. For each entity, find its **first exact match** in the text and return:
- `word`
- `label`
- `start_index`
- `end_index`
3. `start_index` = index of the **first character** of the entity in the text.
`end_index` = index of the **last character + 1** (Python slicing convention).
4. Ignore entities not found exactly in the text.
5. Do not modify the text, normalize spaces, or fix typos.
6. If an entity occurs multiple times, use only the first occurrence.
7. Return output as a JSON list under key `"indexed_entities"`.
'''
ASSIST_PROMPT = '''---
### Example:
Input:
{
"text": "تبصره 3 - برای اجرای مقررات قانون مزبور و آییننامه اجرایی آن درباره افزارمندان ژاندارمری کشور صندوق مستقلی بنام صندوق بیمههای اجتماعی و بازنشستگی و تعاون افزارمندان ژاندارمری کشور با سرمایه زیر در بانک سپه تشکیل خواهد شد.",
"result": [
{"word": "تبصره 3", "label": "ارجاع جزء یا ماده"},
{"word": "قانون مزبور", "label": "ارجاع جزء یا ماده"},
{"word": "آییننامه اجرایی آن", "label": "محصول"},
{"word": "صندوق بیمههای اجتماعی و بازنشستگی و تعاون افزارمندان ژاندارمری کشور", "label": "سازمان"},
{"word": "بانک سپه", "label": "سازمان"}
]
}
Expected Output:
{
"indexed_entities": [
{"word": "تبصره 3", "label": "ارجاع جزء یا ماده", "start_index": 0, "end_index": 8},
{"word": "قانون مزبور", "label": "ارجاع جزء یا ماده", "start_index": 27, "end_index": 38},
{"word": "آییننامه اجرایی آن", "label": "محصول", "start_index": 41, "end_index": 62},
{"word": "صندوق بیمههای اجتماعی و بازنشستگی و تعاون افزارمندان ژاندارمری کشور", "label": "سازمان", "start_index": 97, "end_index": 174},
{"word": "بانک سپه", "label": "سازمان", "start_index": 201, "end_index": 209}
]
}
---
Now, process the given text and entity list and return JSON in the same format.
"""'''
def indexing_ner(text, entities):
"""
ایندکس شروع و پایان موجودیت‌ها را در متن برمی‌گرداند.
فقط برای موجودیت‌هایی که دقیقا یک‌بار در متن آمده‌اند.
"""
result = {}
for entity in entities:
matches = list(re.finditer(re.escape(entity), text))
if len(matches) == 1: # فقط اگر یک‌بار آمده
m = matches[0]
result[entity] = (m.start(), m.end())
return result if result else None
def process_data(data):
number = 0
print(f"data {len(data)}")
unprocees = []
for item in data:
id = item['id']
text = item.get("text", "")
item['len_text'] = len(text)
ai_result = item.get("ai_code", {}).get("ai_code_ner_result", {}).get("result", [])
entities = [i.get("word", "") for i in ai_result if i.get("word")]
# print(f'entities {entities}')
# print(f'id {id}')
result = indexing_ner(text=text, entities=entities)
if result is None:
number += 1
unprocees.append(id)
else:
# اضافه کردن ایندکس‌ها به هر موجودیت در لیست result
for ner_obj in ai_result:
word = ner_obj.get("word")
if word in result:
start, end = result[word]
ner_obj["index"] = {"start":start, "end":end}
# else:
# print(f'Erorr-code')
# ner_obj["index"] = None
print(f"number (no index found): {number}")
return data, unprocees
# ---------- مثال استفاده ----------
if __name__ == "__main__":
# فرض کن data از فایل خونده شده
# data = load_orjson("/home1/ava3/project/aidataparser_test/ner_jokar/input/ner_4525_unindex.json")
# # data= [data[0]]
# updated_data, unprocees = process_data(data)
# finall_data = [i for i in updated_data if i['id'] not in unprocees]
# # print(
# # f'updated_data {updated_data}'
# # )
# # print(type(updated_data))
# print(
# f'updated_data {len(updated_data)}',
# f'finall_data {len(finall_data)}',
# f'unprocees {len(unprocees)}',
# f'finall {len(finall_data)+len(unprocees)}',
# sep='\n'
# )
# save_orjson(
# data=finall_data,
# path="./phase2_ner_index_p1.json")
# save_orjson(
# data=unprocees,
# path="./unprocees_phase2_ner_index_p1.json")
# ------------------------------------- normalize json data format
data = load_orjson("/home1/ava3/project/aidataparser_test/ner_jokar/phase2_ner_index_p1.json")
new_data = []
for item in data:
id= item['id']
text = item['text']
len_text = item['len_text']
score = 1.0
ai_code = []
ai_code_version= item['ai_code']['ai_code_version']
result= item['ai_code']['ai_code_ner_result']['result']
for i in result:
i['score'] = score
ai_code.append(
{
"ai_code_version":ai_code_version,
"result":result
}
)
new_data.append({
"id":id,
"text":text,
"len_text":len_text,
"ai_code":ai_code
})
save_orjson(
data=new_data,
path='./finall_new_arch.json'
)