BU1
This commit is contained in:
+1
-1
@@ -1,3 +1,3 @@
|
|||||||
from aiDataParser.core.ai_parser import AsyncCore
|
from aiDataParser.core.ai_parser import AsyncCore, SmartMultiServerCore
|
||||||
from aiDataParser.core.ai_stream_parser import StreamAsyncCore
|
from aiDataParser.core.ai_stream_parser import StreamAsyncCore
|
||||||
from aiDataParser.core.data_normalizer import load_orjson, save_orjson
|
from aiDataParser.core.data_normalizer import load_orjson, save_orjson
|
||||||
|
|||||||
+1
-1
@@ -1392,7 +1392,7 @@ class SmartMultiServerCore:
|
|||||||
print(f"=== Config{i}: {j}")
|
print(f"=== Config{i}: {j}")
|
||||||
|
|
||||||
else:
|
else:
|
||||||
print(f"Not Found Any Active Service !!!")
|
raise ValueError(f"Not Found Any Active Service !!!")
|
||||||
|
|
||||||
def validate_configs(self):
|
def validate_configs(self):
|
||||||
self.active_configs = []
|
self.active_configs = []
|
||||||
|
|||||||
+196
-31
@@ -3,6 +3,26 @@ import json
|
|||||||
import orjson
|
import orjson
|
||||||
import tiktoken
|
import tiktoken
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
from typing import List, Dict, Optional, Union, Tuple
|
||||||
|
from pydantic import BaseModel, ConfigDict, ValidationError
|
||||||
|
|
||||||
|
|
||||||
|
class LLMOutputData(BaseModel):
|
||||||
|
id: str
|
||||||
|
|
||||||
|
# این تنظیم باعث میشود هر فیلد دیگری که در JSON هست حفظ شود و از بین نرود
|
||||||
|
model_config = ConfigDict(extra="allow")
|
||||||
|
|
||||||
|
def __hash__(self):
|
||||||
|
# تولید هش فقط بر اساس فیلد id
|
||||||
|
return hash(self.id)
|
||||||
|
|
||||||
|
def __eq__(self, other):
|
||||||
|
# برای اینکه Set پایتون متوجه شود دو شیء تکراری هستند،
|
||||||
|
# باید به آن بگوییم که برابری دو شیء به معنای برابری id آنهاست.
|
||||||
|
if isinstance(other, LLMOutputData):
|
||||||
|
return self.id == other.id
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
def load_orjson(path: str | Path):
|
def load_orjson(path: str | Path):
|
||||||
@@ -47,7 +67,7 @@ def merge_json_dir(input_path, output_path):
|
|||||||
item_id = item.get("id")
|
item_id = item.get("id")
|
||||||
if not item_id:
|
if not item_id:
|
||||||
item_id = item.get("_id")
|
item_id = item.get("_id")
|
||||||
|
|
||||||
if item_id is None:
|
if item_id is None:
|
||||||
# اگر id نداشت، میتونی تصمیم بگیری: نگه داری یا ردش کنی
|
# اگر id نداشت، میتونی تصمیم بگیری: نگه داری یا ردش کنی
|
||||||
# اینجا فرض میکنیم فقط مواردی با id معتبر مهم هستند
|
# اینجا فرض میکنیم فقط مواردی با id معتبر مهم هستند
|
||||||
@@ -156,9 +176,7 @@ def make_format(in_path, out_path):
|
|||||||
save_orjson(data=f_data, path=out_path)
|
save_orjson(data=f_data, path=out_path)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def count_tokens(model_name, system_prompt, user_prompt):
|
def count_tokens(model_name, system_prompt, user_prompt):
|
||||||
|
|
||||||
"""
|
"""
|
||||||
شمارش دقیق توکنهای ورودی برای مدلهای مختلف
|
شمارش دقیق توکنهای ورودی برای مدلهای مختلف
|
||||||
"""
|
"""
|
||||||
@@ -173,6 +191,7 @@ def count_tokens(model_name, system_prompt, user_prompt):
|
|||||||
|
|
||||||
elif "gemma" in model_name.lower():
|
elif "gemma" in model_name.lower():
|
||||||
from transformers import AutoTokenizer
|
from transformers import AutoTokenizer
|
||||||
|
|
||||||
# SentencePiece tokenizer (Gemma از HuggingFace)
|
# SentencePiece tokenizer (Gemma از HuggingFace)
|
||||||
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
||||||
tokens = tokenizer.encode(text)
|
tokens = tokenizer.encode(text)
|
||||||
@@ -180,6 +199,7 @@ def count_tokens(model_name, system_prompt, user_prompt):
|
|||||||
|
|
||||||
elif "magistral" in model_name.lower() or "mistral" in model_name.lower():
|
elif "magistral" in model_name.lower() or "mistral" in model_name.lower():
|
||||||
from transformers import AutoTokenizer
|
from transformers import AutoTokenizer
|
||||||
|
|
||||||
# Mistral / Magistral tokenizer (BPE)
|
# Mistral / Magistral tokenizer (BPE)
|
||||||
tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=True)
|
tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=True)
|
||||||
tokens = tokenizer.encode(text)
|
tokens = tokenizer.encode(text)
|
||||||
@@ -187,15 +207,164 @@ def count_tokens(model_name, system_prompt, user_prompt):
|
|||||||
|
|
||||||
else:
|
else:
|
||||||
raise ValueError(f"Model {model_name} not recognized.")
|
raise ValueError(f"Model {model_name} not recognized.")
|
||||||
|
|
||||||
|
|
||||||
|
def validate_merge_json_dir(
|
||||||
|
input_path,
|
||||||
|
base_output_path,
|
||||||
|
final_data_name,
|
||||||
|
processed_id_name,
|
||||||
|
):
|
||||||
|
output_data_path = base_output_path / final_data_name
|
||||||
|
processed_id_path = base_output_path / processed_id_name
|
||||||
|
directory = Path(input_path)
|
||||||
|
|
||||||
|
if not directory.is_dir():
|
||||||
|
raise ValueError(f"Not valid PATH: {input_path}")
|
||||||
|
|
||||||
|
# این متغیر (Set) تمام دادههای یکتا را به صورت شیء (Object) در خود نگه میدارد
|
||||||
|
unique_objects_set = set()
|
||||||
|
|
||||||
|
# مرحله ۱: خواندن دادههای قبلی از خروجی نهایی (برای تست و جلوگیری از تکرار با دادههای قدیمی)
|
||||||
|
try:
|
||||||
|
existing_data = load_orjson(output_data_path)
|
||||||
|
if isinstance(existing_data, list):
|
||||||
|
for item in existing_data:
|
||||||
|
if "id" not in item or item["id"] is None:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
# سریالایز با Pydantic
|
||||||
|
obj = LLMOutputData(**item)
|
||||||
|
# اضافه کردن به Set. اگر id تکراری باشد، پایتون اتوماتیک نادیده میگیرد
|
||||||
|
unique_objects_set.add(obj)
|
||||||
|
except ValidationError as e:
|
||||||
|
print(
|
||||||
|
f"⚠️ Validation error in existing data (ID: {item.get('id')}): {e}"
|
||||||
|
)
|
||||||
|
print(f"✅ Loaded {len(unique_objects_set)} unique items from existing output.")
|
||||||
|
except Exception:
|
||||||
|
print("ℹ️ No valid existing output data found. Starting fresh.")
|
||||||
|
|
||||||
|
# مرحله ۲: خواندن فایلهای جدید دایرکتوری Temp
|
||||||
|
failed_files = 0
|
||||||
|
json_files = list(directory.glob("*.json"))
|
||||||
|
|
||||||
|
if not json_files:
|
||||||
|
print("⚠️ NO JSON File Found In This PATH")
|
||||||
|
# حتی اگر فایل جدیدی نبود، ممکن است بخواهیم دادههای قبلی که تمیز شدهاند را دوباره ذخیره کنیم
|
||||||
|
else:
|
||||||
|
for json_file in json_files:
|
||||||
|
try:
|
||||||
|
data = load_orjson(json_file)
|
||||||
|
if not data: # خالی یا None
|
||||||
|
failed_files += 1
|
||||||
|
continue
|
||||||
|
|
||||||
|
if (
|
||||||
|
isinstance(data, list)
|
||||||
|
and len(data) > 0
|
||||||
|
and isinstance(data[0], dict)
|
||||||
|
):
|
||||||
|
for item in data:
|
||||||
|
if "id" not in item or item["id"] is None:
|
||||||
|
continue
|
||||||
|
|
||||||
|
try:
|
||||||
|
# سریالایز داده جدید
|
||||||
|
obj = LLMOutputData(**item)
|
||||||
|
# افزودن به Set. (بررسی تکراری بودن فقط با id در کسری از ثانیه انجام میشود)
|
||||||
|
unique_objects_set.add(obj)
|
||||||
|
except ValidationError as e:
|
||||||
|
print(f"⚠️ Validation error in file {json_file.name}: {e}")
|
||||||
|
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}' ")
|
||||||
|
failed_files += 1
|
||||||
|
|
||||||
|
print(f"Total unique_data ready to save: {len(unique_objects_set)}")
|
||||||
|
|
||||||
|
# مرحله ۳: ساخت داینامیک دادههای خروجی و لیست idهای پردازش شده
|
||||||
|
# تبدیل دوباره اشیاء به دیکشنری (فیلدهای اضافه با این متد حفظ میشوند)
|
||||||
|
final_unique_data = [obj.model_dump() for obj in unique_objects_set]
|
||||||
|
|
||||||
|
# ساخت داینامیک لیست IDها از روی Set
|
||||||
|
dynamic_seen_ids = [obj.id for obj in unique_objects_set]
|
||||||
|
|
||||||
|
# مرحله ۴: ذخیرهسازی دادهها
|
||||||
|
try:
|
||||||
|
save_orjson(data=final_unique_data, path=output_data_path)
|
||||||
|
save_orjson(data=dynamic_seen_ids, path=processed_id_path)
|
||||||
|
return len(final_unique_data), len(dynamic_seen_ids)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"❌ Error in saving final file: {e}")
|
||||||
|
return 0, 0
|
||||||
|
|
||||||
|
|
||||||
# --- نحوه استفاده ---
|
# --- نحوه استفاده ---
|
||||||
|
# python3 /home1/ava3/init_mahdi/project/aiDataParser/core/data_normalizer.py
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
# ##### یکی کردن تمام بچ های خروجی در یک فایل
|
# ##### یکی کردن تمام بچ های خروجی در یک فایل و ساخت proccessed_id
|
||||||
merge_json_dir(
|
[
|
||||||
input_path= '/home1/ava3/init_mahdi/project/rule_extractor/im_based/data/sequential/subject_unity/output_6152/batch_data',
|
1,
|
||||||
output_path='/home1/ava3/init_mahdi/project/rule_extractor/im_based/data/sequential/subject_unity/output_6152/final_data_subject_unity.json'
|
2,
|
||||||
|
3,
|
||||||
|
4,
|
||||||
|
5,
|
||||||
|
7,
|
||||||
|
8,
|
||||||
|
9,
|
||||||
|
10,
|
||||||
|
11,
|
||||||
|
13,
|
||||||
|
14,
|
||||||
|
15,
|
||||||
|
18,
|
||||||
|
19,
|
||||||
|
20,
|
||||||
|
21,
|
||||||
|
22,
|
||||||
|
23,
|
||||||
|
24,
|
||||||
|
25,
|
||||||
|
26,
|
||||||
|
28,
|
||||||
|
30,
|
||||||
|
32,
|
||||||
|
33,
|
||||||
|
34,
|
||||||
|
35,
|
||||||
|
]
|
||||||
|
i = 2
|
||||||
|
# validate_merge_json_dir(
|
||||||
|
# input_path=Path(
|
||||||
|
# f"/home1/ava3/init_mahdi/project/rule_extractor/im_based/data/sequential/subject_unity/output_all_qavanin/part_{i}/batch_data"
|
||||||
|
# ),
|
||||||
|
# base_output_path=Path(
|
||||||
|
# f"/home1/ava3/init_mahdi/project/rule_extractor/im_based/data/sequential/subject_unity/output_all_qavanin/part_{i}"
|
||||||
|
# ),
|
||||||
|
# final_data_name="final_data_subject_unity.json",
|
||||||
|
# processed_id_name="processed_id.json",
|
||||||
|
# )
|
||||||
|
print(
|
||||||
|
len(
|
||||||
|
load_orjson(
|
||||||
|
"/home1/ava3/init_mahdi/project/rule_extractor/im_based/data/sequential/subject_unity/output_all_qavanin/part_1/final_data_subject_unity.json"
|
||||||
|
)
|
||||||
|
)
|
||||||
)
|
)
|
||||||
|
# # ##### یکی کردن تمام بچ های خروجی در یک فایل
|
||||||
|
# merge_json_dir(
|
||||||
|
# input_path="/home1/ava3/init_mahdi/project/aiDataParser/task/mn_heading/output1/batch_data",
|
||||||
|
# output_path="/home1/ava3/init_mahdi/project/aiDataParser/task/mn_heading/output1/final_data_gemma-27.json",
|
||||||
|
# )
|
||||||
|
|
||||||
###### ساخت یک proccessed id از فایل نهایی
|
###### ساخت یک proccessed id از فایل نهایی
|
||||||
# make_new_proccessed_ids_from_file(
|
# make_new_proccessed_ids_from_file(
|
||||||
@@ -270,7 +439,7 @@ if __name__ == "__main__":
|
|||||||
##################################### work with tree #####################################
|
##################################### work with tree #####################################
|
||||||
# fr_tree = '/home1/ava3/project/aiDataParser/task/match_code_fr_per/prompt_ir_def.json'
|
# fr_tree = '/home1/ava3/project/aiDataParser/task/match_code_fr_per/prompt_ir_def.json'
|
||||||
# fr_tree = load_orjson(fr_tree)
|
# fr_tree = load_orjson(fr_tree)
|
||||||
|
|
||||||
# code_title = []
|
# code_title = []
|
||||||
# for k, v in fr_tree.items():
|
# for k, v in fr_tree.items():
|
||||||
# code_title.append(
|
# code_title.append(
|
||||||
@@ -278,18 +447,17 @@ if __name__ == "__main__":
|
|||||||
# )
|
# )
|
||||||
|
|
||||||
# save_orjson(
|
# save_orjson(
|
||||||
# data=code_title,
|
# data=code_title,
|
||||||
# path='/home1/ava3/project/aiDataParser/task/match_code_fr_per/all_code_title_persian.json'
|
# path='/home1/ava3/project/aiDataParser/task/match_code_fr_per/all_code_title_persian.json'
|
||||||
# )
|
# )
|
||||||
|
|
||||||
##################################### make tree #####################################
|
##################################### make tree #####################################
|
||||||
# fr_tree = '/home1/ava3/franc_legal_codes/translate/all_tree_franc.json'
|
# fr_tree = '/home1/ava3/franc_legal_codes/translate/all_tree_franc.json'
|
||||||
# fr_tree = load_orjson(fr_tree)
|
# fr_tree = load_orjson(fr_tree)
|
||||||
|
|
||||||
# pr_data = '/home1/ava3/project/aiDataParser/task/france_translate/all_pr_fr_title_cleaned_1.json'
|
# pr_data = '/home1/ava3/project/aiDataParser/task/france_translate/all_pr_fr_title_cleaned_1.json'
|
||||||
# pr_data = load_orjson(pr_data)
|
# pr_data = load_orjson(pr_data)
|
||||||
|
|
||||||
|
|
||||||
# def build_lookup(flat_list):
|
# def build_lookup(flat_list):
|
||||||
# lookup = {}
|
# lookup = {}
|
||||||
# for item in flat_list:
|
# for item in flat_list:
|
||||||
@@ -298,7 +466,6 @@ if __name__ == "__main__":
|
|||||||
# lookup[key] = item
|
# lookup[key] = item
|
||||||
# return lookup
|
# return lookup
|
||||||
|
|
||||||
|
|
||||||
# def clean_title(title: str) -> str:
|
# def clean_title(title: str) -> str:
|
||||||
# import re
|
# import re
|
||||||
# title = re.sub(r'\n+', '', title) # \s+ = هر ترکیبی از whitespace (space, \t, \n, \r, ...)
|
# title = re.sub(r'\n+', '', title) # \s+ = هر ترکیبی از whitespace (space, \t, \n, \r, ...)
|
||||||
@@ -316,12 +483,12 @@ if __name__ == "__main__":
|
|||||||
# persian = enriched.get("persian")
|
# persian = enriched.get("persian")
|
||||||
# if persian == None:
|
# if persian == None:
|
||||||
# unlist = {
|
# unlist = {
|
||||||
# 'fr_title':title,
|
# 'fr_title':title,
|
||||||
# 'pr_title':enriched.get('france')
|
# 'pr_title':enriched.get('france')
|
||||||
# }
|
# }
|
||||||
# print(unlist)
|
# print(unlist)
|
||||||
# return (unlist, 1)
|
# return (unlist, 1)
|
||||||
# # ساخت گره جدید
|
# # ساخت گره جدید
|
||||||
# new_node = {
|
# new_node = {
|
||||||
# "france": title,
|
# "france": title,
|
||||||
# "persian": enriched.get("persian"), # پیشفرض: همان فرانسوی اگر ترجمه نبود
|
# "persian": enriched.get("persian"), # پیشفرض: همان فرانسوی اگر ترجمه نبود
|
||||||
@@ -351,7 +518,7 @@ if __name__ == "__main__":
|
|||||||
# )
|
# )
|
||||||
|
|
||||||
# save_orjson(
|
# save_orjson(
|
||||||
# path='/home1/ava3/project/aiDataParser/task/france_translate/tree_test1_title.json',
|
# path='/home1/ava3/project/aiDataParser/task/france_translate/tree_test1_title.json',
|
||||||
# data=f_data
|
# data=f_data
|
||||||
# )
|
# )
|
||||||
|
|
||||||
@@ -368,11 +535,11 @@ if __name__ == "__main__":
|
|||||||
|
|
||||||
# if '.' in title:
|
# if '.' in title:
|
||||||
# title = title.replace('.', '')
|
# title = title.replace('.', '')
|
||||||
|
|
||||||
# if ':' in title:
|
# if ':' in title:
|
||||||
# title = title.split(':', 1)[1].strip()
|
# title = title.split(':', 1)[1].strip()
|
||||||
|
|
||||||
# if ')' in title : #and '(' not in title:
|
# if ')' in title : #and '(' not in title:
|
||||||
# colon_count1 = title.count(')')
|
# colon_count1 = title.count(')')
|
||||||
# colon_count2 = title.count('(')
|
# colon_count2 = title.count('(')
|
||||||
# if colon_count1 == colon_count2:
|
# if colon_count1 == colon_count2:
|
||||||
@@ -384,7 +551,7 @@ if __name__ == "__main__":
|
|||||||
# title = title.split(')', 1)[1].strip()
|
# title = title.split(')', 1)[1].strip()
|
||||||
# # print(title)
|
# # print(title)
|
||||||
# # break
|
# # break
|
||||||
# i['persian'] = title
|
# i['persian'] = title
|
||||||
|
|
||||||
# save_orjson(
|
# save_orjson(
|
||||||
# data=input_per,
|
# data=input_per,
|
||||||
@@ -399,11 +566,11 @@ if __name__ == "__main__":
|
|||||||
# # if len(i['persian']) > 0 and isinstance(i['persian'], list) and bool(i['persian'][0] != None) and bool(i['persian'][0] != ''):
|
# # if len(i['persian']) > 0 and isinstance(i['persian'], list) and bool(i['persian'][0] != None) and bool(i['persian'][0] != ''):
|
||||||
# data_1.append(
|
# data_1.append(
|
||||||
# {
|
# {
|
||||||
# "id": str(i["id"]),
|
# "id": str(i["id"]),
|
||||||
# # "ai_code_version": str(i["ai_code_version"]),
|
# # "ai_code_version": str(i["ai_code_version"]),
|
||||||
# 'persian' : i['fa']
|
# 'persian' : i['fa']
|
||||||
# }
|
# }
|
||||||
# )
|
# )
|
||||||
# # else:
|
# # else:
|
||||||
# # unvalid.append(str(i["id"]))
|
# # unvalid.append(str(i["id"]))
|
||||||
|
|
||||||
@@ -413,7 +580,7 @@ if __name__ == "__main__":
|
|||||||
# {
|
# {
|
||||||
# "id": str(i["id"]),
|
# "id": str(i["id"]),
|
||||||
# "fr": str(i["fr"])
|
# "fr": str(i["fr"])
|
||||||
# }
|
# }
|
||||||
# for i in data_2 # if str(i['id']) in unvalid
|
# for i in data_2 # if str(i['id']) in unvalid
|
||||||
# ]
|
# ]
|
||||||
|
|
||||||
@@ -436,7 +603,6 @@ if __name__ == "__main__":
|
|||||||
# )
|
# )
|
||||||
# break
|
# break
|
||||||
|
|
||||||
|
|
||||||
# save_orjson(
|
# save_orjson(
|
||||||
# data=f_data,
|
# data=f_data,
|
||||||
# path="/home1/ava3/project/aiDataParser/task/france_translate/all_title_persian/temp2.json",
|
# path="/home1/ava3/project/aiDataParser/task/france_translate/all_title_persian/temp2.json",
|
||||||
@@ -500,15 +666,14 @@ if __name__ == "__main__":
|
|||||||
# )
|
# )
|
||||||
|
|
||||||
# save_orjson(
|
# save_orjson(
|
||||||
# path='/home1/ava3/project/aiDataParser/task/keyword_extractor/output/finall_dataset.json',
|
# path='/home1/ava3/project/aiDataParser/task/keyword_extractor/output/finall_dataset.json',
|
||||||
# data=clean_data
|
# data=clean_data
|
||||||
# )
|
# )
|
||||||
# save_orjson(
|
# save_orjson(
|
||||||
# path='/home1/ava3/project/aiDataParser/task/keyword_extractor/output/error_data.json',
|
# path='/home1/ava3/project/aiDataParser/task/keyword_extractor/output/error_data.json',
|
||||||
# data=error_data
|
# data=error_data
|
||||||
# )
|
# )
|
||||||
|
|
||||||
|
|
||||||
##########################################################################
|
##########################################################################
|
||||||
print(":D")
|
print(":D")
|
||||||
# python3 -m aiDataParser.core.data_normalizer
|
# python3 -m aiDataParser.core.data_normalizer
|
||||||
|
|||||||
Reference in New Issue
Block a user