This commit is contained in:
init_mahdi
2026-11-28 16:36:19 +00:00
parent f7f9e85b02
commit 31a0647f77
111 changed files with 23944 additions and 3 deletions
+171
View File
@@ -0,0 +1,171 @@
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}")
all_data = []
failed_files = []
# پیدا کردن تمام فایل‌های .json در دایرکتوری
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 len(data) == 0:
failed_files.append(json_file.name)
continue
if isinstance(data, list) and isinstance(data[0], dict):
all_data.extend(data)
# print(f"✅ {json_file.name} با موفقیت اضافه شد.")
else:
raise ValueError(f"no list available in this json ->{json_file}")
except (json.JSONDecodeError, ValueError, OSError) as e:
print(f"❌ Faild in proccess '{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=all_data, path=output_path)
print(f"\n💾 finall file saved {output_path}")
except Exception as e:
print(f"❌error in sAve finall 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)
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
)
# --- نحوه استفاده ---
if __name__ == "__main__":
##### یکی کردن تمام بچ های خروجی در یک فایل
merge_json_dir(
input_path='/home1/ava3/code_match/finallize_exel',
output_path='/home1/ava3/code_match/finallize_exel/all_data.json'
)
###### ساخت یک proccessed id از فایل نهایی
# make_new_proccessed_ids_from_file(
# out_path='/home1/ava3/code_match/data1/proccessed_id_2.json',
# json_in='/home1/ava3/code_match/data1/merged_3.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'
# )
print(':D')