to-164
This commit is contained in:
Executable
+302
@@ -0,0 +1,302 @@
|
||||
import os
|
||||
import json
|
||||
import orjson
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
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 merge_json_dir(input_path, output_path):
|
||||
directory = Path(input_path)
|
||||
if not directory.is_dir():
|
||||
raise ValueError(f"Not valid PATH: {input_path}")
|
||||
|
||||
seen_ids = set() # برای ردیابی idهای دیدهشده (سریع!)
|
||||
unique_data = [] # فقط دادههای یکتا
|
||||
failed_files = []
|
||||
|
||||
json_files = list(directory.glob("*.json"))
|
||||
if not json_files:
|
||||
print("⚠️ NO JSON File Found In This PATH")
|
||||
return
|
||||
|
||||
for json_file in json_files:
|
||||
try:
|
||||
data = load_orjson(json_file)
|
||||
if not data: # خالی یا None
|
||||
failed_files.append(json_file.name)
|
||||
continue
|
||||
|
||||
# if isinstance(data, dict):
|
||||
# unique_data.append(data)
|
||||
if isinstance(data, list) and isinstance(data[0], dict):
|
||||
for item in data:
|
||||
item_id = item.get("id")
|
||||
if item_id is None:
|
||||
# اگر id نداشت، میتونی تصمیم بگیری: نگه داری یا ردش کنی
|
||||
# اینجا فرض میکنیم فقط مواردی با id معتبر مهم هستند
|
||||
continue
|
||||
if item_id not in seen_ids:
|
||||
seen_ids.add(item_id)
|
||||
unique_data.append(item)
|
||||
else:
|
||||
raise ValueError(f"no list available in this json -> {json_file}")
|
||||
except (json.JSONDecodeError, ValueError, OSError, KeyError, TypeError) as e:
|
||||
print(f"❌ Failed in process '{json_file.name}': {e}")
|
||||
failed_files.append(json_file.name)
|
||||
|
||||
# گزارش خطاها
|
||||
if failed_files:
|
||||
print("\n❌ We lose this file:")
|
||||
for name in failed_files:
|
||||
print(f" - {name}")
|
||||
else:
|
||||
print("\n✅ All JSON added")
|
||||
|
||||
# ذخیره خروجی
|
||||
try:
|
||||
save_orjson(data=unique_data, path=output_path)
|
||||
print(
|
||||
f"\n💾 Final file saved: {output_path} (Total unique items: {len(unique_data)})"
|
||||
)
|
||||
except Exception as e:
|
||||
print(f"❌ Error in saving final file: {e}")
|
||||
|
||||
|
||||
def make_new_proccessed_ids_from_file(json_in, out_path):
|
||||
data = load_orjson(json_in)
|
||||
|
||||
finall_data = []
|
||||
for d in data:
|
||||
if d["id"]:
|
||||
finall_data.append(d["id"])
|
||||
finall_data = set(finall_data)
|
||||
finall_data = list(finall_data)
|
||||
print(f"-- len ids {len(finall_data)}")
|
||||
|
||||
save_orjson(data=finall_data, path=out_path)
|
||||
|
||||
|
||||
def __try_parse_json(value):
|
||||
"""اگر value یک رشته باشد و بتوان آن را به JSON پارس کرد، نسخه پارسشده را برمیگرداند."""
|
||||
if isinstance(value, str):
|
||||
try:
|
||||
parsed = json.loads(value)
|
||||
# فقط اگر واقعاً JSON بود (نه یک عدد یا کلمه ساده)
|
||||
if isinstance(parsed, (dict, list)):
|
||||
return parsed
|
||||
else:
|
||||
return value # مثلاً اگر رشته "123" بود، نمیخواهیم به عدد تبدیلش کنیم
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
pass
|
||||
return value
|
||||
|
||||
|
||||
def __deep_parse_json_strings(obj):
|
||||
"""به صورت بازگشتی همه رشتههایی که JSON هستند را پارس میکند."""
|
||||
if isinstance(obj, dict):
|
||||
return {
|
||||
key: __deep_parse_json_strings(__try_parse_json(value))
|
||||
for key, value in obj.items()
|
||||
}
|
||||
elif isinstance(obj, list):
|
||||
return [__deep_parse_json_strings(__try_parse_json(item)) for item in obj]
|
||||
else:
|
||||
return obj
|
||||
|
||||
|
||||
def serialize_json_from_str_fields(json_in, out_path=None):
|
||||
if out_path is None:
|
||||
out_path = json_in
|
||||
|
||||
# بارگذاری داده
|
||||
data = load_orjson(json_in)
|
||||
|
||||
# پارس کردن عمیق همه رشتههای JSON
|
||||
cleaned_data = __deep_parse_json_strings(data)
|
||||
|
||||
# ذخیره نتیجه
|
||||
save_orjson(data=cleaned_data, path=out_path)
|
||||
print(f"✅ all done '{out_path}'")
|
||||
|
||||
|
||||
def make_format(in_path, out_path):
|
||||
data = load_orjson(in_path)
|
||||
f_data = []
|
||||
|
||||
for i in data:
|
||||
form = {
|
||||
"id": None,
|
||||
"word": None,
|
||||
"ai_code_version": None,
|
||||
"ai_result": [],
|
||||
}
|
||||
form["id"] = i["id"]
|
||||
form["word"] = i["word"]
|
||||
form["ai_result"] = i["ai_code"]["ai_code"]["result"]
|
||||
form["ai_code_version"] = i["ai_code"]["ai_code_version"]
|
||||
f_data.append(form)
|
||||
|
||||
save_orjson(data=f_data, path=out_path)
|
||||
|
||||
|
||||
# --- نحوه استفاده ---
|
||||
# python3 -m aiDataParser.task.word_bank_proccess.normalize_data
|
||||
if __name__ == "__main__":
|
||||
# ##### یکی کردن تمام بچ های خروجی در یک فایل
|
||||
# merge_json_dir(
|
||||
# input_path= '/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/word_v2/input_data/batch_data',
|
||||
# output_path='/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/data/lang_ncw/final_data_translate-word-v1-gemma-3-27b_3.json'
|
||||
# )
|
||||
|
||||
###### ساخت یک proccessed id از فایل نهایی
|
||||
# make_new_proccessed_ids_from_file(
|
||||
# json_in ='/home1/ava3/word_bank_proccess/oss_120b_v1/merged_finall.json',
|
||||
# out_path='/home1/ava3/word_bank_proccess/oss_120b_v1/proccessed_id.json',
|
||||
# )
|
||||
|
||||
# جیسونی کردن تمام فیلد ها
|
||||
# serialize_json_from_str_fields(
|
||||
# json_in='/home1/ava3/keyword_simpify_proccess/data_keyword_gemma27/merged_1.json',
|
||||
# out_path='/home1/ava3/keyword_simpify_proccess/data_keyword_gemma27/merged_2.json'
|
||||
# )
|
||||
|
||||
# format finallize
|
||||
# make_format(
|
||||
# in_path='/home1/ava3/keyword_simpify_proccess/data_keyword_gemma27/data.json',
|
||||
# out_path='/home1/ava3/keyword_simpify_proccess/data_keyword_gemma27/data_f1.json'
|
||||
# )
|
||||
# input_path = "/home1/ava3/word_bank_proccess/oss_120b_v1/merged_finall.json"
|
||||
# data = load_orjson(input_path)
|
||||
# print(f"------{len(data)}-----")
|
||||
# Truley = []
|
||||
# for i in data:
|
||||
# if i['ai_code']['ai_code']['is_correct'] is True : #and i['ai_code']['ai_code']['is_proper_noun'] is True
|
||||
# Truley.append(i)
|
||||
|
||||
# ---------------- filter حقوقی word
|
||||
# input_path = "/home1/ava3/word_bank_proccess/oss_120b_v1/merged_finall.json"
|
||||
# data = load_orjson(input_path)
|
||||
# Truley = []
|
||||
# for item in data:
|
||||
# if "حقوقی" in item['ai_code']['ai_code']['scope'] and item['ai_code']['ai_code']["is_correct"] is True:
|
||||
# Truley.append(item)
|
||||
|
||||
# print(f'Truley {len(Truley)}')
|
||||
# save_orjson(
|
||||
# data=Truley,
|
||||
# path='/home1/ava3/project/aidataparser_test/motaradef_dataset/motaradef.json'
|
||||
# )
|
||||
########################################################################
|
||||
# raw_data = '/home1/ava3/data/mj_qa_section.json'
|
||||
# raw_data = load_orjson(raw_data)
|
||||
# ignore_data = '/home1/ava3/data/ignore_mj_qa_sections.json'
|
||||
# ignore_data = load_orjson(ignore_data)
|
||||
# ignore_data = set(ignore_data)
|
||||
|
||||
# f_data = []
|
||||
# for item in raw_data:
|
||||
# if item['id'] not in ignore_data:
|
||||
# f_data.append(item)
|
||||
|
||||
# print(f'f_data {len(f_data)}')
|
||||
# save_orjson(
|
||||
# data=f_data,
|
||||
# path='/home1/ava3/data/valid_mj_qa_sections.json'
|
||||
# )
|
||||
|
||||
# ##########################################################################
|
||||
input_data = load_orjson(
|
||||
"/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/data/v1_()/merge_all_().json"
|
||||
)
|
||||
v2_data = load_orjson(
|
||||
'/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/data/v1_()/per_word_327k_magistral_small_2509.json'
|
||||
)
|
||||
print(F'input_data {len(input_data)}')
|
||||
print(F'v2_data {len(v2_data)}')
|
||||
f_data = {}
|
||||
for item in v2_data:
|
||||
new_item = {}
|
||||
result = item["result"]
|
||||
try:
|
||||
result = result.split('(')[1]
|
||||
result = result.split(')')[0]
|
||||
except:
|
||||
print(f"item {item}")
|
||||
break
|
||||
ai_code_version = item["ai_code_version"]
|
||||
ai_code_version = ai_code_version +"_true_word_oss120"
|
||||
|
||||
word = item["word"]
|
||||
_data = input_data.get(word, None)
|
||||
if _data:
|
||||
input_data[word][ai_code_version] = result
|
||||
else:
|
||||
input_data[word] = {
|
||||
ai_code_version : result,
|
||||
}
|
||||
|
||||
print(
|
||||
f"input_data {len(input_data)}"
|
||||
)
|
||||
save_orjson(
|
||||
data=input_data,
|
||||
path='/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/data/v1_()/merge_all_().json'
|
||||
)
|
||||
###########################################################################
|
||||
# words1 = load_orjson("/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/data/phase1/phase1_1218k_oss_120b.json")
|
||||
|
||||
# f_data = []
|
||||
# for item in words1:
|
||||
# new_item = {}
|
||||
# new_item["word"] = item["word"]
|
||||
# new_item["ai_code_version"] = item["ai_code"]["ai_code_version"]
|
||||
# new_item["is_correct"] = item["ai_code"]["ai_code"]["is_correct"]
|
||||
# new_item["nearest_correct_word"] = item["ai_code"]["ai_code"]["nearest_correct_word"]
|
||||
# new_item["origin"] = item["ai_code"]["ai_code"]["origin"]
|
||||
# new_item["stem"] = item["ai_code"]["ai_code"]["stem"]
|
||||
# new_item["is_proper_noun"] = item["ai_code"]["ai_code"]["is_proper_noun"]
|
||||
# new_item["word_class"] = item["ai_code"]["ai_code"]["word_class"]
|
||||
# new_item["tags"] = item["ai_code"]["ai_code"]["tags"]
|
||||
# new_item["ner_description"] = item["ai_code"]["ai_code"]["ner_description"]
|
||||
# new_item["confidence"] = item["ai_code"]["ai_code"]["confidence"]
|
||||
# new_item["lang"] = item["ai_code"]["ai_code"]["lang"]
|
||||
# new_item["scope"] = item["ai_code"]["ai_code"]["scope"]
|
||||
|
||||
# f_data.append(
|
||||
# new_item
|
||||
# )
|
||||
# print(
|
||||
# f"f_data {len(f_data)}"
|
||||
# )
|
||||
# save_orjson(
|
||||
# data=f_data,
|
||||
# path='/home1/ava3/init_mahdi/DataLake/Word/all_data_v1/phase1_1218706_oss_120b.json'
|
||||
# )
|
||||
# ##########################################################################
|
||||
# raw_data = load_orjson('/home1/ava3/data/valid_mj_qa_sections.json')
|
||||
# f_data = []
|
||||
# for item in raw_data:
|
||||
# f_data.append(
|
||||
# {
|
||||
# 'id':item['id'],
|
||||
# 'content':item['content']
|
||||
# }
|
||||
# )
|
||||
|
||||
# save_orjson(
|
||||
# data=f_data,
|
||||
# path='/home1/ava3/data/valid_mj_qa_sections_light.json')
|
||||
##########################################################################
|
||||
print(":D")
|
||||
Reference in New Issue
Block a user